babylon.engine.ts 318 KB

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