babylon.engine.ts 330 KB

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