babylon.engine.ts 315 KB

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