babylon.engine.ts 314 KB

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