babylon.engine.ts 330 KB

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