babylon.scene.ts 193 KB

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