babylon.scene.ts 167 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200
  1. module BABYLON {
  2. export interface IDisposable {
  3. dispose(): void;
  4. }
  5. class ClickInfo {
  6. private _singleClick = false;
  7. private _doubleClick = false;
  8. private _hasSwiped = false;
  9. private _ignore = false;
  10. public get singleClick(): boolean {
  11. return this._singleClick;
  12. }
  13. public get doubleClick(): boolean {
  14. return this._doubleClick;
  15. }
  16. public get hasSwiped(): boolean {
  17. return this._hasSwiped;
  18. }
  19. public get ignore(): boolean {
  20. return this._ignore;
  21. }
  22. public set singleClick(b: boolean) {
  23. this._singleClick = b;
  24. }
  25. public set doubleClick(b: boolean) {
  26. this._doubleClick = b;
  27. }
  28. public set hasSwiped(b: boolean) {
  29. this._hasSwiped = b;
  30. }
  31. public set ignore(b: boolean) {
  32. this._ignore = b;
  33. }
  34. }
  35. /**
  36. * This class is used by the onRenderingGroupObservable
  37. */
  38. export class RenderingGroupInfo {
  39. /**
  40. * The Scene that being rendered
  41. */
  42. scene: Scene;
  43. /**
  44. * The camera currently used for the rendering pass
  45. */
  46. camera: Camera;
  47. /**
  48. * The ID of the renderingGroup being processed
  49. */
  50. renderingGroupId: number;
  51. /**
  52. * The rendering stage, can be either STAGE_PRECLEAR, STAGE_PREOPAQUE, STAGE_PRETRANSPARENT, STAGE_POSTTRANSPARENT
  53. */
  54. renderStage: number;
  55. /**
  56. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  57. * This stage will be fired no matter what
  58. */
  59. static STAGE_PRECLEAR = 1;
  60. /**
  61. * Called before opaque object are rendered.
  62. * This stage will be fired only if there's 3D Opaque content to render
  63. */
  64. static STAGE_PREOPAQUE = 2;
  65. /**
  66. * Called after the opaque objects are rendered and before the transparent ones
  67. * This stage will be fired only if there's 3D transparent content to render
  68. */
  69. static STAGE_PRETRANSPARENT = 3;
  70. /**
  71. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  72. * This stage will be fired no matter what
  73. */
  74. static STAGE_POSTTRANSPARENT = 4;
  75. }
  76. /**
  77. * Represents a scene to be rendered by the engine.
  78. * @see http://doc.babylonjs.com/page.php?p=21911
  79. */
  80. export class Scene implements IAnimatable {
  81. // Statics
  82. private static _FOGMODE_NONE = 0;
  83. private static _FOGMODE_EXP = 1;
  84. private static _FOGMODE_EXP2 = 2;
  85. private static _FOGMODE_LINEAR = 3;
  86. public static MinDeltaTime = 1.0;
  87. public static MaxDeltaTime = 1000.0;
  88. /** The fog is deactivated */
  89. public static get FOGMODE_NONE(): number {
  90. return Scene._FOGMODE_NONE;
  91. }
  92. /** The fog density is following an exponential function */
  93. public static get FOGMODE_EXP(): number {
  94. return Scene._FOGMODE_EXP;
  95. }
  96. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  97. public static get FOGMODE_EXP2(): number {
  98. return Scene._FOGMODE_EXP2;
  99. }
  100. /** The fog density is following a linear function. */
  101. public static get FOGMODE_LINEAR(): number {
  102. return Scene._FOGMODE_LINEAR;
  103. }
  104. // Members
  105. public autoClear = true;
  106. public autoClearDepthAndStencil = true;
  107. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  108. public ambientColor = new Color3(0, 0, 0);
  109. public _environmentBRDFTexture: BaseTexture;
  110. protected _environmentTexture: BaseTexture;
  111. /**
  112. * Texture used in all pbr material as the reflection texture.
  113. * As in the majority of the scene they are the same (exception for multi room and so on),
  114. * this is easier to reference from here than from all the materials.
  115. */
  116. public get environmentTexture(): BaseTexture {
  117. return this._environmentTexture;
  118. }
  119. /**
  120. * Texture used in all pbr material as the reflection texture.
  121. * As in the majority of the scene they are the same (exception for multi room and so on),
  122. * this is easier to set here than in all the materials.
  123. */
  124. public set environmentTexture(value: BaseTexture) {
  125. this._environmentTexture = value;
  126. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  127. }
  128. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  129. /**
  130. * Default image processing configuration used either in the rendering
  131. * Forward main pass or through the imageProcessingPostProcess if present.
  132. * As in the majority of the scene they are the same (exception for multi camera),
  133. * this is easier to reference from here than from all the materials and post process.
  134. *
  135. * No setter as we it is a shared configuration, you can set the values instead.
  136. */
  137. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  138. return this._imageProcessingConfiguration;
  139. }
  140. public forceWireframe = false;
  141. private _forcePointsCloud = false;
  142. public set forcePointsCloud(value: boolean) {
  143. if (this._forcePointsCloud === value) {
  144. return;
  145. }
  146. this._forcePointsCloud = value;
  147. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  148. }
  149. public get forcePointsCloud(): boolean {
  150. return this._forcePointsCloud;
  151. }
  152. public forceShowBoundingBoxes = false;
  153. public clipPlane: Plane;
  154. public animationsEnabled = true;
  155. public constantlyUpdateMeshUnderPointer = false;
  156. public hoverCursor = "pointer";
  157. public defaultCursor: string = "";
  158. // Metadata
  159. public metadata: any = null;
  160. public loadingPluginName: string;
  161. // Events
  162. private _spritePredicate: (sprite: Sprite) => boolean;
  163. /**
  164. * An event triggered when the scene is disposed.
  165. * @type {BABYLON.Observable}
  166. */
  167. public onDisposeObservable = new Observable<Scene>();
  168. private _onDisposeObserver: Observer<Scene>;
  169. /** A function to be executed when this scene is disposed. */
  170. public set onDispose(callback: () => void) {
  171. if (this._onDisposeObserver) {
  172. this.onDisposeObservable.remove(this._onDisposeObserver);
  173. }
  174. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  175. }
  176. /**
  177. * An event triggered before rendering the scene
  178. * @type {BABYLON.Observable}
  179. */
  180. public onBeforeRenderObservable = new Observable<Scene>();
  181. private _onBeforeRenderObserver: Observer<Scene>;
  182. /** A function to be executed before rendering this scene */
  183. public set beforeRender(callback: () => void) {
  184. if (this._onBeforeRenderObserver) {
  185. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  186. }
  187. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  188. }
  189. /**
  190. * An event triggered after rendering the scene
  191. * @type {BABYLON.Observable}
  192. */
  193. public onAfterRenderObservable = new Observable<Scene>();
  194. private _onAfterRenderObserver: Observer<Scene>;
  195. /** A function to be executed after rendering this scene */
  196. public set afterRender(callback: () => void) {
  197. if (this._onAfterRenderObserver) {
  198. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  199. }
  200. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  201. }
  202. /**
  203. * An event triggered when the scene is ready
  204. * @type {BABYLON.Observable}
  205. */
  206. public onReadyObservable = new Observable<Scene>();
  207. /**
  208. * An event triggered before rendering a camera
  209. * @type {BABYLON.Observable}
  210. */
  211. public onBeforeCameraRenderObservable = new Observable<Camera>();
  212. private _onBeforeCameraRenderObserver: Observer<Camera>;
  213. public set beforeCameraRender(callback: () => void) {
  214. if (this._onBeforeCameraRenderObserver) {
  215. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  216. }
  217. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  218. }
  219. /**
  220. * An event triggered after rendering a camera
  221. * @type {BABYLON.Observable}
  222. */
  223. public onAfterCameraRenderObservable = new Observable<Camera>();
  224. private _onAfterCameraRenderObserver: Observer<Camera>;
  225. public set afterCameraRender(callback: () => void) {
  226. if (this._onAfterCameraRenderObserver) {
  227. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  228. }
  229. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  230. }
  231. /**
  232. * An event triggered when a camera is created
  233. * @type {BABYLON.Observable}
  234. */
  235. public onNewCameraAddedObservable = new Observable<Camera>();
  236. /**
  237. * An event triggered when a camera is removed
  238. * @type {BABYLON.Observable}
  239. */
  240. public onCameraRemovedObservable = new Observable<Camera>();
  241. /**
  242. * An event triggered when a light is created
  243. * @type {BABYLON.Observable}
  244. */
  245. public onNewLightAddedObservable = new Observable<Light>();
  246. /**
  247. * An event triggered when a light is removed
  248. * @type {BABYLON.Observable}
  249. */
  250. public onLightRemovedObservable = new Observable<Light>();
  251. /**
  252. * An event triggered when a geometry is created
  253. * @type {BABYLON.Observable}
  254. */
  255. public onNewGeometryAddedObservable = new Observable<Geometry>();
  256. /**
  257. * An event triggered when a geometry is removed
  258. * @type {BABYLON.Observable}
  259. */
  260. public onGeometryRemovedObservable = new Observable<Geometry>();
  261. /**
  262. * An event triggered when a mesh is created
  263. * @type {BABYLON.Observable}
  264. */
  265. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  266. /**
  267. * An event triggered when a mesh is removed
  268. * @type {BABYLON.Observable}
  269. */
  270. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  271. /**
  272. * An event triggered before calculating deterministic simulation step
  273. * @type {BABYLON.Observable}
  274. */
  275. public onBeforeStepObservable = new Observable<Scene>();
  276. /**
  277. * An event triggered after calculating deterministic simulation step
  278. * @type {BABYLON.Observable}
  279. */
  280. public onAfterStepObservable = new Observable<Scene>();
  281. /**
  282. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  283. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  284. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  285. */
  286. public onRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  287. // Animations
  288. public animations: Animation[] = [];
  289. // Pointers
  290. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  291. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  292. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  293. private _onPointerMove: (evt: PointerEvent) => void;
  294. private _onPointerDown: (evt: PointerEvent) => void;
  295. private _onPointerUp: (evt: PointerEvent) => void;
  296. /** Deprecated. Use onPointerObservable instead */
  297. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  298. /** Deprecated. Use onPointerObservable instead */
  299. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  300. /** Deprecated. Use onPointerObservable instead */
  301. public onPointerUp: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  302. /** Deprecated. Use onPointerObservable instead */
  303. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  304. // Gamepads
  305. private _gamepadManager: GamepadManager;
  306. public get gamepadManager(): GamepadManager {
  307. if (!this._gamepadManager) {
  308. this._gamepadManager = new GamepadManager();
  309. }
  310. return this._gamepadManager;
  311. }
  312. /**
  313. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  314. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  315. */
  316. public onPrePointerObservable = new Observable<PointerInfoPre>();
  317. /**
  318. * Observable event triggered each time an input event is received from the rendering canvas
  319. */
  320. public onPointerObservable = new Observable<PointerInfo>();
  321. public get unTranslatedPointer(): Vector2 {
  322. return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  323. }
  324. /** The distance in pixel that you have to move to prevent some events */
  325. public static DragMovementThreshold = 10; // in pixels
  326. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  327. public static LongPressDelay = 500; // in milliseconds
  328. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  329. public static DoubleClickDelay = 300; // in milliseconds
  330. /** If you need to check double click without raising a single click at first click, enable this flag */
  331. public static ExclusiveDoubleClickMode = false;
  332. private _initClickEvent: (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: PointerInfo) => void) => void;
  333. private _initActionManager: (act: ActionManager, clickInfo: ClickInfo) => ActionManager;
  334. private _delayedSimpleClick: (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: PointerInfo) => void) => void;
  335. private _delayedSimpleClickTimeout;
  336. private _previousDelayedSimpleClickTimeout;
  337. private _meshPickProceed = false;
  338. private _previousButtonPressed;
  339. private _previousHasSwiped = false;
  340. private _currentPickResult = null;
  341. private _previousPickResult = null;
  342. private _isButtonPressed = false;
  343. private _doubleClickOccured = false;
  344. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  345. public cameraToUseForPointers: Camera = null;
  346. private _pointerX: number;
  347. private _pointerY: number;
  348. private _unTranslatedPointerX: number;
  349. private _unTranslatedPointerY: number;
  350. private _startingPointerPosition = new Vector2(0, 0);
  351. private _previousStartingPointerPosition = new Vector2(0, 0);
  352. private _startingPointerTime = 0;
  353. private _previousStartingPointerTime = 0;
  354. // Deterministic lockstep
  355. private _timeAccumulator: number = 0;
  356. private _currentStepId: number = 0;
  357. private _currentInternalStep: number = 0;
  358. // Mirror
  359. public _mirroredCameraPosition: Vector3;
  360. // Keyboard
  361. /**
  362. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  363. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  364. */
  365. public onPreKeyboardObservable = new Observable<KeyboardInfoPre>();
  366. /**
  367. * Observable event triggered each time an keyboard event is received from the hosting window
  368. */
  369. public onKeyboardObservable = new Observable<KeyboardInfo>();
  370. private _onKeyDown: (evt: Event) => void;
  371. private _onKeyUp: (evt: Event) => void;
  372. private _onCanvasFocusObserver: Observer<Engine>;
  373. private _onCanvasBlurObserver: Observer<Engine>;
  374. // Coordinate system
  375. /**
  376. * use right-handed coordinate system on this scene.
  377. * @type {boolean}
  378. */
  379. private _useRightHandedSystem = false;
  380. public set useRightHandedSystem(value: boolean) {
  381. if (this._useRightHandedSystem === value) {
  382. return;
  383. }
  384. this._useRightHandedSystem = value;
  385. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  386. }
  387. public get useRightHandedSystem(): boolean {
  388. return this._useRightHandedSystem;
  389. }
  390. public setStepId(newStepId: number): void {
  391. this._currentStepId = newStepId;
  392. };
  393. public getStepId(): number {
  394. return this._currentStepId;
  395. };
  396. public getInternalStep(): number {
  397. return this._currentInternalStep;
  398. };
  399. // Fog
  400. private _fogEnabled = true;
  401. /**
  402. * is fog enabled on this scene.
  403. */
  404. public set fogEnabled(value: boolean) {
  405. if (this._fogEnabled === value) {
  406. return;
  407. }
  408. this._fogEnabled = value;
  409. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  410. }
  411. public get fogEnabled(): boolean {
  412. return this._fogEnabled;
  413. }
  414. private _fogMode = Scene.FOGMODE_NONE;
  415. public set fogMode(value: number) {
  416. if (this._fogMode === value) {
  417. return;
  418. }
  419. this._fogMode = value;
  420. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  421. }
  422. public get fogMode(): number {
  423. return this._fogMode;
  424. }
  425. public fogColor = new Color3(0.2, 0.2, 0.3);
  426. public fogDensity = 0.1;
  427. public fogStart = 0;
  428. public fogEnd = 1000.0;
  429. // Lights
  430. /**
  431. * is shadow enabled on this scene.
  432. * @type {boolean}
  433. */
  434. private _shadowsEnabled = true;
  435. public set shadowsEnabled(value: boolean) {
  436. if (this._shadowsEnabled === value) {
  437. return;
  438. }
  439. this._shadowsEnabled = value;
  440. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  441. }
  442. public get shadowsEnabled(): boolean {
  443. return this._shadowsEnabled;
  444. }
  445. /**
  446. * is light enabled on this scene.
  447. * @type {boolean}
  448. */
  449. private _lightsEnabled = true;
  450. public set lightsEnabled(value: boolean) {
  451. if (this._lightsEnabled === value) {
  452. return;
  453. }
  454. this._lightsEnabled = value;
  455. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  456. }
  457. public get lightsEnabled(): boolean {
  458. return this._lightsEnabled;
  459. }
  460. /**
  461. * All of the lights added to this scene.
  462. * @see BABYLON.Light
  463. * @type {BABYLON.Light[]}
  464. */
  465. public lights = new Array<Light>();
  466. // Cameras
  467. /** All of the cameras added to this scene. */
  468. public cameras = new Array<Camera>();
  469. /** All of the active cameras added to this scene. */
  470. public activeCameras = new Array<Camera>();
  471. /** The current active camera */
  472. public activeCamera: Camera;
  473. // Meshes
  474. /**
  475. * All of the (abstract) meshes added to this scene.
  476. * @see BABYLON.AbstractMesh
  477. * @type {BABYLON.AbstractMesh[]}
  478. */
  479. public meshes = new Array<AbstractMesh>();
  480. // Geometries
  481. private _geometries = new Array<Geometry>();
  482. public materials = new Array<Material>();
  483. public multiMaterials = new Array<MultiMaterial>();
  484. private _defaultMaterial: Material;
  485. /** The default material used on meshes when no material is affected */
  486. public get defaultMaterial(): Material {
  487. if (!this._defaultMaterial) {
  488. this._defaultMaterial = new StandardMaterial("default material", this);
  489. }
  490. return this._defaultMaterial;
  491. }
  492. /** The default material used on meshes when no material is affected */
  493. public set defaultMaterial(value: Material) {
  494. this._defaultMaterial = value;
  495. }
  496. // Textures
  497. private _texturesEnabled = true;
  498. public set texturesEnabled(value: boolean) {
  499. if (this._texturesEnabled === value) {
  500. return;
  501. }
  502. this._texturesEnabled = value;
  503. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  504. }
  505. public get texturesEnabled(): boolean {
  506. return this._texturesEnabled;
  507. }
  508. public textures = new Array<BaseTexture>();
  509. // Particles
  510. public particlesEnabled = true;
  511. public particleSystems = new Array<IParticleSystem>();
  512. // Sprites
  513. public spritesEnabled = true;
  514. public spriteManagers = new Array<SpriteManager>();
  515. // Layers
  516. public layers = new Array<Layer>();
  517. public highlightLayers = new Array<HighlightLayer>();
  518. // Skeletons
  519. private _skeletonsEnabled = true;
  520. public set skeletonsEnabled(value: boolean) {
  521. if (this._skeletonsEnabled === value) {
  522. return;
  523. }
  524. this._skeletonsEnabled = value;
  525. this.markAllMaterialsAsDirty(Material.AttributesDirtyFlag);
  526. }
  527. public get skeletonsEnabled(): boolean {
  528. return this._skeletonsEnabled;
  529. }
  530. public skeletons = new Array<Skeleton>();
  531. // Morph targets
  532. public morphTargetManagers = new Array<MorphTargetManager>();
  533. // Lens flares
  534. public lensFlaresEnabled = true;
  535. public lensFlareSystems = new Array<LensFlareSystem>();
  536. // Collisions
  537. public collisionsEnabled = true;
  538. private _workerCollisions;
  539. public collisionCoordinator: ICollisionCoordinator;
  540. /** Defines the gravity applied to this scene */
  541. public gravity = new Vector3(0, -9.807, 0);
  542. // Postprocesses
  543. public postProcesses = new Array<PostProcess>();
  544. public postProcessesEnabled = true;
  545. public postProcessManager: PostProcessManager;
  546. private _postProcessRenderPipelineManager: PostProcessRenderPipelineManager
  547. public get postProcessRenderPipelineManager(): PostProcessRenderPipelineManager {
  548. if (!this._postProcessRenderPipelineManager) {
  549. this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  550. }
  551. return this._postProcessRenderPipelineManager;
  552. }
  553. // Customs render targets
  554. public renderTargetsEnabled = true;
  555. public dumpNextRenderTargets = false;
  556. public customRenderTargets = new Array<RenderTargetTexture>();
  557. // Delay loading
  558. public useDelayedTextureLoading: boolean;
  559. // Imported meshes
  560. public importedMeshesFiles = new Array<String>();
  561. // Probes
  562. public probesEnabled = true;
  563. public reflectionProbes = new Array<ReflectionProbe>();
  564. // Database
  565. public database; //ANY
  566. /**
  567. * This scene's action manager
  568. * @type {BABYLON.ActionManager}
  569. */
  570. public actionManager: ActionManager;
  571. public _actionManagers = new Array<ActionManager>();
  572. private _meshesForIntersections = new SmartArray<AbstractMesh>(256);
  573. // Procedural textures
  574. public proceduralTexturesEnabled = true;
  575. public _proceduralTextures = new Array<ProceduralTexture>();
  576. // Sound Tracks
  577. public mainSoundTrack: SoundTrack;
  578. public soundTracks = new Array<SoundTrack>();
  579. private _audioEnabled = true;
  580. private _headphone = false;
  581. // VR Helper
  582. public VRHelper: VRExperienceHelper;
  583. //Simplification Queue
  584. public simplificationQueue: SimplificationQueue;
  585. // Private
  586. private _engine: Engine;
  587. // Performance counters
  588. private _totalMeshesCounter = new PerfCounter();
  589. private _totalLightsCounter = new PerfCounter();
  590. private _totalMaterialsCounter = new PerfCounter();
  591. private _totalTexturesCounter = new PerfCounter();
  592. private _totalVertices = new PerfCounter();
  593. public _activeIndices = new PerfCounter();
  594. public _activeParticles = new PerfCounter();
  595. private _interFrameDuration = new PerfCounter();
  596. private _lastFrameDuration = new PerfCounter();
  597. private _evaluateActiveMeshesDuration = new PerfCounter();
  598. private _renderTargetsDuration = new PerfCounter();
  599. public _particlesDuration = new PerfCounter();
  600. private _renderDuration = new PerfCounter();
  601. public _spritesDuration = new PerfCounter();
  602. public _activeBones = new PerfCounter();
  603. private _animationRatio: number;
  604. private _animationTimeLast: number;
  605. private _animationTime: number = 0;
  606. public animationTimeScale: number = 1;
  607. public _cachedMaterial: Material;
  608. public _cachedEffect: Effect;
  609. public _cachedVisibility: number;
  610. private _renderId = 0;
  611. private _executeWhenReadyTimeoutId = -1;
  612. private _intermediateRendering = false;
  613. private _viewUpdateFlag = -1;
  614. private _projectionUpdateFlag = -1;
  615. private _alternateViewUpdateFlag = -1;
  616. private _alternateProjectionUpdateFlag = -1;
  617. public _toBeDisposed = new SmartArray<IDisposable>(256);
  618. private _pendingData = [];//ANY
  619. private _activeMeshes = new SmartArray<Mesh>(256);
  620. private _processedMaterials = new SmartArray<Material>(256);
  621. private _renderTargets = new SmartArray<RenderTargetTexture>(256);
  622. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  623. private _activeSkeletons = new SmartArray<Skeleton>(32);
  624. private _softwareSkinnedMeshes = new SmartArray<Mesh>(32);
  625. private _renderingManager: RenderingManager;
  626. private _physicsEngine: PhysicsEngine;
  627. public _activeAnimatables = new Array<Animatable>();
  628. private _transformMatrix = Matrix.Zero();
  629. private _sceneUbo: UniformBuffer;
  630. private _alternateSceneUbo: UniformBuffer;
  631. private _pickWithRayInverseMatrix: Matrix;
  632. private _boundingBoxRenderer: BoundingBoxRenderer;
  633. private _outlineRenderer: OutlineRenderer;
  634. private _viewMatrix: Matrix;
  635. private _projectionMatrix: Matrix;
  636. private _alternateViewMatrix: Matrix;
  637. private _alternateProjectionMatrix: Matrix;
  638. private _alternateTransformMatrix: Matrix;
  639. private _useAlternateCameraConfiguration = false;
  640. private _alternateRendering = false;
  641. public get _isAlternateRenderingEnabled(): boolean {
  642. return this._alternateRendering;
  643. }
  644. private _frustumPlanes: Plane[];
  645. public get frustumPlanes(): Plane[] {
  646. return this._frustumPlanes;
  647. }
  648. public requireLightSorting = false;
  649. private _selectionOctree: Octree<AbstractMesh>;
  650. private _pointerOverMesh: AbstractMesh;
  651. private _pointerOverSprite: Sprite;
  652. private _debugLayer: DebugLayer;
  653. private _depthRenderer: DepthRenderer;
  654. private _geometryBufferRenderer: GeometryBufferRenderer;
  655. private _uniqueIdCounter = 0;
  656. private _pickedDownMesh: AbstractMesh;
  657. private _pickedUpMesh: AbstractMesh;
  658. private _pickedDownSprite: Sprite;
  659. private _externalData: StringDictionary<Object>;
  660. private _uid: string;
  661. /**
  662. * @constructor
  663. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  664. */
  665. constructor(engine: Engine) {
  666. this._engine = engine || Engine.LastCreatedEngine;
  667. this._engine.scenes.push(this);
  668. this._uid = null;
  669. this._renderingManager = new RenderingManager(this);
  670. this.postProcessManager = new PostProcessManager(this);
  671. if (OutlineRenderer) {
  672. this._outlineRenderer = new OutlineRenderer(this);
  673. }
  674. this.attachControl();
  675. if (SoundTrack) {
  676. this.mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  677. }
  678. //simplification queue
  679. if (SimplificationQueue) {
  680. this.simplificationQueue = new SimplificationQueue();
  681. }
  682. //collision coordinator initialization. For now legacy per default.
  683. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  684. // Uniform Buffer
  685. this._createUbo();
  686. // Default Image processing definition.
  687. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  688. }
  689. // Properties
  690. public get debugLayer(): DebugLayer {
  691. if (!this._debugLayer) {
  692. this._debugLayer = new DebugLayer(this);
  693. }
  694. return this._debugLayer;
  695. }
  696. public set workerCollisions(enabled: boolean) {
  697. if (!BABYLON.CollisionCoordinatorLegacy) {
  698. return;
  699. }
  700. enabled = (enabled && !!Worker);
  701. this._workerCollisions = enabled;
  702. if (this.collisionCoordinator) {
  703. this.collisionCoordinator.destroy();
  704. }
  705. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  706. this.collisionCoordinator.init(this);
  707. }
  708. public get workerCollisions(): boolean {
  709. return this._workerCollisions;
  710. }
  711. public get selectionOctree(): Octree<AbstractMesh> {
  712. return this._selectionOctree;
  713. }
  714. /**
  715. * The mesh that is currently under the pointer.
  716. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  717. */
  718. public get meshUnderPointer(): AbstractMesh {
  719. return this._pointerOverMesh;
  720. }
  721. /**
  722. * Current on-screen X position of the pointer
  723. * @return {number} X position of the pointer
  724. */
  725. public get pointerX(): number {
  726. return this._pointerX;
  727. }
  728. /**
  729. * Current on-screen Y position of the pointer
  730. * @return {number} Y position of the pointer
  731. */
  732. public get pointerY(): number {
  733. return this._pointerY;
  734. }
  735. public getCachedMaterial(): Material {
  736. return this._cachedMaterial;
  737. }
  738. public getCachedEffect(): Effect {
  739. return this._cachedEffect;
  740. }
  741. public getCachedVisibility(): number {
  742. return this._cachedVisibility;
  743. }
  744. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  745. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  746. }
  747. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  748. if (!this._boundingBoxRenderer) {
  749. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  750. }
  751. return this._boundingBoxRenderer;
  752. }
  753. public getOutlineRenderer(): OutlineRenderer {
  754. return this._outlineRenderer;
  755. }
  756. public getEngine(): Engine {
  757. return this._engine;
  758. }
  759. public getTotalVertices(): number {
  760. return this._totalVertices.current;
  761. }
  762. public get totalVerticesPerfCounter(): PerfCounter {
  763. return this._totalVertices;
  764. }
  765. public getActiveIndices(): number {
  766. return this._activeIndices.current;
  767. }
  768. public get totalActiveIndicesPerfCounter(): PerfCounter {
  769. return this._activeIndices;
  770. }
  771. public getActiveParticles(): number {
  772. return this._activeParticles.current;
  773. }
  774. public get activeParticlesPerfCounter(): PerfCounter {
  775. return this._activeParticles;
  776. }
  777. public getActiveBones(): number {
  778. return this._activeBones.current;
  779. }
  780. public get activeBonesPerfCounter(): PerfCounter {
  781. return this._activeBones;
  782. }
  783. // Stats
  784. public getInterFramePerfCounter(): number {
  785. return this._interFrameDuration.current;
  786. }
  787. public get interFramePerfCounter(): PerfCounter {
  788. return this._interFrameDuration;
  789. }
  790. public getLastFrameDuration(): number {
  791. return this._lastFrameDuration.current;
  792. }
  793. public get lastFramePerfCounter(): PerfCounter {
  794. return this._lastFrameDuration;
  795. }
  796. public getEvaluateActiveMeshesDuration(): number {
  797. return this._evaluateActiveMeshesDuration.current;
  798. }
  799. public get evaluateActiveMeshesDurationPerfCounter(): PerfCounter {
  800. return this._evaluateActiveMeshesDuration;
  801. }
  802. public getActiveMeshes(): SmartArray<Mesh> {
  803. return this._activeMeshes;
  804. }
  805. public getRenderTargetsDuration(): number {
  806. return this._renderTargetsDuration.current;
  807. }
  808. public getRenderDuration(): number {
  809. return this._renderDuration.current;
  810. }
  811. public get renderDurationPerfCounter(): PerfCounter {
  812. return this._renderDuration;
  813. }
  814. public getParticlesDuration(): number {
  815. return this._particlesDuration.current;
  816. }
  817. public get particlesDurationPerfCounter(): PerfCounter {
  818. return this._particlesDuration;
  819. }
  820. public getSpritesDuration(): number {
  821. return this._spritesDuration.current;
  822. }
  823. public get spriteDuractionPerfCounter(): PerfCounter {
  824. return this._spritesDuration;
  825. }
  826. public getAnimationRatio(): number {
  827. return this._animationRatio;
  828. }
  829. public getRenderId(): number {
  830. return this._renderId;
  831. }
  832. public incrementRenderId(): void {
  833. this._renderId++;
  834. }
  835. private _updatePointerPosition(evt: PointerEvent): void {
  836. var canvasRect = this._engine.getRenderingCanvasClientRect();
  837. this._pointerX = evt.clientX - canvasRect.left;
  838. this._pointerY = evt.clientY - canvasRect.top;
  839. this._unTranslatedPointerX = this._pointerX;
  840. this._unTranslatedPointerY = this._pointerY;
  841. }
  842. private _createUbo(): void {
  843. this._sceneUbo = new UniformBuffer(this._engine, null, true);
  844. this._sceneUbo.addUniform("viewProjection", 16);
  845. this._sceneUbo.addUniform("view", 16);
  846. }
  847. private _createAlternateUbo(): void {
  848. this._alternateSceneUbo = new UniformBuffer(this._engine, null, true);
  849. this._alternateSceneUbo.addUniform("viewProjection", 16);
  850. this._alternateSceneUbo.addUniform("view", 16);
  851. }
  852. // Pointers handling
  853. /**
  854. * Use this method to simulate a pointer move on a mesh
  855. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  856. */
  857. public simulatePointerMove(pickResult: PickingInfo): Scene {
  858. let evt = new PointerEvent("pointermove");
  859. return this._processPointerMove(pickResult, evt);
  860. }
  861. private _processPointerMove(pickResult: PickingInfo, evt: PointerEvent): Scene {
  862. var canvas = this._engine.getRenderingCanvas();
  863. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  864. this.setPointerOverSprite(null);
  865. this.setPointerOverMesh(pickResult.pickedMesh);
  866. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  867. if (this._pointerOverMesh.actionManager.hoverCursor) {
  868. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  869. } else {
  870. canvas.style.cursor = this.hoverCursor;
  871. }
  872. } else {
  873. canvas.style.cursor = this.defaultCursor;
  874. }
  875. } else {
  876. this.setPointerOverMesh(null);
  877. // Sprites
  878. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  879. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  880. this.setPointerOverSprite(pickResult.pickedSprite);
  881. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  882. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  883. } else {
  884. canvas.style.cursor = this.hoverCursor;
  885. }
  886. } else {
  887. this.setPointerOverSprite(null);
  888. // Restore pointer
  889. canvas.style.cursor = this.defaultCursor;
  890. }
  891. }
  892. if (this.onPointerMove) {
  893. this.onPointerMove(evt, pickResult);
  894. }
  895. if (this.onPointerObservable.hasObservers()) {
  896. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  897. let pi = new PointerInfo(type, evt, pickResult);
  898. this.onPointerObservable.notifyObservers(pi, type);
  899. }
  900. return this;
  901. }
  902. /**
  903. * Use this method to simulate a pointer down on a mesh
  904. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  905. */
  906. public simulatePointerDown(pickResult: PickingInfo): Scene {
  907. let evt = new PointerEvent("pointerdown");
  908. return this._processPointerDown(pickResult, evt);
  909. }
  910. private _processPointerDown(pickResult: PickingInfo, evt: PointerEvent): Scene {
  911. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  912. this._pickedDownMesh = pickResult.pickedMesh;
  913. var actionManager = pickResult.pickedMesh.actionManager;
  914. if (actionManager) {
  915. if (actionManager.hasPickTriggers) {
  916. actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  917. switch (evt.button) {
  918. case 0:
  919. actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  920. break;
  921. case 1:
  922. actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  923. break;
  924. case 2:
  925. actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  926. break;
  927. }
  928. }
  929. if (actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger)) {
  930. window.setTimeout((function () {
  931. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  932. (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger) && mesh == this._pickedDownMesh,
  933. false, this.cameraToUseForPointers);
  934. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  935. if (this._isButtonPressed &&
  936. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  937. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  938. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  939. this._startingPointerTime = 0;
  940. actionManager.processTrigger(ActionManager.OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  941. }
  942. }
  943. }).bind(this), Scene.LongPressDelay);
  944. }
  945. }
  946. }
  947. if (this.onPointerDown) {
  948. this.onPointerDown(evt, pickResult);
  949. }
  950. if (this.onPointerObservable.hasObservers()) {
  951. let type = PointerEventTypes.POINTERDOWN;
  952. let pi = new PointerInfo(type, evt, pickResult);
  953. this.onPointerObservable.notifyObservers(pi, type);
  954. }
  955. return this;
  956. }
  957. /**
  958. * Use this method to simulate a pointer up on a mesh
  959. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  960. */
  961. public simulatePointerUp(pickResult: PickingInfo): Scene {
  962. let evt = new PointerEvent("pointerup");
  963. let clickInfo = new ClickInfo();
  964. clickInfo.singleClick = true;
  965. return this._processPointerUp(pickResult, evt, clickInfo);
  966. }
  967. private _processPointerUp(pickResult: PickingInfo, evt: PointerEvent, clickInfo: ClickInfo): Scene {
  968. if (pickResult && pickResult && pickResult.pickedMesh) {
  969. this._pickedUpMesh = pickResult.pickedMesh;
  970. if (this._pickedDownMesh === this._pickedUpMesh) {
  971. if (this.onPointerPick) {
  972. this.onPointerPick(evt, pickResult);
  973. }
  974. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  975. let type = PointerEventTypes.POINTERPICK;
  976. let pi = new PointerInfo(type, evt, pickResult);
  977. this.onPointerObservable.notifyObservers(pi, type);
  978. }
  979. }
  980. if (pickResult.pickedMesh.actionManager) {
  981. if (clickInfo.ignore) {
  982. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  983. }
  984. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  985. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  986. }
  987. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  988. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  989. }
  990. }
  991. }
  992. if (this._pickedDownMesh &&
  993. this._pickedDownMesh.actionManager &&
  994. this._pickedDownMesh.actionManager.hasSpecificTrigger(ActionManager.OnPickOutTrigger) &&
  995. this._pickedDownMesh !== this._pickedUpMesh) {
  996. this._pickedDownMesh.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  997. }
  998. if (this.onPointerUp) {
  999. this.onPointerUp(evt, pickResult);
  1000. }
  1001. if (this.onPointerObservable.hasObservers()) {
  1002. if (!clickInfo.ignore) {
  1003. if (!clickInfo.hasSwiped) {
  1004. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1005. let type = PointerEventTypes.POINTERTAP;
  1006. let pi = new PointerInfo(type, evt, pickResult);
  1007. this.onPointerObservable.notifyObservers(pi, type);
  1008. }
  1009. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1010. let type = PointerEventTypes.POINTERDOUBLETAP;
  1011. let pi = new PointerInfo(type, evt, pickResult);
  1012. this.onPointerObservable.notifyObservers(pi, type);
  1013. }
  1014. }
  1015. }
  1016. else {
  1017. let type = PointerEventTypes.POINTERUP;
  1018. let pi = new PointerInfo(type, evt, pickResult);
  1019. this.onPointerObservable.notifyObservers(pi, type);
  1020. }
  1021. }
  1022. return this;
  1023. }
  1024. /**
  1025. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1026. * @param attachUp defines if you want to attach events to pointerup
  1027. * @param attachDown defines if you want to attach events to pointerdown
  1028. * @param attachMove defines if you want to attach events to pointermove
  1029. */
  1030. public attachControl(attachUp = true, attachDown = true, attachMove = true) {
  1031. this._initActionManager = (act: ActionManager, clickInfo: ClickInfo): ActionManager => {
  1032. if (!this._meshPickProceed) {
  1033. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1034. this._currentPickResult = pickResult;
  1035. if (pickResult) {
  1036. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  1037. }
  1038. this._meshPickProceed = true;
  1039. }
  1040. return act;
  1041. };
  1042. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: PointerInfo) => void) => {
  1043. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  1044. if ((new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  1045. btn !== this._previousButtonPressed) {
  1046. this._doubleClickOccured = false;
  1047. clickInfo.singleClick = true;
  1048. clickInfo.ignore = false;
  1049. cb(clickInfo, this._currentPickResult);
  1050. }
  1051. }
  1052. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: PointerInfo) => void): void => {
  1053. let clickInfo = new ClickInfo();
  1054. this._currentPickResult = null;
  1055. let act;
  1056. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  1057. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  1058. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1059. if (!checkPicking && BABYLON.ActionManager && ActionManager.HasPickTriggers) {
  1060. act = this._initActionManager(act, clickInfo);
  1061. if (act)
  1062. checkPicking = act.hasPickTriggers;
  1063. }
  1064. if (checkPicking) {
  1065. let btn = evt.button;
  1066. clickInfo.hasSwiped = Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  1067. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  1068. if (!clickInfo.hasSwiped) {
  1069. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  1070. if (!checkSingleClickImmediately) {
  1071. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  1072. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1073. if (checkSingleClickImmediately && !ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1074. act = this._initActionManager(act, clickInfo);
  1075. if (act)
  1076. checkSingleClickImmediately = !act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1077. }
  1078. }
  1079. if (checkSingleClickImmediately) {
  1080. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  1081. if (new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  1082. btn !== this._previousButtonPressed) {
  1083. clickInfo.singleClick = true;
  1084. cb(clickInfo, this._currentPickResult);
  1085. }
  1086. }
  1087. // at least one double click is required to be check and exclusive double click is enabled
  1088. else {
  1089. // wait that no double click has been raised during the double click delay
  1090. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1091. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  1092. }
  1093. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  1094. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1095. if (!checkDoubleClick && ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1096. act = this._initActionManager(act, clickInfo);
  1097. if (act)
  1098. checkDoubleClick = act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1099. }
  1100. if (checkDoubleClick) {
  1101. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  1102. if (btn === this._previousButtonPressed &&
  1103. new Date().getTime() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  1104. !this._doubleClickOccured
  1105. ) {
  1106. // pointer has not moved for 2 clicks, it's a double click
  1107. if (!clickInfo.hasSwiped &&
  1108. Math.abs(this._previousStartingPointerPosition.x - this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  1109. Math.abs(this._previousStartingPointerPosition.y - this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  1110. this._previousStartingPointerTime = 0;
  1111. this._doubleClickOccured = true;
  1112. clickInfo.doubleClick = true;
  1113. clickInfo.ignore = false;
  1114. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout && this._previousDelayedSimpleClickTimeout.clearTimeout)
  1115. this._previousDelayedSimpleClickTimeout.clearTimeout();
  1116. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1117. cb(clickInfo, this._currentPickResult);
  1118. }
  1119. // if the two successive clicks are too far, it's just two simple clicks
  1120. else {
  1121. this._doubleClickOccured = false;
  1122. this._previousStartingPointerTime = this._startingPointerTime;
  1123. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1124. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1125. this._previousButtonPressed = btn;
  1126. this._previousHasSwiped = clickInfo.hasSwiped;
  1127. if (Scene.ExclusiveDoubleClickMode) {
  1128. if (this._previousDelayedSimpleClickTimeout && this._previousDelayedSimpleClickTimeout.clearTimeout) {
  1129. this._previousDelayedSimpleClickTimeout.clearTimeout();
  1130. }
  1131. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1132. cb(clickInfo, this._previousPickResult);
  1133. }
  1134. else {
  1135. cb(clickInfo, this._currentPickResult);
  1136. }
  1137. }
  1138. }
  1139. // just the first click of the double has been raised
  1140. else {
  1141. this._doubleClickOccured = false;
  1142. this._previousStartingPointerTime = this._startingPointerTime;
  1143. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1144. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1145. this._previousButtonPressed = btn;
  1146. this._previousHasSwiped = clickInfo.hasSwiped;
  1147. }
  1148. }
  1149. }
  1150. }
  1151. clickInfo.ignore = true;
  1152. cb(clickInfo, this._currentPickResult);
  1153. };
  1154. this._spritePredicate = (sprite: Sprite): boolean => {
  1155. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  1156. };
  1157. this._onPointerMove = (evt: PointerEvent) => {
  1158. this._updatePointerPosition(evt);
  1159. // PreObservable support
  1160. if (this.onPrePointerObservable.hasObservers()) {
  1161. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1162. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1163. this.onPrePointerObservable.notifyObservers(pi, type);
  1164. if (pi.skipOnPointerObservable) {
  1165. return;
  1166. }
  1167. }
  1168. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1169. return;
  1170. }
  1171. if (!this.pointerMovePredicate) {
  1172. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined));
  1173. }
  1174. // Meshes
  1175. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  1176. this._processPointerMove(pickResult, evt);
  1177. };
  1178. this._onPointerDown = (evt: PointerEvent) => {
  1179. this._isButtonPressed = true;
  1180. this._pickedDownMesh = null;
  1181. this._meshPickProceed = false;
  1182. this._updatePointerPosition(evt);
  1183. // PreObservable support
  1184. if (this.onPrePointerObservable.hasObservers()) {
  1185. let type = PointerEventTypes.POINTERDOWN;
  1186. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1187. this.onPrePointerObservable.notifyObservers(pi, type);
  1188. if (pi.skipOnPointerObservable) {
  1189. return;
  1190. }
  1191. }
  1192. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1193. return;
  1194. }
  1195. this._startingPointerPosition.x = this._pointerX;
  1196. this._startingPointerPosition.y = this._pointerY;
  1197. this._startingPointerTime = new Date().getTime();
  1198. if (!this.pointerDownPredicate) {
  1199. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  1200. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1201. };
  1202. }
  1203. // Meshes
  1204. this._pickedDownMesh = null;
  1205. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1206. this._processPointerDown(pickResult, evt);
  1207. // Sprites
  1208. this._pickedDownSprite = null;
  1209. if (this.spriteManagers.length > 0) {
  1210. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  1211. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1212. if (pickResult.pickedSprite.actionManager) {
  1213. this._pickedDownSprite = pickResult.pickedSprite;
  1214. switch (evt.button) {
  1215. case 0:
  1216. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1217. break;
  1218. case 1:
  1219. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1220. break;
  1221. case 2:
  1222. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1223. break;
  1224. }
  1225. if (pickResult.pickedSprite.actionManager) {
  1226. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1227. }
  1228. }
  1229. }
  1230. }
  1231. };
  1232. this._onPointerUp = (evt: PointerEvent) => {
  1233. this._isButtonPressed = false;
  1234. this._pickedUpMesh = null;
  1235. this._meshPickProceed = false;
  1236. this._updatePointerPosition(evt);
  1237. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  1238. // PreObservable support
  1239. if (this.onPrePointerObservable.hasObservers()) {
  1240. if (!clickInfo.ignore) {
  1241. if (!clickInfo.hasSwiped) {
  1242. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1243. let type = PointerEventTypes.POINTERTAP;
  1244. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1245. this.onPrePointerObservable.notifyObservers(pi, type);
  1246. if (pi.skipOnPointerObservable) {
  1247. return;
  1248. }
  1249. }
  1250. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1251. let type = PointerEventTypes.POINTERDOUBLETAP;
  1252. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1253. this.onPrePointerObservable.notifyObservers(pi, type);
  1254. if (pi.skipOnPointerObservable) {
  1255. return;
  1256. }
  1257. }
  1258. }
  1259. }
  1260. else {
  1261. let type = PointerEventTypes.POINTERUP;
  1262. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1263. this.onPrePointerObservable.notifyObservers(pi, type);
  1264. if (pi.skipOnPointerObservable) {
  1265. return;
  1266. }
  1267. }
  1268. }
  1269. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1270. return;
  1271. }
  1272. if (!this.pointerUpPredicate) {
  1273. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1274. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1275. };
  1276. }
  1277. // Meshes
  1278. if (!this._meshPickProceed && (BABYLON.ActionManager && ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1279. this._initActionManager(null, clickInfo);
  1280. }
  1281. if (!pickResult) {
  1282. pickResult = this._currentPickResult;
  1283. }
  1284. this._processPointerUp(pickResult, evt, clickInfo);
  1285. // Sprites
  1286. if (this.spriteManagers.length > 0) {
  1287. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  1288. if (pickResult.hit && pickResult.pickedSprite) {
  1289. if (pickResult.pickedSprite.actionManager) {
  1290. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1291. if (pickResult.pickedSprite.actionManager) {
  1292. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  1293. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1294. }
  1295. }
  1296. }
  1297. }
  1298. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  1299. this._pickedDownSprite.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  1300. }
  1301. }
  1302. this._previousPickResult = this._currentPickResult;
  1303. }).bind(this));
  1304. };
  1305. this._onKeyDown = (evt: KeyboardEvent) => {
  1306. let type = KeyboardEventTypes.KEYDOWN;
  1307. if (this.onPreKeyboardObservable.hasObservers()) {
  1308. let pi = new KeyboardInfoPre(type, evt);
  1309. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1310. if (pi.skipOnPointerObservable) {
  1311. return;
  1312. }
  1313. }
  1314. if (this.onKeyboardObservable.hasObservers()) {
  1315. let pi = new KeyboardInfo(type, evt);
  1316. this.onKeyboardObservable.notifyObservers(pi, type);
  1317. }
  1318. if (this.actionManager) {
  1319. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1320. }
  1321. };
  1322. this._onKeyUp = (evt: KeyboardEvent) => {
  1323. let type = KeyboardEventTypes.KEYUP;
  1324. if (this.onPreKeyboardObservable.hasObservers()) {
  1325. let pi = new KeyboardInfoPre(type, evt);
  1326. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1327. if (pi.skipOnPointerObservable) {
  1328. return;
  1329. }
  1330. }
  1331. if (this.onKeyboardObservable.hasObservers()) {
  1332. let pi = new KeyboardInfo(type, evt);
  1333. this.onKeyboardObservable.notifyObservers(pi, type);
  1334. }
  1335. if (this.actionManager) {
  1336. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1337. }
  1338. };
  1339. let engine = this.getEngine();
  1340. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(()=>{
  1341. canvas.addEventListener("keydown", this._onKeyDown, false);
  1342. canvas.addEventListener("keyup", this._onKeyUp, false);
  1343. });
  1344. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(()=>{
  1345. canvas.removeEventListener("keydown", this._onKeyDown);
  1346. canvas.removeEventListener("keyup", this._onKeyUp);
  1347. });
  1348. var eventPrefix = Tools.GetPointerPrefix();
  1349. var canvas = this._engine.getRenderingCanvas();
  1350. if (attachMove) {
  1351. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  1352. // Wheel
  1353. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  1354. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  1355. }
  1356. if (attachDown) {
  1357. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  1358. }
  1359. if (attachUp) {
  1360. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  1361. }
  1362. canvas.tabIndex = 1;
  1363. }
  1364. public detachControl() {
  1365. let engine = this.getEngine();
  1366. var eventPrefix = Tools.GetPointerPrefix();
  1367. var canvas = engine.getRenderingCanvas();
  1368. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  1369. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  1370. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  1371. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  1372. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  1373. // Wheel
  1374. canvas.removeEventListener('mousewheel', this._onPointerMove);
  1375. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  1376. // Keyboard
  1377. canvas.removeEventListener("keydown", this._onKeyDown);
  1378. canvas.removeEventListener("keyup", this._onKeyUp);
  1379. // Observables
  1380. this.onKeyboardObservable.clear();
  1381. this.onPreKeyboardObservable.clear();
  1382. this.onPointerObservable.clear();
  1383. this.onPrePointerObservable.clear();
  1384. }
  1385. // Ready
  1386. public isReady(): boolean {
  1387. if (this._pendingData.length > 0) {
  1388. return false;
  1389. }
  1390. var index: number;
  1391. // Geometries
  1392. for (index = 0; index < this._geometries.length; index++) {
  1393. var geometry = this._geometries[index];
  1394. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1395. return false;
  1396. }
  1397. }
  1398. // Meshes
  1399. for (index = 0; index < this.meshes.length; index++) {
  1400. var mesh = this.meshes[index];
  1401. if (!mesh.isEnabled()) {
  1402. continue;
  1403. }
  1404. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  1405. continue;
  1406. }
  1407. if (!mesh.isReady()) {
  1408. return false;
  1409. }
  1410. var mat = mesh.material;
  1411. if (mat) {
  1412. if (!mat.isReady(mesh)) {
  1413. return false;
  1414. }
  1415. }
  1416. }
  1417. return true;
  1418. }
  1419. public resetCachedMaterial(): void {
  1420. this._cachedMaterial = null;
  1421. this._cachedEffect = null;
  1422. this._cachedVisibility = null;
  1423. }
  1424. public registerBeforeRender(func: () => void): void {
  1425. this.onBeforeRenderObservable.add(func);
  1426. }
  1427. public unregisterBeforeRender(func: () => void): void {
  1428. this.onBeforeRenderObservable.removeCallback(func);
  1429. }
  1430. public registerAfterRender(func: () => void): void {
  1431. this.onAfterRenderObservable.add(func);
  1432. }
  1433. public unregisterAfterRender(func: () => void): void {
  1434. this.onAfterRenderObservable.removeCallback(func);
  1435. }
  1436. public _addPendingData(data): void {
  1437. this._pendingData.push(data);
  1438. }
  1439. public _removePendingData(data): void {
  1440. var index = this._pendingData.indexOf(data);
  1441. if (index !== -1) {
  1442. this._pendingData.splice(index, 1);
  1443. }
  1444. }
  1445. public getWaitingItemsCount(): number {
  1446. return this._pendingData.length;
  1447. }
  1448. /**
  1449. * Registers a function to be executed when the scene is ready.
  1450. * @param {Function} func - the function to be executed.
  1451. */
  1452. public executeWhenReady(func: () => void): void {
  1453. this.onReadyObservable.add(func);
  1454. if (this._executeWhenReadyTimeoutId !== -1) {
  1455. return;
  1456. }
  1457. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1458. this._checkIsReady();
  1459. }, 150);
  1460. }
  1461. public _checkIsReady() {
  1462. if (this.isReady()) {
  1463. this.onReadyObservable.notifyObservers(this);
  1464. this.onReadyObservable.clear();
  1465. this._executeWhenReadyTimeoutId = -1;
  1466. return;
  1467. }
  1468. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1469. this._checkIsReady();
  1470. }, 150);
  1471. }
  1472. // Animations
  1473. /**
  1474. * Will start the animation sequence of a given target
  1475. * @param target - the target
  1476. * @param {number} from - from which frame should animation start
  1477. * @param {number} to - till which frame should animation run.
  1478. * @param {boolean} [loop] - should the animation loop
  1479. * @param {number} [speedRatio] - the speed in which to run the animation
  1480. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  1481. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  1482. * Returns {BABYLON.Animatable} the animatable object created for this animation
  1483. * See BABYLON.Animatable
  1484. */
  1485. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  1486. if (from > to && speedRatio > 0) {
  1487. speedRatio *= -1;
  1488. }
  1489. this.stopAnimation(target);
  1490. if (!animatable) {
  1491. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  1492. }
  1493. // Local animations
  1494. if (target.animations) {
  1495. animatable.appendAnimations(target, target.animations);
  1496. }
  1497. // Children animations
  1498. if (target.getAnimatables) {
  1499. var animatables = target.getAnimatables();
  1500. for (var index = 0; index < animatables.length; index++) {
  1501. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  1502. }
  1503. }
  1504. animatable.reset();
  1505. return animatable;
  1506. }
  1507. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  1508. if (speedRatio === undefined) {
  1509. speedRatio = 1.0;
  1510. }
  1511. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  1512. return animatable;
  1513. }
  1514. public getAnimatableByTarget(target: any): Animatable {
  1515. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1516. if (this._activeAnimatables[index].target === target) {
  1517. return this._activeAnimatables[index];
  1518. }
  1519. }
  1520. return null;
  1521. }
  1522. public get Animatables(): Animatable[] {
  1523. return this._activeAnimatables;
  1524. }
  1525. /**
  1526. * Will stop the animation of the given target
  1527. * @param target - the target
  1528. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  1529. * @see beginAnimation
  1530. */
  1531. public stopAnimation(target: any, animationName?: string): void {
  1532. var animatable = this.getAnimatableByTarget(target);
  1533. if (animatable) {
  1534. animatable.stop(animationName);
  1535. }
  1536. }
  1537. private _animate(): void {
  1538. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  1539. return;
  1540. }
  1541. // Getting time
  1542. var now = Tools.Now;
  1543. if (!this._animationTimeLast) {
  1544. if (this._pendingData.length > 0) {
  1545. return;
  1546. }
  1547. this._animationTimeLast = now;
  1548. }
  1549. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  1550. this._animationTime += deltaTime;
  1551. this._animationTimeLast = now;
  1552. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1553. this._activeAnimatables[index]._animate(this._animationTime);
  1554. }
  1555. }
  1556. // Matrix
  1557. public _switchToAlternateCameraConfiguration(active: boolean): void {
  1558. this._useAlternateCameraConfiguration = active;
  1559. }
  1560. public getViewMatrix(): Matrix {
  1561. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  1562. }
  1563. public getProjectionMatrix(): Matrix {
  1564. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  1565. }
  1566. public getTransformMatrix(): Matrix {
  1567. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  1568. }
  1569. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  1570. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  1571. return;
  1572. }
  1573. this._viewUpdateFlag = view.updateFlag;
  1574. this._projectionUpdateFlag = projection.updateFlag;
  1575. this._viewMatrix = view;
  1576. this._projectionMatrix = projection;
  1577. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  1578. // Update frustum
  1579. if (!this._frustumPlanes) {
  1580. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  1581. } else {
  1582. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1583. }
  1584. if (this._sceneUbo.useUbo) {
  1585. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  1586. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  1587. this._sceneUbo.update();
  1588. }
  1589. }
  1590. public _setAlternateTransformMatrix(view: Matrix, projection: Matrix): void {
  1591. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  1592. return;
  1593. }
  1594. this._alternateViewUpdateFlag = view.updateFlag;
  1595. this._alternateProjectionUpdateFlag = projection.updateFlag;
  1596. this._alternateViewMatrix = view;
  1597. this._alternateProjectionMatrix = projection;
  1598. if (!this._alternateTransformMatrix) {
  1599. this._alternateTransformMatrix = Matrix.Zero();
  1600. }
  1601. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  1602. if (!this._alternateSceneUbo) {
  1603. this._createAlternateUbo();
  1604. }
  1605. if (this._alternateSceneUbo.useUbo) {
  1606. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  1607. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  1608. this._alternateSceneUbo.update();
  1609. }
  1610. }
  1611. public getSceneUniformBuffer(): UniformBuffer {
  1612. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  1613. }
  1614. // Methods
  1615. public getUniqueId() {
  1616. var result = this._uniqueIdCounter;
  1617. this._uniqueIdCounter++;
  1618. return result;
  1619. }
  1620. public addMesh(newMesh: AbstractMesh) {
  1621. newMesh.uniqueId = this.getUniqueId();
  1622. var position = this.meshes.push(newMesh);
  1623. //notify the collision coordinator
  1624. if (this.collisionCoordinator) {
  1625. this.collisionCoordinator.onMeshAdded(newMesh);
  1626. }
  1627. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  1628. }
  1629. public removeMesh(toRemove: AbstractMesh): number {
  1630. var index = this.meshes.indexOf(toRemove);
  1631. if (index !== -1) {
  1632. // Remove from the scene if mesh found
  1633. this.meshes.splice(index, 1);
  1634. }
  1635. //notify the collision coordinator
  1636. if (this.collisionCoordinator) {
  1637. this.collisionCoordinator.onMeshRemoved(toRemove);
  1638. }
  1639. this.onMeshRemovedObservable.notifyObservers(toRemove);
  1640. return index;
  1641. }
  1642. public removeSkeleton(toRemove: Skeleton): number {
  1643. var index = this.skeletons.indexOf(toRemove);
  1644. if (index !== -1) {
  1645. // Remove from the scene if found
  1646. this.skeletons.splice(index, 1);
  1647. }
  1648. return index;
  1649. }
  1650. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  1651. var index = this.morphTargetManagers.indexOf(toRemove);
  1652. if (index !== -1) {
  1653. // Remove from the scene if found
  1654. this.morphTargetManagers.splice(index, 1);
  1655. }
  1656. return index;
  1657. }
  1658. public removeLight(toRemove: Light): number {
  1659. var index = this.lights.indexOf(toRemove);
  1660. if (index !== -1) {
  1661. // Remove from the scene if mesh found
  1662. this.lights.splice(index, 1);
  1663. this.sortLightsByPriority();
  1664. }
  1665. this.onLightRemovedObservable.notifyObservers(toRemove);
  1666. return index;
  1667. }
  1668. public removeCamera(toRemove: Camera): number {
  1669. var index = this.cameras.indexOf(toRemove);
  1670. if (index !== -1) {
  1671. // Remove from the scene if mesh found
  1672. this.cameras.splice(index, 1);
  1673. }
  1674. // Remove from activeCameras
  1675. var index2 = this.activeCameras.indexOf(toRemove);
  1676. if (index2 !== -1) {
  1677. // Remove from the scene if mesh found
  1678. this.activeCameras.splice(index2, 1);
  1679. }
  1680. // Reset the activeCamera
  1681. if (this.activeCamera === toRemove) {
  1682. if (this.cameras.length > 0) {
  1683. this.activeCamera = this.cameras[0];
  1684. } else {
  1685. this.activeCamera = null;
  1686. }
  1687. }
  1688. this.onCameraRemovedObservable.notifyObservers(toRemove);
  1689. return index;
  1690. }
  1691. public addLight(newLight: Light) {
  1692. newLight.uniqueId = this.getUniqueId();
  1693. this.lights.push(newLight);
  1694. this.sortLightsByPriority();
  1695. this.onNewLightAddedObservable.notifyObservers(newLight);
  1696. }
  1697. public sortLightsByPriority(): void {
  1698. if (this.requireLightSorting) {
  1699. this.lights.sort(Light.compareLightsPriority);
  1700. }
  1701. }
  1702. public addCamera(newCamera: Camera) {
  1703. newCamera.uniqueId = this.getUniqueId();
  1704. var position = this.cameras.push(newCamera);
  1705. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  1706. }
  1707. /**
  1708. * Switch active camera
  1709. * @param {Camera} newCamera - new active camera
  1710. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  1711. */
  1712. public switchActiveCamera(newCamera: Camera, attachControl = true) {
  1713. var canvas = this._engine.getRenderingCanvas();
  1714. this.activeCamera.detachControl(canvas);
  1715. this.activeCamera = newCamera;
  1716. if (attachControl) {
  1717. newCamera.attachControl(canvas);
  1718. }
  1719. }
  1720. /**
  1721. * sets the active camera of the scene using its ID
  1722. * @param {string} id - the camera's ID
  1723. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  1724. * @see activeCamera
  1725. */
  1726. public setActiveCameraByID(id: string): Camera {
  1727. var camera = this.getCameraByID(id);
  1728. if (camera) {
  1729. this.activeCamera = camera;
  1730. return camera;
  1731. }
  1732. return null;
  1733. }
  1734. /**
  1735. * sets the active camera of the scene using its name
  1736. * @param {string} name - the camera's name
  1737. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  1738. * @see activeCamera
  1739. */
  1740. public setActiveCameraByName(name: string): Camera {
  1741. var camera = this.getCameraByName(name);
  1742. if (camera) {
  1743. this.activeCamera = camera;
  1744. return camera;
  1745. }
  1746. return null;
  1747. }
  1748. /**
  1749. * get a material using its id
  1750. * @param {string} the material's ID
  1751. * @return {BABYLON.Material|null} the material or null if none found.
  1752. */
  1753. public getMaterialByID(id: string): Material {
  1754. for (var index = 0; index < this.materials.length; index++) {
  1755. if (this.materials[index].id === id) {
  1756. return this.materials[index];
  1757. }
  1758. }
  1759. return null;
  1760. }
  1761. /**
  1762. * get a material using its name
  1763. * @param {string} the material's name
  1764. * @return {BABYLON.Material|null} the material or null if none found.
  1765. */
  1766. public getMaterialByName(name: string): Material {
  1767. for (var index = 0; index < this.materials.length; index++) {
  1768. if (this.materials[index].name === name) {
  1769. return this.materials[index];
  1770. }
  1771. }
  1772. return null;
  1773. }
  1774. public getLensFlareSystemByName(name: string): LensFlareSystem {
  1775. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  1776. if (this.lensFlareSystems[index].name === name) {
  1777. return this.lensFlareSystems[index];
  1778. }
  1779. }
  1780. return null;
  1781. }
  1782. public getLensFlareSystemByID(id: string): LensFlareSystem {
  1783. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  1784. if (this.lensFlareSystems[index].id === id) {
  1785. return this.lensFlareSystems[index];
  1786. }
  1787. }
  1788. return null;
  1789. }
  1790. public getCameraByID(id: string): Camera {
  1791. for (var index = 0; index < this.cameras.length; index++) {
  1792. if (this.cameras[index].id === id) {
  1793. return this.cameras[index];
  1794. }
  1795. }
  1796. return null;
  1797. }
  1798. public getCameraByUniqueID(uniqueId: number): Camera {
  1799. for (var index = 0; index < this.cameras.length; index++) {
  1800. if (this.cameras[index].uniqueId === uniqueId) {
  1801. return this.cameras[index];
  1802. }
  1803. }
  1804. return null;
  1805. }
  1806. /**
  1807. * get a camera using its name
  1808. * @param {string} the camera's name
  1809. * @return {BABYLON.Camera|null} the camera or null if none found.
  1810. */
  1811. public getCameraByName(name: string): Camera {
  1812. for (var index = 0; index < this.cameras.length; index++) {
  1813. if (this.cameras[index].name === name) {
  1814. return this.cameras[index];
  1815. }
  1816. }
  1817. return null;
  1818. }
  1819. /**
  1820. * get a bone using its id
  1821. * @param {string} the bone's id
  1822. * @return {BABYLON.Bone|null} the bone or null if not found
  1823. */
  1824. public getBoneByID(id: string): Bone {
  1825. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  1826. var skeleton = this.skeletons[skeletonIndex];
  1827. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  1828. if (skeleton.bones[boneIndex].id === id) {
  1829. return skeleton.bones[boneIndex];
  1830. }
  1831. }
  1832. }
  1833. return null;
  1834. }
  1835. /**
  1836. * get a bone using its id
  1837. * @param {string} the bone's name
  1838. * @return {BABYLON.Bone|null} the bone or null if not found
  1839. */
  1840. public getBoneByName(name: string): Bone {
  1841. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  1842. var skeleton = this.skeletons[skeletonIndex];
  1843. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  1844. if (skeleton.bones[boneIndex].name === name) {
  1845. return skeleton.bones[boneIndex];
  1846. }
  1847. }
  1848. }
  1849. return null;
  1850. }
  1851. /**
  1852. * get a light node using its name
  1853. * @param {string} the light's name
  1854. * @return {BABYLON.Light|null} the light or null if none found.
  1855. */
  1856. public getLightByName(name: string): Light {
  1857. for (var index = 0; index < this.lights.length; index++) {
  1858. if (this.lights[index].name === name) {
  1859. return this.lights[index];
  1860. }
  1861. }
  1862. return null;
  1863. }
  1864. /**
  1865. * get a light node using its ID
  1866. * @param {string} the light's id
  1867. * @return {BABYLON.Light|null} the light or null if none found.
  1868. */
  1869. public getLightByID(id: string): Light {
  1870. for (var index = 0; index < this.lights.length; index++) {
  1871. if (this.lights[index].id === id) {
  1872. return this.lights[index];
  1873. }
  1874. }
  1875. return null;
  1876. }
  1877. /**
  1878. * get a light node using its scene-generated unique ID
  1879. * @param {number} the light's unique id
  1880. * @return {BABYLON.Light|null} the light or null if none found.
  1881. */
  1882. public getLightByUniqueID(uniqueId: number): Light {
  1883. for (var index = 0; index < this.lights.length; index++) {
  1884. if (this.lights[index].uniqueId === uniqueId) {
  1885. return this.lights[index];
  1886. }
  1887. }
  1888. return null;
  1889. }
  1890. /**
  1891. * get a particle system by id
  1892. * @param id {number} the particle system id
  1893. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  1894. */
  1895. public getParticleSystemByID(id: string): IParticleSystem {
  1896. for (var index = 0; index < this.particleSystems.length; index++) {
  1897. if (this.particleSystems[index].id === id) {
  1898. return this.particleSystems[index];
  1899. }
  1900. }
  1901. return null;
  1902. }
  1903. /**
  1904. * get a geometry using its ID
  1905. * @param {string} the geometry's id
  1906. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  1907. */
  1908. public getGeometryByID(id: string): Geometry {
  1909. for (var index = 0; index < this._geometries.length; index++) {
  1910. if (this._geometries[index].id === id) {
  1911. return this._geometries[index];
  1912. }
  1913. }
  1914. return null;
  1915. }
  1916. /**
  1917. * add a new geometry to this scene.
  1918. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  1919. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  1920. * @return {boolean} was the geometry added or not
  1921. */
  1922. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  1923. if (!force && this.getGeometryByID(geometry.id)) {
  1924. return false;
  1925. }
  1926. this._geometries.push(geometry);
  1927. //notify the collision coordinator
  1928. if (this.collisionCoordinator) {
  1929. this.collisionCoordinator.onGeometryAdded(geometry);
  1930. }
  1931. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  1932. return true;
  1933. }
  1934. /**
  1935. * Removes an existing geometry
  1936. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  1937. * @return {boolean} was the geometry removed or not
  1938. */
  1939. public removeGeometry(geometry: Geometry): boolean {
  1940. var index = this._geometries.indexOf(geometry);
  1941. if (index > -1) {
  1942. this._geometries.splice(index, 1);
  1943. //notify the collision coordinator
  1944. if (this.collisionCoordinator) {
  1945. this.collisionCoordinator.onGeometryDeleted(geometry);
  1946. }
  1947. this.onGeometryRemovedObservable.notifyObservers(geometry);
  1948. return true;
  1949. }
  1950. return false;
  1951. }
  1952. public getGeometries(): Geometry[] {
  1953. return this._geometries;
  1954. }
  1955. /**
  1956. * Get the first added mesh found of a given ID
  1957. * @param {string} id - the id to search for
  1958. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1959. */
  1960. public getMeshByID(id: string): AbstractMesh {
  1961. for (var index = 0; index < this.meshes.length; index++) {
  1962. if (this.meshes[index].id === id) {
  1963. return this.meshes[index];
  1964. }
  1965. }
  1966. return null;
  1967. }
  1968. public getMeshesByID(id: string): Array<AbstractMesh> {
  1969. return this.meshes.filter(function (m) {
  1970. return m.id === id;
  1971. })
  1972. }
  1973. /**
  1974. * Get a mesh with its auto-generated unique id
  1975. * @param {number} uniqueId - the unique id to search for
  1976. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1977. */
  1978. public getMeshByUniqueID(uniqueId: number): AbstractMesh {
  1979. for (var index = 0; index < this.meshes.length; index++) {
  1980. if (this.meshes[index].uniqueId === uniqueId) {
  1981. return this.meshes[index];
  1982. }
  1983. }
  1984. return null;
  1985. }
  1986. /**
  1987. * Get a the last added mesh found of a given ID
  1988. * @param {string} id - the id to search for
  1989. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1990. */
  1991. public getLastMeshByID(id: string): AbstractMesh {
  1992. for (var index = this.meshes.length - 1; index >= 0; index--) {
  1993. if (this.meshes[index].id === id) {
  1994. return this.meshes[index];
  1995. }
  1996. }
  1997. return null;
  1998. }
  1999. /**
  2000. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  2001. * @param {string} id - the id to search for
  2002. * @return {BABYLON.Node|null} the node found or null if not found at all.
  2003. */
  2004. public getLastEntryByID(id: string): Node {
  2005. var index: number;
  2006. for (index = this.meshes.length - 1; index >= 0; index--) {
  2007. if (this.meshes[index].id === id) {
  2008. return this.meshes[index];
  2009. }
  2010. }
  2011. for (index = this.cameras.length - 1; index >= 0; index--) {
  2012. if (this.cameras[index].id === id) {
  2013. return this.cameras[index];
  2014. }
  2015. }
  2016. for (index = this.lights.length - 1; index >= 0; index--) {
  2017. if (this.lights[index].id === id) {
  2018. return this.lights[index];
  2019. }
  2020. }
  2021. return null;
  2022. }
  2023. public getNodeByID(id: string): Node {
  2024. var mesh = this.getMeshByID(id);
  2025. if (mesh) {
  2026. return mesh;
  2027. }
  2028. var light = this.getLightByID(id);
  2029. if (light) {
  2030. return light;
  2031. }
  2032. var camera = this.getCameraByID(id);
  2033. if (camera) {
  2034. return camera;
  2035. }
  2036. var bone = this.getBoneByID(id);
  2037. return bone;
  2038. }
  2039. public getNodeByName(name: string): Node {
  2040. var mesh = this.getMeshByName(name);
  2041. if (mesh) {
  2042. return mesh;
  2043. }
  2044. var light = this.getLightByName(name);
  2045. if (light) {
  2046. return light;
  2047. }
  2048. var camera = this.getCameraByName(name);
  2049. if (camera) {
  2050. return camera;
  2051. }
  2052. var bone = this.getBoneByName(name);
  2053. return bone;
  2054. }
  2055. public getMeshByName(name: string): AbstractMesh {
  2056. for (var index = 0; index < this.meshes.length; index++) {
  2057. if (this.meshes[index].name === name) {
  2058. return this.meshes[index];
  2059. }
  2060. }
  2061. return null;
  2062. }
  2063. public getSoundByName(name: string): Sound {
  2064. var index: number;
  2065. if (AudioEngine) {
  2066. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  2067. if (this.mainSoundTrack.soundCollection[index].name === name) {
  2068. return this.mainSoundTrack.soundCollection[index];
  2069. }
  2070. }
  2071. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  2072. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  2073. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  2074. return this.soundTracks[sdIndex].soundCollection[index];
  2075. }
  2076. }
  2077. }
  2078. }
  2079. return null;
  2080. }
  2081. public getLastSkeletonByID(id: string): Skeleton {
  2082. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  2083. if (this.skeletons[index].id === id) {
  2084. return this.skeletons[index];
  2085. }
  2086. }
  2087. return null;
  2088. }
  2089. public getSkeletonById(id: string): Skeleton {
  2090. for (var index = 0; index < this.skeletons.length; index++) {
  2091. if (this.skeletons[index].id === id) {
  2092. return this.skeletons[index];
  2093. }
  2094. }
  2095. return null;
  2096. }
  2097. public getSkeletonByName(name: string): Skeleton {
  2098. for (var index = 0; index < this.skeletons.length; index++) {
  2099. if (this.skeletons[index].name === name) {
  2100. return this.skeletons[index];
  2101. }
  2102. }
  2103. return null;
  2104. }
  2105. public getMorphTargetManagerById(id: number): MorphTargetManager {
  2106. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  2107. if (this.morphTargetManagers[index].uniqueId === id) {
  2108. return this.morphTargetManagers[index];
  2109. }
  2110. }
  2111. return null;
  2112. }
  2113. public isActiveMesh(mesh: Mesh): boolean {
  2114. return (this._activeMeshes.indexOf(mesh) !== -1);
  2115. }
  2116. /**
  2117. * Return a the first highlight layer of the scene with a given name.
  2118. * @param name The name of the highlight layer to look for.
  2119. * @return The highlight layer if found otherwise null.
  2120. */
  2121. public getHighlightLayerByName(name: string): HighlightLayer {
  2122. for (var index = 0; index < this.highlightLayers.length; index++) {
  2123. if (this.highlightLayers[index].name === name) {
  2124. return this.highlightLayers[index];
  2125. }
  2126. }
  2127. return null;
  2128. }
  2129. /**
  2130. * Return a unique id as a string which can serve as an identifier for the scene
  2131. */
  2132. public get uid(): string {
  2133. if (!this._uid) {
  2134. this._uid = Tools.RandomId();
  2135. }
  2136. return this._uid;
  2137. }
  2138. /**
  2139. * Add an externaly attached data from its key.
  2140. * This method call will fail and return false, if such key already exists.
  2141. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2142. * @param key the unique key that identifies the data
  2143. * @param data the data object to associate to the key for this Engine instance
  2144. * @return true if no such key were already present and the data was added successfully, false otherwise
  2145. */
  2146. public addExternalData<T>(key: string, data: T): boolean {
  2147. if (!this._externalData) {
  2148. this._externalData = new StringDictionary<Object>();
  2149. }
  2150. return this._externalData.add(key, data);
  2151. }
  2152. /**
  2153. * Get an externaly attached data from its key
  2154. * @param key the unique key that identifies the data
  2155. * @return the associated data, if present (can be null), or undefined if not present
  2156. */
  2157. public getExternalData<T>(key: string): T {
  2158. if (!this._externalData) {
  2159. return null;
  2160. }
  2161. return <T>this._externalData.get(key);
  2162. }
  2163. /**
  2164. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2165. * @param key the unique key that identifies the data
  2166. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2167. * @return the associated data, can be null if the factory returned null.
  2168. */
  2169. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  2170. if (!this._externalData) {
  2171. this._externalData = new StringDictionary<Object>();
  2172. }
  2173. return <T>this._externalData.getOrAddWithFactory(key, factory);
  2174. }
  2175. /**
  2176. * Remove an externaly attached data from the Engine instance
  2177. * @param key the unique key that identifies the data
  2178. * @return true if the data was successfully removed, false if it doesn't exist
  2179. */
  2180. public removeExternalData(key): boolean {
  2181. return this._externalData.remove(key);
  2182. }
  2183. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  2184. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  2185. var material = subMesh.getMaterial();
  2186. if (mesh.showSubMeshesBoundingBox) {
  2187. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  2188. }
  2189. if (material) {
  2190. // Render targets
  2191. if (material.getRenderTargetTextures) {
  2192. if (this._processedMaterials.indexOf(material) === -1) {
  2193. this._processedMaterials.push(material);
  2194. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  2195. }
  2196. }
  2197. // Dispatch
  2198. this._activeIndices.addCount(subMesh.indexCount, false);
  2199. this._renderingManager.dispatch(subMesh);
  2200. }
  2201. }
  2202. }
  2203. public _isInIntermediateRendering(): boolean {
  2204. return this._intermediateRendering
  2205. }
  2206. private _activeMeshesFrozen = false;
  2207. /**
  2208. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  2209. */
  2210. public freezeActiveMeshes(): Scene {
  2211. this._evaluateActiveMeshes();
  2212. this._activeMeshesFrozen = true;
  2213. return this;
  2214. }
  2215. /**
  2216. * Use this function to restart evaluating active meshes on every frame
  2217. */
  2218. public unfreezeActiveMeshes() {
  2219. this._activeMeshesFrozen = false;
  2220. return this;
  2221. }
  2222. private _evaluateActiveMeshes(): void {
  2223. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  2224. return;
  2225. }
  2226. this.activeCamera._activeMeshes.reset();
  2227. this._activeMeshes.reset();
  2228. this._renderingManager.reset();
  2229. this._processedMaterials.reset();
  2230. this._activeParticleSystems.reset();
  2231. this._activeSkeletons.reset();
  2232. this._softwareSkinnedMeshes.reset();
  2233. if (this._boundingBoxRenderer) {
  2234. this._boundingBoxRenderer.reset();
  2235. }
  2236. // Meshes
  2237. var meshes: AbstractMesh[];
  2238. var len: number;
  2239. if (this._selectionOctree) { // Octree
  2240. var selection = this._selectionOctree.select(this._frustumPlanes);
  2241. meshes = selection.data;
  2242. len = selection.length;
  2243. } else { // Full scene traversal
  2244. len = this.meshes.length;
  2245. meshes = this.meshes;
  2246. }
  2247. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  2248. var mesh = meshes[meshIndex];
  2249. if (mesh.isBlocked) {
  2250. continue;
  2251. }
  2252. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  2253. if (!mesh.isReady() || !mesh.isEnabled()) {
  2254. continue;
  2255. }
  2256. mesh.computeWorldMatrix();
  2257. // Intersections
  2258. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  2259. this._meshesForIntersections.pushNoDuplicate(mesh);
  2260. }
  2261. // Switch to current LOD
  2262. var meshLOD = mesh.getLOD(this.activeCamera);
  2263. if (!meshLOD) {
  2264. continue;
  2265. }
  2266. mesh._preActivate();
  2267. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  2268. this._activeMeshes.push(mesh);
  2269. this.activeCamera._activeMeshes.push(mesh);
  2270. mesh._activate(this._renderId);
  2271. if (meshLOD !== mesh) {
  2272. meshLOD._activate(this._renderId);
  2273. }
  2274. this._activeMesh(mesh, meshLOD);
  2275. }
  2276. }
  2277. // Particle systems
  2278. this._particlesDuration.beginMonitoring();
  2279. var beforeParticlesDate = Tools.Now;
  2280. if (this.particlesEnabled) {
  2281. Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  2282. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  2283. var particleSystem = this.particleSystems[particleIndex];
  2284. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  2285. continue;
  2286. }
  2287. let emitter = <any>particleSystem.emitter;
  2288. if (!emitter.position || emitter.isEnabled()) {
  2289. this._activeParticleSystems.push(particleSystem);
  2290. particleSystem.animate();
  2291. this._renderingManager.dispatchParticles(particleSystem);
  2292. }
  2293. }
  2294. Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  2295. }
  2296. this._particlesDuration.endMonitoring(false);
  2297. }
  2298. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  2299. if (mesh.skeleton && this.skeletonsEnabled) {
  2300. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  2301. mesh.skeleton.prepare();
  2302. }
  2303. if (!mesh.computeBonesUsingShaders) {
  2304. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  2305. }
  2306. }
  2307. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  2308. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  2309. }
  2310. if (mesh && mesh.subMeshes) {
  2311. // Submeshes Octrees
  2312. var len: number;
  2313. var subMeshes: SubMesh[];
  2314. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  2315. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  2316. len = intersections.length;
  2317. subMeshes = intersections.data;
  2318. } else {
  2319. subMeshes = mesh.subMeshes;
  2320. len = subMeshes.length;
  2321. }
  2322. for (var subIndex = 0; subIndex < len; subIndex++) {
  2323. var subMesh = subMeshes[subIndex];
  2324. this._evaluateSubMesh(subMesh, mesh);
  2325. }
  2326. }
  2327. }
  2328. public updateTransformMatrix(force?: boolean): void {
  2329. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  2330. }
  2331. public updateAlternateTransformMatrix(alternateCamera: Camera): void {
  2332. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  2333. }
  2334. private _renderForCamera(camera: Camera): void {
  2335. if (camera && camera._skipRendering) {
  2336. return;
  2337. }
  2338. var engine = this._engine;
  2339. var startTime = Tools.Now;
  2340. this.activeCamera = camera;
  2341. if (!this.activeCamera)
  2342. throw new Error("Active camera not set");
  2343. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2344. // Viewport
  2345. engine.setViewport(this.activeCamera.viewport);
  2346. // Camera
  2347. this.resetCachedMaterial();
  2348. this._renderId++;
  2349. this.activeCamera.update();
  2350. this.updateTransformMatrix();
  2351. if (camera._alternateCamera) {
  2352. this.updateAlternateTransformMatrix(camera._alternateCamera);
  2353. this._alternateRendering = true;
  2354. }
  2355. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  2356. // Meshes
  2357. this._evaluateActiveMeshesDuration.beginMonitoring();
  2358. Tools.StartPerformanceCounter("Active meshes evaluation");
  2359. this._evaluateActiveMeshes();
  2360. this._evaluateActiveMeshesDuration.endMonitoring(false);
  2361. Tools.EndPerformanceCounter("Active meshes evaluation");
  2362. // Software skinning
  2363. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  2364. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  2365. mesh.applySkeleton(mesh.skeleton);
  2366. }
  2367. // Render targets
  2368. this._renderTargetsDuration.beginMonitoring();
  2369. var needsRestoreFrameBuffer = false;
  2370. var beforeRenderTargetDate = Tools.Now;
  2371. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  2372. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  2373. }
  2374. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  2375. this._intermediateRendering = true;
  2376. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2377. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  2378. let renderTarget = this._renderTargets.data[renderIndex];
  2379. if (renderTarget._shouldRender()) {
  2380. this._renderId++;
  2381. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  2382. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  2383. }
  2384. }
  2385. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2386. this._intermediateRendering = false;
  2387. this._renderId++;
  2388. needsRestoreFrameBuffer = true; // Restore back buffer
  2389. }
  2390. // Render HighlightLayer Texture
  2391. var stencilState = this._engine.getStencilBuffer();
  2392. var renderhighlights = false;
  2393. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  2394. this._intermediateRendering = true;
  2395. for (let i = 0; i < this.highlightLayers.length; i++) {
  2396. let highlightLayer = this.highlightLayers[i];
  2397. if (highlightLayer.shouldRender() &&
  2398. (!highlightLayer.camera ||
  2399. (highlightLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  2400. (highlightLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  2401. renderhighlights = true;
  2402. let renderTarget = (<RenderTargetTexture>(<any>highlightLayer)._mainTexture);
  2403. if (renderTarget._shouldRender()) {
  2404. this._renderId++;
  2405. renderTarget.render(false, false);
  2406. needsRestoreFrameBuffer = true;
  2407. }
  2408. }
  2409. }
  2410. this._intermediateRendering = false;
  2411. this._renderId++;
  2412. }
  2413. if (needsRestoreFrameBuffer) {
  2414. engine.restoreDefaultFramebuffer(); // Restore back buffer
  2415. }
  2416. this._renderTargetsDuration.endMonitoring(false);
  2417. // Prepare Frame
  2418. this.postProcessManager._prepareFrame();
  2419. this._renderDuration.beginMonitoring();
  2420. // Backgrounds
  2421. var layerIndex;
  2422. var layer;
  2423. if (this.layers.length) {
  2424. engine.setDepthBuffer(false);
  2425. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2426. layer = this.layers[layerIndex];
  2427. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  2428. layer.render();
  2429. }
  2430. }
  2431. engine.setDepthBuffer(true);
  2432. }
  2433. // Render
  2434. Tools.StartPerformanceCounter("Main render");
  2435. // Activate HighlightLayer stencil
  2436. if (renderhighlights) {
  2437. this._engine.setStencilBuffer(true);
  2438. }
  2439. this._renderingManager.render(null, null, true, true);
  2440. // Restore HighlightLayer stencil
  2441. if (renderhighlights) {
  2442. this._engine.setStencilBuffer(stencilState);
  2443. }
  2444. Tools.EndPerformanceCounter("Main render");
  2445. // Bounding boxes
  2446. if (this._boundingBoxRenderer) {
  2447. this._boundingBoxRenderer.render();
  2448. }
  2449. // Lens flares
  2450. if (this.lensFlaresEnabled) {
  2451. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2452. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  2453. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  2454. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  2455. lensFlareSystem.render();
  2456. }
  2457. }
  2458. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2459. }
  2460. // Foregrounds
  2461. if (this.layers.length) {
  2462. engine.setDepthBuffer(false);
  2463. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2464. layer = this.layers[layerIndex];
  2465. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  2466. layer.render();
  2467. }
  2468. }
  2469. engine.setDepthBuffer(true);
  2470. }
  2471. // Highlight Layer
  2472. if (renderhighlights) {
  2473. engine.setDepthBuffer(false);
  2474. for (let i = 0; i < this.highlightLayers.length; i++) {
  2475. if (this.highlightLayers[i].shouldRender()) {
  2476. this.highlightLayers[i].render();
  2477. }
  2478. }
  2479. engine.setDepthBuffer(true);
  2480. }
  2481. this._renderDuration.endMonitoring(false);
  2482. // Finalize frame
  2483. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  2484. // Reset some special arrays
  2485. this._renderTargets.reset();
  2486. this._alternateRendering = false;
  2487. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  2488. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2489. }
  2490. private _processSubCameras(camera: Camera): void {
  2491. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  2492. this._renderForCamera(camera);
  2493. return;
  2494. }
  2495. // Update camera
  2496. this.activeCamera.update();
  2497. // rig cameras
  2498. for (var index = 0; index < camera._rigCameras.length; index++) {
  2499. this._renderForCamera(camera._rigCameras[index]);
  2500. }
  2501. this.activeCamera = camera;
  2502. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  2503. }
  2504. private _checkIntersections(): void {
  2505. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  2506. var sourceMesh = this._meshesForIntersections.data[index];
  2507. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  2508. var action = sourceMesh.actionManager.actions[actionIndex];
  2509. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2510. var parameters = action.getTriggerParameter();
  2511. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  2512. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  2513. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  2514. if (areIntersecting && currentIntersectionInProgress === -1) {
  2515. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  2516. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  2517. sourceMesh._intersectionsInProgress.push(otherMesh);
  2518. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2519. sourceMesh._intersectionsInProgress.push(otherMesh);
  2520. }
  2521. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  2522. //They intersected, and now they don't.
  2523. //is this trigger an exit trigger? execute an event.
  2524. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2525. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  2526. }
  2527. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  2528. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2529. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  2530. }
  2531. }
  2532. }
  2533. }
  2534. }
  2535. }
  2536. public render(): void {
  2537. if (this.isDisposed) {
  2538. return;
  2539. }
  2540. this._interFrameDuration.endMonitoring();
  2541. this._lastFrameDuration.beginMonitoring();
  2542. this._particlesDuration.fetchNewFrame();
  2543. this._spritesDuration.fetchNewFrame();
  2544. this._activeParticles.fetchNewFrame();
  2545. this._renderDuration.fetchNewFrame();
  2546. this._renderTargetsDuration.fetchNewFrame();
  2547. this._evaluateActiveMeshesDuration.fetchNewFrame();
  2548. this._totalVertices.fetchNewFrame();
  2549. this._activeIndices.fetchNewFrame();
  2550. this._activeBones.fetchNewFrame();
  2551. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  2552. this._meshesForIntersections.reset();
  2553. this.resetCachedMaterial();
  2554. Tools.StartPerformanceCounter("Scene rendering");
  2555. // Actions
  2556. if (this.actionManager) {
  2557. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger, null);
  2558. }
  2559. //Simplification Queue
  2560. if (this.simplificationQueue && !this.simplificationQueue.running) {
  2561. this.simplificationQueue.executeNext();
  2562. }
  2563. if(this._engine.isDeterministicLockStep()){
  2564. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  2565. var defaultTimeStep = (60.0 / 1000.0);
  2566. if (this._physicsEngine) {
  2567. defaultTimeStep = this._physicsEngine.getTimeStep();
  2568. }
  2569. var maxSubSteps = this._engine.getLockstepMaxSteps();
  2570. this._timeAccumulator += deltaTime;
  2571. // compute the amount of fixed steps we should have taken since the last step
  2572. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  2573. internalSteps = Math.min(internalSteps, maxSubSteps);
  2574. for(this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++){
  2575. this.onBeforeStepObservable.notifyObservers(this);
  2576. // Animations
  2577. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  2578. this._animate();
  2579. // Physics
  2580. if (this._physicsEngine) {
  2581. Tools.StartPerformanceCounter("Physics");
  2582. this._physicsEngine._step(defaultTimeStep);
  2583. Tools.EndPerformanceCounter("Physics");
  2584. }
  2585. this._timeAccumulator -= defaultTimeStep;
  2586. this.onAfterStepObservable.notifyObservers(this);
  2587. this._currentStepId++;
  2588. if((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  2589. this._evaluateActiveMeshes();
  2590. }
  2591. }
  2592. }
  2593. else {
  2594. // Animations
  2595. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  2596. this._animationRatio = deltaTime * (60.0 / 1000.0);
  2597. this._animate();
  2598. // Physics
  2599. if (this._physicsEngine) {
  2600. Tools.StartPerformanceCounter("Physics");
  2601. this._physicsEngine._step(deltaTime / 1000.0);
  2602. Tools.EndPerformanceCounter("Physics");
  2603. }
  2604. }
  2605. // Before render
  2606. this.onBeforeRenderObservable.notifyObservers(this);
  2607. // Customs render targets
  2608. this._renderTargetsDuration.beginMonitoring();
  2609. var beforeRenderTargetDate = Tools.Now;
  2610. var engine = this.getEngine();
  2611. var currentActiveCamera = this.activeCamera;
  2612. if (this.renderTargetsEnabled) {
  2613. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  2614. this._intermediateRendering = true;
  2615. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  2616. var renderTarget = this.customRenderTargets[customIndex];
  2617. if (renderTarget._shouldRender()) {
  2618. this._renderId++;
  2619. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  2620. if (!this.activeCamera)
  2621. throw new Error("Active camera not set");
  2622. // Viewport
  2623. engine.setViewport(this.activeCamera.viewport);
  2624. // Camera
  2625. this.updateTransformMatrix();
  2626. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  2627. }
  2628. }
  2629. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  2630. this._intermediateRendering = false;
  2631. this._renderId++;
  2632. }
  2633. // Restore back buffer
  2634. if (this.customRenderTargets.length > 0) {
  2635. engine.restoreDefaultFramebuffer();
  2636. }
  2637. this._renderTargetsDuration.endMonitoring();
  2638. this.activeCamera = currentActiveCamera;
  2639. // Procedural textures
  2640. if (this.proceduralTexturesEnabled) {
  2641. Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  2642. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  2643. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  2644. if (proceduralTexture._shouldRender()) {
  2645. proceduralTexture.render();
  2646. }
  2647. }
  2648. Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  2649. }
  2650. // Clear
  2651. if (this.autoClearDepthAndStencil || this.autoClear) {
  2652. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  2653. }
  2654. // Shadows
  2655. if (this.shadowsEnabled) {
  2656. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  2657. var light = this.lights[lightIndex];
  2658. var shadowGenerator = light.getShadowGenerator();
  2659. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  2660. var shadowMap = shadowGenerator.getShadowMap();
  2661. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  2662. this._renderTargets.push(shadowMap);
  2663. }
  2664. }
  2665. }
  2666. }
  2667. // Depth renderer
  2668. if (this._depthRenderer) {
  2669. this._renderTargets.push(this._depthRenderer.getDepthMap());
  2670. }
  2671. // Geometry renderer
  2672. if (this._geometryBufferRenderer) {
  2673. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  2674. }
  2675. // RenderPipeline
  2676. if (this._postProcessRenderPipelineManager) {
  2677. this._postProcessRenderPipelineManager.update();
  2678. }
  2679. // Multi-cameras?
  2680. if (this.activeCameras.length > 0) {
  2681. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  2682. if (cameraIndex > 0) {
  2683. this._engine.clear(null, false, true, true);
  2684. }
  2685. this._processSubCameras(this.activeCameras[cameraIndex]);
  2686. }
  2687. } else {
  2688. if (!this.activeCamera) {
  2689. throw new Error("No camera defined");
  2690. }
  2691. this._processSubCameras(this.activeCamera);
  2692. }
  2693. // Intersection checks
  2694. this._checkIntersections();
  2695. // Update the audio listener attached to the camera
  2696. if (AudioEngine) {
  2697. this._updateAudioParameters();
  2698. }
  2699. // After render
  2700. if (this.afterRender) {
  2701. this.afterRender();
  2702. }
  2703. this.onAfterRenderObservable.notifyObservers(this);
  2704. // Cleaning
  2705. for (var index = 0; index < this._toBeDisposed.length; index++) {
  2706. this._toBeDisposed.data[index].dispose();
  2707. this._toBeDisposed[index] = null;
  2708. }
  2709. this._toBeDisposed.reset();
  2710. if (this.dumpNextRenderTargets) {
  2711. this.dumpNextRenderTargets = false;
  2712. }
  2713. Tools.EndPerformanceCounter("Scene rendering");
  2714. this._interFrameDuration.beginMonitoring();
  2715. this._lastFrameDuration.endMonitoring();
  2716. this._totalMeshesCounter.addCount(this.meshes.length, true);
  2717. this._totalLightsCounter.addCount(this.lights.length, true);
  2718. this._totalMaterialsCounter.addCount(this.materials.length, true);
  2719. this._totalTexturesCounter.addCount(this.textures.length, true);
  2720. this._activeBones.addCount(0, true);
  2721. this._activeIndices.addCount(0, true);
  2722. this._activeParticles.addCount(0, true);
  2723. }
  2724. private _updateAudioParameters() {
  2725. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  2726. return;
  2727. }
  2728. var listeningCamera: Camera;
  2729. var audioEngine = Engine.audioEngine;
  2730. if (this.activeCameras.length > 0) {
  2731. listeningCamera = this.activeCameras[0];
  2732. } else {
  2733. listeningCamera = this.activeCamera;
  2734. }
  2735. if (listeningCamera && audioEngine.canUseWebAudio) {
  2736. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  2737. // for VR cameras
  2738. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  2739. listeningCamera = listeningCamera.rigCameras[0];
  2740. }
  2741. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  2742. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  2743. cameraDirection.normalize();
  2744. // To avoid some errors on GearVR
  2745. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  2746. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  2747. }
  2748. var i: number;
  2749. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2750. var sound = this.mainSoundTrack.soundCollection[i];
  2751. if (sound.useCustomAttenuation) {
  2752. sound.updateDistanceFromListener();
  2753. }
  2754. }
  2755. for (i = 0; i < this.soundTracks.length; i++) {
  2756. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2757. sound = this.soundTracks[i].soundCollection[j];
  2758. if (sound.useCustomAttenuation) {
  2759. sound.updateDistanceFromListener();
  2760. }
  2761. }
  2762. }
  2763. }
  2764. }
  2765. // Audio
  2766. public get audioEnabled(): boolean {
  2767. return this._audioEnabled;
  2768. }
  2769. public set audioEnabled(value: boolean) {
  2770. this._audioEnabled = value;
  2771. if (AudioEngine) {
  2772. if (this._audioEnabled) {
  2773. this._enableAudio();
  2774. }
  2775. else {
  2776. this._disableAudio();
  2777. }
  2778. }
  2779. }
  2780. private _disableAudio() {
  2781. var i: number;
  2782. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2783. this.mainSoundTrack.soundCollection[i].pause();
  2784. }
  2785. for (i = 0; i < this.soundTracks.length; i++) {
  2786. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2787. this.soundTracks[i].soundCollection[j].pause();
  2788. }
  2789. }
  2790. }
  2791. private _enableAudio() {
  2792. var i: number;
  2793. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2794. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  2795. this.mainSoundTrack.soundCollection[i].play();
  2796. }
  2797. }
  2798. for (i = 0; i < this.soundTracks.length; i++) {
  2799. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2800. if (this.soundTracks[i].soundCollection[j].isPaused) {
  2801. this.soundTracks[i].soundCollection[j].play();
  2802. }
  2803. }
  2804. }
  2805. }
  2806. public get headphone(): boolean {
  2807. return this._headphone;
  2808. }
  2809. public set headphone(value: boolean) {
  2810. this._headphone = value;
  2811. if (AudioEngine) {
  2812. if (this._headphone) {
  2813. this._switchAudioModeForHeadphones();
  2814. }
  2815. else {
  2816. this._switchAudioModeForNormalSpeakers();
  2817. }
  2818. }
  2819. }
  2820. private _switchAudioModeForHeadphones() {
  2821. this.mainSoundTrack.switchPanningModelToHRTF();
  2822. for (var i = 0; i < this.soundTracks.length; i++) {
  2823. this.soundTracks[i].switchPanningModelToHRTF();
  2824. }
  2825. }
  2826. private _switchAudioModeForNormalSpeakers() {
  2827. this.mainSoundTrack.switchPanningModelToEqualPower();
  2828. for (var i = 0; i < this.soundTracks.length; i++) {
  2829. this.soundTracks[i].switchPanningModelToEqualPower();
  2830. }
  2831. }
  2832. public enableDepthRenderer(): DepthRenderer {
  2833. if (this._depthRenderer) {
  2834. return this._depthRenderer;
  2835. }
  2836. this._depthRenderer = new DepthRenderer(this);
  2837. return this._depthRenderer;
  2838. }
  2839. public disableDepthRenderer(): void {
  2840. if (!this._depthRenderer) {
  2841. return;
  2842. }
  2843. this._depthRenderer.dispose();
  2844. this._depthRenderer = null;
  2845. }
  2846. public enableGeometryBufferRenderer(ratio: number = 1): GeometryBufferRenderer {
  2847. if (this._geometryBufferRenderer) {
  2848. return this._geometryBufferRenderer;
  2849. }
  2850. this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio);
  2851. if (!this._geometryBufferRenderer.isSupported) {
  2852. this._geometryBufferRenderer = null;
  2853. }
  2854. return this._geometryBufferRenderer;
  2855. }
  2856. public disableGeometryBufferRenderer(): void {
  2857. if (!this._geometryBufferRenderer) {
  2858. return;
  2859. }
  2860. this._geometryBufferRenderer.dispose();
  2861. this._geometryBufferRenderer = null;
  2862. }
  2863. public freezeMaterials(): void {
  2864. for (var i = 0; i < this.materials.length; i++) {
  2865. this.materials[i].freeze();
  2866. }
  2867. }
  2868. public unfreezeMaterials(): void {
  2869. for (var i = 0; i < this.materials.length; i++) {
  2870. this.materials[i].unfreeze();
  2871. }
  2872. }
  2873. public dispose(): void {
  2874. this.beforeRender = null;
  2875. this.afterRender = null;
  2876. this.skeletons = [];
  2877. this.morphTargetManagers = [];
  2878. this.importedMeshesFiles = new Array<string>();
  2879. this.resetCachedMaterial();
  2880. if (this._depthRenderer) {
  2881. this._depthRenderer.dispose();
  2882. }
  2883. if (this._gamepadManager) {
  2884. this._gamepadManager.dispose();
  2885. this._gamepadManager = null;
  2886. }
  2887. // Smart arrays
  2888. if (this.activeCamera) {
  2889. this.activeCamera._activeMeshes.dispose();
  2890. this.activeCamera = null;
  2891. }
  2892. this._activeMeshes.dispose();
  2893. this._renderingManager.dispose();
  2894. this._processedMaterials.dispose();
  2895. this._activeParticleSystems.dispose();
  2896. this._activeSkeletons.dispose();
  2897. this._softwareSkinnedMeshes.dispose();
  2898. this._renderTargets.dispose();
  2899. if (this._boundingBoxRenderer) {
  2900. this._boundingBoxRenderer.dispose();
  2901. }
  2902. this._meshesForIntersections.dispose();
  2903. this._toBeDisposed.dispose();
  2904. // Debug layer
  2905. if (this._debugLayer) {
  2906. this._debugLayer.hide();
  2907. }
  2908. // Events
  2909. this.onDisposeObservable.notifyObservers(this);
  2910. this.onDisposeObservable.clear();
  2911. this.onBeforeRenderObservable.clear();
  2912. this.onAfterRenderObservable.clear();
  2913. this.detachControl();
  2914. // Release sounds & sounds tracks
  2915. if (AudioEngine) {
  2916. this.disposeSounds();
  2917. }
  2918. // VR Helper
  2919. if (this.VRHelper) {
  2920. this.VRHelper.dispose();
  2921. }
  2922. // Detach cameras
  2923. var canvas = this._engine.getRenderingCanvas();
  2924. var index;
  2925. for (index = 0; index < this.cameras.length; index++) {
  2926. this.cameras[index].detachControl(canvas);
  2927. }
  2928. // Release lights
  2929. while (this.lights.length) {
  2930. this.lights[0].dispose();
  2931. }
  2932. // Release meshes
  2933. while (this.meshes.length) {
  2934. this.meshes[0].dispose(true);
  2935. }
  2936. // Release cameras
  2937. while (this.cameras.length) {
  2938. this.cameras[0].dispose();
  2939. }
  2940. // Release materials
  2941. if (this.defaultMaterial) {
  2942. this.defaultMaterial.dispose()
  2943. }
  2944. while (this.multiMaterials.length) {
  2945. this.multiMaterials[0].dispose();
  2946. }
  2947. while (this.materials.length) {
  2948. this.materials[0].dispose();
  2949. }
  2950. // Release particles
  2951. while (this.particleSystems.length) {
  2952. this.particleSystems[0].dispose();
  2953. }
  2954. // Release sprites
  2955. while (this.spriteManagers.length) {
  2956. this.spriteManagers[0].dispose();
  2957. }
  2958. // Release postProcesses
  2959. while (this.postProcesses.length) {
  2960. this.postProcesses[0].dispose();
  2961. }
  2962. // Release layers
  2963. while (this.layers.length) {
  2964. this.layers[0].dispose();
  2965. }
  2966. while (this.highlightLayers.length) {
  2967. this.highlightLayers[0].dispose();
  2968. }
  2969. // Release textures
  2970. while (this.textures.length) {
  2971. this.textures[0].dispose();
  2972. }
  2973. // Release UBO
  2974. this._sceneUbo.dispose();
  2975. if (this._alternateSceneUbo) {
  2976. this._alternateSceneUbo.dispose();
  2977. }
  2978. // Post-processes
  2979. this.postProcessManager.dispose();
  2980. if (this._postProcessRenderPipelineManager) {
  2981. this._postProcessRenderPipelineManager.dispose();
  2982. }
  2983. // Physics
  2984. if (this._physicsEngine) {
  2985. this.disablePhysicsEngine();
  2986. }
  2987. // Remove from engine
  2988. index = this._engine.scenes.indexOf(this);
  2989. if (index > -1) {
  2990. this._engine.scenes.splice(index, 1);
  2991. }
  2992. this._engine.wipeCaches();
  2993. this._engine = null;
  2994. this.defaultMaterial = null;
  2995. this.multiMaterials = null;
  2996. this.materials = null;
  2997. }
  2998. public get isDisposed(): boolean {
  2999. return !this._engine;
  3000. }
  3001. // Release sounds & sounds tracks
  3002. public disposeSounds() {
  3003. this.mainSoundTrack.dispose();
  3004. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  3005. this.soundTracks[scIndex].dispose();
  3006. }
  3007. }
  3008. // Octrees
  3009. public getWorldExtends(): { min: Vector3; max: Vector3 } {
  3010. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3011. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3012. for (var index = 0; index < this.meshes.length; index++) {
  3013. var mesh = this.meshes[index];
  3014. mesh.computeWorldMatrix(true);
  3015. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  3016. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  3017. Tools.CheckExtends(minBox, min, max);
  3018. Tools.CheckExtends(maxBox, min, max);
  3019. }
  3020. return {
  3021. min: min,
  3022. max: max
  3023. };
  3024. }
  3025. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  3026. if (!this._selectionOctree) {
  3027. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  3028. }
  3029. var worldExtends = this.getWorldExtends();
  3030. // Update octree
  3031. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  3032. return this._selectionOctree;
  3033. }
  3034. // Picking
  3035. public createPickingRay(x: number, y: number, world: Matrix, camera: Camera, cameraViewSpace = false): Ray {
  3036. var engine = this._engine;
  3037. if (!camera) {
  3038. if (!this.activeCamera)
  3039. throw new Error("Active camera not set");
  3040. camera = this.activeCamera;
  3041. }
  3042. var cameraViewport = camera.viewport;
  3043. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  3044. // Moving coordinates to local viewport world
  3045. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  3046. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  3047. return Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  3048. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  3049. }
  3050. public createPickingRayInCameraSpace(x: number, y: number, camera: Camera): Ray {
  3051. if (!BABYLON.PickingInfo) {
  3052. return null;
  3053. }
  3054. var engine = this._engine;
  3055. if (!camera) {
  3056. if (!this.activeCamera)
  3057. throw new Error("Active camera not set");
  3058. camera = this.activeCamera;
  3059. }
  3060. var cameraViewport = camera.viewport;
  3061. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  3062. var identity = Matrix.Identity();
  3063. // Moving coordinates to local viewport world
  3064. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  3065. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  3066. return Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  3067. }
  3068. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): PickingInfo {
  3069. if (!BABYLON.PickingInfo) {
  3070. return null;
  3071. }
  3072. var pickingInfo = null;
  3073. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3074. var mesh = this.meshes[meshIndex];
  3075. if (predicate) {
  3076. if (!predicate(mesh)) {
  3077. continue;
  3078. }
  3079. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  3080. continue;
  3081. }
  3082. var world = mesh.getWorldMatrix();
  3083. var ray = rayFunction(world);
  3084. var result = mesh.intersects(ray, fastCheck);
  3085. if (!result || !result.hit)
  3086. continue;
  3087. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  3088. continue;
  3089. pickingInfo = result;
  3090. if (fastCheck) {
  3091. break;
  3092. }
  3093. }
  3094. return pickingInfo || new PickingInfo();
  3095. }
  3096. private _internalMultiPick(rayFunction: (world: Matrix) => Ray, predicate: (mesh: AbstractMesh) => boolean): PickingInfo[] {
  3097. if (!BABYLON.PickingInfo) {
  3098. return null;
  3099. }
  3100. var pickingInfos = new Array<PickingInfo>();
  3101. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3102. var mesh = this.meshes[meshIndex];
  3103. if (predicate) {
  3104. if (!predicate(mesh)) {
  3105. continue;
  3106. }
  3107. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  3108. continue;
  3109. }
  3110. var world = mesh.getWorldMatrix();
  3111. var ray = rayFunction(world);
  3112. var result = mesh.intersects(ray, false);
  3113. if (!result || !result.hit)
  3114. continue;
  3115. pickingInfos.push(result);
  3116. }
  3117. return pickingInfos;
  3118. }
  3119. private _internalPickSprites(ray: Ray, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  3120. if (!BABYLON.PickingInfo) {
  3121. return null;
  3122. }
  3123. var pickingInfo = null;
  3124. camera = camera || this.activeCamera;
  3125. if (this.spriteManagers.length > 0) {
  3126. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  3127. var spriteManager = this.spriteManagers[spriteIndex];
  3128. if (!spriteManager.isPickable) {
  3129. continue;
  3130. }
  3131. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  3132. if (!result || !result.hit)
  3133. continue;
  3134. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  3135. continue;
  3136. pickingInfo = result;
  3137. if (fastCheck) {
  3138. break;
  3139. }
  3140. }
  3141. }
  3142. return pickingInfo || new PickingInfo();
  3143. }
  3144. /** Launch a ray to try to pick a mesh in the scene
  3145. * @param x position on screen
  3146. * @param y position on screen
  3147. * @param 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
  3148. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3149. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3150. */
  3151. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  3152. return this._internalPick(world => this.createPickingRay(x, y, world, camera), predicate, fastCheck);
  3153. }
  3154. /** Launch a ray to try to pick a sprite in the scene
  3155. * @param x position on screen
  3156. * @param y position on screen
  3157. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  3158. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3159. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3160. */
  3161. public pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  3162. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  3163. }
  3164. /** Use the given ray to pick a mesh in the scene
  3165. * @param ray The ray to use to pick meshes
  3166. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  3167. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3168. */
  3169. public pickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean, fastCheck?: boolean): PickingInfo {
  3170. return this._internalPick(world => {
  3171. if (!this._pickWithRayInverseMatrix) {
  3172. this._pickWithRayInverseMatrix = Matrix.Identity();
  3173. }
  3174. world.invertToRef(this._pickWithRayInverseMatrix);
  3175. return Ray.Transform(ray, this._pickWithRayInverseMatrix);
  3176. }, predicate, fastCheck);
  3177. }
  3178. /**
  3179. * Launch a ray to try to pick a mesh in the scene
  3180. * @param x X position on screen
  3181. * @param y Y position on screen
  3182. * @param 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
  3183. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3184. */
  3185. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera): PickingInfo[] {
  3186. return this._internalMultiPick(world => this.createPickingRay(x, y, world, camera), predicate);
  3187. }
  3188. /**
  3189. * Launch a ray to try to pick a mesh in the scene
  3190. * @param ray Ray to use
  3191. * @param 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
  3192. */
  3193. public multiPickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean): PickingInfo[] {
  3194. return this._internalMultiPick(world => {
  3195. if (!this._pickWithRayInverseMatrix) {
  3196. this._pickWithRayInverseMatrix = Matrix.Identity();
  3197. }
  3198. world.invertToRef(this._pickWithRayInverseMatrix);
  3199. return Ray.Transform(ray, this._pickWithRayInverseMatrix);
  3200. }, predicate);
  3201. }
  3202. public setPointerOverMesh(mesh: AbstractMesh): void {
  3203. if (this._pointerOverMesh === mesh) {
  3204. return;
  3205. }
  3206. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  3207. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  3208. }
  3209. this._pointerOverMesh = mesh;
  3210. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  3211. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  3212. }
  3213. }
  3214. public getPointerOverMesh(): AbstractMesh {
  3215. return this._pointerOverMesh;
  3216. }
  3217. public setPointerOverSprite(sprite: Sprite): void {
  3218. if (this._pointerOverSprite === sprite) {
  3219. return;
  3220. }
  3221. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  3222. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  3223. }
  3224. this._pointerOverSprite = sprite;
  3225. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  3226. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  3227. }
  3228. }
  3229. public getPointerOverSprite(): Sprite {
  3230. return this._pointerOverSprite;
  3231. }
  3232. // Physics
  3233. public getPhysicsEngine(): PhysicsEngine {
  3234. return this._physicsEngine;
  3235. }
  3236. /**
  3237. * Enables physics to the current scene
  3238. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  3239. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  3240. * @return {boolean} was the physics engine initialized
  3241. */
  3242. public enablePhysics(gravity?: Vector3, plugin?: IPhysicsEnginePlugin): boolean {
  3243. if (this._physicsEngine) {
  3244. return true;
  3245. }
  3246. try {
  3247. this._physicsEngine = new PhysicsEngine(gravity, plugin);
  3248. return true;
  3249. } catch (e) {
  3250. Tools.Error(e.message);
  3251. return false;
  3252. }
  3253. }
  3254. public disablePhysicsEngine(): void {
  3255. if (!this._physicsEngine) {
  3256. return;
  3257. }
  3258. this._physicsEngine.dispose();
  3259. this._physicsEngine = undefined;
  3260. }
  3261. public isPhysicsEnabled(): boolean {
  3262. return this._physicsEngine !== undefined;
  3263. }
  3264. public deleteCompoundImpostor(compound: any): void {
  3265. var mesh: AbstractMesh = compound.parts[0].mesh;
  3266. mesh.physicsImpostor.dispose(/*true*/);
  3267. mesh.physicsImpostor = null;
  3268. }
  3269. // Misc.
  3270. public _rebuildGeometries(): void {
  3271. for (var geometry of this._geometries) {
  3272. geometry._rebuild();
  3273. }
  3274. for (var mesh of this.meshes) {
  3275. mesh._rebuild();
  3276. }
  3277. if (this.postProcessManager) {
  3278. this.postProcessManager._rebuild();
  3279. }
  3280. for (var layer of this.layers) {
  3281. layer._rebuild();
  3282. }
  3283. for (var highlightLayer of this.highlightLayers) {
  3284. highlightLayer._rebuild();
  3285. }
  3286. if (this._boundingBoxRenderer) {
  3287. this._boundingBoxRenderer._rebuild();
  3288. }
  3289. for (var system of this.particleSystems) {
  3290. system.rebuild();
  3291. }
  3292. if (this._postProcessRenderPipelineManager) {
  3293. this._postProcessRenderPipelineManager._rebuild();
  3294. }
  3295. }
  3296. public _rebuildTextures(): void {
  3297. for (var texture of this.textures) {
  3298. texture._rebuild();
  3299. }
  3300. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  3301. }
  3302. public createDefaultCameraOrLight(createArcRotateCamera = false, replace = false, attachCameraControls = false) {
  3303. // Dispose existing camera or light in replace mode.
  3304. if (replace) {
  3305. if (this.activeCamera) {
  3306. this.activeCamera.dispose();
  3307. this.activeCamera = null;
  3308. }
  3309. if (this.lights) {
  3310. for (var i = 0; i < this.lights.length; i++) {
  3311. this.lights[i].dispose();
  3312. }
  3313. }
  3314. }
  3315. // Light
  3316. if (this.lights.length === 0) {
  3317. new HemisphericLight("default light", Vector3.Up(), this);
  3318. }
  3319. // Camera
  3320. if (!this.activeCamera) {
  3321. var worldExtends = this.getWorldExtends();
  3322. var worldSize = worldExtends.max.subtract(worldExtends.min);
  3323. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  3324. var camera: TargetCamera;
  3325. var radius = worldSize.length() * 1.5;
  3326. if (createArcRotateCamera) {
  3327. var arcRotateCamera = new ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  3328. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  3329. arcRotateCamera.wheelPrecision = 100 / radius;
  3330. camera = arcRotateCamera;
  3331. }
  3332. else {
  3333. var freeCamera = new FreeCamera("default camera", new Vector3(worldCenter.x, worldCenter.y, -radius), this);
  3334. freeCamera.setTarget(worldCenter);
  3335. camera = freeCamera;
  3336. }
  3337. camera.minZ = radius * 0.01;
  3338. camera.maxZ = radius * 100;
  3339. camera.speed = radius * 0.2;
  3340. this.activeCamera = camera;
  3341. if (attachCameraControls) {
  3342. camera.attachControl(this.getEngine().getRenderingCanvas());
  3343. }
  3344. }
  3345. }
  3346. public createDefaultSkybox(environmentTexture?: BaseTexture, pbr = false, scale = 1000, blur = 0): Mesh {
  3347. if (environmentTexture) {
  3348. this.environmentTexture = environmentTexture;
  3349. }
  3350. if (!this.environmentTexture) {
  3351. Tools.Warn("Can not create default skybox without environment texture.");
  3352. return;
  3353. }
  3354. // Skybox
  3355. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  3356. if (pbr) {
  3357. let hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  3358. hdrSkyboxMaterial.backFaceCulling = false;
  3359. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  3360. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  3361. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  3362. hdrSkyboxMaterial.disableLighting = true;
  3363. hdrSkyboxMaterial.twoSidedLighting = true;
  3364. hdrSkybox.infiniteDistance = true;
  3365. hdrSkybox.material = hdrSkyboxMaterial;
  3366. }
  3367. else {
  3368. let skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  3369. skyboxMaterial.backFaceCulling = false;
  3370. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  3371. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  3372. skyboxMaterial.disableLighting = true;
  3373. hdrSkybox.infiniteDistance = true;
  3374. hdrSkybox.material = skyboxMaterial;
  3375. }
  3376. return hdrSkybox;
  3377. }
  3378. public createDefaultVRExperience() {
  3379. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  3380. }
  3381. // Tags
  3382. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  3383. if (tagsQuery === undefined) {
  3384. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  3385. return list;
  3386. }
  3387. var listByTags = [];
  3388. forEach = forEach || ((item: any) => { return; });
  3389. for (var i in list) {
  3390. var item = list[i];
  3391. if (Tags.MatchesQuery(item, tagsQuery)) {
  3392. listByTags.push(item);
  3393. forEach(item);
  3394. }
  3395. }
  3396. return listByTags;
  3397. }
  3398. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  3399. return this._getByTags(this.meshes, tagsQuery, forEach);
  3400. }
  3401. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  3402. return this._getByTags(this.cameras, tagsQuery, forEach);
  3403. }
  3404. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  3405. return this._getByTags(this.lights, tagsQuery, forEach);
  3406. }
  3407. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  3408. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  3409. }
  3410. /**
  3411. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  3412. * This allowed control for front to back rendering or reversly depending of the special needs.
  3413. *
  3414. * @param renderingGroupId The rendering group id corresponding to its index
  3415. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  3416. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  3417. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  3418. */
  3419. public setRenderingOrder(renderingGroupId: number,
  3420. opaqueSortCompareFn: (a: SubMesh, b: SubMesh) => number = null,
  3421. alphaTestSortCompareFn: (a: SubMesh, b: SubMesh) => number = null,
  3422. transparentSortCompareFn: (a: SubMesh, b: SubMesh) => number = null): void {
  3423. this._renderingManager.setRenderingOrder(renderingGroupId,
  3424. opaqueSortCompareFn,
  3425. alphaTestSortCompareFn,
  3426. transparentSortCompareFn);
  3427. }
  3428. /**
  3429. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  3430. *
  3431. * @param renderingGroupId The rendering group id corresponding to its index
  3432. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  3433. * @param depth Automatically clears depth between groups if true and autoClear is true.
  3434. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  3435. */
  3436. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  3437. depth = true,
  3438. stencil = true): void {
  3439. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  3440. }
  3441. /**
  3442. * Will flag all materials as dirty to trigger new shader compilation
  3443. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  3444. */
  3445. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  3446. for (var material of this.materials) {
  3447. if (predicate && !predicate(material)) {
  3448. continue;
  3449. }
  3450. material.markAsDirty(flag);
  3451. }
  3452. }
  3453. }
  3454. }