engine.ts 331 KB

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