engine.ts 337 KB

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