babylon.engine.ts 330 KB

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