babylon.engine.ts 320 KB

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