engine.ts 307 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500
  1. import { Observer, Observable } from "../Misc/observable";
  2. import { PerformanceMonitor } from "../Misc/performanceMonitor";
  3. import { StringDictionary } from "../Misc/stringDictionary";
  4. import { PromisePolyfill } from "../Misc/promise";
  5. import { Tools, ICustomAnimationFrameRequester, PerfCounter, IFileRequest } from "../Misc/tools";
  6. import { Nullable, FloatArray, DataArray, IndicesArray } from "../types";
  7. import { Camera } from "../Cameras/camera";
  8. import { Scene } from "../scene";
  9. import { Matrix, Color3, Color4, Viewport, Size, Vector4 } from "../Maths/math";
  10. import { Scalar } from "../Maths/math.scalar";
  11. import { IDisplayChangedEventArgs } from "../Engines/engine";
  12. import { VertexBuffer } from "../Meshes/buffer";
  13. import { UniformBuffer } from "../Materials/uniformBuffer";
  14. import { Effect, EffectCreationOptions, EffectFallbacks } from "../Materials/effect";
  15. import { Material } from "../Materials/material";
  16. import { IInternalTextureTracker, DummyInternalTextureTracker } from "../Materials/Textures/internalTextureTracker";
  17. import { IInternalTextureLoader } from "../Materials/Textures/internalTextureLoader";
  18. import { InternalTexture } from "../Materials/Textures/internalTexture";
  19. import { BaseTexture } from "../Materials/Textures/baseTexture";
  20. import { IMultiRenderTargetOptions } from "../Materials/Textures/multiRenderTarget";
  21. import { _TimeToken } from "../Instrumentation/timeToken";
  22. import { IAudioEngine } from "../Audio/audioEngine";
  23. import { IOfflineProvider } from "../Offline/IOfflineProvider";
  24. import { ILoadingScreen } from "../Loading/loadingScreen";
  25. import { _DepthCullingState, _StencilState, _AlphaState } from "../States/index";
  26. import { Constants } from "./constants";
  27. import { DomManagement } from "../Misc/domManagement";
  28. import { Logger } from "../Misc/logger";
  29. import { EngineStore } from "./engineStore";
  30. import { RenderTargetCreationOptions } from "../Materials/Textures/renderTargetCreationOptions";
  31. import { _DevTools } from '../Misc/devTools';
  32. declare type PostProcess = import("../PostProcesses/postProcess").PostProcess;
  33. declare type Texture = import("../Materials/Textures/texture").Texture;
  34. declare type VideoTexture = import("../Materials/Textures/videoTexture").VideoTexture;
  35. declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
  36. /**
  37. * Keeps track of all the buffer info used in engine.
  38. */
  39. class BufferPointer {
  40. public active: boolean;
  41. public index: number;
  42. public size: number;
  43. public type: number;
  44. public normalized: boolean;
  45. public stride: number;
  46. public offset: number;
  47. public buffer: WebGLBuffer;
  48. }
  49. /**
  50. * Interface for attribute information associated with buffer instanciation
  51. */
  52. export class InstancingAttributeInfo {
  53. /**
  54. * Index/offset of the attribute in the vertex shader
  55. */
  56. index: number;
  57. /**
  58. * size of the attribute, 1, 2, 3 or 4
  59. */
  60. attributeSize: number;
  61. /**
  62. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  63. * default is FLOAT
  64. */
  65. attribyteType: number;
  66. /**
  67. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  68. */
  69. normalized: boolean;
  70. /**
  71. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  72. */
  73. offset: number;
  74. /**
  75. * Name of the GLSL attribute, for debugging purpose only
  76. */
  77. attributeName: string;
  78. }
  79. /**
  80. * Define options used to create a depth texture
  81. */
  82. export class DepthTextureCreationOptions {
  83. /** Specifies whether or not a stencil should be allocated in the texture */
  84. generateStencil?: boolean;
  85. /** Specifies whether or not bilinear filtering is enable on the texture */
  86. bilinearFiltering?: boolean;
  87. /** Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode */
  88. comparisonFunction?: number;
  89. /** Specifies if the created texture is a cube texture */
  90. isCube?: boolean;
  91. }
  92. /**
  93. * Class used to describe the capabilities of the engine relatively to the current browser
  94. */
  95. export class EngineCapabilities {
  96. /** Maximum textures units per fragment shader */
  97. public maxTexturesImageUnits: number;
  98. /** Maximum texture units per vertex shader */
  99. public maxVertexTextureImageUnits: number;
  100. /** Maximum textures units in the entire pipeline */
  101. public maxCombinedTexturesImageUnits: number;
  102. /** Maximum texture size */
  103. public maxTextureSize: number;
  104. /** Maximum cube texture size */
  105. public maxCubemapTextureSize: number;
  106. /** Maximum render texture size */
  107. public maxRenderTextureSize: number;
  108. /** Maximum number of vertex attributes */
  109. public maxVertexAttribs: number;
  110. /** Maximum number of varyings */
  111. public maxVaryingVectors: number;
  112. /** Maximum number of uniforms per vertex shader */
  113. public maxVertexUniformVectors: number;
  114. /** Maximum number of uniforms per fragment shader */
  115. public maxFragmentUniformVectors: number;
  116. /** Defines if standard derivates (dx/dy) are supported */
  117. public standardDerivatives: boolean;
  118. /** Defines if s3tc texture compression is supported */
  119. public s3tc: Nullable<WEBGL_compressed_texture_s3tc>;
  120. /** Defines if pvrtc texture compression is supported */
  121. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  122. /** Defines if etc1 texture compression is supported */
  123. public etc1: any; //WEBGL_compressed_texture_etc1;
  124. /** Defines if etc2 texture compression is supported */
  125. public etc2: any; //WEBGL_compressed_texture_etc;
  126. /** Defines if astc texture compression is supported */
  127. public astc: any; //WEBGL_compressed_texture_astc;
  128. /** Defines if float textures are supported */
  129. public textureFloat: boolean;
  130. /** Defines if vertex array objects are supported */
  131. public vertexArrayObject: boolean;
  132. /** Gets the webgl extension for anisotropic filtering (null if not supported) */
  133. public textureAnisotropicFilterExtension: Nullable<EXT_texture_filter_anisotropic>;
  134. /** Gets the maximum level of anisotropy supported */
  135. public maxAnisotropy: number;
  136. /** Defines if instancing is supported */
  137. public instancedArrays: boolean;
  138. /** Defines if 32 bits indices are supported */
  139. public uintIndices: boolean;
  140. /** Defines if high precision shaders are supported */
  141. public highPrecisionShaderSupported: boolean;
  142. /** Defines if depth reading in the fragment shader is supported */
  143. public fragmentDepthSupported: boolean;
  144. /** Defines if float texture linear filtering is supported*/
  145. public textureFloatLinearFiltering: boolean;
  146. /** Defines if rendering to float textures is supported */
  147. public textureFloatRender: boolean;
  148. /** Defines if half float textures are supported*/
  149. public textureHalfFloat: boolean;
  150. /** Defines if half float texture linear filtering is supported*/
  151. public textureHalfFloatLinearFiltering: boolean;
  152. /** Defines if rendering to half float textures is supported */
  153. public textureHalfFloatRender: boolean;
  154. /** Defines if textureLOD shader command is supported */
  155. public textureLOD: boolean;
  156. /** Defines if draw buffers extension is supported */
  157. public drawBuffersExtension: boolean;
  158. /** Defines if depth textures are supported */
  159. public depthTextureExtension: boolean;
  160. /** Defines if float color buffer are supported */
  161. public colorBufferFloat: boolean;
  162. /** Gets disjoint timer query extension (null if not supported) */
  163. public timerQuery: EXT_disjoint_timer_query;
  164. /** Defines if timestamp can be used with timer query */
  165. public canUseTimestampForTimerQuery: boolean;
  166. /** Function used to let the system compiles shaders in background */
  167. public parallelShaderCompile: {
  168. MAX_SHADER_COMPILER_THREADS_KHR: number;
  169. maxShaderCompilerThreadsKHR: (thread: number) => void;
  170. COMPLETION_STATUS_KHR: number;
  171. };
  172. }
  173. /** Interface defining initialization parameters for Engine class */
  174. export interface EngineOptions extends WebGLContextAttributes {
  175. /**
  176. * Defines if the engine should no exceed a specified device ratio
  177. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  178. */
  179. limitDeviceRatio?: number;
  180. /**
  181. * Defines if webvr should be enabled automatically
  182. * @see http://doc.babylonjs.com/how_to/webvr_camera
  183. */
  184. autoEnableWebVR?: boolean;
  185. /**
  186. * Defines if webgl2 should be turned off even if supported
  187. * @see http://doc.babylonjs.com/features/webgl2
  188. */
  189. disableWebGL2Support?: boolean;
  190. /**
  191. * Defines if webaudio should be initialized as well
  192. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  193. */
  194. audioEngine?: boolean;
  195. /**
  196. * Defines if animations should run using a deterministic lock step
  197. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  198. */
  199. deterministicLockstep?: boolean;
  200. /** Defines the maximum steps to use with deterministic lock step mode */
  201. lockstepMaxSteps?: number;
  202. /**
  203. * Defines that engine should ignore context lost events
  204. * If this event happens when this parameter is true, you will have to reload the page to restore rendering
  205. */
  206. doNotHandleContextLost?: boolean;
  207. /**
  208. * Defines that engine should ignore modifying touch action attribute and style
  209. * If not handle, you might need to set it up on your side for expected touch devices behavior.
  210. */
  211. doNotHandleTouchAction?: boolean;
  212. }
  213. /**
  214. * Defines the interface used by display changed events
  215. */
  216. export interface IDisplayChangedEventArgs {
  217. /** Gets the vrDisplay object (if any) */
  218. vrDisplay: Nullable<any>;
  219. /** Gets a boolean indicating if webVR is supported */
  220. vrSupported: boolean;
  221. }
  222. /**
  223. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  224. */
  225. export class Engine {
  226. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  227. public static ExceptionList = [
  228. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  229. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  230. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  231. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  232. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  233. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  234. ];
  235. /** Gets the list of created engines */
  236. public static get Instances(): Engine[] {
  237. return EngineStore.Instances;
  238. }
  239. /**
  240. * Gets the latest created engine
  241. */
  242. public static get LastCreatedEngine(): Nullable<Engine> {
  243. return EngineStore.LastCreatedEngine;
  244. }
  245. /**
  246. * Gets the latest created scene
  247. */
  248. public static get LastCreatedScene(): Nullable<Scene> {
  249. return EngineStore.LastCreatedScene;
  250. }
  251. /**
  252. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  253. * @param flag defines which part of the materials must be marked as dirty
  254. * @param predicate defines a predicate used to filter which materials should be affected
  255. */
  256. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  257. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  258. var engine = Engine.Instances[engineIndex];
  259. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  260. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  261. }
  262. }
  263. }
  264. /**
  265. * Hidden
  266. */
  267. public static _TextureLoaders: IInternalTextureLoader[] = [];
  268. // Const statics
  269. /** Defines that alpha blending is disabled */
  270. public static readonly ALPHA_DISABLE = Constants.ALPHA_DISABLE;
  271. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  272. public static readonly ALPHA_ADD = Constants.ALPHA_ADD;
  273. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  274. public static readonly ALPHA_COMBINE = Constants.ALPHA_COMBINE;
  275. /** Defines that alpha blending to DEST - SRC * DEST */
  276. public static readonly ALPHA_SUBTRACT = Constants.ALPHA_SUBTRACT;
  277. /** Defines that alpha blending to SRC * DEST */
  278. public static readonly ALPHA_MULTIPLY = Constants.ALPHA_MULTIPLY;
  279. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  280. public static readonly ALPHA_MAXIMIZED = Constants.ALPHA_MAXIMIZED;
  281. /** Defines that alpha blending to SRC + DEST */
  282. public static readonly ALPHA_ONEONE = Constants.ALPHA_ONEONE;
  283. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  284. public static readonly ALPHA_PREMULTIPLIED = Constants.ALPHA_PREMULTIPLIED;
  285. /**
  286. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  287. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  288. */
  289. public static readonly ALPHA_PREMULTIPLIED_PORTERDUFF = Constants.ALPHA_PREMULTIPLIED_PORTERDUFF;
  290. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  291. public static readonly ALPHA_INTERPOLATE = Constants.ALPHA_INTERPOLATE;
  292. /**
  293. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  294. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  295. */
  296. public static readonly ALPHA_SCREENMODE = Constants.ALPHA_SCREENMODE;
  297. /** Defines that the ressource is not delayed*/
  298. public static readonly DELAYLOADSTATE_NONE = Constants.DELAYLOADSTATE_NONE;
  299. /** Defines that the ressource was successfully delay loaded */
  300. public static readonly DELAYLOADSTATE_LOADED = Constants.DELAYLOADSTATE_LOADED;
  301. /** Defines that the ressource is currently delay loading */
  302. public static readonly DELAYLOADSTATE_LOADING = Constants.DELAYLOADSTATE_LOADING;
  303. /** Defines that the ressource is delayed and has not started loading */
  304. public static readonly DELAYLOADSTATE_NOTLOADED = Constants.DELAYLOADSTATE_NOTLOADED;
  305. // Depht or Stencil test Constants.
  306. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  307. public static readonly NEVER = Constants.NEVER;
  308. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
  309. public static readonly ALWAYS = Constants.ALWAYS;
  310. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  311. public static readonly LESS = Constants.LESS;
  312. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  313. public static readonly EQUAL = Constants.EQUAL;
  314. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
  315. public static readonly LEQUAL = Constants.LEQUAL;
  316. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  317. public static readonly GREATER = Constants.GREATER;
  318. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
  319. public static readonly GEQUAL = Constants.GEQUAL;
  320. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
  321. public static readonly NOTEQUAL = Constants.NOTEQUAL;
  322. // Stencil Actions Constants.
  323. /** Passed to stencilOperation to specify that stencil value must be kept */
  324. public static readonly KEEP = Constants.KEEP;
  325. /** Passed to stencilOperation to specify that stencil value must be replaced */
  326. public static readonly REPLACE = Constants.REPLACE;
  327. /** Passed to stencilOperation to specify that stencil value must be incremented */
  328. public static readonly INCR = Constants.INCR;
  329. /** Passed to stencilOperation to specify that stencil value must be decremented */
  330. public static readonly DECR = Constants.DECR;
  331. /** Passed to stencilOperation to specify that stencil value must be inverted */
  332. public static readonly INVERT = Constants.INVERT;
  333. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  334. public static readonly INCR_WRAP = Constants.INCR_WRAP;
  335. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  336. public static readonly DECR_WRAP = Constants.DECR_WRAP;
  337. /** Texture is not repeating outside of 0..1 UVs */
  338. public static readonly TEXTURE_CLAMP_ADDRESSMODE = Constants.TEXTURE_CLAMP_ADDRESSMODE;
  339. /** Texture is repeating outside of 0..1 UVs */
  340. public static readonly TEXTURE_WRAP_ADDRESSMODE = Constants.TEXTURE_WRAP_ADDRESSMODE;
  341. /** Texture is repeating and mirrored */
  342. public static readonly TEXTURE_MIRROR_ADDRESSMODE = Constants.TEXTURE_MIRROR_ADDRESSMODE;
  343. /** ALPHA */
  344. public static readonly TEXTUREFORMAT_ALPHA = Constants.TEXTUREFORMAT_ALPHA;
  345. /** LUMINANCE */
  346. public static readonly TEXTUREFORMAT_LUMINANCE = Constants.TEXTUREFORMAT_LUMINANCE;
  347. /** LUMINANCE_ALPHA */
  348. public static readonly TEXTUREFORMAT_LUMINANCE_ALPHA = Constants.TEXTUREFORMAT_LUMINANCE_ALPHA;
  349. /** RGB */
  350. public static readonly TEXTUREFORMAT_RGB = Constants.TEXTUREFORMAT_RGB;
  351. /** RGBA */
  352. public static readonly TEXTUREFORMAT_RGBA = Constants.TEXTUREFORMAT_RGBA;
  353. /** RED */
  354. public static readonly TEXTUREFORMAT_RED = Constants.TEXTUREFORMAT_RED;
  355. /** RED (2nd reference) */
  356. public static readonly TEXTUREFORMAT_R = Constants.TEXTUREFORMAT_R;
  357. /** RG */
  358. public static readonly TEXTUREFORMAT_RG = Constants.TEXTUREFORMAT_RG;
  359. /** RED_INTEGER */
  360. public static readonly TEXTUREFORMAT_RED_INTEGER = Constants.TEXTUREFORMAT_RED_INTEGER;
  361. /** RED_INTEGER (2nd reference) */
  362. public static readonly TEXTUREFORMAT_R_INTEGER = Constants.TEXTUREFORMAT_R_INTEGER;
  363. /** RG_INTEGER */
  364. public static readonly TEXTUREFORMAT_RG_INTEGER = Constants.TEXTUREFORMAT_RG_INTEGER;
  365. /** RGB_INTEGER */
  366. public static readonly TEXTUREFORMAT_RGB_INTEGER = Constants.TEXTUREFORMAT_RGB_INTEGER;
  367. /** RGBA_INTEGER */
  368. public static readonly TEXTUREFORMAT_RGBA_INTEGER = Constants.TEXTUREFORMAT_RGBA_INTEGER;
  369. /** UNSIGNED_BYTE */
  370. public static readonly TEXTURETYPE_UNSIGNED_BYTE = Constants.TEXTURETYPE_UNSIGNED_BYTE;
  371. /** UNSIGNED_BYTE (2nd reference) */
  372. public static readonly TEXTURETYPE_UNSIGNED_INT = Constants.TEXTURETYPE_UNSIGNED_INT;
  373. /** FLOAT */
  374. public static readonly TEXTURETYPE_FLOAT = Constants.TEXTURETYPE_FLOAT;
  375. /** HALF_FLOAT */
  376. public static readonly TEXTURETYPE_HALF_FLOAT = Constants.TEXTURETYPE_HALF_FLOAT;
  377. /** BYTE */
  378. public static readonly TEXTURETYPE_BYTE = Constants.TEXTURETYPE_BYTE;
  379. /** SHORT */
  380. public static readonly TEXTURETYPE_SHORT = Constants.TEXTURETYPE_SHORT;
  381. /** UNSIGNED_SHORT */
  382. public static readonly TEXTURETYPE_UNSIGNED_SHORT = Constants.TEXTURETYPE_UNSIGNED_SHORT;
  383. /** INT */
  384. public static readonly TEXTURETYPE_INT = Constants.TEXTURETYPE_INT;
  385. /** UNSIGNED_INT */
  386. public static readonly TEXTURETYPE_UNSIGNED_INTEGER = Constants.TEXTURETYPE_UNSIGNED_INTEGER;
  387. /** UNSIGNED_SHORT_4_4_4_4 */
  388. public static readonly TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4;
  389. /** UNSIGNED_SHORT_5_5_5_1 */
  390. public static readonly TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1;
  391. /** UNSIGNED_SHORT_5_6_5 */
  392. public static readonly TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5;
  393. /** UNSIGNED_INT_2_10_10_10_REV */
  394. public static readonly TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV;
  395. /** UNSIGNED_INT_24_8 */
  396. public static readonly TEXTURETYPE_UNSIGNED_INT_24_8 = Constants.TEXTURETYPE_UNSIGNED_INT_24_8;
  397. /** UNSIGNED_INT_10F_11F_11F_REV */
  398. public static readonly TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV;
  399. /** UNSIGNED_INT_5_9_9_9_REV */
  400. public static readonly TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV;
  401. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  402. public static readonly TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV;
  403. /** nearest is mag = nearest and min = nearest and mip = linear */
  404. public static readonly TEXTURE_NEAREST_SAMPLINGMODE = Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  405. /** Bilinear is mag = linear and min = linear and mip = nearest */
  406. public static readonly TEXTURE_BILINEAR_SAMPLINGMODE = Constants.TEXTURE_BILINEAR_SAMPLINGMODE;
  407. /** Trilinear is mag = linear and min = linear and mip = linear */
  408. public static readonly TEXTURE_TRILINEAR_SAMPLINGMODE = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  409. /** nearest is mag = nearest and min = nearest and mip = linear */
  410. public static readonly TEXTURE_NEAREST_NEAREST_MIPLINEAR = Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR;
  411. /** Bilinear is mag = linear and min = linear and mip = nearest */
  412. public static readonly TEXTURE_LINEAR_LINEAR_MIPNEAREST = Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST;
  413. /** Trilinear is mag = linear and min = linear and mip = linear */
  414. public static readonly TEXTURE_LINEAR_LINEAR_MIPLINEAR = Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR;
  415. /** mag = nearest and min = nearest and mip = nearest */
  416. public static readonly TEXTURE_NEAREST_NEAREST_MIPNEAREST = Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  417. /** mag = nearest and min = linear and mip = nearest */
  418. public static readonly TEXTURE_NEAREST_LINEAR_MIPNEAREST = Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  419. /** mag = nearest and min = linear and mip = linear */
  420. public static readonly TEXTURE_NEAREST_LINEAR_MIPLINEAR = Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  421. /** mag = nearest and min = linear and mip = none */
  422. public static readonly TEXTURE_NEAREST_LINEAR = Constants.TEXTURE_NEAREST_LINEAR;
  423. /** mag = nearest and min = nearest and mip = none */
  424. public static readonly TEXTURE_NEAREST_NEAREST = Constants.TEXTURE_NEAREST_NEAREST;
  425. /** mag = linear and min = nearest and mip = nearest */
  426. public static readonly TEXTURE_LINEAR_NEAREST_MIPNEAREST = Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  427. /** mag = linear and min = nearest and mip = linear */
  428. public static readonly TEXTURE_LINEAR_NEAREST_MIPLINEAR = Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  429. /** mag = linear and min = linear and mip = none */
  430. public static readonly TEXTURE_LINEAR_LINEAR = Constants.TEXTURE_LINEAR_LINEAR;
  431. /** mag = linear and min = nearest and mip = none */
  432. public static readonly TEXTURE_LINEAR_NEAREST = Constants.TEXTURE_LINEAR_NEAREST;
  433. /** Explicit coordinates mode */
  434. public static readonly TEXTURE_EXPLICIT_MODE = Constants.TEXTURE_EXPLICIT_MODE;
  435. /** Spherical coordinates mode */
  436. public static readonly TEXTURE_SPHERICAL_MODE = Constants.TEXTURE_SPHERICAL_MODE;
  437. /** Planar coordinates mode */
  438. public static readonly TEXTURE_PLANAR_MODE = Constants.TEXTURE_PLANAR_MODE;
  439. /** Cubic coordinates mode */
  440. public static readonly TEXTURE_CUBIC_MODE = Constants.TEXTURE_CUBIC_MODE;
  441. /** Projection coordinates mode */
  442. public static readonly TEXTURE_PROJECTION_MODE = Constants.TEXTURE_PROJECTION_MODE;
  443. /** Skybox coordinates mode */
  444. public static readonly TEXTURE_SKYBOX_MODE = Constants.TEXTURE_SKYBOX_MODE;
  445. /** Inverse Cubic coordinates mode */
  446. public static readonly TEXTURE_INVCUBIC_MODE = Constants.TEXTURE_INVCUBIC_MODE;
  447. /** Equirectangular coordinates mode */
  448. public static readonly TEXTURE_EQUIRECTANGULAR_MODE = Constants.TEXTURE_EQUIRECTANGULAR_MODE;
  449. /** Equirectangular Fixed coordinates mode */
  450. public static readonly TEXTURE_FIXED_EQUIRECTANGULAR_MODE = Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  451. /** Equirectangular Fixed Mirrored coordinates mode */
  452. public static readonly TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  453. // Texture rescaling mode
  454. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  455. public static readonly SCALEMODE_FLOOR = Constants.SCALEMODE_FLOOR;
  456. /** Defines that texture rescaling will look for the nearest power of 2 size */
  457. public static readonly SCALEMODE_NEAREST = Constants.SCALEMODE_NEAREST;
  458. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  459. public static readonly SCALEMODE_CEILING = Constants.SCALEMODE_CEILING;
  460. /**
  461. * Returns the current version of the framework
  462. */
  463. public static get Version(): string {
  464. return "4.0.0-alpha.19";
  465. }
  466. /**
  467. * Returns a string describing the current engine
  468. */
  469. public get description(): string {
  470. let description = "WebGL" + this.webGLVersion;
  471. if (this._caps.parallelShaderCompile) {
  472. description += " - Parallel shader compilation";
  473. }
  474. return description;
  475. }
  476. // Updatable statics so stick with vars here
  477. /**
  478. * Gets or sets the epsilon value used by collision engine
  479. */
  480. public static CollisionsEpsilon = 0.001;
  481. /**
  482. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  483. */
  484. public static get ShadersRepository(): string {
  485. return Effect.ShadersRepository;
  486. }
  487. public static set ShadersRepository(value: string) {
  488. Effect.ShadersRepository = value;
  489. }
  490. /**
  491. * Method called to create the default loading screen.
  492. * This can be overriden in your own app.
  493. * @param canvas The rendering canvas element
  494. * @returns The loading screen
  495. */
  496. public static DefaultLoadingScreenFactory(canvas: HTMLCanvasElement): ILoadingScreen {
  497. throw _DevTools.WarnImport("LoadingScreen");
  498. }
  499. /**
  500. * Method called to create the default rescale post process on each engine.
  501. */
  502. public static _RescalePostProcessFactory: Nullable<(engine: Engine) => PostProcess> = null;
  503. // Public members
  504. /**
  505. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  506. */
  507. public forcePOTTextures = false;
  508. /**
  509. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  510. */
  511. public isFullscreen = false;
  512. /**
  513. * Gets a boolean indicating if the pointer is currently locked
  514. */
  515. public isPointerLock = false;
  516. /**
  517. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  518. */
  519. public cullBackFaces = true;
  520. /**
  521. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  522. */
  523. public renderEvenInBackground = true;
  524. /**
  525. * Gets or sets a boolean indicating that cache can be kept between frames
  526. */
  527. public preventCacheWipeBetweenFrames = false;
  528. /**
  529. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  530. **/
  531. public enableOfflineSupport = false;
  532. /**
  533. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (js will always consider the database is up to date)
  534. **/
  535. public disableManifestCheck = false;
  536. /**
  537. * Gets the list of created scenes
  538. */
  539. public scenes = new Array<Scene>();
  540. /**
  541. * Event raised when a new scene is created
  542. */
  543. public onNewSceneAddedObservable = new Observable<Scene>();
  544. /**
  545. * Gets the list of created postprocesses
  546. */
  547. public postProcesses = new Array<PostProcess>();
  548. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  549. public validateShaderPrograms = false;
  550. // Observables
  551. /**
  552. * Observable event triggered each time the rendering canvas is resized
  553. */
  554. public onResizeObservable = new Observable<Engine>();
  555. /**
  556. * Observable event triggered each time the canvas loses focus
  557. */
  558. public onCanvasBlurObservable = new Observable<Engine>();
  559. /**
  560. * Observable event triggered each time the canvas gains focus
  561. */
  562. public onCanvasFocusObservable = new Observable<Engine>();
  563. /**
  564. * Observable event triggered each time the canvas receives pointerout event
  565. */
  566. public onCanvasPointerOutObservable = new Observable<PointerEvent>();
  567. /**
  568. * Observable event triggered before each texture is initialized
  569. */
  570. public onBeforeTextureInitObservable = new Observable<Texture>();
  571. //WebVR
  572. private _vrDisplay: any = undefined;
  573. private _vrSupported: boolean = false;
  574. private _oldSize: Size;
  575. private _oldHardwareScaleFactor: number;
  576. private _vrExclusivePointerMode = false;
  577. private _webVRInitPromise: Promise<IDisplayChangedEventArgs>;
  578. /**
  579. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  580. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  581. */
  582. public get isInVRExclusivePointerMode(): boolean {
  583. return this._vrExclusivePointerMode;
  584. }
  585. // Uniform buffers list
  586. /**
  587. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  588. */
  589. public disableUniformBuffers = false;
  590. /** @hidden */
  591. public _uniformBuffers = new Array<UniformBuffer>();
  592. /**
  593. * Gets a boolean indicating that the engine supports uniform buffers
  594. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  595. */
  596. public get supportsUniformBuffers(): boolean {
  597. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  598. }
  599. // Observables
  600. /**
  601. * Observable raised when the engine begins a new frame
  602. */
  603. public onBeginFrameObservable = new Observable<Engine>();
  604. /**
  605. * If set, will be used to request the next animation frame for the render loop
  606. */
  607. public customAnimationFrameRequester: Nullable<ICustomAnimationFrameRequester> = null;
  608. /**
  609. * Observable raised when the engine ends the current frame
  610. */
  611. public onEndFrameObservable = new Observable<Engine>();
  612. /**
  613. * Observable raised when the engine is about to compile a shader
  614. */
  615. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  616. /**
  617. * Observable raised when the engine has jsut compiled a shader
  618. */
  619. public onAfterShaderCompilationObservable = new Observable<Engine>();
  620. // Private Members
  621. /** @hidden */
  622. public _gl: WebGLRenderingContext;
  623. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  624. private _windowIsBackground = false;
  625. private _webGLVersion = 1.0;
  626. /**
  627. * Gets a boolean indicating that only power of 2 textures are supported
  628. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  629. */
  630. public get needPOTTextures(): boolean {
  631. return this._webGLVersion < 2 || this.forcePOTTextures;
  632. }
  633. /** @hidden */
  634. public _badOS = false;
  635. /** @hidden */
  636. public _badDesktopOS = false;
  637. /**
  638. * Gets or sets a value indicating if we want to disable texture binding optimization.
  639. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  640. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  641. */
  642. public disableTextureBindingOptimization = false;
  643. /**
  644. * Gets the audio engine
  645. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  646. * @ignorenaming
  647. */
  648. public static audioEngine: IAudioEngine;
  649. /**
  650. * Default AudioEngine factory responsible of creating the Audio Engine.
  651. * By default, this will create a BabylonJS Audio Engine if the workload has been embedded.
  652. */
  653. public static AudioEngineFactory: (hostElement: Nullable<HTMLElement>) => IAudioEngine;
  654. /**
  655. * Default offline support factory responsible of creating a tool used to store data locally.
  656. * By default, this will create a Database object if the workload has been embedded.
  657. */
  658. public static OfflineProviderFactory: (urlToScene: string, callbackManifestChecked: (checked: boolean) => any, disableManifestCheck: boolean) => IOfflineProvider;
  659. // Focus
  660. private _onFocus: () => void;
  661. private _onBlur: () => void;
  662. private _onCanvasPointerOut: (event: PointerEvent) => void;
  663. private _onCanvasBlur: () => void;
  664. private _onCanvasFocus: () => void;
  665. private _onFullscreenChange: () => void;
  666. private _onPointerLockChange: () => void;
  667. private _onVRDisplayPointerRestricted: () => void;
  668. private _onVRDisplayPointerUnrestricted: () => void;
  669. // VRDisplay connection
  670. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  671. private _onVrDisplayDisconnect: Nullable<() => void>;
  672. private _onVrDisplayPresentChange: Nullable<() => void>;
  673. /**
  674. * Observable signaled when VR display mode changes
  675. */
  676. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  677. /**
  678. * Observable signaled when VR request present is complete
  679. */
  680. public onVRRequestPresentComplete = new Observable<boolean>();
  681. /**
  682. * Observable signaled when VR request present starts
  683. */
  684. public onVRRequestPresentStart = new Observable<Engine>();
  685. private _hardwareScalingLevel: number;
  686. /** @hidden */
  687. protected _caps: EngineCapabilities;
  688. private _pointerLockRequested: boolean;
  689. private _isStencilEnable: boolean;
  690. private _colorWrite = true;
  691. private _loadingScreen: ILoadingScreen;
  692. /** @hidden */
  693. public _drawCalls = new PerfCounter();
  694. /** @hidden */
  695. public _textureCollisions = new PerfCounter();
  696. private _glVersion: string;
  697. private _glRenderer: string;
  698. private _glVendor: string;
  699. private _videoTextureSupported: boolean;
  700. private _renderingQueueLaunched = false;
  701. private _activeRenderLoops = new Array<() => void>();
  702. // Deterministic lockstepMaxSteps
  703. private _deterministicLockstep: boolean = false;
  704. private _lockstepMaxSteps: number = 4;
  705. // Lost context
  706. /**
  707. * Observable signaled when a context lost event is raised
  708. */
  709. public onContextLostObservable = new Observable<Engine>();
  710. /**
  711. * Observable signaled when a context restored event is raised
  712. */
  713. public onContextRestoredObservable = new Observable<Engine>();
  714. private _onContextLost: (evt: Event) => void;
  715. private _onContextRestored: (evt: Event) => void;
  716. private _contextWasLost = false;
  717. private _doNotHandleContextLost = false;
  718. /**
  719. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  720. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  721. */
  722. public get doNotHandleContextLost(): boolean {
  723. return this._doNotHandleContextLost;
  724. }
  725. public set doNotHandleContextLost(value: boolean) {
  726. this._doNotHandleContextLost = value;
  727. }
  728. // FPS
  729. private _performanceMonitor = new PerformanceMonitor();
  730. private _fps = 60;
  731. private _deltaTime = 0;
  732. /**
  733. * Turn this value on if you want to pause FPS computation when in background
  734. */
  735. public disablePerformanceMonitorInBackground = false;
  736. /**
  737. * Gets the performance monitor attached to this engine
  738. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  739. */
  740. public get performanceMonitor(): PerformanceMonitor {
  741. return this._performanceMonitor;
  742. }
  743. // States
  744. /** @hidden */
  745. protected _depthCullingState = new _DepthCullingState();
  746. /** @hidden */
  747. protected _stencilState = new _StencilState();
  748. /** @hidden */
  749. protected _alphaState = new _AlphaState();
  750. /** @hidden */
  751. protected _alphaMode = Engine.ALPHA_DISABLE;
  752. // Cache
  753. protected _internalTexturesCache = new Array<InternalTexture>();
  754. /** @hidden */
  755. protected _activeChannel = 0;
  756. private _currentTextureChannel = -1;
  757. /** @hidden */
  758. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  759. /** @hidden */
  760. protected _currentEffect: Nullable<Effect>;
  761. /** @hidden */
  762. protected _currentProgram: Nullable<WebGLProgram>;
  763. private _compiledEffects: { [key: string]: Effect } = {};
  764. private _vertexAttribArraysEnabled: boolean[] = [];
  765. /** @hidden */
  766. protected _cachedViewport: Nullable<Viewport>;
  767. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  768. /** @hidden */
  769. protected _cachedVertexBuffers: any;
  770. /** @hidden */
  771. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  772. /** @hidden */
  773. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  774. /** @hidden */
  775. protected _currentRenderTarget: Nullable<InternalTexture>;
  776. private _uintIndicesCurrentlySet = false;
  777. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  778. /** @hidden */
  779. protected _currentFramebuffer: Nullable<WebGLFramebuffer> = null;
  780. private _currentBufferPointers = new Array<BufferPointer>();
  781. private _currentInstanceLocations = new Array<number>();
  782. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  783. private _textureUnits: Int32Array;
  784. private _firstBoundInternalTextureTracker = new DummyInternalTextureTracker();
  785. private _lastBoundInternalTextureTracker = new DummyInternalTextureTracker();
  786. private _workingCanvas: Nullable<HTMLCanvasElement>;
  787. private _workingContext: Nullable<CanvasRenderingContext2D>;
  788. private _rescalePostProcess: PostProcess;
  789. private _dummyFramebuffer: WebGLFramebuffer;
  790. private _externalData: StringDictionary<Object>;
  791. private _bindedRenderFunction: any;
  792. private _vaoRecordInProgress = false;
  793. private _mustWipeVertexAttributes = false;
  794. private _emptyTexture: Nullable<InternalTexture>;
  795. private _emptyCubeTexture: Nullable<InternalTexture>;
  796. private _emptyTexture3D: Nullable<InternalTexture>;
  797. /** @hidden */
  798. public _frameHandler: number;
  799. private _nextFreeTextureSlots = new Array<number>();
  800. private _maxSimultaneousTextures = 0;
  801. private _activeRequests = new Array<IFileRequest>();
  802. // Hardware supported Compressed Textures
  803. private _texturesSupported = new Array<string>();
  804. private _textureFormatInUse: Nullable<string>;
  805. /**
  806. * Gets the list of texture formats supported
  807. */
  808. public get texturesSupported(): Array<string> {
  809. return this._texturesSupported;
  810. }
  811. /**
  812. * Gets the list of texture formats in use
  813. */
  814. public get textureFormatInUse(): Nullable<string> {
  815. return this._textureFormatInUse;
  816. }
  817. /**
  818. * Gets the current viewport
  819. */
  820. public get currentViewport(): Nullable<Viewport> {
  821. return this._cachedViewport;
  822. }
  823. /**
  824. * Gets the default empty texture
  825. */
  826. public get emptyTexture(): InternalTexture {
  827. if (!this._emptyTexture) {
  828. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  829. }
  830. return this._emptyTexture;
  831. }
  832. /**
  833. * Gets the default empty 3D texture
  834. */
  835. public get emptyTexture3D(): InternalTexture {
  836. if (!this._emptyTexture3D) {
  837. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  838. }
  839. return this._emptyTexture3D;
  840. }
  841. /**
  842. * Gets the default empty cube texture
  843. */
  844. public get emptyCubeTexture(): InternalTexture {
  845. if (!this._emptyCubeTexture) {
  846. var faceData = new Uint8Array(4);
  847. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  848. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  849. }
  850. return this._emptyCubeTexture;
  851. }
  852. /**
  853. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  854. */
  855. public readonly premultipliedAlpha: boolean = true;
  856. /**
  857. * Creates a new engine
  858. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  859. * @param antialias defines enable antialiasing (default: false)
  860. * @param options defines further options to be sent to the getContext() function
  861. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  862. */
  863. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  864. // Register promises
  865. PromisePolyfill.Apply();
  866. let canvas: Nullable<HTMLCanvasElement> = null;
  867. Engine.Instances.push(this);
  868. if (!canvasOrContext) {
  869. return;
  870. }
  871. options = options || {};
  872. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  873. canvas = <HTMLCanvasElement>canvasOrContext;
  874. this._renderingCanvas = canvas;
  875. if (antialias != null) {
  876. options.antialias = antialias;
  877. }
  878. if (options.deterministicLockstep === undefined) {
  879. options.deterministicLockstep = false;
  880. }
  881. if (options.lockstepMaxSteps === undefined) {
  882. options.lockstepMaxSteps = 4;
  883. }
  884. if (options.preserveDrawingBuffer === undefined) {
  885. options.preserveDrawingBuffer = false;
  886. }
  887. if (options.audioEngine === undefined) {
  888. options.audioEngine = true;
  889. }
  890. if (options.stencil === undefined) {
  891. options.stencil = true;
  892. }
  893. if (options.premultipliedAlpha === false) {
  894. this.premultipliedAlpha = false;
  895. }
  896. this._deterministicLockstep = options.deterministicLockstep;
  897. this._lockstepMaxSteps = options.lockstepMaxSteps;
  898. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  899. // Exceptions
  900. if (navigator && navigator.userAgent) {
  901. let ua = navigator.userAgent;
  902. for (var exception of Engine.ExceptionList) {
  903. let key = exception.key;
  904. let targets = exception.targets;
  905. if (ua.indexOf(key) > -1) {
  906. if (exception.capture && exception.captureConstraint) {
  907. let capture = exception.capture;
  908. let constraint = exception.captureConstraint;
  909. let regex = new RegExp(capture);
  910. let matches = regex.exec(ua);
  911. if (matches && matches.length > 0) {
  912. let capturedValue = parseInt(matches[matches.length - 1]);
  913. if (capturedValue >= constraint) {
  914. continue;
  915. }
  916. }
  917. }
  918. for (var target of targets) {
  919. switch (target) {
  920. case "uniformBuffer":
  921. this.disableUniformBuffers = true;
  922. break;
  923. case "textureBindingOptimization":
  924. this.disableTextureBindingOptimization = true;
  925. break;
  926. }
  927. }
  928. }
  929. }
  930. }
  931. // GL
  932. if (!options.disableWebGL2Support) {
  933. try {
  934. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  935. if (this._gl) {
  936. this._webGLVersion = 2.0;
  937. // Prevent weird browsers to lie :-)
  938. if (!this._gl.deleteQuery) {
  939. this._webGLVersion = 1.0;
  940. }
  941. }
  942. } catch (e) {
  943. // Do nothing
  944. }
  945. }
  946. if (!this._gl) {
  947. if (!canvas) {
  948. throw new Error("The provided canvas is null or undefined.");
  949. }
  950. try {
  951. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  952. } catch (e) {
  953. throw new Error("WebGL not supported");
  954. }
  955. }
  956. if (!this._gl) {
  957. throw new Error("WebGL not supported");
  958. }
  959. this._onCanvasFocus = () => {
  960. this.onCanvasFocusObservable.notifyObservers(this);
  961. };
  962. this._onCanvasBlur = () => {
  963. this.onCanvasBlurObservable.notifyObservers(this);
  964. };
  965. canvas.addEventListener("focus", this._onCanvasFocus);
  966. canvas.addEventListener("blur", this._onCanvasBlur);
  967. this._onBlur = () => {
  968. if (this.disablePerformanceMonitorInBackground) {
  969. this._performanceMonitor.disable();
  970. }
  971. this._windowIsBackground = true;
  972. };
  973. this._onFocus = () => {
  974. if (this.disablePerformanceMonitorInBackground) {
  975. this._performanceMonitor.enable();
  976. }
  977. this._windowIsBackground = false;
  978. };
  979. this._onCanvasPointerOut = (ev) => {
  980. this.onCanvasPointerOutObservable.notifyObservers(ev);
  981. };
  982. if (DomManagement.IsWindowObjectExist()) {
  983. window.addEventListener("blur", this._onBlur);
  984. window.addEventListener("focus", this._onFocus);
  985. }
  986. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  987. // Context lost
  988. if (!this._doNotHandleContextLost) {
  989. this._onContextLost = (evt: Event) => {
  990. evt.preventDefault();
  991. this._contextWasLost = true;
  992. Logger.Warn("WebGL context lost.");
  993. this.onContextLostObservable.notifyObservers(this);
  994. };
  995. this._onContextRestored = () => {
  996. // Adding a timeout to avoid race condition at browser level
  997. setTimeout(() => {
  998. // Rebuild gl context
  999. this._initGLContext();
  1000. // Rebuild effects
  1001. this._rebuildEffects();
  1002. // Rebuild textures
  1003. this._rebuildInternalTextures();
  1004. // Rebuild buffers
  1005. this._rebuildBuffers();
  1006. // Cache
  1007. this.wipeCaches(true);
  1008. Logger.Warn("WebGL context successfully restored.");
  1009. this.onContextRestoredObservable.notifyObservers(this);
  1010. this._contextWasLost = false;
  1011. }, 0);
  1012. };
  1013. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  1014. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  1015. }
  1016. if (!options.doNotHandleTouchAction) {
  1017. this._disableTouchAction();
  1018. }
  1019. } else {
  1020. this._gl = <WebGLRenderingContext>canvasOrContext;
  1021. this._renderingCanvas = this._gl.canvas;
  1022. if (this._gl.renderbufferStorageMultisample) {
  1023. this._webGLVersion = 2.0;
  1024. }
  1025. const attributes = this._gl.getContextAttributes();
  1026. if (attributes) {
  1027. options.stencil = attributes.stencil;
  1028. }
  1029. }
  1030. // Viewport
  1031. const devicePixelRatio = DomManagement.IsWindowObjectExist() ? (window.devicePixelRatio || 1.0) : 1.0;
  1032. var limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
  1033. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0;
  1034. this.resize();
  1035. this._isStencilEnable = options.stencil ? true : false;
  1036. this._initGLContext();
  1037. if (canvas) {
  1038. // Fullscreen
  1039. this._onFullscreenChange = () => {
  1040. if ((<any>document).fullscreen !== undefined) {
  1041. this.isFullscreen = (<any>document).fullscreen;
  1042. } else if (document.mozFullScreen !== undefined) {
  1043. this.isFullscreen = document.mozFullScreen;
  1044. } else if (document.webkitIsFullScreen !== undefined) {
  1045. this.isFullscreen = document.webkitIsFullScreen;
  1046. } else if (document.msIsFullScreen !== undefined) {
  1047. this.isFullscreen = document.msIsFullScreen;
  1048. }
  1049. // Pointer lock
  1050. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  1051. canvas.requestPointerLock = canvas.requestPointerLock ||
  1052. canvas.msRequestPointerLock ||
  1053. canvas.mozRequestPointerLock ||
  1054. canvas.webkitRequestPointerLock;
  1055. if (canvas.requestPointerLock) {
  1056. canvas.requestPointerLock();
  1057. }
  1058. }
  1059. };
  1060. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  1061. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  1062. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  1063. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  1064. // Pointer lock
  1065. this._onPointerLockChange = () => {
  1066. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  1067. document.webkitPointerLockElement === canvas ||
  1068. document.msPointerLockElement === canvas ||
  1069. document.pointerLockElement === canvas
  1070. );
  1071. };
  1072. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  1073. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  1074. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  1075. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  1076. this._onVRDisplayPointerRestricted = () => {
  1077. if (canvas) {
  1078. canvas.requestPointerLock();
  1079. }
  1080. };
  1081. this._onVRDisplayPointerUnrestricted = () => {
  1082. document.exitPointerLock();
  1083. };
  1084. if (DomManagement.IsWindowObjectExist()) {
  1085. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  1086. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  1087. }
  1088. }
  1089. // Create Audio Engine if needed.
  1090. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  1091. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  1092. }
  1093. // Prepare buffer pointers
  1094. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  1095. this._currentBufferPointers[i] = new BufferPointer();
  1096. }
  1097. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  1098. // Load WebVR Devices
  1099. if (options.autoEnableWebVR) {
  1100. this.initWebVR();
  1101. }
  1102. // Detect if we are running on a faulty buggy OS.
  1103. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  1104. // Detect if we are running on a faulty buggy desktop OS.
  1105. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  1106. console.log(`Babylon.js v${Engine.Version} - ${this.description}`);
  1107. this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;
  1108. }
  1109. private _disableTouchAction(): void {
  1110. if (!this._renderingCanvas) {
  1111. return;
  1112. }
  1113. this._renderingCanvas.setAttribute("touch-action", "none");
  1114. this._renderingCanvas.style.touchAction = "none";
  1115. this._renderingCanvas.style.msTouchAction = "none";
  1116. }
  1117. private _rebuildInternalTextures(): void {
  1118. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  1119. for (var internalTexture of currentState) {
  1120. internalTexture._rebuild();
  1121. }
  1122. }
  1123. private _rebuildEffects(): void {
  1124. for (var key in this._compiledEffects) {
  1125. let effect = <Effect>this._compiledEffects[key];
  1126. effect._prepareEffect();
  1127. }
  1128. Effect.ResetCache();
  1129. }
  1130. /**
  1131. * Gets a boolean indicating if all created effects are ready
  1132. * @returns true if all effects are ready
  1133. */
  1134. public areAllEffectsReady(): boolean {
  1135. for (var key in this._compiledEffects) {
  1136. let effect = <Effect>this._compiledEffects[key];
  1137. if (!effect.isReady()) {
  1138. return false;
  1139. }
  1140. }
  1141. return true;
  1142. }
  1143. private _rebuildBuffers(): void {
  1144. // Index / Vertex
  1145. for (var scene of this.scenes) {
  1146. scene.resetCachedMaterial();
  1147. scene._rebuildGeometries();
  1148. scene._rebuildTextures();
  1149. }
  1150. // Uniforms
  1151. for (var uniformBuffer of this._uniformBuffers) {
  1152. uniformBuffer._rebuild();
  1153. }
  1154. }
  1155. private _initGLContext(): void {
  1156. // Caps
  1157. this._caps = new EngineCapabilities();
  1158. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  1159. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  1160. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  1161. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  1162. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  1163. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  1164. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  1165. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  1166. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  1167. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  1168. // Infos
  1169. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  1170. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  1171. if (rendererInfo != null) {
  1172. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  1173. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  1174. }
  1175. if (!this._glVendor) {
  1176. this._glVendor = "Unknown vendor";
  1177. }
  1178. if (!this._glRenderer) {
  1179. this._glRenderer = "Unknown renderer";
  1180. }
  1181. // Constants
  1182. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  1183. if (this._gl.RGBA16F !== 0x881A) {
  1184. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  1185. }
  1186. if (this._gl.RGBA32F !== 0x8814) {
  1187. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  1188. }
  1189. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  1190. this._gl.DEPTH24_STENCIL8 = 35056;
  1191. }
  1192. // Extensions
  1193. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  1194. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  1195. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  1196. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  1197. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  1198. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  1199. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  1200. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  1201. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  1202. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  1203. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  1204. this._caps.highPrecisionShaderSupported = false;
  1205. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  1206. if (this._caps.timerQuery) {
  1207. if (this._webGLVersion === 1) {
  1208. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  1209. }
  1210. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  1211. }
  1212. // Checks if some of the format renders first to allow the use of webgl inspector.
  1213. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  1214. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  1215. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  1216. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  1217. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  1218. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  1219. if (this._webGLVersion > 1) {
  1220. this._gl.HALF_FLOAT_OES = 0x140B;
  1221. }
  1222. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  1223. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  1224. // Draw buffers
  1225. if (this._webGLVersion > 1) {
  1226. this._caps.drawBuffersExtension = true;
  1227. } else {
  1228. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1229. if (drawBuffersExtension !== null) {
  1230. this._caps.drawBuffersExtension = true;
  1231. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1232. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1233. for (var i = 0; i < 16; i++) {
  1234. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1235. }
  1236. } else {
  1237. this._caps.drawBuffersExtension = false;
  1238. }
  1239. }
  1240. // Shader compiler threads
  1241. this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile');
  1242. if (this._caps.parallelShaderCompile) {
  1243. const threads = this._gl.getParameter(this._caps.parallelShaderCompile.MAX_SHADER_COMPILER_THREADS_KHR);
  1244. this._caps.parallelShaderCompile.maxShaderCompilerThreadsKHR(threads);
  1245. }
  1246. // Depth Texture
  1247. if (this._webGLVersion > 1) {
  1248. this._caps.depthTextureExtension = true;
  1249. } else {
  1250. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1251. if (depthTextureExtension != null) {
  1252. this._caps.depthTextureExtension = true;
  1253. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  1254. }
  1255. }
  1256. // Vertex array object
  1257. if (this._webGLVersion > 1) {
  1258. this._caps.vertexArrayObject = true;
  1259. } else {
  1260. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1261. if (vertexArrayObjectExtension != null) {
  1262. this._caps.vertexArrayObject = true;
  1263. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1264. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1265. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1266. } else {
  1267. this._caps.vertexArrayObject = false;
  1268. }
  1269. }
  1270. // Instances count
  1271. if (this._webGLVersion > 1) {
  1272. this._caps.instancedArrays = true;
  1273. } else {
  1274. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1275. if (instanceExtension != null) {
  1276. this._caps.instancedArrays = true;
  1277. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1278. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1279. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1280. } else {
  1281. this._caps.instancedArrays = false;
  1282. }
  1283. }
  1284. // Intelligently add supported compressed formats in order to check for.
  1285. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1286. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1287. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1288. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1289. if (this._caps.astc) { this.texturesSupported.push('-astc.ktx'); }
  1290. if (this._caps.s3tc) { this.texturesSupported.push('-dxt.ktx'); }
  1291. if (this._caps.pvrtc) { this.texturesSupported.push('-pvrtc.ktx'); }
  1292. if (this._caps.etc2) { this.texturesSupported.push('-etc2.ktx'); }
  1293. if (this._caps.etc1) { this.texturesSupported.push('-etc1.ktx'); }
  1294. if (this._gl.getShaderPrecisionFormat) {
  1295. var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
  1296. var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1297. if (vertex_highp && fragment_highp) {
  1298. this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
  1299. }
  1300. }
  1301. // Depth buffer
  1302. this.setDepthBuffer(true);
  1303. this.setDepthFunctionToLessOrEqual();
  1304. this.setDepthWrite(true);
  1305. // Texture maps
  1306. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1307. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1308. this._nextFreeTextureSlots.push(slot);
  1309. }
  1310. }
  1311. /**
  1312. * Gets version of the current webGL context
  1313. */
  1314. public get webGLVersion(): number {
  1315. return this._webGLVersion;
  1316. }
  1317. /**
  1318. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1319. */
  1320. public get isStencilEnable(): boolean {
  1321. return this._isStencilEnable;
  1322. }
  1323. private _prepareWorkingCanvas(): void {
  1324. if (this._workingCanvas) {
  1325. return;
  1326. }
  1327. this._workingCanvas = document.createElement("canvas");
  1328. let context = this._workingCanvas.getContext("2d");
  1329. if (context) {
  1330. this._workingContext = context;
  1331. }
  1332. }
  1333. /**
  1334. * Reset the texture cache to empty state
  1335. */
  1336. public resetTextureCache() {
  1337. for (var key in this._boundTexturesCache) {
  1338. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  1339. continue;
  1340. }
  1341. let boundTexture = this._boundTexturesCache[key];
  1342. if (boundTexture) {
  1343. this._removeDesignatedSlot(boundTexture);
  1344. }
  1345. this._boundTexturesCache[key] = null;
  1346. }
  1347. if (!this.disableTextureBindingOptimization) {
  1348. this._nextFreeTextureSlots = [];
  1349. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1350. this._nextFreeTextureSlots.push(slot);
  1351. }
  1352. }
  1353. this._currentTextureChannel = -1;
  1354. }
  1355. /**
  1356. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  1357. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1358. * @returns true if engine is in deterministic lock step mode
  1359. */
  1360. public isDeterministicLockStep(): boolean {
  1361. return this._deterministicLockstep;
  1362. }
  1363. /**
  1364. * Gets the max steps when engine is running in deterministic lock step
  1365. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1366. * @returns the max steps
  1367. */
  1368. public getLockstepMaxSteps(): number {
  1369. return this._lockstepMaxSteps;
  1370. }
  1371. /**
  1372. * Gets an object containing information about the current webGL context
  1373. * @returns an object containing the vender, the renderer and the version of the current webGL context
  1374. */
  1375. public getGlInfo() {
  1376. return {
  1377. vendor: this._glVendor,
  1378. renderer: this._glRenderer,
  1379. version: this._glVersion
  1380. };
  1381. }
  1382. /**
  1383. * Gets current aspect ratio
  1384. * @param camera defines the camera to use to get the aspect ratio
  1385. * @param useScreen defines if screen size must be used (or the current render target if any)
  1386. * @returns a number defining the aspect ratio
  1387. */
  1388. public getAspectRatio(camera: Camera, useScreen = false): number {
  1389. var viewport = camera.viewport;
  1390. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1391. }
  1392. /**
  1393. * Gets current screen aspect ratio
  1394. * @returns a number defining the aspect ratio
  1395. */
  1396. public getScreenAspectRatio(): number {
  1397. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  1398. }
  1399. /**
  1400. * Gets the current render width
  1401. * @param useScreen defines if screen size must be used (or the current render target if any)
  1402. * @returns a number defining the current render width
  1403. */
  1404. public getRenderWidth(useScreen = false): number {
  1405. if (!useScreen && this._currentRenderTarget) {
  1406. return this._currentRenderTarget.width;
  1407. }
  1408. return this._gl.drawingBufferWidth;
  1409. }
  1410. /**
  1411. * Gets the current render height
  1412. * @param useScreen defines if screen size must be used (or the current render target if any)
  1413. * @returns a number defining the current render height
  1414. */
  1415. public getRenderHeight(useScreen = false): number {
  1416. if (!useScreen && this._currentRenderTarget) {
  1417. return this._currentRenderTarget.height;
  1418. }
  1419. return this._gl.drawingBufferHeight;
  1420. }
  1421. /**
  1422. * Gets the HTML canvas attached with the current webGL context
  1423. * @returns a HTML canvas
  1424. */
  1425. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1426. return this._renderingCanvas;
  1427. }
  1428. /**
  1429. * Gets the client rect of the HTML canvas attached with the current webGL context
  1430. * @returns a client rectanglee
  1431. */
  1432. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1433. if (!this._renderingCanvas) {
  1434. return null;
  1435. }
  1436. return this._renderingCanvas.getBoundingClientRect();
  1437. }
  1438. /**
  1439. * Defines the hardware scaling level.
  1440. * By default the hardware scaling level is computed from the window device ratio.
  1441. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  1442. * @param level defines the level to use
  1443. */
  1444. public setHardwareScalingLevel(level: number): void {
  1445. this._hardwareScalingLevel = level;
  1446. this.resize();
  1447. }
  1448. /**
  1449. * Gets the current hardware scaling level.
  1450. * By default the hardware scaling level is computed from the window device ratio.
  1451. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  1452. * @returns a number indicating the current hardware scaling level
  1453. */
  1454. public getHardwareScalingLevel(): number {
  1455. return this._hardwareScalingLevel;
  1456. }
  1457. /**
  1458. * Gets the list of loaded textures
  1459. * @returns an array containing all loaded textures
  1460. */
  1461. public getLoadedTexturesCache(): InternalTexture[] {
  1462. return this._internalTexturesCache;
  1463. }
  1464. /**
  1465. * Gets the object containing all engine capabilities
  1466. * @returns the EngineCapabilities object
  1467. */
  1468. public getCaps(): EngineCapabilities {
  1469. return this._caps;
  1470. }
  1471. /**
  1472. * Gets the current depth function
  1473. * @returns a number defining the depth function
  1474. */
  1475. public getDepthFunction(): Nullable<number> {
  1476. return this._depthCullingState.depthFunc;
  1477. }
  1478. /**
  1479. * Sets the current depth function
  1480. * @param depthFunc defines the function to use
  1481. */
  1482. public setDepthFunction(depthFunc: number) {
  1483. this._depthCullingState.depthFunc = depthFunc;
  1484. }
  1485. /**
  1486. * Sets the current depth function to GREATER
  1487. */
  1488. public setDepthFunctionToGreater(): void {
  1489. this._depthCullingState.depthFunc = this._gl.GREATER;
  1490. }
  1491. /**
  1492. * Sets the current depth function to GEQUAL
  1493. */
  1494. public setDepthFunctionToGreaterOrEqual(): void {
  1495. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1496. }
  1497. /**
  1498. * Sets the current depth function to LESS
  1499. */
  1500. public setDepthFunctionToLess(): void {
  1501. this._depthCullingState.depthFunc = this._gl.LESS;
  1502. }
  1503. /**
  1504. * Sets the current depth function to LEQUAL
  1505. */
  1506. public setDepthFunctionToLessOrEqual(): void {
  1507. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1508. }
  1509. /**
  1510. * Gets a boolean indicating if stencil buffer is enabled
  1511. * @returns the current stencil buffer state
  1512. */
  1513. public getStencilBuffer(): boolean {
  1514. return this._stencilState.stencilTest;
  1515. }
  1516. /**
  1517. * Enable or disable the stencil buffer
  1518. * @param enable defines if the stencil buffer must be enabled or disabled
  1519. */
  1520. public setStencilBuffer(enable: boolean): void {
  1521. this._stencilState.stencilTest = enable;
  1522. }
  1523. /**
  1524. * Gets the current stencil mask
  1525. * @returns a number defining the new stencil mask to use
  1526. */
  1527. public getStencilMask(): number {
  1528. return this._stencilState.stencilMask;
  1529. }
  1530. /**
  1531. * Sets the current stencil mask
  1532. * @param mask defines the new stencil mask to use
  1533. */
  1534. public setStencilMask(mask: number): void {
  1535. this._stencilState.stencilMask = mask;
  1536. }
  1537. /**
  1538. * Gets the current stencil function
  1539. * @returns a number defining the stencil function to use
  1540. */
  1541. public getStencilFunction(): number {
  1542. return this._stencilState.stencilFunc;
  1543. }
  1544. /**
  1545. * Gets the current stencil reference value
  1546. * @returns a number defining the stencil reference value to use
  1547. */
  1548. public getStencilFunctionReference(): number {
  1549. return this._stencilState.stencilFuncRef;
  1550. }
  1551. /**
  1552. * Gets the current stencil mask
  1553. * @returns a number defining the stencil mask to use
  1554. */
  1555. public getStencilFunctionMask(): number {
  1556. return this._stencilState.stencilFuncMask;
  1557. }
  1558. /**
  1559. * Sets the current stencil function
  1560. * @param stencilFunc defines the new stencil function to use
  1561. */
  1562. public setStencilFunction(stencilFunc: number) {
  1563. this._stencilState.stencilFunc = stencilFunc;
  1564. }
  1565. /**
  1566. * Sets the current stencil reference
  1567. * @param reference defines the new stencil reference to use
  1568. */
  1569. public setStencilFunctionReference(reference: number) {
  1570. this._stencilState.stencilFuncRef = reference;
  1571. }
  1572. /**
  1573. * Sets the current stencil mask
  1574. * @param mask defines the new stencil mask to use
  1575. */
  1576. public setStencilFunctionMask(mask: number) {
  1577. this._stencilState.stencilFuncMask = mask;
  1578. }
  1579. /**
  1580. * Gets the current stencil operation when stencil fails
  1581. * @returns a number defining stencil operation to use when stencil fails
  1582. */
  1583. public getStencilOperationFail(): number {
  1584. return this._stencilState.stencilOpStencilFail;
  1585. }
  1586. /**
  1587. * Gets the current stencil operation when depth fails
  1588. * @returns a number defining stencil operation to use when depth fails
  1589. */
  1590. public getStencilOperationDepthFail(): number {
  1591. return this._stencilState.stencilOpDepthFail;
  1592. }
  1593. /**
  1594. * Gets the current stencil operation when stencil passes
  1595. * @returns a number defining stencil operation to use when stencil passes
  1596. */
  1597. public getStencilOperationPass(): number {
  1598. return this._stencilState.stencilOpStencilDepthPass;
  1599. }
  1600. /**
  1601. * Sets the stencil operation to use when stencil fails
  1602. * @param operation defines the stencil operation to use when stencil fails
  1603. */
  1604. public setStencilOperationFail(operation: number): void {
  1605. this._stencilState.stencilOpStencilFail = operation;
  1606. }
  1607. /**
  1608. * Sets the stencil operation to use when depth fails
  1609. * @param operation defines the stencil operation to use when depth fails
  1610. */
  1611. public setStencilOperationDepthFail(operation: number): void {
  1612. this._stencilState.stencilOpDepthFail = operation;
  1613. }
  1614. /**
  1615. * Sets the stencil operation to use when stencil passes
  1616. * @param operation defines the stencil operation to use when stencil passes
  1617. */
  1618. public setStencilOperationPass(operation: number): void {
  1619. this._stencilState.stencilOpStencilDepthPass = operation;
  1620. }
  1621. /**
  1622. * Sets a boolean indicating if the dithering state is enabled or disabled
  1623. * @param value defines the dithering state
  1624. */
  1625. public setDitheringState(value: boolean): void {
  1626. if (value) {
  1627. this._gl.enable(this._gl.DITHER);
  1628. } else {
  1629. this._gl.disable(this._gl.DITHER);
  1630. }
  1631. }
  1632. /**
  1633. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  1634. * @param value defines the rasterizer state
  1635. */
  1636. public setRasterizerState(value: boolean): void {
  1637. if (value) {
  1638. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  1639. } else {
  1640. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  1641. }
  1642. }
  1643. /**
  1644. * stop executing a render loop function and remove it from the execution array
  1645. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  1646. */
  1647. public stopRenderLoop(renderFunction?: () => void): void {
  1648. if (!renderFunction) {
  1649. this._activeRenderLoops = [];
  1650. return;
  1651. }
  1652. var index = this._activeRenderLoops.indexOf(renderFunction);
  1653. if (index >= 0) {
  1654. this._activeRenderLoops.splice(index, 1);
  1655. }
  1656. }
  1657. /** @hidden */
  1658. public _renderLoop(): void {
  1659. if (!this._contextWasLost) {
  1660. var shouldRender = true;
  1661. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1662. shouldRender = false;
  1663. }
  1664. if (shouldRender) {
  1665. // Start new frame
  1666. this.beginFrame();
  1667. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1668. var renderFunction = this._activeRenderLoops[index];
  1669. renderFunction();
  1670. }
  1671. // Present
  1672. this.endFrame();
  1673. }
  1674. }
  1675. if (this._activeRenderLoops.length > 0) {
  1676. // Register new frame
  1677. if (this.customAnimationFrameRequester) {
  1678. this.customAnimationFrameRequester.requestID = Tools.QueueNewFrame(this.customAnimationFrameRequester.renderFunction || this._bindedRenderFunction, this.customAnimationFrameRequester);
  1679. this._frameHandler = this.customAnimationFrameRequester.requestID;
  1680. } else if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1681. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplay);
  1682. } else {
  1683. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1684. }
  1685. } else {
  1686. this._renderingQueueLaunched = false;
  1687. }
  1688. }
  1689. /**
  1690. * Register and execute a render loop. The engine can have more than one render function
  1691. * @param renderFunction defines the function to continuously execute
  1692. */
  1693. public runRenderLoop(renderFunction: () => void): void {
  1694. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1695. return;
  1696. }
  1697. this._activeRenderLoops.push(renderFunction);
  1698. if (!this._renderingQueueLaunched) {
  1699. this._renderingQueueLaunched = true;
  1700. this._bindedRenderFunction = this._renderLoop.bind(this);
  1701. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1702. }
  1703. }
  1704. /**
  1705. * Toggle full screen mode
  1706. * @param requestPointerLock defines if a pointer lock should be requested from the user
  1707. */
  1708. public switchFullscreen(requestPointerLock: boolean): void {
  1709. if (this.isFullscreen) {
  1710. Tools.ExitFullscreen();
  1711. } else {
  1712. this._pointerLockRequested = requestPointerLock;
  1713. if (this._renderingCanvas) {
  1714. Tools.RequestFullscreen(this._renderingCanvas);
  1715. }
  1716. }
  1717. }
  1718. /**
  1719. * Clear the current render buffer or the current render target (if any is set up)
  1720. * @param color defines the color to use
  1721. * @param backBuffer defines if the back buffer must be cleared
  1722. * @param depth defines if the depth buffer must be cleared
  1723. * @param stencil defines if the stencil buffer must be cleared
  1724. */
  1725. public clear(color: Nullable<Color4>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1726. this.applyStates();
  1727. var mode = 0;
  1728. if (backBuffer && color) {
  1729. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1730. mode |= this._gl.COLOR_BUFFER_BIT;
  1731. }
  1732. if (depth) {
  1733. this._gl.clearDepth(1.0);
  1734. mode |= this._gl.DEPTH_BUFFER_BIT;
  1735. }
  1736. if (stencil) {
  1737. this._gl.clearStencil(0);
  1738. mode |= this._gl.STENCIL_BUFFER_BIT;
  1739. }
  1740. this._gl.clear(mode);
  1741. }
  1742. /**
  1743. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  1744. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  1745. * @param y defines the y-coordinate of the corner of the clear rectangle
  1746. * @param width defines the width of the clear rectangle
  1747. * @param height defines the height of the clear rectangle
  1748. * @param clearColor defines the clear color
  1749. */
  1750. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1751. this.enableScissor(x, y, width, height);
  1752. this.clear(clearColor, true, true, true);
  1753. this.disableScissor();
  1754. }
  1755. /**
  1756. * Enable scissor test on a specific rectangle (ie. render will only be executed on a specific portion of the screen)
  1757. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  1758. * @param y defines the y-coordinate of the corner of the clear rectangle
  1759. * @param width defines the width of the clear rectangle
  1760. * @param height defines the height of the clear rectangle
  1761. */
  1762. public enableScissor(x: number, y: number, width: number, height: number): void {
  1763. let gl = this._gl;
  1764. // Change state
  1765. gl.enable(gl.SCISSOR_TEST);
  1766. gl.scissor(x, y, width, height);
  1767. }
  1768. /**
  1769. * Disable previously set scissor test rectangle
  1770. */
  1771. public disableScissor() {
  1772. let gl = this._gl;
  1773. gl.disable(gl.SCISSOR_TEST);
  1774. }
  1775. private _viewportCached = new Vector4(0, 0, 0, 0);
  1776. /** @hidden */
  1777. public _viewport(x: number, y: number, width: number, height: number): void {
  1778. if (x !== this._viewportCached.x ||
  1779. y !== this._viewportCached.y ||
  1780. width !== this._viewportCached.z ||
  1781. height !== this._viewportCached.w) {
  1782. this._viewportCached.x = x;
  1783. this._viewportCached.y = y;
  1784. this._viewportCached.z = width;
  1785. this._viewportCached.w = height;
  1786. this._gl.viewport(x, y, width, height);
  1787. }
  1788. }
  1789. /**
  1790. * Set the WebGL's viewport
  1791. * @param viewport defines the viewport element to be used
  1792. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  1793. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  1794. */
  1795. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1796. var width = requiredWidth || this.getRenderWidth();
  1797. var height = requiredHeight || this.getRenderHeight();
  1798. var x = viewport.x || 0;
  1799. var y = viewport.y || 0;
  1800. this._cachedViewport = viewport;
  1801. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1802. }
  1803. /**
  1804. * Directly set the WebGL Viewport
  1805. * @param x defines the x coordinate of the viewport (in screen space)
  1806. * @param y defines the y coordinate of the viewport (in screen space)
  1807. * @param width defines the width of the viewport (in screen space)
  1808. * @param height defines the height of the viewport (in screen space)
  1809. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
  1810. */
  1811. public setDirectViewport(x: number, y: number, width: number, height: number): Nullable<Viewport> {
  1812. let currentViewport = this._cachedViewport;
  1813. this._cachedViewport = null;
  1814. this._viewport(x, y, width, height);
  1815. return currentViewport;
  1816. }
  1817. /**
  1818. * Begin a new frame
  1819. */
  1820. public beginFrame(): void {
  1821. this.onBeginFrameObservable.notifyObservers(this);
  1822. this._measureFps();
  1823. }
  1824. /**
  1825. * Enf the current frame
  1826. */
  1827. public endFrame(): void {
  1828. // Force a flush in case we are using a bad OS.
  1829. if (this._badOS) {
  1830. this.flushFramebuffer();
  1831. }
  1832. // Submit frame to the vr device, if enabled
  1833. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1834. // TODO: We should only submit the frame if we read frameData successfully.
  1835. this._vrDisplay.submitFrame();
  1836. }
  1837. this.onEndFrameObservable.notifyObservers(this);
  1838. }
  1839. /**
  1840. * Resize the view according to the canvas' size
  1841. */
  1842. public resize(): void {
  1843. // We're not resizing the size of the canvas while in VR mode & presenting
  1844. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  1845. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1846. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1847. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1848. }
  1849. }
  1850. /**
  1851. * Force a specific size of the canvas
  1852. * @param width defines the new canvas' width
  1853. * @param height defines the new canvas' height
  1854. */
  1855. public setSize(width: number, height: number): void {
  1856. if (!this._renderingCanvas) {
  1857. return;
  1858. }
  1859. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1860. return;
  1861. }
  1862. this._renderingCanvas.width = width;
  1863. this._renderingCanvas.height = height;
  1864. for (var index = 0; index < this.scenes.length; index++) {
  1865. var scene = this.scenes[index];
  1866. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1867. var cam = scene.cameras[camIndex];
  1868. cam._currentRenderId = 0;
  1869. }
  1870. }
  1871. if (this.onResizeObservable.hasObservers) {
  1872. this.onResizeObservable.notifyObservers(this);
  1873. }
  1874. }
  1875. // WebVR functions
  1876. /**
  1877. * Gets a boolean indicating if a webVR device was detected
  1878. * @returns true if a webVR device was detected
  1879. */
  1880. public isVRDevicePresent(): boolean {
  1881. return !!this._vrDisplay;
  1882. }
  1883. /**
  1884. * Gets the current webVR device
  1885. * @returns the current webVR device (or null)
  1886. */
  1887. public getVRDevice(): any {
  1888. return this._vrDisplay;
  1889. }
  1890. /**
  1891. * Initializes a webVR display and starts listening to display change events
  1892. * The onVRDisplayChangedObservable will be notified upon these changes
  1893. * @returns The onVRDisplayChangedObservable
  1894. */
  1895. public initWebVR(): Observable<IDisplayChangedEventArgs> {
  1896. this.initWebVRAsync();
  1897. return this.onVRDisplayChangedObservable;
  1898. }
  1899. /**
  1900. * Initializes a webVR display and starts listening to display change events
  1901. * The onVRDisplayChangedObservable will be notified upon these changes
  1902. * @returns A promise containing a VRDisplay and if vr is supported
  1903. */
  1904. public initWebVRAsync(): Promise<IDisplayChangedEventArgs> {
  1905. var notifyObservers = () => {
  1906. var eventArgs = {
  1907. vrDisplay: this._vrDisplay,
  1908. vrSupported: this._vrSupported
  1909. };
  1910. this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  1911. this._webVRInitPromise = new Promise((res) => { res(eventArgs); });
  1912. };
  1913. if (!this._onVrDisplayConnect) {
  1914. this._onVrDisplayConnect = (event) => {
  1915. this._vrDisplay = event.display;
  1916. notifyObservers();
  1917. };
  1918. this._onVrDisplayDisconnect = () => {
  1919. this._vrDisplay.cancelAnimationFrame(this._frameHandler);
  1920. this._vrDisplay = undefined;
  1921. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1922. notifyObservers();
  1923. };
  1924. this._onVrDisplayPresentChange = () => {
  1925. this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;
  1926. };
  1927. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  1928. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  1929. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1930. }
  1931. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  1932. this._webVRInitPromise.then(notifyObservers);
  1933. return this._webVRInitPromise;
  1934. }
  1935. /**
  1936. * Call this function to switch to webVR mode
  1937. * Will do nothing if webVR is not supported or if there is no webVR device
  1938. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1939. */
  1940. public enableVR() {
  1941. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  1942. var onResolved = () => {
  1943. this.onVRRequestPresentComplete.notifyObservers(true);
  1944. this._onVRFullScreenTriggered();
  1945. };
  1946. var onRejected = () => {
  1947. this.onVRRequestPresentComplete.notifyObservers(false);
  1948. };
  1949. this.onVRRequestPresentStart.notifyObservers(this);
  1950. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  1951. }
  1952. }
  1953. /**
  1954. * Call this function to leave webVR mode
  1955. * Will do nothing if webVR is not supported or if there is no webVR device
  1956. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1957. */
  1958. public disableVR() {
  1959. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1960. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  1961. }
  1962. }
  1963. private _onVRFullScreenTriggered = () => {
  1964. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1965. //get the old size before we change
  1966. this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());
  1967. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1968. //get the width and height, change the render size
  1969. var leftEye = this._vrDisplay.getEyeParameters('left');
  1970. this.setHardwareScalingLevel(1);
  1971. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1972. } else {
  1973. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1974. this.setSize(this._oldSize.width, this._oldSize.height);
  1975. }
  1976. }
  1977. private _getVRDisplaysAsync(): Promise<IDisplayChangedEventArgs> {
  1978. return new Promise((res) => {
  1979. if (navigator.getVRDisplays) {
  1980. navigator.getVRDisplays().then((devices: Array<any>) => {
  1981. this._vrSupported = true;
  1982. // note that devices may actually be an empty array. This is fine;
  1983. // we expect this._vrDisplay to be undefined in this case.
  1984. this._vrDisplay = devices[0];
  1985. res({
  1986. vrDisplay: this._vrDisplay,
  1987. vrSupported: this._vrSupported
  1988. });
  1989. });
  1990. } else {
  1991. this._vrDisplay = undefined;
  1992. this._vrSupported = false;
  1993. res({
  1994. vrDisplay: this._vrDisplay,
  1995. vrSupported: this._vrSupported
  1996. });
  1997. }
  1998. });
  1999. }
  2000. /**
  2001. * Binds the frame buffer to the specified texture.
  2002. * @param texture The texture to render to or null for the default canvas
  2003. * @param faceIndex The face of the texture to render to in case of cube texture
  2004. * @param requiredWidth The width of the target to render to
  2005. * @param requiredHeight The height of the target to render to
  2006. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  2007. * @param depthStencilTexture The depth stencil texture to use to render
  2008. * @param lodLevel defines le lod level to bind to the frame buffer
  2009. */
  2010. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture, lodLevel = 0): void {
  2011. if (this._currentRenderTarget) {
  2012. this.unBindFramebuffer(this._currentRenderTarget);
  2013. }
  2014. this._currentRenderTarget = texture;
  2015. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  2016. var gl = this._gl;
  2017. if (texture.isCube) {
  2018. if (faceIndex === undefined) {
  2019. faceIndex = 0;
  2020. }
  2021. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  2022. if (depthStencilTexture) {
  2023. if (depthStencilTexture._generateStencilBuffer) {
  2024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  2025. }
  2026. else {
  2027. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  2028. }
  2029. }
  2030. }
  2031. if (this._cachedViewport && !forceFullscreenViewport) {
  2032. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  2033. } else {
  2034. if (!requiredWidth) {
  2035. requiredWidth = texture.width;
  2036. if (lodLevel) {
  2037. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  2038. }
  2039. }
  2040. if (!requiredHeight) {
  2041. requiredHeight = texture.height;
  2042. if (lodLevel) {
  2043. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  2044. }
  2045. }
  2046. this._viewport(0, 0, requiredWidth, requiredHeight);
  2047. }
  2048. this.wipeCaches();
  2049. }
  2050. private bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  2051. if (this._currentFramebuffer !== framebuffer) {
  2052. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  2053. this._currentFramebuffer = framebuffer;
  2054. }
  2055. }
  2056. /**
  2057. * Unbind the current render target texture from the webGL context
  2058. * @param texture defines the render target texture to unbind
  2059. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  2060. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  2061. */
  2062. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  2063. this._currentRenderTarget = null;
  2064. // If MSAA, we need to bitblt back to main texture
  2065. var gl = this._gl;
  2066. if (texture._MSAAFramebuffer) {
  2067. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  2068. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  2069. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  2070. 0, 0, texture.width, texture.height,
  2071. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  2072. }
  2073. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2074. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2075. gl.generateMipmap(gl.TEXTURE_2D);
  2076. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2077. }
  2078. if (onBeforeUnbind) {
  2079. if (texture._MSAAFramebuffer) {
  2080. // Bind the correct framebuffer
  2081. this.bindUnboundFramebuffer(texture._framebuffer);
  2082. }
  2083. onBeforeUnbind();
  2084. }
  2085. this.bindUnboundFramebuffer(null);
  2086. }
  2087. /**
  2088. * Unbind a list of render target textures from the webGL context
  2089. * This is used only when drawBuffer extension or webGL2 are active
  2090. * @param textures defines the render target textures to unbind
  2091. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  2092. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  2093. */
  2094. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  2095. this._currentRenderTarget = null;
  2096. // If MSAA, we need to bitblt back to main texture
  2097. var gl = this._gl;
  2098. if (textures[0]._MSAAFramebuffer) {
  2099. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  2100. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  2101. var attachments = textures[0]._attachments;
  2102. if (!attachments) {
  2103. attachments = new Array(textures.length);
  2104. textures[0]._attachments = attachments;
  2105. }
  2106. for (var i = 0; i < textures.length; i++) {
  2107. var texture = textures[i];
  2108. for (var j = 0; j < attachments.length; j++) {
  2109. attachments[j] = gl.NONE;
  2110. }
  2111. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2112. gl.readBuffer(attachments[i]);
  2113. gl.drawBuffers(attachments);
  2114. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  2115. 0, 0, texture.width, texture.height,
  2116. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  2117. }
  2118. for (var i = 0; i < attachments.length; i++) {
  2119. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2120. }
  2121. gl.drawBuffers(attachments);
  2122. }
  2123. for (var i = 0; i < textures.length; i++) {
  2124. var texture = textures[i];
  2125. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2126. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2127. gl.generateMipmap(gl.TEXTURE_2D);
  2128. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2129. }
  2130. }
  2131. if (onBeforeUnbind) {
  2132. if (textures[0]._MSAAFramebuffer) {
  2133. // Bind the correct framebuffer
  2134. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  2135. }
  2136. onBeforeUnbind();
  2137. }
  2138. this.bindUnboundFramebuffer(null);
  2139. }
  2140. /**
  2141. * Force the mipmap generation for the given render target texture
  2142. * @param texture defines the render target texture to use
  2143. */
  2144. public generateMipMapsForCubemap(texture: InternalTexture) {
  2145. if (texture.generateMipMaps) {
  2146. var gl = this._gl;
  2147. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  2148. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2149. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2150. }
  2151. }
  2152. /**
  2153. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  2154. */
  2155. public flushFramebuffer(): void {
  2156. this._gl.flush();
  2157. }
  2158. /**
  2159. * Unbind the current render target and bind the default framebuffer
  2160. */
  2161. public restoreDefaultFramebuffer(): void {
  2162. if (this._currentRenderTarget) {
  2163. this.unBindFramebuffer(this._currentRenderTarget);
  2164. } else {
  2165. this.bindUnboundFramebuffer(null);
  2166. }
  2167. if (this._cachedViewport) {
  2168. this.setViewport(this._cachedViewport);
  2169. }
  2170. this.wipeCaches();
  2171. }
  2172. // UBOs
  2173. /**
  2174. * Create an uniform buffer
  2175. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2176. * @param elements defines the content of the uniform buffer
  2177. * @returns the webGL uniform buffer
  2178. */
  2179. public createUniformBuffer(elements: FloatArray): WebGLBuffer {
  2180. var ubo = this._gl.createBuffer();
  2181. if (!ubo) {
  2182. throw new Error("Unable to create uniform buffer");
  2183. }
  2184. this.bindUniformBuffer(ubo);
  2185. if (elements instanceof Float32Array) {
  2186. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  2187. } else {
  2188. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  2189. }
  2190. this.bindUniformBuffer(null);
  2191. ubo.references = 1;
  2192. return ubo;
  2193. }
  2194. /**
  2195. * Create a dynamic uniform buffer
  2196. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2197. * @param elements defines the content of the uniform buffer
  2198. * @returns the webGL uniform buffer
  2199. */
  2200. public createDynamicUniformBuffer(elements: FloatArray): WebGLBuffer {
  2201. var ubo = this._gl.createBuffer();
  2202. if (!ubo) {
  2203. throw new Error("Unable to create dynamic uniform buffer");
  2204. }
  2205. this.bindUniformBuffer(ubo);
  2206. if (elements instanceof Float32Array) {
  2207. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  2208. } else {
  2209. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  2210. }
  2211. this.bindUniformBuffer(null);
  2212. ubo.references = 1;
  2213. return ubo;
  2214. }
  2215. /**
  2216. * Update an existing uniform buffer
  2217. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2218. * @param uniformBuffer defines the target uniform buffer
  2219. * @param elements defines the content to update
  2220. * @param offset defines the offset in the uniform buffer where update should start
  2221. * @param count defines the size of the data to update
  2222. */
  2223. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void {
  2224. this.bindUniformBuffer(uniformBuffer);
  2225. if (offset === undefined) {
  2226. offset = 0;
  2227. }
  2228. if (count === undefined) {
  2229. if (elements instanceof Float32Array) {
  2230. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  2231. } else {
  2232. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  2233. }
  2234. } else {
  2235. if (elements instanceof Float32Array) {
  2236. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  2237. } else {
  2238. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  2239. }
  2240. }
  2241. this.bindUniformBuffer(null);
  2242. }
  2243. // VBOs
  2244. private _resetVertexBufferBinding(): void {
  2245. this.bindArrayBuffer(null);
  2246. this._cachedVertexBuffers = null;
  2247. }
  2248. /**
  2249. * Creates a vertex buffer
  2250. * @param data the data for the vertex buffer
  2251. * @returns the new WebGL static buffer
  2252. */
  2253. public createVertexBuffer(data: DataArray): WebGLBuffer {
  2254. var vbo = this._gl.createBuffer();
  2255. if (!vbo) {
  2256. throw new Error("Unable to create vertex buffer");
  2257. }
  2258. this.bindArrayBuffer(vbo);
  2259. if (data instanceof Array) {
  2260. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  2261. } else {
  2262. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.STATIC_DRAW);
  2263. }
  2264. this._resetVertexBufferBinding();
  2265. vbo.references = 1;
  2266. return vbo;
  2267. }
  2268. /**
  2269. * Creates a dynamic vertex buffer
  2270. * @param data the data for the dynamic vertex buffer
  2271. * @returns the new WebGL dynamic buffer
  2272. */
  2273. public createDynamicVertexBuffer(data: DataArray): WebGLBuffer {
  2274. var vbo = this._gl.createBuffer();
  2275. if (!vbo) {
  2276. throw new Error("Unable to create dynamic vertex buffer");
  2277. }
  2278. this.bindArrayBuffer(vbo);
  2279. if (data instanceof Array) {
  2280. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  2281. } else {
  2282. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.DYNAMIC_DRAW);
  2283. }
  2284. this._resetVertexBufferBinding();
  2285. vbo.references = 1;
  2286. return vbo;
  2287. }
  2288. /**
  2289. * Update a dynamic index buffer
  2290. * @param indexBuffer defines the target index buffer
  2291. * @param indices defines the data to update
  2292. * @param offset defines the offset in the target index buffer where update should start
  2293. */
  2294. public updateDynamicIndexBuffer(indexBuffer: WebGLBuffer, indices: IndicesArray, offset: number = 0): void {
  2295. // Force cache update
  2296. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  2297. this.bindIndexBuffer(indexBuffer);
  2298. var arrayBuffer;
  2299. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  2300. arrayBuffer = indices;
  2301. } else {
  2302. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2303. }
  2304. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  2305. this._resetIndexBufferBinding();
  2306. }
  2307. /**
  2308. * Updates a dynamic vertex buffer.
  2309. * @param vertexBuffer the vertex buffer to update
  2310. * @param data the data used to update the vertex buffer
  2311. * @param byteOffset the byte offset of the data
  2312. * @param byteLength the byte length of the data
  2313. */
  2314. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  2315. this.bindArrayBuffer(vertexBuffer);
  2316. if (byteOffset === undefined) {
  2317. byteOffset = 0;
  2318. }
  2319. if (byteLength === undefined) {
  2320. if (data instanceof Array) {
  2321. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  2322. } else {
  2323. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, <ArrayBuffer>data);
  2324. }
  2325. } else {
  2326. if (data instanceof Array) {
  2327. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  2328. } else {
  2329. if (data instanceof ArrayBuffer) {
  2330. data = new Uint8Array(data, byteOffset, byteLength);
  2331. } else {
  2332. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  2333. }
  2334. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <ArrayBuffer>data);
  2335. }
  2336. }
  2337. this._resetVertexBufferBinding();
  2338. }
  2339. private _resetIndexBufferBinding(): void {
  2340. this.bindIndexBuffer(null);
  2341. this._cachedIndexBuffer = null;
  2342. }
  2343. /**
  2344. * Creates a new index buffer
  2345. * @param indices defines the content of the index buffer
  2346. * @param updatable defines if the index buffer must be updatable
  2347. * @returns a new webGL buffer
  2348. */
  2349. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): WebGLBuffer {
  2350. var vbo = this._gl.createBuffer();
  2351. if (!vbo) {
  2352. throw new Error("Unable to create index buffer");
  2353. }
  2354. this.bindIndexBuffer(vbo);
  2355. // Check for 32 bits indices
  2356. var arrayBuffer;
  2357. var need32Bits = false;
  2358. if (indices instanceof Uint16Array) {
  2359. arrayBuffer = indices;
  2360. } else {
  2361. //check 32 bit support
  2362. if (this._caps.uintIndices) {
  2363. if (indices instanceof Uint32Array) {
  2364. arrayBuffer = indices;
  2365. need32Bits = true;
  2366. } else {
  2367. //number[] or Int32Array, check if 32 bit is necessary
  2368. for (var index = 0; index < indices.length; index++) {
  2369. if (indices[index] > 65535) {
  2370. need32Bits = true;
  2371. break;
  2372. }
  2373. }
  2374. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2375. }
  2376. } else {
  2377. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  2378. arrayBuffer = new Uint16Array(indices);
  2379. }
  2380. }
  2381. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  2382. this._resetIndexBufferBinding();
  2383. vbo.references = 1;
  2384. vbo.is32Bits = need32Bits;
  2385. return vbo;
  2386. }
  2387. /**
  2388. * Bind a webGL buffer to the webGL context
  2389. * @param buffer defines the buffer to bind
  2390. */
  2391. public bindArrayBuffer(buffer: Nullable<WebGLBuffer>): void {
  2392. if (!this._vaoRecordInProgress) {
  2393. this._unbindVertexArrayObject();
  2394. }
  2395. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  2396. }
  2397. /**
  2398. * Bind an uniform buffer to the current webGL context
  2399. * @param buffer defines the buffer to bind
  2400. */
  2401. public bindUniformBuffer(buffer: Nullable<WebGLBuffer>): void {
  2402. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  2403. }
  2404. /**
  2405. * Bind a buffer to the current webGL context at a given location
  2406. * @param buffer defines the buffer to bind
  2407. * @param location defines the index where to bind the buffer
  2408. */
  2409. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  2410. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  2411. }
  2412. /**
  2413. * Bind a specific block at a given index in a specific shader program
  2414. * @param shaderProgram defines the shader program
  2415. * @param blockName defines the block name
  2416. * @param index defines the index where to bind the block
  2417. */
  2418. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  2419. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  2420. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  2421. }
  2422. private bindIndexBuffer(buffer: Nullable<WebGLBuffer>): void {
  2423. if (!this._vaoRecordInProgress) {
  2424. this._unbindVertexArrayObject();
  2425. }
  2426. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  2427. }
  2428. private bindBuffer(buffer: Nullable<WebGLBuffer>, target: number): void {
  2429. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  2430. this._gl.bindBuffer(target, buffer);
  2431. this._currentBoundBuffer[target] = buffer;
  2432. }
  2433. }
  2434. /**
  2435. * update the bound buffer with the given data
  2436. * @param data defines the data to update
  2437. */
  2438. public updateArrayBuffer(data: Float32Array): void {
  2439. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2440. }
  2441. private _vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  2442. var pointer = this._currentBufferPointers[indx];
  2443. var changed = false;
  2444. if (!pointer.active) {
  2445. changed = true;
  2446. pointer.active = true;
  2447. pointer.index = indx;
  2448. pointer.size = size;
  2449. pointer.type = type;
  2450. pointer.normalized = normalized;
  2451. pointer.stride = stride;
  2452. pointer.offset = offset;
  2453. pointer.buffer = buffer;
  2454. } else {
  2455. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  2456. if (pointer.size !== size) { pointer.size = size; changed = true; }
  2457. if (pointer.type !== type) { pointer.type = type; changed = true; }
  2458. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  2459. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  2460. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  2461. }
  2462. if (changed || this._vaoRecordInProgress) {
  2463. this.bindArrayBuffer(buffer);
  2464. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  2465. }
  2466. }
  2467. private _bindIndexBufferWithCache(indexBuffer: Nullable<WebGLBuffer>): void {
  2468. if (indexBuffer == null) {
  2469. return;
  2470. }
  2471. if (this._cachedIndexBuffer !== indexBuffer) {
  2472. this._cachedIndexBuffer = indexBuffer;
  2473. this.bindIndexBuffer(indexBuffer);
  2474. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  2475. }
  2476. }
  2477. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  2478. var attributes = effect.getAttributesNames();
  2479. if (!this._vaoRecordInProgress) {
  2480. this._unbindVertexArrayObject();
  2481. }
  2482. this.unbindAllAttributes();
  2483. for (var index = 0; index < attributes.length; index++) {
  2484. var order = effect.getAttributeLocation(index);
  2485. if (order >= 0) {
  2486. var vertexBuffer = vertexBuffers[attributes[index]];
  2487. if (!vertexBuffer) {
  2488. continue;
  2489. }
  2490. this._gl.enableVertexAttribArray(order);
  2491. if (!this._vaoRecordInProgress) {
  2492. this._vertexAttribArraysEnabled[order] = true;
  2493. }
  2494. var buffer = vertexBuffer.getBuffer();
  2495. if (buffer) {
  2496. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  2497. if (vertexBuffer.getIsInstanced()) {
  2498. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  2499. if (!this._vaoRecordInProgress) {
  2500. this._currentInstanceLocations.push(order);
  2501. this._currentInstanceBuffers.push(buffer);
  2502. }
  2503. }
  2504. }
  2505. }
  2506. }
  2507. }
  2508. /**
  2509. * Records a vertex array object
  2510. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2511. * @param vertexBuffers defines the list of vertex buffers to store
  2512. * @param indexBuffer defines the index buffer to store
  2513. * @param effect defines the effect to store
  2514. * @returns the new vertex array object
  2515. */
  2516. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): WebGLVertexArrayObject {
  2517. var vao = this._gl.createVertexArray();
  2518. this._vaoRecordInProgress = true;
  2519. this._gl.bindVertexArray(vao);
  2520. this._mustWipeVertexAttributes = true;
  2521. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2522. this.bindIndexBuffer(indexBuffer);
  2523. this._vaoRecordInProgress = false;
  2524. this._gl.bindVertexArray(null);
  2525. return vao;
  2526. }
  2527. /**
  2528. * Bind a specific vertex array object
  2529. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2530. * @param vertexArrayObject defines the vertex array object to bind
  2531. * @param indexBuffer defines the index buffer to bind
  2532. */
  2533. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<WebGLBuffer>): void {
  2534. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  2535. this._cachedVertexArrayObject = vertexArrayObject;
  2536. this._gl.bindVertexArray(vertexArrayObject);
  2537. this._cachedVertexBuffers = null;
  2538. this._cachedIndexBuffer = null;
  2539. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  2540. this._mustWipeVertexAttributes = true;
  2541. }
  2542. }
  2543. /**
  2544. * Bind webGl buffers directly to the webGL context
  2545. * @param vertexBuffer defines the vertex buffer to bind
  2546. * @param indexBuffer defines the index buffer to bind
  2547. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  2548. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  2549. * @param effect defines the effect associated with the vertex buffer
  2550. */
  2551. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  2552. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2553. this._cachedVertexBuffers = vertexBuffer;
  2554. this._cachedEffectForVertexBuffers = effect;
  2555. let attributesCount = effect.getAttributesCount();
  2556. this._unbindVertexArrayObject();
  2557. this.unbindAllAttributes();
  2558. var offset = 0;
  2559. for (var index = 0; index < attributesCount; index++) {
  2560. if (index < vertexDeclaration.length) {
  2561. var order = effect.getAttributeLocation(index);
  2562. if (order >= 0) {
  2563. this._gl.enableVertexAttribArray(order);
  2564. this._vertexAttribArraysEnabled[order] = true;
  2565. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2566. }
  2567. offset += vertexDeclaration[index] * 4;
  2568. }
  2569. }
  2570. }
  2571. this._bindIndexBufferWithCache(indexBuffer);
  2572. }
  2573. private _unbindVertexArrayObject(): void {
  2574. if (!this._cachedVertexArrayObject) {
  2575. return;
  2576. }
  2577. this._cachedVertexArrayObject = null;
  2578. this._gl.bindVertexArray(null);
  2579. }
  2580. /**
  2581. * Bind a list of vertex buffers to the webGL context
  2582. * @param vertexBuffers defines the list of vertex buffers to bind
  2583. * @param indexBuffer defines the index buffer to bind
  2584. * @param effect defines the effect associated with the vertex buffers
  2585. */
  2586. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): void {
  2587. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2588. this._cachedVertexBuffers = vertexBuffers;
  2589. this._cachedEffectForVertexBuffers = effect;
  2590. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2591. }
  2592. this._bindIndexBufferWithCache(indexBuffer);
  2593. }
  2594. /**
  2595. * Unbind all instance attributes
  2596. */
  2597. public unbindInstanceAttributes() {
  2598. var boundBuffer;
  2599. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  2600. var instancesBuffer = this._currentInstanceBuffers[i];
  2601. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  2602. boundBuffer = instancesBuffer;
  2603. this.bindArrayBuffer(instancesBuffer);
  2604. }
  2605. var offsetLocation = this._currentInstanceLocations[i];
  2606. this._gl.vertexAttribDivisor(offsetLocation, 0);
  2607. }
  2608. this._currentInstanceBuffers.length = 0;
  2609. this._currentInstanceLocations.length = 0;
  2610. }
  2611. /**
  2612. * Release and free the memory of a vertex array object
  2613. * @param vao defines the vertex array object to delete
  2614. */
  2615. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  2616. this._gl.deleteVertexArray(vao);
  2617. }
  2618. /** @hidden */
  2619. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  2620. buffer.references--;
  2621. if (buffer.references === 0) {
  2622. this._gl.deleteBuffer(buffer);
  2623. return true;
  2624. }
  2625. return false;
  2626. }
  2627. /**
  2628. * Creates a webGL buffer to use with instanciation
  2629. * @param capacity defines the size of the buffer
  2630. * @returns the webGL buffer
  2631. */
  2632. public createInstancesBuffer(capacity: number): WebGLBuffer {
  2633. var buffer = this._gl.createBuffer();
  2634. if (!buffer) {
  2635. throw new Error("Unable to create instance buffer");
  2636. }
  2637. buffer.capacity = capacity;
  2638. this.bindArrayBuffer(buffer);
  2639. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2640. return buffer;
  2641. }
  2642. /**
  2643. * Delete a webGL buffer used with instanciation
  2644. * @param buffer defines the webGL buffer to delete
  2645. */
  2646. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  2647. this._gl.deleteBuffer(buffer);
  2648. }
  2649. /**
  2650. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  2651. * @param instancesBuffer defines the webGL buffer to update and bind
  2652. * @param data defines the data to store in the buffer
  2653. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  2654. */
  2655. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  2656. this.bindArrayBuffer(instancesBuffer);
  2657. if (data) {
  2658. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2659. }
  2660. if ((<any>offsetLocations[0]).index !== undefined) {
  2661. let stride = 0;
  2662. for (let i = 0; i < offsetLocations.length; i++) {
  2663. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2664. stride += ai.attributeSize * 4;
  2665. }
  2666. for (let i = 0; i < offsetLocations.length; i++) {
  2667. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2668. if (!this._vertexAttribArraysEnabled[ai.index]) {
  2669. this._gl.enableVertexAttribArray(ai.index);
  2670. this._vertexAttribArraysEnabled[ai.index] = true;
  2671. }
  2672. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  2673. this._gl.vertexAttribDivisor(ai.index, 1);
  2674. this._currentInstanceLocations.push(ai.index);
  2675. this._currentInstanceBuffers.push(instancesBuffer);
  2676. }
  2677. } else {
  2678. for (let index = 0; index < 4; index++) {
  2679. let offsetLocation = <number>offsetLocations[index];
  2680. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  2681. this._gl.enableVertexAttribArray(offsetLocation);
  2682. this._vertexAttribArraysEnabled[offsetLocation] = true;
  2683. }
  2684. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2685. this._gl.vertexAttribDivisor(offsetLocation, 1);
  2686. this._currentInstanceLocations.push(offsetLocation);
  2687. this._currentInstanceBuffers.push(instancesBuffer);
  2688. }
  2689. }
  2690. }
  2691. /**
  2692. * Apply all cached states (depth, culling, stencil and alpha)
  2693. */
  2694. public applyStates() {
  2695. this._depthCullingState.apply(this._gl);
  2696. this._stencilState.apply(this._gl);
  2697. this._alphaState.apply(this._gl);
  2698. }
  2699. /**
  2700. * Send a draw order
  2701. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2702. * @param indexStart defines the starting index
  2703. * @param indexCount defines the number of index to draw
  2704. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2705. */
  2706. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  2707. this.drawElementsType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  2708. }
  2709. /**
  2710. * Draw a list of points
  2711. * @param verticesStart defines the index of first vertex to draw
  2712. * @param verticesCount defines the count of vertices to draw
  2713. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2714. */
  2715. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2716. this.drawArraysType(Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  2717. }
  2718. /**
  2719. * Draw a list of unindexed primitives
  2720. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2721. * @param verticesStart defines the index of first vertex to draw
  2722. * @param verticesCount defines the count of vertices to draw
  2723. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2724. */
  2725. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2726. this.drawArraysType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  2727. }
  2728. /**
  2729. * Draw a list of indexed primitives
  2730. * @param fillMode defines the primitive to use
  2731. * @param indexStart defines the starting index
  2732. * @param indexCount defines the number of index to draw
  2733. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2734. */
  2735. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  2736. // Apply states
  2737. this.applyStates();
  2738. this._drawCalls.addCount(1, false);
  2739. // Render
  2740. const drawMode = this._drawMode(fillMode);
  2741. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  2742. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  2743. if (instancesCount) {
  2744. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  2745. } else {
  2746. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  2747. }
  2748. }
  2749. /**
  2750. * Draw a list of unindexed primitives
  2751. * @param fillMode defines the primitive to use
  2752. * @param verticesStart defines the index of first vertex to draw
  2753. * @param verticesCount defines the count of vertices to draw
  2754. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2755. */
  2756. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2757. // Apply states
  2758. this.applyStates();
  2759. this._drawCalls.addCount(1, false);
  2760. const drawMode = this._drawMode(fillMode);
  2761. if (instancesCount) {
  2762. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  2763. } else {
  2764. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  2765. }
  2766. }
  2767. private _drawMode(fillMode: number): number {
  2768. switch (fillMode) {
  2769. // Triangle views
  2770. case Material.TriangleFillMode:
  2771. return this._gl.TRIANGLES;
  2772. case Material.PointFillMode:
  2773. return this._gl.POINTS;
  2774. case Material.WireFrameFillMode:
  2775. return this._gl.LINES;
  2776. // Draw modes
  2777. case Material.PointListDrawMode:
  2778. return this._gl.POINTS;
  2779. case Material.LineListDrawMode:
  2780. return this._gl.LINES;
  2781. case Material.LineLoopDrawMode:
  2782. return this._gl.LINE_LOOP;
  2783. case Material.LineStripDrawMode:
  2784. return this._gl.LINE_STRIP;
  2785. case Material.TriangleStripDrawMode:
  2786. return this._gl.TRIANGLE_STRIP;
  2787. case Material.TriangleFanDrawMode:
  2788. return this._gl.TRIANGLE_FAN;
  2789. default:
  2790. return this._gl.TRIANGLES;
  2791. }
  2792. }
  2793. // Shaders
  2794. /** @hidden */
  2795. public _releaseEffect(effect: Effect): void {
  2796. if (this._compiledEffects[effect._key]) {
  2797. delete this._compiledEffects[effect._key];
  2798. this._deleteProgram(effect.getProgram());
  2799. }
  2800. }
  2801. /** @hidden */
  2802. public _deleteProgram(program: WebGLProgram): void {
  2803. if (program) {
  2804. program.__SPECTOR_rebuildProgram = null;
  2805. if (program.transformFeedback) {
  2806. this.deleteTransformFeedback(program.transformFeedback);
  2807. program.transformFeedback = null;
  2808. }
  2809. this._gl.deleteProgram(program);
  2810. }
  2811. }
  2812. /**
  2813. * Create a new effect (used to store vertex/fragment shaders)
  2814. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  2815. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  2816. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  2817. * @param samplers defines an array of string used to represent textures
  2818. * @param defines defines the string containing the defines to use to compile the shaders
  2819. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  2820. * @param onCompiled defines a function to call when the effect creation is successful
  2821. * @param onError defines a function to call when the effect creation has failed
  2822. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  2823. * @returns the new Effect
  2824. */
  2825. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  2826. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  2827. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2828. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2829. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  2830. if (this._compiledEffects[name]) {
  2831. var compiledEffect = <Effect>this._compiledEffects[name];
  2832. if (onCompiled && compiledEffect.isReady()) {
  2833. onCompiled(compiledEffect);
  2834. }
  2835. return compiledEffect;
  2836. }
  2837. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  2838. effect._key = name;
  2839. this._compiledEffects[name] = effect;
  2840. return effect;
  2841. }
  2842. private _compileShader(source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader {
  2843. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  2844. }
  2845. private _compileRawShader(source: string, type: string): WebGLShader {
  2846. var gl = this._gl;
  2847. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2848. if (!shader) {
  2849. throw new Error("Something went wrong while compile the shader.");
  2850. }
  2851. gl.shaderSource(shader, source);
  2852. gl.compileShader(shader);
  2853. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2854. let log = gl.getShaderInfoLog(shader);
  2855. if (log) {
  2856. throw new Error(log);
  2857. }
  2858. }
  2859. return shader;
  2860. }
  2861. /**
  2862. * Directly creates a webGL program
  2863. * @param vertexCode defines the vertex shader code to use
  2864. * @param fragmentCode defines the fragment shader code to use
  2865. * @param context defines the webGL context to use (if not set, the current one will be used)
  2866. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2867. * @returns the new webGL program
  2868. */
  2869. public createRawShaderProgram(vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2870. context = context || this._gl;
  2871. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  2872. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  2873. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2874. }
  2875. /**
  2876. * Creates a webGL program
  2877. * @param vertexCode defines the vertex shader code to use
  2878. * @param fragmentCode defines the fragment shader code to use
  2879. * @param defines defines the string containing the defines to use to compile the shaders
  2880. * @param context defines the webGL context to use (if not set, the current one will be used)
  2881. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2882. * @returns the new webGL program
  2883. */
  2884. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2885. context = context || this._gl;
  2886. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  2887. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  2888. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  2889. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  2890. let program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2891. this.onAfterShaderCompilationObservable.notifyObservers(this);
  2892. return program;
  2893. }
  2894. private _createShaderProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2895. var shaderProgram = context.createProgram();
  2896. if (!shaderProgram) {
  2897. throw new Error("Unable to create program");
  2898. }
  2899. context.attachShader(shaderProgram, vertexShader);
  2900. context.attachShader(shaderProgram, fragmentShader);
  2901. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2902. let transformFeedback = this.createTransformFeedback();
  2903. this.bindTransformFeedback(transformFeedback);
  2904. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  2905. shaderProgram.transformFeedback = transformFeedback;
  2906. }
  2907. context.linkProgram(shaderProgram);
  2908. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2909. this.bindTransformFeedback(null);
  2910. }
  2911. shaderProgram.context = context;
  2912. shaderProgram.vertexShader = vertexShader;
  2913. shaderProgram.fragmentShader = fragmentShader;
  2914. if (!this._caps.parallelShaderCompile) {
  2915. this._finalizeProgram(shaderProgram);
  2916. } else {
  2917. shaderProgram.isParallelCompiled = true;
  2918. }
  2919. return shaderProgram;
  2920. }
  2921. private _finalizeProgram(shaderProgram: WebGLProgram) {
  2922. const context = shaderProgram.context!;
  2923. const vertexShader = shaderProgram.vertexShader!;
  2924. const fragmentShader = shaderProgram.fragmentShader!;
  2925. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  2926. if (!linked) {
  2927. var error = context.getProgramInfoLog(shaderProgram);
  2928. if (error) {
  2929. throw new Error(error);
  2930. }
  2931. }
  2932. if (this.validateShaderPrograms) {
  2933. context.validateProgram(shaderProgram);
  2934. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  2935. if (!validated) {
  2936. var error = context.getProgramInfoLog(shaderProgram);
  2937. if (error) {
  2938. throw new Error(error);
  2939. }
  2940. }
  2941. }
  2942. context.deleteShader(vertexShader);
  2943. context.deleteShader(fragmentShader);
  2944. shaderProgram.context = undefined;
  2945. shaderProgram.vertexShader = undefined;
  2946. shaderProgram.fragmentShader = undefined;
  2947. if (shaderProgram.onCompiled) {
  2948. shaderProgram.onCompiled();
  2949. shaderProgram.onCompiled = undefined;
  2950. }
  2951. }
  2952. /** @hidden */
  2953. public _isProgramCompiled(shaderProgram: WebGLProgram): boolean {
  2954. if (!shaderProgram.isParallelCompiled) {
  2955. return true;
  2956. }
  2957. if (this._gl.getProgramParameter(shaderProgram, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
  2958. this._finalizeProgram(shaderProgram);
  2959. return true;
  2960. }
  2961. return false;
  2962. }
  2963. /** @hidden */
  2964. public _executeWhenProgramIsCompiled(shaderProgram: WebGLProgram, action: () => void) {
  2965. if (!shaderProgram.isParallelCompiled) {
  2966. action();
  2967. return;
  2968. }
  2969. shaderProgram.onCompiled = action;
  2970. }
  2971. /**
  2972. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  2973. * @param shaderProgram defines the webGL program to use
  2974. * @param uniformsNames defines the list of uniform names
  2975. * @returns an array of webGL uniform locations
  2976. */
  2977. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2978. var results = new Array<Nullable<WebGLUniformLocation>>();
  2979. for (var index = 0; index < uniformsNames.length; index++) {
  2980. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2981. }
  2982. return results;
  2983. }
  2984. /**
  2985. * Gets the lsit of active attributes for a given webGL program
  2986. * @param shaderProgram defines the webGL program to use
  2987. * @param attributesNames defines the list of attribute names to get
  2988. * @returns an array of indices indicating the offset of each attribute
  2989. */
  2990. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  2991. var results = [];
  2992. for (var index = 0; index < attributesNames.length; index++) {
  2993. try {
  2994. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2995. } catch (e) {
  2996. results.push(-1);
  2997. }
  2998. }
  2999. return results;
  3000. }
  3001. /**
  3002. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  3003. * @param effect defines the effect to activate
  3004. */
  3005. public enableEffect(effect: Nullable<Effect>): void {
  3006. if (!effect || effect === this._currentEffect) {
  3007. return;
  3008. }
  3009. // Use program
  3010. this.bindSamplers(effect);
  3011. this._currentEffect = effect;
  3012. if (effect.onBind) {
  3013. effect.onBind(effect);
  3014. }
  3015. if (effect._onBindObservable) {
  3016. effect._onBindObservable.notifyObservers(effect);
  3017. }
  3018. }
  3019. /**
  3020. * Set the value of an uniform to an array of int32
  3021. * @param uniform defines the webGL uniform location where to store the value
  3022. * @param array defines the array of int32 to store
  3023. */
  3024. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3025. if (!uniform) {
  3026. return;
  3027. }
  3028. this._gl.uniform1iv(uniform, array);
  3029. }
  3030. /**
  3031. * Set the value of an uniform to an array of int32 (stored as vec2)
  3032. * @param uniform defines the webGL uniform location where to store the value
  3033. * @param array defines the array of int32 to store
  3034. */
  3035. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3036. if (!uniform || array.length % 2 !== 0) {
  3037. return;
  3038. }
  3039. this._gl.uniform2iv(uniform, array);
  3040. }
  3041. /**
  3042. * Set the value of an uniform to an array of int32 (stored as vec3)
  3043. * @param uniform defines the webGL uniform location where to store the value
  3044. * @param array defines the array of int32 to store
  3045. */
  3046. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3047. if (!uniform || array.length % 3 !== 0) {
  3048. return;
  3049. }
  3050. this._gl.uniform3iv(uniform, array);
  3051. }
  3052. /**
  3053. * Set the value of an uniform to an array of int32 (stored as vec4)
  3054. * @param uniform defines the webGL uniform location where to store the value
  3055. * @param array defines the array of int32 to store
  3056. */
  3057. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3058. if (!uniform || array.length % 4 !== 0) {
  3059. return;
  3060. }
  3061. this._gl.uniform4iv(uniform, array);
  3062. }
  3063. /**
  3064. * Set the value of an uniform to an array of float32
  3065. * @param uniform defines the webGL uniform location where to store the value
  3066. * @param array defines the array of float32 to store
  3067. */
  3068. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3069. if (!uniform) {
  3070. return;
  3071. }
  3072. this._gl.uniform1fv(uniform, array);
  3073. }
  3074. /**
  3075. * Set the value of an uniform to an array of float32 (stored as vec2)
  3076. * @param uniform defines the webGL uniform location where to store the value
  3077. * @param array defines the array of float32 to store
  3078. */
  3079. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3080. if (!uniform || array.length % 2 !== 0) {
  3081. return;
  3082. }
  3083. this._gl.uniform2fv(uniform, array);
  3084. }
  3085. /**
  3086. * Set the value of an uniform to an array of float32 (stored as vec3)
  3087. * @param uniform defines the webGL uniform location where to store the value
  3088. * @param array defines the array of float32 to store
  3089. */
  3090. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3091. if (!uniform || array.length % 3 !== 0) {
  3092. return;
  3093. }
  3094. this._gl.uniform3fv(uniform, array);
  3095. }
  3096. /**
  3097. * Set the value of an uniform to an array of float32 (stored as vec4)
  3098. * @param uniform defines the webGL uniform location where to store the value
  3099. * @param array defines the array of float32 to store
  3100. */
  3101. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3102. if (!uniform || array.length % 4 !== 0) {
  3103. return;
  3104. }
  3105. this._gl.uniform4fv(uniform, array);
  3106. }
  3107. /**
  3108. * Set the value of an uniform to an array of number
  3109. * @param uniform defines the webGL uniform location where to store the value
  3110. * @param array defines the array of number to store
  3111. */
  3112. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3113. if (!uniform) {
  3114. return;
  3115. }
  3116. this._gl.uniform1fv(uniform, <any>array);
  3117. }
  3118. /**
  3119. * Set the value of an uniform to an array of number (stored as vec2)
  3120. * @param uniform defines the webGL uniform location where to store the value
  3121. * @param array defines the array of number to store
  3122. */
  3123. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3124. if (!uniform || array.length % 2 !== 0) {
  3125. return;
  3126. }
  3127. this._gl.uniform2fv(uniform, <any>array);
  3128. }
  3129. /**
  3130. * Set the value of an uniform to an array of number (stored as vec3)
  3131. * @param uniform defines the webGL uniform location where to store the value
  3132. * @param array defines the array of number to store
  3133. */
  3134. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3135. if (!uniform || array.length % 3 !== 0) {
  3136. return;
  3137. }
  3138. this._gl.uniform3fv(uniform, <any>array);
  3139. }
  3140. /**
  3141. * Set the value of an uniform to an array of number (stored as vec4)
  3142. * @param uniform defines the webGL uniform location where to store the value
  3143. * @param array defines the array of number to store
  3144. */
  3145. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3146. if (!uniform || array.length % 4 !== 0) {
  3147. return;
  3148. }
  3149. this._gl.uniform4fv(uniform, <any>array);
  3150. }
  3151. /**
  3152. * Set the value of an uniform to an array of float32 (stored as matrices)
  3153. * @param uniform defines the webGL uniform location where to store the value
  3154. * @param matrices defines the array of float32 to store
  3155. */
  3156. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  3157. if (!uniform) {
  3158. return;
  3159. }
  3160. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3161. }
  3162. /**
  3163. * Set the value of an uniform to a matrix
  3164. * @param uniform defines the webGL uniform location where to store the value
  3165. * @param matrix defines the matrix to store
  3166. */
  3167. public setMatrix(uniform: Nullable<WebGLUniformLocation>, matrix: Matrix): void {
  3168. if (!uniform) {
  3169. return;
  3170. }
  3171. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray() as Float32Array);
  3172. }
  3173. /**
  3174. * Set the value of an uniform to a matrix (3x3)
  3175. * @param uniform defines the webGL uniform location where to store the value
  3176. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  3177. */
  3178. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  3179. if (!uniform) {
  3180. return;
  3181. }
  3182. this._gl.uniformMatrix3fv(uniform, false, matrix);
  3183. }
  3184. /**
  3185. * Set the value of an uniform to a matrix (2x2)
  3186. * @param uniform defines the webGL uniform location where to store the value
  3187. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  3188. */
  3189. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  3190. if (!uniform) {
  3191. return;
  3192. }
  3193. this._gl.uniformMatrix2fv(uniform, false, matrix);
  3194. }
  3195. /**
  3196. * Set the value of an uniform to a number (int)
  3197. * @param uniform defines the webGL uniform location where to store the value
  3198. * @param value defines the int number to store
  3199. */
  3200. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3201. if (!uniform) {
  3202. return;
  3203. }
  3204. this._gl.uniform1i(uniform, value);
  3205. }
  3206. /**
  3207. * Set the value of an uniform to a number (float)
  3208. * @param uniform defines the webGL uniform location where to store the value
  3209. * @param value defines the float number to store
  3210. */
  3211. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3212. if (!uniform) {
  3213. return;
  3214. }
  3215. this._gl.uniform1f(uniform, value);
  3216. }
  3217. /**
  3218. * Set the value of an uniform to a vec2
  3219. * @param uniform defines the webGL uniform location where to store the value
  3220. * @param x defines the 1st component of the value
  3221. * @param y defines the 2nd component of the value
  3222. */
  3223. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  3224. if (!uniform) {
  3225. return;
  3226. }
  3227. this._gl.uniform2f(uniform, x, y);
  3228. }
  3229. /**
  3230. * Set the value of an uniform to a vec3
  3231. * @param uniform defines the webGL uniform location where to store the value
  3232. * @param x defines the 1st component of the value
  3233. * @param y defines the 2nd component of the value
  3234. * @param z defines the 3rd component of the value
  3235. */
  3236. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  3237. if (!uniform) {
  3238. return;
  3239. }
  3240. this._gl.uniform3f(uniform, x, y, z);
  3241. }
  3242. /**
  3243. * Set the value of an uniform to a boolean
  3244. * @param uniform defines the webGL uniform location where to store the value
  3245. * @param bool defines the boolean to store
  3246. */
  3247. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  3248. if (!uniform) {
  3249. return;
  3250. }
  3251. this._gl.uniform1i(uniform, bool);
  3252. }
  3253. /**
  3254. * Set the value of an uniform to a vec4
  3255. * @param uniform defines the webGL uniform location where to store the value
  3256. * @param x defines the 1st component of the value
  3257. * @param y defines the 2nd component of the value
  3258. * @param z defines the 3rd component of the value
  3259. * @param w defines the 4th component of the value
  3260. */
  3261. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  3262. if (!uniform) {
  3263. return;
  3264. }
  3265. this._gl.uniform4f(uniform, x, y, z, w);
  3266. }
  3267. /**
  3268. * Set the value of an uniform to a Color3
  3269. * @param uniform defines the webGL uniform location where to store the value
  3270. * @param color3 defines the color to store
  3271. */
  3272. public setColor3(uniform: Nullable<WebGLUniformLocation>, color3: Color3): void {
  3273. if (!uniform) {
  3274. return;
  3275. }
  3276. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3277. }
  3278. /**
  3279. * Set the value of an uniform to a Color3 and an alpha value
  3280. * @param uniform defines the webGL uniform location where to store the value
  3281. * @param color3 defines the color to store
  3282. * @param alpha defines the alpha component to store
  3283. */
  3284. public setColor4(uniform: Nullable<WebGLUniformLocation>, color3: Color3, alpha: number): void {
  3285. if (!uniform) {
  3286. return;
  3287. }
  3288. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3289. }
  3290. /**
  3291. * Sets a Color4 on a uniform variable
  3292. * @param uniform defines the uniform location
  3293. * @param color4 defines the value to be set
  3294. */
  3295. public setDirectColor4(uniform: Nullable<WebGLUniformLocation>, color4: Color4): void {
  3296. if (!uniform) {
  3297. return;
  3298. }
  3299. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  3300. }
  3301. // States
  3302. /**
  3303. * Set various states to the webGL context
  3304. * @param culling defines backface culling state
  3305. * @param zOffset defines the value to apply to zOffset (0 by default)
  3306. * @param force defines if states must be applied even if cache is up to date
  3307. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  3308. */
  3309. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  3310. // Culling
  3311. if (this._depthCullingState.cull !== culling || force) {
  3312. this._depthCullingState.cull = culling;
  3313. }
  3314. // Cull face
  3315. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3316. if (this._depthCullingState.cullFace !== cullFace || force) {
  3317. this._depthCullingState.cullFace = cullFace;
  3318. }
  3319. // Z offset
  3320. this.setZOffset(zOffset);
  3321. // Front face
  3322. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  3323. if (this._depthCullingState.frontFace !== frontFace || force) {
  3324. this._depthCullingState.frontFace = frontFace;
  3325. }
  3326. }
  3327. /**
  3328. * Set the z offset to apply to current rendering
  3329. * @param value defines the offset to apply
  3330. */
  3331. public setZOffset(value: number): void {
  3332. this._depthCullingState.zOffset = value;
  3333. }
  3334. /**
  3335. * Gets the current value of the zOffset
  3336. * @returns the current zOffset state
  3337. */
  3338. public getZOffset(): number {
  3339. return this._depthCullingState.zOffset;
  3340. }
  3341. /**
  3342. * Enable or disable depth buffering
  3343. * @param enable defines the state to set
  3344. */
  3345. public setDepthBuffer(enable: boolean): void {
  3346. this._depthCullingState.depthTest = enable;
  3347. }
  3348. /**
  3349. * Gets a boolean indicating if depth writing is enabled
  3350. * @returns the current depth writing state
  3351. */
  3352. public getDepthWrite(): boolean {
  3353. return this._depthCullingState.depthMask;
  3354. }
  3355. /**
  3356. * Enable or disable depth writing
  3357. * @param enable defines the state to set
  3358. */
  3359. public setDepthWrite(enable: boolean): void {
  3360. this._depthCullingState.depthMask = enable;
  3361. }
  3362. /**
  3363. * Enable or disable color writing
  3364. * @param enable defines the state to set
  3365. */
  3366. public setColorWrite(enable: boolean): void {
  3367. this._gl.colorMask(enable, enable, enable, enable);
  3368. this._colorWrite = enable;
  3369. }
  3370. /**
  3371. * Gets a boolean indicating if color writing is enabled
  3372. * @returns the current color writing state
  3373. */
  3374. public getColorWrite(): boolean {
  3375. return this._colorWrite;
  3376. }
  3377. /**
  3378. * Sets alpha constants used by some alpha blending modes
  3379. * @param r defines the red component
  3380. * @param g defines the green component
  3381. * @param b defines the blue component
  3382. * @param a defines the alpha component
  3383. */
  3384. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  3385. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  3386. }
  3387. /**
  3388. * Sets the current alpha mode
  3389. * @param mode defines the mode to use (one of the Engine.ALPHA_XXX)
  3390. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  3391. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3392. */
  3393. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  3394. if (this._alphaMode === mode) {
  3395. return;
  3396. }
  3397. switch (mode) {
  3398. case Engine.ALPHA_DISABLE:
  3399. this._alphaState.alphaBlend = false;
  3400. break;
  3401. case Engine.ALPHA_PREMULTIPLIED:
  3402. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3403. this._alphaState.alphaBlend = true;
  3404. break;
  3405. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  3406. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3407. this._alphaState.alphaBlend = true;
  3408. break;
  3409. case Engine.ALPHA_COMBINE:
  3410. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3411. this._alphaState.alphaBlend = true;
  3412. break;
  3413. case Engine.ALPHA_ONEONE:
  3414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3415. this._alphaState.alphaBlend = true;
  3416. break;
  3417. case Engine.ALPHA_ADD:
  3418. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3419. this._alphaState.alphaBlend = true;
  3420. break;
  3421. case Engine.ALPHA_SUBTRACT:
  3422. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3423. this._alphaState.alphaBlend = true;
  3424. break;
  3425. case Engine.ALPHA_MULTIPLY:
  3426. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  3427. this._alphaState.alphaBlend = true;
  3428. break;
  3429. case Engine.ALPHA_MAXIMIZED:
  3430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3431. this._alphaState.alphaBlend = true;
  3432. break;
  3433. case Engine.ALPHA_INTERPOLATE:
  3434. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  3435. this._alphaState.alphaBlend = true;
  3436. break;
  3437. case Engine.ALPHA_SCREENMODE:
  3438. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3439. this._alphaState.alphaBlend = true;
  3440. break;
  3441. }
  3442. if (!noDepthWriteChange) {
  3443. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  3444. }
  3445. this._alphaMode = mode;
  3446. }
  3447. /**
  3448. * Gets the current alpha mode
  3449. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3450. * @returns the current alpha mode
  3451. */
  3452. public getAlphaMode(): number {
  3453. return this._alphaMode;
  3454. }
  3455. // Textures
  3456. /**
  3457. * Clears the list of texture accessible through engine.
  3458. * This can help preventing texture load conflict due to name collision.
  3459. */
  3460. public clearInternalTexturesCache() {
  3461. this._internalTexturesCache = [];
  3462. }
  3463. /**
  3464. * Force the entire cache to be cleared
  3465. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  3466. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  3467. */
  3468. public wipeCaches(bruteForce?: boolean): void {
  3469. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  3470. return;
  3471. }
  3472. this._currentEffect = null;
  3473. this._viewportCached.x = 0;
  3474. this._viewportCached.y = 0;
  3475. this._viewportCached.z = 0;
  3476. this._viewportCached.w = 0;
  3477. if (bruteForce) {
  3478. this.resetTextureCache();
  3479. this._currentProgram = null;
  3480. this._stencilState.reset();
  3481. this._depthCullingState.reset();
  3482. this.setDepthFunctionToLessOrEqual();
  3483. this._alphaState.reset();
  3484. this._unpackFlipYCached = null;
  3485. }
  3486. this._resetVertexBufferBinding();
  3487. this._cachedIndexBuffer = null;
  3488. this._cachedEffectForVertexBuffers = null;
  3489. this._unbindVertexArrayObject();
  3490. this.bindIndexBuffer(null);
  3491. }
  3492. /**
  3493. * Set the compressed texture format to use, based on the formats you have, and the formats
  3494. * supported by the hardware / browser.
  3495. *
  3496. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  3497. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  3498. * to API arguments needed to compressed textures. This puts the burden on the container
  3499. * generator to house the arcane code for determining these for current & future formats.
  3500. *
  3501. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  3502. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  3503. *
  3504. * Note: The result of this call is not taken into account when a texture is base64.
  3505. *
  3506. * @param formatsAvailable defines the list of those format families you have created
  3507. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  3508. *
  3509. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  3510. * @returns The extension selected.
  3511. */
  3512. public setTextureFormatToUse(formatsAvailable: Array<string>): Nullable<string> {
  3513. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  3514. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  3515. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  3516. return this._textureFormatInUse = this._texturesSupported[i];
  3517. }
  3518. }
  3519. }
  3520. // actively set format to nothing, to allow this to be called more than once
  3521. // and possibly fail the 2nd time
  3522. this._textureFormatInUse = null;
  3523. return null;
  3524. }
  3525. private _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  3526. var gl = this._gl;
  3527. var magFilter = gl.NEAREST;
  3528. var minFilter = gl.NEAREST;
  3529. switch (samplingMode) {
  3530. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  3531. magFilter = gl.LINEAR;
  3532. if (generateMipMaps) {
  3533. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3534. } else {
  3535. minFilter = gl.LINEAR;
  3536. }
  3537. break;
  3538. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  3539. magFilter = gl.LINEAR;
  3540. if (generateMipMaps) {
  3541. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3542. } else {
  3543. minFilter = gl.LINEAR;
  3544. }
  3545. break;
  3546. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  3547. magFilter = gl.NEAREST;
  3548. if (generateMipMaps) {
  3549. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3550. } else {
  3551. minFilter = gl.NEAREST;
  3552. }
  3553. break;
  3554. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  3555. magFilter = gl.NEAREST;
  3556. if (generateMipMaps) {
  3557. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  3558. } else {
  3559. minFilter = gl.NEAREST;
  3560. }
  3561. break;
  3562. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  3563. magFilter = gl.NEAREST;
  3564. if (generateMipMaps) {
  3565. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3566. } else {
  3567. minFilter = gl.LINEAR;
  3568. }
  3569. break;
  3570. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  3571. magFilter = gl.NEAREST;
  3572. if (generateMipMaps) {
  3573. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3574. } else {
  3575. minFilter = gl.LINEAR;
  3576. }
  3577. break;
  3578. case Engine.TEXTURE_NEAREST_LINEAR:
  3579. magFilter = gl.NEAREST;
  3580. minFilter = gl.LINEAR;
  3581. break;
  3582. case Engine.TEXTURE_NEAREST_NEAREST:
  3583. magFilter = gl.NEAREST;
  3584. minFilter = gl.NEAREST;
  3585. break;
  3586. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  3587. magFilter = gl.LINEAR;
  3588. if (generateMipMaps) {
  3589. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  3590. } else {
  3591. minFilter = gl.NEAREST;
  3592. }
  3593. break;
  3594. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  3595. magFilter = gl.LINEAR;
  3596. if (generateMipMaps) {
  3597. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3598. } else {
  3599. minFilter = gl.NEAREST;
  3600. }
  3601. break;
  3602. case Engine.TEXTURE_LINEAR_LINEAR:
  3603. magFilter = gl.LINEAR;
  3604. minFilter = gl.LINEAR;
  3605. break;
  3606. case Engine.TEXTURE_LINEAR_NEAREST:
  3607. magFilter = gl.LINEAR;
  3608. minFilter = gl.NEAREST;
  3609. break;
  3610. }
  3611. return {
  3612. min: minFilter,
  3613. mag: magFilter
  3614. };
  3615. }
  3616. private _partialLoadImg(url: string, index: number, loadedImages: HTMLImageElement[], scene: Nullable<Scene>,
  3617. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null) {
  3618. var img: HTMLImageElement;
  3619. var onload = () => {
  3620. loadedImages[index] = img;
  3621. (<any>loadedImages)._internalCount++;
  3622. if (scene) {
  3623. scene._removePendingData(img);
  3624. }
  3625. if ((<any>loadedImages)._internalCount === 6) {
  3626. onfinish(loadedImages);
  3627. }
  3628. };
  3629. var onerror = (message?: string, exception?: any) => {
  3630. if (scene) {
  3631. scene._removePendingData(img);
  3632. }
  3633. if (onErrorCallBack) {
  3634. onErrorCallBack(message, exception);
  3635. }
  3636. };
  3637. img = Tools.LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null);
  3638. if (scene) {
  3639. scene._addPendingData(img);
  3640. }
  3641. }
  3642. private _cascadeLoadImgs(scene: Nullable<Scene>,
  3643. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null) {
  3644. var loadedImages: HTMLImageElement[] = [];
  3645. (<any>loadedImages)._internalCount = 0;
  3646. for (let index = 0; index < 6; index++) {
  3647. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  3648. }
  3649. }
  3650. /** @hidden */
  3651. public _createTexture(): WebGLTexture {
  3652. let texture = this._gl.createTexture();
  3653. if (!texture) {
  3654. throw new Error("Unable to create texture");
  3655. }
  3656. return texture;
  3657. }
  3658. /**
  3659. * Usually called from Texture.ts.
  3660. * Passed information to create a WebGLTexture
  3661. * @param urlArg defines a value which contains one of the following:
  3662. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  3663. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  3664. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  3665. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  3666. * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
  3667. * @param scene needed for loading to the correct scene
  3668. * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
  3669. * @param onLoad optional callback to be called upon successful completion
  3670. * @param onError optional callback to be called upon failure
  3671. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  3672. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  3673. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  3674. * @param forcedExtension defines the extension to use to pick the right loader
  3675. * @param excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (default: empty array)
  3676. * @returns a InternalTexture for assignment back into BABYLON.Texture
  3677. */
  3678. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  3679. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  3680. buffer: Nullable<string | ArrayBuffer | HTMLImageElement | Blob> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  3681. forcedExtension: Nullable<string> = null, excludeLoaders: Array<IInternalTextureLoader> = []): InternalTexture {
  3682. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  3683. var fromData = url.substr(0, 5) === "data:";
  3684. var fromBlob = url.substr(0, 5) === "blob:";
  3685. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  3686. let texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  3687. // establish the file extension, if possible
  3688. var lastDot = url.lastIndexOf('.');
  3689. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  3690. let loader: Nullable<IInternalTextureLoader> = null;
  3691. for (let availableLoader of Engine._TextureLoaders) {
  3692. if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  3693. loader = availableLoader;
  3694. break;
  3695. }
  3696. }
  3697. if (loader) {
  3698. url = loader.transformUrl(url, this._textureFormatInUse);
  3699. }
  3700. if (scene) {
  3701. scene._addPendingData(texture);
  3702. }
  3703. texture.url = url;
  3704. texture.generateMipMaps = !noMipmap;
  3705. texture.samplingMode = samplingMode;
  3706. texture.invertY = invertY;
  3707. if (!this._doNotHandleContextLost) {
  3708. // Keep a link to the buffer only if we plan to handle context lost
  3709. texture._buffer = buffer;
  3710. }
  3711. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  3712. if (onLoad && !fallback) {
  3713. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  3714. }
  3715. if (!fallback) { this._internalTexturesCache.push(texture); }
  3716. let onInternalError = (message?: string, exception?: any) => {
  3717. if (scene) {
  3718. scene._removePendingData(texture);
  3719. }
  3720. let customFallback = false;
  3721. if (loader) {
  3722. const fallbackUrl = loader.getFallbackTextureUrl(url, this._textureFormatInUse);
  3723. if (fallbackUrl) {
  3724. // Add Back
  3725. customFallback = true;
  3726. excludeLoaders.push(loader);
  3727. Tools.Warn((loader.constructor as any).name + " failed when trying to load " + texture.url + ", falling back to the next supported loader");
  3728. this.createTexture(urlArg, noMipmap, texture.invertY, scene, samplingMode, null, null, buffer, texture, undefined, undefined, excludeLoaders);
  3729. }
  3730. }
  3731. if (!customFallback) {
  3732. if (onLoadObserver) {
  3733. texture.onLoadedObservable.remove(onLoadObserver);
  3734. }
  3735. if (Tools.UseFallbackTexture) {
  3736. this.createTexture(Tools.fallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, null, buffer, texture);
  3737. }
  3738. }
  3739. if (onError) {
  3740. onError(message || "Unknown error", exception);
  3741. }
  3742. };
  3743. // processing for non-image formats
  3744. if (loader) {
  3745. var callback = (data: string | ArrayBuffer) => {
  3746. loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void, loadFailed) => {
  3747. if (loadFailed) {
  3748. onInternalError("TextureLoader failed to load data");
  3749. } else {
  3750. this._prepareWebGLTexture(texture, scene, width, height, texture.invertY, !loadMipmap, isCompressed, () => {
  3751. done();
  3752. return false;
  3753. }, samplingMode);
  3754. }
  3755. });
  3756. };
  3757. if (!buffer) {
  3758. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  3759. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  3760. });
  3761. } else {
  3762. callback(buffer as ArrayBuffer);
  3763. }
  3764. } else {
  3765. var onload = (img: HTMLImageElement) => {
  3766. if (fromBlob && !this._doNotHandleContextLost) {
  3767. // We need to store the image if we need to rebuild the texture
  3768. // in case of a webgl context lost
  3769. texture._buffer = img;
  3770. }
  3771. this._prepareWebGLTexture(texture, scene, img.width, img.height, texture.invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  3772. let gl = this._gl;
  3773. var isPot = (img.width === potWidth && img.height === potHeight);
  3774. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  3775. if (isPot) {
  3776. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3777. return false;
  3778. }
  3779. let maxTextureSize = this._caps.maxTextureSize;
  3780. if (img.width > maxTextureSize || img.height > maxTextureSize || Engine._RescalePostProcessFactory === null) {
  3781. this._prepareWorkingCanvas();
  3782. if (!this._workingCanvas || !this._workingContext) {
  3783. return false;
  3784. }
  3785. this._workingCanvas.width = potWidth;
  3786. this._workingCanvas.height = potHeight;
  3787. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3788. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  3789. texture.width = potWidth;
  3790. texture.height = potHeight;
  3791. return false;
  3792. } else {
  3793. // Using shaders when possible to rescale because canvas.drawImage is lossy
  3794. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3795. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  3796. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3797. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3798. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3801. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  3802. this._releaseTexture(source);
  3803. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3804. continuationCallback();
  3805. });
  3806. }
  3807. return true;
  3808. }, samplingMode);
  3809. };
  3810. if (!fromData || isBase64) {
  3811. if (buffer instanceof HTMLImageElement) {
  3812. onload(buffer);
  3813. } else {
  3814. Tools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null);
  3815. }
  3816. }
  3817. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  3818. Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null);
  3819. }
  3820. else {
  3821. onload(<HTMLImageElement>buffer);
  3822. }
  3823. }
  3824. return texture;
  3825. }
  3826. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  3827. let rtt = this.createRenderTargetTexture({
  3828. width: destination.width,
  3829. height: destination.height,
  3830. }, {
  3831. generateMipMaps: false,
  3832. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  3833. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  3834. generateDepthBuffer: false,
  3835. generateStencilBuffer: false
  3836. }
  3837. );
  3838. if (!this._rescalePostProcess && Engine._RescalePostProcessFactory) {
  3839. this._rescalePostProcess = Engine._RescalePostProcessFactory(this);
  3840. }
  3841. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  3842. this._rescalePostProcess.onApply = function(effect) {
  3843. effect._bindTexture("textureSampler", source);
  3844. };
  3845. let hostingScene = scene;
  3846. if (!hostingScene) {
  3847. hostingScene = this.scenes[this.scenes.length - 1];
  3848. }
  3849. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  3850. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  3851. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  3852. this.unBindFramebuffer(rtt);
  3853. this._releaseTexture(rtt);
  3854. if (onComplete) {
  3855. onComplete();
  3856. }
  3857. });
  3858. }
  3859. /**
  3860. * Update a raw texture
  3861. * @param texture defines the texture to update
  3862. * @param data defines the data to store in the texture
  3863. * @param format defines the format of the data
  3864. * @param invertY defines if data must be stored with Y axis inverted
  3865. * @param compression defines the compression used (null by default)
  3866. * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3867. */
  3868. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  3869. if (!texture) {
  3870. return;
  3871. }
  3872. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  3873. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  3874. // babylon's internalFormat but gl's texImage2D format
  3875. var internalFormat = this._getInternalFormat(format);
  3876. var textureType = this._getWebGLTextureType(type);
  3877. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3878. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  3879. if (!this._doNotHandleContextLost) {
  3880. texture._bufferView = data;
  3881. texture.format = format;
  3882. texture.type = type;
  3883. texture.invertY = invertY;
  3884. texture._compression = compression;
  3885. }
  3886. if (texture.width % 4 !== 0) {
  3887. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3888. }
  3889. if (compression && data) {
  3890. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, <DataView>data);
  3891. } else {
  3892. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  3893. }
  3894. if (texture.generateMipMaps) {
  3895. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3896. }
  3897. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3898. // this.resetTextureCache();
  3899. texture.isReady = true;
  3900. }
  3901. /**
  3902. * Creates a raw texture
  3903. * @param data defines the data to store in the texture
  3904. * @param width defines the width of the texture
  3905. * @param height defines the height of the texture
  3906. * @param format defines the format of the data
  3907. * @param generateMipMaps defines if the engine should generate the mip levels
  3908. * @param invertY defines if data must be stored with Y axis inverted
  3909. * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
  3910. * @param compression defines the compression used (null by default)
  3911. * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3912. * @returns the raw texture inside an InternalTexture
  3913. */
  3914. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, type: number = Engine.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  3915. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  3916. texture.baseWidth = width;
  3917. texture.baseHeight = height;
  3918. texture.width = width;
  3919. texture.height = height;
  3920. texture.format = format;
  3921. texture.generateMipMaps = generateMipMaps;
  3922. texture.samplingMode = samplingMode;
  3923. texture.invertY = invertY;
  3924. texture._compression = compression;
  3925. texture.type = type;
  3926. if (!this._doNotHandleContextLost) {
  3927. texture._bufferView = data;
  3928. }
  3929. this.updateRawTexture(texture, data, format, invertY, compression, type);
  3930. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3931. // Filters
  3932. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  3933. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3934. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3935. if (generateMipMaps) {
  3936. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3937. }
  3938. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3939. this._internalTexturesCache.push(texture);
  3940. return texture;
  3941. }
  3942. private _unpackFlipYCached: Nullable<boolean> = null;
  3943. /**
  3944. * In case you are sharing the context with other applications, it might
  3945. * be interested to not cache the unpack flip y state to ensure a consistent
  3946. * value would be set.
  3947. */
  3948. public enableUnpackFlipYCached = true;
  3949. /** @hidden */
  3950. public _unpackFlipY(value: boolean): void {
  3951. if (this._unpackFlipYCached !== value) {
  3952. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  3953. if (this.enableUnpackFlipYCached) {
  3954. this._unpackFlipYCached = value;
  3955. }
  3956. }
  3957. }
  3958. /** @hidden */
  3959. public _getUnpackAlignement(): number {
  3960. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  3961. }
  3962. /**
  3963. * Creates a dynamic texture
  3964. * @param width defines the width of the texture
  3965. * @param height defines the height of the texture
  3966. * @param generateMipMaps defines if the engine should generate the mip levels
  3967. * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
  3968. * @returns the dynamic texture inside an InternalTexture
  3969. */
  3970. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  3971. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC);
  3972. texture.baseWidth = width;
  3973. texture.baseHeight = height;
  3974. if (generateMipMaps) {
  3975. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  3976. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  3977. }
  3978. // this.resetTextureCache();
  3979. texture.width = width;
  3980. texture.height = height;
  3981. texture.isReady = false;
  3982. texture.generateMipMaps = generateMipMaps;
  3983. texture.samplingMode = samplingMode;
  3984. this.updateTextureSamplingMode(samplingMode, texture);
  3985. this._internalTexturesCache.push(texture);
  3986. return texture;
  3987. }
  3988. /**
  3989. * Update the sampling mode of a given texture
  3990. * @param samplingMode defines the required sampling mode
  3991. * @param texture defines the texture to update
  3992. */
  3993. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  3994. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  3995. if (texture.isCube) {
  3996. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3997. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3998. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3999. } else if (texture.is3D) {
  4000. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  4001. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4002. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  4003. } else {
  4004. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  4005. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4006. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  4007. }
  4008. texture.samplingMode = samplingMode;
  4009. }
  4010. /**
  4011. * Update the content of a dynamic texture
  4012. * @param texture defines the texture to update
  4013. * @param canvas defines the canvas containing the source
  4014. * @param invertY defines if data must be stored with Y axis inverted
  4015. * @param premulAlpha defines if alpha is stored as premultiplied
  4016. * @param format defines the format of the data
  4017. * @param forceBindTexture if the texture should be forced to be bound eg. after a graphics context loss (Default: false)
  4018. */
  4019. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number, forceBindTexture: boolean = false): void {
  4020. if (!texture) {
  4021. return;
  4022. }
  4023. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true, forceBindTexture);
  4024. this._unpackFlipY(invertY);
  4025. if (premulAlpha) {
  4026. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  4027. }
  4028. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  4029. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  4030. if (texture.generateMipMaps) {
  4031. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4032. }
  4033. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  4034. if (premulAlpha) {
  4035. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  4036. }
  4037. texture.isReady = true;
  4038. }
  4039. /**
  4040. * Update a video texture
  4041. * @param texture defines the texture to update
  4042. * @param video defines the video element to use
  4043. * @param invertY defines if data must be stored with Y axis inverted
  4044. */
  4045. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  4046. if (!texture || texture._isDisabled) {
  4047. return;
  4048. }
  4049. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  4050. this._unpackFlipY(!invertY); // Video are upside down by default
  4051. try {
  4052. // Testing video texture support
  4053. if (this._videoTextureSupported === undefined) {
  4054. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4055. if (this._gl.getError() !== 0) {
  4056. this._videoTextureSupported = false;
  4057. } else {
  4058. this._videoTextureSupported = true;
  4059. }
  4060. }
  4061. // Copy video through the current working canvas if video texture is not supported
  4062. if (!this._videoTextureSupported) {
  4063. if (!texture._workingCanvas) {
  4064. texture._workingCanvas = document.createElement("canvas");
  4065. let context = texture._workingCanvas.getContext("2d");
  4066. if (!context) {
  4067. throw new Error("Unable to get 2d context");
  4068. }
  4069. texture._workingContext = context;
  4070. texture._workingCanvas.width = texture.width;
  4071. texture._workingCanvas.height = texture.height;
  4072. }
  4073. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  4074. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4075. } else {
  4076. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4077. }
  4078. if (texture.generateMipMaps) {
  4079. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4080. }
  4081. if (!wasPreviouslyBound) {
  4082. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  4083. }
  4084. // this.resetTextureCache();
  4085. texture.isReady = true;
  4086. } catch (ex) {
  4087. // Something unexpected
  4088. // Let's disable the texture
  4089. texture._isDisabled = true;
  4090. }
  4091. }
  4092. /**
  4093. * Updates a depth texture Comparison Mode and Function.
  4094. * If the comparison Function is equal to 0, the mode will be set to none.
  4095. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  4096. * @param texture The texture to set the comparison function for
  4097. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  4098. */
  4099. public updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void {
  4100. if (this.webGLVersion === 1) {
  4101. Logger.Error("WebGL 1 does not support texture comparison.");
  4102. return;
  4103. }
  4104. var gl = this._gl;
  4105. if (texture.isCube) {
  4106. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  4107. if (comparisonFunction === 0) {
  4108. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  4109. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  4110. }
  4111. else {
  4112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  4113. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  4114. }
  4115. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4116. } else {
  4117. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  4118. if (comparisonFunction === 0) {
  4119. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  4120. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  4121. }
  4122. else {
  4123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  4124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  4125. }
  4126. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  4127. }
  4128. texture._comparisonFunction = comparisonFunction;
  4129. }
  4130. private _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number): void {
  4131. var width = (<{ width: number, height: number }>size).width || <number>size;
  4132. var height = (<{ width: number, height: number }>size).height || <number>size;
  4133. internalTexture.baseWidth = width;
  4134. internalTexture.baseHeight = height;
  4135. internalTexture.width = width;
  4136. internalTexture.height = height;
  4137. internalTexture.isReady = true;
  4138. internalTexture.samples = 1;
  4139. internalTexture.generateMipMaps = false;
  4140. internalTexture._generateDepthBuffer = true;
  4141. internalTexture._generateStencilBuffer = generateStencil;
  4142. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4143. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4144. internalTexture._comparisonFunction = comparisonFunction;
  4145. var gl = this._gl;
  4146. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4147. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  4148. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  4149. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  4150. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4151. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4152. if (comparisonFunction === 0) {
  4153. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  4154. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  4155. }
  4156. else {
  4157. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  4158. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  4159. }
  4160. }
  4161. /**
  4162. * Creates a depth stencil texture.
  4163. * This is only available in WebGL 2 or with the depth texture extension available.
  4164. * @param size The size of face edge in the texture.
  4165. * @param options The options defining the texture.
  4166. * @returns The texture
  4167. */
  4168. public createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions): InternalTexture {
  4169. if (options.isCube) {
  4170. let width = (<{ width: number, height: number }>size).width || <number>size;
  4171. return this._createDepthStencilCubeTexture(width, options);
  4172. }
  4173. else {
  4174. return this._createDepthStencilTexture(size, options);
  4175. }
  4176. }
  4177. /**
  4178. * Creates a depth stencil texture.
  4179. * This is only available in WebGL 2 or with the depth texture extension available.
  4180. * @param size The size of face edge in the texture.
  4181. * @param options The options defining the texture.
  4182. * @returns The texture
  4183. */
  4184. private _createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions): InternalTexture {
  4185. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_DEPTHTEXTURE);
  4186. if (!this._caps.depthTextureExtension) {
  4187. Logger.Error("Depth texture is not supported by your browser or hardware.");
  4188. return internalTexture;
  4189. }
  4190. var internalOptions = {
  4191. bilinearFiltering: false,
  4192. comparisonFunction: 0,
  4193. generateStencil: false,
  4194. ...options
  4195. };
  4196. var gl = this._gl;
  4197. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  4198. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4199. if (this.webGLVersion > 1) {
  4200. if (internalOptions.generateStencil) {
  4201. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4202. }
  4203. else {
  4204. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4205. }
  4206. }
  4207. else {
  4208. if (internalOptions.generateStencil) {
  4209. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4210. }
  4211. else {
  4212. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4213. }
  4214. }
  4215. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4216. return internalTexture;
  4217. }
  4218. /**
  4219. * Creates a depth stencil cube texture.
  4220. * This is only available in WebGL 2.
  4221. * @param size The size of face edge in the cube texture.
  4222. * @param options The options defining the cube texture.
  4223. * @returns The cube texture
  4224. */
  4225. private _createDepthStencilCubeTexture(size: number, options: DepthTextureCreationOptions): InternalTexture {
  4226. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_UNKNOWN);
  4227. internalTexture.isCube = true;
  4228. if (this.webGLVersion === 1) {
  4229. Logger.Error("Depth cube texture is not supported by WebGL 1.");
  4230. return internalTexture;
  4231. }
  4232. var internalOptions = {
  4233. bilinearFiltering: false,
  4234. comparisonFunction: 0,
  4235. generateStencil: false,
  4236. ...options
  4237. };
  4238. var gl = this._gl;
  4239. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  4240. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4241. // Create the depth/stencil buffer
  4242. for (var face = 0; face < 6; face++) {
  4243. if (internalOptions.generateStencil) {
  4244. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4245. }
  4246. else {
  4247. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4248. }
  4249. }
  4250. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4251. return internalTexture;
  4252. }
  4253. /**
  4254. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  4255. * @param renderTarget The render target to set the frame buffer for
  4256. */
  4257. public setFrameBufferDepthStencilTexture(renderTarget: RenderTargetTexture): void {
  4258. // Create the framebuffer
  4259. var internalTexture = renderTarget.getInternalTexture();
  4260. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  4261. return;
  4262. }
  4263. var gl = this._gl;
  4264. var depthStencilTexture = renderTarget.depthStencilTexture;
  4265. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  4266. if (depthStencilTexture.isCube) {
  4267. if (depthStencilTexture._generateStencilBuffer) {
  4268. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4269. }
  4270. else {
  4271. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4272. }
  4273. }
  4274. else {
  4275. if (depthStencilTexture._generateStencilBuffer) {
  4276. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4277. }
  4278. else {
  4279. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4280. }
  4281. }
  4282. this.bindUnboundFramebuffer(null);
  4283. }
  4284. /**
  4285. * Creates a new render target texture
  4286. * @param size defines the size of the texture
  4287. * @param options defines the options used to create the texture
  4288. * @returns a new render target texture stored in an InternalTexture
  4289. */
  4290. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  4291. let fullOptions = new RenderTargetCreationOptions();
  4292. if (options !== undefined && typeof options === "object") {
  4293. fullOptions.generateMipMaps = options.generateMipMaps;
  4294. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4295. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  4296. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  4297. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  4298. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  4299. } else {
  4300. fullOptions.generateMipMaps = <boolean>options;
  4301. fullOptions.generateDepthBuffer = true;
  4302. fullOptions.generateStencilBuffer = false;
  4303. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4304. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  4305. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  4306. }
  4307. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4308. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4309. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4310. }
  4311. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4312. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4313. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4314. }
  4315. var gl = this._gl;
  4316. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4317. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  4318. var width = (<{ width: number, height: number }>size).width || <number>size;
  4319. var height = (<{ width: number, height: number }>size).height || <number>size;
  4320. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  4321. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4322. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4323. Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4324. }
  4325. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4326. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4327. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4328. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4329. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4330. // Create the framebuffer
  4331. var currentFrameBuffer = this._currentFramebuffer;
  4332. var framebuffer = gl.createFramebuffer();
  4333. this.bindUnboundFramebuffer(framebuffer);
  4334. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4335. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  4336. if (fullOptions.generateMipMaps) {
  4337. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4338. }
  4339. // Unbind
  4340. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4341. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4342. this.bindUnboundFramebuffer(currentFrameBuffer);
  4343. texture._framebuffer = framebuffer;
  4344. texture.baseWidth = width;
  4345. texture.baseHeight = height;
  4346. texture.width = width;
  4347. texture.height = height;
  4348. texture.isReady = true;
  4349. texture.samples = 1;
  4350. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  4351. texture.samplingMode = fullOptions.samplingMode;
  4352. texture.type = fullOptions.type;
  4353. texture.format = fullOptions.format;
  4354. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4355. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  4356. // this.resetTextureCache();
  4357. this._internalTexturesCache.push(texture);
  4358. return texture;
  4359. }
  4360. /**
  4361. * Create a multi render target texture
  4362. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  4363. * @param size defines the size of the texture
  4364. * @param options defines the creation options
  4365. * @returns the cube texture as an InternalTexture
  4366. */
  4367. public createMultipleRenderTarget(size: any, options: IMultiRenderTargetOptions): InternalTexture[] {
  4368. var generateMipMaps = false;
  4369. var generateDepthBuffer = true;
  4370. var generateStencilBuffer = false;
  4371. var generateDepthTexture = false;
  4372. var textureCount = 1;
  4373. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  4374. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  4375. var types = new Array<number>();
  4376. var samplingModes = new Array<number>();
  4377. if (options !== undefined) {
  4378. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  4379. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4380. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  4381. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  4382. textureCount = options.textureCount || 1;
  4383. if (options.types) {
  4384. types = options.types;
  4385. }
  4386. if (options.samplingModes) {
  4387. samplingModes = options.samplingModes;
  4388. }
  4389. }
  4390. var gl = this._gl;
  4391. // Create the framebuffer
  4392. var framebuffer = gl.createFramebuffer();
  4393. this.bindUnboundFramebuffer(framebuffer);
  4394. var width = size.width || size;
  4395. var height = size.height || size;
  4396. var textures = [];
  4397. var attachments = [];
  4398. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  4399. for (var i = 0; i < textureCount; i++) {
  4400. var samplingMode = samplingModes[i] || defaultSamplingMode;
  4401. var type = types[i] || defaultType;
  4402. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4403. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4404. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4405. }
  4406. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4407. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4408. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4409. }
  4410. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  4411. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4412. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4413. Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4414. }
  4415. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4416. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4417. textures.push(texture);
  4418. attachments.push(attachment);
  4419. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  4420. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  4421. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4425. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4426. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4427. if (generateMipMaps) {
  4428. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4429. }
  4430. // Unbind
  4431. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4432. texture._framebuffer = framebuffer;
  4433. texture._depthStencilBuffer = depthStencilBuffer;
  4434. texture.baseWidth = width;
  4435. texture.baseHeight = height;
  4436. texture.width = width;
  4437. texture.height = height;
  4438. texture.isReady = true;
  4439. texture.samples = 1;
  4440. texture.generateMipMaps = generateMipMaps;
  4441. texture.samplingMode = samplingMode;
  4442. texture.type = type;
  4443. texture._generateDepthBuffer = generateDepthBuffer;
  4444. texture._generateStencilBuffer = generateStencilBuffer;
  4445. texture._attachments = attachments;
  4446. this._internalTexturesCache.push(texture);
  4447. }
  4448. if (generateDepthTexture && this._caps.depthTextureExtension) {
  4449. // Depth texture
  4450. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4451. gl.activeTexture(gl.TEXTURE0);
  4452. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  4453. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4454. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4455. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4456. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4457. gl.texImage2D(
  4458. gl.TEXTURE_2D,
  4459. 0,
  4460. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  4461. width,
  4462. height,
  4463. 0,
  4464. gl.DEPTH_COMPONENT,
  4465. gl.UNSIGNED_SHORT,
  4466. null
  4467. );
  4468. gl.framebufferTexture2D(
  4469. gl.FRAMEBUFFER,
  4470. gl.DEPTH_ATTACHMENT,
  4471. gl.TEXTURE_2D,
  4472. depthTexture._webGLTexture,
  4473. 0
  4474. );
  4475. depthTexture._framebuffer = framebuffer;
  4476. depthTexture.baseWidth = width;
  4477. depthTexture.baseHeight = height;
  4478. depthTexture.width = width;
  4479. depthTexture.height = height;
  4480. depthTexture.isReady = true;
  4481. depthTexture.samples = 1;
  4482. depthTexture.generateMipMaps = generateMipMaps;
  4483. depthTexture.samplingMode = gl.NEAREST;
  4484. depthTexture._generateDepthBuffer = generateDepthBuffer;
  4485. depthTexture._generateStencilBuffer = generateStencilBuffer;
  4486. textures.push(depthTexture);
  4487. this._internalTexturesCache.push(depthTexture);
  4488. }
  4489. gl.drawBuffers(attachments);
  4490. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4491. this.bindUnboundFramebuffer(null);
  4492. this.resetTextureCache();
  4493. return textures;
  4494. }
  4495. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  4496. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  4497. var gl = this._gl;
  4498. // Create the depth/stencil buffer
  4499. if (generateStencilBuffer) {
  4500. depthStencilBuffer = gl.createRenderbuffer();
  4501. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4502. if (samples > 1) {
  4503. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  4504. } else {
  4505. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  4506. }
  4507. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4508. }
  4509. else if (generateDepthBuffer) {
  4510. depthStencilBuffer = gl.createRenderbuffer();
  4511. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4512. if (samples > 1) {
  4513. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  4514. } else {
  4515. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4516. }
  4517. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4518. }
  4519. return depthStencilBuffer;
  4520. }
  4521. /**
  4522. * Updates the sample count of a render target texture
  4523. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4524. * @param texture defines the texture to update
  4525. * @param samples defines the sample count to set
  4526. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4527. */
  4528. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  4529. if (this.webGLVersion < 2 || !texture) {
  4530. return 1;
  4531. }
  4532. if (texture.samples === samples) {
  4533. return samples;
  4534. }
  4535. var gl = this._gl;
  4536. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4537. // Dispose previous render buffers
  4538. if (texture._depthStencilBuffer) {
  4539. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  4540. texture._depthStencilBuffer = null;
  4541. }
  4542. if (texture._MSAAFramebuffer) {
  4543. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  4544. texture._MSAAFramebuffer = null;
  4545. }
  4546. if (texture._MSAARenderBuffer) {
  4547. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  4548. texture._MSAARenderBuffer = null;
  4549. }
  4550. if (samples > 1) {
  4551. let framebuffer = gl.createFramebuffer();
  4552. if (!framebuffer) {
  4553. throw new Error("Unable to create multi sampled framebuffer");
  4554. }
  4555. texture._MSAAFramebuffer = framebuffer;
  4556. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  4557. var colorRenderbuffer = gl.createRenderbuffer();
  4558. if (!colorRenderbuffer) {
  4559. throw new Error("Unable to create multi sampled framebuffer");
  4560. }
  4561. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4562. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4563. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  4564. texture._MSAARenderBuffer = colorRenderbuffer;
  4565. } else {
  4566. this.bindUnboundFramebuffer(texture._framebuffer);
  4567. }
  4568. texture.samples = samples;
  4569. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  4570. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4571. this.bindUnboundFramebuffer(null);
  4572. return samples;
  4573. }
  4574. /**
  4575. * Update the sample count for a given multiple render target texture
  4576. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4577. * @param textures defines the textures to update
  4578. * @param samples defines the sample count to set
  4579. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4580. */
  4581. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  4582. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  4583. return 1;
  4584. }
  4585. if (textures[0].samples === samples) {
  4586. return samples;
  4587. }
  4588. var gl = this._gl;
  4589. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4590. // Dispose previous render buffers
  4591. if (textures[0]._depthStencilBuffer) {
  4592. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  4593. textures[0]._depthStencilBuffer = null;
  4594. }
  4595. if (textures[0]._MSAAFramebuffer) {
  4596. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  4597. textures[0]._MSAAFramebuffer = null;
  4598. }
  4599. for (var i = 0; i < textures.length; i++) {
  4600. if (textures[i]._MSAARenderBuffer) {
  4601. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  4602. textures[i]._MSAARenderBuffer = null;
  4603. }
  4604. }
  4605. if (samples > 1) {
  4606. let framebuffer = gl.createFramebuffer();
  4607. if (!framebuffer) {
  4608. throw new Error("Unable to create multi sampled framebuffer");
  4609. }
  4610. this.bindUnboundFramebuffer(framebuffer);
  4611. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  4612. var attachments = [];
  4613. for (var i = 0; i < textures.length; i++) {
  4614. var texture = textures[i];
  4615. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4616. var colorRenderbuffer = gl.createRenderbuffer();
  4617. if (!colorRenderbuffer) {
  4618. throw new Error("Unable to create multi sampled framebuffer");
  4619. }
  4620. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4621. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4622. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  4623. texture._MSAAFramebuffer = framebuffer;
  4624. texture._MSAARenderBuffer = colorRenderbuffer;
  4625. texture.samples = samples;
  4626. texture._depthStencilBuffer = depthStencilBuffer;
  4627. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4628. attachments.push(attachment);
  4629. }
  4630. gl.drawBuffers(attachments);
  4631. } else {
  4632. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  4633. }
  4634. this.bindUnboundFramebuffer(null);
  4635. return samples;
  4636. }
  4637. /** @hidden */
  4638. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  4639. var gl = this._gl;
  4640. var target = gl.TEXTURE_2D;
  4641. if (texture.isCube) {
  4642. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4643. }
  4644. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  4645. }
  4646. /** @hidden */
  4647. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  4648. var gl = this._gl;
  4649. var textureType = this._getWebGLTextureType(texture.type);
  4650. var format = this._getInternalFormat(texture.format);
  4651. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  4652. this._unpackFlipY(texture.invertY);
  4653. var target = gl.TEXTURE_2D;
  4654. if (texture.isCube) {
  4655. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4656. }
  4657. const lodMaxWidth = Math.round(Scalar.Log2(texture.width));
  4658. const lodMaxHeight = Math.round(Scalar.Log2(texture.height));
  4659. const width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  4660. const height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  4661. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  4662. }
  4663. /** @hidden */
  4664. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  4665. var gl = this._gl;
  4666. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4667. this._bindTextureDirectly(bindTarget, texture, true);
  4668. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  4669. this._bindTextureDirectly(bindTarget, null, true);
  4670. }
  4671. /** @hidden */
  4672. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  4673. var gl = this._gl;
  4674. var textureType = this._getWebGLTextureType(texture.type);
  4675. var format = this._getInternalFormat(texture.format);
  4676. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  4677. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4678. this._bindTextureDirectly(bindTarget, texture, true);
  4679. this._unpackFlipY(texture.invertY);
  4680. var target = gl.TEXTURE_2D;
  4681. if (texture.isCube) {
  4682. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4683. }
  4684. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  4685. this._bindTextureDirectly(bindTarget, null, true);
  4686. }
  4687. /**
  4688. * Creates a new render target cube texture
  4689. * @param size defines the size of the texture
  4690. * @param options defines the options used to create the texture
  4691. * @returns a new render target cube texture stored in an InternalTexture
  4692. */
  4693. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  4694. let fullOptions = {
  4695. generateMipMaps: true,
  4696. generateDepthBuffer: true,
  4697. generateStencilBuffer: false,
  4698. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  4699. samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  4700. format: Engine.TEXTUREFORMAT_RGBA,
  4701. ...options
  4702. };
  4703. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  4704. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4705. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4706. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4707. }
  4708. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4709. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4710. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4711. }
  4712. var gl = this._gl;
  4713. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4714. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4715. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  4716. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4717. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4718. Logger.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  4719. }
  4720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4724. for (var face = 0; face < 6; face++) {
  4725. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4726. }
  4727. // Create the framebuffer
  4728. var framebuffer = gl.createFramebuffer();
  4729. this.bindUnboundFramebuffer(framebuffer);
  4730. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  4731. // MipMaps
  4732. if (fullOptions.generateMipMaps) {
  4733. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4734. }
  4735. // Unbind
  4736. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4737. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4738. this.bindUnboundFramebuffer(null);
  4739. texture._framebuffer = framebuffer;
  4740. texture.width = size;
  4741. texture.height = size;
  4742. texture.isReady = true;
  4743. texture.isCube = true;
  4744. texture.samples = 1;
  4745. texture.generateMipMaps = fullOptions.generateMipMaps;
  4746. texture.samplingMode = fullOptions.samplingMode;
  4747. texture.type = fullOptions.type;
  4748. texture.format = fullOptions.format;
  4749. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4750. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  4751. this._internalTexturesCache.push(texture);
  4752. return texture;
  4753. }
  4754. /**
  4755. * Creates a cube texture
  4756. * @param rootUrl defines the url where the files to load is located
  4757. * @param scene defines the current scene
  4758. * @param files defines the list of files to load (1 per face)
  4759. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  4760. * @param onLoad defines an optional callback raised when the texture is loaded
  4761. * @param onError defines an optional callback raised if there is an issue to load the texture
  4762. * @param format defines the format of the data
  4763. * @param forcedExtension defines the extension to use to pick the right loader
  4764. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  4765. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  4766. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  4767. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  4768. * @param excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (defualt: empty array)
  4769. * @returns the cube texture as an InternalTexture
  4770. */
  4771. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null, onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null, createPolynomials = false, lodScale: number = 0, lodOffset: number = 0, fallback: Nullable<InternalTexture> = null, excludeLoaders: Array<IInternalTextureLoader> = []): InternalTexture {
  4772. var gl = this._gl;
  4773. var texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  4774. texture.isCube = true;
  4775. texture.url = rootUrl;
  4776. texture.generateMipMaps = !noMipmap;
  4777. texture._lodGenerationScale = lodScale;
  4778. texture._lodGenerationOffset = lodOffset;
  4779. if (!this._doNotHandleContextLost) {
  4780. texture._extension = forcedExtension;
  4781. texture._files = files;
  4782. }
  4783. var lastDot = rootUrl.lastIndexOf('.');
  4784. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  4785. let loader: Nullable<IInternalTextureLoader> = null;
  4786. for (let availableLoader of Engine._TextureLoaders) {
  4787. if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  4788. loader = availableLoader;
  4789. break;
  4790. }
  4791. }
  4792. let onInternalError = (request?: XMLHttpRequest, exception?: any) => {
  4793. if (loader) {
  4794. const fallbackUrl = loader.getFallbackTextureUrl(texture.url, this._textureFormatInUse);
  4795. Logger.Warn((loader.constructor as any).name + " failed when trying to load " + texture.url + ", falling back to the next supported loader");
  4796. if (fallbackUrl) {
  4797. excludeLoaders.push(loader);
  4798. this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture, excludeLoaders);
  4799. return;
  4800. }
  4801. }
  4802. if (onError && request) {
  4803. onError(request.status + " " + request.statusText, exception);
  4804. }
  4805. };
  4806. if (loader) {
  4807. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  4808. const onloaddata = (data: any) => {
  4809. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4810. loader!.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  4811. };
  4812. if (files && files.length === 6) {
  4813. if (loader.supportCascades) {
  4814. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  4815. }
  4816. else if (onError) {
  4817. onError("Textures type does not support cascades.");
  4818. }
  4819. }
  4820. else {
  4821. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  4822. }
  4823. }
  4824. else {
  4825. if (!files) {
  4826. throw new Error("Cannot load cubemap because files were not defined");
  4827. }
  4828. this._cascadeLoadImgs(scene, (imgs) => {
  4829. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  4830. var height = width;
  4831. this._prepareWorkingCanvas();
  4832. if (!this._workingCanvas || !this._workingContext) {
  4833. return;
  4834. }
  4835. this._workingCanvas.width = width;
  4836. this._workingCanvas.height = height;
  4837. var faces = [
  4838. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4839. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4840. ];
  4841. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4842. this._unpackFlipY(false);
  4843. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  4844. for (var index = 0; index < faces.length; index++) {
  4845. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4846. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  4847. }
  4848. if (!noMipmap) {
  4849. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4850. }
  4851. this._setCubeMapTextureParams(!noMipmap);
  4852. texture.width = width;
  4853. texture.height = height;
  4854. texture.isReady = true;
  4855. if (format) {
  4856. texture.format = format;
  4857. }
  4858. texture.onLoadedObservable.notifyObservers(texture);
  4859. texture.onLoadedObservable.clear();
  4860. if (onLoad) {
  4861. onLoad();
  4862. }
  4863. }, files, onError);
  4864. }
  4865. this._internalTexturesCache.push(texture);
  4866. return texture;
  4867. }
  4868. /**
  4869. * @hidden
  4870. */
  4871. public _setCubeMapTextureParams(loadMipmap: boolean): void {
  4872. var gl = this._gl;
  4873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4877. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4878. // this.resetTextureCache();
  4879. }
  4880. /**
  4881. * Update a raw cube texture
  4882. * @param texture defines the texture to udpdate
  4883. * @param data defines the data to store
  4884. * @param format defines the data format
  4885. * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
  4886. * @param invertY defines if data must be stored with Y axis inverted
  4887. * @param compression defines the compression used (null by default)
  4888. * @param level defines which level of the texture to update
  4889. */
  4890. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  4891. texture._bufferViewArray = data;
  4892. texture.format = format;
  4893. texture.type = type;
  4894. texture.invertY = invertY;
  4895. texture._compression = compression;
  4896. var gl = this._gl;
  4897. var textureType = this._getWebGLTextureType(type);
  4898. var internalFormat = this._getInternalFormat(format);
  4899. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4900. var needConversion = false;
  4901. if (internalFormat === gl.RGB) {
  4902. internalFormat = gl.RGBA;
  4903. needConversion = true;
  4904. }
  4905. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4906. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  4907. if (texture.width % 4 !== 0) {
  4908. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  4909. }
  4910. // Data are known to be in +X +Y +Z -X -Y -Z
  4911. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  4912. let faceData = data[faceIndex];
  4913. if (compression) {
  4914. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, <DataView>faceData);
  4915. } else {
  4916. if (needConversion) {
  4917. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  4918. }
  4919. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  4920. }
  4921. }
  4922. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4923. if (isPot && texture.generateMipMaps && level === 0) {
  4924. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4925. }
  4926. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4927. // this.resetTextureCache();
  4928. texture.isReady = true;
  4929. }
  4930. /**
  4931. * Creates a new raw cube texture
  4932. * @param data defines the array of data to use to create each face
  4933. * @param size defines the size of the textures
  4934. * @param format defines the format of the data
  4935. * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT)
  4936. * @param generateMipMaps defines if the engine should generate the mip levels
  4937. * @param invertY defines if data must be stored with Y axis inverted
  4938. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  4939. * @param compression defines the compression used (null by default)
  4940. * @returns the cube texture as an InternalTexture
  4941. */
  4942. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  4943. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  4944. compression: Nullable<string> = null): InternalTexture {
  4945. var gl = this._gl;
  4946. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  4947. texture.isCube = true;
  4948. texture.format = format;
  4949. texture.type = type;
  4950. if (!this._doNotHandleContextLost) {
  4951. texture._bufferViewArray = data;
  4952. }
  4953. var textureType = this._getWebGLTextureType(type);
  4954. var internalFormat = this._getInternalFormat(format);
  4955. if (internalFormat === gl.RGB) {
  4956. internalFormat = gl.RGBA;
  4957. }
  4958. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  4959. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  4960. generateMipMaps = false;
  4961. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4962. Logger.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  4963. }
  4964. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  4965. generateMipMaps = false;
  4966. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4967. Logger.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  4968. }
  4969. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  4970. generateMipMaps = false;
  4971. Logger.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  4972. }
  4973. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  4974. generateMipMaps = false;
  4975. Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  4976. }
  4977. var width = size;
  4978. var height = width;
  4979. texture.width = width;
  4980. texture.height = height;
  4981. // Double check on POT to generate Mips.
  4982. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4983. if (!isPot) {
  4984. generateMipMaps = false;
  4985. }
  4986. // Upload data if needed. The texture won't be ready until then.
  4987. if (data) {
  4988. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  4989. }
  4990. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  4991. // Filters
  4992. if (data && generateMipMaps) {
  4993. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4994. }
  4995. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  4996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4997. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4998. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4999. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5000. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  5001. texture.generateMipMaps = generateMipMaps;
  5002. return texture;
  5003. }
  5004. /**
  5005. * Creates a new raw cube texture from a specified url
  5006. * @param url defines the url where the data is located
  5007. * @param scene defines the current scene
  5008. * @param size defines the size of the textures
  5009. * @param format defines the format of the data
  5010. * @param type defines the type fo the data (like Engine.TEXTURETYPE_UNSIGNED_INT)
  5011. * @param noMipmap defines if the engine should avoid generating the mip levels
  5012. * @param callback defines a callback used to extract texture data from loaded data
  5013. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  5014. * @param onLoad defines a callback called when texture is loaded
  5015. * @param onError defines a callback called if there is an error
  5016. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  5017. * @param invertY defines if data must be stored with Y axis inverted
  5018. * @returns the cube texture as an InternalTexture
  5019. */
  5020. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  5021. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  5022. mipmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  5023. onLoad: Nullable<() => void> = null,
  5024. onError: Nullable<(message?: string, exception?: any) => void> = null,
  5025. samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  5026. invertY = false): InternalTexture {
  5027. var gl = this._gl;
  5028. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  5029. scene._addPendingData(texture);
  5030. texture.url = url;
  5031. this._internalTexturesCache.push(texture);
  5032. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  5033. scene._removePendingData(texture);
  5034. if (onError && request) {
  5035. onError(request.status + " " + request.statusText, exception);
  5036. }
  5037. };
  5038. var internalCallback = (data: any) => {
  5039. var width = texture.width;
  5040. var faceDataArrays = callback(data);
  5041. if (!faceDataArrays) {
  5042. return;
  5043. }
  5044. if (mipmapGenerator) {
  5045. var textureType = this._getWebGLTextureType(type);
  5046. var internalFormat = this._getInternalFormat(format);
  5047. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  5048. var needConversion = false;
  5049. if (internalFormat === gl.RGB) {
  5050. internalFormat = gl.RGBA;
  5051. needConversion = true;
  5052. }
  5053. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  5054. this._unpackFlipY(false);
  5055. var mipData = mipmapGenerator(faceDataArrays);
  5056. for (var level = 0; level < mipData.length; level++) {
  5057. var mipSize = width >> level;
  5058. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  5059. let mipFaceData = mipData[level][faceIndex];
  5060. if (needConversion) {
  5061. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  5062. }
  5063. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  5064. }
  5065. }
  5066. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  5067. }
  5068. else {
  5069. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  5070. }
  5071. texture.isReady = true;
  5072. // this.resetTextureCache();
  5073. scene._removePendingData(texture);
  5074. if (onLoad) {
  5075. onLoad();
  5076. }
  5077. };
  5078. this._loadFile(url, (data) => {
  5079. internalCallback(data);
  5080. }, undefined, scene.offlineProvider, true, onerror);
  5081. return texture;
  5082. }
  5083. /**
  5084. * Update a raw 3D texture
  5085. * @param texture defines the texture to update
  5086. * @param data defines the data to store
  5087. * @param format defines the data format
  5088. * @param invertY defines if data must be stored with Y axis inverted
  5089. * @param compression defines the used compression (can be null)
  5090. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  5091. */
  5092. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, textureType = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  5093. var internalType = this._getWebGLTextureType(textureType);
  5094. var internalFormat = this._getInternalFormat(format);
  5095. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  5096. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  5097. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  5098. if (!this._doNotHandleContextLost) {
  5099. texture._bufferView = data;
  5100. texture.format = format;
  5101. texture.invertY = invertY;
  5102. texture._compression = compression;
  5103. }
  5104. if (texture.width % 4 !== 0) {
  5105. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  5106. }
  5107. if (compression && data) {
  5108. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  5109. } else {
  5110. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  5111. }
  5112. if (texture.generateMipMaps) {
  5113. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  5114. }
  5115. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5116. // this.resetTextureCache();
  5117. texture.isReady = true;
  5118. }
  5119. /**
  5120. * Creates a new raw 3D texture
  5121. * @param data defines the data used to create the texture
  5122. * @param width defines the width of the texture
  5123. * @param height defines the height of the texture
  5124. * @param depth defines the depth of the texture
  5125. * @param format defines the format of the texture
  5126. * @param generateMipMaps defines if the engine must generate mip levels
  5127. * @param invertY defines if data must be stored with Y axis inverted
  5128. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  5129. * @param compression defines the compressed used (can be null)
  5130. * @param textureType defines the compressed used (can be null)
  5131. * @returns a new raw 3D texture (stored in an InternalTexture)
  5132. */
  5133. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, textureType = Engine.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  5134. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  5135. texture.baseWidth = width;
  5136. texture.baseHeight = height;
  5137. texture.baseDepth = depth;
  5138. texture.width = width;
  5139. texture.height = height;
  5140. texture.depth = depth;
  5141. texture.format = format;
  5142. texture.type = textureType;
  5143. texture.generateMipMaps = generateMipMaps;
  5144. texture.samplingMode = samplingMode;
  5145. texture.is3D = true;
  5146. if (!this._doNotHandleContextLost) {
  5147. texture._bufferView = data;
  5148. }
  5149. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  5150. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  5151. // Filters
  5152. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  5153. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5154. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5155. if (generateMipMaps) {
  5156. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  5157. }
  5158. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5159. this._internalTexturesCache.push(texture);
  5160. return texture;
  5161. }
  5162. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  5163. var gl = this._gl;
  5164. if (!gl) {
  5165. return;
  5166. }
  5167. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  5168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5170. if (!noMipmap && !isCompressed) {
  5171. gl.generateMipmap(gl.TEXTURE_2D);
  5172. }
  5173. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  5174. // this.resetTextureCache();
  5175. if (scene) {
  5176. scene._removePendingData(texture);
  5177. }
  5178. texture.onLoadedObservable.notifyObservers(texture);
  5179. texture.onLoadedObservable.clear();
  5180. }
  5181. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  5182. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE): void {
  5183. var maxTextureSize = this.getCaps().maxTextureSize;
  5184. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  5185. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  5186. var gl = this._gl;
  5187. if (!gl) {
  5188. return;
  5189. }
  5190. if (!texture._webGLTexture) {
  5191. // this.resetTextureCache();
  5192. if (scene) {
  5193. scene._removePendingData(texture);
  5194. }
  5195. return;
  5196. }
  5197. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  5198. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  5199. texture.baseWidth = width;
  5200. texture.baseHeight = height;
  5201. texture.width = potWidth;
  5202. texture.height = potHeight;
  5203. texture.isReady = true;
  5204. if (processFunction(potWidth, potHeight, () => {
  5205. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5206. })) {
  5207. // Returning as texture needs extra async steps
  5208. return;
  5209. }
  5210. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5211. }
  5212. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  5213. // Create new RGBA data container.
  5214. var rgbaData: any;
  5215. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  5216. rgbaData = new Float32Array(width * height * 4);
  5217. }
  5218. else {
  5219. rgbaData = new Uint32Array(width * height * 4);
  5220. }
  5221. // Convert each pixel.
  5222. for (let x = 0; x < width; x++) {
  5223. for (let y = 0; y < height; y++) {
  5224. let index = (y * width + x) * 3;
  5225. let newIndex = (y * width + x) * 4;
  5226. // Map Old Value to new value.
  5227. rgbaData[newIndex + 0] = rgbData[index + 0];
  5228. rgbaData[newIndex + 1] = rgbData[index + 1];
  5229. rgbaData[newIndex + 2] = rgbData[index + 2];
  5230. // Add fully opaque alpha channel.
  5231. rgbaData[newIndex + 3] = 1;
  5232. }
  5233. }
  5234. return rgbaData;
  5235. }
  5236. /** @hidden */
  5237. public _releaseFramebufferObjects(texture: InternalTexture): void {
  5238. var gl = this._gl;
  5239. if (texture._framebuffer) {
  5240. gl.deleteFramebuffer(texture._framebuffer);
  5241. texture._framebuffer = null;
  5242. }
  5243. if (texture._depthStencilBuffer) {
  5244. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  5245. texture._depthStencilBuffer = null;
  5246. }
  5247. if (texture._MSAAFramebuffer) {
  5248. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  5249. texture._MSAAFramebuffer = null;
  5250. }
  5251. if (texture._MSAARenderBuffer) {
  5252. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  5253. texture._MSAARenderBuffer = null;
  5254. }
  5255. }
  5256. /** @hidden */
  5257. public _releaseTexture(texture: InternalTexture): void {
  5258. var gl = this._gl;
  5259. this._releaseFramebufferObjects(texture);
  5260. gl.deleteTexture(texture._webGLTexture);
  5261. // Unbind channels
  5262. this.unbindAllTextures();
  5263. var index = this._internalTexturesCache.indexOf(texture);
  5264. if (index !== -1) {
  5265. this._internalTexturesCache.splice(index, 1);
  5266. }
  5267. // Integrated fixed lod samplers.
  5268. if (texture._lodTextureHigh) {
  5269. texture._lodTextureHigh.dispose();
  5270. }
  5271. if (texture._lodTextureMid) {
  5272. texture._lodTextureMid.dispose();
  5273. }
  5274. if (texture._lodTextureLow) {
  5275. texture._lodTextureLow.dispose();
  5276. }
  5277. // Set output texture of post process to null if the texture has been released/disposed
  5278. this.scenes.forEach((scene) => {
  5279. scene.postProcesses.forEach((postProcess) => {
  5280. if (postProcess._outputTexture == texture) {
  5281. postProcess._outputTexture = null;
  5282. }
  5283. });
  5284. scene.cameras.forEach((camera) => {
  5285. camera._postProcesses.forEach((postProcess) => {
  5286. if (postProcess) {
  5287. if (postProcess._outputTexture == texture) {
  5288. postProcess._outputTexture = null;
  5289. }
  5290. }
  5291. });
  5292. });
  5293. });
  5294. }
  5295. private setProgram(program: WebGLProgram): void {
  5296. if (this._currentProgram !== program) {
  5297. this._gl.useProgram(program);
  5298. this._currentProgram = program;
  5299. }
  5300. }
  5301. private _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  5302. /**
  5303. * Binds an effect to the webGL context
  5304. * @param effect defines the effect to bind
  5305. */
  5306. public bindSamplers(effect: Effect): void {
  5307. this.setProgram(effect.getProgram());
  5308. var samplers = effect.getSamplers();
  5309. for (var index = 0; index < samplers.length; index++) {
  5310. var uniform = effect.getUniform(samplers[index]);
  5311. if (uniform) {
  5312. this._boundUniforms[index] = uniform;
  5313. }
  5314. }
  5315. this._currentEffect = null;
  5316. }
  5317. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  5318. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  5319. return;
  5320. }
  5321. // Remove
  5322. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5323. // Bind last to it
  5324. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  5325. // Bind to dummy
  5326. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  5327. }
  5328. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  5329. if (!internalTexture) {
  5330. return -1;
  5331. }
  5332. internalTexture._initialSlot = channel;
  5333. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  5334. if (channel !== internalTexture._designatedSlot) {
  5335. this._textureCollisions.addCount(1, false);
  5336. }
  5337. } else {
  5338. if (channel !== internalTexture._designatedSlot) {
  5339. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  5340. return internalTexture._designatedSlot;
  5341. } else {
  5342. // No slot for this texture, let's pick a new one (if we find a free slot)
  5343. if (this._nextFreeTextureSlots.length) {
  5344. return this._nextFreeTextureSlots[0];
  5345. }
  5346. // We need to recycle the oldest bound texture, sorry.
  5347. this._textureCollisions.addCount(1, false);
  5348. return this._removeDesignatedSlot(<InternalTexture>this._firstBoundInternalTextureTracker.next);
  5349. }
  5350. }
  5351. }
  5352. return channel;
  5353. }
  5354. private _linkTrackers(previous: Nullable<IInternalTextureTracker>, next: Nullable<IInternalTextureTracker>) {
  5355. previous!.next = next;
  5356. next!.previous = previous;
  5357. }
  5358. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  5359. let currentSlot = internalTexture._designatedSlot;
  5360. if (currentSlot === -1) {
  5361. return -1;
  5362. }
  5363. internalTexture._designatedSlot = -1;
  5364. if (this.disableTextureBindingOptimization) {
  5365. return -1;
  5366. }
  5367. // Remove from bound list
  5368. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5369. // Free the slot
  5370. this._boundTexturesCache[currentSlot] = null;
  5371. this._nextFreeTextureSlots.push(currentSlot);
  5372. return currentSlot;
  5373. }
  5374. private _activateCurrentTexture() {
  5375. if (this._currentTextureChannel !== this._activeChannel) {
  5376. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  5377. this._currentTextureChannel = this._activeChannel;
  5378. }
  5379. }
  5380. /** @hidden */
  5381. public _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): boolean {
  5382. var wasPreviouslyBound = false;
  5383. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  5384. this._activeChannel = texture._designatedSlot;
  5385. }
  5386. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  5387. let isTextureForRendering = texture && texture._initialSlot > -1;
  5388. if (currentTextureBound !== texture || force) {
  5389. if (currentTextureBound) {
  5390. this._removeDesignatedSlot(currentTextureBound);
  5391. }
  5392. this._activateCurrentTexture();
  5393. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  5394. this._boundTexturesCache[this._activeChannel] = texture;
  5395. if (texture) {
  5396. if (!this.disableTextureBindingOptimization) {
  5397. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  5398. if (slotIndex > -1) {
  5399. this._nextFreeTextureSlots.splice(slotIndex, 1);
  5400. }
  5401. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  5402. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  5403. }
  5404. texture._designatedSlot = this._activeChannel;
  5405. }
  5406. } else if (forTextureDataUpdate) {
  5407. wasPreviouslyBound = true;
  5408. this._activateCurrentTexture();
  5409. }
  5410. if (isTextureForRendering && !forTextureDataUpdate) {
  5411. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  5412. }
  5413. return wasPreviouslyBound;
  5414. }
  5415. /** @hidden */
  5416. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  5417. if (channel < 0) {
  5418. return;
  5419. }
  5420. if (texture) {
  5421. channel = this._getCorrectTextureChannel(channel, texture);
  5422. }
  5423. this._activeChannel = channel;
  5424. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  5425. }
  5426. /**
  5427. * Sets a texture to the webGL context from a postprocess
  5428. * @param channel defines the channel to use
  5429. * @param postProcess defines the source postprocess
  5430. */
  5431. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  5432. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  5433. }
  5434. /**
  5435. * Binds the output of the passed in post process to the texture channel specified
  5436. * @param channel The channel the texture should be bound to
  5437. * @param postProcess The post process which's output should be bound
  5438. */
  5439. public setTextureFromPostProcessOutput(channel: number, postProcess: Nullable<PostProcess>): void {
  5440. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  5441. }
  5442. /**
  5443. * Unbind all textures from the webGL context
  5444. */
  5445. public unbindAllTextures(): void {
  5446. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  5447. this._activeChannel = channel;
  5448. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5449. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5450. if (this.webGLVersion > 1) {
  5451. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5452. }
  5453. }
  5454. }
  5455. /**
  5456. * Sets a texture to the according uniform.
  5457. * @param channel The texture channel
  5458. * @param uniform The uniform to set
  5459. * @param texture The texture to apply
  5460. */
  5461. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  5462. if (channel < 0) {
  5463. return;
  5464. }
  5465. if (uniform) {
  5466. this._boundUniforms[channel] = uniform;
  5467. }
  5468. this._setTexture(channel, texture);
  5469. }
  5470. /**
  5471. * Sets a depth stencil texture from a render target to the according uniform.
  5472. * @param channel The texture channel
  5473. * @param uniform The uniform to set
  5474. * @param texture The render target texture containing the depth stencil texture to apply
  5475. */
  5476. public setDepthStencilTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<RenderTargetTexture>): void {
  5477. if (channel < 0) {
  5478. return;
  5479. }
  5480. if (uniform) {
  5481. this._boundUniforms[channel] = uniform;
  5482. }
  5483. if (!texture || !texture.depthStencilTexture) {
  5484. this._setTexture(channel, null);
  5485. }
  5486. else {
  5487. this._setTexture(channel, texture, false, true);
  5488. }
  5489. }
  5490. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  5491. let uniform = this._boundUniforms[sourceSlot];
  5492. if (uniform._currentState === destination) {
  5493. return;
  5494. }
  5495. this._gl.uniform1i(uniform, destination);
  5496. uniform._currentState = destination;
  5497. }
  5498. private _getTextureWrapMode(mode: number): number {
  5499. switch (mode) {
  5500. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  5501. return this._gl.REPEAT;
  5502. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  5503. return this._gl.CLAMP_TO_EDGE;
  5504. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  5505. return this._gl.MIRRORED_REPEAT;
  5506. }
  5507. return this._gl.REPEAT;
  5508. }
  5509. private _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  5510. // Not ready?
  5511. if (!texture) {
  5512. if (this._boundTexturesCache[channel] != null) {
  5513. this._activeChannel = channel;
  5514. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5515. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5516. if (this.webGLVersion > 1) {
  5517. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5518. }
  5519. }
  5520. return false;
  5521. }
  5522. // Video
  5523. if ((<VideoTexture>texture).video) {
  5524. this._activeChannel = channel;
  5525. (<VideoTexture>texture).update();
  5526. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  5527. texture.delayLoad();
  5528. return false;
  5529. }
  5530. let internalTexture: InternalTexture;
  5531. if (depthStencilTexture) {
  5532. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  5533. }
  5534. else if (texture.isReady()) {
  5535. internalTexture = <InternalTexture>texture.getInternalTexture();
  5536. }
  5537. else if (texture.isCube) {
  5538. internalTexture = this.emptyCubeTexture;
  5539. }
  5540. else if (texture.is3D) {
  5541. internalTexture = this.emptyTexture3D;
  5542. }
  5543. else {
  5544. internalTexture = this.emptyTexture;
  5545. }
  5546. if (!isPartOfTextureArray) {
  5547. channel = this._getCorrectTextureChannel(channel, internalTexture);
  5548. }
  5549. let needToBind = true;
  5550. if (this._boundTexturesCache[channel] === internalTexture) {
  5551. this._moveBoundTextureOnTop(internalTexture);
  5552. if (!isPartOfTextureArray) {
  5553. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  5554. }
  5555. needToBind = false;
  5556. }
  5557. this._activeChannel = channel;
  5558. if (internalTexture && internalTexture.is3D) {
  5559. if (needToBind) {
  5560. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  5561. }
  5562. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5563. internalTexture._cachedWrapU = texture.wrapU;
  5564. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5565. }
  5566. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5567. internalTexture._cachedWrapV = texture.wrapV;
  5568. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5569. }
  5570. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  5571. internalTexture._cachedWrapR = texture.wrapR;
  5572. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  5573. }
  5574. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  5575. }
  5576. else if (internalTexture && internalTexture.isCube) {
  5577. if (needToBind) {
  5578. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  5579. }
  5580. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5581. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5582. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5583. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5584. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  5585. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5586. }
  5587. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5588. } else {
  5589. if (needToBind) {
  5590. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  5591. }
  5592. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5593. internalTexture._cachedWrapU = texture.wrapU;
  5594. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5595. }
  5596. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5597. internalTexture._cachedWrapV = texture.wrapV;
  5598. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5599. }
  5600. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5601. }
  5602. return true;
  5603. }
  5604. /**
  5605. * Sets an array of texture to the webGL context
  5606. * @param channel defines the channel where the texture array must be set
  5607. * @param uniform defines the associated uniform location
  5608. * @param textures defines the array of textures to bind
  5609. */
  5610. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  5611. if (channel < 0 || !uniform) {
  5612. return;
  5613. }
  5614. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  5615. this._textureUnits = new Int32Array(textures.length);
  5616. }
  5617. for (let i = 0; i < textures.length; i++) {
  5618. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  5619. }
  5620. this._gl.uniform1iv(uniform, this._textureUnits);
  5621. for (var index = 0; index < textures.length; index++) {
  5622. this._setTexture(this._textureUnits[index], textures[index], true);
  5623. }
  5624. }
  5625. /** @hidden */
  5626. public _setAnisotropicLevel(target: number, texture: BaseTexture) {
  5627. var internalTexture = texture.getInternalTexture();
  5628. if (!internalTexture) {
  5629. return;
  5630. }
  5631. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5632. var value = texture.anisotropicFilteringLevel;
  5633. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  5634. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  5635. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  5636. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  5637. }
  5638. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  5639. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  5640. internalTexture._cachedAnisotropicFilteringLevel = value;
  5641. }
  5642. }
  5643. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  5644. this._bindTextureDirectly(target, texture, true, true);
  5645. this._gl.texParameterf(target, parameter, value);
  5646. }
  5647. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  5648. if (texture) {
  5649. this._bindTextureDirectly(target, texture, true, true);
  5650. }
  5651. this._gl.texParameteri(target, parameter, value);
  5652. }
  5653. /**
  5654. * Reads pixels from the current frame buffer. Please note that this function can be slow
  5655. * @param x defines the x coordinate of the rectangle where pixels must be read
  5656. * @param y defines the y coordinate of the rectangle where pixels must be read
  5657. * @param width defines the width of the rectangle where pixels must be read
  5658. * @param height defines the height of the rectangle where pixels must be read
  5659. * @returns a Uint8Array containing RGBA colors
  5660. */
  5661. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  5662. var data = new Uint8Array(height * width * 4);
  5663. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5664. return data;
  5665. }
  5666. /**
  5667. * Add an externaly attached data from its key.
  5668. * This method call will fail and return false, if such key already exists.
  5669. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  5670. * @param key the unique key that identifies the data
  5671. * @param data the data object to associate to the key for this Engine instance
  5672. * @return true if no such key were already present and the data was added successfully, false otherwise
  5673. */
  5674. public addExternalData<T>(key: string, data: T): boolean {
  5675. if (!this._externalData) {
  5676. this._externalData = new StringDictionary<Object>();
  5677. }
  5678. return this._externalData.add(key, data);
  5679. }
  5680. /**
  5681. * Get an externaly attached data from its key
  5682. * @param key the unique key that identifies the data
  5683. * @return the associated data, if present (can be null), or undefined if not present
  5684. */
  5685. public getExternalData<T>(key: string): T {
  5686. if (!this._externalData) {
  5687. this._externalData = new StringDictionary<Object>();
  5688. }
  5689. return <T>this._externalData.get(key);
  5690. }
  5691. /**
  5692. * Get an externaly attached data from its key, create it using a factory if it's not already present
  5693. * @param key the unique key that identifies the data
  5694. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  5695. * @return the associated data, can be null if the factory returned null.
  5696. */
  5697. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  5698. if (!this._externalData) {
  5699. this._externalData = new StringDictionary<Object>();
  5700. }
  5701. return <T>this._externalData.getOrAddWithFactory(key, factory);
  5702. }
  5703. /**
  5704. * Remove an externaly attached data from the Engine instance
  5705. * @param key the unique key that identifies the data
  5706. * @return true if the data was successfully removed, false if it doesn't exist
  5707. */
  5708. public removeExternalData(key: string): boolean {
  5709. if (!this._externalData) {
  5710. this._externalData = new StringDictionary<Object>();
  5711. }
  5712. return this._externalData.remove(key);
  5713. }
  5714. /**
  5715. * Unbind all vertex attributes from the webGL context
  5716. */
  5717. public unbindAllAttributes() {
  5718. if (this._mustWipeVertexAttributes) {
  5719. this._mustWipeVertexAttributes = false;
  5720. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  5721. this._gl.disableVertexAttribArray(i);
  5722. this._vertexAttribArraysEnabled[i] = false;
  5723. this._currentBufferPointers[i].active = false;
  5724. }
  5725. return;
  5726. }
  5727. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  5728. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  5729. continue;
  5730. }
  5731. this._gl.disableVertexAttribArray(i);
  5732. this._vertexAttribArraysEnabled[i] = false;
  5733. this._currentBufferPointers[i].active = false;
  5734. }
  5735. }
  5736. /**
  5737. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  5738. */
  5739. public releaseEffects() {
  5740. for (var name in this._compiledEffects) {
  5741. this._deleteProgram(this._compiledEffects[name]._program);
  5742. }
  5743. this._compiledEffects = {};
  5744. }
  5745. /**
  5746. * Dispose and release all associated resources
  5747. */
  5748. public dispose(): void {
  5749. this.hideLoadingUI();
  5750. this.stopRenderLoop();
  5751. this.onNewSceneAddedObservable.clear();
  5752. // Release postProcesses
  5753. while (this.postProcesses.length) {
  5754. this.postProcesses[0].dispose();
  5755. }
  5756. // Empty texture
  5757. if (this._emptyTexture) {
  5758. this._releaseTexture(this._emptyTexture);
  5759. this._emptyTexture = null;
  5760. }
  5761. if (this._emptyCubeTexture) {
  5762. this._releaseTexture(this._emptyCubeTexture);
  5763. this._emptyCubeTexture = null;
  5764. }
  5765. // Rescale PP
  5766. if (this._rescalePostProcess) {
  5767. this._rescalePostProcess.dispose();
  5768. }
  5769. // Release scenes
  5770. while (this.scenes.length) {
  5771. this.scenes[0].dispose();
  5772. }
  5773. // Release audio engine
  5774. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  5775. Engine.audioEngine.dispose();
  5776. }
  5777. // Release effects
  5778. this.releaseEffects();
  5779. // Unbind
  5780. this.unbindAllAttributes();
  5781. this._boundUniforms = [];
  5782. if (this._dummyFramebuffer) {
  5783. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  5784. }
  5785. //WebVR
  5786. this.disableVR();
  5787. // Events
  5788. if (DomManagement.IsWindowObjectExist()) {
  5789. window.removeEventListener("blur", this._onBlur);
  5790. window.removeEventListener("focus", this._onFocus);
  5791. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  5792. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  5793. if (this._renderingCanvas) {
  5794. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  5795. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  5796. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  5797. if (!this._doNotHandleContextLost) {
  5798. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  5799. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  5800. }
  5801. }
  5802. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5803. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5804. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5805. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5806. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5807. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5808. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5809. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5810. if (this._onVrDisplayConnect) {
  5811. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  5812. if (this._onVrDisplayDisconnect) {
  5813. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  5814. }
  5815. if (this._onVrDisplayPresentChange) {
  5816. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  5817. }
  5818. this._onVrDisplayConnect = null;
  5819. this._onVrDisplayDisconnect = null;
  5820. }
  5821. }
  5822. // Remove from Instances
  5823. var index = Engine.Instances.indexOf(this);
  5824. if (index >= 0) {
  5825. Engine.Instances.splice(index, 1);
  5826. }
  5827. this._workingCanvas = null;
  5828. this._workingContext = null;
  5829. this._currentBufferPointers = [];
  5830. this._renderingCanvas = null;
  5831. this._currentProgram = null;
  5832. this._bindedRenderFunction = null;
  5833. this.onResizeObservable.clear();
  5834. this.onCanvasBlurObservable.clear();
  5835. this.onCanvasFocusObservable.clear();
  5836. this.onCanvasPointerOutObservable.clear();
  5837. this.onBeginFrameObservable.clear();
  5838. this.onEndFrameObservable.clear();
  5839. Effect.ResetCache();
  5840. // Abort active requests
  5841. for (let request of this._activeRequests) {
  5842. request.abort();
  5843. }
  5844. }
  5845. // Loading screen
  5846. /**
  5847. * Display the loading screen
  5848. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5849. */
  5850. public displayLoadingUI(): void {
  5851. if (!DomManagement.IsWindowObjectExist()) {
  5852. return;
  5853. }
  5854. const loadingScreen = this.loadingScreen;
  5855. if (loadingScreen) {
  5856. loadingScreen.displayLoadingUI();
  5857. }
  5858. }
  5859. /**
  5860. * Hide the loading screen
  5861. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5862. */
  5863. public hideLoadingUI(): void {
  5864. if (!DomManagement.IsWindowObjectExist()) {
  5865. return;
  5866. }
  5867. const loadingScreen = this.loadingScreen;
  5868. if (loadingScreen) {
  5869. loadingScreen.hideLoadingUI();
  5870. }
  5871. }
  5872. /**
  5873. * Gets the current loading screen object
  5874. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5875. */
  5876. public get loadingScreen(): ILoadingScreen {
  5877. if (!this._loadingScreen && this._renderingCanvas) {
  5878. this._loadingScreen = Engine.DefaultLoadingScreenFactory(this._renderingCanvas);
  5879. }
  5880. return this._loadingScreen;
  5881. }
  5882. /**
  5883. * Sets the current loading screen object
  5884. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5885. */
  5886. public set loadingScreen(loadingScreen: ILoadingScreen) {
  5887. this._loadingScreen = loadingScreen;
  5888. }
  5889. /**
  5890. * Sets the current loading screen text
  5891. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5892. */
  5893. public set loadingUIText(text: string) {
  5894. this.loadingScreen.loadingUIText = text;
  5895. }
  5896. /**
  5897. * Sets the current loading screen background color
  5898. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5899. */
  5900. public set loadingUIBackgroundColor(color: string) {
  5901. this.loadingScreen.loadingUIBackgroundColor = color;
  5902. }
  5903. /**
  5904. * Attach a new callback raised when context lost event is fired
  5905. * @param callback defines the callback to call
  5906. */
  5907. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5908. if (this._renderingCanvas) {
  5909. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  5910. }
  5911. }
  5912. /**
  5913. * Attach a new callback raised when context restored event is fired
  5914. * @param callback defines the callback to call
  5915. */
  5916. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5917. if (this._renderingCanvas) {
  5918. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  5919. }
  5920. }
  5921. /**
  5922. * Gets the source code of the vertex shader associated with a specific webGL program
  5923. * @param program defines the program to use
  5924. * @returns a string containing the source code of the vertex shader associated with the program
  5925. */
  5926. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  5927. var shaders = this._gl.getAttachedShaders(program);
  5928. if (!shaders) {
  5929. return null;
  5930. }
  5931. return this._gl.getShaderSource(shaders[0]);
  5932. }
  5933. /**
  5934. * Gets the source code of the fragment shader associated with a specific webGL program
  5935. * @param program defines the program to use
  5936. * @returns a string containing the source code of the fragment shader associated with the program
  5937. */
  5938. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  5939. var shaders = this._gl.getAttachedShaders(program);
  5940. if (!shaders) {
  5941. return null;
  5942. }
  5943. return this._gl.getShaderSource(shaders[1]);
  5944. }
  5945. /**
  5946. * Get the current error code of the webGL context
  5947. * @returns the error code
  5948. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  5949. */
  5950. public getError(): number {
  5951. return this._gl.getError();
  5952. }
  5953. // FPS
  5954. /**
  5955. * Gets the current framerate
  5956. * @returns a number representing the framerate
  5957. */
  5958. public getFps(): number {
  5959. return this._fps;
  5960. }
  5961. /**
  5962. * Gets the time spent between current and previous frame
  5963. * @returns a number representing the delta time in ms
  5964. */
  5965. public getDeltaTime(): number {
  5966. return this._deltaTime;
  5967. }
  5968. private _measureFps(): void {
  5969. this._performanceMonitor.sampleFrame();
  5970. this._fps = this._performanceMonitor.averageFPS;
  5971. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  5972. }
  5973. /** @hidden */
  5974. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1, level = 0, buffer: Nullable<ArrayBufferView> = null): ArrayBufferView {
  5975. let gl = this._gl;
  5976. if (!this._dummyFramebuffer) {
  5977. let dummy = gl.createFramebuffer();
  5978. if (!dummy) {
  5979. throw new Error("Unable to create dummy framebuffer");
  5980. }
  5981. this._dummyFramebuffer = dummy;
  5982. }
  5983. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  5984. if (faceIndex > -1) {
  5985. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  5986. } else {
  5987. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  5988. }
  5989. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  5990. switch (readType) {
  5991. case gl.UNSIGNED_BYTE:
  5992. if (!buffer) {
  5993. buffer = new Uint8Array(4 * width * height);
  5994. }
  5995. readType = gl.UNSIGNED_BYTE;
  5996. break;
  5997. default:
  5998. if (!buffer) {
  5999. buffer = new Float32Array(4 * width * height);
  6000. }
  6001. readType = gl.FLOAT;
  6002. break;
  6003. }
  6004. gl.readPixels(0, 0, width, height, gl.RGBA, readType, <DataView>buffer);
  6005. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  6006. return buffer;
  6007. }
  6008. private _canRenderToFloatFramebuffer(): boolean {
  6009. if (this._webGLVersion > 1) {
  6010. return this._caps.colorBufferFloat;
  6011. }
  6012. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  6013. }
  6014. private _canRenderToHalfFloatFramebuffer(): boolean {
  6015. if (this._webGLVersion > 1) {
  6016. return this._caps.colorBufferFloat;
  6017. }
  6018. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  6019. }
  6020. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  6021. private _canRenderToFramebuffer(type: number): boolean {
  6022. let gl = this._gl;
  6023. //clear existing errors
  6024. while (gl.getError() !== gl.NO_ERROR) { }
  6025. let successful = true;
  6026. let texture = gl.createTexture();
  6027. gl.bindTexture(gl.TEXTURE_2D, texture);
  6028. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  6029. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6031. let fb = gl.createFramebuffer();
  6032. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  6033. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6034. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  6035. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  6036. successful = successful && (gl.getError() === gl.NO_ERROR);
  6037. //try render by clearing frame buffer's color buffer
  6038. if (successful) {
  6039. gl.clear(gl.COLOR_BUFFER_BIT);
  6040. successful = successful && (gl.getError() === gl.NO_ERROR);
  6041. }
  6042. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  6043. if (successful) {
  6044. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  6045. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6046. let readFormat = gl.RGBA;
  6047. let readType = gl.UNSIGNED_BYTE;
  6048. let buffer = new Uint8Array(4);
  6049. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  6050. successful = successful && (gl.getError() === gl.NO_ERROR);
  6051. }
  6052. //clean up
  6053. gl.deleteTexture(texture);
  6054. gl.deleteFramebuffer(fb);
  6055. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6056. //clear accumulated errors
  6057. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  6058. return successful;
  6059. }
  6060. /** @hidden */
  6061. public _getWebGLTextureType(type: number): number {
  6062. if (this._webGLVersion === 1) {
  6063. switch (type) {
  6064. case Engine.TEXTURETYPE_FLOAT:
  6065. return this._gl.FLOAT;
  6066. case Engine.TEXTURETYPE_HALF_FLOAT:
  6067. return this._gl.HALF_FLOAT_OES;
  6068. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  6069. return this._gl.UNSIGNED_BYTE;
  6070. }
  6071. return this._gl.UNSIGNED_BYTE;
  6072. }
  6073. switch (type) {
  6074. case Engine.TEXTURETYPE_BYTE:
  6075. return this._gl.BYTE;
  6076. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  6077. return this._gl.UNSIGNED_BYTE;
  6078. case Engine.TEXTURETYPE_SHORT:
  6079. return this._gl.SHORT;
  6080. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  6081. return this._gl.UNSIGNED_SHORT;
  6082. case Engine.TEXTURETYPE_INT:
  6083. return this._gl.INT;
  6084. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  6085. return this._gl.UNSIGNED_INT;
  6086. case Engine.TEXTURETYPE_FLOAT:
  6087. return this._gl.FLOAT;
  6088. case Engine.TEXTURETYPE_HALF_FLOAT:
  6089. return this._gl.HALF_FLOAT;
  6090. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  6091. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  6092. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  6093. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  6094. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  6095. return this._gl.UNSIGNED_SHORT_5_6_5;
  6096. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  6097. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  6098. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  6099. return this._gl.UNSIGNED_INT_24_8;
  6100. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  6101. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  6102. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  6103. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  6104. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  6105. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  6106. }
  6107. return this._gl.UNSIGNED_BYTE;
  6108. }
  6109. private _getInternalFormat(format: number): number {
  6110. var internalFormat = this._gl.RGBA;
  6111. switch (format) {
  6112. case Engine.TEXTUREFORMAT_ALPHA:
  6113. internalFormat = this._gl.ALPHA;
  6114. break;
  6115. case Engine.TEXTUREFORMAT_LUMINANCE:
  6116. internalFormat = this._gl.LUMINANCE;
  6117. break;
  6118. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6119. internalFormat = this._gl.LUMINANCE_ALPHA;
  6120. break;
  6121. case Engine.TEXTUREFORMAT_RED:
  6122. internalFormat = this._gl.RED;
  6123. break;
  6124. case Engine.TEXTUREFORMAT_RG:
  6125. internalFormat = this._gl.RG;
  6126. break;
  6127. case Engine.TEXTUREFORMAT_RGB:
  6128. internalFormat = this._gl.RGB;
  6129. break;
  6130. case Engine.TEXTUREFORMAT_RGBA:
  6131. internalFormat = this._gl.RGBA;
  6132. break;
  6133. }
  6134. if (this._webGLVersion > 1) {
  6135. switch (format) {
  6136. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6137. internalFormat = this._gl.RED_INTEGER;
  6138. break;
  6139. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6140. internalFormat = this._gl.RG_INTEGER;
  6141. break;
  6142. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6143. internalFormat = this._gl.RGB_INTEGER;
  6144. break;
  6145. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6146. internalFormat = this._gl.RGBA_INTEGER;
  6147. break;
  6148. }
  6149. }
  6150. return internalFormat;
  6151. }
  6152. /** @hidden */
  6153. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  6154. if (this._webGLVersion === 1) {
  6155. if (format !== undefined) {
  6156. switch (format) {
  6157. case Engine.TEXTUREFORMAT_ALPHA:
  6158. return this._gl.ALPHA;
  6159. case Engine.TEXTUREFORMAT_LUMINANCE:
  6160. return this._gl.LUMINANCE;
  6161. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6162. return this._gl.LUMINANCE_ALPHA;
  6163. }
  6164. }
  6165. return this._gl.RGBA;
  6166. }
  6167. switch (type) {
  6168. case Engine.TEXTURETYPE_BYTE:
  6169. switch (format) {
  6170. case Engine.TEXTUREFORMAT_RED:
  6171. return this._gl.R8_SNORM;
  6172. case Engine.TEXTUREFORMAT_RG:
  6173. return this._gl.RG8_SNORM;
  6174. case Engine.TEXTUREFORMAT_RGB:
  6175. return this._gl.RGB8_SNORM;
  6176. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6177. return this._gl.R8I;
  6178. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6179. return this._gl.RG8I;
  6180. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6181. return this._gl.RGB8I;
  6182. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6183. return this._gl.RGBA8I;
  6184. default:
  6185. return this._gl.RGBA8_SNORM;
  6186. }
  6187. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  6188. switch (format) {
  6189. case Engine.TEXTUREFORMAT_RED:
  6190. return this._gl.R8;
  6191. case Engine.TEXTUREFORMAT_RG:
  6192. return this._gl.RG8;
  6193. case Engine.TEXTUREFORMAT_RGB:
  6194. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  6195. case Engine.TEXTUREFORMAT_RGBA:
  6196. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  6197. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6198. return this._gl.R8UI;
  6199. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6200. return this._gl.RG8UI;
  6201. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6202. return this._gl.RGB8UI;
  6203. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6204. return this._gl.RGBA8UI;
  6205. default:
  6206. return this._gl.RGBA8;
  6207. }
  6208. case Engine.TEXTURETYPE_SHORT:
  6209. switch (format) {
  6210. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6211. return this._gl.R16I;
  6212. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6213. return this._gl.RG16I;
  6214. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6215. return this._gl.RGB16I;
  6216. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6217. return this._gl.RGBA16I;
  6218. default:
  6219. return this._gl.RGBA16I;
  6220. }
  6221. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  6222. switch (format) {
  6223. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6224. return this._gl.R16UI;
  6225. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6226. return this._gl.RG16UI;
  6227. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6228. return this._gl.RGB16UI;
  6229. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6230. return this._gl.RGBA16UI;
  6231. default:
  6232. return this._gl.RGBA16UI;
  6233. }
  6234. case Engine.TEXTURETYPE_INT:
  6235. switch (format) {
  6236. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6237. return this._gl.R32I;
  6238. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6239. return this._gl.RG32I;
  6240. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6241. return this._gl.RGB32I;
  6242. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6243. return this._gl.RGBA32I;
  6244. default:
  6245. return this._gl.RGBA32I;
  6246. }
  6247. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  6248. switch (format) {
  6249. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6250. return this._gl.R32UI;
  6251. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6252. return this._gl.RG32UI;
  6253. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6254. return this._gl.RGB32UI;
  6255. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6256. return this._gl.RGBA32UI;
  6257. default:
  6258. return this._gl.RGBA32UI;
  6259. }
  6260. case Engine.TEXTURETYPE_FLOAT:
  6261. switch (format) {
  6262. case Engine.TEXTUREFORMAT_RED:
  6263. return this._gl.R32F; // By default. Other possibility is R16F.
  6264. case Engine.TEXTUREFORMAT_RG:
  6265. return this._gl.RG32F; // By default. Other possibility is RG16F.
  6266. case Engine.TEXTUREFORMAT_RGB:
  6267. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  6268. case Engine.TEXTUREFORMAT_RGBA:
  6269. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  6270. default:
  6271. return this._gl.RGBA32F;
  6272. }
  6273. case Engine.TEXTURETYPE_HALF_FLOAT:
  6274. switch (format) {
  6275. case Engine.TEXTUREFORMAT_RED:
  6276. return this._gl.R16F;
  6277. case Engine.TEXTUREFORMAT_RG:
  6278. return this._gl.RG16F;
  6279. case Engine.TEXTUREFORMAT_RGB:
  6280. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  6281. case Engine.TEXTUREFORMAT_RGBA:
  6282. return this._gl.RGBA16F;
  6283. default:
  6284. return this._gl.RGBA16F;
  6285. }
  6286. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  6287. return this._gl.RGB565;
  6288. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  6289. return this._gl.R11F_G11F_B10F;
  6290. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  6291. return this._gl.RGB9_E5;
  6292. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  6293. return this._gl.RGBA4;
  6294. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  6295. return this._gl.RGB5_A1;
  6296. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  6297. switch (format) {
  6298. case Engine.TEXTUREFORMAT_RGBA:
  6299. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  6300. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6301. return this._gl.RGB10_A2UI;
  6302. default:
  6303. return this._gl.RGB10_A2;
  6304. }
  6305. }
  6306. return this._gl.RGBA8;
  6307. }
  6308. /** @hidden */
  6309. public _getRGBAMultiSampleBufferFormat(type: number): number {
  6310. if (type === Engine.TEXTURETYPE_FLOAT) {
  6311. return this._gl.RGBA32F;
  6312. }
  6313. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6314. return this._gl.RGBA16F;
  6315. }
  6316. return this._gl.RGBA8;
  6317. }
  6318. /** @hidden */
  6319. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  6320. let request = Tools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  6321. this._activeRequests.push(request);
  6322. request.onCompleteObservable.add((request) => {
  6323. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  6324. });
  6325. return request;
  6326. }
  6327. /** @hidden */
  6328. public _loadFileAsync(url: string, offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  6329. return new Promise((resolve, reject) => {
  6330. this._loadFile(url, (data) => {
  6331. resolve(data);
  6332. }, undefined, offlineProvider, useArrayBuffer, (request, exception) => {
  6333. reject(exception);
  6334. });
  6335. });
  6336. }
  6337. private _partialLoadFile(url: string, index: number, loadedFiles: (string | ArrayBuffer)[], onfinish: (files: (string | ArrayBuffer)[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null): void {
  6338. var onload = (data: string | ArrayBuffer) => {
  6339. loadedFiles[index] = data;
  6340. (<any>loadedFiles)._internalCount++;
  6341. if ((<any>loadedFiles)._internalCount === 6) {
  6342. onfinish(loadedFiles);
  6343. }
  6344. };
  6345. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  6346. if (onErrorCallBack && request) {
  6347. onErrorCallBack(request.status + " " + request.statusText, exception);
  6348. }
  6349. };
  6350. this._loadFile(url, onload, undefined, undefined, true, onerror);
  6351. }
  6352. private _cascadeLoadFiles(scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  6353. var loadedFiles: (string | ArrayBuffer)[] = [];
  6354. (<any>loadedFiles)._internalCount = 0;
  6355. for (let index = 0; index < 6; index++) {
  6356. this._partialLoadFile(files[index], index, loadedFiles, onfinish, onError);
  6357. }
  6358. }
  6359. // Statics
  6360. /**
  6361. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  6362. * @returns true if the engine can be created
  6363. * @ignorenaming
  6364. */
  6365. public static isSupported(): boolean {
  6366. try {
  6367. var tempcanvas = document.createElement("canvas");
  6368. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6369. return gl != null && !!window.WebGLRenderingContext;
  6370. } catch (e) {
  6371. return false;
  6372. }
  6373. }
  6374. }