babylon.engine.ts 325 KB

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