babylon.scene.ts 211 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277
  1. module BABYLON {
  2. /**
  3. * Define an interface for all classes that will hold resources
  4. */
  5. export interface IDisposable {
  6. /**
  7. * Releases all held resources
  8. */
  9. dispose(): void;
  10. }
  11. /** @hidden */
  12. class ClickInfo {
  13. private _singleClick = false;
  14. private _doubleClick = false;
  15. private _hasSwiped = false;
  16. private _ignore = false;
  17. public get singleClick(): boolean {
  18. return this._singleClick;
  19. }
  20. public get doubleClick(): boolean {
  21. return this._doubleClick;
  22. }
  23. public get hasSwiped(): boolean {
  24. return this._hasSwiped;
  25. }
  26. public get ignore(): boolean {
  27. return this._ignore;
  28. }
  29. public set singleClick(b: boolean) {
  30. this._singleClick = b;
  31. }
  32. public set doubleClick(b: boolean) {
  33. this._doubleClick = b;
  34. }
  35. public set hasSwiped(b: boolean) {
  36. this._hasSwiped = b;
  37. }
  38. public set ignore(b: boolean) {
  39. this._ignore = b;
  40. }
  41. }
  42. /**
  43. * This class is used by the onRenderingGroupObservable
  44. */
  45. export class RenderingGroupInfo {
  46. /**
  47. * The Scene that being rendered
  48. */
  49. scene: Scene;
  50. /**
  51. * The camera currently used for the rendering pass
  52. */
  53. camera: Nullable<Camera>;
  54. /**
  55. * The ID of the renderingGroup being processed
  56. */
  57. renderingGroupId: number;
  58. }
  59. /**
  60. * Represents a scene to be rendered by the engine.
  61. * @see http://doc.babylonjs.com/features/scene
  62. */
  63. export class Scene extends AbstractScene implements IAnimatable {
  64. // Statics
  65. private static _uniqueIdCounter = 0;
  66. /** The fog is deactivated */
  67. public static readonly FOGMODE_NONE = 0;
  68. /** The fog density is following an exponential function */
  69. public static readonly FOGMODE_EXP = 1;
  70. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  71. public static readonly FOGMODE_EXP2 = 2;
  72. /** The fog density is following a linear function. */
  73. public static readonly FOGMODE_LINEAR = 3;
  74. /**
  75. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  76. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  77. */
  78. public static MinDeltaTime = 1.0;
  79. /**
  80. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  81. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  82. */
  83. public static MaxDeltaTime = 1000.0;
  84. // Members
  85. /**
  86. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  87. */
  88. public autoClear = true;
  89. /**
  90. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  91. */
  92. public autoClearDepthAndStencil = true;
  93. /**
  94. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  95. */
  96. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  97. /**
  98. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  99. */
  100. public ambientColor = new Color3(0, 0, 0);
  101. /** @hidden */
  102. public _environmentBRDFTexture: BaseTexture;
  103. /** @hidden */
  104. protected _environmentTexture: BaseTexture;
  105. /**
  106. * Texture used in all pbr material as the reflection texture.
  107. * As in the majority of the scene they are the same (exception for multi room and so on),
  108. * this is easier to reference from here than from all the materials.
  109. */
  110. public get environmentTexture(): BaseTexture {
  111. return this._environmentTexture;
  112. }
  113. /**
  114. * Texture used in all pbr material as the reflection texture.
  115. * As in the majority of the scene they are the same (exception for multi room and so on),
  116. * this is easier to set here than in all the materials.
  117. */
  118. public set environmentTexture(value: BaseTexture) {
  119. if (this._environmentTexture === value) {
  120. return;
  121. }
  122. this._environmentTexture = value;
  123. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  124. }
  125. /** @hidden */
  126. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  127. /**
  128. * Default image processing configuration used either in the rendering
  129. * Forward main pass or through the imageProcessingPostProcess if present.
  130. * As in the majority of the scene they are the same (exception for multi camera),
  131. * this is easier to reference from here than from all the materials and post process.
  132. *
  133. * No setter as we it is a shared configuration, you can set the values instead.
  134. */
  135. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  136. return this._imageProcessingConfiguration;
  137. }
  138. private _forceWireframe = false;
  139. /**
  140. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  141. */
  142. public set forceWireframe(value: boolean) {
  143. if (this._forceWireframe === value) {
  144. return;
  145. }
  146. this._forceWireframe = value;
  147. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  148. }
  149. public get forceWireframe(): boolean {
  150. return this._forceWireframe;
  151. }
  152. private _forcePointsCloud = false;
  153. /**
  154. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  155. */
  156. public set forcePointsCloud(value: boolean) {
  157. if (this._forcePointsCloud === value) {
  158. return;
  159. }
  160. this._forcePointsCloud = value;
  161. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  162. }
  163. public get forcePointsCloud(): boolean {
  164. return this._forcePointsCloud;
  165. }
  166. /**
  167. * Gets or sets the active clipplane 1
  168. */
  169. public clipPlane: Nullable<Plane>;
  170. /**
  171. * Gets or sets the active clipplane 2
  172. */
  173. public clipPlane2: Nullable<Plane>;
  174. /**
  175. * Gets or sets the active clipplane 3
  176. */
  177. public clipPlane3: Nullable<Plane>;
  178. /**
  179. * Gets or sets the active clipplane 4
  180. */
  181. public clipPlane4: Nullable<Plane>;
  182. /**
  183. * Gets or sets a boolean indicating if animations are enabled
  184. */
  185. public animationsEnabled = true;
  186. private _animationPropertiesOverride: Nullable<AnimationPropertiesOverride> = null;
  187. /**
  188. * Gets or sets the animation properties override
  189. */
  190. public get animationPropertiesOverride(): Nullable<AnimationPropertiesOverride> {
  191. return this._animationPropertiesOverride;
  192. }
  193. public set animationPropertiesOverride(value: Nullable<AnimationPropertiesOverride>) {
  194. this._animationPropertiesOverride = value;
  195. }
  196. /**
  197. * Gets or sets a boolean indicating if a constant deltatime has to be used
  198. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  199. */
  200. public useConstantAnimationDeltaTime = false;
  201. /**
  202. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  203. * Please note that it requires to run a ray cast through the scene on every frame
  204. */
  205. public constantlyUpdateMeshUnderPointer = false;
  206. /**
  207. * Defines the HTML cursor to use when hovering over interactive elements
  208. */
  209. public hoverCursor = "pointer";
  210. /**
  211. * Defines the HTML default cursor to use (empty by default)
  212. */
  213. public defaultCursor: string = "";
  214. /**
  215. * This is used to call preventDefault() on pointer down
  216. * in order to block unwanted artifacts like system double clicks
  217. */
  218. public preventDefaultOnPointerDown = true;
  219. // Metadata
  220. /**
  221. * Gets or sets user defined metadata
  222. */
  223. public metadata: any = null;
  224. /**
  225. * Gets the name of the plugin used to load this scene (null by default)
  226. */
  227. public loadingPluginName: string;
  228. /**
  229. * Use this array to add regular expressions used to disable offline support for specific urls
  230. */
  231. public disableOfflineSupportExceptionRules = new Array<RegExp>();
  232. /**
  233. * An event triggered when the scene is disposed.
  234. */
  235. public onDisposeObservable = new Observable<Scene>();
  236. private _onDisposeObserver: Nullable<Observer<Scene>> = null;
  237. /** Sets a function to be executed when this scene is disposed. */
  238. public set onDispose(callback: () => void) {
  239. if (this._onDisposeObserver) {
  240. this.onDisposeObservable.remove(this._onDisposeObserver);
  241. }
  242. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  243. }
  244. /**
  245. * An event triggered before rendering the scene (right after animations and physics)
  246. */
  247. public onBeforeRenderObservable = new Observable<Scene>();
  248. private _onBeforeRenderObserver: Nullable<Observer<Scene>> = null;
  249. /** Sets a function to be executed before rendering this scene */
  250. public set beforeRender(callback: Nullable<() => void>) {
  251. if (this._onBeforeRenderObserver) {
  252. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  253. }
  254. if (callback) {
  255. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  256. }
  257. }
  258. /**
  259. * An event triggered after rendering the scene
  260. */
  261. public onAfterRenderObservable = new Observable<Scene>();
  262. private _onAfterRenderObserver: Nullable<Observer<Scene>> = null;
  263. /** Sets a function to be executed after rendering this scene */
  264. public set afterRender(callback: Nullable<() => void>) {
  265. if (this._onAfterRenderObserver) {
  266. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  267. }
  268. if (callback) {
  269. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  270. }
  271. }
  272. /**
  273. * An event triggered before animating the scene
  274. */
  275. public onBeforeAnimationsObservable = new Observable<Scene>();
  276. /**
  277. * An event triggered after animations processing
  278. */
  279. public onAfterAnimationsObservable = new Observable<Scene>();
  280. /**
  281. * An event triggered before draw calls are ready to be sent
  282. */
  283. public onBeforeDrawPhaseObservable = new Observable<Scene>();
  284. /**
  285. * An event triggered after draw calls have been sent
  286. */
  287. public onAfterDrawPhaseObservable = new Observable<Scene>();
  288. /**
  289. * An event triggered when the scene is ready
  290. */
  291. public onReadyObservable = new Observable<Scene>();
  292. /**
  293. * An event triggered before rendering a camera
  294. */
  295. public onBeforeCameraRenderObservable = new Observable<Camera>();
  296. private _onBeforeCameraRenderObserver: Nullable<Observer<Camera>> = null;
  297. /** Sets a function to be executed before rendering a camera*/
  298. public set beforeCameraRender(callback: () => void) {
  299. if (this._onBeforeCameraRenderObserver) {
  300. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  301. }
  302. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  303. }
  304. /**
  305. * An event triggered after rendering a camera
  306. */
  307. public onAfterCameraRenderObservable = new Observable<Camera>();
  308. private _onAfterCameraRenderObserver: Nullable<Observer<Camera>> = null;
  309. /** Sets a function to be executed after rendering a camera*/
  310. public set afterCameraRender(callback: () => void) {
  311. if (this._onAfterCameraRenderObserver) {
  312. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  313. }
  314. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  315. }
  316. /**
  317. * An event triggered when active meshes evaluation is about to start
  318. */
  319. public onBeforeActiveMeshesEvaluationObservable = new Observable<Scene>();
  320. /**
  321. * An event triggered when active meshes evaluation is done
  322. */
  323. public onAfterActiveMeshesEvaluationObservable = new Observable<Scene>();
  324. /**
  325. * An event triggered when particles rendering is about to start
  326. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  327. */
  328. public onBeforeParticlesRenderingObservable = new Observable<Scene>();
  329. /**
  330. * An event triggered when particles rendering is done
  331. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  332. */
  333. public onAfterParticlesRenderingObservable = new Observable<Scene>();
  334. /**
  335. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  336. */
  337. public onDataLoadedObservable = new Observable<Scene>();
  338. /**
  339. * An event triggered when a camera is created
  340. */
  341. public onNewCameraAddedObservable = new Observable<Camera>();
  342. /**
  343. * An event triggered when a camera is removed
  344. */
  345. public onCameraRemovedObservable = new Observable<Camera>();
  346. /**
  347. * An event triggered when a light is created
  348. */
  349. public onNewLightAddedObservable = new Observable<Light>();
  350. /**
  351. * An event triggered when a light is removed
  352. */
  353. public onLightRemovedObservable = new Observable<Light>();
  354. /**
  355. * An event triggered when a geometry is created
  356. */
  357. public onNewGeometryAddedObservable = new Observable<Geometry>();
  358. /**
  359. * An event triggered when a geometry is removed
  360. */
  361. public onGeometryRemovedObservable = new Observable<Geometry>();
  362. /**
  363. * An event triggered when a transform node is created
  364. */
  365. public onNewTransformNodeAddedObservable = new Observable<TransformNode>();
  366. /**
  367. * An event triggered when a transform node is removed
  368. */
  369. public onTransformNodeRemovedObservable = new Observable<TransformNode>();
  370. /**
  371. * An event triggered when a mesh is created
  372. */
  373. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  374. /**
  375. * An event triggered when a mesh is removed
  376. */
  377. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  378. /**
  379. * An event triggered when render targets are about to be rendered
  380. * Can happen multiple times per frame.
  381. */
  382. public onBeforeRenderTargetsRenderObservable = new Observable<Scene>();
  383. /**
  384. * An event triggered when render targets were rendered.
  385. * Can happen multiple times per frame.
  386. */
  387. public onAfterRenderTargetsRenderObservable = new Observable<Scene>();
  388. /**
  389. * An event triggered before calculating deterministic simulation step
  390. */
  391. public onBeforeStepObservable = new Observable<Scene>();
  392. /**
  393. * An event triggered after calculating deterministic simulation step
  394. */
  395. public onAfterStepObservable = new Observable<Scene>();
  396. /**
  397. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  398. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  399. * 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)
  400. */
  401. public onBeforeRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  402. /**
  403. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  404. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  405. * 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)
  406. */
  407. public onAfterRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  408. /**
  409. * This Observable will when a mesh has been imported into the scene.
  410. */
  411. public onMeshImportedObservable = new Observable<AbstractMesh>();
  412. // Animations
  413. private _registeredForLateAnimationBindings = new SmartArrayNoDuplicate<any>(256);
  414. // Pointers
  415. /**
  416. * Gets or sets a predicate used to select candidate meshes for a pointer down event
  417. */
  418. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  419. /**
  420. * Gets or sets a predicate used to select candidate meshes for a pointer up event
  421. */
  422. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  423. /**
  424. * Gets or sets a predicate used to select candidate meshes for a pointer move event
  425. */
  426. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  427. private _onPointerMove: (evt: PointerEvent) => void;
  428. private _onPointerDown: (evt: PointerEvent) => void;
  429. private _onPointerUp: (evt: PointerEvent) => void;
  430. /** Deprecated. Use onPointerObservable instead */
  431. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  432. /** Deprecated. Use onPointerObservable instead */
  433. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  434. /** Deprecated. Use onPointerObservable instead */
  435. public onPointerUp: (evt: PointerEvent, pickInfo: Nullable<PickingInfo>, type: PointerEventTypes) => void;
  436. /** Deprecated. Use onPointerObservable instead */
  437. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  438. /**
  439. * 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).
  440. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  441. */
  442. public onPrePointerObservable = new Observable<PointerInfoPre>();
  443. /**
  444. * Observable event triggered each time an input event is received from the rendering canvas
  445. */
  446. public onPointerObservable = new Observable<PointerInfo>();
  447. /**
  448. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  449. */
  450. public get unTranslatedPointer(): Vector2 {
  451. return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  452. }
  453. /** The distance in pixel that you have to move to prevent some events */
  454. public static DragMovementThreshold = 10; // in pixels
  455. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  456. public static LongPressDelay = 500; // in milliseconds
  457. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  458. public static DoubleClickDelay = 300; // in milliseconds
  459. /** If you need to check double click without raising a single click at first click, enable this flag */
  460. public static ExclusiveDoubleClickMode = false;
  461. private _initClickEvent: (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  462. private _initActionManager: (act: Nullable<ActionManager>, clickInfo: ClickInfo) => Nullable<ActionManager>;
  463. private _delayedSimpleClick: (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  464. private _delayedSimpleClickTimeout: number;
  465. private _previousDelayedSimpleClickTimeout: number;
  466. private _meshPickProceed = false;
  467. private _previousButtonPressed: number;
  468. private _currentPickResult: Nullable<PickingInfo> = null;
  469. private _previousPickResult: Nullable<PickingInfo> = null;
  470. private _totalPointersPressed = 0;
  471. private _doubleClickOccured = false;
  472. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  473. public cameraToUseForPointers: Nullable<Camera> = null;
  474. private _pointerX: number = 0;
  475. private _pointerY: number = 0;
  476. private _unTranslatedPointerX: number;
  477. private _unTranslatedPointerY: number;
  478. private _startingPointerPosition = new Vector2(0, 0);
  479. private _previousStartingPointerPosition = new Vector2(0, 0);
  480. private _startingPointerTime = 0;
  481. private _previousStartingPointerTime = 0;
  482. private _pointerCaptures: { [pointerId: number]: boolean } = {};
  483. // Deterministic lockstep
  484. private _timeAccumulator: number = 0;
  485. private _currentStepId: number = 0;
  486. private _currentInternalStep: number = 0;
  487. // Mirror
  488. /** @hidden */
  489. public _mirroredCameraPosition: Nullable<Vector3>;
  490. // Keyboard
  491. /**
  492. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  493. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  494. */
  495. public onPreKeyboardObservable = new Observable<KeyboardInfoPre>();
  496. /**
  497. * Observable event triggered each time an keyboard event is received from the hosting window
  498. */
  499. public onKeyboardObservable = new Observable<KeyboardInfo>();
  500. private _onKeyDown: (evt: KeyboardEvent) => void;
  501. private _onKeyUp: (evt: KeyboardEvent) => void;
  502. private _onCanvasFocusObserver: Nullable<Observer<Engine>>;
  503. private _onCanvasBlurObserver: Nullable<Observer<Engine>>;
  504. // Coordinates system
  505. private _useRightHandedSystem = false;
  506. /**
  507. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  508. */
  509. public set useRightHandedSystem(value: boolean) {
  510. if (this._useRightHandedSystem === value) {
  511. return;
  512. }
  513. this._useRightHandedSystem = value;
  514. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  515. }
  516. public get useRightHandedSystem(): boolean {
  517. return this._useRightHandedSystem;
  518. }
  519. /**
  520. * Sets the step Id used by deterministic lock step
  521. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  522. * @param newStepId defines the step Id
  523. */
  524. public setStepId(newStepId: number): void {
  525. this._currentStepId = newStepId;
  526. };
  527. /**
  528. * Gets the step Id used by deterministic lock step
  529. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  530. * @returns the step Id
  531. */
  532. public getStepId(): number {
  533. return this._currentStepId;
  534. };
  535. /**
  536. * Gets the internal step used by deterministic lock step
  537. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  538. * @returns the internal step
  539. */
  540. public getInternalStep(): number {
  541. return this._currentInternalStep;
  542. };
  543. // Fog
  544. private _fogEnabled = true;
  545. /**
  546. * Gets or sets a boolean indicating if fog is enabled on this scene
  547. * @see http://doc.babylonjs.com/babylon101/environment#fog
  548. */
  549. public set fogEnabled(value: boolean) {
  550. if (this._fogEnabled === value) {
  551. return;
  552. }
  553. this._fogEnabled = value;
  554. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  555. }
  556. public get fogEnabled(): boolean {
  557. return this._fogEnabled;
  558. }
  559. private _fogMode = Scene.FOGMODE_NONE;
  560. /**
  561. * Gets or sets the fog mode to use
  562. * @see http://doc.babylonjs.com/babylon101/environment#fog
  563. */
  564. public set fogMode(value: number) {
  565. if (this._fogMode === value) {
  566. return;
  567. }
  568. this._fogMode = value;
  569. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  570. }
  571. public get fogMode(): number {
  572. return this._fogMode;
  573. }
  574. /**
  575. * Gets or sets the fog color to use
  576. * @see http://doc.babylonjs.com/babylon101/environment#fog
  577. */
  578. public fogColor = new Color3(0.2, 0.2, 0.3);
  579. /**
  580. * Gets or sets the fog density to use
  581. * @see http://doc.babylonjs.com/babylon101/environment#fog
  582. */
  583. public fogDensity = 0.1;
  584. /**
  585. * Gets or sets the fog start distance to use
  586. * @see http://doc.babylonjs.com/babylon101/environment#fog
  587. */
  588. public fogStart = 0;
  589. /**
  590. * Gets or sets the fog end distance to use
  591. * @see http://doc.babylonjs.com/babylon101/environment#fog
  592. */
  593. public fogEnd = 1000.0;
  594. // Lights
  595. private _shadowsEnabled = true;
  596. /**
  597. * Gets or sets a boolean indicating if shadows are enabled on this scene
  598. */
  599. public set shadowsEnabled(value: boolean) {
  600. if (this._shadowsEnabled === value) {
  601. return;
  602. }
  603. this._shadowsEnabled = value;
  604. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  605. }
  606. public get shadowsEnabled(): boolean {
  607. return this._shadowsEnabled;
  608. }
  609. private _lightsEnabled = true;
  610. /**
  611. * Gets or sets a boolean indicating if lights are enabled on this scene
  612. */
  613. public set lightsEnabled(value: boolean) {
  614. if (this._lightsEnabled === value) {
  615. return;
  616. }
  617. this._lightsEnabled = value;
  618. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  619. }
  620. public get lightsEnabled(): boolean {
  621. return this._lightsEnabled;
  622. }
  623. /** All of the active cameras added to this scene. */
  624. public activeCameras = new Array<Camera>();
  625. /** The current active camera */
  626. public activeCamera: Nullable<Camera>;
  627. private _defaultMaterial: Material;
  628. /** The default material used on meshes when no material is affected */
  629. public get defaultMaterial(): Material {
  630. if (!this._defaultMaterial) {
  631. this._defaultMaterial = new StandardMaterial("default material", this);
  632. }
  633. return this._defaultMaterial;
  634. }
  635. /** The default material used on meshes when no material is affected */
  636. public set defaultMaterial(value: Material) {
  637. this._defaultMaterial = value;
  638. }
  639. // Textures
  640. private _texturesEnabled = true;
  641. /**
  642. * Gets or sets a boolean indicating if textures are enabled on this scene
  643. */
  644. public set texturesEnabled(value: boolean) {
  645. if (this._texturesEnabled === value) {
  646. return;
  647. }
  648. this._texturesEnabled = value;
  649. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  650. }
  651. public get texturesEnabled(): boolean {
  652. return this._texturesEnabled;
  653. }
  654. // Particles
  655. /**
  656. * Gets or sets a boolean indicating if particles are enabled on this scene
  657. */
  658. public particlesEnabled = true;
  659. // Sprites
  660. /**
  661. * Gets or sets a boolean indicating if sprites are enabled on this scene
  662. */
  663. public spritesEnabled = true;
  664. // Skeletons
  665. private _skeletonsEnabled = true;
  666. /**
  667. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  668. */
  669. public set skeletonsEnabled(value: boolean) {
  670. if (this._skeletonsEnabled === value) {
  671. return;
  672. }
  673. this._skeletonsEnabled = value;
  674. this.markAllMaterialsAsDirty(Material.AttributesDirtyFlag);
  675. }
  676. public get skeletonsEnabled(): boolean {
  677. return this._skeletonsEnabled;
  678. }
  679. // Lens flares
  680. /**
  681. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  682. */
  683. public lensFlaresEnabled = true;
  684. // Collisions
  685. /**
  686. * Gets or sets a boolean indicating if collisions are enabled on this scene
  687. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  688. */
  689. public collisionsEnabled = true;
  690. private _workerCollisions: boolean;
  691. /** @hidden */
  692. public collisionCoordinator: ICollisionCoordinator;
  693. /**
  694. * Defines the gravity applied to this scene (used only for collisions)
  695. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  696. */
  697. public gravity = new Vector3(0, -9.807, 0);
  698. // Postprocesses
  699. /**
  700. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  701. */
  702. public postProcessesEnabled = true;
  703. /**
  704. * The list of postprocesses added to the scene
  705. */
  706. public postProcesses = new Array<PostProcess>();
  707. /**
  708. * Gets the current postprocess manager
  709. */
  710. public postProcessManager: PostProcessManager;
  711. // Customs render targets
  712. /**
  713. * Gets or sets a boolean indicating if render targets are enabled on this scene
  714. */
  715. public renderTargetsEnabled = true;
  716. /**
  717. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  718. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  719. */
  720. public dumpNextRenderTargets = false;
  721. /**
  722. * The list of user defined render targets added to the scene
  723. */
  724. public customRenderTargets = new Array<RenderTargetTexture>();
  725. /**
  726. * Defines if texture loading must be delayed
  727. * If true, textures will only be loaded when they need to be rendered
  728. */
  729. public useDelayedTextureLoading: boolean;
  730. /**
  731. * Gets the list of meshes imported to the scene through SceneLoader
  732. */
  733. public importedMeshesFiles = new Array<String>();
  734. // Probes
  735. /**
  736. * Gets or sets a boolean indicating if probes are enabled on this scene
  737. */
  738. public probesEnabled = true;
  739. // Database
  740. /**
  741. * @hidden
  742. */
  743. public database: Database;
  744. /**
  745. * Gets or sets the action manager associated with the scene
  746. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  747. */
  748. public actionManager: ActionManager;
  749. private _meshesForIntersections = new SmartArrayNoDuplicate<AbstractMesh>(256);
  750. // Procedural textures
  751. /**
  752. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  753. */
  754. public proceduralTexturesEnabled = true;
  755. // Private
  756. private _engine: Engine;
  757. // Performance counters
  758. private _totalVertices = new PerfCounter();
  759. /** @hidden */
  760. public _activeIndices = new PerfCounter();
  761. /** @hidden */
  762. public _activeParticles = new PerfCounter();
  763. /** @hidden */
  764. public _activeBones = new PerfCounter();
  765. private _animationRatio: number;
  766. private _animationTimeLast: number;
  767. private _animationTime: number = 0;
  768. /**
  769. * Gets or sets a general scale for animation speed
  770. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  771. */
  772. public animationTimeScale: number = 1;
  773. /** @hidden */
  774. public _cachedMaterial: Nullable<Material>;
  775. /** @hidden */
  776. public _cachedEffect: Nullable<Effect>;
  777. /** @hidden */
  778. public _cachedVisibility: Nullable<number>;
  779. private _renderId = 0;
  780. private _frameId = 0;
  781. private _executeWhenReadyTimeoutId = -1;
  782. private _intermediateRendering = false;
  783. private _viewUpdateFlag = -1;
  784. private _projectionUpdateFlag = -1;
  785. private _alternateViewUpdateFlag = -1;
  786. private _alternateProjectionUpdateFlag = -1;
  787. /** @hidden */
  788. public _toBeDisposed = new Array<Nullable<IDisposable>>(256);
  789. private _activeRequests = new Array<IFileRequest>();
  790. private _pendingData = new Array();
  791. private _isDisposed = false;
  792. /**
  793. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  794. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  795. */
  796. public dispatchAllSubMeshesOfActiveMeshes: boolean = false;
  797. private _activeMeshes = new SmartArray<AbstractMesh>(256);
  798. private _processedMaterials = new SmartArray<Material>(256);
  799. private _renderTargets = new SmartArrayNoDuplicate<RenderTargetTexture>(256);
  800. /** @hidden */
  801. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  802. private _activeSkeletons = new SmartArrayNoDuplicate<Skeleton>(32);
  803. private _softwareSkinnedMeshes = new SmartArrayNoDuplicate<Mesh>(32);
  804. private _renderingManager: RenderingManager;
  805. /** @hidden */
  806. public _activeAnimatables = new Array<Animatable>();
  807. private _transformMatrix = Matrix.Zero();
  808. private _sceneUbo: UniformBuffer;
  809. private _alternateSceneUbo: UniformBuffer;
  810. private _pickWithRayInverseMatrix: Matrix;
  811. private _viewMatrix: Matrix;
  812. private _projectionMatrix: Matrix;
  813. private _alternateViewMatrix: Matrix;
  814. private _alternateProjectionMatrix: Matrix;
  815. private _alternateTransformMatrix: Matrix;
  816. private _useAlternateCameraConfiguration = false;
  817. private _alternateRendering = false;
  818. /** @hidden */
  819. public _forcedViewPosition: Nullable<Vector3>;
  820. /** @hidden */
  821. public get _isAlternateRenderingEnabled(): boolean {
  822. return this._alternateRendering;
  823. }
  824. private _frustumPlanes: Plane[];
  825. /**
  826. * Gets the list of frustum planes (built from the active camera)
  827. */
  828. public get frustumPlanes(): Plane[] {
  829. return this._frustumPlanes;
  830. }
  831. /**
  832. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  833. * This is useful if there are more lights that the maximum simulteanous authorized
  834. */
  835. public requireLightSorting = false;
  836. private _pointerOverMesh: Nullable<AbstractMesh>;
  837. private _pickedDownMesh: Nullable<AbstractMesh>;
  838. private _pickedUpMesh: Nullable<AbstractMesh>;
  839. private _externalData: StringDictionary<Object>;
  840. private _uid: Nullable<string>;
  841. /**
  842. * @hidden
  843. * Backing store of defined scene components.
  844. */
  845. public _components: ISceneComponent[] = [];
  846. /**
  847. * @hidden
  848. * Backing store of defined scene components.
  849. */
  850. public _serializableComponents: ISceneSerializableComponent[] = [];
  851. /**
  852. * List of components to register on the next registration step.
  853. */
  854. private _transientComponents: ISceneComponent[] = [];
  855. /**
  856. * Registers the transient components if needed.
  857. */
  858. private _registerTransientComponents(): void {
  859. // Register components that have been associated lately to the scene.
  860. if (this._transientComponents.length > 0) {
  861. for (let component of this._transientComponents) {
  862. component.register();
  863. }
  864. this._transientComponents = [];
  865. }
  866. }
  867. /**
  868. * @hidden
  869. * Add a component to the scene.
  870. * Note that the ccomponent could be registered on th next frame if this is called after
  871. * the register component stage.
  872. * @param component Defines the component to add to the scene
  873. */
  874. public _addComponent(component: ISceneComponent) {
  875. this._components.push(component);
  876. this._transientComponents.push(component);
  877. const serializableComponent = component as ISceneSerializableComponent;
  878. if (serializableComponent.addFromContainer) {
  879. this._serializableComponents.push(serializableComponent);
  880. }
  881. }
  882. /**
  883. * @hidden
  884. * Gets a component from the scene.
  885. * @param name defines the name of the component to retrieve
  886. * @returns the component or null if not present
  887. */
  888. public _getComponent(name: string): Nullable<ISceneComponent> {
  889. for (let component of this._components) {
  890. if (component.name === name) {
  891. return component;
  892. }
  893. }
  894. return null;
  895. }
  896. /**
  897. * @hidden
  898. * Defines the actions happening before camera updates.
  899. */
  900. public _beforeCameraUpdateStage = Stage.Create<SimpleStageAction>();
  901. /**
  902. * @hidden
  903. * Defines the actions happening before clear the canvas.
  904. */
  905. public _beforeClearStage = Stage.Create<SimpleStageAction>();
  906. /**
  907. * @hidden
  908. * Defines the actions when collecting render targets for the frame.
  909. */
  910. public _gatherRenderTargetsStage = Stage.Create<RenderTargetsStageAction>();
  911. /**
  912. * @hidden
  913. * Defines the actions happening for one camera in the frame.
  914. */
  915. public _gatherActiveCameraRenderTargetsStage = Stage.Create<RenderTargetsStageAction>();
  916. /**
  917. * @hidden
  918. * Defines the actions happening during the per mesh ready checks.
  919. */
  920. public _isReadyForMeshStage = Stage.Create<MeshStageAction>();
  921. /**
  922. * @hidden
  923. * Defines the actions happening before evaluate active mesh checks.
  924. */
  925. public _beforeEvaluateActiveMeshStage = Stage.Create<SimpleStageAction>();
  926. /**
  927. * @hidden
  928. * Defines the actions happening during the evaluate sub mesh checks.
  929. */
  930. public _evaluateSubMeshStage = Stage.Create<EvaluateSubMeshStageAction>();
  931. /**
  932. * @hidden
  933. * Defines the actions happening during the active mesh stage.
  934. */
  935. public _activeMeshStage = Stage.Create<ActiveMeshStageAction>();
  936. /**
  937. * @hidden
  938. * Defines the actions happening during the per camera render target step.
  939. */
  940. public _cameraDrawRenderTargetStage = Stage.Create<CameraStageAction>();
  941. /**
  942. * @hidden
  943. * Defines the actions happening just before the active camera is drawing.
  944. */
  945. public _beforeCameraDrawStage = Stage.Create<CameraStageAction>();
  946. /**
  947. * @hidden
  948. * Defines the actions happening just before a rendering group is drawing.
  949. */
  950. public _beforeRenderingGroupDrawStage = Stage.Create<RenderingGroupStageAction>();
  951. /**
  952. * @hidden
  953. * Defines the actions happening just before a mesh is drawing.
  954. */
  955. public _beforeRenderingMeshStage = Stage.Create<RenderingMeshStageAction>();
  956. /**
  957. * @hidden
  958. * Defines the actions happening just after a mesh has been drawn.
  959. */
  960. public _afterRenderingMeshStage = Stage.Create<RenderingMeshStageAction>();
  961. /**
  962. * @hidden
  963. * Defines the actions happening just after a rendering group has been drawn.
  964. */
  965. public _afterRenderingGroupDrawStage = Stage.Create<RenderingGroupStageAction>();
  966. /**
  967. * @hidden
  968. * Defines the actions happening just after the active camera has been drawn.
  969. */
  970. public _afterCameraDrawStage = Stage.Create<CameraStageAction>();
  971. /**
  972. * @hidden
  973. * Defines the actions happening just after rendering all cameras and computing intersections.
  974. */
  975. public _afterRenderStage = Stage.Create<SimpleStageAction>();
  976. /**
  977. * @hidden
  978. * Defines the actions happening when a pointer move event happens.
  979. */
  980. public _pointerMoveStage = Stage.Create<PointerMoveStageAction>();
  981. /**
  982. * @hidden
  983. * Defines the actions happening when a pointer down event happens.
  984. */
  985. public _pointerDownStage = Stage.Create<PointerUpDownStageAction>();
  986. /**
  987. * @hidden
  988. * Defines the actions happening when a pointer up event happens.
  989. */
  990. public _pointerUpStage = Stage.Create<PointerUpDownStageAction>();
  991. /**
  992. * Creates a new Scene
  993. * @param engine defines the engine to use to render this scene
  994. */
  995. constructor(engine: Engine) {
  996. super();
  997. this._engine = engine || Engine.LastCreatedEngine;
  998. this._engine.scenes.push(this);
  999. this._uid = null;
  1000. this._renderingManager = new RenderingManager(this);
  1001. if (PostProcessManager) {
  1002. this.postProcessManager = new PostProcessManager(this);
  1003. }
  1004. if (Tools.IsWindowObjectExist()) {
  1005. this.attachControl();
  1006. }
  1007. //collision coordinator initialization. For now legacy per default.
  1008. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  1009. // Uniform Buffer
  1010. this._createUbo();
  1011. // Default Image processing definition
  1012. if (ImageProcessingConfiguration) {
  1013. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  1014. }
  1015. this.setDefaultCandidateProviders();
  1016. }
  1017. private _defaultMeshCandidates: ISmartArrayLike<AbstractMesh> = {
  1018. data: [],
  1019. length: 0
  1020. }
  1021. /**
  1022. * @hidden
  1023. */
  1024. public _getDefaultMeshCandidates(): ISmartArrayLike<AbstractMesh> {
  1025. this._defaultMeshCandidates.data = this.meshes;
  1026. this._defaultMeshCandidates.length = this.meshes.length;
  1027. return this._defaultMeshCandidates;
  1028. }
  1029. private _defaultSubMeshCandidates: ISmartArrayLike<SubMesh> = {
  1030. data: [],
  1031. length: 0
  1032. }
  1033. /**
  1034. * @hidden
  1035. */
  1036. public _getDefaultSubMeshCandidates(mesh: AbstractMesh): ISmartArrayLike<SubMesh> {
  1037. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  1038. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  1039. return this._defaultSubMeshCandidates;
  1040. }
  1041. /**
  1042. * Sets the default candidate providers for the scene.
  1043. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  1044. * and getCollidingSubMeshCandidates to their default function
  1045. */
  1046. public setDefaultCandidateProviders(): void {
  1047. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  1048. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1049. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1050. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1051. }
  1052. public set workerCollisions(enabled: boolean) {
  1053. if (!CollisionCoordinatorLegacy) {
  1054. return;
  1055. }
  1056. enabled = (enabled && !!Worker && !!CollisionWorker);
  1057. this._workerCollisions = enabled;
  1058. if (this.collisionCoordinator) {
  1059. this.collisionCoordinator.destroy();
  1060. }
  1061. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  1062. this.collisionCoordinator.init(this);
  1063. }
  1064. /**
  1065. * Gets a boolean indicating if collisions are processed on a web worker
  1066. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  1067. */
  1068. public get workerCollisions(): boolean {
  1069. return this._workerCollisions;
  1070. }
  1071. /**
  1072. * Gets the mesh that is currently under the pointer
  1073. */
  1074. public get meshUnderPointer(): Nullable<AbstractMesh> {
  1075. return this._pointerOverMesh;
  1076. }
  1077. /**
  1078. * Gets the current on-screen X position of the pointer
  1079. */
  1080. public get pointerX(): number {
  1081. return this._pointerX;
  1082. }
  1083. /**
  1084. * Gets the current on-screen Y position of the pointer
  1085. */
  1086. public get pointerY(): number {
  1087. return this._pointerY;
  1088. }
  1089. /**
  1090. * Gets the cached material (ie. the latest rendered one)
  1091. * @returns the cached material
  1092. */
  1093. public getCachedMaterial(): Nullable<Material> {
  1094. return this._cachedMaterial;
  1095. }
  1096. /**
  1097. * Gets the cached effect (ie. the latest rendered one)
  1098. * @returns the cached effect
  1099. */
  1100. public getCachedEffect(): Nullable<Effect> {
  1101. return this._cachedEffect;
  1102. }
  1103. /**
  1104. * Gets the cached visibility state (ie. the latest rendered one)
  1105. * @returns the cached visibility state
  1106. */
  1107. public getCachedVisibility(): Nullable<number> {
  1108. return this._cachedVisibility;
  1109. }
  1110. /**
  1111. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  1112. * @param material defines the current material
  1113. * @param effect defines the current effect
  1114. * @param visibility defines the current visibility state
  1115. * @returns true if one parameter is not cached
  1116. */
  1117. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  1118. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  1119. }
  1120. /**
  1121. * Gets the engine associated with the scene
  1122. * @returns an Engine
  1123. */
  1124. public getEngine(): Engine {
  1125. return this._engine;
  1126. }
  1127. /**
  1128. * Gets the total number of vertices rendered per frame
  1129. * @returns the total number of vertices rendered per frame
  1130. */
  1131. public getTotalVertices(): number {
  1132. return this._totalVertices.current;
  1133. }
  1134. /**
  1135. * Gets the performance counter for total vertices
  1136. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1137. */
  1138. public get totalVerticesPerfCounter(): PerfCounter {
  1139. return this._totalVertices;
  1140. }
  1141. /**
  1142. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  1143. * @returns the total number of active indices rendered per frame
  1144. */
  1145. public getActiveIndices(): number {
  1146. return this._activeIndices.current;
  1147. }
  1148. /**
  1149. * Gets the performance counter for active indices
  1150. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1151. */
  1152. public get totalActiveIndicesPerfCounter(): PerfCounter {
  1153. return this._activeIndices;
  1154. }
  1155. /**
  1156. * Gets the total number of active particles rendered per frame
  1157. * @returns the total number of active particles rendered per frame
  1158. */
  1159. public getActiveParticles(): number {
  1160. return this._activeParticles.current;
  1161. }
  1162. /**
  1163. * Gets the performance counter for active particles
  1164. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1165. */
  1166. public get activeParticlesPerfCounter(): PerfCounter {
  1167. return this._activeParticles;
  1168. }
  1169. /**
  1170. * Gets the total number of active bones rendered per frame
  1171. * @returns the total number of active bones rendered per frame
  1172. */
  1173. public getActiveBones(): number {
  1174. return this._activeBones.current;
  1175. }
  1176. /**
  1177. * Gets the performance counter for active bones
  1178. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1179. */
  1180. public get activeBonesPerfCounter(): PerfCounter {
  1181. return this._activeBones;
  1182. }
  1183. /** @hidden */
  1184. public getInterFramePerfCounter(): number {
  1185. Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  1186. return 0;
  1187. }
  1188. /** @hidden */
  1189. public get interFramePerfCounter(): Nullable<PerfCounter> {
  1190. Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  1191. return null;
  1192. }
  1193. /** @hidden */
  1194. public getLastFrameDuration(): number {
  1195. Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  1196. return 0;
  1197. }
  1198. /** @hidden */
  1199. public get lastFramePerfCounter(): Nullable<PerfCounter> {
  1200. Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  1201. return null;
  1202. }
  1203. /** @hidden */
  1204. public getEvaluateActiveMeshesDuration(): number {
  1205. Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  1206. return 0;
  1207. }
  1208. /** @hidden */
  1209. public get evaluateActiveMeshesDurationPerfCounter(): Nullable<PerfCounter> {
  1210. Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  1211. return null;
  1212. }
  1213. /**
  1214. * Gets the array of active meshes
  1215. * @returns an array of AbstractMesh
  1216. */
  1217. public getActiveMeshes(): SmartArray<AbstractMesh> {
  1218. return this._activeMeshes;
  1219. }
  1220. /** @hidden */
  1221. public getRenderTargetsDuration(): number {
  1222. Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  1223. return 0;
  1224. }
  1225. /** @hidden */
  1226. public getRenderDuration(): number {
  1227. Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  1228. return 0;
  1229. }
  1230. /** @hidden */
  1231. public get renderDurationPerfCounter(): Nullable<PerfCounter> {
  1232. Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  1233. return null;
  1234. }
  1235. /** @hidden */
  1236. public getParticlesDuration(): number {
  1237. Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  1238. return 0;
  1239. }
  1240. /** @hidden */
  1241. public get particlesDurationPerfCounter(): Nullable<PerfCounter> {
  1242. Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  1243. return null;
  1244. }
  1245. /** @hidden */
  1246. public getSpritesDuration(): number {
  1247. Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  1248. return 0;
  1249. }
  1250. /** @hidden */
  1251. public get spriteDuractionPerfCounter(): Nullable<PerfCounter> {
  1252. Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  1253. return null;
  1254. }
  1255. /**
  1256. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  1257. * @returns a number
  1258. */
  1259. public getAnimationRatio(): number {
  1260. return this._animationRatio !== undefined ? this._animationRatio : 1;
  1261. }
  1262. /**
  1263. * Gets an unique Id for the current render phase
  1264. * @returns a number
  1265. */
  1266. public getRenderId(): number {
  1267. return this._renderId;
  1268. }
  1269. /**
  1270. * Gets an unique Id for the current frame
  1271. * @returns a number
  1272. */
  1273. public getFrameId(): number {
  1274. return this._frameId;
  1275. }
  1276. /** Call this function if you want to manually increment the render Id*/
  1277. public incrementRenderId(): void {
  1278. this._renderId++;
  1279. }
  1280. private _updatePointerPosition(evt: PointerEvent): void {
  1281. var canvasRect = this._engine.getRenderingCanvasClientRect();
  1282. if (!canvasRect) {
  1283. return;
  1284. }
  1285. this._pointerX = evt.clientX - canvasRect.left;
  1286. this._pointerY = evt.clientY - canvasRect.top;
  1287. this._unTranslatedPointerX = this._pointerX;
  1288. this._unTranslatedPointerY = this._pointerY;
  1289. }
  1290. private _createUbo(): void {
  1291. this._sceneUbo = new UniformBuffer(this._engine, undefined, true);
  1292. this._sceneUbo.addUniform("viewProjection", 16);
  1293. this._sceneUbo.addUniform("view", 16);
  1294. }
  1295. private _createAlternateUbo(): void {
  1296. this._alternateSceneUbo = new UniformBuffer(this._engine, undefined, true);
  1297. this._alternateSceneUbo.addUniform("viewProjection", 16);
  1298. this._alternateSceneUbo.addUniform("view", 16);
  1299. }
  1300. // Pointers handling
  1301. private _setRayOnPointerInfo(pointerInfo: PointerInfo) {
  1302. if (pointerInfo.pickInfo) {
  1303. if (!pointerInfo.pickInfo.ray) {
  1304. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, Matrix.Identity(), this.activeCamera);
  1305. }
  1306. }
  1307. }
  1308. /**
  1309. * Use this method to simulate a pointer move on a mesh
  1310. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1311. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1312. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1313. * @returns the current scene
  1314. */
  1315. public simulatePointerMove(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1316. let evt = new PointerEvent("pointermove", pointerEventInit);
  1317. if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERMOVE)) {
  1318. return this;
  1319. }
  1320. return this._processPointerMove(pickResult, evt);
  1321. }
  1322. private _processPointerMove(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1323. var canvas = this._engine.getRenderingCanvas();
  1324. if (!canvas) {
  1325. return this;
  1326. }
  1327. // Restore pointer
  1328. canvas.style.cursor = this.defaultCursor;
  1329. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  1330. if (isMeshPicked) {
  1331. this.setPointerOverMesh(pickResult!.pickedMesh);
  1332. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  1333. if (this._pointerOverMesh.actionManager.hoverCursor) {
  1334. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  1335. } else {
  1336. canvas.style.cursor = this.hoverCursor;
  1337. }
  1338. }
  1339. } else {
  1340. this.setPointerOverMesh(null);
  1341. }
  1342. for (let step of this._pointerMoveStage) {
  1343. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  1344. }
  1345. if (pickResult) {
  1346. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1347. if (this.onPointerMove) {
  1348. this.onPointerMove(evt, pickResult, type);
  1349. }
  1350. if (this.onPointerObservable.hasObservers()) {
  1351. let pi = new PointerInfo(type, evt, pickResult);
  1352. this._setRayOnPointerInfo(pi);
  1353. this.onPointerObservable.notifyObservers(pi, type);
  1354. }
  1355. }
  1356. return this;
  1357. }
  1358. private _checkPrePointerObservable(pickResult: Nullable<PickingInfo>, evt: PointerEvent, type: number) {
  1359. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1360. if (pickResult) {
  1361. pi.ray = pickResult.ray;
  1362. }
  1363. this.onPrePointerObservable.notifyObservers(pi, type);
  1364. if (pi.skipOnPointerObservable) {
  1365. return true;
  1366. } else {
  1367. return false;
  1368. }
  1369. }
  1370. /**
  1371. * Use this method to simulate a pointer down on a mesh
  1372. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1373. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1374. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1375. * @returns the current scene
  1376. */
  1377. public simulatePointerDown(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1378. let evt = new PointerEvent("pointerdown", pointerEventInit);
  1379. if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERDOWN)) {
  1380. return this;
  1381. }
  1382. return this._processPointerDown(pickResult, evt);
  1383. }
  1384. private _processPointerDown(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1385. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1386. this._pickedDownMesh = pickResult.pickedMesh;
  1387. var actionManager = pickResult.pickedMesh.actionManager;
  1388. if (actionManager) {
  1389. if (actionManager.hasPickTriggers) {
  1390. actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1391. switch (evt.button) {
  1392. case 0:
  1393. actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1394. break;
  1395. case 1:
  1396. actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1397. break;
  1398. case 2:
  1399. actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1400. break;
  1401. }
  1402. }
  1403. if (actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger)) {
  1404. window.setTimeout(() => {
  1405. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  1406. (mesh: AbstractMesh): boolean => (<boolean>(mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger) && mesh == this._pickedDownMesh)),
  1407. false, this.cameraToUseForPointers);
  1408. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  1409. if (this._totalPointersPressed !== 0 &&
  1410. ((Date.now() - this._startingPointerTime) > Scene.LongPressDelay) &&
  1411. !this._isPointerSwiping()) {
  1412. this._startingPointerTime = 0;
  1413. actionManager.processTrigger(ActionManager.OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1414. }
  1415. }
  1416. }, Scene.LongPressDelay);
  1417. }
  1418. }
  1419. }
  1420. else {
  1421. for (let step of this._pointerDownStage) {
  1422. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  1423. }
  1424. }
  1425. if (pickResult) {
  1426. let type = PointerEventTypes.POINTERDOWN;
  1427. if (this.onPointerDown) {
  1428. this.onPointerDown(evt, pickResult, type);
  1429. }
  1430. if (this.onPointerObservable.hasObservers()) {
  1431. let pi = new PointerInfo(type, evt, pickResult);
  1432. this._setRayOnPointerInfo(pi);
  1433. this.onPointerObservable.notifyObservers(pi, type);
  1434. }
  1435. }
  1436. return this;
  1437. }
  1438. /**
  1439. * Use this method to simulate a pointer up on a mesh
  1440. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1441. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1442. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1443. * @returns the current scene
  1444. */
  1445. public simulatePointerUp(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1446. let evt = new PointerEvent("pointerup", pointerEventInit);
  1447. let clickInfo = new ClickInfo();
  1448. clickInfo.singleClick = true;
  1449. clickInfo.ignore = true;
  1450. if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERUP)) {
  1451. return this;
  1452. }
  1453. return this._processPointerUp(pickResult, evt, clickInfo);
  1454. }
  1455. private _processPointerUp(pickResult: Nullable<PickingInfo>, evt: PointerEvent, clickInfo: ClickInfo): Scene {
  1456. if (pickResult && pickResult && pickResult.pickedMesh) {
  1457. this._pickedUpMesh = pickResult.pickedMesh;
  1458. if (this._pickedDownMesh === this._pickedUpMesh) {
  1459. if (this.onPointerPick) {
  1460. this.onPointerPick(evt, pickResult);
  1461. }
  1462. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  1463. let type = PointerEventTypes.POINTERPICK;
  1464. let pi = new PointerInfo(type, evt, pickResult);
  1465. this._setRayOnPointerInfo(pi);
  1466. this.onPointerObservable.notifyObservers(pi, type);
  1467. }
  1468. }
  1469. if (pickResult.pickedMesh.actionManager) {
  1470. if (clickInfo.ignore) {
  1471. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1472. }
  1473. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  1474. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1475. }
  1476. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1477. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1478. }
  1479. }
  1480. }
  1481. else {
  1482. if (!clickInfo.ignore) {
  1483. for (let step of this._pointerUpStage) {
  1484. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  1485. }
  1486. }
  1487. }
  1488. if (this._pickedDownMesh &&
  1489. this._pickedDownMesh.actionManager &&
  1490. this._pickedDownMesh.actionManager.hasSpecificTrigger(ActionManager.OnPickOutTrigger) &&
  1491. this._pickedDownMesh !== this._pickedUpMesh) {
  1492. this._pickedDownMesh.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  1493. }
  1494. let type = PointerEventTypes.POINTERUP;
  1495. if (this.onPointerObservable.hasObservers()) {
  1496. if (!clickInfo.ignore) {
  1497. if (!clickInfo.hasSwiped) {
  1498. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1499. let type = PointerEventTypes.POINTERTAP;
  1500. let pi = new PointerInfo(type, evt, pickResult);
  1501. this._setRayOnPointerInfo(pi);
  1502. this.onPointerObservable.notifyObservers(pi, type);
  1503. }
  1504. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1505. let type = PointerEventTypes.POINTERDOUBLETAP;
  1506. let pi = new PointerInfo(type, evt, pickResult);
  1507. this._setRayOnPointerInfo(pi);
  1508. this.onPointerObservable.notifyObservers(pi, type);
  1509. }
  1510. }
  1511. }
  1512. else {
  1513. let pi = new PointerInfo(type, evt, pickResult);
  1514. this._setRayOnPointerInfo(pi);
  1515. this.onPointerObservable.notifyObservers(pi, type);
  1516. }
  1517. }
  1518. if (this.onPointerUp) {
  1519. this.onPointerUp(evt, pickResult, type);
  1520. }
  1521. return this;
  1522. }
  1523. /**
  1524. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  1525. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  1526. * @returns true if the pointer was captured
  1527. */
  1528. public isPointerCaptured(pointerId = 0): boolean {
  1529. return this._pointerCaptures[pointerId];
  1530. }
  1531. /** @hidden */
  1532. public _isPointerSwiping(): boolean {
  1533. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  1534. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  1535. }
  1536. /**
  1537. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1538. * @param attachUp defines if you want to attach events to pointerup
  1539. * @param attachDown defines if you want to attach events to pointerdown
  1540. * @param attachMove defines if you want to attach events to pointermove
  1541. */
  1542. public attachControl(attachUp = true, attachDown = true, attachMove = true): void {
  1543. this._initActionManager = (act: Nullable<ActionManager>, clickInfo: ClickInfo): Nullable<ActionManager> => {
  1544. if (!this._meshPickProceed) {
  1545. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1546. this._currentPickResult = pickResult;
  1547. if (pickResult) {
  1548. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  1549. }
  1550. this._meshPickProceed = true;
  1551. }
  1552. return act;
  1553. };
  1554. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => {
  1555. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  1556. if ((Date.now() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  1557. btn !== this._previousButtonPressed) {
  1558. this._doubleClickOccured = false;
  1559. clickInfo.singleClick = true;
  1560. clickInfo.ignore = false;
  1561. cb(clickInfo, this._currentPickResult);
  1562. }
  1563. }
  1564. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void): void => {
  1565. let clickInfo = new ClickInfo();
  1566. this._currentPickResult = null;
  1567. let act: Nullable<ActionManager> = null;
  1568. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  1569. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  1570. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1571. if (!checkPicking && ActionManager && ActionManager.HasPickTriggers) {
  1572. act = this._initActionManager(act, clickInfo);
  1573. if (act)
  1574. checkPicking = act.hasPickTriggers;
  1575. }
  1576. if (checkPicking) {
  1577. let btn = evt.button;
  1578. clickInfo.hasSwiped = this._isPointerSwiping();
  1579. if (!clickInfo.hasSwiped) {
  1580. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  1581. if (!checkSingleClickImmediately) {
  1582. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  1583. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1584. if (checkSingleClickImmediately && !ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1585. act = this._initActionManager(act, clickInfo);
  1586. if (act)
  1587. checkSingleClickImmediately = !act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1588. }
  1589. }
  1590. if (checkSingleClickImmediately) {
  1591. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  1592. if (Date.now() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  1593. btn !== this._previousButtonPressed) {
  1594. clickInfo.singleClick = true;
  1595. cb(clickInfo, this._currentPickResult);
  1596. }
  1597. }
  1598. // at least one double click is required to be check and exclusive double click is enabled
  1599. else {
  1600. // wait that no double click has been raised during the double click delay
  1601. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1602. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  1603. }
  1604. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  1605. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1606. if (!checkDoubleClick && ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1607. act = this._initActionManager(act, clickInfo);
  1608. if (act)
  1609. checkDoubleClick = act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1610. }
  1611. if (checkDoubleClick) {
  1612. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  1613. if (btn === this._previousButtonPressed &&
  1614. Date.now() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  1615. !this._doubleClickOccured
  1616. ) {
  1617. // pointer has not moved for 2 clicks, it's a double click
  1618. if (!clickInfo.hasSwiped &&
  1619. !this._isPointerSwiping()) {
  1620. this._previousStartingPointerTime = 0;
  1621. this._doubleClickOccured = true;
  1622. clickInfo.doubleClick = true;
  1623. clickInfo.ignore = false;
  1624. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout) {
  1625. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1626. }
  1627. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1628. cb(clickInfo, this._currentPickResult);
  1629. }
  1630. // if the two successive clicks are too far, it's just two simple clicks
  1631. else {
  1632. this._doubleClickOccured = false;
  1633. this._previousStartingPointerTime = this._startingPointerTime;
  1634. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1635. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1636. this._previousButtonPressed = btn;
  1637. if (Scene.ExclusiveDoubleClickMode) {
  1638. if (this._previousDelayedSimpleClickTimeout) {
  1639. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1640. }
  1641. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1642. cb(clickInfo, this._previousPickResult);
  1643. }
  1644. else {
  1645. cb(clickInfo, this._currentPickResult);
  1646. }
  1647. }
  1648. }
  1649. // just the first click of the double has been raised
  1650. else {
  1651. this._doubleClickOccured = false;
  1652. this._previousStartingPointerTime = this._startingPointerTime;
  1653. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1654. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1655. this._previousButtonPressed = btn;
  1656. }
  1657. }
  1658. }
  1659. }
  1660. clickInfo.ignore = true;
  1661. cb(clickInfo, this._currentPickResult);
  1662. };
  1663. this._onPointerMove = (evt: PointerEvent) => {
  1664. this._updatePointerPosition(evt);
  1665. // PreObservable support
  1666. if (this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE)) {
  1667. return;
  1668. }
  1669. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1670. return;
  1671. }
  1672. if (!this.pointerMovePredicate) {
  1673. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined));
  1674. }
  1675. // Meshes
  1676. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  1677. this._processPointerMove(pickResult, evt);
  1678. };
  1679. this._onPointerDown = (evt: PointerEvent) => {
  1680. this._totalPointersPressed++;
  1681. this._pickedDownMesh = null;
  1682. this._meshPickProceed = false;
  1683. this._updatePointerPosition(evt);
  1684. if (this.preventDefaultOnPointerDown && canvas) {
  1685. evt.preventDefault();
  1686. canvas.focus();
  1687. }
  1688. // PreObservable support
  1689. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOWN)) {
  1690. return;
  1691. }
  1692. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1693. return;
  1694. }
  1695. this._pointerCaptures[evt.pointerId] = true;
  1696. this._startingPointerPosition.x = this._pointerX;
  1697. this._startingPointerPosition.y = this._pointerY;
  1698. this._startingPointerTime = Date.now();
  1699. if (!this.pointerDownPredicate) {
  1700. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  1701. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1702. };
  1703. }
  1704. // Meshes
  1705. this._pickedDownMesh = null;
  1706. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1707. this._processPointerDown(pickResult, evt);
  1708. };
  1709. this._onPointerUp = (evt: PointerEvent) => {
  1710. if (this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  1711. return; // So we need to test it the pointer down was pressed before.
  1712. }
  1713. this._totalPointersPressed--;
  1714. this._pickedUpMesh = null;
  1715. this._meshPickProceed = false;
  1716. this._updatePointerPosition(evt);
  1717. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => {
  1718. // PreObservable support
  1719. if (this.onPrePointerObservable.hasObservers()) {
  1720. if (!clickInfo.ignore) {
  1721. if (!clickInfo.hasSwiped) {
  1722. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1723. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERTAP)) {
  1724. return;
  1725. }
  1726. }
  1727. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1728. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOUBLETAP)) {
  1729. return;
  1730. }
  1731. }
  1732. }
  1733. }
  1734. else {
  1735. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)) {
  1736. return;
  1737. }
  1738. }
  1739. }
  1740. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1741. return;
  1742. }
  1743. this._pointerCaptures[evt.pointerId] = false;
  1744. if (!this.pointerUpPredicate) {
  1745. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1746. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1747. };
  1748. }
  1749. // Meshes
  1750. if (!this._meshPickProceed && (ActionManager && ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1751. this._initActionManager(null, clickInfo);
  1752. }
  1753. if (!pickResult) {
  1754. pickResult = this._currentPickResult;
  1755. }
  1756. this._processPointerUp(pickResult, evt, clickInfo);
  1757. this._previousPickResult = this._currentPickResult;
  1758. });
  1759. };
  1760. this._onKeyDown = (evt: KeyboardEvent) => {
  1761. let type = KeyboardEventTypes.KEYDOWN;
  1762. if (this.onPreKeyboardObservable.hasObservers()) {
  1763. let pi = new KeyboardInfoPre(type, evt);
  1764. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1765. if (pi.skipOnPointerObservable) {
  1766. return;
  1767. }
  1768. }
  1769. if (this.onKeyboardObservable.hasObservers()) {
  1770. let pi = new KeyboardInfo(type, evt);
  1771. this.onKeyboardObservable.notifyObservers(pi, type);
  1772. }
  1773. if (this.actionManager) {
  1774. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1775. }
  1776. };
  1777. this._onKeyUp = (evt: KeyboardEvent) => {
  1778. let type = KeyboardEventTypes.KEYUP;
  1779. if (this.onPreKeyboardObservable.hasObservers()) {
  1780. let pi = new KeyboardInfoPre(type, evt);
  1781. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1782. if (pi.skipOnPointerObservable) {
  1783. return;
  1784. }
  1785. }
  1786. if (this.onKeyboardObservable.hasObservers()) {
  1787. let pi = new KeyboardInfo(type, evt);
  1788. this.onKeyboardObservable.notifyObservers(pi, type);
  1789. }
  1790. if (this.actionManager) {
  1791. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1792. }
  1793. };
  1794. let engine = this.getEngine();
  1795. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(() => {
  1796. if (!canvas) {
  1797. return;
  1798. }
  1799. canvas.addEventListener("keydown", this._onKeyDown, false);
  1800. canvas.addEventListener("keyup", this._onKeyUp, false);
  1801. });
  1802. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(() => {
  1803. if (!canvas) {
  1804. return;
  1805. }
  1806. canvas.removeEventListener("keydown", this._onKeyDown);
  1807. canvas.removeEventListener("keyup", this._onKeyUp);
  1808. });
  1809. var eventPrefix = Tools.GetPointerPrefix();
  1810. var canvas = this._engine.getRenderingCanvas();
  1811. if (!canvas) {
  1812. return;
  1813. }
  1814. if (attachMove) {
  1815. canvas.addEventListener(eventPrefix + "move", <any>this._onPointerMove, false);
  1816. // Wheel
  1817. canvas.addEventListener('mousewheel', <any>this._onPointerMove, false);
  1818. canvas.addEventListener('DOMMouseScroll', <any>this._onPointerMove, false);
  1819. }
  1820. if (attachDown) {
  1821. canvas.addEventListener(eventPrefix + "down", <any>this._onPointerDown, false);
  1822. }
  1823. if (attachUp) {
  1824. window.addEventListener(eventPrefix + "up", <any>this._onPointerUp, false);
  1825. }
  1826. canvas.tabIndex = 1;
  1827. }
  1828. /** Detaches all event handlers*/
  1829. public detachControl() {
  1830. let engine = this.getEngine();
  1831. var eventPrefix = Tools.GetPointerPrefix();
  1832. var canvas = engine.getRenderingCanvas();
  1833. if (!canvas) {
  1834. return;
  1835. }
  1836. canvas.removeEventListener(eventPrefix + "move", <any>this._onPointerMove);
  1837. canvas.removeEventListener(eventPrefix + "down", <any>this._onPointerDown);
  1838. window.removeEventListener(eventPrefix + "up", <any>this._onPointerUp);
  1839. if (this._onCanvasBlurObserver) {
  1840. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  1841. }
  1842. if (this._onCanvasFocusObserver) {
  1843. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  1844. }
  1845. // Wheel
  1846. canvas.removeEventListener('mousewheel', <any>this._onPointerMove);
  1847. canvas.removeEventListener('DOMMouseScroll', <any>this._onPointerMove);
  1848. // Keyboard
  1849. canvas.removeEventListener("keydown", this._onKeyDown);
  1850. canvas.removeEventListener("keyup", this._onKeyUp);
  1851. // Observables
  1852. this.onKeyboardObservable.clear();
  1853. this.onPreKeyboardObservable.clear();
  1854. this.onPointerObservable.clear();
  1855. this.onPrePointerObservable.clear();
  1856. }
  1857. /**
  1858. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  1859. * Delay loaded resources are not taking in account
  1860. * @return true if all required resources are ready
  1861. */
  1862. public isReady(): boolean {
  1863. if (this._isDisposed) {
  1864. return false;
  1865. }
  1866. if (this._pendingData.length > 0) {
  1867. return false;
  1868. }
  1869. let index: number;
  1870. let engine = this.getEngine();
  1871. // Geometries
  1872. for (index = 0; index < this.geometries.length; index++) {
  1873. var geometry = this.geometries[index];
  1874. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1875. return false;
  1876. }
  1877. }
  1878. // Meshes
  1879. for (index = 0; index < this.meshes.length; index++) {
  1880. var mesh = this.meshes[index];
  1881. if (!mesh.isEnabled()) {
  1882. continue;
  1883. }
  1884. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  1885. continue;
  1886. }
  1887. if (!mesh.isReady(true)) {
  1888. return false;
  1889. }
  1890. let hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && (<Mesh>mesh).instances.length > 0;
  1891. // Is Ready For Mesh
  1892. for (let step of this._isReadyForMeshStage) {
  1893. if (!step.action(mesh, hardwareInstancedRendering)) {
  1894. return false;
  1895. }
  1896. }
  1897. }
  1898. // Post-processes
  1899. if (this.activeCameras && this.activeCameras.length > 0) {
  1900. for (var camera of this.activeCameras) {
  1901. if (!camera.isReady(true)) {
  1902. return false;
  1903. }
  1904. }
  1905. } else if (this.activeCamera) {
  1906. if (!this.activeCamera.isReady(true)) {
  1907. return false;
  1908. }
  1909. }
  1910. // Particles
  1911. for (var particleSystem of this.particleSystems) {
  1912. if (!particleSystem.isReady()) {
  1913. return false;
  1914. }
  1915. }
  1916. return true;
  1917. }
  1918. /** Resets all cached information relative to material (including effect and visibility) */
  1919. public resetCachedMaterial(): void {
  1920. this._cachedMaterial = null;
  1921. this._cachedEffect = null;
  1922. this._cachedVisibility = null;
  1923. }
  1924. /**
  1925. * Registers a function to be called before every frame render
  1926. * @param func defines the function to register
  1927. */
  1928. public registerBeforeRender(func: () => void): void {
  1929. this.onBeforeRenderObservable.add(func);
  1930. }
  1931. /**
  1932. * Unregisters a function called before every frame render
  1933. * @param func defines the function to unregister
  1934. */
  1935. public unregisterBeforeRender(func: () => void): void {
  1936. this.onBeforeRenderObservable.removeCallback(func);
  1937. }
  1938. /**
  1939. * Registers a function to be called after every frame render
  1940. * @param func defines the function to register
  1941. */
  1942. public registerAfterRender(func: () => void): void {
  1943. this.onAfterRenderObservable.add(func);
  1944. }
  1945. /**
  1946. * Unregisters a function called after every frame render
  1947. * @param func defines the function to unregister
  1948. */
  1949. public unregisterAfterRender(func: () => void): void {
  1950. this.onAfterRenderObservable.removeCallback(func);
  1951. }
  1952. private _executeOnceBeforeRender(func: () => void): void {
  1953. let execFunc = () => {
  1954. func();
  1955. setTimeout(() => {
  1956. this.unregisterBeforeRender(execFunc);
  1957. });
  1958. }
  1959. this.registerBeforeRender(execFunc);
  1960. }
  1961. /**
  1962. * The provided function will run before render once and will be disposed afterwards.
  1963. * A timeout delay can be provided so that the function will be executed in N ms.
  1964. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  1965. * @param func The function to be executed.
  1966. * @param timeout optional delay in ms
  1967. */
  1968. public executeOnceBeforeRender(func: () => void, timeout?: number): void {
  1969. if (timeout !== undefined) {
  1970. setTimeout(() => {
  1971. this._executeOnceBeforeRender(func);
  1972. }, timeout);
  1973. } else {
  1974. this._executeOnceBeforeRender(func);
  1975. }
  1976. }
  1977. /** @hidden */
  1978. public _addPendingData(data: any): void {
  1979. this._pendingData.push(data);
  1980. }
  1981. /** @hidden */
  1982. public _removePendingData(data: any): void {
  1983. var wasLoading = this.isLoading;
  1984. var index = this._pendingData.indexOf(data);
  1985. if (index !== -1) {
  1986. this._pendingData.splice(index, 1);
  1987. }
  1988. if (wasLoading && !this.isLoading) {
  1989. this.onDataLoadedObservable.notifyObservers(this);
  1990. }
  1991. }
  1992. /**
  1993. * Returns the number of items waiting to be loaded
  1994. * @returns the number of items waiting to be loaded
  1995. */
  1996. public getWaitingItemsCount(): number {
  1997. return this._pendingData.length;
  1998. }
  1999. /**
  2000. * Returns a boolean indicating if the scene is still loading data
  2001. */
  2002. public get isLoading(): boolean {
  2003. return this._pendingData.length > 0;
  2004. }
  2005. /**
  2006. * Registers a function to be executed when the scene is ready
  2007. * @param {Function} func - the function to be executed
  2008. */
  2009. public executeWhenReady(func: () => void): void {
  2010. this.onReadyObservable.add(func);
  2011. if (this._executeWhenReadyTimeoutId !== -1) {
  2012. return;
  2013. }
  2014. this._executeWhenReadyTimeoutId = setTimeout(() => {
  2015. this._checkIsReady();
  2016. }, 150);
  2017. }
  2018. /**
  2019. * Returns a promise that resolves when the scene is ready
  2020. * @returns A promise that resolves when the scene is ready
  2021. */
  2022. public whenReadyAsync(): Promise<void> {
  2023. return new Promise(resolve => {
  2024. this.executeWhenReady(() => {
  2025. resolve();
  2026. });
  2027. });
  2028. }
  2029. /** @hidden */
  2030. public _checkIsReady() {
  2031. this._registerTransientComponents();
  2032. if (this.isReady()) {
  2033. this.onReadyObservable.notifyObservers(this);
  2034. this.onReadyObservable.clear();
  2035. this._executeWhenReadyTimeoutId = -1;
  2036. return;
  2037. }
  2038. this._executeWhenReadyTimeoutId = setTimeout(() => {
  2039. this._checkIsReady();
  2040. }, 150);
  2041. }
  2042. // Animations
  2043. /**
  2044. * Will start the animation sequence of a given target
  2045. * @param target defines the target
  2046. * @param from defines from which frame should animation start
  2047. * @param to defines until which frame should animation run.
  2048. * @param weight defines the weight to apply to the animation (1.0 by default)
  2049. * @param loop defines if the animation loops
  2050. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  2051. * @param onAnimationEnd defines the function to be executed when the animation ends
  2052. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  2053. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  2054. * @returns the animatable object created for this animation
  2055. */
  2056. public beginWeightedAnimation(target: any, from: number, to: number, weight = 1.0, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable, targetMask?: (target: any) => boolean): Animatable {
  2057. let returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  2058. returnedAnimatable.weight = weight;
  2059. return returnedAnimatable;
  2060. }
  2061. /**
  2062. * Will start the animation sequence of a given target
  2063. * @param target defines the target
  2064. * @param from defines from which frame should animation start
  2065. * @param to defines until which frame should animation run.
  2066. * @param loop defines if the animation loops
  2067. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  2068. * @param onAnimationEnd defines the function to be executed when the animation ends
  2069. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  2070. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  2071. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  2072. * @returns the animatable object created for this animation
  2073. */
  2074. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable, stopCurrent = true, targetMask?: (target: any) => boolean): Animatable {
  2075. if (from > to && speedRatio > 0) {
  2076. speedRatio *= -1;
  2077. }
  2078. if (stopCurrent) {
  2079. this.stopAnimation(target, undefined, targetMask);
  2080. }
  2081. if (!animatable) {
  2082. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  2083. }
  2084. const shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  2085. // Local animations
  2086. if (target.animations && shouldRunTargetAnimations) {
  2087. animatable.appendAnimations(target, target.animations);
  2088. }
  2089. // Children animations
  2090. if (target.getAnimatables) {
  2091. var animatables = target.getAnimatables();
  2092. for (var index = 0; index < animatables.length; index++) {
  2093. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  2094. }
  2095. }
  2096. animatable.reset();
  2097. return animatable;
  2098. }
  2099. /**
  2100. * Begin a new animation on a given node
  2101. * @param target defines the target where the animation will take place
  2102. * @param animations defines the list of animations to start
  2103. * @param from defines the initial value
  2104. * @param to defines the final value
  2105. * @param loop defines if you want animation to loop (off by default)
  2106. * @param speedRatio defines the speed ratio to apply to all animations
  2107. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  2108. * @returns the list of created animatables
  2109. */
  2110. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  2111. if (speedRatio === undefined) {
  2112. speedRatio = 1.0;
  2113. }
  2114. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  2115. return animatable;
  2116. }
  2117. /**
  2118. * Begin a new animation on a given node and its hierarchy
  2119. * @param target defines the root node where the animation will take place
  2120. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  2121. * @param animations defines the list of animations to start
  2122. * @param from defines the initial value
  2123. * @param to defines the final value
  2124. * @param loop defines if you want animation to loop (off by default)
  2125. * @param speedRatio defines the speed ratio to apply to all animations
  2126. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  2127. * @returns the list of animatables created for all nodes
  2128. */
  2129. public beginDirectHierarchyAnimation(target: Node, directDescendantsOnly: boolean, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable[] {
  2130. let children = target.getDescendants(directDescendantsOnly);
  2131. let result = [];
  2132. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  2133. for (var child of children) {
  2134. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  2135. }
  2136. return result;
  2137. }
  2138. /**
  2139. * Gets the animatable associated with a specific target
  2140. * @param target defines the target of the animatable
  2141. * @returns the required animatable if found
  2142. */
  2143. public getAnimatableByTarget(target: any): Nullable<Animatable> {
  2144. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2145. if (this._activeAnimatables[index].target === target) {
  2146. return this._activeAnimatables[index];
  2147. }
  2148. }
  2149. return null;
  2150. }
  2151. /**
  2152. * Gets all animatables associated with a given target
  2153. * @param target defines the target to look animatables for
  2154. * @returns an array of Animatables
  2155. */
  2156. public getAllAnimatablesByTarget(target: any): Array<Animatable> {
  2157. let result = [];
  2158. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2159. if (this._activeAnimatables[index].target === target) {
  2160. result.push(this._activeAnimatables[index]);
  2161. }
  2162. }
  2163. return result;
  2164. }
  2165. /**
  2166. * Gets all animatable attached to the scene
  2167. */
  2168. public get animatables(): Animatable[] {
  2169. return this._activeAnimatables;
  2170. }
  2171. /**
  2172. * Will stop the animation of the given target
  2173. * @param target - the target
  2174. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  2175. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  2176. */
  2177. public stopAnimation(target: any, animationName?: string, targetMask?: (target: any) => boolean): void {
  2178. var animatables = this.getAllAnimatablesByTarget(target);
  2179. for (var animatable of animatables) {
  2180. animatable.stop(animationName, targetMask);
  2181. }
  2182. }
  2183. /**
  2184. * Stops and removes all animations that have been applied to the scene
  2185. */
  2186. public stopAllAnimations(): void {
  2187. if (this._activeAnimatables) {
  2188. for (let i = 0; i < this._activeAnimatables.length; i++) {
  2189. this._activeAnimatables[i].stop();
  2190. }
  2191. this._activeAnimatables = [];
  2192. }
  2193. for (var group of this.animationGroups) {
  2194. group.stop();
  2195. }
  2196. }
  2197. private _animate(): void {
  2198. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  2199. return;
  2200. }
  2201. // Getting time
  2202. var now = Tools.Now;
  2203. if (!this._animationTimeLast) {
  2204. if (this._pendingData.length > 0) {
  2205. return;
  2206. }
  2207. this._animationTimeLast = now;
  2208. }
  2209. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  2210. this._animationTime += deltaTime;
  2211. this._animationTimeLast = now;
  2212. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2213. this._activeAnimatables[index]._animate(this._animationTime);
  2214. }
  2215. // Late animation bindings
  2216. this._processLateAnimationBindings();
  2217. }
  2218. /** @hidden */
  2219. public _registerTargetForLateAnimationBinding(runtimeAnimation: RuntimeAnimation, originalValue: any): void {
  2220. let target = runtimeAnimation.target;
  2221. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  2222. if (!target._lateAnimationHolders) {
  2223. target._lateAnimationHolders = {};
  2224. }
  2225. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  2226. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  2227. totalWeight: 0,
  2228. animations: [],
  2229. originalValue: originalValue
  2230. }
  2231. }
  2232. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  2233. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  2234. }
  2235. private _processLateAnimationBindingsForMatrices(holder: {
  2236. totalWeight: number,
  2237. animations: RuntimeAnimation[],
  2238. originalValue: Matrix
  2239. }): any {
  2240. let normalizer = 1.0;
  2241. let finalPosition = Tmp.Vector3[0];
  2242. let finalScaling = Tmp.Vector3[1];
  2243. let finalQuaternion = Tmp.Quaternion[0];
  2244. let startIndex = 0;
  2245. let originalAnimation = holder.animations[0];
  2246. let originalValue = holder.originalValue;
  2247. var scale = 1;
  2248. if (holder.totalWeight < 1.0) {
  2249. // We need to mix the original value in
  2250. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  2251. scale = 1.0 - holder.totalWeight;
  2252. } else {
  2253. startIndex = 1;
  2254. // We need to normalize the weights
  2255. normalizer = holder.totalWeight;
  2256. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  2257. scale = originalAnimation.weight / normalizer;
  2258. if (scale == 1) {
  2259. return originalAnimation.currentValue;
  2260. }
  2261. }
  2262. finalScaling.scaleInPlace(scale);
  2263. finalPosition.scaleInPlace(scale);
  2264. finalQuaternion.scaleInPlace(scale);
  2265. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  2266. var runtimeAnimation = holder.animations[animIndex];
  2267. var scale = runtimeAnimation.weight / normalizer;
  2268. let currentPosition = Tmp.Vector3[2];
  2269. let currentScaling = Tmp.Vector3[3];
  2270. let currentQuaternion = Tmp.Quaternion[1];
  2271. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  2272. currentScaling.scaleAndAddToRef(scale, finalScaling);
  2273. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  2274. currentPosition.scaleAndAddToRef(scale, finalPosition);
  2275. }
  2276. Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  2277. return originalAnimation._workValue;
  2278. }
  2279. private _processLateAnimationBindingsForQuaternions(holder: {
  2280. totalWeight: number,
  2281. animations: RuntimeAnimation[],
  2282. originalValue: Quaternion
  2283. }, refQuaternion: Quaternion): Quaternion {
  2284. let originalAnimation = holder.animations[0];
  2285. let originalValue = holder.originalValue;
  2286. if (holder.animations.length === 1) {
  2287. Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  2288. return refQuaternion;
  2289. }
  2290. let normalizer = 1.0;
  2291. let quaternions: Array<Quaternion>;
  2292. let weights: Array<number>;
  2293. if (holder.totalWeight < 1.0) {
  2294. let scale = 1.0 - holder.totalWeight;
  2295. quaternions = [];
  2296. weights = [];
  2297. quaternions.push(originalValue);
  2298. weights.push(scale);
  2299. } else {
  2300. if (holder.animations.length === 2) { // Slerp as soon as we can
  2301. Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  2302. return refQuaternion;
  2303. }
  2304. quaternions = [];
  2305. weights = [];
  2306. normalizer = holder.totalWeight;
  2307. }
  2308. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  2309. let runtimeAnimation = holder.animations[animIndex];
  2310. quaternions.push(runtimeAnimation.currentValue);
  2311. weights.push(runtimeAnimation.weight / normalizer);
  2312. }
  2313. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  2314. let cumulativeAmount = 0;
  2315. let cumulativeQuaternion: Nullable<Quaternion> = null;
  2316. for (var index = 0; index < quaternions.length;) {
  2317. if (!cumulativeQuaternion) {
  2318. Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  2319. cumulativeQuaternion = refQuaternion;
  2320. cumulativeAmount = weights[index] + weights[index + 1];
  2321. index += 2;
  2322. continue;
  2323. }
  2324. cumulativeAmount += weights[index];
  2325. Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  2326. index++;
  2327. }
  2328. return cumulativeQuaternion!;
  2329. }
  2330. private _processLateAnimationBindings(): void {
  2331. if (!this._registeredForLateAnimationBindings.length) {
  2332. return;
  2333. }
  2334. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  2335. var target = this._registeredForLateAnimationBindings.data[index];
  2336. for (var path in target._lateAnimationHolders) {
  2337. var holder = target._lateAnimationHolders[path];
  2338. let originalAnimation: RuntimeAnimation = holder.animations[0];
  2339. let originalValue = holder.originalValue;
  2340. let matrixDecomposeMode = Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  2341. let finalValue: any = target[path];
  2342. if (matrixDecomposeMode) {
  2343. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  2344. } else {
  2345. let quaternionMode = originalValue.w !== undefined;
  2346. if (quaternionMode) {
  2347. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || Quaternion.Identity());
  2348. } else {
  2349. let startIndex = 0;
  2350. let normalizer = 1.0;
  2351. if (holder.totalWeight < 1.0) {
  2352. // We need to mix the original value in
  2353. if (originalValue.scale) {
  2354. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  2355. } else {
  2356. finalValue = originalValue * (1.0 - holder.totalWeight);
  2357. }
  2358. } else {
  2359. // We need to normalize the weights
  2360. normalizer = holder.totalWeight;
  2361. let scale = originalAnimation.weight / normalizer;
  2362. if (scale !== 1) {
  2363. if (originalAnimation.currentValue.scale) {
  2364. finalValue = originalAnimation.currentValue.scale(scale);
  2365. } else {
  2366. finalValue = originalAnimation.currentValue * scale;
  2367. }
  2368. } else {
  2369. finalValue = originalAnimation.currentValue;
  2370. }
  2371. startIndex = 1;
  2372. }
  2373. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  2374. var runtimeAnimation = holder.animations[animIndex];
  2375. var scale = runtimeAnimation.weight / normalizer;
  2376. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  2377. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  2378. } else {
  2379. finalValue += runtimeAnimation.currentValue * scale;
  2380. }
  2381. }
  2382. }
  2383. }
  2384. target[path] = finalValue;
  2385. }
  2386. target._lateAnimationHolders = {};
  2387. }
  2388. this._registeredForLateAnimationBindings.reset();
  2389. }
  2390. // Matrix
  2391. /** @hidden */
  2392. public _switchToAlternateCameraConfiguration(active: boolean): void {
  2393. this._useAlternateCameraConfiguration = active;
  2394. }
  2395. /**
  2396. * Gets the current view matrix
  2397. * @returns a Matrix
  2398. */
  2399. public getViewMatrix(): Matrix {
  2400. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  2401. }
  2402. /**
  2403. * Gets the current projection matrix
  2404. * @returns a Matrix
  2405. */
  2406. public getProjectionMatrix(): Matrix {
  2407. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  2408. }
  2409. /**
  2410. * Gets the current transform matrix
  2411. * @returns a Matrix made of View * Projection
  2412. */
  2413. public getTransformMatrix(): Matrix {
  2414. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  2415. }
  2416. /**
  2417. * Sets the current transform matrix
  2418. * @param view defines the View matrix to use
  2419. * @param projection defines the Projection matrix to use
  2420. */
  2421. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  2422. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  2423. return;
  2424. }
  2425. this._viewUpdateFlag = view.updateFlag;
  2426. this._projectionUpdateFlag = projection.updateFlag;
  2427. this._viewMatrix = view;
  2428. this._projectionMatrix = projection;
  2429. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  2430. // Update frustum
  2431. if (!this._frustumPlanes) {
  2432. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  2433. } else {
  2434. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  2435. }
  2436. if (this.activeCamera && this.activeCamera._alternateCamera) {
  2437. let otherCamera = this.activeCamera._alternateCamera;
  2438. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), Tmp.Matrix[0]);
  2439. Frustum.GetRightPlaneToRef(Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  2440. }
  2441. if (this._sceneUbo.useUbo) {
  2442. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  2443. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  2444. this._sceneUbo.update();
  2445. }
  2446. }
  2447. /** @hidden */
  2448. public _setAlternateTransformMatrix(view: Matrix, projection: Matrix): void {
  2449. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  2450. return;
  2451. }
  2452. this._alternateViewUpdateFlag = view.updateFlag;
  2453. this._alternateProjectionUpdateFlag = projection.updateFlag;
  2454. this._alternateViewMatrix = view;
  2455. this._alternateProjectionMatrix = projection;
  2456. if (!this._alternateTransformMatrix) {
  2457. this._alternateTransformMatrix = Matrix.Zero();
  2458. }
  2459. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  2460. if (!this._alternateSceneUbo) {
  2461. this._createAlternateUbo();
  2462. }
  2463. if (this._alternateSceneUbo.useUbo) {
  2464. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  2465. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  2466. this._alternateSceneUbo.update();
  2467. }
  2468. }
  2469. /**
  2470. * Gets the uniform buffer used to store scene data
  2471. * @returns a UniformBuffer
  2472. */
  2473. public getSceneUniformBuffer(): UniformBuffer {
  2474. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  2475. }
  2476. /**
  2477. * Gets an unique (relatively to the current scene) Id
  2478. * @returns an unique number for the scene
  2479. */
  2480. public getUniqueId() {
  2481. var result = Scene._uniqueIdCounter;
  2482. Scene._uniqueIdCounter++;
  2483. return result;
  2484. }
  2485. /**
  2486. * Add a mesh to the list of scene's meshes
  2487. * @param newMesh defines the mesh to add
  2488. * @param recursive if all child meshes should also be added to the scene
  2489. */
  2490. public addMesh(newMesh: AbstractMesh, recursive = false) {
  2491. this.meshes.push(newMesh);
  2492. //notify the collision coordinator
  2493. if (this.collisionCoordinator) {
  2494. this.collisionCoordinator.onMeshAdded(newMesh);
  2495. }
  2496. newMesh._resyncLightSources();
  2497. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  2498. if (recursive) {
  2499. newMesh.getChildMeshes().forEach((m) => {
  2500. this.addMesh(m);
  2501. })
  2502. }
  2503. }
  2504. /**
  2505. * Remove a mesh for the list of scene's meshes
  2506. * @param toRemove defines the mesh to remove
  2507. * @param recursive if all child meshes should also be removed from the scene
  2508. * @returns the index where the mesh was in the mesh list
  2509. */
  2510. public removeMesh(toRemove: AbstractMesh, recursive = false): number {
  2511. var index = this.meshes.indexOf(toRemove);
  2512. if (index !== -1) {
  2513. // Remove from the scene if mesh found
  2514. this.meshes.splice(index, 1);
  2515. }
  2516. this.onMeshRemovedObservable.notifyObservers(toRemove);
  2517. if (recursive) {
  2518. toRemove.getChildMeshes().forEach((m) => {
  2519. this.removeMesh(m);
  2520. })
  2521. }
  2522. return index;
  2523. }
  2524. /**
  2525. * Add a transform node to the list of scene's transform nodes
  2526. * @param newTransformNode defines the transform node to add
  2527. */
  2528. public addTransformNode(newTransformNode: TransformNode) {
  2529. this.transformNodes.push(newTransformNode);
  2530. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  2531. }
  2532. /**
  2533. * Remove a transform node for the list of scene's transform nodes
  2534. * @param toRemove defines the transform node to remove
  2535. * @returns the index where the transform node was in the transform node list
  2536. */
  2537. public removeTransformNode(toRemove: TransformNode): number {
  2538. var index = this.transformNodes.indexOf(toRemove);
  2539. if (index !== -1) {
  2540. // Remove from the scene if found
  2541. this.transformNodes.splice(index, 1);
  2542. }
  2543. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  2544. return index;
  2545. }
  2546. /**
  2547. * Remove a skeleton for the list of scene's skeletons
  2548. * @param toRemove defines the skeleton to remove
  2549. * @returns the index where the skeleton was in the skeleton list
  2550. */
  2551. public removeSkeleton(toRemove: Skeleton): number {
  2552. var index = this.skeletons.indexOf(toRemove);
  2553. if (index !== -1) {
  2554. // Remove from the scene if found
  2555. this.skeletons.splice(index, 1);
  2556. }
  2557. return index;
  2558. }
  2559. /**
  2560. * Remove a morph target for the list of scene's morph targets
  2561. * @param toRemove defines the morph target to remove
  2562. * @returns the index where the morph target was in the morph target list
  2563. */
  2564. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  2565. var index = this.morphTargetManagers.indexOf(toRemove);
  2566. if (index !== -1) {
  2567. // Remove from the scene if found
  2568. this.morphTargetManagers.splice(index, 1);
  2569. }
  2570. return index;
  2571. }
  2572. /**
  2573. * Remove a light for the list of scene's lights
  2574. * @param toRemove defines the light to remove
  2575. * @returns the index where the light was in the light list
  2576. */
  2577. public removeLight(toRemove: Light): number {
  2578. var index = this.lights.indexOf(toRemove);
  2579. if (index !== -1) {
  2580. // Remove from meshes
  2581. for (var mesh of this.meshes) {
  2582. mesh._removeLightSource(toRemove);
  2583. }
  2584. // Remove from the scene if mesh found
  2585. this.lights.splice(index, 1);
  2586. this.sortLightsByPriority();
  2587. }
  2588. this.onLightRemovedObservable.notifyObservers(toRemove);
  2589. return index;
  2590. }
  2591. /**
  2592. * Remove a camera for the list of scene's cameras
  2593. * @param toRemove defines the camera to remove
  2594. * @returns the index where the camera was in the camera list
  2595. */
  2596. public removeCamera(toRemove: Camera): number {
  2597. var index = this.cameras.indexOf(toRemove);
  2598. if (index !== -1) {
  2599. // Remove from the scene if mesh found
  2600. this.cameras.splice(index, 1);
  2601. }
  2602. // Remove from activeCameras
  2603. var index2 = this.activeCameras.indexOf(toRemove);
  2604. if (index2 !== -1) {
  2605. // Remove from the scene if mesh found
  2606. this.activeCameras.splice(index2, 1);
  2607. }
  2608. // Reset the activeCamera
  2609. if (this.activeCamera === toRemove) {
  2610. if (this.cameras.length > 0) {
  2611. this.activeCamera = this.cameras[0];
  2612. } else {
  2613. this.activeCamera = null;
  2614. }
  2615. }
  2616. this.onCameraRemovedObservable.notifyObservers(toRemove);
  2617. return index;
  2618. }
  2619. /**
  2620. * Remove a particle system for the list of scene's particle systems
  2621. * @param toRemove defines the particle system to remove
  2622. * @returns the index where the particle system was in the particle system list
  2623. */
  2624. public removeParticleSystem(toRemove: IParticleSystem): number {
  2625. var index = this.particleSystems.indexOf(toRemove);
  2626. if (index !== -1) {
  2627. this.particleSystems.splice(index, 1);
  2628. }
  2629. return index;
  2630. }
  2631. /**
  2632. * Remove a animation for the list of scene's animations
  2633. * @param toRemove defines the animation to remove
  2634. * @returns the index where the animation was in the animation list
  2635. */
  2636. public removeAnimation(toRemove: Animation): number {
  2637. var index = this.animations.indexOf(toRemove);
  2638. if (index !== -1) {
  2639. this.animations.splice(index, 1);
  2640. }
  2641. return index;
  2642. }
  2643. /**
  2644. * Removes the given animation group from this scene.
  2645. * @param toRemove The animation group to remove
  2646. * @returns The index of the removed animation group
  2647. */
  2648. public removeAnimationGroup(toRemove: AnimationGroup): number {
  2649. var index = this.animationGroups.indexOf(toRemove);
  2650. if (index !== -1) {
  2651. this.animationGroups.splice(index, 1);
  2652. }
  2653. return index;
  2654. }
  2655. /**
  2656. * Removes the given multi-material from this scene.
  2657. * @param toRemove The multi-material to remove
  2658. * @returns The index of the removed multi-material
  2659. */
  2660. public removeMultiMaterial(toRemove: MultiMaterial): number {
  2661. var index = this.multiMaterials.indexOf(toRemove);
  2662. if (index !== -1) {
  2663. this.multiMaterials.splice(index, 1);
  2664. }
  2665. return index;
  2666. }
  2667. /**
  2668. * Removes the given material from this scene.
  2669. * @param toRemove The material to remove
  2670. * @returns The index of the removed material
  2671. */
  2672. public removeMaterial(toRemove: Material): number {
  2673. var index = this.materials.indexOf(toRemove);
  2674. if (index !== -1) {
  2675. this.materials.splice(index, 1);
  2676. }
  2677. return index;
  2678. }
  2679. /**
  2680. * Removes the given action manager from this scene.
  2681. * @param toRemove The action manager to remove
  2682. * @returns The index of the removed action manager
  2683. */
  2684. public removeActionManager(toRemove: ActionManager): number {
  2685. var index = this.actionManagers.indexOf(toRemove);
  2686. if (index !== -1) {
  2687. this.actionManagers.splice(index, 1);
  2688. }
  2689. return index;
  2690. }
  2691. /**
  2692. * Removes the given texture from this scene.
  2693. * @param toRemove The texture to remove
  2694. * @returns The index of the removed texture
  2695. */
  2696. public removeTexture(toRemove: BaseTexture): number {
  2697. var index = this.textures.indexOf(toRemove);
  2698. if (index !== -1) {
  2699. this.textures.splice(index, 1);
  2700. }
  2701. return index;
  2702. }
  2703. /**
  2704. * Adds the given light to this scene
  2705. * @param newLight The light to add
  2706. */
  2707. public addLight(newLight: Light): void {
  2708. this.lights.push(newLight);
  2709. this.sortLightsByPriority();
  2710. // Add light to all meshes (To support if the light is removed and then readded)
  2711. for (var mesh of this.meshes) {
  2712. if (mesh._lightSources.indexOf(newLight) === -1) {
  2713. mesh._lightSources.push(newLight);
  2714. mesh._resyncLightSources();
  2715. }
  2716. }
  2717. this.onNewLightAddedObservable.notifyObservers(newLight);
  2718. }
  2719. /**
  2720. * Sorts the list list based on light priorities
  2721. */
  2722. public sortLightsByPriority(): void {
  2723. if (this.requireLightSorting) {
  2724. this.lights.sort(Light.CompareLightsPriority);
  2725. }
  2726. }
  2727. /**
  2728. * Adds the given camera to this scene
  2729. * @param newCamera The camera to add
  2730. */
  2731. public addCamera(newCamera: Camera): void {
  2732. this.cameras.push(newCamera);
  2733. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  2734. }
  2735. /**
  2736. * Adds the given skeleton to this scene
  2737. * @param newSkeleton The skeleton to add
  2738. */
  2739. public addSkeleton(newSkeleton: Skeleton): void {
  2740. this.skeletons.push(newSkeleton);
  2741. }
  2742. /**
  2743. * Adds the given particle system to this scene
  2744. * @param newParticleSystem The particle system to add
  2745. */
  2746. public addParticleSystem(newParticleSystem: IParticleSystem): void {
  2747. this.particleSystems.push(newParticleSystem);
  2748. }
  2749. /**
  2750. * Adds the given animation to this scene
  2751. * @param newAnimation The animation to add
  2752. */
  2753. public addAnimation(newAnimation: Animation): void {
  2754. this.animations.push(newAnimation);
  2755. }
  2756. /**
  2757. * Adds the given animation group to this scene.
  2758. * @param newAnimationGroup The animation group to add
  2759. */
  2760. public addAnimationGroup(newAnimationGroup: AnimationGroup): void {
  2761. this.animationGroups.push(newAnimationGroup);
  2762. }
  2763. /**
  2764. * Adds the given multi-material to this scene
  2765. * @param newMultiMaterial The multi-material to add
  2766. */
  2767. public addMultiMaterial(newMultiMaterial: MultiMaterial): void {
  2768. this.multiMaterials.push(newMultiMaterial);
  2769. }
  2770. /**
  2771. * Adds the given material to this scene
  2772. * @param newMaterial The material to add
  2773. */
  2774. public addMaterial(newMaterial: Material): void {
  2775. this.materials.push(newMaterial);
  2776. }
  2777. /**
  2778. * Adds the given morph target to this scene
  2779. * @param newMorphTargetManager The morph target to add
  2780. */
  2781. public addMorphTargetManager(newMorphTargetManager: MorphTargetManager): void {
  2782. this.morphTargetManagers.push(newMorphTargetManager);
  2783. }
  2784. /**
  2785. * Adds the given geometry to this scene
  2786. * @param newGeometry The geometry to add
  2787. */
  2788. public addGeometry(newGeometry: Geometry): void {
  2789. this.geometries.push(newGeometry);
  2790. }
  2791. /**
  2792. * Adds the given action manager to this scene
  2793. * @param newActionManager The action manager to add
  2794. */
  2795. public addActionManager(newActionManager: ActionManager): void {
  2796. this.actionManagers.push(newActionManager);
  2797. }
  2798. /**
  2799. * Adds the given texture to this scene.
  2800. * @param newTexture The texture to add
  2801. */
  2802. public addTexture(newTexture: BaseTexture): void {
  2803. this.textures.push(newTexture);
  2804. }
  2805. /**
  2806. * Switch active camera
  2807. * @param newCamera defines the new active camera
  2808. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  2809. */
  2810. public switchActiveCamera(newCamera: Camera, attachControl = true): void {
  2811. var canvas = this._engine.getRenderingCanvas();
  2812. if (!canvas) {
  2813. return;
  2814. }
  2815. if (this.activeCamera) {
  2816. this.activeCamera.detachControl(canvas);
  2817. }
  2818. this.activeCamera = newCamera;
  2819. if (attachControl) {
  2820. newCamera.attachControl(canvas);
  2821. }
  2822. }
  2823. /**
  2824. * sets the active camera of the scene using its ID
  2825. * @param id defines the camera's ID
  2826. * @return the new active camera or null if none found.
  2827. */
  2828. public setActiveCameraByID(id: string): Nullable<Camera> {
  2829. var camera = this.getCameraByID(id);
  2830. if (camera) {
  2831. this.activeCamera = camera;
  2832. return camera;
  2833. }
  2834. return null;
  2835. }
  2836. /**
  2837. * sets the active camera of the scene using its name
  2838. * @param name defines the camera's name
  2839. * @returns the new active camera or null if none found.
  2840. */
  2841. public setActiveCameraByName(name: string): Nullable<Camera> {
  2842. var camera = this.getCameraByName(name);
  2843. if (camera) {
  2844. this.activeCamera = camera;
  2845. return camera;
  2846. }
  2847. return null;
  2848. }
  2849. /**
  2850. * get an animation group using its name
  2851. * @param name defines the material's name
  2852. * @return the animation group or null if none found.
  2853. */
  2854. public getAnimationGroupByName(name: string): Nullable<AnimationGroup> {
  2855. for (var index = 0; index < this.animationGroups.length; index++) {
  2856. if (this.animationGroups[index].name === name) {
  2857. return this.animationGroups[index];
  2858. }
  2859. }
  2860. return null;
  2861. }
  2862. /**
  2863. * get a material using its id
  2864. * @param id defines the material's ID
  2865. * @return the material or null if none found.
  2866. */
  2867. public getMaterialByID(id: string): Nullable<Material> {
  2868. for (var index = 0; index < this.materials.length; index++) {
  2869. if (this.materials[index].id === id) {
  2870. return this.materials[index];
  2871. }
  2872. }
  2873. return null;
  2874. }
  2875. /**
  2876. * Gets a material using its name
  2877. * @param name defines the material's name
  2878. * @return the material or null if none found.
  2879. */
  2880. public getMaterialByName(name: string): Nullable<Material> {
  2881. for (var index = 0; index < this.materials.length; index++) {
  2882. if (this.materials[index].name === name) {
  2883. return this.materials[index];
  2884. }
  2885. }
  2886. return null;
  2887. }
  2888. /**
  2889. * Gets a camera using its id
  2890. * @param id defines the id to look for
  2891. * @returns the camera or null if not found
  2892. */
  2893. public getCameraByID(id: string): Nullable<Camera> {
  2894. for (var index = 0; index < this.cameras.length; index++) {
  2895. if (this.cameras[index].id === id) {
  2896. return this.cameras[index];
  2897. }
  2898. }
  2899. return null;
  2900. }
  2901. /**
  2902. * Gets a camera using its unique id
  2903. * @param uniqueId defines the unique id to look for
  2904. * @returns the camera or null if not found
  2905. */
  2906. public getCameraByUniqueID(uniqueId: number): Nullable<Camera> {
  2907. for (var index = 0; index < this.cameras.length; index++) {
  2908. if (this.cameras[index].uniqueId === uniqueId) {
  2909. return this.cameras[index];
  2910. }
  2911. }
  2912. return null;
  2913. }
  2914. /**
  2915. * Gets a camera using its name
  2916. * @param name defines the camera's name
  2917. * @return the camera or null if none found.
  2918. */
  2919. public getCameraByName(name: string): Nullable<Camera> {
  2920. for (var index = 0; index < this.cameras.length; index++) {
  2921. if (this.cameras[index].name === name) {
  2922. return this.cameras[index];
  2923. }
  2924. }
  2925. return null;
  2926. }
  2927. /**
  2928. * Gets a bone using its id
  2929. * @param id defines the bone's id
  2930. * @return the bone or null if not found
  2931. */
  2932. public getBoneByID(id: string): Nullable<Bone> {
  2933. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2934. var skeleton = this.skeletons[skeletonIndex];
  2935. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2936. if (skeleton.bones[boneIndex].id === id) {
  2937. return skeleton.bones[boneIndex];
  2938. }
  2939. }
  2940. }
  2941. return null;
  2942. }
  2943. /**
  2944. * Gets a bone using its id
  2945. * @param name defines the bone's name
  2946. * @return the bone or null if not found
  2947. */
  2948. public getBoneByName(name: string): Nullable<Bone> {
  2949. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2950. var skeleton = this.skeletons[skeletonIndex];
  2951. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2952. if (skeleton.bones[boneIndex].name === name) {
  2953. return skeleton.bones[boneIndex];
  2954. }
  2955. }
  2956. }
  2957. return null;
  2958. }
  2959. /**
  2960. * Gets a light node using its name
  2961. * @param name defines the the light's name
  2962. * @return the light or null if none found.
  2963. */
  2964. public getLightByName(name: string): Nullable<Light> {
  2965. for (var index = 0; index < this.lights.length; index++) {
  2966. if (this.lights[index].name === name) {
  2967. return this.lights[index];
  2968. }
  2969. }
  2970. return null;
  2971. }
  2972. /**
  2973. * Gets a light node using its id
  2974. * @param id defines the light's id
  2975. * @return the light or null if none found.
  2976. */
  2977. public getLightByID(id: string): Nullable<Light> {
  2978. for (var index = 0; index < this.lights.length; index++) {
  2979. if (this.lights[index].id === id) {
  2980. return this.lights[index];
  2981. }
  2982. }
  2983. return null;
  2984. }
  2985. /**
  2986. * Gets a light node using its scene-generated unique ID
  2987. * @param uniqueId defines the light's unique id
  2988. * @return the light or null if none found.
  2989. */
  2990. public getLightByUniqueID(uniqueId: number): Nullable<Light> {
  2991. for (var index = 0; index < this.lights.length; index++) {
  2992. if (this.lights[index].uniqueId === uniqueId) {
  2993. return this.lights[index];
  2994. }
  2995. }
  2996. return null;
  2997. }
  2998. /**
  2999. * Gets a particle system by id
  3000. * @param id defines the particle system id
  3001. * @return the corresponding system or null if none found
  3002. */
  3003. public getParticleSystemByID(id: string): Nullable<IParticleSystem> {
  3004. for (var index = 0; index < this.particleSystems.length; index++) {
  3005. if (this.particleSystems[index].id === id) {
  3006. return this.particleSystems[index];
  3007. }
  3008. }
  3009. return null;
  3010. }
  3011. /**
  3012. * Gets a geometry using its ID
  3013. * @param id defines the geometry's id
  3014. * @return the geometry or null if none found.
  3015. */
  3016. public getGeometryByID(id: string): Nullable<Geometry> {
  3017. for (var index = 0; index < this.geometries.length; index++) {
  3018. if (this.geometries[index].id === id) {
  3019. return this.geometries[index];
  3020. }
  3021. }
  3022. return null;
  3023. }
  3024. /**
  3025. * Add a new geometry to this scene
  3026. * @param geometry defines the geometry to be added to the scene.
  3027. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  3028. * @return a boolean defining if the geometry was added or not
  3029. */
  3030. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  3031. if (!force && this.getGeometryByID(geometry.id)) {
  3032. return false;
  3033. }
  3034. this.geometries.push(geometry);
  3035. //notify the collision coordinator
  3036. if (this.collisionCoordinator) {
  3037. this.collisionCoordinator.onGeometryAdded(geometry);
  3038. }
  3039. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  3040. return true;
  3041. }
  3042. /**
  3043. * Removes an existing geometry
  3044. * @param geometry defines the geometry to be removed from the scene
  3045. * @return a boolean defining if the geometry was removed or not
  3046. */
  3047. public removeGeometry(geometry: Geometry): boolean {
  3048. var index = this.geometries.indexOf(geometry);
  3049. if (index > -1) {
  3050. this.geometries.splice(index, 1);
  3051. //notify the collision coordinator
  3052. if (this.collisionCoordinator) {
  3053. this.collisionCoordinator.onGeometryDeleted(geometry);
  3054. }
  3055. this.onGeometryRemovedObservable.notifyObservers(geometry);
  3056. return true;
  3057. }
  3058. return false;
  3059. }
  3060. /**
  3061. * Gets the list of geometries attached to the scene
  3062. * @returns an array of Geometry
  3063. */
  3064. public getGeometries(): Geometry[] {
  3065. return this.geometries;
  3066. }
  3067. /**
  3068. * Gets the first added mesh found of a given ID
  3069. * @param id defines the id to search for
  3070. * @return the mesh found or null if not found at all
  3071. */
  3072. public getMeshByID(id: string): Nullable<AbstractMesh> {
  3073. for (var index = 0; index < this.meshes.length; index++) {
  3074. if (this.meshes[index].id === id) {
  3075. return this.meshes[index];
  3076. }
  3077. }
  3078. return null;
  3079. }
  3080. /**
  3081. * Gets a list of meshes using their id
  3082. * @param id defines the id to search for
  3083. * @returns a list of meshes
  3084. */
  3085. public getMeshesByID(id: string): Array<AbstractMesh> {
  3086. return this.meshes.filter(function (m) {
  3087. return m.id === id;
  3088. })
  3089. }
  3090. /**
  3091. * Gets the first added transform node found of a given ID
  3092. * @param id defines the id to search for
  3093. * @return the found transform node or null if not found at all.
  3094. */
  3095. public getTransformNodeByID(id: string): Nullable<TransformNode> {
  3096. for (var index = 0; index < this.transformNodes.length; index++) {
  3097. if (this.transformNodes[index].id === id) {
  3098. return this.transformNodes[index];
  3099. }
  3100. }
  3101. return null;
  3102. }
  3103. /**
  3104. * Gets a list of transform nodes using their id
  3105. * @param id defines the id to search for
  3106. * @returns a list of transform nodes
  3107. */
  3108. public getTransformNodesByID(id: string): Array<TransformNode> {
  3109. return this.transformNodes.filter(function (m) {
  3110. return m.id === id;
  3111. })
  3112. }
  3113. /**
  3114. * Gets a mesh with its auto-generated unique id
  3115. * @param uniqueId defines the unique id to search for
  3116. * @return the found mesh or null if not found at all.
  3117. */
  3118. public getMeshByUniqueID(uniqueId: number): Nullable<AbstractMesh> {
  3119. for (var index = 0; index < this.meshes.length; index++) {
  3120. if (this.meshes[index].uniqueId === uniqueId) {
  3121. return this.meshes[index];
  3122. }
  3123. }
  3124. return null;
  3125. }
  3126. /**
  3127. * Gets a the last added mesh using a given id
  3128. * @param id defines the id to search for
  3129. * @return the found mesh or null if not found at all.
  3130. */
  3131. public getLastMeshByID(id: string): Nullable<AbstractMesh> {
  3132. for (var index = this.meshes.length - 1; index >= 0; index--) {
  3133. if (this.meshes[index].id === id) {
  3134. return this.meshes[index];
  3135. }
  3136. }
  3137. return null;
  3138. }
  3139. /**
  3140. * Gets a the last added node (Mesh, Camera, Light) using a given id
  3141. * @param id defines the id to search for
  3142. * @return the found node or null if not found at all
  3143. */
  3144. public getLastEntryByID(id: string): Nullable<Node> {
  3145. var index: number;
  3146. for (index = this.meshes.length - 1; index >= 0; index--) {
  3147. if (this.meshes[index].id === id) {
  3148. return this.meshes[index];
  3149. }
  3150. }
  3151. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  3152. if (this.transformNodes[index].id === id) {
  3153. return this.transformNodes[index];
  3154. }
  3155. }
  3156. for (index = this.cameras.length - 1; index >= 0; index--) {
  3157. if (this.cameras[index].id === id) {
  3158. return this.cameras[index];
  3159. }
  3160. }
  3161. for (index = this.lights.length - 1; index >= 0; index--) {
  3162. if (this.lights[index].id === id) {
  3163. return this.lights[index];
  3164. }
  3165. }
  3166. return null;
  3167. }
  3168. /**
  3169. * Gets a node (Mesh, Camera, Light) using a given id
  3170. * @param id defines the id to search for
  3171. * @return the found node or null if not found at all
  3172. */
  3173. public getNodeByID(id: string): Nullable<Node> {
  3174. var mesh = this.getMeshByID(id);
  3175. if (mesh) {
  3176. return mesh;
  3177. }
  3178. var light = this.getLightByID(id);
  3179. if (light) {
  3180. return light;
  3181. }
  3182. var camera = this.getCameraByID(id);
  3183. if (camera) {
  3184. return camera;
  3185. }
  3186. var bone = this.getBoneByID(id);
  3187. return bone;
  3188. }
  3189. /**
  3190. * Gets a node (Mesh, Camera, Light) using a given name
  3191. * @param name defines the name to search for
  3192. * @return the found node or null if not found at all.
  3193. */
  3194. public getNodeByName(name: string): Nullable<Node> {
  3195. var mesh = this.getMeshByName(name);
  3196. if (mesh) {
  3197. return mesh;
  3198. }
  3199. var light = this.getLightByName(name);
  3200. if (light) {
  3201. return light;
  3202. }
  3203. var camera = this.getCameraByName(name);
  3204. if (camera) {
  3205. return camera;
  3206. }
  3207. var bone = this.getBoneByName(name);
  3208. return bone;
  3209. }
  3210. /**
  3211. * Gets a mesh using a given name
  3212. * @param name defines the name to search for
  3213. * @return the found mesh or null if not found at all.
  3214. */
  3215. public getMeshByName(name: string): Nullable<AbstractMesh> {
  3216. for (var index = 0; index < this.meshes.length; index++) {
  3217. if (this.meshes[index].name === name) {
  3218. return this.meshes[index];
  3219. }
  3220. }
  3221. return null;
  3222. }
  3223. /**
  3224. * Gets a transform node using a given name
  3225. * @param name defines the name to search for
  3226. * @return the found transform node or null if not found at all.
  3227. */
  3228. public getTransformNodeByName(name: string): Nullable<TransformNode> {
  3229. for (var index = 0; index < this.transformNodes.length; index++) {
  3230. if (this.transformNodes[index].name === name) {
  3231. return this.transformNodes[index];
  3232. }
  3233. }
  3234. return null;
  3235. }
  3236. /**
  3237. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  3238. * @param id defines the id to search for
  3239. * @return the found skeleton or null if not found at all.
  3240. */
  3241. public getLastSkeletonByID(id: string): Nullable<Skeleton> {
  3242. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  3243. if (this.skeletons[index].id === id) {
  3244. return this.skeletons[index];
  3245. }
  3246. }
  3247. return null;
  3248. }
  3249. /**
  3250. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  3251. * @param id defines the id to search for
  3252. * @return the found skeleton or null if not found at all.
  3253. */
  3254. public getSkeletonById(id: string): Nullable<Skeleton> {
  3255. for (var index = 0; index < this.skeletons.length; index++) {
  3256. if (this.skeletons[index].id === id) {
  3257. return this.skeletons[index];
  3258. }
  3259. }
  3260. return null;
  3261. }
  3262. /**
  3263. * Gets a skeleton using a given name
  3264. * @param name defines the name to search for
  3265. * @return the found skeleton or null if not found at all.
  3266. */
  3267. public getSkeletonByName(name: string): Nullable<Skeleton> {
  3268. for (var index = 0; index < this.skeletons.length; index++) {
  3269. if (this.skeletons[index].name === name) {
  3270. return this.skeletons[index];
  3271. }
  3272. }
  3273. return null;
  3274. }
  3275. /**
  3276. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  3277. * @param id defines the id to search for
  3278. * @return the found morph target manager or null if not found at all.
  3279. */
  3280. public getMorphTargetManagerById(id: number): Nullable<MorphTargetManager> {
  3281. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  3282. if (this.morphTargetManagers[index].uniqueId === id) {
  3283. return this.morphTargetManagers[index];
  3284. }
  3285. }
  3286. return null;
  3287. }
  3288. /**
  3289. * Gets a boolean indicating if the given mesh is active
  3290. * @param mesh defines the mesh to look for
  3291. * @returns true if the mesh is in the active list
  3292. */
  3293. public isActiveMesh(mesh: AbstractMesh): boolean {
  3294. return (this._activeMeshes.indexOf(mesh) !== -1);
  3295. }
  3296. /**
  3297. * Return a unique id as a string which can serve as an identifier for the scene
  3298. */
  3299. public get uid(): string {
  3300. if (!this._uid) {
  3301. this._uid = Tools.RandomId();
  3302. }
  3303. return this._uid;
  3304. }
  3305. /**
  3306. * Add an externaly attached data from its key.
  3307. * This method call will fail and return false, if such key already exists.
  3308. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3309. * @param key the unique key that identifies the data
  3310. * @param data the data object to associate to the key for this Engine instance
  3311. * @return true if no such key were already present and the data was added successfully, false otherwise
  3312. */
  3313. public addExternalData<T>(key: string, data: T): boolean {
  3314. if (!this._externalData) {
  3315. this._externalData = new StringDictionary<Object>();
  3316. }
  3317. return this._externalData.add(key, data);
  3318. }
  3319. /**
  3320. * Get an externaly attached data from its key
  3321. * @param key the unique key that identifies the data
  3322. * @return the associated data, if present (can be null), or undefined if not present
  3323. */
  3324. public getExternalData<T>(key: string): Nullable<T> {
  3325. if (!this._externalData) {
  3326. return null;
  3327. }
  3328. return <T>this._externalData.get(key);
  3329. }
  3330. /**
  3331. * Get an externaly attached data from its key, create it using a factory if it's not already present
  3332. * @param key the unique key that identifies the data
  3333. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3334. * @return the associated data, can be null if the factory returned null.
  3335. */
  3336. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  3337. if (!this._externalData) {
  3338. this._externalData = new StringDictionary<Object>();
  3339. }
  3340. return <T>this._externalData.getOrAddWithFactory(key, factory);
  3341. }
  3342. /**
  3343. * Remove an externaly attached data from the Engine instance
  3344. * @param key the unique key that identifies the data
  3345. * @return true if the data was successfully removed, false if it doesn't exist
  3346. */
  3347. public removeExternalData(key: string): boolean {
  3348. return this._externalData.remove(key);
  3349. }
  3350. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  3351. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  3352. for (let step of this._evaluateSubMeshStage) {
  3353. step.action(mesh, subMesh);
  3354. }
  3355. const material = subMesh.getMaterial();
  3356. if (material !== null && material !== undefined) {
  3357. // Render targets
  3358. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  3359. if (this._processedMaterials.indexOf(material) === -1) {
  3360. this._processedMaterials.push(material);
  3361. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  3362. }
  3363. }
  3364. // Dispatch
  3365. this._activeIndices.addCount(subMesh.indexCount, false);
  3366. this._renderingManager.dispatch(subMesh, mesh, material);
  3367. }
  3368. }
  3369. }
  3370. /**
  3371. * Clear the processed materials smart array preventing retention point in material dispose.
  3372. */
  3373. public freeProcessedMaterials(): void {
  3374. this._processedMaterials.dispose();
  3375. }
  3376. /**
  3377. * Clear the active meshes smart array preventing retention point in mesh dispose.
  3378. */
  3379. public freeActiveMeshes(): void {
  3380. this._activeMeshes.dispose();
  3381. if (this.activeCamera && this.activeCamera._activeMeshes) {
  3382. this.activeCamera._activeMeshes.dispose();
  3383. }
  3384. if (this.activeCameras) {
  3385. for (let i = 0; i < this.activeCameras.length; i++) {
  3386. let activeCamera = this.activeCameras[i];
  3387. if (activeCamera && activeCamera._activeMeshes) {
  3388. activeCamera._activeMeshes.dispose();
  3389. }
  3390. }
  3391. }
  3392. }
  3393. /**
  3394. * Clear the info related to rendering groups preventing retention points during dispose.
  3395. */
  3396. public freeRenderingGroups(): void {
  3397. if (this._renderingManager) {
  3398. this._renderingManager.freeRenderingGroups();
  3399. }
  3400. if (this.textures) {
  3401. for (let i = 0; i < this.textures.length; i++) {
  3402. let texture = this.textures[i];
  3403. if (texture && (<RenderTargetTexture>texture).renderList) {
  3404. (<RenderTargetTexture>texture).freeRenderingGroups();
  3405. }
  3406. }
  3407. }
  3408. }
  3409. /** @hidden */
  3410. public _isInIntermediateRendering(): boolean {
  3411. return this._intermediateRendering
  3412. }
  3413. /**
  3414. * Lambda returning the list of potentially active meshes.
  3415. */
  3416. public getActiveMeshCandidates: () => ISmartArrayLike<AbstractMesh>;
  3417. /**
  3418. * Lambda returning the list of potentially active sub meshes.
  3419. */
  3420. public getActiveSubMeshCandidates: (mesh: AbstractMesh) => ISmartArrayLike<SubMesh>;
  3421. /**
  3422. * Lambda returning the list of potentially intersecting sub meshes.
  3423. */
  3424. public getIntersectingSubMeshCandidates: (mesh: AbstractMesh, localRay: Ray) => ISmartArrayLike<SubMesh>;
  3425. /**
  3426. * Lambda returning the list of potentially colliding sub meshes.
  3427. */
  3428. public getCollidingSubMeshCandidates: (mesh: AbstractMesh, collider: Collider) => ISmartArrayLike<SubMesh>;
  3429. private _activeMeshesFrozen = false;
  3430. /**
  3431. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  3432. * @returns the current scene
  3433. */
  3434. public freezeActiveMeshes(): Scene {
  3435. if (!this.activeCamera) {
  3436. return this;
  3437. }
  3438. if (!this._frustumPlanes) {
  3439. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  3440. }
  3441. this._evaluateActiveMeshes();
  3442. this._activeMeshesFrozen = true;
  3443. return this;
  3444. }
  3445. /**
  3446. * Use this function to restart evaluating active meshes on every frame
  3447. * @returns the current scene
  3448. */
  3449. public unfreezeActiveMeshes(): Scene {
  3450. this._activeMeshesFrozen = false;
  3451. return this;
  3452. }
  3453. private _evaluateActiveMeshes(): void {
  3454. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  3455. return;
  3456. }
  3457. if (!this.activeCamera) {
  3458. return;
  3459. }
  3460. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  3461. this.activeCamera._activeMeshes.reset();
  3462. this._activeMeshes.reset();
  3463. this._renderingManager.reset();
  3464. this._processedMaterials.reset();
  3465. this._activeParticleSystems.reset();
  3466. this._activeSkeletons.reset();
  3467. this._softwareSkinnedMeshes.reset();
  3468. for (let step of this._beforeEvaluateActiveMeshStage) {
  3469. step.action();
  3470. }
  3471. // Determine mesh candidates
  3472. const meshes = this.getActiveMeshCandidates();
  3473. // Check each mesh
  3474. const len = meshes.length;
  3475. for (let i = 0; i < len; i++) {
  3476. const mesh = meshes.data[i];
  3477. if (mesh.isBlocked) {
  3478. continue;
  3479. }
  3480. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  3481. if (!mesh.isReady() || !mesh.isEnabled()) {
  3482. continue;
  3483. }
  3484. mesh.computeWorldMatrix();
  3485. // Intersections
  3486. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger)) {
  3487. this._meshesForIntersections.pushNoDuplicate(mesh);
  3488. }
  3489. // Switch to current LOD
  3490. const meshLOD = mesh.getLOD(this.activeCamera);
  3491. if (meshLOD === undefined || meshLOD === null) {
  3492. continue;
  3493. }
  3494. mesh._preActivate();
  3495. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  3496. this._activeMeshes.push(mesh);
  3497. this.activeCamera._activeMeshes.push(mesh);
  3498. mesh._activate(this._renderId);
  3499. if (meshLOD !== mesh) {
  3500. meshLOD._activate(this._renderId);
  3501. }
  3502. this._activeMesh(mesh, meshLOD);
  3503. }
  3504. }
  3505. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  3506. // Particle systems
  3507. if (this.particlesEnabled) {
  3508. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  3509. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  3510. var particleSystem = this.particleSystems[particleIndex];
  3511. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  3512. continue;
  3513. }
  3514. let emitter = <any>particleSystem.emitter;
  3515. if (!emitter.position || emitter.isEnabled()) {
  3516. this._activeParticleSystems.push(particleSystem);
  3517. particleSystem.animate();
  3518. this._renderingManager.dispatchParticles(particleSystem);
  3519. }
  3520. }
  3521. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  3522. }
  3523. }
  3524. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  3525. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  3526. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  3527. mesh.skeleton.prepare();
  3528. }
  3529. if (!mesh.computeBonesUsingShaders) {
  3530. this._softwareSkinnedMeshes.pushNoDuplicate(<Mesh>mesh);
  3531. }
  3532. }
  3533. for (let step of this._activeMeshStage) {
  3534. step.action(sourceMesh, mesh);
  3535. }
  3536. if (
  3537. mesh !== undefined && mesh !== null
  3538. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0
  3539. ) {
  3540. const subMeshes = this.getActiveSubMeshCandidates(mesh);
  3541. const len = subMeshes.length;
  3542. for (let i = 0; i < len; i++) {
  3543. const subMesh = subMeshes.data[i];
  3544. this._evaluateSubMesh(subMesh, mesh);
  3545. }
  3546. }
  3547. }
  3548. /**
  3549. * Update the transform matrix to update from the current active camera
  3550. * @param force defines a boolean used to force the update even if cache is up to date
  3551. */
  3552. public updateTransformMatrix(force?: boolean): void {
  3553. if (!this.activeCamera) {
  3554. return;
  3555. }
  3556. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  3557. }
  3558. /**
  3559. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  3560. * @param alternateCamera defines the camera to use
  3561. */
  3562. public updateAlternateTransformMatrix(alternateCamera: Camera): void {
  3563. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  3564. }
  3565. /** @hidden */
  3566. public _allowPostProcessClearColor = true;
  3567. private _renderForCamera(camera: Camera, rigParent?: Camera): void {
  3568. if (camera && camera._skipRendering) {
  3569. return;
  3570. }
  3571. var engine = this._engine;
  3572. this.activeCamera = camera;
  3573. if (!this.activeCamera)
  3574. throw new Error("Active camera not set");
  3575. // Viewport
  3576. engine.setViewport(this.activeCamera.viewport);
  3577. // Camera
  3578. this.resetCachedMaterial();
  3579. this._renderId++;
  3580. this.updateTransformMatrix();
  3581. if (camera._alternateCamera) {
  3582. this.updateAlternateTransformMatrix(camera._alternateCamera);
  3583. this._alternateRendering = true;
  3584. }
  3585. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  3586. // Meshes
  3587. this._evaluateActiveMeshes();
  3588. // Software skinning
  3589. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  3590. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  3591. mesh.applySkeleton(<Skeleton>mesh.skeleton);
  3592. }
  3593. // Render targets
  3594. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3595. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  3596. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  3597. }
  3598. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  3599. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  3600. }
  3601. // Collects render targets from external components.
  3602. for (let step of this._gatherActiveCameraRenderTargetsStage) {
  3603. step.action(this._renderTargets);
  3604. }
  3605. if (this.renderTargetsEnabled) {
  3606. this._intermediateRendering = true;
  3607. if (this._renderTargets.length > 0) {
  3608. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3609. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  3610. let renderTarget = this._renderTargets.data[renderIndex];
  3611. if (renderTarget._shouldRender()) {
  3612. this._renderId++;
  3613. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  3614. renderTarget.render((<boolean>hasSpecialRenderTargetCamera), this.dumpNextRenderTargets);
  3615. }
  3616. }
  3617. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3618. this._renderId++;
  3619. }
  3620. for (let step of this._cameraDrawRenderTargetStage) {
  3621. step.action(this.activeCamera);
  3622. }
  3623. this._intermediateRendering = false;
  3624. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  3625. }
  3626. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  3627. // Prepare Frame
  3628. if (this.postProcessManager) {
  3629. this.postProcessManager._prepareFrame();
  3630. }
  3631. // Before Camera Draw
  3632. for (let step of this._beforeCameraDrawStage) {
  3633. step.action(this.activeCamera);
  3634. }
  3635. // Render
  3636. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  3637. this._renderingManager.render(null, null, true, true);
  3638. this.onAfterDrawPhaseObservable.notifyObservers(this);
  3639. // After Camera Draw
  3640. for (let step of this._afterCameraDrawStage) {
  3641. step.action(this.activeCamera);
  3642. }
  3643. // Finalize frame
  3644. if (this.postProcessManager) {
  3645. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  3646. }
  3647. // Reset some special arrays
  3648. this._renderTargets.reset();
  3649. this._alternateRendering = false;
  3650. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  3651. }
  3652. private _processSubCameras(camera: Camera): void {
  3653. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  3654. this._renderForCamera(camera);
  3655. return;
  3656. }
  3657. // rig cameras
  3658. for (var index = 0; index < camera._rigCameras.length; index++) {
  3659. this._renderForCamera(camera._rigCameras[index], camera);
  3660. }
  3661. this.activeCamera = camera;
  3662. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  3663. }
  3664. private _checkIntersections(): void {
  3665. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  3666. var sourceMesh = this._meshesForIntersections.data[index];
  3667. if (!sourceMesh.actionManager) {
  3668. continue;
  3669. }
  3670. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  3671. var action = sourceMesh.actionManager.actions[actionIndex];
  3672. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3673. var parameters = action.getTriggerParameter();
  3674. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  3675. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  3676. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  3677. if (areIntersecting && currentIntersectionInProgress === -1) {
  3678. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  3679. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3680. sourceMesh._intersectionsInProgress.push(otherMesh);
  3681. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3682. sourceMesh._intersectionsInProgress.push(otherMesh);
  3683. }
  3684. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  3685. //They intersected, and now they don't.
  3686. //is this trigger an exit trigger? execute an event.
  3687. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3688. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3689. }
  3690. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  3691. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger, parameter => {
  3692. var parameterMesh = parameter instanceof AbstractMesh ? parameter : parameter.mesh;
  3693. return otherMesh === parameterMesh;
  3694. }) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3695. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  3696. }
  3697. }
  3698. }
  3699. }
  3700. }
  3701. }
  3702. /** @hidden */
  3703. public _advancePhysicsEngineStep(step: number) {
  3704. // Do nothing. Code will be replaced if physics engine component is referenced
  3705. }
  3706. /**
  3707. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  3708. */
  3709. public getDeterministicFrameTime: () => number = () => {
  3710. return 1000.0 / 60.0; // frame time in ms
  3711. }
  3712. /**
  3713. * Render the scene
  3714. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  3715. */
  3716. public render(updateCameras = true): void {
  3717. if (this.isDisposed) {
  3718. return;
  3719. }
  3720. this._frameId++;
  3721. // Register components that have been associated lately to the scene.
  3722. this._registerTransientComponents();
  3723. this._activeParticles.fetchNewFrame();
  3724. this._totalVertices.fetchNewFrame();
  3725. this._activeIndices.fetchNewFrame();
  3726. this._activeBones.fetchNewFrame();
  3727. this._meshesForIntersections.reset();
  3728. this.resetCachedMaterial();
  3729. this.onBeforeAnimationsObservable.notifyObservers(this);
  3730. // Actions
  3731. if (this.actionManager) {
  3732. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger);
  3733. }
  3734. if (this._engine.isDeterministicLockStep()) {
  3735. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  3736. var defaultFPS = (60.0 / 1000.0);
  3737. let defaultFrameTime = this.getDeterministicFrameTime();
  3738. let stepsTaken = 0;
  3739. var maxSubSteps = this._engine.getLockstepMaxSteps();
  3740. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  3741. internalSteps = Math.min(internalSteps, maxSubSteps);
  3742. do {
  3743. this.onBeforeStepObservable.notifyObservers(this);
  3744. // Animations
  3745. this._animationRatio = defaultFrameTime * defaultFPS;
  3746. this._animate();
  3747. this.onAfterAnimationsObservable.notifyObservers(this);
  3748. // Physics
  3749. this._advancePhysicsEngineStep(defaultFrameTime);
  3750. this.onAfterStepObservable.notifyObservers(this);
  3751. this._currentStepId++;
  3752. stepsTaken++;
  3753. deltaTime -= defaultFrameTime;
  3754. } while (deltaTime > 0 && stepsTaken < internalSteps);
  3755. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  3756. }
  3757. else {
  3758. // Animations
  3759. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  3760. this._animationRatio = deltaTime * (60.0 / 1000.0);
  3761. this._animate();
  3762. this.onAfterAnimationsObservable.notifyObservers(this);
  3763. // Physics
  3764. this._advancePhysicsEngineStep(deltaTime);
  3765. }
  3766. // Before camera update steps
  3767. for (let step of this._beforeCameraUpdateStage) {
  3768. step.action();
  3769. }
  3770. // Update Cameras
  3771. if (updateCameras) {
  3772. if (this.activeCameras.length > 0) {
  3773. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  3774. let camera = this.activeCameras[cameraIndex];
  3775. camera.update();
  3776. if (camera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  3777. // rig cameras
  3778. for (var index = 0; index < camera._rigCameras.length; index++) {
  3779. camera._rigCameras[index].update();
  3780. }
  3781. }
  3782. }
  3783. } else if (this.activeCamera) {
  3784. this.activeCamera.update();
  3785. if (this.activeCamera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  3786. // rig cameras
  3787. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  3788. this.activeCamera._rigCameras[index].update();
  3789. }
  3790. }
  3791. }
  3792. }
  3793. // Before render
  3794. this.onBeforeRenderObservable.notifyObservers(this);
  3795. // Customs render targets
  3796. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3797. var engine = this.getEngine();
  3798. var currentActiveCamera = this.activeCamera;
  3799. if (this.renderTargetsEnabled) {
  3800. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  3801. this._intermediateRendering = true;
  3802. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  3803. var renderTarget = this.customRenderTargets[customIndex];
  3804. if (renderTarget._shouldRender()) {
  3805. this._renderId++;
  3806. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  3807. if (!this.activeCamera)
  3808. throw new Error("Active camera not set");
  3809. // Viewport
  3810. engine.setViewport(this.activeCamera.viewport);
  3811. // Camera
  3812. this.updateTransformMatrix();
  3813. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  3814. }
  3815. }
  3816. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  3817. this._intermediateRendering = false;
  3818. this._renderId++;
  3819. }
  3820. // Restore back buffer
  3821. if (this.customRenderTargets.length > 0) {
  3822. engine.restoreDefaultFramebuffer();
  3823. }
  3824. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  3825. this.activeCamera = currentActiveCamera;
  3826. for (let step of this._beforeClearStage) {
  3827. step.action();
  3828. }
  3829. // Clear
  3830. if (this.autoClearDepthAndStencil || this.autoClear) {
  3831. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  3832. }
  3833. // Collects render targets from external components.
  3834. for (let step of this._gatherRenderTargetsStage) {
  3835. step.action(this._renderTargets);
  3836. }
  3837. // Multi-cameras?
  3838. if (this.activeCameras.length > 0) {
  3839. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  3840. if (cameraIndex > 0) {
  3841. this._engine.clear(null, false, true, true);
  3842. }
  3843. this._processSubCameras(this.activeCameras[cameraIndex]);
  3844. }
  3845. } else {
  3846. if (!this.activeCamera) {
  3847. throw new Error("No camera defined");
  3848. }
  3849. this._processSubCameras(this.activeCamera);
  3850. }
  3851. // Intersection checks
  3852. this._checkIntersections();
  3853. // Executes the after render stage actions.
  3854. for (let step of this._afterRenderStage) {
  3855. step.action();
  3856. }
  3857. // After render
  3858. if (this.afterRender) {
  3859. this.afterRender();
  3860. }
  3861. this.onAfterRenderObservable.notifyObservers(this);
  3862. // Cleaning
  3863. if (this._toBeDisposed.length) {
  3864. for (var index = 0; index < this._toBeDisposed.length; index++) {
  3865. var data = this._toBeDisposed[index];
  3866. if (data) {
  3867. data.dispose();
  3868. }
  3869. }
  3870. this._toBeDisposed = [];
  3871. }
  3872. if (this.dumpNextRenderTargets) {
  3873. this.dumpNextRenderTargets = false;
  3874. }
  3875. this._activeBones.addCount(0, true);
  3876. this._activeIndices.addCount(0, true);
  3877. this._activeParticles.addCount(0, true);
  3878. }
  3879. /**
  3880. * Freeze all materials
  3881. * A frozen material will not be updatable but should be faster to render
  3882. */
  3883. public freezeMaterials(): void {
  3884. for (var i = 0; i < this.materials.length; i++) {
  3885. this.materials[i].freeze();
  3886. }
  3887. }
  3888. /**
  3889. * Unfreeze all materials
  3890. * A frozen material will not be updatable but should be faster to render
  3891. */
  3892. public unfreezeMaterials(): void {
  3893. for (var i = 0; i < this.materials.length; i++) {
  3894. this.materials[i].unfreeze();
  3895. }
  3896. }
  3897. /**
  3898. * Releases all held ressources
  3899. */
  3900. public dispose(): void {
  3901. this.beforeRender = null;
  3902. this.afterRender = null;
  3903. this.skeletons = [];
  3904. this.morphTargetManagers = [];
  3905. this._transientComponents = [];
  3906. this._isReadyForMeshStage.clear();
  3907. this._beforeEvaluateActiveMeshStage.clear();
  3908. this._evaluateSubMeshStage.clear();
  3909. this._activeMeshStage.clear();
  3910. this._cameraDrawRenderTargetStage.clear();
  3911. this._beforeCameraDrawStage.clear();
  3912. this._beforeRenderingGroupDrawStage.clear();
  3913. this._beforeRenderingMeshStage.clear();
  3914. this._afterRenderingMeshStage.clear();
  3915. this._afterRenderingGroupDrawStage.clear();
  3916. this._afterCameraDrawStage.clear();
  3917. this._afterRenderStage.clear();
  3918. this._beforeCameraUpdateStage.clear();
  3919. this._beforeClearStage.clear();
  3920. this._gatherRenderTargetsStage.clear();
  3921. this._gatherActiveCameraRenderTargetsStage.clear();
  3922. this._pointerMoveStage.clear();
  3923. this._pointerDownStage.clear();
  3924. this._pointerUpStage.clear();
  3925. for (let component of this._components) {
  3926. component.dispose();
  3927. }
  3928. this.importedMeshesFiles = new Array<string>();
  3929. this.stopAllAnimations();
  3930. this.resetCachedMaterial();
  3931. // Smart arrays
  3932. if (this.activeCamera) {
  3933. this.activeCamera._activeMeshes.dispose();
  3934. this.activeCamera = null;
  3935. }
  3936. this._activeMeshes.dispose();
  3937. this._renderingManager.dispose();
  3938. this._processedMaterials.dispose();
  3939. this._activeParticleSystems.dispose();
  3940. this._activeSkeletons.dispose();
  3941. this._softwareSkinnedMeshes.dispose();
  3942. this._renderTargets.dispose();
  3943. this._registeredForLateAnimationBindings.dispose();
  3944. this._meshesForIntersections.dispose();
  3945. this._toBeDisposed = [];
  3946. // Abort active requests
  3947. for (let request of this._activeRequests) {
  3948. request.abort();
  3949. }
  3950. // Events
  3951. this.onDisposeObservable.notifyObservers(this);
  3952. this.onDisposeObservable.clear();
  3953. this.onBeforeRenderObservable.clear();
  3954. this.onAfterRenderObservable.clear();
  3955. this.onBeforeRenderTargetsRenderObservable.clear();
  3956. this.onAfterRenderTargetsRenderObservable.clear();
  3957. this.onAfterStepObservable.clear();
  3958. this.onBeforeStepObservable.clear();
  3959. this.onBeforeActiveMeshesEvaluationObservable.clear();
  3960. this.onAfterActiveMeshesEvaluationObservable.clear();
  3961. this.onBeforeParticlesRenderingObservable.clear();
  3962. this.onAfterParticlesRenderingObservable.clear();
  3963. this.onBeforeDrawPhaseObservable.clear();
  3964. this.onAfterDrawPhaseObservable.clear();
  3965. this.onBeforeAnimationsObservable.clear();
  3966. this.onAfterAnimationsObservable.clear();
  3967. this.onDataLoadedObservable.clear();
  3968. this.onBeforeRenderingGroupObservable.clear();
  3969. this.onAfterRenderingGroupObservable.clear();
  3970. this.onMeshImportedObservable.clear();
  3971. this.detachControl();
  3972. // Detach cameras
  3973. var canvas = this._engine.getRenderingCanvas();
  3974. if (canvas) {
  3975. var index;
  3976. for (index = 0; index < this.cameras.length; index++) {
  3977. this.cameras[index].detachControl(canvas);
  3978. }
  3979. }
  3980. // Release animation groups
  3981. while (this.animationGroups.length) {
  3982. this.animationGroups[0].dispose();
  3983. }
  3984. // Release lights
  3985. while (this.lights.length) {
  3986. this.lights[0].dispose();
  3987. }
  3988. // Release meshes
  3989. while (this.meshes.length) {
  3990. this.meshes[0].dispose(true);
  3991. }
  3992. while (this.transformNodes.length) {
  3993. this.removeTransformNode(this.transformNodes[0]);
  3994. }
  3995. // Release cameras
  3996. while (this.cameras.length) {
  3997. this.cameras[0].dispose();
  3998. }
  3999. // Release materials
  4000. if (this.defaultMaterial) {
  4001. this.defaultMaterial.dispose()
  4002. }
  4003. while (this.multiMaterials.length) {
  4004. this.multiMaterials[0].dispose();
  4005. }
  4006. while (this.materials.length) {
  4007. this.materials[0].dispose();
  4008. }
  4009. // Release particles
  4010. while (this.particleSystems.length) {
  4011. this.particleSystems[0].dispose();
  4012. }
  4013. // Release postProcesses
  4014. while (this.postProcesses.length) {
  4015. this.postProcesses[0].dispose();
  4016. }
  4017. // Release textures
  4018. while (this.textures.length) {
  4019. this.textures[0].dispose();
  4020. }
  4021. // Release UBO
  4022. this._sceneUbo.dispose();
  4023. if (this._alternateSceneUbo) {
  4024. this._alternateSceneUbo.dispose();
  4025. }
  4026. // Post-processes
  4027. this.postProcessManager.dispose();
  4028. // Remove from engine
  4029. index = this._engine.scenes.indexOf(this);
  4030. if (index > -1) {
  4031. this._engine.scenes.splice(index, 1);
  4032. }
  4033. this._engine.wipeCaches(true);
  4034. this._isDisposed = true;
  4035. }
  4036. /**
  4037. * Gets if the scene is already disposed
  4038. */
  4039. public get isDisposed(): boolean {
  4040. return this._isDisposed;
  4041. }
  4042. /**
  4043. * Call this function to reduce memory footprint of the scene.
  4044. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  4045. */
  4046. public clearCachedVertexData(): void {
  4047. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4048. var mesh = this.meshes[meshIndex];
  4049. var geometry = (<Mesh>mesh).geometry;
  4050. if (geometry) {
  4051. geometry._indices = [];
  4052. for (var vbName in geometry._vertexBuffers) {
  4053. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  4054. continue;
  4055. }
  4056. geometry._vertexBuffers[vbName]._buffer._data = null;
  4057. }
  4058. }
  4059. }
  4060. }
  4061. /**
  4062. * This function will remove the local cached buffer data from texture.
  4063. * It will save memory but will prevent the texture from being rebuilt
  4064. */
  4065. public cleanCachedTextureBuffer(): void {
  4066. for (var baseTexture of this.textures) {
  4067. let buffer = (<Texture>baseTexture)._buffer;
  4068. if (buffer) {
  4069. (<Texture>baseTexture)._buffer = null;
  4070. }
  4071. }
  4072. }
  4073. /**
  4074. * Get the world extend vectors with an optional filter
  4075. *
  4076. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  4077. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  4078. */
  4079. public getWorldExtends(filterPredicate?: (mesh: AbstractMesh) => boolean): { min: Vector3; max: Vector3 } {
  4080. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4081. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4082. filterPredicate = filterPredicate || (() => true);
  4083. this.meshes.filter(filterPredicate).forEach(mesh => {
  4084. mesh.computeWorldMatrix(true);
  4085. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  4086. return;
  4087. }
  4088. let boundingInfo = mesh.getBoundingInfo();
  4089. var minBox = boundingInfo.boundingBox.minimumWorld;
  4090. var maxBox = boundingInfo.boundingBox.maximumWorld;
  4091. Tools.CheckExtends(minBox, min, max);
  4092. Tools.CheckExtends(maxBox, min, max);
  4093. })
  4094. return {
  4095. min: min,
  4096. max: max
  4097. };
  4098. }
  4099. // Picking
  4100. /**
  4101. * Creates a ray that can be used to pick in the scene
  4102. * @param x defines the x coordinate of the origin (on-screen)
  4103. * @param y defines the y coordinate of the origin (on-screen)
  4104. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  4105. * @param camera defines the camera to use for the picking
  4106. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  4107. * @returns a Ray
  4108. */
  4109. public createPickingRay(x: number, y: number, world: Matrix, camera: Nullable<Camera>, cameraViewSpace = false): Ray {
  4110. let result = Ray.Zero();
  4111. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  4112. return result;
  4113. }
  4114. /**
  4115. * Creates a ray that can be used to pick in the scene
  4116. * @param x defines the x coordinate of the origin (on-screen)
  4117. * @param y defines the y coordinate of the origin (on-screen)
  4118. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  4119. * @param result defines the ray where to store the picking ray
  4120. * @param camera defines the camera to use for the picking
  4121. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  4122. * @returns the current scene
  4123. */
  4124. public createPickingRayToRef(x: number, y: number, world: Matrix, result: Ray, camera: Nullable<Camera>, cameraViewSpace = false): Scene {
  4125. var engine = this._engine;
  4126. if (!camera) {
  4127. if (!this.activeCamera)
  4128. throw new Error("Active camera not set");
  4129. camera = this.activeCamera;
  4130. }
  4131. var cameraViewport = camera.viewport;
  4132. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4133. // Moving coordinates to local viewport world
  4134. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  4135. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  4136. result.update(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  4137. return this;
  4138. }
  4139. /**
  4140. * Creates a ray that can be used to pick in the scene
  4141. * @param x defines the x coordinate of the origin (on-screen)
  4142. * @param y defines the y coordinate of the origin (on-screen)
  4143. * @param camera defines the camera to use for the picking
  4144. * @returns a Ray
  4145. */
  4146. public createPickingRayInCameraSpace(x: number, y: number, camera?: Camera): Ray {
  4147. let result = Ray.Zero();
  4148. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  4149. return result;
  4150. }
  4151. /**
  4152. * Creates a ray that can be used to pick in the scene
  4153. * @param x defines the x coordinate of the origin (on-screen)
  4154. * @param y defines the y coordinate of the origin (on-screen)
  4155. * @param result defines the ray where to store the picking ray
  4156. * @param camera defines the camera to use for the picking
  4157. * @returns the current scene
  4158. */
  4159. public createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene {
  4160. if (!PickingInfo) {
  4161. return this;
  4162. }
  4163. var engine = this._engine;
  4164. if (!camera) {
  4165. if (!this.activeCamera)
  4166. throw new Error("Active camera not set");
  4167. camera = this.activeCamera;
  4168. }
  4169. var cameraViewport = camera.viewport;
  4170. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4171. var identity = Matrix.Identity();
  4172. // Moving coordinates to local viewport world
  4173. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  4174. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  4175. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  4176. return this;
  4177. }
  4178. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  4179. if (!PickingInfo) {
  4180. return null;
  4181. }
  4182. var pickingInfo = null;
  4183. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4184. var mesh = this.meshes[meshIndex];
  4185. if (predicate) {
  4186. if (!predicate(mesh)) {
  4187. continue;
  4188. }
  4189. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  4190. continue;
  4191. }
  4192. var world = mesh.getWorldMatrix();
  4193. var ray = rayFunction(world);
  4194. var result = mesh.intersects(ray, fastCheck);
  4195. if (!result || !result.hit)
  4196. continue;
  4197. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  4198. continue;
  4199. pickingInfo = result;
  4200. if (fastCheck) {
  4201. break;
  4202. }
  4203. }
  4204. return pickingInfo || new PickingInfo();
  4205. }
  4206. private _internalMultiPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  4207. if (!PickingInfo) {
  4208. return null;
  4209. }
  4210. var pickingInfos = new Array<PickingInfo>();
  4211. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4212. var mesh = this.meshes[meshIndex];
  4213. if (predicate) {
  4214. if (!predicate(mesh)) {
  4215. continue;
  4216. }
  4217. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  4218. continue;
  4219. }
  4220. var world = mesh.getWorldMatrix();
  4221. var ray = rayFunction(world);
  4222. var result = mesh.intersects(ray, false);
  4223. if (!result || !result.hit)
  4224. continue;
  4225. pickingInfos.push(result);
  4226. }
  4227. return pickingInfos;
  4228. }
  4229. private _tempPickingRay: Nullable<Ray> = Ray ? Ray.Zero() : null;
  4230. /** Launch a ray to try to pick a mesh in the scene
  4231. * @param x position on screen
  4232. * @param y position on screen
  4233. * @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
  4234. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  4235. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4236. * @returns a PickingInfo
  4237. */
  4238. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Nullable<Camera>): Nullable<PickingInfo> {
  4239. if (!PickingInfo) {
  4240. return null;
  4241. }
  4242. var result = this._internalPick(world => {
  4243. this.createPickingRayToRef(x, y, world, this._tempPickingRay!, camera || null);
  4244. return this._tempPickingRay!;
  4245. }, predicate, fastCheck);
  4246. if (result) {
  4247. result.ray = this.createPickingRay(x, y, Matrix.Identity(), camera || null);
  4248. }
  4249. return result;
  4250. }
  4251. private _cachedRayForTransform: Ray;
  4252. /** Use the given ray to pick a mesh in the scene
  4253. * @param ray The ray to use to pick meshes
  4254. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  4255. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  4256. * @returns a PickingInfo
  4257. */
  4258. public pickWithRay(ray: Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  4259. var result = this._internalPick(world => {
  4260. if (!this._pickWithRayInverseMatrix) {
  4261. this._pickWithRayInverseMatrix = Matrix.Identity();
  4262. }
  4263. world.invertToRef(this._pickWithRayInverseMatrix);
  4264. if (!this._cachedRayForTransform) {
  4265. this._cachedRayForTransform = Ray.Zero();
  4266. }
  4267. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  4268. return this._cachedRayForTransform;
  4269. }, predicate, fastCheck);
  4270. if (result) {
  4271. result.ray = ray;
  4272. }
  4273. return result;
  4274. }
  4275. /**
  4276. * Launch a ray to try to pick a mesh in the scene
  4277. * @param x X position on screen
  4278. * @param y Y position on screen
  4279. * @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
  4280. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4281. * @returns an array of PickingInfo
  4282. */
  4283. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera): Nullable<PickingInfo[]> {
  4284. return this._internalMultiPick(world => this.createPickingRay(x, y, world, camera || null), predicate);
  4285. }
  4286. /**
  4287. * Launch a ray to try to pick a mesh in the scene
  4288. * @param ray Ray to use
  4289. * @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
  4290. * @returns an array of PickingInfo
  4291. */
  4292. public multiPickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  4293. return this._internalMultiPick(world => {
  4294. if (!this._pickWithRayInverseMatrix) {
  4295. this._pickWithRayInverseMatrix = Matrix.Identity();
  4296. }
  4297. world.invertToRef(this._pickWithRayInverseMatrix);
  4298. if (!this._cachedRayForTransform) {
  4299. this._cachedRayForTransform = Ray.Zero();
  4300. }
  4301. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  4302. return this._cachedRayForTransform;
  4303. }, predicate);
  4304. }
  4305. /**
  4306. * Force the value of meshUnderPointer
  4307. * @param mesh defines the mesh to use
  4308. */
  4309. public setPointerOverMesh(mesh: Nullable<AbstractMesh>): void {
  4310. if (this._pointerOverMesh === mesh) {
  4311. return;
  4312. }
  4313. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  4314. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  4315. }
  4316. this._pointerOverMesh = mesh;
  4317. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  4318. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  4319. }
  4320. }
  4321. /**
  4322. * Gets the mesh under the pointer
  4323. * @returns a Mesh or null if no mesh is under the pointer
  4324. */
  4325. public getPointerOverMesh(): Nullable<AbstractMesh> {
  4326. return this._pointerOverMesh;
  4327. }
  4328. // Misc.
  4329. /** @hidden */
  4330. public _rebuildGeometries(): void {
  4331. for (var geometry of this.geometries) {
  4332. geometry._rebuild();
  4333. }
  4334. for (var mesh of this.meshes) {
  4335. mesh._rebuild();
  4336. }
  4337. if (this.postProcessManager) {
  4338. this.postProcessManager._rebuild();
  4339. }
  4340. for (let component of this._components) {
  4341. component.rebuild();
  4342. }
  4343. for (var system of this.particleSystems) {
  4344. system.rebuild();
  4345. }
  4346. }
  4347. /** @hidden */
  4348. public _rebuildTextures(): void {
  4349. for (var texture of this.textures) {
  4350. texture._rebuild();
  4351. }
  4352. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  4353. }
  4354. // Tags
  4355. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  4356. if (tagsQuery === undefined) {
  4357. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  4358. return list;
  4359. }
  4360. var listByTags = [];
  4361. forEach = forEach || ((item: any) => { return; });
  4362. for (var i in list) {
  4363. var item = list[i];
  4364. if (Tags && Tags.MatchesQuery(item, tagsQuery)) {
  4365. listByTags.push(item);
  4366. forEach(item);
  4367. }
  4368. }
  4369. return listByTags;
  4370. }
  4371. /**
  4372. * Get a list of meshes by tags
  4373. * @param tagsQuery defines the tags query to use
  4374. * @param forEach defines a predicate used to filter results
  4375. * @returns an array of Mesh
  4376. */
  4377. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  4378. return this._getByTags(this.meshes, tagsQuery, forEach);
  4379. }
  4380. /**
  4381. * Get a list of cameras by tags
  4382. * @param tagsQuery defines the tags query to use
  4383. * @param forEach defines a predicate used to filter results
  4384. * @returns an array of Camera
  4385. */
  4386. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  4387. return this._getByTags(this.cameras, tagsQuery, forEach);
  4388. }
  4389. /**
  4390. * Get a list of lights by tags
  4391. * @param tagsQuery defines the tags query to use
  4392. * @param forEach defines a predicate used to filter results
  4393. * @returns an array of Light
  4394. */
  4395. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  4396. return this._getByTags(this.lights, tagsQuery, forEach);
  4397. }
  4398. /**
  4399. * Get a list of materials by tags
  4400. * @param tagsQuery defines the tags query to use
  4401. * @param forEach defines a predicate used to filter results
  4402. * @returns an array of Material
  4403. */
  4404. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  4405. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  4406. }
  4407. /**
  4408. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  4409. * This allowed control for front to back rendering or reversly depending of the special needs.
  4410. *
  4411. * @param renderingGroupId The rendering group id corresponding to its index
  4412. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  4413. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  4414. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  4415. */
  4416. public setRenderingOrder(renderingGroupId: number,
  4417. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  4418. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  4419. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  4420. this._renderingManager.setRenderingOrder(renderingGroupId,
  4421. opaqueSortCompareFn,
  4422. alphaTestSortCompareFn,
  4423. transparentSortCompareFn);
  4424. }
  4425. /**
  4426. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  4427. *
  4428. * @param renderingGroupId The rendering group id corresponding to its index
  4429. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  4430. * @param depth Automatically clears depth between groups if true and autoClear is true.
  4431. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  4432. */
  4433. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  4434. depth = true,
  4435. stencil = true): void {
  4436. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  4437. }
  4438. /**
  4439. * Gets the current auto clear configuration for one rendering group of the rendering
  4440. * manager.
  4441. * @param index the rendering group index to get the information for
  4442. * @returns The auto clear setup for the requested rendering group
  4443. */
  4444. public getAutoClearDepthStencilSetup(index: number): IRenderingManagerAutoClearSetup {
  4445. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  4446. }
  4447. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  4448. public blockMaterialDirtyMechanism = false;
  4449. /**
  4450. * Will flag all materials as dirty to trigger new shader compilation
  4451. * @param flag defines the flag used to specify which material part must be marked as dirty
  4452. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  4453. */
  4454. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  4455. if (this.blockMaterialDirtyMechanism) {
  4456. return;
  4457. }
  4458. for (var material of this.materials) {
  4459. if (predicate && !predicate(material)) {
  4460. continue;
  4461. }
  4462. material.markAsDirty(flag);
  4463. }
  4464. }
  4465. /** @hidden */
  4466. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, useDatabase?: boolean, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  4467. let request = Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  4468. this._activeRequests.push(request);
  4469. request.onCompleteObservable.add(request => {
  4470. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4471. });
  4472. return request;
  4473. }
  4474. /** @hidden */
  4475. public _loadFileAsync(url: string, useDatabase?: boolean, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  4476. return new Promise((resolve, reject) => {
  4477. this._loadFile(url, (data) => {
  4478. resolve(data);
  4479. }, undefined, useDatabase, useArrayBuffer, (request, exception) => {
  4480. reject(exception);
  4481. })
  4482. });
  4483. }
  4484. }
  4485. }