babylon.engine.ts 241 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader => {
  3. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  4. };
  5. var compileRawShader = (gl: WebGLRenderingContext, source: string, type: string): WebGLShader => {
  6. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7. gl.shaderSource(shader, source);
  8. gl.compileShader(shader);
  9. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10. let log = gl.getShaderInfoLog(shader);
  11. if (log) {
  12. throw new Error(log);
  13. }
  14. }
  15. if (!shader) {
  16. throw new Error("Something went wrong while compile the shader.");
  17. }
  18. return shader;
  19. };
  20. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  21. var magFilter = gl.NEAREST;
  22. var minFilter = gl.NEAREST;
  23. switch (samplingMode) {
  24. case Texture.BILINEAR_SAMPLINGMODE:
  25. magFilter = gl.LINEAR;
  26. if (generateMipMaps) {
  27. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  28. } else {
  29. minFilter = gl.LINEAR;
  30. }
  31. break;
  32. case Texture.TRILINEAR_SAMPLINGMODE:
  33. magFilter = gl.LINEAR;
  34. if (generateMipMaps) {
  35. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  36. } else {
  37. minFilter = gl.LINEAR;
  38. }
  39. break;
  40. case Texture.NEAREST_SAMPLINGMODE:
  41. magFilter = gl.NEAREST;
  42. if (generateMipMaps) {
  43. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  44. } else {
  45. minFilter = gl.NEAREST;
  46. }
  47. break;
  48. case Texture.NEAREST_NEAREST_MIPNEAREST:
  49. magFilter = gl.NEAREST;
  50. if (generateMipMaps) {
  51. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  52. } else {
  53. minFilter = gl.NEAREST;
  54. }
  55. break;
  56. case Texture.NEAREST_LINEAR_MIPNEAREST:
  57. magFilter = gl.NEAREST;
  58. if (generateMipMaps) {
  59. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  60. } else {
  61. minFilter = gl.LINEAR;
  62. }
  63. break;
  64. case Texture.NEAREST_LINEAR_MIPLINEAR:
  65. magFilter = gl.NEAREST;
  66. if (generateMipMaps) {
  67. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  68. } else {
  69. minFilter = gl.LINEAR;
  70. }
  71. break;
  72. case Texture.NEAREST_LINEAR:
  73. magFilter = gl.NEAREST;
  74. minFilter = gl.LINEAR;
  75. break;
  76. case Texture.NEAREST_NEAREST:
  77. magFilter = gl.NEAREST;
  78. minFilter = gl.NEAREST;
  79. break;
  80. case Texture.LINEAR_NEAREST_MIPNEAREST:
  81. magFilter = gl.LINEAR;
  82. if (generateMipMaps) {
  83. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  84. } else {
  85. minFilter = gl.NEAREST;
  86. }
  87. break;
  88. case Texture.LINEAR_NEAREST_MIPLINEAR:
  89. magFilter = gl.LINEAR;
  90. if (generateMipMaps) {
  91. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  92. } else {
  93. minFilter = gl.NEAREST;
  94. }
  95. break;
  96. case Texture.LINEAR_LINEAR:
  97. magFilter = gl.LINEAR;
  98. minFilter = gl.LINEAR;
  99. break;
  100. case Texture.LINEAR_NEAREST:
  101. magFilter = gl.LINEAR;
  102. minFilter = gl.NEAREST;
  103. break;
  104. }
  105. return {
  106. min: minFilter,
  107. mag: magFilter
  108. }
  109. }
  110. var partialLoadImg = (url: string, index: number, loadedImages: HTMLImageElement[], scene: Nullable<Scene>,
  111. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null) => {
  112. var img: HTMLImageElement;
  113. var onload = () => {
  114. loadedImages[index] = img;
  115. (<any>loadedImages)._internalCount++;
  116. if (scene) {
  117. scene._removePendingData(img);
  118. }
  119. if ((<any>loadedImages)._internalCount === 6) {
  120. onfinish(loadedImages);
  121. }
  122. };
  123. var onerror = (message?: string, exception?: any) => {
  124. if (scene) {
  125. scene._removePendingData(img);
  126. }
  127. if (onErrorCallBack) {
  128. onErrorCallBack(message, exception);
  129. }
  130. };
  131. img = Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  132. if (scene) {
  133. scene._addPendingData(img);
  134. }
  135. }
  136. var cascadeLoadImgs = (rootUrl: string, scene: Nullable<Scene>,
  137. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null) => {
  138. var loadedImages: HTMLImageElement[] = [];
  139. (<any>loadedImages)._internalCount = 0;
  140. for (let index = 0; index < 6; index++) {
  141. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  142. }
  143. };
  144. class BufferPointer {
  145. public active: boolean;
  146. public index: number;
  147. public size: number;
  148. public type: number;
  149. public normalized: boolean;
  150. public stride: number;
  151. public offset: number;
  152. public buffer: WebGLBuffer;
  153. }
  154. export class InstancingAttributeInfo {
  155. /**
  156. * Index/offset of the attribute in the vertex shader
  157. */
  158. index: number;
  159. /**
  160. * size of the attribute, 1, 2, 3 or 4
  161. */
  162. attributeSize: number;
  163. /**
  164. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  165. * default is FLOAT
  166. */
  167. attribyteType: number;
  168. /**
  169. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  170. */
  171. normalized: boolean;
  172. /**
  173. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  174. */
  175. offset: number;
  176. /**
  177. * Name of the GLSL attribute, for debugging purpose only
  178. */
  179. attributeName: string;
  180. }
  181. /**
  182. * Define options used to create a render target texture
  183. */
  184. export class RenderTargetCreationOptions {
  185. generateMipMaps?: boolean;
  186. generateDepthBuffer?: boolean;
  187. generateStencilBuffer?: boolean;
  188. type?: number;
  189. samplingMode?: number;
  190. }
  191. /**
  192. * Regroup several parameters relative to the browser in use
  193. */
  194. export class EngineCapabilities {
  195. /** The maximum textures image */
  196. public maxTexturesImageUnits: number;
  197. public maxVertexTextureImageUnits: number;
  198. public maxCombinedTexturesImageUnits: number;
  199. /** The maximum texture size */
  200. public maxTextureSize: number;
  201. public maxCubemapTextureSize: number;
  202. public maxRenderTextureSize: number;
  203. public maxVertexAttribs: number;
  204. public maxVaryingVectors: number;
  205. public maxVertexUniformVectors: number;
  206. public maxFragmentUniformVectors: number;
  207. public standardDerivatives: boolean;
  208. public s3tc: Nullable<WEBGL_compressed_texture_s3tc>;
  209. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  210. public etc1: any; //WEBGL_compressed_texture_etc1;
  211. public etc2: any; //WEBGL_compressed_texture_etc;
  212. public astc: any; //WEBGL_compressed_texture_astc;
  213. public textureFloat: boolean;
  214. public vertexArrayObject: boolean;
  215. public textureAnisotropicFilterExtension: Nullable<EXT_texture_filter_anisotropic>;
  216. public maxAnisotropy: number;
  217. public instancedArrays: boolean;
  218. public uintIndices: boolean;
  219. public highPrecisionShaderSupported: boolean;
  220. public fragmentDepthSupported: boolean;
  221. public textureFloatLinearFiltering: boolean;
  222. public textureFloatRender: boolean;
  223. public textureHalfFloat: boolean;
  224. public textureHalfFloatLinearFiltering: boolean;
  225. public textureHalfFloatRender: boolean;
  226. public textureLOD: boolean;
  227. public drawBuffersExtension: boolean;
  228. public depthTextureExtension: boolean;
  229. public colorBufferFloat: boolean;
  230. public timerQuery: EXT_disjoint_timer_query;
  231. public canUseTimestampForTimerQuery: boolean;
  232. }
  233. export interface EngineOptions extends WebGLContextAttributes {
  234. limitDeviceRatio?: number;
  235. autoEnableWebVR?: boolean;
  236. disableWebGL2Support?: boolean;
  237. audioEngine?: boolean;
  238. deterministicLockstep?: boolean;
  239. lockstepMaxSteps?: number;
  240. doNotHandleContextLost?: boolean;
  241. }
  242. export interface IDisplayChangedEventArgs {
  243. vrDisplay: any;
  244. vrSupported: boolean;
  245. }
  246. /**
  247. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  248. */
  249. export class Engine {
  250. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  251. public static ExceptionList = [
  252. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  253. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  254. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  255. ];
  256. public static Instances = new Array<Engine>();
  257. public static get LastCreatedEngine(): Nullable<Engine> {
  258. if (Engine.Instances.length === 0) {
  259. return null;
  260. }
  261. return Engine.Instances[Engine.Instances.length - 1];
  262. }
  263. public static get LastCreatedScene(): Nullable<Scene> {
  264. var lastCreatedEngine = Engine.LastCreatedEngine;
  265. if (!lastCreatedEngine) {
  266. return null;
  267. }
  268. if (lastCreatedEngine.scenes.length === 0) {
  269. return null;
  270. }
  271. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  272. }
  273. /**
  274. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  275. */
  276. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  277. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  278. var engine = Engine.Instances[engineIndex];
  279. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  280. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  281. }
  282. }
  283. }
  284. // Const statics
  285. private static _ALPHA_DISABLE = 0;
  286. private static _ALPHA_ADD = 1;
  287. private static _ALPHA_COMBINE = 2;
  288. private static _ALPHA_SUBTRACT = 3;
  289. private static _ALPHA_MULTIPLY = 4;
  290. private static _ALPHA_MAXIMIZED = 5;
  291. private static _ALPHA_ONEONE = 6;
  292. private static _ALPHA_PREMULTIPLIED = 7;
  293. private static _ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  294. private static _ALPHA_INTERPOLATE = 9;
  295. private static _ALPHA_SCREENMODE = 10;
  296. private static _DELAYLOADSTATE_NONE = 0;
  297. private static _DELAYLOADSTATE_LOADED = 1;
  298. private static _DELAYLOADSTATE_LOADING = 2;
  299. private static _DELAYLOADSTATE_NOTLOADED = 4;
  300. private static _TEXTUREFORMAT_ALPHA = 0;
  301. private static _TEXTUREFORMAT_LUMINANCE = 1;
  302. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  303. private static _TEXTUREFORMAT_RGB = 4;
  304. private static _TEXTUREFORMAT_RGBA = 5;
  305. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  306. private static _TEXTURETYPE_FLOAT = 1;
  307. private static _TEXTURETYPE_HALF_FLOAT = 2;
  308. // Depht or Stencil test Constants.
  309. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  310. private static _ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  311. private static _LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  312. private static _EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  313. private static _LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  314. private static _GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  315. private static _GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  316. private static _NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  317. public static get NEVER(): number {
  318. return Engine._NEVER;
  319. }
  320. public static get ALWAYS(): number {
  321. return Engine._ALWAYS;
  322. }
  323. public static get LESS(): number {
  324. return Engine._LESS;
  325. }
  326. public static get EQUAL(): number {
  327. return Engine._EQUAL;
  328. }
  329. public static get LEQUAL(): number {
  330. return Engine._LEQUAL;
  331. }
  332. public static get GREATER(): number {
  333. return Engine._GREATER;
  334. }
  335. public static get GEQUAL(): number {
  336. return Engine._GEQUAL;
  337. }
  338. public static get NOTEQUAL(): number {
  339. return Engine._NOTEQUAL;
  340. }
  341. // Stencil Actions Constants.
  342. private static _KEEP = 0x1E00;
  343. private static _REPLACE = 0x1E01;
  344. private static _INCR = 0x1E02;
  345. private static _DECR = 0x1E03;
  346. private static _INVERT = 0x150A;
  347. private static _INCR_WRAP = 0x8507;
  348. private static _DECR_WRAP = 0x8508;
  349. public static get KEEP(): number {
  350. return Engine._KEEP;
  351. }
  352. public static get REPLACE(): number {
  353. return Engine._REPLACE;
  354. }
  355. public static get INCR(): number {
  356. return Engine._INCR;
  357. }
  358. public static get DECR(): number {
  359. return Engine._DECR;
  360. }
  361. public static get INVERT(): number {
  362. return Engine._INVERT;
  363. }
  364. public static get INCR_WRAP(): number {
  365. return Engine._INCR_WRAP;
  366. }
  367. public static get DECR_WRAP(): number {
  368. return Engine._DECR_WRAP;
  369. }
  370. public static get ALPHA_DISABLE(): number {
  371. return Engine._ALPHA_DISABLE;
  372. }
  373. public static get ALPHA_ONEONE(): number {
  374. return Engine._ALPHA_ONEONE;
  375. }
  376. public static get ALPHA_ADD(): number {
  377. return Engine._ALPHA_ADD;
  378. }
  379. public static get ALPHA_COMBINE(): number {
  380. return Engine._ALPHA_COMBINE;
  381. }
  382. public static get ALPHA_SUBTRACT(): number {
  383. return Engine._ALPHA_SUBTRACT;
  384. }
  385. public static get ALPHA_MULTIPLY(): number {
  386. return Engine._ALPHA_MULTIPLY;
  387. }
  388. public static get ALPHA_MAXIMIZED(): number {
  389. return Engine._ALPHA_MAXIMIZED;
  390. }
  391. public static get ALPHA_PREMULTIPLIED(): number {
  392. return Engine._ALPHA_PREMULTIPLIED;
  393. }
  394. public static get ALPHA_PREMULTIPLIED_PORTERDUFF(): number {
  395. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  396. }
  397. public static get ALPHA_INTERPOLATE(): number {
  398. return Engine._ALPHA_INTERPOLATE;
  399. }
  400. public static get ALPHA_SCREENMODE(): number {
  401. return Engine._ALPHA_SCREENMODE;
  402. }
  403. public static get DELAYLOADSTATE_NONE(): number {
  404. return Engine._DELAYLOADSTATE_NONE;
  405. }
  406. public static get DELAYLOADSTATE_LOADED(): number {
  407. return Engine._DELAYLOADSTATE_LOADED;
  408. }
  409. public static get DELAYLOADSTATE_LOADING(): number {
  410. return Engine._DELAYLOADSTATE_LOADING;
  411. }
  412. public static get DELAYLOADSTATE_NOTLOADED(): number {
  413. return Engine._DELAYLOADSTATE_NOTLOADED;
  414. }
  415. public static get TEXTUREFORMAT_ALPHA(): number {
  416. return Engine._TEXTUREFORMAT_ALPHA;
  417. }
  418. public static get TEXTUREFORMAT_LUMINANCE(): number {
  419. return Engine._TEXTUREFORMAT_LUMINANCE;
  420. }
  421. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  422. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  423. }
  424. public static get TEXTUREFORMAT_RGB(): number {
  425. return Engine._TEXTUREFORMAT_RGB;
  426. }
  427. public static get TEXTUREFORMAT_RGBA(): number {
  428. return Engine._TEXTUREFORMAT_RGBA;
  429. }
  430. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  431. return Engine._TEXTURETYPE_UNSIGNED_INT;
  432. }
  433. public static get TEXTURETYPE_FLOAT(): number {
  434. return Engine._TEXTURETYPE_FLOAT;
  435. }
  436. public static get TEXTURETYPE_HALF_FLOAT(): number {
  437. return Engine._TEXTURETYPE_HALF_FLOAT;
  438. }
  439. // Texture rescaling mode
  440. private static _SCALEMODE_FLOOR = 1;
  441. private static _SCALEMODE_NEAREST = 2;
  442. private static _SCALEMODE_CEILING = 3;
  443. public static get SCALEMODE_FLOOR(): number {
  444. return Engine._SCALEMODE_FLOOR;
  445. }
  446. public static get SCALEMODE_NEAREST(): number {
  447. return Engine._SCALEMODE_NEAREST;
  448. }
  449. public static get SCALEMODE_CEILING(): number {
  450. return Engine._SCALEMODE_CEILING;
  451. }
  452. public static get Version(): string {
  453. return "3.2.0-alpha3";
  454. }
  455. // Updatable statics so stick with vars here
  456. public static CollisionsEpsilon = 0.001;
  457. public static CodeRepository = "src/";
  458. public static ShadersRepository = "src/Shaders/";
  459. // Public members
  460. public forcePOTTextures = false;
  461. public isFullscreen = false;
  462. public isPointerLock = false;
  463. public cullBackFaces = true;
  464. public renderEvenInBackground = true;
  465. public preventCacheWipeBetweenFrames = false;
  466. // To enable/disable IDB support and avoid XHR on .manifest
  467. public enableOfflineSupport = false;
  468. public scenes = new Array<Scene>();
  469. public postProcesses = new Array<PostProcess>();
  470. // Observables
  471. /**
  472. * Observable event triggered each time the rendering canvas is resized
  473. */
  474. public onResizeObservable = new Observable<Engine>();
  475. /**
  476. * Observable event triggered each time the canvas loses focus
  477. */
  478. public onCanvasBlurObservable = new Observable<Engine>();
  479. /**
  480. * Observable event triggered each time the canvas gains focus
  481. */
  482. public onCanvasFocusObservable = new Observable<Engine>();
  483. /**
  484. * Observable event triggered each time the canvas receives pointerout event
  485. */
  486. public onCanvasPointerOutObservable = new Observable<Engine>();
  487. /**
  488. * Observable event triggered before each texture is initialized
  489. */
  490. public onBeforeTextureInitObservable = new Observable<Texture>();
  491. //WebVR
  492. private _vrDisplay: any = undefined;
  493. private _vrSupported: boolean = false;
  494. private _oldSize: Size;
  495. private _oldHardwareScaleFactor: number;
  496. private _vrExclusivePointerMode = false;
  497. public get isInVRExclusivePointerMode(): boolean {
  498. return this._vrExclusivePointerMode;
  499. }
  500. // Uniform buffers list
  501. public disableUniformBuffers = false;
  502. public _uniformBuffers = new Array<UniformBuffer>();
  503. public get supportsUniformBuffers(): boolean {
  504. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  505. }
  506. // Observables
  507. /**
  508. * Observable raised when the engine begins a new frame
  509. */
  510. public onBeginFrameObservable = new Observable<Engine>();
  511. /**
  512. * Observable raised when the engine ends the current frame
  513. */
  514. public onEndFrameObservable = new Observable<Engine>();
  515. /**
  516. * Observable raised when the engine is about to compile a shader
  517. */
  518. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  519. /**
  520. * Observable raised when the engine has jsut compiled a shader
  521. */
  522. public onAfterShaderCompilationObservable = new Observable<Engine>();
  523. // Private Members
  524. private _gl: WebGLRenderingContext;
  525. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  526. private _windowIsBackground = false;
  527. private _webGLVersion = 1.0;
  528. public get needPOTTextures(): boolean {
  529. return this._webGLVersion < 2 || this.forcePOTTextures;
  530. }
  531. private _badOS = false;
  532. public get badOS(): boolean {
  533. return this._badOS;
  534. }
  535. private _badDesktopOS = false;
  536. public get badDesktopOS(): boolean {
  537. return this._badDesktopOS;
  538. }
  539. /**
  540. * Gets or sets a value indicating if we want to disable texture binding optmization.
  541. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  542. * By default Babylon.js will try to let textures bound and only update the samplers to point where the texture is.
  543. */
  544. public disableTextureBindingOptimization = false;
  545. public static audioEngine: AudioEngine;
  546. // Focus
  547. private _onFocus: () => void;
  548. private _onBlur: () => void;
  549. private _onCanvasPointerOut: () => void;
  550. private _onCanvasBlur: () => void;
  551. private _onCanvasFocus: () => void;
  552. private _onFullscreenChange: () => void;
  553. private _onPointerLockChange: () => void;
  554. private _onVRDisplayPointerRestricted: () => void;
  555. private _onVRDisplayPointerUnrestricted: () => void;
  556. // VRDisplay connection
  557. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  558. private _onVrDisplayDisconnect: Nullable<() => void>;
  559. private _onVrDisplayPresentChange: Nullable<() => void>;
  560. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  561. public onVRRequestPresentComplete = new Observable<boolean>();
  562. public onVRRequestPresentStart = new Observable<Engine>();
  563. private _hardwareScalingLevel: number;
  564. protected _caps: EngineCapabilities;
  565. private _pointerLockRequested: boolean;
  566. private _alphaTest: boolean;
  567. private _isStencilEnable: boolean;
  568. private _colorWrite = true;
  569. private _loadingScreen: ILoadingScreen;
  570. public _drawCalls = new PerfCounter();
  571. public _textureCollisions = new PerfCounter();
  572. private _glVersion: string;
  573. private _glRenderer: string;
  574. private _glVendor: string;
  575. private _videoTextureSupported: boolean;
  576. private _renderingQueueLaunched = false;
  577. private _activeRenderLoops = new Array<() => void>();
  578. // Deterministic lockstepMaxSteps
  579. private _deterministicLockstep: boolean = false;
  580. private _lockstepMaxSteps: number = 4;
  581. // Lost context
  582. public onContextLostObservable = new Observable<Engine>();
  583. public onContextRestoredObservable = new Observable<Engine>();
  584. private _onContextLost: (evt: Event) => void;
  585. private _onContextRestored: (evt: Event) => void;
  586. private _contextWasLost = false;
  587. private _doNotHandleContextLost = false;
  588. // FPS
  589. private _performanceMonitor = new PerformanceMonitor();
  590. private _fps = 60;
  591. private _deltaTime = 0;
  592. /**
  593. * Turn this value on if you want to pause FPS computation when in background
  594. */
  595. public disablePerformanceMonitorInBackground = false;
  596. public get performanceMonitor(): PerformanceMonitor {
  597. return this._performanceMonitor;
  598. }
  599. // States
  600. protected _depthCullingState = new _DepthCullingState();
  601. protected _stencilState = new _StencilState();
  602. protected _alphaState = new _AlphaState();
  603. protected _alphaMode = Engine.ALPHA_DISABLE;
  604. // Cache
  605. private _internalTexturesCache = new Array<InternalTexture>();
  606. protected _activeChannel: number;
  607. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  608. protected _boundTexturesStack = new Array<InternalTexture>();
  609. protected _currentEffect: Nullable<Effect>;
  610. protected _currentProgram: Nullable<WebGLProgram>;
  611. private _compiledEffects: { [key: string]: Effect } = {}
  612. private _vertexAttribArraysEnabled: boolean[] = [];
  613. protected _cachedViewport: Nullable<Viewport>;
  614. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  615. protected _cachedVertexBuffers: any;
  616. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  617. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  618. protected _currentRenderTarget: Nullable<InternalTexture>;
  619. private _uintIndicesCurrentlySet = false;
  620. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  621. protected _currentFramebuffer: Nullable<WebGLFramebuffer>;
  622. private _currentBufferPointers = new Array<BufferPointer>();
  623. private _currentInstanceLocations = new Array<number>();
  624. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  625. private _textureUnits: Int32Array;
  626. private _workingCanvas: Nullable<HTMLCanvasElement>;
  627. private _workingContext: Nullable<CanvasRenderingContext2D>;
  628. private _rescalePostProcess: PassPostProcess;
  629. private _dummyFramebuffer: WebGLFramebuffer;
  630. private _externalData: StringDictionary<Object>;
  631. private _bindedRenderFunction: any;
  632. private _vaoRecordInProgress = false;
  633. private _mustWipeVertexAttributes = false;
  634. private _emptyTexture: Nullable<InternalTexture>;
  635. private _emptyCubeTexture: Nullable<InternalTexture>;
  636. private _emptyTexture3D: Nullable<InternalTexture>;
  637. private _frameHandler: number;
  638. private _nextFreeTextureSlots = new Array<number>();
  639. private _maxSimultaneousTextures = 0;
  640. private _activeRequests = new Array<IFileRequest>();
  641. // Hardware supported Compressed Textures
  642. private _texturesSupported = new Array<string>();
  643. private _textureFormatInUse: Nullable<string>;
  644. public get texturesSupported(): Array<string> {
  645. return this._texturesSupported;
  646. }
  647. public get textureFormatInUse(): Nullable<string> {
  648. return this._textureFormatInUse;
  649. }
  650. public get currentViewport(): Nullable<Viewport> {
  651. return this._cachedViewport;
  652. }
  653. // Empty texture
  654. public get emptyTexture(): InternalTexture {
  655. if (!this._emptyTexture) {
  656. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  657. }
  658. return this._emptyTexture;
  659. }
  660. public get emptyTexture3D(): InternalTexture {
  661. if (!this._emptyTexture3D) {
  662. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  663. }
  664. return this._emptyTexture3D;
  665. }
  666. public get emptyCubeTexture(): InternalTexture {
  667. if (!this._emptyCubeTexture) {
  668. var faceData = new Uint8Array(4);
  669. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  670. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Texture.NEAREST_SAMPLINGMODE);
  671. }
  672. return this._emptyCubeTexture;
  673. }
  674. /**
  675. * @constructor
  676. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  677. * @param {boolean} [antialias] - enable antialias
  678. * @param options - further options to be sent to the getContext function
  679. */
  680. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = false) {
  681. let canvas: Nullable<HTMLCanvasElement> = null;
  682. Engine.Instances.push(this);
  683. if (!canvasOrContext) {
  684. return;
  685. }
  686. options = options || {};
  687. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  688. canvas = <HTMLCanvasElement>canvasOrContext;
  689. this._renderingCanvas = canvas;
  690. if (antialias != null) {
  691. options.antialias = antialias;
  692. }
  693. if (options.deterministicLockstep === undefined) {
  694. options.deterministicLockstep = false;
  695. }
  696. if (options.lockstepMaxSteps === undefined) {
  697. options.lockstepMaxSteps = 4;
  698. }
  699. if (options.preserveDrawingBuffer === undefined) {
  700. options.preserveDrawingBuffer = false;
  701. }
  702. if (options.audioEngine === undefined) {
  703. options.audioEngine = true;
  704. }
  705. if (options.stencil === undefined) {
  706. options.stencil = true;
  707. }
  708. this._deterministicLockstep = options.deterministicLockstep;
  709. this._lockstepMaxSteps = options.lockstepMaxSteps;
  710. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  711. // Exceptions
  712. if (navigator && navigator.userAgent) {
  713. let ua = navigator.userAgent;
  714. for (var exception of Engine.ExceptionList) {
  715. let key = exception.key;
  716. let targets = exception.targets;
  717. if (ua.indexOf(key) > -1) {
  718. if (exception.capture && exception.captureConstraint) {
  719. let capture = exception.capture;
  720. let constraint = exception.captureConstraint;
  721. let regex = new RegExp(capture);
  722. let matches = regex.exec(ua);
  723. if (matches && matches.length > 0) {
  724. let capturedValue = parseInt(matches[matches.length - 1]);
  725. if (capturedValue >= constraint) {
  726. continue;
  727. }
  728. }
  729. }
  730. for (var target of targets) {
  731. switch (target) {
  732. case "uniformBuffer":
  733. this.disableUniformBuffers = true;
  734. break;
  735. case "textureBindingOptimization":
  736. this.disableTextureBindingOptimization = true;
  737. break;
  738. }
  739. }
  740. break;
  741. }
  742. }
  743. }
  744. // GL
  745. if (!options.disableWebGL2Support) {
  746. try {
  747. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  748. if (this._gl) {
  749. this._webGLVersion = 2.0;
  750. }
  751. } catch (e) {
  752. // Do nothing
  753. }
  754. }
  755. if (!this._gl) {
  756. if (!canvas) {
  757. throw new Error("The provided canvas is null or undefined.");
  758. }
  759. try {
  760. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  761. } catch (e) {
  762. throw new Error("WebGL not supported");
  763. }
  764. }
  765. if (!this._gl) {
  766. throw new Error("WebGL not supported");
  767. }
  768. this._onCanvasFocus = () => {
  769. this.onCanvasFocusObservable.notifyObservers(this);
  770. }
  771. this._onCanvasBlur = () => {
  772. this.onCanvasBlurObservable.notifyObservers(this);
  773. }
  774. canvas.addEventListener("focus", this._onCanvasFocus);
  775. canvas.addEventListener("blur", this._onCanvasBlur);
  776. this._onBlur = () => {
  777. if (this.disablePerformanceMonitorInBackground) {
  778. this._performanceMonitor.disable();
  779. }
  780. this._windowIsBackground = true;
  781. };
  782. this._onFocus = () => {
  783. if (this.disablePerformanceMonitorInBackground) {
  784. this._performanceMonitor.enable();
  785. }
  786. this._windowIsBackground = false;
  787. };
  788. this._onCanvasPointerOut = () => {
  789. this.onCanvasPointerOutObservable.notifyObservers(this);
  790. };
  791. window.addEventListener("blur", this._onBlur);
  792. window.addEventListener("focus", this._onFocus);
  793. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  794. // Context lost
  795. if (!this._doNotHandleContextLost) {
  796. this._onContextLost = (evt: Event) => {
  797. evt.preventDefault();
  798. this._contextWasLost = true;
  799. Tools.Warn("WebGL context lost.");
  800. this.onContextLostObservable.notifyObservers(this);
  801. };
  802. this._onContextRestored = (evt: Event) => {
  803. // Adding a timeout to avoid race condition at browser level
  804. setTimeout(() => {
  805. // Rebuild gl context
  806. this._initGLContext();
  807. // Rebuild effects
  808. this._rebuildEffects();
  809. // Rebuild textures
  810. this._rebuildInternalTextures();
  811. // Rebuild buffers
  812. this._rebuildBuffers();
  813. // Cache
  814. this.wipeCaches(true);
  815. Tools.Warn("WebGL context successfully restored.");
  816. this.onContextRestoredObservable.notifyObservers(this);
  817. this._contextWasLost = false;
  818. }, 0);
  819. };
  820. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  821. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  822. }
  823. } else {
  824. this._gl = <WebGLRenderingContext>canvasOrContext;
  825. this._renderingCanvas = this._gl.canvas
  826. if (this._gl.renderbufferStorageMultisample) {
  827. this._webGLVersion = 2.0;
  828. }
  829. options.stencil = this._gl.getContextAttributes().stencil;
  830. }
  831. // Viewport
  832. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  833. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  834. this.resize();
  835. this._isStencilEnable = options.stencil ? true : false;
  836. this._initGLContext();
  837. if (canvas) {
  838. // Fullscreen
  839. this._onFullscreenChange = () => {
  840. if (document.fullscreen !== undefined) {
  841. this.isFullscreen = document.fullscreen;
  842. } else if (document.mozFullScreen !== undefined) {
  843. this.isFullscreen = document.mozFullScreen;
  844. } else if (document.webkitIsFullScreen !== undefined) {
  845. this.isFullscreen = document.webkitIsFullScreen;
  846. } else if (document.msIsFullScreen !== undefined) {
  847. this.isFullscreen = document.msIsFullScreen;
  848. }
  849. // Pointer lock
  850. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  851. canvas.requestPointerLock = canvas.requestPointerLock ||
  852. canvas.msRequestPointerLock ||
  853. canvas.mozRequestPointerLock ||
  854. canvas.webkitRequestPointerLock;
  855. if (canvas.requestPointerLock) {
  856. canvas.requestPointerLock();
  857. }
  858. }
  859. };
  860. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  861. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  862. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  863. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  864. // Pointer lock
  865. this._onPointerLockChange = () => {
  866. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  867. document.webkitPointerLockElement === canvas ||
  868. document.msPointerLockElement === canvas ||
  869. document.pointerLockElement === canvas
  870. );
  871. };
  872. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  873. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  874. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  875. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  876. this._onVRDisplayPointerRestricted = () => {
  877. if (canvas) {
  878. canvas.requestPointerLock();
  879. }
  880. }
  881. this._onVRDisplayPointerUnrestricted = () => {
  882. document.exitPointerLock();
  883. }
  884. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  885. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  886. }
  887. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  888. Engine.audioEngine = new AudioEngine();
  889. }
  890. // Prepare buffer pointers
  891. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  892. this._currentBufferPointers[i] = new BufferPointer();
  893. }
  894. // Load WebVR Devices
  895. if (options.autoEnableWebVR) {
  896. this.initWebVR();
  897. }
  898. // Detect if we are running on a faulty buggy OS.
  899. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  900. // Detect if we are running on a faulty buggy desktop OS.
  901. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  902. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  903. this.enableOfflineSupport = (Database !== undefined);
  904. }
  905. private _rebuildInternalTextures(): void {
  906. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  907. for (var internalTexture of currentState) {
  908. internalTexture._rebuild();
  909. }
  910. }
  911. private _rebuildEffects(): void {
  912. for (var key in this._compiledEffects) {
  913. let effect = <Effect>this._compiledEffects[key];
  914. effect._prepareEffect();
  915. }
  916. Effect.ResetCache();
  917. }
  918. private _rebuildBuffers(): void {
  919. // Index / Vertex
  920. for (var scene of this.scenes) {
  921. scene.resetCachedMaterial();
  922. scene._rebuildGeometries();
  923. scene._rebuildTextures();
  924. }
  925. // Uniforms
  926. for (var uniformBuffer of this._uniformBuffers) {
  927. uniformBuffer._rebuild();
  928. }
  929. }
  930. private _initGLContext(): void {
  931. // Caps
  932. this._caps = new EngineCapabilities();
  933. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  934. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  935. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  936. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  937. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  938. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  939. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  940. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  941. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  942. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  943. // Infos
  944. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  945. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  946. if (rendererInfo != null) {
  947. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  948. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  949. }
  950. if (!this._glVendor) {
  951. this._glVendor = "Unknown vendor";
  952. }
  953. if (!this._glRenderer) {
  954. this._glRenderer = "Unknown renderer";
  955. }
  956. // Constants
  957. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  958. if (this._gl.RGBA16F !== 0x881A) {
  959. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  960. }
  961. if (this._gl.RGBA32F !== 0x8814) {
  962. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  963. }
  964. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  965. this._gl.DEPTH24_STENCIL8 = 35056;
  966. }
  967. // Extensions
  968. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  969. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  970. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  971. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  972. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  973. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  974. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  975. 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');
  976. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  977. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  978. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  979. this._caps.highPrecisionShaderSupported = true;
  980. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  981. if (this._caps.timerQuery) {
  982. if (this._webGLVersion === 1) {
  983. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  984. }
  985. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  986. }
  987. // Checks if some of the format renders first to allow the use of webgl inspector.
  988. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  989. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  990. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  991. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  992. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  993. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  994. if (this._webGLVersion > 1) {
  995. this._gl.HALF_FLOAT_OES = 0x140B;
  996. }
  997. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  998. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  999. // Draw buffers
  1000. if (this._webGLVersion > 1) {
  1001. this._caps.drawBuffersExtension = true;
  1002. } else {
  1003. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1004. if (drawBuffersExtension !== null) {
  1005. this._caps.drawBuffersExtension = true;
  1006. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1007. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1008. for (var i = 0; i < 16; i++) {
  1009. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1010. }
  1011. } else {
  1012. this._caps.drawBuffersExtension = false;
  1013. }
  1014. }
  1015. // Depth Texture
  1016. if (this._webGLVersion > 1) {
  1017. this._caps.depthTextureExtension = true;
  1018. } else {
  1019. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1020. if (depthTextureExtension != null) {
  1021. this._caps.depthTextureExtension = true;
  1022. }
  1023. }
  1024. // Vertex array object
  1025. if (this._webGLVersion > 1) {
  1026. this._caps.vertexArrayObject = true;
  1027. } else {
  1028. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1029. if (vertexArrayObjectExtension != null) {
  1030. this._caps.vertexArrayObject = true;
  1031. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1032. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1033. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1034. } else {
  1035. this._caps.vertexArrayObject = false;
  1036. }
  1037. }
  1038. // Instances count
  1039. if (this._webGLVersion > 1) {
  1040. this._caps.instancedArrays = true;
  1041. } else {
  1042. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1043. if (instanceExtension != null) {
  1044. this._caps.instancedArrays = true;
  1045. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1046. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1047. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1048. } else {
  1049. this._caps.instancedArrays = false;
  1050. }
  1051. }
  1052. // Intelligently add supported compressed formats in order to check for.
  1053. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1054. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1055. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1056. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1057. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  1058. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  1059. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  1060. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  1061. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  1062. if (this._gl.getShaderPrecisionFormat) {
  1063. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1064. if (highp) {
  1065. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  1066. }
  1067. }
  1068. // Depth buffer
  1069. this.setDepthBuffer(true);
  1070. this.setDepthFunctionToLessOrEqual();
  1071. this.setDepthWrite(true);
  1072. // Texture maps
  1073. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1074. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1075. this._nextFreeTextureSlots.push(slot);
  1076. }
  1077. }
  1078. public get webGLVersion(): number {
  1079. return this._webGLVersion;
  1080. }
  1081. /**
  1082. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1083. */
  1084. public get isStencilEnable(): boolean {
  1085. return this._isStencilEnable;
  1086. }
  1087. private _prepareWorkingCanvas(): void {
  1088. if (this._workingCanvas) {
  1089. return;
  1090. }
  1091. this._workingCanvas = document.createElement("canvas");
  1092. let context = this._workingCanvas.getContext("2d");
  1093. if (context) {
  1094. this._workingContext = context;
  1095. }
  1096. }
  1097. public resetTextureCache() {
  1098. for (var key in this._boundTexturesCache) {
  1099. let boundTexture = this._boundTexturesCache[key];
  1100. if (boundTexture) {
  1101. this._removeDesignatedSlot(boundTexture);
  1102. }
  1103. this._boundTexturesCache[key] = null;
  1104. }
  1105. this._nextFreeTextureSlots = [];
  1106. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1107. this._nextFreeTextureSlots.push(slot);
  1108. }
  1109. this._activeChannel = -1;
  1110. }
  1111. public isDeterministicLockStep(): boolean {
  1112. return this._deterministicLockstep;
  1113. }
  1114. public getLockstepMaxSteps(): number {
  1115. return this._lockstepMaxSteps;
  1116. }
  1117. public getGlInfo() {
  1118. return {
  1119. vendor: this._glVendor,
  1120. renderer: this._glRenderer,
  1121. version: this._glVersion
  1122. }
  1123. }
  1124. public getAspectRatio(camera: Camera, useScreen = false): number {
  1125. var viewport = camera.viewport;
  1126. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1127. }
  1128. public getRenderWidth(useScreen = false): number {
  1129. if (!useScreen && this._currentRenderTarget) {
  1130. return this._currentRenderTarget.width;
  1131. }
  1132. return this._gl.drawingBufferWidth;
  1133. }
  1134. public getRenderHeight(useScreen = false): number {
  1135. if (!useScreen && this._currentRenderTarget) {
  1136. return this._currentRenderTarget.height;
  1137. }
  1138. return this._gl.drawingBufferHeight;
  1139. }
  1140. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1141. return this._renderingCanvas;
  1142. }
  1143. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1144. if (!this._renderingCanvas) {
  1145. return null;
  1146. }
  1147. return this._renderingCanvas.getBoundingClientRect();
  1148. }
  1149. public setHardwareScalingLevel(level: number): void {
  1150. this._hardwareScalingLevel = level;
  1151. this.resize();
  1152. }
  1153. public getHardwareScalingLevel(): number {
  1154. return this._hardwareScalingLevel;
  1155. }
  1156. public getLoadedTexturesCache(): InternalTexture[] {
  1157. return this._internalTexturesCache;
  1158. }
  1159. public getCaps(): EngineCapabilities {
  1160. return this._caps;
  1161. }
  1162. /** The number of draw calls submitted last frame */
  1163. public get drawCalls(): number {
  1164. Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  1165. return 0;
  1166. }
  1167. public get drawCallsPerfCounter(): Nullable<PerfCounter> {
  1168. Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  1169. return null;
  1170. }
  1171. public getDepthFunction(): Nullable<number> {
  1172. return this._depthCullingState.depthFunc;
  1173. }
  1174. public setDepthFunction(depthFunc: number) {
  1175. this._depthCullingState.depthFunc = depthFunc;
  1176. }
  1177. public setDepthFunctionToGreater(): void {
  1178. this._depthCullingState.depthFunc = this._gl.GREATER;
  1179. }
  1180. public setDepthFunctionToGreaterOrEqual(): void {
  1181. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1182. }
  1183. public setDepthFunctionToLess(): void {
  1184. this._depthCullingState.depthFunc = this._gl.LESS;
  1185. }
  1186. public setDepthFunctionToLessOrEqual(): void {
  1187. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1188. }
  1189. public getStencilBuffer(): boolean {
  1190. return this._stencilState.stencilTest;
  1191. }
  1192. public setStencilBuffer(enable: boolean): void {
  1193. this._stencilState.stencilTest = enable;
  1194. }
  1195. public getStencilMask(): number {
  1196. return this._stencilState.stencilMask;
  1197. }
  1198. public setStencilMask(mask: number): void {
  1199. this._stencilState.stencilMask = mask;
  1200. }
  1201. public getStencilFunction(): number {
  1202. return this._stencilState.stencilFunc;
  1203. }
  1204. public getStencilFunctionReference(): number {
  1205. return this._stencilState.stencilFuncRef;
  1206. }
  1207. public getStencilFunctionMask(): number {
  1208. return this._stencilState.stencilFuncMask;
  1209. }
  1210. public setStencilFunction(stencilFunc: number) {
  1211. this._stencilState.stencilFunc = stencilFunc;
  1212. }
  1213. public setStencilFunctionReference(reference: number) {
  1214. this._stencilState.stencilFuncRef = reference;
  1215. }
  1216. public setStencilFunctionMask(mask: number) {
  1217. this._stencilState.stencilFuncMask = mask;
  1218. }
  1219. public getStencilOperationFail(): number {
  1220. return this._stencilState.stencilOpStencilFail;
  1221. }
  1222. public getStencilOperationDepthFail(): number {
  1223. return this._stencilState.stencilOpDepthFail;
  1224. }
  1225. public getStencilOperationPass(): number {
  1226. return this._stencilState.stencilOpStencilDepthPass;
  1227. }
  1228. public setStencilOperationFail(operation: number): void {
  1229. this._stencilState.stencilOpStencilFail = operation;
  1230. }
  1231. public setStencilOperationDepthFail(operation: number): void {
  1232. this._stencilState.stencilOpDepthFail = operation;
  1233. }
  1234. public setStencilOperationPass(operation: number): void {
  1235. this._stencilState.stencilOpStencilDepthPass = operation;
  1236. }
  1237. public setDitheringState(value: boolean): void {
  1238. if (value) {
  1239. this._gl.enable(this._gl.DITHER);
  1240. } else {
  1241. this._gl.disable(this._gl.DITHER);
  1242. }
  1243. }
  1244. public setRasterizerState(value: boolean): void {
  1245. if (value) {
  1246. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  1247. } else {
  1248. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  1249. }
  1250. }
  1251. /**
  1252. * stop executing a render loop function and remove it from the execution array
  1253. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  1254. */
  1255. public stopRenderLoop(renderFunction?: () => void): void {
  1256. if (!renderFunction) {
  1257. this._activeRenderLoops = [];
  1258. return;
  1259. }
  1260. var index = this._activeRenderLoops.indexOf(renderFunction);
  1261. if (index >= 0) {
  1262. this._activeRenderLoops.splice(index, 1);
  1263. }
  1264. }
  1265. public _renderLoop(): void {
  1266. if (!this._contextWasLost) {
  1267. var shouldRender = true;
  1268. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1269. shouldRender = false;
  1270. }
  1271. if (shouldRender) {
  1272. // Start new frame
  1273. this.beginFrame();
  1274. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1275. var renderFunction = this._activeRenderLoops[index];
  1276. renderFunction();
  1277. }
  1278. // Present
  1279. this.endFrame();
  1280. }
  1281. }
  1282. if (this._activeRenderLoops.length > 0) {
  1283. // Register new frame
  1284. var requester = null;
  1285. if (this._vrDisplay && this._vrDisplay.isPresenting)
  1286. requester = this._vrDisplay;
  1287. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  1288. } else {
  1289. this._renderingQueueLaunched = false;
  1290. }
  1291. }
  1292. /**
  1293. * Register and execute a render loop. The engine can have more than one render function.
  1294. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  1295. * @example
  1296. * engine.runRenderLoop(function () {
  1297. * scene.render()
  1298. * })
  1299. */
  1300. public runRenderLoop(renderFunction: () => void): void {
  1301. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1302. return;
  1303. }
  1304. this._activeRenderLoops.push(renderFunction);
  1305. if (!this._renderingQueueLaunched) {
  1306. this._renderingQueueLaunched = true;
  1307. this._bindedRenderFunction = this._renderLoop.bind(this);
  1308. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1309. }
  1310. }
  1311. /**
  1312. * Toggle full screen mode.
  1313. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  1314. * @param {any} options - an options object to be sent to the requestFullscreen function
  1315. */
  1316. public switchFullscreen(requestPointerLock: boolean): void {
  1317. if (this.isFullscreen) {
  1318. Tools.ExitFullscreen();
  1319. } else {
  1320. this._pointerLockRequested = requestPointerLock;
  1321. if (this._renderingCanvas) {
  1322. Tools.RequestFullscreen(this._renderingCanvas);
  1323. }
  1324. }
  1325. }
  1326. public clear(color: Nullable<Color4>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1327. this.applyStates();
  1328. var mode = 0;
  1329. if (backBuffer && color) {
  1330. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1331. mode |= this._gl.COLOR_BUFFER_BIT;
  1332. }
  1333. if (depth) {
  1334. this._gl.clearDepth(1.0);
  1335. mode |= this._gl.DEPTH_BUFFER_BIT;
  1336. }
  1337. if (stencil) {
  1338. this._gl.clearStencil(0);
  1339. mode |= this._gl.STENCIL_BUFFER_BIT;
  1340. }
  1341. this._gl.clear(mode);
  1342. }
  1343. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1344. let gl = this._gl;
  1345. // Save state
  1346. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1347. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1348. // Change state
  1349. gl.enable(gl.SCISSOR_TEST);
  1350. gl.scissor(x, y, width, height);
  1351. // Clear
  1352. this.clear(clearColor, true, true, true);
  1353. // Restore state
  1354. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1355. if (curScissor === true) {
  1356. gl.enable(gl.SCISSOR_TEST);
  1357. } else {
  1358. gl.disable(gl.SCISSOR_TEST);
  1359. }
  1360. }
  1361. /**
  1362. * Set the WebGL's viewport
  1363. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  1364. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  1365. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  1366. */
  1367. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1368. var width = requiredWidth || this.getRenderWidth();
  1369. var height = requiredHeight || this.getRenderHeight();
  1370. var x = viewport.x || 0;
  1371. var y = viewport.y || 0;
  1372. this._cachedViewport = viewport;
  1373. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1374. }
  1375. /**
  1376. * Directly set the WebGL Viewport
  1377. * The x, y, width & height are directly passed to the WebGL call
  1378. * @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.
  1379. */
  1380. public setDirectViewport(x: number, y: number, width: number, height: number): Nullable<Viewport> {
  1381. let currentViewport = this._cachedViewport;
  1382. this._cachedViewport = null;
  1383. this._gl.viewport(x, y, width, height);
  1384. return currentViewport;
  1385. }
  1386. public beginFrame(): void {
  1387. this.onBeginFrameObservable.notifyObservers(this);
  1388. this._measureFps();
  1389. }
  1390. public endFrame(): void {
  1391. //force a flush in case we are using a bad OS.
  1392. if (this._badOS) {
  1393. this.flushFramebuffer();
  1394. }
  1395. //submit frame to the vr device, if enabled
  1396. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1397. // TODO: We should only submit the frame if we read frameData successfully.
  1398. this._vrDisplay.submitFrame();
  1399. }
  1400. this.onEndFrameObservable.notifyObservers(this);
  1401. }
  1402. /**
  1403. * resize the view according to the canvas' size.
  1404. * @example
  1405. * window.addEventListener("resize", function () {
  1406. * engine.resize();
  1407. * });
  1408. */
  1409. public resize(): void {
  1410. // We're not resizing the size of the canvas while in VR mode & presenting
  1411. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  1412. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1413. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1414. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1415. }
  1416. }
  1417. /**
  1418. * force a specific size of the canvas
  1419. * @param {number} width - the new canvas' width
  1420. * @param {number} height - the new canvas' height
  1421. */
  1422. public setSize(width: number, height: number): void {
  1423. if (!this._renderingCanvas) {
  1424. return;
  1425. }
  1426. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1427. return;
  1428. }
  1429. this._renderingCanvas.width = width;
  1430. this._renderingCanvas.height = height;
  1431. for (var index = 0; index < this.scenes.length; index++) {
  1432. var scene = this.scenes[index];
  1433. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1434. var cam = scene.cameras[camIndex];
  1435. cam._currentRenderId = 0;
  1436. }
  1437. }
  1438. if (this.onResizeObservable.hasObservers) {
  1439. this.onResizeObservable.notifyObservers(this);
  1440. }
  1441. }
  1442. // WebVR functions
  1443. public isVRDevicePresent(): boolean {
  1444. return !!this._vrDisplay;
  1445. }
  1446. public getVRDevice(): any {
  1447. return this._vrDisplay;
  1448. }
  1449. public initWebVR(): Observable<{ vrDisplay: any, vrSupported: any }> {
  1450. var notifyObservers = () => {
  1451. var eventArgs = {
  1452. vrDisplay: this._vrDisplay,
  1453. vrSupported: this._vrSupported
  1454. };
  1455. this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  1456. }
  1457. if (!this._onVrDisplayConnect) {
  1458. this._onVrDisplayConnect = (event) => {
  1459. this._vrDisplay = event.display;
  1460. notifyObservers();
  1461. };
  1462. this._onVrDisplayDisconnect = () => {
  1463. this._vrDisplay.cancelAnimationFrame(this._frameHandler);
  1464. this._vrDisplay = undefined;
  1465. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1466. notifyObservers();
  1467. };
  1468. this._onVrDisplayPresentChange = () => {
  1469. this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;
  1470. }
  1471. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  1472. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  1473. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1474. }
  1475. this._getVRDisplays(notifyObservers);
  1476. return this.onVRDisplayChangedObservable;
  1477. }
  1478. public enableVR() {
  1479. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  1480. var onResolved = () => {
  1481. this.onVRRequestPresentComplete.notifyObservers(true);
  1482. this._onVRFullScreenTriggered();
  1483. };
  1484. var onRejected = () => {
  1485. this.onVRRequestPresentComplete.notifyObservers(false);
  1486. };
  1487. this.onVRRequestPresentStart.notifyObservers(this);
  1488. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  1489. }
  1490. }
  1491. public disableVR() {
  1492. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1493. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  1494. }
  1495. }
  1496. private _onVRFullScreenTriggered = () => {
  1497. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1498. //get the old size before we change
  1499. this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());
  1500. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1501. //get the width and height, change the render size
  1502. var leftEye = this._vrDisplay.getEyeParameters('left');
  1503. this.setHardwareScalingLevel(1);
  1504. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1505. } else {
  1506. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1507. this.setSize(this._oldSize.width, this._oldSize.height);
  1508. }
  1509. }
  1510. private _getVRDisplays(callback: () => void) {
  1511. var getWebVRDevices = (devices: Array<any>) => {
  1512. this._vrSupported = true;
  1513. // note that devices may actually be an empty array. This is fine;
  1514. // we expect this._vrDisplay to be undefined in this case.
  1515. return this._vrDisplay = devices[0];
  1516. }
  1517. if (navigator.getVRDisplays) {
  1518. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch((error: () => void) => {
  1519. // TODO: System CANNOT support WebVR, despite API presence.
  1520. this._vrSupported = false;
  1521. callback();
  1522. });
  1523. } else {
  1524. // TODO: Browser does not support WebVR
  1525. this._vrDisplay = undefined;
  1526. this._vrSupported = false;
  1527. callback();
  1528. }
  1529. }
  1530. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1531. if (this._currentRenderTarget) {
  1532. this.unBindFramebuffer(this._currentRenderTarget);
  1533. }
  1534. this._currentRenderTarget = texture;
  1535. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1536. var gl = this._gl;
  1537. if (texture.isCube) {
  1538. if (faceIndex === undefined) {
  1539. faceIndex = 0;
  1540. }
  1541. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  1542. }
  1543. if (this._cachedViewport && !forceFullscreenViewport) {
  1544. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1545. } else {
  1546. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  1547. }
  1548. this.wipeCaches();
  1549. }
  1550. private bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  1551. if (this._currentFramebuffer !== framebuffer) {
  1552. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1553. this._currentFramebuffer = framebuffer;
  1554. }
  1555. }
  1556. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1557. this._currentRenderTarget = null;
  1558. // If MSAA, we need to bitblt back to main texture
  1559. var gl = this._gl;
  1560. if (texture._MSAAFramebuffer) {
  1561. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1562. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1563. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1564. 0, 0, texture.width, texture.height,
  1565. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1566. }
  1567. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1568. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  1569. gl.generateMipmap(gl.TEXTURE_2D);
  1570. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1571. }
  1572. if (onBeforeUnbind) {
  1573. if (texture._MSAAFramebuffer) {
  1574. // Bind the correct framebuffer
  1575. this.bindUnboundFramebuffer(texture._framebuffer);
  1576. }
  1577. onBeforeUnbind();
  1578. }
  1579. this.bindUnboundFramebuffer(null);
  1580. }
  1581. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1582. this._currentRenderTarget = null;
  1583. // If MSAA, we need to bitblt back to main texture
  1584. var gl = this._gl;
  1585. if (textures[0]._MSAAFramebuffer) {
  1586. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  1587. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  1588. var attachments = textures[0]._attachments;
  1589. if (!attachments) {
  1590. attachments = new Array(textures.length);
  1591. textures[0]._attachments = attachments;
  1592. }
  1593. for (var i = 0; i < textures.length; i++) {
  1594. var texture = textures[i];
  1595. for (var j = 0; j < attachments.length; j++) {
  1596. attachments[j] = gl.NONE;
  1597. }
  1598. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  1599. gl.readBuffer(attachments[i]);
  1600. gl.drawBuffers(attachments);
  1601. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1602. 0, 0, texture.width, texture.height,
  1603. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1604. }
  1605. for (var i = 0; i < attachments.length; i++) {
  1606. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  1607. }
  1608. gl.drawBuffers(attachments);
  1609. }
  1610. for (var i = 0; i < textures.length; i++) {
  1611. var texture = textures[i];
  1612. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1613. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1614. gl.generateMipmap(gl.TEXTURE_2D);
  1615. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1616. }
  1617. }
  1618. if (onBeforeUnbind) {
  1619. if (textures[0]._MSAAFramebuffer) {
  1620. // Bind the correct framebuffer
  1621. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  1622. }
  1623. onBeforeUnbind();
  1624. }
  1625. this.bindUnboundFramebuffer(null);
  1626. }
  1627. public generateMipMapsForCubemap(texture: InternalTexture) {
  1628. if (texture.generateMipMaps) {
  1629. var gl = this._gl;
  1630. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  1631. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1632. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1633. }
  1634. }
  1635. public flushFramebuffer(): void {
  1636. this._gl.flush();
  1637. }
  1638. public restoreDefaultFramebuffer(): void {
  1639. if (this._currentRenderTarget) {
  1640. this.unBindFramebuffer(this._currentRenderTarget);
  1641. } else {
  1642. this.bindUnboundFramebuffer(null);
  1643. }
  1644. if (this._cachedViewport) {
  1645. this.setViewport(this._cachedViewport);
  1646. }
  1647. this.wipeCaches();
  1648. }
  1649. // UBOs
  1650. public createUniformBuffer(elements: FloatArray): WebGLBuffer {
  1651. var ubo = this._gl.createBuffer();
  1652. if (!ubo) {
  1653. throw new Error("Unable to create uniform buffer");
  1654. }
  1655. this.bindUniformBuffer(ubo);
  1656. if (elements instanceof Float32Array) {
  1657. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  1658. } else {
  1659. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  1660. }
  1661. this.bindUniformBuffer(null);
  1662. ubo.references = 1;
  1663. return ubo;
  1664. }
  1665. public createDynamicUniformBuffer(elements: FloatArray): WebGLBuffer {
  1666. var ubo = this._gl.createBuffer();
  1667. if (!ubo) {
  1668. throw new Error("Unable to create dynamic uniform buffer");
  1669. }
  1670. this.bindUniformBuffer(ubo);
  1671. if (elements instanceof Float32Array) {
  1672. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  1673. } else {
  1674. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  1675. }
  1676. this.bindUniformBuffer(null);
  1677. ubo.references = 1;
  1678. return ubo;
  1679. }
  1680. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void {
  1681. this.bindUniformBuffer(uniformBuffer);
  1682. if (offset === undefined) {
  1683. offset = 0;
  1684. }
  1685. if (count === undefined) {
  1686. if (elements instanceof Float32Array) {
  1687. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  1688. } else {
  1689. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  1690. }
  1691. } else {
  1692. if (elements instanceof Float32Array) {
  1693. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  1694. } else {
  1695. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  1696. }
  1697. }
  1698. this.bindUniformBuffer(null);
  1699. }
  1700. // VBOs
  1701. private _resetVertexBufferBinding(): void {
  1702. this.bindArrayBuffer(null);
  1703. this._cachedVertexBuffers = null;
  1704. }
  1705. public createVertexBuffer(vertices: FloatArray): WebGLBuffer {
  1706. var vbo = this._gl.createBuffer();
  1707. if (!vbo) {
  1708. throw new Error("Unable to create vertex buffer");
  1709. }
  1710. this.bindArrayBuffer(vbo);
  1711. if (vertices instanceof Float32Array) {
  1712. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1713. } else {
  1714. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1715. }
  1716. this._resetVertexBufferBinding();
  1717. vbo.references = 1;
  1718. return vbo;
  1719. }
  1720. public createDynamicVertexBuffer(vertices: FloatArray): WebGLBuffer {
  1721. var vbo = this._gl.createBuffer();
  1722. if (!vbo) {
  1723. throw new Error("Unable to create dynamic vertex buffer");
  1724. }
  1725. this.bindArrayBuffer(vbo);
  1726. if (vertices instanceof Float32Array) {
  1727. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1728. } else {
  1729. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1730. }
  1731. this._resetVertexBufferBinding();
  1732. vbo.references = 1;
  1733. return vbo;
  1734. }
  1735. public updateDynamicIndexBuffer(indexBuffer: WebGLBuffer, indices: IndicesArray, offset: number = 0): void {
  1736. // Force cache update
  1737. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  1738. this.bindIndexBuffer(indexBuffer);
  1739. var arrayBuffer;
  1740. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  1741. arrayBuffer = indices;
  1742. } else {
  1743. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1744. }
  1745. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  1746. this._resetIndexBufferBinding();
  1747. }
  1748. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: FloatArray, offset?: number, count?: number): void {
  1749. this.bindArrayBuffer(vertexBuffer);
  1750. if (offset === undefined) {
  1751. offset = 0;
  1752. }
  1753. if (count === undefined) {
  1754. if (vertices instanceof Float32Array) {
  1755. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1756. } else {
  1757. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1758. }
  1759. } else {
  1760. if (vertices instanceof Float32Array) {
  1761. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1762. } else {
  1763. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1764. }
  1765. }
  1766. this._resetVertexBufferBinding();
  1767. }
  1768. private _resetIndexBufferBinding(): void {
  1769. this.bindIndexBuffer(null);
  1770. this._cachedIndexBuffer = null;
  1771. }
  1772. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): WebGLBuffer {
  1773. var vbo = this._gl.createBuffer();
  1774. if (!vbo) {
  1775. throw new Error("Unable to create index buffer");
  1776. }
  1777. this.bindIndexBuffer(vbo);
  1778. // Check for 32 bits indices
  1779. var arrayBuffer;
  1780. var need32Bits = false;
  1781. if (indices instanceof Uint16Array) {
  1782. arrayBuffer = indices;
  1783. } else {
  1784. //check 32 bit support
  1785. if (this._caps.uintIndices) {
  1786. if (indices instanceof Uint32Array) {
  1787. arrayBuffer = indices;
  1788. need32Bits = true;
  1789. } else {
  1790. //number[] or Int32Array, check if 32 bit is necessary
  1791. for (var index = 0; index < indices.length; index++) {
  1792. if (indices[index] > 65535) {
  1793. need32Bits = true;
  1794. break;
  1795. }
  1796. }
  1797. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1798. }
  1799. } else {
  1800. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1801. arrayBuffer = new Uint16Array(indices);
  1802. }
  1803. }
  1804. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  1805. this._resetIndexBufferBinding();
  1806. vbo.references = 1;
  1807. vbo.is32Bits = need32Bits;
  1808. return vbo;
  1809. }
  1810. public bindArrayBuffer(buffer: Nullable<WebGLBuffer>): void {
  1811. if (!this._vaoRecordInProgress) {
  1812. this._unbindVertexArrayObject();
  1813. }
  1814. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1815. }
  1816. public bindUniformBuffer(buffer: Nullable<WebGLBuffer>): void {
  1817. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  1818. }
  1819. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  1820. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  1821. }
  1822. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  1823. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  1824. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  1825. };
  1826. private bindIndexBuffer(buffer: Nullable<WebGLBuffer>): void {
  1827. if (!this._vaoRecordInProgress) {
  1828. this._unbindVertexArrayObject();
  1829. }
  1830. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1831. }
  1832. private bindBuffer(buffer: Nullable<WebGLBuffer>, target: number): void {
  1833. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1834. this._gl.bindBuffer(target, buffer);
  1835. this._currentBoundBuffer[target] = buffer;
  1836. }
  1837. }
  1838. public updateArrayBuffer(data: Float32Array): void {
  1839. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1840. }
  1841. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1842. var pointer = this._currentBufferPointers[indx];
  1843. var changed = false;
  1844. if (!pointer.active) {
  1845. changed = true;
  1846. pointer.active = true;
  1847. pointer.index = indx;
  1848. pointer.size = size;
  1849. pointer.type = type;
  1850. pointer.normalized = normalized;
  1851. pointer.stride = stride;
  1852. pointer.offset = offset;
  1853. pointer.buffer = buffer;
  1854. } else {
  1855. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1856. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1857. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1858. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1859. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1860. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1861. }
  1862. if (changed || this._vaoRecordInProgress) {
  1863. this.bindArrayBuffer(buffer);
  1864. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1865. }
  1866. }
  1867. private _bindIndexBufferWithCache(indexBuffer: Nullable<WebGLBuffer>): void {
  1868. if (indexBuffer == null) {
  1869. return;
  1870. }
  1871. if (this._cachedIndexBuffer !== indexBuffer) {
  1872. this._cachedIndexBuffer = indexBuffer;
  1873. this.bindIndexBuffer(indexBuffer);
  1874. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1875. }
  1876. }
  1877. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  1878. var attributes = effect.getAttributesNames();
  1879. if (!this._vaoRecordInProgress) {
  1880. this._unbindVertexArrayObject();
  1881. }
  1882. this.unbindAllAttributes();
  1883. for (var index = 0; index < attributes.length; index++) {
  1884. var order = effect.getAttributeLocation(index);
  1885. if (order >= 0) {
  1886. var vertexBuffer = vertexBuffers[attributes[index]];
  1887. if (!vertexBuffer) {
  1888. continue;
  1889. }
  1890. this._gl.enableVertexAttribArray(order);
  1891. if (!this._vaoRecordInProgress) {
  1892. this._vertexAttribArraysEnabled[order] = true;
  1893. }
  1894. var buffer = vertexBuffer.getBuffer();
  1895. if (buffer) {
  1896. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1897. if (vertexBuffer.getIsInstanced()) {
  1898. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1899. if (!this._vaoRecordInProgress) {
  1900. this._currentInstanceLocations.push(order);
  1901. this._currentInstanceBuffers.push(buffer);
  1902. }
  1903. }
  1904. }
  1905. }
  1906. }
  1907. }
  1908. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): WebGLVertexArrayObject {
  1909. var vao = this._gl.createVertexArray();
  1910. this._vaoRecordInProgress = true;
  1911. this._gl.bindVertexArray(vao);
  1912. this._mustWipeVertexAttributes = true;
  1913. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1914. this.bindIndexBuffer(indexBuffer);
  1915. this._vaoRecordInProgress = false;
  1916. this._gl.bindVertexArray(null);
  1917. return vao;
  1918. }
  1919. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<WebGLBuffer>): void {
  1920. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1921. this._cachedVertexArrayObject = vertexArrayObject;
  1922. this._gl.bindVertexArray(vertexArrayObject);
  1923. this._cachedVertexBuffers = null;
  1924. this._cachedIndexBuffer = null;
  1925. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1926. this._mustWipeVertexAttributes = true;
  1927. }
  1928. }
  1929. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1930. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1931. this._cachedVertexBuffers = vertexBuffer;
  1932. this._cachedEffectForVertexBuffers = effect;
  1933. let attributesCount = effect.getAttributesCount();
  1934. this._unbindVertexArrayObject();
  1935. this.unbindAllAttributes();
  1936. var offset = 0;
  1937. for (var index = 0; index < attributesCount; index++) {
  1938. if (index < vertexDeclaration.length) {
  1939. var order = effect.getAttributeLocation(index);
  1940. if (order >= 0) {
  1941. this._gl.enableVertexAttribArray(order);
  1942. this._vertexAttribArraysEnabled[order] = true;
  1943. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1944. }
  1945. offset += vertexDeclaration[index] * 4;
  1946. }
  1947. }
  1948. }
  1949. this._bindIndexBufferWithCache(indexBuffer);
  1950. }
  1951. private _unbindVertexArrayObject(): void {
  1952. if (!this._cachedVertexArrayObject) {
  1953. return;
  1954. }
  1955. this._cachedVertexArrayObject = null;
  1956. this._gl.bindVertexArray(null);
  1957. }
  1958. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): void {
  1959. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1960. this._cachedVertexBuffers = vertexBuffers;
  1961. this._cachedEffectForVertexBuffers = effect;
  1962. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1963. }
  1964. this._bindIndexBufferWithCache(indexBuffer);
  1965. }
  1966. public unbindInstanceAttributes() {
  1967. var boundBuffer;
  1968. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1969. var instancesBuffer = this._currentInstanceBuffers[i];
  1970. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  1971. boundBuffer = instancesBuffer;
  1972. this.bindArrayBuffer(instancesBuffer);
  1973. }
  1974. var offsetLocation = this._currentInstanceLocations[i];
  1975. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1976. }
  1977. this._currentInstanceBuffers.length = 0;
  1978. this._currentInstanceLocations.length = 0;
  1979. }
  1980. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1981. this._gl.deleteVertexArray(vao);
  1982. }
  1983. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  1984. buffer.references--;
  1985. if (buffer.references === 0) {
  1986. this._gl.deleteBuffer(buffer);
  1987. return true;
  1988. }
  1989. return false;
  1990. }
  1991. public createInstancesBuffer(capacity: number): WebGLBuffer {
  1992. var buffer = this._gl.createBuffer();
  1993. if (!buffer) {
  1994. throw new Error("Unable to create instance buffer");
  1995. }
  1996. buffer.capacity = capacity;
  1997. this.bindArrayBuffer(buffer);
  1998. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1999. return buffer;
  2000. }
  2001. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  2002. this._gl.deleteBuffer(buffer);
  2003. }
  2004. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  2005. this.bindArrayBuffer(instancesBuffer);
  2006. if (data) {
  2007. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2008. }
  2009. if ((<any>offsetLocations[0]).index !== undefined) {
  2010. let stride = 0;
  2011. for (let i = 0; i < offsetLocations.length; i++) {
  2012. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2013. stride += ai.attributeSize * 4;
  2014. }
  2015. for (let i = 0; i < offsetLocations.length; i++) {
  2016. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2017. if (!this._vertexAttribArraysEnabled[ai.index]) {
  2018. this._gl.enableVertexAttribArray(ai.index);
  2019. this._vertexAttribArraysEnabled[ai.index] = true;
  2020. }
  2021. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  2022. this._gl.vertexAttribDivisor(ai.index, 1);
  2023. this._currentInstanceLocations.push(ai.index);
  2024. this._currentInstanceBuffers.push(instancesBuffer);
  2025. }
  2026. } else {
  2027. for (let index = 0; index < 4; index++) {
  2028. let offsetLocation = <number>offsetLocations[index];
  2029. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  2030. this._gl.enableVertexAttribArray(offsetLocation);
  2031. this._vertexAttribArraysEnabled[offsetLocation] = true;
  2032. }
  2033. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2034. this._gl.vertexAttribDivisor(offsetLocation, 1);
  2035. this._currentInstanceLocations.push(offsetLocation);
  2036. this._currentInstanceBuffers.push(instancesBuffer);
  2037. }
  2038. }
  2039. }
  2040. public applyStates() {
  2041. this._depthCullingState.apply(this._gl);
  2042. this._stencilState.apply(this._gl);
  2043. this._alphaState.apply(this._gl);
  2044. }
  2045. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  2046. this.drawElementsType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  2047. }
  2048. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2049. this.drawArraysType(Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  2050. }
  2051. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2052. this.drawArraysType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  2053. }
  2054. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  2055. // Apply states
  2056. this.applyStates();
  2057. this._drawCalls.addCount(1, false);
  2058. // Render
  2059. const drawMode = this.DrawMode(fillMode);
  2060. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  2061. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  2062. if (instancesCount) {
  2063. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  2064. } else {
  2065. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  2066. }
  2067. }
  2068. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2069. // Apply states
  2070. this.applyStates();
  2071. this._drawCalls.addCount(1, false);
  2072. const drawMode = this.DrawMode(fillMode);
  2073. if (instancesCount) {
  2074. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  2075. } else {
  2076. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  2077. }
  2078. }
  2079. private DrawMode(fillMode: number): number {
  2080. switch (fillMode) {
  2081. // Triangle views
  2082. case Material.TriangleFillMode:
  2083. return this._gl.TRIANGLES;
  2084. case Material.PointFillMode:
  2085. return this._gl.POINTS;
  2086. case Material.WireFrameFillMode:
  2087. return this._gl.LINES;
  2088. // Draw modes
  2089. case Material.PointListDrawMode:
  2090. return this._gl.POINTS
  2091. case Material.LineListDrawMode:
  2092. return this._gl.LINES;
  2093. case Material.LineLoopDrawMode:
  2094. return this._gl.LINE_LOOP
  2095. case Material.LineStripDrawMode:
  2096. return this._gl.LINE_STRIP
  2097. case Material.TriangleStripDrawMode:
  2098. return this._gl.TRIANGLE_STRIP
  2099. case Material.TriangleFanDrawMode:
  2100. return this._gl.TRIANGLE_FAN;
  2101. default:
  2102. return this._gl.TRIANGLES;
  2103. }
  2104. }
  2105. // Shaders
  2106. public _releaseEffect(effect: Effect): void {
  2107. if (this._compiledEffects[effect._key]) {
  2108. delete this._compiledEffects[effect._key];
  2109. this._deleteProgram(effect.getProgram());
  2110. }
  2111. }
  2112. public _deleteProgram(program: WebGLProgram): void {
  2113. if (program) {
  2114. program.__SPECTOR_rebuildProgram = null;
  2115. if (program.transformFeedback) {
  2116. this.deleteTransformFeedback(program.transformFeedback);
  2117. program.transformFeedback = null;
  2118. }
  2119. this._gl.deleteProgram(program);
  2120. }
  2121. }
  2122. /**
  2123. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  2124. * @param samplers An array of string used to represent textures
  2125. */
  2126. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  2127. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  2128. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2129. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2130. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  2131. if (this._compiledEffects[name]) {
  2132. var compiledEffect = <Effect>this._compiledEffects[name];
  2133. if (onCompiled && compiledEffect.isReady()) {
  2134. onCompiled(compiledEffect);
  2135. }
  2136. return compiledEffect;
  2137. }
  2138. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  2139. effect._key = name;
  2140. this._compiledEffects[name] = effect;
  2141. return effect;
  2142. }
  2143. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  2144. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  2145. return this.createEffect(
  2146. {
  2147. vertex: "particles",
  2148. fragmentElement: fragmentName
  2149. },
  2150. ["position", "color", "options"],
  2151. ["view", "projection"].concat(uniformsNames),
  2152. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2153. }
  2154. public createRawShaderProgram(vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2155. context = context || this._gl;
  2156. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  2157. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  2158. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2159. }
  2160. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2161. context = context || this._gl;
  2162. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  2163. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  2164. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  2165. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  2166. let program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2167. this.onAfterShaderCompilationObservable.notifyObservers(this);
  2168. return program;
  2169. }
  2170. private _createShaderProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2171. var shaderProgram = context.createProgram();
  2172. if (!shaderProgram) {
  2173. throw new Error("Unable to create program");
  2174. }
  2175. context.attachShader(shaderProgram, vertexShader);
  2176. context.attachShader(shaderProgram, fragmentShader);
  2177. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2178. let transformFeedback = this.createTransformFeedback();
  2179. this.bindTransformFeedback(transformFeedback);
  2180. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  2181. shaderProgram.transformFeedback = transformFeedback;
  2182. }
  2183. context.linkProgram(shaderProgram);
  2184. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2185. this.bindTransformFeedback(null);
  2186. }
  2187. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  2188. if (!linked) {
  2189. context.validateProgram(shaderProgram);
  2190. var error = context.getProgramInfoLog(shaderProgram);
  2191. if (error) {
  2192. throw new Error(error);
  2193. }
  2194. }
  2195. context.deleteShader(vertexShader);
  2196. context.deleteShader(fragmentShader);
  2197. return shaderProgram;
  2198. }
  2199. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2200. var results = new Array<Nullable<WebGLUniformLocation>>();
  2201. for (var index = 0; index < uniformsNames.length; index++) {
  2202. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2203. }
  2204. return results;
  2205. }
  2206. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  2207. var results = [];
  2208. for (var index = 0; index < attributesNames.length; index++) {
  2209. try {
  2210. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2211. } catch (e) {
  2212. results.push(-1);
  2213. }
  2214. }
  2215. return results;
  2216. }
  2217. public enableEffect(effect: Nullable<Effect>): void {
  2218. if (!effect) {
  2219. return;
  2220. }
  2221. // Use program
  2222. this.bindSamplers(effect);
  2223. this._currentEffect = effect;
  2224. if (effect.onBind) {
  2225. effect.onBind(effect);
  2226. }
  2227. effect.onBindObservable.notifyObservers(effect);
  2228. }
  2229. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2230. if (!uniform)
  2231. return;
  2232. this._gl.uniform1iv(uniform, array);
  2233. }
  2234. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2235. if (!uniform || array.length % 2 !== 0)
  2236. return;
  2237. this._gl.uniform2iv(uniform, array);
  2238. }
  2239. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2240. if (!uniform || array.length % 3 !== 0)
  2241. return;
  2242. this._gl.uniform3iv(uniform, array);
  2243. }
  2244. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2245. if (!uniform || array.length % 4 !== 0)
  2246. return;
  2247. this._gl.uniform4iv(uniform, array);
  2248. }
  2249. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2250. if (!uniform)
  2251. return;
  2252. this._gl.uniform1fv(uniform, array);
  2253. }
  2254. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2255. if (!uniform || array.length % 2 !== 0)
  2256. return;
  2257. this._gl.uniform2fv(uniform, array);
  2258. }
  2259. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2260. if (!uniform || array.length % 3 !== 0)
  2261. return;
  2262. this._gl.uniform3fv(uniform, array);
  2263. }
  2264. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2265. if (!uniform || array.length % 4 !== 0)
  2266. return;
  2267. this._gl.uniform4fv(uniform, array);
  2268. }
  2269. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2270. if (!uniform)
  2271. return;
  2272. this._gl.uniform1fv(uniform, <any>array);
  2273. }
  2274. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2275. if (!uniform || array.length % 2 !== 0)
  2276. return;
  2277. this._gl.uniform2fv(uniform, <any>array);
  2278. }
  2279. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2280. if (!uniform || array.length % 3 !== 0)
  2281. return;
  2282. this._gl.uniform3fv(uniform, <any>array);
  2283. }
  2284. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2285. if (!uniform || array.length % 4 !== 0)
  2286. return;
  2287. this._gl.uniform4fv(uniform, <any>array);
  2288. }
  2289. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  2290. if (!uniform)
  2291. return;
  2292. this._gl.uniformMatrix4fv(uniform, false, matrices);
  2293. }
  2294. public setMatrix(uniform: Nullable<WebGLUniformLocation>, matrix: Matrix): void {
  2295. if (!uniform)
  2296. return;
  2297. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  2298. }
  2299. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2300. if (!uniform)
  2301. return;
  2302. this._gl.uniformMatrix3fv(uniform, false, matrix);
  2303. }
  2304. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2305. if (!uniform)
  2306. return;
  2307. this._gl.uniformMatrix2fv(uniform, false, matrix);
  2308. }
  2309. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2310. if (!uniform)
  2311. return;
  2312. this._gl.uniform1i(uniform, value);
  2313. }
  2314. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2315. if (!uniform)
  2316. return;
  2317. this._gl.uniform1f(uniform, value);
  2318. }
  2319. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  2320. if (!uniform)
  2321. return;
  2322. this._gl.uniform2f(uniform, x, y);
  2323. }
  2324. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  2325. if (!uniform)
  2326. return;
  2327. this._gl.uniform3f(uniform, x, y, z);
  2328. }
  2329. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  2330. if (!uniform)
  2331. return;
  2332. this._gl.uniform1i(uniform, bool);
  2333. }
  2334. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  2335. if (!uniform)
  2336. return;
  2337. this._gl.uniform4f(uniform, x, y, z, w);
  2338. }
  2339. public setColor3(uniform: Nullable<WebGLUniformLocation>, color3: Color3): void {
  2340. if (!uniform)
  2341. return;
  2342. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  2343. }
  2344. public setColor4(uniform: Nullable<WebGLUniformLocation>, color3: Color3, alpha: number): void {
  2345. if (!uniform)
  2346. return;
  2347. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  2348. }
  2349. // States
  2350. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  2351. // Culling
  2352. if (this._depthCullingState.cull !== culling || force) {
  2353. this._depthCullingState.cull = culling;
  2354. }
  2355. // Cull face
  2356. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  2357. if (this._depthCullingState.cullFace !== cullFace || force) {
  2358. this._depthCullingState.cullFace = cullFace;
  2359. }
  2360. // Z offset
  2361. this.setZOffset(zOffset);
  2362. // Front face
  2363. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  2364. if (this._depthCullingState.frontFace !== frontFace || force) {
  2365. this._depthCullingState.frontFace = frontFace;
  2366. }
  2367. }
  2368. public setZOffset(value: number): void {
  2369. this._depthCullingState.zOffset = value;
  2370. }
  2371. public getZOffset(): number {
  2372. return this._depthCullingState.zOffset;
  2373. }
  2374. public setDepthBuffer(enable: boolean): void {
  2375. this._depthCullingState.depthTest = enable;
  2376. }
  2377. public getDepthWrite(): boolean {
  2378. return this._depthCullingState.depthMask;
  2379. }
  2380. public setDepthWrite(enable: boolean): void {
  2381. this._depthCullingState.depthMask = enable;
  2382. }
  2383. public setColorWrite(enable: boolean): void {
  2384. this._gl.colorMask(enable, enable, enable, enable);
  2385. this._colorWrite = enable;
  2386. }
  2387. public getColorWrite(): boolean {
  2388. return this._colorWrite;
  2389. }
  2390. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  2391. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  2392. }
  2393. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  2394. if (this._alphaMode === mode) {
  2395. return;
  2396. }
  2397. switch (mode) {
  2398. case Engine.ALPHA_DISABLE:
  2399. this._alphaState.alphaBlend = false;
  2400. break;
  2401. case Engine.ALPHA_PREMULTIPLIED:
  2402. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2403. this._alphaState.alphaBlend = true;
  2404. break;
  2405. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  2406. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2407. this._alphaState.alphaBlend = true;
  2408. break;
  2409. case Engine.ALPHA_COMBINE:
  2410. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2411. this._alphaState.alphaBlend = true;
  2412. break;
  2413. case Engine.ALPHA_ONEONE:
  2414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2415. this._alphaState.alphaBlend = true;
  2416. break;
  2417. case Engine.ALPHA_ADD:
  2418. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2419. this._alphaState.alphaBlend = true;
  2420. break;
  2421. case Engine.ALPHA_SUBTRACT:
  2422. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2423. this._alphaState.alphaBlend = true;
  2424. break;
  2425. case Engine.ALPHA_MULTIPLY:
  2426. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  2427. this._alphaState.alphaBlend = true;
  2428. break;
  2429. case Engine.ALPHA_MAXIMIZED:
  2430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2431. this._alphaState.alphaBlend = true;
  2432. break;
  2433. case Engine.ALPHA_INTERPOLATE:
  2434. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  2435. this._alphaState.alphaBlend = true;
  2436. break;
  2437. case Engine.ALPHA_SCREENMODE:
  2438. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2439. this._alphaState.alphaBlend = true;
  2440. break;
  2441. }
  2442. if (!noDepthWriteChange) {
  2443. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  2444. }
  2445. this._alphaMode = mode;
  2446. }
  2447. public getAlphaMode(): number {
  2448. return this._alphaMode;
  2449. }
  2450. public setAlphaTesting(enable: boolean): void {
  2451. this._alphaTest = enable;
  2452. }
  2453. public getAlphaTesting(): boolean {
  2454. return !!this._alphaTest;
  2455. }
  2456. // Textures
  2457. public wipeCaches(bruteForce?: boolean): void {
  2458. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  2459. return;
  2460. }
  2461. this._currentEffect = null;
  2462. // 6/8/2017: deltakosh: Should not be required anymore.
  2463. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  2464. if (bruteForce) {
  2465. this.resetTextureCache();
  2466. this._currentProgram = null;
  2467. this._stencilState.reset();
  2468. this._depthCullingState.reset();
  2469. this.setDepthFunctionToLessOrEqual();
  2470. this._alphaState.reset();
  2471. }
  2472. this._resetVertexBufferBinding();
  2473. this._cachedIndexBuffer = null;
  2474. this._cachedEffectForVertexBuffers = null;
  2475. this._unbindVertexArrayObject();
  2476. this.bindIndexBuffer(null);
  2477. }
  2478. /**
  2479. * Set the compressed texture format to use, based on the formats you have, and the formats
  2480. * supported by the hardware / browser.
  2481. *
  2482. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  2483. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  2484. * to API arguments needed to compressed textures. This puts the burden on the container
  2485. * generator to house the arcane code for determining these for current & future formats.
  2486. *
  2487. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  2488. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  2489. *
  2490. * Note: The result of this call is not taken into account when a texture is base64.
  2491. *
  2492. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  2493. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  2494. *
  2495. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  2496. * @returns The extension selected.
  2497. */
  2498. public setTextureFormatToUse(formatsAvailable: Array<string>): Nullable<string> {
  2499. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  2500. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  2501. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  2502. return this._textureFormatInUse = this._texturesSupported[i];
  2503. }
  2504. }
  2505. }
  2506. // actively set format to nothing, to allow this to be called more than once
  2507. // and possibly fail the 2nd time
  2508. this._textureFormatInUse = null;
  2509. return null;
  2510. }
  2511. public _createTexture(): WebGLTexture {
  2512. let texture = this._gl.createTexture();
  2513. if (!texture) {
  2514. throw new Error("Unable to create texture");
  2515. }
  2516. return texture;
  2517. }
  2518. /**
  2519. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  2520. * @param {string} urlArg- This contains one of the following:
  2521. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  2522. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2523. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2524. *
  2525. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  2526. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  2527. * @param {Scene} scene- Needed for loading to the correct scene.
  2528. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  2529. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  2530. * @param {callback} onError- Optional callback to be called upon failure.
  2531. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  2532. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  2533. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  2534. *
  2535. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  2536. */
  2537. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE,
  2538. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  2539. buffer: Nullable<ArrayBuffer | HTMLImageElement> = null, fallBack: Nullable<InternalTexture> = null, format: Nullable<number> = null): InternalTexture {
  2540. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  2541. var fromData = url.substr(0, 5) === "data:";
  2542. var fromBlob = url.substr(0, 5) === "blob:";
  2543. var isBase64 = fromData && url.indexOf("base64") !== -1;
  2544. let texture = fallBack ? fallBack : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  2545. // establish the file extension, if possible
  2546. var lastDot = url.lastIndexOf('.');
  2547. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  2548. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  2549. var isTGA = (extension === ".tga");
  2550. // determine if a ktx file should be substituted
  2551. var isKTX = false;
  2552. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  2553. url = url.substring(0, lastDot) + this._textureFormatInUse;
  2554. isKTX = true;
  2555. }
  2556. if (scene) {
  2557. scene._addPendingData(texture);
  2558. }
  2559. texture.url = url;
  2560. texture.generateMipMaps = !noMipmap;
  2561. texture.samplingMode = samplingMode;
  2562. texture.invertY = invertY;
  2563. if (!this._doNotHandleContextLost) {
  2564. // Keep a link to the buffer only if we plan to handle context lost
  2565. texture._buffer = buffer;
  2566. }
  2567. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  2568. if (onLoad && !fallBack) {
  2569. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  2570. }
  2571. if (!fallBack) this._internalTexturesCache.push(texture);
  2572. var onerror = (message?: string, exception?: any) => {
  2573. if (scene) {
  2574. scene._removePendingData(texture);
  2575. }
  2576. if (onLoadObserver) {
  2577. texture.onLoadedObservable.remove(onLoadObserver);
  2578. }
  2579. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  2580. if (isKTX) {
  2581. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2582. } else if (Tools.UseFallbackTexture) {
  2583. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2584. }
  2585. if (onError) {
  2586. onError(message || "Unknown error", exception);
  2587. }
  2588. };
  2589. var callback: Nullable<(arrayBuffer: any) => void> = null;
  2590. // processing for non-image formats
  2591. if (isKTX || isTGA || isDDS) {
  2592. if (isKTX) {
  2593. callback = (data) => {
  2594. var ktx = new KhronosTextureContainer(data, 1);
  2595. this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  2596. ktx.uploadLevels(this._gl, !noMipmap);
  2597. return false;
  2598. }, samplingMode);
  2599. };
  2600. } else if (isTGA) {
  2601. callback = (arrayBuffer) => {
  2602. var data = new Uint8Array(arrayBuffer);
  2603. var header = TGATools.GetTGAHeader(data);
  2604. this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, () => {
  2605. TGATools.UploadContent(this._gl, data);
  2606. return false;
  2607. }, samplingMode);
  2608. };
  2609. } else if (isDDS) {
  2610. callback = (data) => {
  2611. var info = DDSTools.GetDDSInfo(data);
  2612. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  2613. this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  2614. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 1);
  2615. return false;
  2616. }, samplingMode);
  2617. };
  2618. }
  2619. if (!buffer) {
  2620. this._loadFile(url, data => {
  2621. if (callback) {
  2622. callback(data);
  2623. }
  2624. }, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  2625. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  2626. });
  2627. } else {
  2628. if (callback) {
  2629. callback(buffer);
  2630. }
  2631. }
  2632. // image format processing
  2633. } else {
  2634. var onload = (img: HTMLImageElement) => {
  2635. if (fromBlob && !this._doNotHandleContextLost) {
  2636. // We need to store the image if we need to rebuild the texture
  2637. // in case of a webgl context lost
  2638. texture._buffer = img;
  2639. }
  2640. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2641. let gl = this._gl;
  2642. var isPot = (img.width === potWidth && img.height === potHeight);
  2643. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2644. if (isPot) {
  2645. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2646. return false;
  2647. }
  2648. // Using shaders to rescale because canvas.drawImage is lossy
  2649. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  2650. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  2651. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2652. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2653. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2655. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2656. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2657. this._releaseTexture(source);
  2658. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2659. continuationCallback();
  2660. });
  2661. return true;
  2662. }, samplingMode);
  2663. };
  2664. if (!fromData || isBase64)
  2665. if (buffer instanceof HTMLImageElement) {
  2666. onload(buffer);
  2667. } else {
  2668. Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  2669. }
  2670. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  2671. Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  2672. else
  2673. onload(<HTMLImageElement>buffer);
  2674. }
  2675. return texture;
  2676. }
  2677. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  2678. let rtt = this.createRenderTargetTexture({
  2679. width: destination.width,
  2680. height: destination.height,
  2681. }, {
  2682. generateMipMaps: false,
  2683. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  2684. samplingMode: Texture.BILINEAR_SAMPLINGMODE,
  2685. generateDepthBuffer: false,
  2686. generateStencilBuffer: false
  2687. }
  2688. );
  2689. if (!this._rescalePostProcess) {
  2690. this._rescalePostProcess = new PassPostProcess("rescale", 1, null, Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  2691. }
  2692. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  2693. this._rescalePostProcess.onApply = function (effect) {
  2694. effect._bindTexture("textureSampler", source);
  2695. }
  2696. let hostingScene = scene;
  2697. if (!hostingScene) {
  2698. hostingScene = this.scenes[this.scenes.length - 1];
  2699. }
  2700. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  2701. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  2702. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  2703. this.unBindFramebuffer(rtt);
  2704. this._releaseTexture(rtt);
  2705. if (onComplete) {
  2706. onComplete();
  2707. }
  2708. });
  2709. }
  2710. private _getInternalFormat(format: number): number {
  2711. var internalFormat = this._gl.RGBA;
  2712. switch (format) {
  2713. case Engine.TEXTUREFORMAT_ALPHA:
  2714. internalFormat = this._gl.ALPHA;
  2715. break;
  2716. case Engine.TEXTUREFORMAT_LUMINANCE:
  2717. internalFormat = this._gl.LUMINANCE;
  2718. break;
  2719. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  2720. internalFormat = this._gl.LUMINANCE_ALPHA;
  2721. break;
  2722. case Engine.TEXTUREFORMAT_RGB:
  2723. internalFormat = this._gl.RGB;
  2724. break;
  2725. case Engine.TEXTUREFORMAT_RGBA:
  2726. internalFormat = this._gl.RGBA;
  2727. break;
  2728. }
  2729. return internalFormat;
  2730. }
  2731. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  2732. if (!texture) {
  2733. return;
  2734. }
  2735. var internalFormat = this._getInternalFormat(format);
  2736. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  2737. var textureType = this._getWebGLTextureType(type);
  2738. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2739. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2740. if (!this._doNotHandleContextLost) {
  2741. texture._bufferView = data;
  2742. texture.format = format;
  2743. texture.type = type;
  2744. texture.invertY = invertY;
  2745. texture._compression = compression;
  2746. }
  2747. if (texture.width % 4 !== 0) {
  2748. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  2749. }
  2750. if (compression && data) {
  2751. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, data);
  2752. } else {
  2753. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  2754. }
  2755. if (texture.generateMipMaps) {
  2756. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2757. }
  2758. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2759. // this.resetTextureCache();
  2760. texture.isReady = true;
  2761. }
  2762. 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 {
  2763. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  2764. texture.baseWidth = width;
  2765. texture.baseHeight = height;
  2766. texture.width = width;
  2767. texture.height = height;
  2768. texture.format = format;
  2769. texture.generateMipMaps = generateMipMaps;
  2770. texture.samplingMode = samplingMode;
  2771. texture.invertY = invertY;
  2772. texture._compression = compression;
  2773. texture.type = type;
  2774. if (!this._doNotHandleContextLost) {
  2775. texture._bufferView = data;
  2776. }
  2777. this.updateRawTexture(texture, data, format, invertY, compression, type);
  2778. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2779. // Filters
  2780. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  2781. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2782. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2783. if (generateMipMaps) {
  2784. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2785. }
  2786. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2787. this._internalTexturesCache.push(texture);
  2788. return texture;
  2789. }
  2790. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  2791. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  2792. texture.baseWidth = width;
  2793. texture.baseHeight = height;
  2794. if (generateMipMaps) {
  2795. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  2796. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  2797. }
  2798. // this.resetTextureCache();
  2799. texture.width = width;
  2800. texture.height = height;
  2801. texture.isReady = false;
  2802. texture.generateMipMaps = generateMipMaps;
  2803. texture.samplingMode = samplingMode;
  2804. this.updateTextureSamplingMode(samplingMode, texture);
  2805. this._internalTexturesCache.push(texture);
  2806. return texture;
  2807. }
  2808. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  2809. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  2810. if (texture.isCube) {
  2811. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  2812. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2813. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2814. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2815. } else if (texture.is3D) {
  2816. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  2817. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2818. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2819. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  2820. } else {
  2821. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2822. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2823. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2824. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2825. }
  2826. texture.samplingMode = samplingMode;
  2827. }
  2828. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  2829. if (!texture) {
  2830. return;
  2831. }
  2832. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2833. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  2834. if (premulAlpha) {
  2835. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  2836. }
  2837. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2838. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  2839. if (texture.generateMipMaps) {
  2840. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2841. }
  2842. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2843. if (premulAlpha) {
  2844. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2845. }
  2846. texture.isReady = true;
  2847. }
  2848. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  2849. if (!texture || texture._isDisabled) {
  2850. return;
  2851. }
  2852. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2853. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  2854. try {
  2855. // Testing video texture support
  2856. if (this._videoTextureSupported === undefined) {
  2857. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2858. if (this._gl.getError() !== 0) {
  2859. this._videoTextureSupported = false;
  2860. } else {
  2861. this._videoTextureSupported = true;
  2862. }
  2863. }
  2864. // Copy video through the current working canvas if video texture is not supported
  2865. if (!this._videoTextureSupported) {
  2866. if (!texture._workingCanvas) {
  2867. texture._workingCanvas = document.createElement("canvas");
  2868. let context = texture._workingCanvas.getContext("2d");
  2869. if (!context) {
  2870. throw new Error("Unable to get 2d context");
  2871. }
  2872. texture._workingContext = context;
  2873. texture._workingCanvas.width = texture.width;
  2874. texture._workingCanvas.height = texture.height;
  2875. }
  2876. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  2877. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  2878. } else {
  2879. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2880. }
  2881. if (texture.generateMipMaps) {
  2882. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2883. }
  2884. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2885. // this.resetTextureCache();
  2886. texture.isReady = true;
  2887. } catch (ex) {
  2888. // Something unexpected
  2889. // Let's disable the texture
  2890. texture._isDisabled = true;
  2891. }
  2892. }
  2893. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  2894. let fullOptions = new RenderTargetCreationOptions();
  2895. if (options !== undefined && typeof options === "object") {
  2896. fullOptions.generateMipMaps = options.generateMipMaps;
  2897. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2898. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  2899. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  2900. fullOptions.samplingMode = options.samplingMode === undefined ? Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  2901. } else {
  2902. fullOptions.generateMipMaps = <boolean>options;
  2903. fullOptions.generateDepthBuffer = true;
  2904. fullOptions.generateStencilBuffer = false;
  2905. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2906. fullOptions.samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2907. }
  2908. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2909. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2910. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2911. }
  2912. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2913. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2914. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2915. }
  2916. var gl = this._gl;
  2917. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  2918. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2919. var width = (<{ width: number, height: number }>size).width || <number>size;
  2920. var height = (<{ width: number, height: number }>size).height || <number>size;
  2921. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  2922. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2923. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2924. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2925. }
  2926. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2927. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2928. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2929. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2930. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  2931. // Create the framebuffer
  2932. var framebuffer = gl.createFramebuffer();
  2933. this.bindUnboundFramebuffer(framebuffer);
  2934. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  2935. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  2936. if (fullOptions.generateMipMaps) {
  2937. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2938. }
  2939. // Unbind
  2940. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2941. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2942. this.bindUnboundFramebuffer(null);
  2943. texture._framebuffer = framebuffer;
  2944. texture.baseWidth = width;
  2945. texture.baseHeight = height;
  2946. texture.width = width;
  2947. texture.height = height;
  2948. texture.isReady = true;
  2949. texture.samples = 1;
  2950. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  2951. texture.samplingMode = fullOptions.samplingMode;
  2952. texture.type = fullOptions.type;
  2953. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  2954. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  2955. // this.resetTextureCache();
  2956. this._internalTexturesCache.push(texture);
  2957. return texture;
  2958. }
  2959. public createMultipleRenderTarget(size: any, options: any): InternalTexture[] {
  2960. var generateMipMaps = false;
  2961. var generateDepthBuffer = true;
  2962. var generateStencilBuffer = false;
  2963. var generateDepthTexture = false;
  2964. var textureCount = 1;
  2965. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  2966. var defaultSamplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2967. var types = [], samplingModes = [];
  2968. if (options !== undefined) {
  2969. generateMipMaps = options.generateMipMaps;
  2970. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2971. generateStencilBuffer = options.generateStencilBuffer;
  2972. generateDepthTexture = options.generateDepthTexture;
  2973. textureCount = options.textureCount || 1;
  2974. if (options.types) {
  2975. types = options.types;
  2976. }
  2977. if (options.samplingModes) {
  2978. samplingModes = options.samplingModes;
  2979. }
  2980. }
  2981. var gl = this._gl;
  2982. // Create the framebuffer
  2983. var framebuffer = gl.createFramebuffer();
  2984. this.bindUnboundFramebuffer(framebuffer);
  2985. var width = size.width || size;
  2986. var height = size.height || size;
  2987. var textures = [];
  2988. var attachments = []
  2989. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  2990. for (var i = 0; i < textureCount; i++) {
  2991. var samplingMode = samplingModes[i] || defaultSamplingMode;
  2992. var type = types[i] || defaultType;
  2993. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2994. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2995. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2996. }
  2997. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2998. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2999. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3000. }
  3001. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3002. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  3003. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3004. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  3005. }
  3006. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  3007. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  3008. textures.push(texture);
  3009. attachments.push(attachment);
  3010. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  3011. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  3012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3013. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3016. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3017. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  3018. if (generateMipMaps) {
  3019. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3020. }
  3021. // Unbind
  3022. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3023. texture._framebuffer = framebuffer;
  3024. texture._depthStencilBuffer = depthStencilBuffer;
  3025. texture.baseWidth = width;
  3026. texture.baseHeight = height;
  3027. texture.width = width;
  3028. texture.height = height;
  3029. texture.isReady = true;
  3030. texture.samples = 1;
  3031. texture.generateMipMaps = generateMipMaps;
  3032. texture.samplingMode = samplingMode;
  3033. texture.type = type;
  3034. texture._generateDepthBuffer = generateDepthBuffer;
  3035. texture._generateStencilBuffer = generateStencilBuffer;
  3036. texture._attachments = attachments;
  3037. this._internalTexturesCache.push(texture);
  3038. }
  3039. if (generateDepthTexture && this._caps.depthTextureExtension) {
  3040. // Depth texture
  3041. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  3042. gl.activeTexture(gl.TEXTURE0);
  3043. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  3044. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3045. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3046. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3047. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3048. gl.texImage2D(
  3049. gl.TEXTURE_2D,
  3050. 0,
  3051. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  3052. width,
  3053. height,
  3054. 0,
  3055. gl.DEPTH_COMPONENT,
  3056. gl.UNSIGNED_SHORT,
  3057. null
  3058. );
  3059. gl.framebufferTexture2D(
  3060. gl.FRAMEBUFFER,
  3061. gl.DEPTH_ATTACHMENT,
  3062. gl.TEXTURE_2D,
  3063. depthTexture._webGLTexture,
  3064. 0
  3065. );
  3066. depthTexture._framebuffer = framebuffer;
  3067. depthTexture.baseWidth = width;
  3068. depthTexture.baseHeight = height;
  3069. depthTexture.width = width;
  3070. depthTexture.height = height;
  3071. depthTexture.isReady = true;
  3072. depthTexture.samples = 1;
  3073. depthTexture.generateMipMaps = generateMipMaps;
  3074. depthTexture.samplingMode = gl.NEAREST;
  3075. depthTexture._generateDepthBuffer = generateDepthBuffer;
  3076. depthTexture._generateStencilBuffer = generateStencilBuffer;
  3077. textures.push(depthTexture)
  3078. this._internalTexturesCache.push(depthTexture);
  3079. }
  3080. gl.drawBuffers(attachments);
  3081. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3082. this.bindUnboundFramebuffer(null);
  3083. this.resetTextureCache();
  3084. return textures;
  3085. }
  3086. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  3087. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  3088. var gl = this._gl;
  3089. // Create the depth/stencil buffer
  3090. if (generateStencilBuffer) {
  3091. depthStencilBuffer = gl.createRenderbuffer();
  3092. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  3093. if (samples > 1) {
  3094. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  3095. } else {
  3096. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  3097. }
  3098. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  3099. }
  3100. else if (generateDepthBuffer) {
  3101. depthStencilBuffer = gl.createRenderbuffer();
  3102. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  3103. if (samples > 1) {
  3104. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  3105. } else {
  3106. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3107. }
  3108. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  3109. }
  3110. return depthStencilBuffer;
  3111. }
  3112. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  3113. if (this.webGLVersion < 2 || !texture) {
  3114. return 1;
  3115. }
  3116. if (texture.samples === samples) {
  3117. return samples;
  3118. }
  3119. var gl = this._gl;
  3120. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  3121. // Dispose previous render buffers
  3122. if (texture._depthStencilBuffer) {
  3123. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3124. texture._depthStencilBuffer = null;
  3125. }
  3126. if (texture._MSAAFramebuffer) {
  3127. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3128. texture._MSAAFramebuffer = null;
  3129. }
  3130. if (texture._MSAARenderBuffer) {
  3131. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3132. texture._MSAARenderBuffer = null;
  3133. }
  3134. if (samples > 1) {
  3135. let framebuffer = gl.createFramebuffer();
  3136. if (!framebuffer) {
  3137. throw new Error("Unable to create multi sampled framebuffer");
  3138. }
  3139. texture._MSAAFramebuffer = framebuffer;
  3140. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  3141. var colorRenderbuffer = gl.createRenderbuffer();
  3142. if (!colorRenderbuffer) {
  3143. throw new Error("Unable to create multi sampled framebuffer");
  3144. }
  3145. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  3146. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  3147. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  3148. texture._MSAARenderBuffer = colorRenderbuffer;
  3149. } else {
  3150. this.bindUnboundFramebuffer(texture._framebuffer);
  3151. }
  3152. texture.samples = samples;
  3153. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  3154. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3155. this.bindUnboundFramebuffer(null);
  3156. return samples;
  3157. }
  3158. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  3159. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  3160. return 1;
  3161. }
  3162. if (textures[0].samples === samples) {
  3163. return samples;
  3164. }
  3165. var gl = this._gl;
  3166. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  3167. // Dispose previous render buffers
  3168. if (textures[0]._depthStencilBuffer) {
  3169. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  3170. textures[0]._depthStencilBuffer = null;
  3171. }
  3172. if (textures[0]._MSAAFramebuffer) {
  3173. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  3174. textures[0]._MSAAFramebuffer = null;
  3175. }
  3176. for (var i = 0; i < textures.length; i++) {
  3177. if (textures[i]._MSAARenderBuffer) {
  3178. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  3179. textures[i]._MSAARenderBuffer = null;
  3180. }
  3181. }
  3182. if (samples > 1) {
  3183. let framebuffer = gl.createFramebuffer();
  3184. if (!framebuffer) {
  3185. throw new Error("Unable to create multi sampled framebuffer");
  3186. }
  3187. this.bindUnboundFramebuffer(framebuffer);
  3188. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  3189. var attachments = [];
  3190. for (var i = 0; i < textures.length; i++) {
  3191. var texture = textures[i];
  3192. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  3193. var colorRenderbuffer = gl.createRenderbuffer();
  3194. if (!colorRenderbuffer) {
  3195. throw new Error("Unable to create multi sampled framebuffer");
  3196. }
  3197. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  3198. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  3199. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  3200. texture._MSAAFramebuffer = framebuffer;
  3201. texture._MSAARenderBuffer = colorRenderbuffer;
  3202. texture.samples = samples;
  3203. texture._depthStencilBuffer = depthStencilBuffer;
  3204. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3205. attachments.push(attachment);
  3206. }
  3207. gl.drawBuffers(attachments);
  3208. } else {
  3209. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  3210. }
  3211. this.bindUnboundFramebuffer(null);
  3212. return samples;
  3213. }
  3214. public _uploadDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, format: number, type: number, data: ArrayBufferView) {
  3215. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  3216. }
  3217. public _uploadCompressedDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, data: ArrayBufferView) {
  3218. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  3219. }
  3220. public createRenderTargetCubeTexture(size: number, options?: RenderTargetCreationOptions): InternalTexture {
  3221. var gl = this._gl;
  3222. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  3223. var generateMipMaps = true;
  3224. var generateDepthBuffer = true;
  3225. var generateStencilBuffer = false;
  3226. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  3227. if (options !== undefined) {
  3228. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  3229. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3230. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  3231. if (options.samplingMode !== undefined) {
  3232. samplingMode = options.samplingMode;
  3233. }
  3234. }
  3235. texture.isCube = true;
  3236. texture.generateMipMaps = generateMipMaps;
  3237. texture.samples = 1;
  3238. texture.samplingMode = samplingMode;
  3239. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3240. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3241. for (var face = 0; face < 6; face++) {
  3242. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3243. }
  3244. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3245. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3246. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3247. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3248. // Create the framebuffer
  3249. var framebuffer = gl.createFramebuffer();
  3250. this.bindUnboundFramebuffer(framebuffer);
  3251. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  3252. // Mipmaps
  3253. if (texture.generateMipMaps) {
  3254. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3255. }
  3256. // Unbind
  3257. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3258. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3259. this.bindUnboundFramebuffer(null);
  3260. texture._framebuffer = framebuffer;
  3261. texture.width = size;
  3262. texture.height = size;
  3263. texture.isReady = true;
  3264. //this.resetTextureCache();
  3265. this._internalTexturesCache.push(texture);
  3266. return texture;
  3267. }
  3268. public createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, scale: number, offset: number,
  3269. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  3270. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null): InternalTexture {
  3271. var callback = (loadData: any) => {
  3272. if (!loadData) {
  3273. if (onLoad) {
  3274. onLoad(null);
  3275. }
  3276. return;
  3277. }
  3278. let texture = loadData.texture as InternalTexture;
  3279. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  3280. texture._lodGenerationScale = scale;
  3281. texture._lodGenerationOffset = offset;
  3282. if (this._caps.textureLOD) {
  3283. // Do not add extra process if texture lod is supported.
  3284. if (onLoad) {
  3285. onLoad(texture);
  3286. }
  3287. return;
  3288. }
  3289. const mipSlices = 3;
  3290. var gl = this._gl;
  3291. const width = loadData.width;
  3292. if (!width) {
  3293. return;
  3294. }
  3295. const textures: BaseTexture[] = [];
  3296. for (let i = 0; i < mipSlices; i++) {
  3297. //compute LOD from even spacing in smoothness (matching shader calculation)
  3298. let smoothness = i / (mipSlices - 1);
  3299. let roughness = 1 - smoothness;
  3300. let minLODIndex = offset; // roughness = 0
  3301. let maxLODIndex = Scalar.Log2(width) * scale + offset; // roughness = 1
  3302. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  3303. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  3304. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3305. glTextureFromLod.isCube = true;
  3306. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  3307. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3308. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3309. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3310. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3311. if (loadData.isDDS) {
  3312. var info: DDSInfo = loadData.info;
  3313. var data: any = loadData.data;
  3314. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3315. DDSTools.UploadDDSLevels(this, this._gl, data, info, true, 6, mipmapIndex);
  3316. }
  3317. else {
  3318. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  3319. }
  3320. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3321. // Wrap in a base texture for easy binding.
  3322. const lodTexture = new BaseTexture(scene);
  3323. lodTexture.isCube = true;
  3324. lodTexture._texture = glTextureFromLod;
  3325. glTextureFromLod.isReady = true;
  3326. textures.push(lodTexture);
  3327. }
  3328. texture._lodTextureHigh = textures[2];
  3329. texture._lodTextureMid = textures[1];
  3330. texture._lodTextureLow = textures[0];
  3331. if (onLoad) {
  3332. onLoad(texture);
  3333. }
  3334. };
  3335. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  3336. }
  3337. 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): InternalTexture {
  3338. var gl = this._gl;
  3339. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  3340. texture.isCube = true;
  3341. texture.url = rootUrl;
  3342. texture.generateMipMaps = !noMipmap;
  3343. if (!this._doNotHandleContextLost) {
  3344. texture._extension = forcedExtension;
  3345. texture._files = files;
  3346. }
  3347. var isKTX = false;
  3348. var isDDS = false;
  3349. var lastDot = rootUrl.lastIndexOf('.');
  3350. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  3351. if (this._textureFormatInUse) {
  3352. extension = this._textureFormatInUse;
  3353. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  3354. isKTX = true;
  3355. } else {
  3356. isDDS = (extension === ".dds");
  3357. }
  3358. let onerror = (request?: XMLHttpRequest, exception?: any) => {
  3359. if (onError && request) {
  3360. onError(request.status + " " + request.statusText, exception);
  3361. }
  3362. }
  3363. if (isKTX) {
  3364. this._loadFile(rootUrl, data => {
  3365. var ktx = new KhronosTextureContainer(data, 6);
  3366. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  3367. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3368. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3369. ktx.uploadLevels(this._gl, !noMipmap);
  3370. this.setCubeMapTextureParams(gl, loadMipmap);
  3371. texture.width = ktx.pixelWidth;
  3372. texture.height = ktx.pixelHeight;
  3373. texture.isReady = true;
  3374. }, undefined, undefined, true, onerror);
  3375. } else if (isDDS) {
  3376. if (files && files.length === 6) {
  3377. this._cascadeLoadFiles(rootUrl,
  3378. scene,
  3379. imgs => {
  3380. var info: DDSInfo | undefined;
  3381. var loadMipmap: boolean = false;
  3382. var width: number = 0;
  3383. for (let index = 0; index < imgs.length; index++) {
  3384. let data = imgs[index];
  3385. info = DDSTools.GetDDSInfo(data);
  3386. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3387. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3388. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3389. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6, -1, index);
  3390. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  3391. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3392. }
  3393. texture.width = info.width;
  3394. texture.height = info.height;
  3395. texture.type = info.textureType;
  3396. width = info.width;
  3397. }
  3398. this.setCubeMapTextureParams(gl, loadMipmap);
  3399. texture.isReady = true;
  3400. if (onLoad) {
  3401. onLoad({ isDDS: true, width: width, info, imgs, texture });
  3402. }
  3403. },
  3404. files,
  3405. onError);
  3406. } else {
  3407. this._loadFile(rootUrl,
  3408. data => {
  3409. var info = DDSTools.GetDDSInfo(data);
  3410. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3411. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3412. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3413. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6);
  3414. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  3415. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3416. }
  3417. this.setCubeMapTextureParams(gl, loadMipmap);
  3418. texture.width = info.width;
  3419. texture.height = info.height;
  3420. texture.isReady = true;
  3421. texture.type = info.textureType;
  3422. if (onLoad) {
  3423. onLoad({ isDDS: true, width: info.width, info, data, texture });
  3424. }
  3425. },
  3426. undefined,
  3427. undefined,
  3428. true,
  3429. onerror);
  3430. }
  3431. } else {
  3432. if (!files) {
  3433. throw new Error("Cannot load cubemap because files were not defined");
  3434. }
  3435. cascadeLoadImgs(rootUrl, scene, imgs => {
  3436. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  3437. var height = width;
  3438. this._prepareWorkingCanvas();
  3439. if (!this._workingCanvas || !this._workingContext) {
  3440. return;
  3441. }
  3442. this._workingCanvas.width = width;
  3443. this._workingCanvas.height = height;
  3444. var faces = [
  3445. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3446. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3447. ];
  3448. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3449. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3450. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  3451. for (var index = 0; index < faces.length; index++) {
  3452. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3453. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  3454. }
  3455. if (!noMipmap) {
  3456. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3457. }
  3458. this.setCubeMapTextureParams(gl, !noMipmap);
  3459. texture.width = width;
  3460. texture.height = height;
  3461. texture.isReady = true;
  3462. if (format) {
  3463. texture.format = format;
  3464. }
  3465. texture.onLoadedObservable.notifyObservers(texture);
  3466. texture.onLoadedObservable.clear();
  3467. if (onLoad) {
  3468. onLoad();
  3469. }
  3470. }, files, onError);
  3471. }
  3472. this._internalTexturesCache.push(texture);
  3473. return texture;
  3474. }
  3475. private setCubeMapTextureParams(gl: WebGLRenderingContext, loadMipmap: boolean) {
  3476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3479. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3480. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3481. // this.resetTextureCache();
  3482. }
  3483. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  3484. texture._bufferViewArray = data;
  3485. texture.format = format;
  3486. texture.type = type;
  3487. texture.invertY = invertY;
  3488. texture._compression = compression;
  3489. var gl = this._gl;
  3490. var textureType = this._getWebGLTextureType(type);
  3491. var internalFormat = this._getInternalFormat(format);
  3492. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3493. var needConversion = false;
  3494. if (internalFormat === gl.RGB) {
  3495. internalFormat = gl.RGBA;
  3496. needConversion = true;
  3497. }
  3498. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3499. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3500. if (texture.width % 4 !== 0) {
  3501. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  3502. }
  3503. // Data are known to be in +X +Y +Z -X -Y -Z
  3504. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  3505. let faceData = data[faceIndex];
  3506. if (compression) {
  3507. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, faceData);
  3508. } else {
  3509. if (needConversion) {
  3510. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  3511. }
  3512. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  3513. }
  3514. }
  3515. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3516. if (isPot && texture.generateMipMaps && level === 0) {
  3517. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3518. }
  3519. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3520. // this.resetTextureCache();
  3521. texture.isReady = true;
  3522. }
  3523. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null): InternalTexture {
  3524. var gl = this._gl;
  3525. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  3526. texture.isCube = true;
  3527. texture.generateMipMaps = generateMipMaps;
  3528. texture.format = format;
  3529. texture.type = type;
  3530. if (!this._doNotHandleContextLost) {
  3531. texture._bufferViewArray = data;
  3532. }
  3533. var textureType = this._getWebGLTextureType(type);
  3534. var internalFormat = this._getInternalFormat(format);
  3535. if (internalFormat === gl.RGB) {
  3536. internalFormat = gl.RGBA;
  3537. }
  3538. var width = size;
  3539. var height = width;
  3540. texture.width = width;
  3541. texture.height = height;
  3542. // Double check on POT to generate Mips.
  3543. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3544. if (!isPot) {
  3545. generateMipMaps = false;
  3546. }
  3547. // Upload data if needed. The texture won't be ready until then.
  3548. if (data) {
  3549. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  3550. }
  3551. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  3552. // Filters
  3553. if (data && generateMipMaps) {
  3554. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3555. }
  3556. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  3557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3559. }
  3560. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  3561. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3562. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3563. }
  3564. else {
  3565. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3568. }
  3569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3571. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3572. return texture;
  3573. }
  3574. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  3575. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  3576. mipmmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  3577. onLoad: Nullable<() => void> = null,
  3578. onError: Nullable<(message?: string, exception?: any) => void> = null,
  3579. samplingMode = Texture.TRILINEAR_SAMPLINGMODE,
  3580. invertY = false): InternalTexture {
  3581. var gl = this._gl;
  3582. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  3583. scene._addPendingData(texture);
  3584. texture.url = url;
  3585. this._internalTexturesCache.push(texture);
  3586. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  3587. scene._removePendingData(texture);
  3588. if (onError && request) {
  3589. onError(request.status + " " + request.statusText, exception);
  3590. }
  3591. };
  3592. var internalCallback = (data: any) => {
  3593. var width = texture.width;
  3594. var faceDataArrays = callback(data);
  3595. if (!faceDataArrays) {
  3596. return;
  3597. }
  3598. if (mipmmapGenerator) {
  3599. var textureType = this._getWebGLTextureType(type);
  3600. var internalFormat = this._getInternalFormat(format);
  3601. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3602. var needConversion = false;
  3603. if (internalFormat === gl.RGB) {
  3604. internalFormat = gl.RGBA;
  3605. needConversion = true;
  3606. }
  3607. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3608. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3609. var mipData = mipmmapGenerator(faceDataArrays);
  3610. for (var level = 0; level < mipData.length; level++) {
  3611. var mipSize = width >> level;
  3612. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  3613. let mipFaceData = mipData[level][faceIndex];
  3614. if (needConversion) {
  3615. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  3616. }
  3617. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  3618. }
  3619. }
  3620. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3621. }
  3622. else {
  3623. texture.generateMipMaps = !noMipmap;
  3624. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  3625. }
  3626. texture.isReady = true;
  3627. // this.resetTextureCache();
  3628. scene._removePendingData(texture);
  3629. if (onLoad) {
  3630. onLoad();
  3631. }
  3632. };
  3633. this._loadFile(url, data => {
  3634. internalCallback(data);
  3635. }, undefined, scene.database, true, onerror);
  3636. return texture;
  3637. };
  3638. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null): void {
  3639. var internalFormat = this._getInternalFormat(format);
  3640. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  3641. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3642. if (!this._doNotHandleContextLost) {
  3643. texture._bufferView = data;
  3644. texture.format = format;
  3645. texture.invertY = invertY;
  3646. texture._compression = compression;
  3647. }
  3648. if (texture.width % 4 !== 0) {
  3649. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3650. }
  3651. if (compression && data) {
  3652. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  3653. } else {
  3654. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  3655. }
  3656. if (texture.generateMipMaps) {
  3657. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  3658. }
  3659. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3660. // this.resetTextureCache();
  3661. texture.isReady = true;
  3662. }
  3663. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null): InternalTexture {
  3664. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  3665. texture.baseWidth = width;
  3666. texture.baseHeight = height;
  3667. texture.baseDepth = depth;
  3668. texture.width = width;
  3669. texture.height = height;
  3670. texture.depth = depth;
  3671. texture.format = format;
  3672. texture.generateMipMaps = generateMipMaps;
  3673. texture.samplingMode = samplingMode;
  3674. texture.is3D = true;
  3675. if (!this._doNotHandleContextLost) {
  3676. texture._bufferView = data;
  3677. }
  3678. this.updateRawTexture3D(texture, data, format, invertY, compression);
  3679. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  3680. // Filters
  3681. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3682. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3683. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3684. if (generateMipMaps) {
  3685. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  3686. }
  3687. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3688. this._internalTexturesCache.push(texture);
  3689. return texture;
  3690. }
  3691. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  3692. var gl = this._gl;
  3693. if (!gl) {
  3694. return;
  3695. }
  3696. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3697. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3698. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3699. if (!noMipmap && !isCompressed) {
  3700. gl.generateMipmap(gl.TEXTURE_2D);
  3701. }
  3702. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3703. // this.resetTextureCache();
  3704. if (scene) {
  3705. scene._removePendingData(texture);
  3706. }
  3707. texture.onLoadedObservable.notifyObservers(texture);
  3708. texture.onLoadedObservable.clear();
  3709. }
  3710. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  3711. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): void {
  3712. var potWidth = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  3713. var potHeight = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  3714. var gl = this._gl;
  3715. if (!gl) {
  3716. return;
  3717. }
  3718. if (!texture._webGLTexture) {
  3719. // this.resetTextureCache();
  3720. if (scene) {
  3721. scene._removePendingData(texture);
  3722. }
  3723. return;
  3724. }
  3725. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3726. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3727. texture.baseWidth = width;
  3728. texture.baseHeight = height;
  3729. texture.width = potWidth;
  3730. texture.height = potHeight;
  3731. texture.isReady = true;
  3732. if (processFunction(potWidth, potHeight, () => {
  3733. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3734. })) {
  3735. // Returning as texture needs extra async steps
  3736. return;
  3737. }
  3738. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3739. }
  3740. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  3741. // Create new RGBA data container.
  3742. var rgbaData: any;
  3743. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  3744. rgbaData = new Float32Array(width * height * 4);
  3745. }
  3746. else {
  3747. rgbaData = new Uint32Array(width * height * 4);
  3748. }
  3749. // Convert each pixel.
  3750. for (let x = 0; x < width; x++) {
  3751. for (let y = 0; y < height; y++) {
  3752. let index = (y * width + x) * 3;
  3753. let newIndex = (y * width + x) * 4;
  3754. // Map Old Value to new value.
  3755. rgbaData[newIndex + 0] = rgbData[index + 0];
  3756. rgbaData[newIndex + 1] = rgbData[index + 1];
  3757. rgbaData[newIndex + 2] = rgbData[index + 2];
  3758. // Add fully opaque alpha channel.
  3759. rgbaData[newIndex + 3] = 1;
  3760. }
  3761. }
  3762. return rgbaData;
  3763. }
  3764. public _releaseFramebufferObjects(texture: InternalTexture): void {
  3765. var gl = this._gl;
  3766. if (texture._framebuffer) {
  3767. gl.deleteFramebuffer(texture._framebuffer);
  3768. texture._framebuffer = null;
  3769. }
  3770. if (texture._depthStencilBuffer) {
  3771. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3772. texture._depthStencilBuffer = null;
  3773. }
  3774. if (texture._MSAAFramebuffer) {
  3775. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3776. texture._MSAAFramebuffer = null;
  3777. }
  3778. if (texture._MSAARenderBuffer) {
  3779. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3780. texture._MSAARenderBuffer = null;
  3781. }
  3782. }
  3783. public _releaseTexture(texture: InternalTexture): void {
  3784. var gl = this._gl;
  3785. this._releaseFramebufferObjects(texture);
  3786. gl.deleteTexture(texture._webGLTexture);
  3787. // Unbind channels
  3788. this.unbindAllTextures();
  3789. var index = this._internalTexturesCache.indexOf(texture);
  3790. if (index !== -1) {
  3791. this._internalTexturesCache.splice(index, 1);
  3792. }
  3793. // Integrated fixed lod samplers.
  3794. if (texture._lodTextureHigh) {
  3795. texture._lodTextureHigh.dispose();
  3796. }
  3797. if (texture._lodTextureMid) {
  3798. texture._lodTextureMid.dispose();
  3799. }
  3800. if (texture._lodTextureLow) {
  3801. texture._lodTextureLow.dispose();
  3802. }
  3803. }
  3804. private setProgram(program: WebGLProgram): void {
  3805. if (this._currentProgram !== program) {
  3806. this._gl.useProgram(program);
  3807. this._currentProgram = program;
  3808. }
  3809. }
  3810. private _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  3811. public bindSamplers(effect: Effect): void {
  3812. this.setProgram(effect.getProgram());
  3813. var samplers = effect.getSamplers();
  3814. for (var index = 0; index < samplers.length; index++) {
  3815. var uniform = effect.getUniform(samplers[index]);
  3816. if (uniform) {
  3817. this._boundUniforms[index] = uniform;
  3818. }
  3819. }
  3820. this._currentEffect = null;
  3821. }
  3822. private _activateTextureChannel(channel: number): void {
  3823. if (this._activeChannel !== channel && channel > -1) {
  3824. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  3825. this._activeChannel = channel;
  3826. }
  3827. }
  3828. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  3829. let index = this._boundTexturesStack.indexOf(internalTexture);
  3830. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  3831. this._boundTexturesStack.splice(index, 1);
  3832. this._boundTexturesStack.push(internalTexture);
  3833. }
  3834. }
  3835. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  3836. let currentSlot = internalTexture._designatedSlot;
  3837. internalTexture._designatedSlot = -1;
  3838. let index = this._boundTexturesStack.indexOf(internalTexture);
  3839. if (index > -1) {
  3840. this._boundTexturesStack.splice(index, 1);
  3841. if (currentSlot > -1) {
  3842. this._boundTexturesCache[currentSlot] = null;
  3843. this._nextFreeTextureSlots.push(currentSlot);
  3844. }
  3845. }
  3846. return currentSlot;
  3847. }
  3848. public _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, doNotBindUniformToTextureChannel = false): void {
  3849. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  3850. let isTextureForRendering = texture && texture._initialSlot > -1;
  3851. if (currentTextureBound !== texture) {
  3852. if (currentTextureBound) {
  3853. this._removeDesignatedSlot(currentTextureBound);
  3854. }
  3855. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  3856. if (this._activeChannel >= 0) {
  3857. this._boundTexturesCache[this._activeChannel] = texture;
  3858. if (isTextureForRendering) {
  3859. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  3860. if (slotIndex > -1) {
  3861. this._nextFreeTextureSlots.splice(slotIndex, 1);
  3862. }
  3863. this._boundTexturesStack.push(texture!);
  3864. }
  3865. }
  3866. }
  3867. if (isTextureForRendering && this._activeChannel > -1) {
  3868. texture!._designatedSlot = this._activeChannel;
  3869. if (!doNotBindUniformToTextureChannel) {
  3870. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  3871. }
  3872. }
  3873. }
  3874. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  3875. if (channel < 0) {
  3876. return;
  3877. }
  3878. if (texture) {
  3879. channel = this._getCorrectTextureChannel(channel, texture);
  3880. }
  3881. this._activateTextureChannel(channel);
  3882. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  3883. }
  3884. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  3885. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  3886. }
  3887. public unbindAllTextures(): void {
  3888. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  3889. this._activateTextureChannel(channel);
  3890. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3891. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3892. if (this.webGLVersion > 1) {
  3893. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3894. }
  3895. }
  3896. }
  3897. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  3898. if (channel < 0) {
  3899. return;
  3900. }
  3901. if (uniform) {
  3902. this._boundUniforms[channel] = uniform;
  3903. }
  3904. this._setTexture(channel, texture);
  3905. }
  3906. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  3907. if (!internalTexture) {
  3908. return -1;
  3909. }
  3910. internalTexture._initialSlot = channel;
  3911. if (this.disableTextureBindingOptimization) { // We want texture sampler ID == texture channel
  3912. if (channel !== internalTexture._designatedSlot) {
  3913. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  3914. this._removeDesignatedSlot(internalTexture);
  3915. }
  3916. this._textureCollisions.addCount(1, false);
  3917. }
  3918. } else {
  3919. if (channel !== internalTexture._designatedSlot) {
  3920. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  3921. return internalTexture._designatedSlot;
  3922. } else {
  3923. // No slot for this texture, let's pick a new one (if we find a free slot)
  3924. if (this._nextFreeTextureSlots.length) {
  3925. return this._nextFreeTextureSlots[0];
  3926. }
  3927. // We need to recycle the oldest bound texture, sorry.
  3928. this._textureCollisions.addCount(1, false);
  3929. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  3930. }
  3931. }
  3932. }
  3933. return channel;
  3934. }
  3935. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  3936. let uniform = this._boundUniforms[sourceSlot];
  3937. this._gl.uniform1i(uniform, destination);
  3938. }
  3939. private _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false): boolean {
  3940. // Not ready?
  3941. if (!texture) {
  3942. if (this._boundTexturesCache[channel] != null) {
  3943. this._activateTextureChannel(channel);
  3944. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3945. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3946. if (this.webGLVersion > 1) {
  3947. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3948. }
  3949. }
  3950. return false;
  3951. }
  3952. // Video
  3953. var alreadyActivated = false;
  3954. if ((<VideoTexture>texture).video) {
  3955. this._activateTextureChannel(channel);
  3956. alreadyActivated = true;
  3957. (<VideoTexture>texture).update();
  3958. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  3959. texture.delayLoad();
  3960. return false;
  3961. }
  3962. let internalTexture: InternalTexture;
  3963. if (texture.isReady()) {
  3964. internalTexture = <InternalTexture>texture.getInternalTexture();
  3965. }
  3966. else if (texture.isCube) {
  3967. internalTexture = this.emptyCubeTexture;
  3968. }
  3969. else if (texture.is3D) {
  3970. internalTexture = this.emptyTexture3D;
  3971. }
  3972. else {
  3973. internalTexture = this.emptyTexture;
  3974. }
  3975. if (!isPartOfTextureArray) {
  3976. channel = this._getCorrectTextureChannel(channel, internalTexture);
  3977. }
  3978. if (this._boundTexturesCache[channel] === internalTexture) {
  3979. this._moveBoundTextureOnTop(internalTexture);
  3980. if (!isPartOfTextureArray) {
  3981. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  3982. }
  3983. return false;
  3984. }
  3985. if (!alreadyActivated) {
  3986. this._activateTextureChannel(channel);
  3987. }
  3988. if (internalTexture && internalTexture.is3D) {
  3989. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  3990. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  3991. internalTexture._cachedWrapU = texture.wrapU;
  3992. switch (texture.wrapU) {
  3993. case Texture.WRAP_ADDRESSMODE:
  3994. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3995. break;
  3996. case Texture.CLAMP_ADDRESSMODE:
  3997. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3998. break;
  3999. case Texture.MIRROR_ADDRESSMODE:
  4000. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4001. break;
  4002. }
  4003. }
  4004. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  4005. internalTexture._cachedWrapV = texture.wrapV;
  4006. switch (texture.wrapV) {
  4007. case Texture.WRAP_ADDRESSMODE:
  4008. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4009. break;
  4010. case Texture.CLAMP_ADDRESSMODE:
  4011. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4012. break;
  4013. case Texture.MIRROR_ADDRESSMODE:
  4014. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4015. break;
  4016. }
  4017. }
  4018. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  4019. internalTexture._cachedWrapR = texture.wrapR;
  4020. switch (texture.wrapV) {
  4021. case Texture.WRAP_ADDRESSMODE:
  4022. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  4023. break;
  4024. case Texture.CLAMP_ADDRESSMODE:
  4025. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  4026. break;
  4027. case Texture.MIRROR_ADDRESSMODE:
  4028. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  4029. break;
  4030. }
  4031. }
  4032. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  4033. }
  4034. else if (internalTexture && internalTexture.isCube) {
  4035. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  4036. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4037. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4038. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4039. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4040. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4041. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4042. }
  4043. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4044. } else {
  4045. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  4046. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  4047. internalTexture._cachedWrapU = texture.wrapU;
  4048. switch (texture.wrapU) {
  4049. case Texture.WRAP_ADDRESSMODE:
  4050. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4051. break;
  4052. case Texture.CLAMP_ADDRESSMODE:
  4053. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4054. break;
  4055. case Texture.MIRROR_ADDRESSMODE:
  4056. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4057. break;
  4058. }
  4059. }
  4060. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  4061. internalTexture._cachedWrapV = texture.wrapV;
  4062. switch (texture.wrapV) {
  4063. case Texture.WRAP_ADDRESSMODE:
  4064. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4065. break;
  4066. case Texture.CLAMP_ADDRESSMODE:
  4067. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4068. break;
  4069. case Texture.MIRROR_ADDRESSMODE:
  4070. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4071. break;
  4072. }
  4073. }
  4074. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4075. }
  4076. return true;
  4077. }
  4078. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  4079. if (channel < 0 || !uniform) {
  4080. return;
  4081. }
  4082. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  4083. this._textureUnits = new Int32Array(textures.length);
  4084. }
  4085. for (let i = 0; i < textures.length; i++) {
  4086. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  4087. }
  4088. this._gl.uniform1iv(uniform, this._textureUnits);
  4089. for (var index = 0; index < textures.length; index++) {
  4090. this._setTexture(this._textureUnits[index], textures[index], true);
  4091. }
  4092. }
  4093. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  4094. var internalTexture = texture.getInternalTexture();
  4095. if (!internalTexture) {
  4096. return;
  4097. }
  4098. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4099. var value = texture.anisotropicFilteringLevel;
  4100. if (internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPNEAREST
  4101. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPLINEAR
  4102. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR) {
  4103. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  4104. }
  4105. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  4106. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  4107. internalTexture._cachedAnisotropicFilteringLevel = value;
  4108. }
  4109. }
  4110. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  4111. var data = new Uint8Array(height * width * 4);
  4112. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4113. return data;
  4114. }
  4115. /**
  4116. * Add an externaly attached data from its key.
  4117. * This method call will fail and return false, if such key already exists.
  4118. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  4119. * @param key the unique key that identifies the data
  4120. * @param data the data object to associate to the key for this Engine instance
  4121. * @return true if no such key were already present and the data was added successfully, false otherwise
  4122. */
  4123. public addExternalData<T>(key: string, data: T): boolean {
  4124. if (!this._externalData) {
  4125. this._externalData = new StringDictionary<Object>();
  4126. }
  4127. return this._externalData.add(key, data);
  4128. }
  4129. /**
  4130. * Get an externaly attached data from its key
  4131. * @param key the unique key that identifies the data
  4132. * @return the associated data, if present (can be null), or undefined if not present
  4133. */
  4134. public getExternalData<T>(key: string): T {
  4135. if (!this._externalData) {
  4136. this._externalData = new StringDictionary<Object>();
  4137. }
  4138. return <T>this._externalData.get(key);
  4139. }
  4140. /**
  4141. * Get an externaly attached data from its key, create it using a factory if it's not already present
  4142. * @param key the unique key that identifies the data
  4143. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  4144. * @return the associated data, can be null if the factory returned null.
  4145. */
  4146. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  4147. if (!this._externalData) {
  4148. this._externalData = new StringDictionary<Object>();
  4149. }
  4150. return <T>this._externalData.getOrAddWithFactory(key, factory);
  4151. }
  4152. /**
  4153. * Remove an externaly attached data from the Engine instance
  4154. * @param key the unique key that identifies the data
  4155. * @return true if the data was successfully removed, false if it doesn't exist
  4156. */
  4157. public removeExternalData(key: string): boolean {
  4158. if (!this._externalData) {
  4159. this._externalData = new StringDictionary<Object>();
  4160. }
  4161. return this._externalData.remove(key);
  4162. }
  4163. public unbindAllAttributes() {
  4164. if (this._mustWipeVertexAttributes) {
  4165. this._mustWipeVertexAttributes = false;
  4166. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  4167. this._gl.disableVertexAttribArray(i);
  4168. this._vertexAttribArraysEnabled[i] = false;
  4169. this._currentBufferPointers[i].active = false;
  4170. }
  4171. return;
  4172. }
  4173. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  4174. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  4175. continue;
  4176. }
  4177. this._gl.disableVertexAttribArray(i);
  4178. this._vertexAttribArraysEnabled[i] = false;
  4179. this._currentBufferPointers[i].active = false;
  4180. }
  4181. }
  4182. public releaseEffects() {
  4183. for (var name in this._compiledEffects) {
  4184. this._deleteProgram(this._compiledEffects[name]._program)
  4185. }
  4186. this._compiledEffects = {};
  4187. }
  4188. // Dispose
  4189. public dispose(): void {
  4190. this.hideLoadingUI();
  4191. this.stopRenderLoop();
  4192. // Release postProcesses
  4193. while (this.postProcesses.length) {
  4194. this.postProcesses[0].dispose();
  4195. }
  4196. // Empty texture
  4197. if (this._emptyTexture) {
  4198. this._releaseTexture(this._emptyTexture);
  4199. this._emptyTexture = null;
  4200. }
  4201. if (this._emptyCubeTexture) {
  4202. this._releaseTexture(this._emptyCubeTexture);
  4203. this._emptyCubeTexture = null;
  4204. }
  4205. // Rescale PP
  4206. if (this._rescalePostProcess) {
  4207. this._rescalePostProcess.dispose();
  4208. }
  4209. // Release scenes
  4210. while (this.scenes.length) {
  4211. this.scenes[0].dispose();
  4212. }
  4213. // Release audio engine
  4214. if (Engine.audioEngine) {
  4215. Engine.audioEngine.dispose();
  4216. }
  4217. // Release effects
  4218. this.releaseEffects();
  4219. // Unbind
  4220. this.unbindAllAttributes();
  4221. if (this._dummyFramebuffer) {
  4222. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  4223. }
  4224. //WebVR
  4225. this.disableVR();
  4226. // Events
  4227. if (Tools.IsWindowObjectExist()) {
  4228. window.removeEventListener("blur", this._onBlur);
  4229. window.removeEventListener("focus", this._onFocus);
  4230. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  4231. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  4232. if (this._renderingCanvas) {
  4233. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  4234. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  4235. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  4236. if (!this._doNotHandleContextLost) {
  4237. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  4238. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  4239. }
  4240. }
  4241. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4242. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4243. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4244. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4245. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4246. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4247. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4248. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4249. if (this._onVrDisplayConnect) {
  4250. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  4251. if (this._onVrDisplayDisconnect) {
  4252. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  4253. }
  4254. if (this._onVrDisplayPresentChange) {
  4255. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  4256. }
  4257. this._onVrDisplayConnect = null;
  4258. this._onVrDisplayDisconnect = null;
  4259. }
  4260. }
  4261. // Remove from Instances
  4262. var index = Engine.Instances.indexOf(this);
  4263. if (index >= 0) {
  4264. Engine.Instances.splice(index, 1);
  4265. }
  4266. this._workingCanvas = null;
  4267. this._workingContext = null;
  4268. this._currentBufferPointers = [];
  4269. this._renderingCanvas = null;
  4270. this._currentProgram = null;
  4271. this.onResizeObservable.clear();
  4272. this.onCanvasBlurObservable.clear();
  4273. this.onCanvasFocusObservable.clear();
  4274. this.onCanvasPointerOutObservable.clear();
  4275. this.onBeginFrameObservable.clear();
  4276. this.onEndFrameObservable.clear();
  4277. Effect.ResetCache();
  4278. // Abort active requests
  4279. for (let request of this._activeRequests) {
  4280. request.abort();
  4281. }
  4282. }
  4283. // Loading screen
  4284. public displayLoadingUI(): void {
  4285. if (!Tools.IsWindowObjectExist()) {
  4286. return;
  4287. }
  4288. const loadingScreen = this.loadingScreen;
  4289. if (loadingScreen) {
  4290. loadingScreen.displayLoadingUI();
  4291. }
  4292. }
  4293. public hideLoadingUI(): void {
  4294. if (!Tools.IsWindowObjectExist()) {
  4295. return;
  4296. }
  4297. const loadingScreen = this.loadingScreen;
  4298. if (loadingScreen) {
  4299. loadingScreen.hideLoadingUI();
  4300. }
  4301. }
  4302. public get loadingScreen(): ILoadingScreen {
  4303. if (!this._loadingScreen && DefaultLoadingScreen && this._renderingCanvas)
  4304. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  4305. return this._loadingScreen;
  4306. }
  4307. public set loadingScreen(loadingScreen: ILoadingScreen) {
  4308. this._loadingScreen = loadingScreen;
  4309. }
  4310. public set loadingUIText(text: string) {
  4311. this.loadingScreen.loadingUIText = text;
  4312. }
  4313. public set loadingUIBackgroundColor(color: string) {
  4314. this.loadingScreen.loadingUIBackgroundColor = color;
  4315. }
  4316. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  4317. if (this._renderingCanvas) {
  4318. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  4319. }
  4320. }
  4321. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  4322. if (this._renderingCanvas) {
  4323. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  4324. }
  4325. }
  4326. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  4327. var shaders = this._gl.getAttachedShaders(program);
  4328. if (!shaders) {
  4329. return null;
  4330. }
  4331. return this._gl.getShaderSource(shaders[0]);
  4332. }
  4333. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  4334. var shaders = this._gl.getAttachedShaders(program);
  4335. if (!shaders) {
  4336. return null;
  4337. }
  4338. return this._gl.getShaderSource(shaders[1]);
  4339. }
  4340. public getError(): number {
  4341. return this._gl.getError();
  4342. }
  4343. // FPS
  4344. public getFps(): number {
  4345. return this._fps;
  4346. }
  4347. public getDeltaTime(): number {
  4348. return this._deltaTime;
  4349. }
  4350. private _measureFps(): void {
  4351. this._performanceMonitor.sampleFrame();
  4352. this._fps = this._performanceMonitor.averageFPS;
  4353. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  4354. }
  4355. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1): ArrayBufferView {
  4356. let gl = this._gl;
  4357. if (!this._dummyFramebuffer) {
  4358. let dummy = gl.createFramebuffer();
  4359. if (!dummy) {
  4360. throw new Error("Unable to create dummy framebuffer");
  4361. }
  4362. this._dummyFramebuffer = dummy;
  4363. }
  4364. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  4365. if (faceIndex > -1) {
  4366. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  4367. } else {
  4368. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4369. }
  4370. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  4371. let buffer: ArrayBufferView;
  4372. switch (readType) {
  4373. case gl.UNSIGNED_BYTE:
  4374. buffer = new Uint8Array(4 * width * height);
  4375. readType = gl.UNSIGNED_BYTE;
  4376. break;
  4377. default:
  4378. buffer = new Float32Array(4 * width * height);
  4379. readType = gl.FLOAT;
  4380. break;
  4381. }
  4382. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  4383. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  4384. return buffer;
  4385. }
  4386. private _canRenderToFloatFramebuffer(): boolean {
  4387. if (this._webGLVersion > 1) {
  4388. return this._caps.colorBufferFloat;
  4389. }
  4390. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  4391. }
  4392. private _canRenderToHalfFloatFramebuffer(): boolean {
  4393. if (this._webGLVersion > 1) {
  4394. return this._caps.colorBufferFloat;
  4395. }
  4396. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  4397. }
  4398. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  4399. private _canRenderToFramebuffer(type: number): boolean {
  4400. let gl = this._gl;
  4401. //clear existing errors
  4402. while (gl.getError() !== gl.NO_ERROR) { }
  4403. let successful = true;
  4404. let texture = gl.createTexture();
  4405. gl.bindTexture(gl.TEXTURE_2D, texture);
  4406. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4407. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4408. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4409. let fb = gl.createFramebuffer();
  4410. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  4411. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4412. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  4413. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  4414. successful = successful && (gl.getError() === gl.NO_ERROR);
  4415. //try render by clearing frame buffer's color buffer
  4416. if (successful) {
  4417. gl.clear(gl.COLOR_BUFFER_BIT);
  4418. successful = successful && (gl.getError() === gl.NO_ERROR);
  4419. }
  4420. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  4421. if (successful) {
  4422. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  4423. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4424. let readFormat = gl.RGBA;
  4425. let readType = gl.UNSIGNED_BYTE;
  4426. let buffer = new Uint8Array(4);
  4427. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  4428. successful = successful && (gl.getError() === gl.NO_ERROR);
  4429. }
  4430. //clean up
  4431. gl.deleteTexture(texture);
  4432. gl.deleteFramebuffer(fb);
  4433. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4434. //clear accumulated errors
  4435. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  4436. return successful;
  4437. }
  4438. public _getWebGLTextureType(type: number): number {
  4439. if (type === Engine.TEXTURETYPE_FLOAT) {
  4440. return this._gl.FLOAT;
  4441. }
  4442. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4443. // Add Half Float Constant.
  4444. return this._gl.HALF_FLOAT_OES;
  4445. }
  4446. return this._gl.UNSIGNED_BYTE;
  4447. };
  4448. public _getRGBABufferInternalSizedFormat(type: number): number {
  4449. if (this._webGLVersion === 1) {
  4450. return this._gl.RGBA;
  4451. }
  4452. if (type === Engine.TEXTURETYPE_FLOAT) {
  4453. return this._gl.RGBA32F;
  4454. }
  4455. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4456. return this._gl.RGBA16F;
  4457. }
  4458. return this._gl.RGBA;
  4459. };
  4460. public _getRGBAMultiSampleBufferFormat(type: number): number {
  4461. if (type === Engine.TEXTURETYPE_FLOAT) {
  4462. return this._gl.RGBA32F;
  4463. }
  4464. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4465. return this._gl.RGBA16F;
  4466. }
  4467. return this._gl.RGBA8;
  4468. };
  4469. public createQuery(): WebGLQuery {
  4470. return this._gl.createQuery();
  4471. }
  4472. public deleteQuery(query: WebGLQuery): Engine {
  4473. this._gl.deleteQuery(query);
  4474. return this;
  4475. }
  4476. public isQueryResultAvailable(query: WebGLQuery): boolean {
  4477. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE) as boolean;
  4478. }
  4479. public getQueryResult(query: WebGLQuery): number {
  4480. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT) as number;
  4481. }
  4482. public beginOcclusionQuery(algorithmType: number, query: WebGLQuery): Engine {
  4483. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  4484. this._gl.beginQuery(glAlgorithm, query);
  4485. return this;
  4486. }
  4487. public endOcclusionQuery(algorithmType: number): Engine {
  4488. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  4489. this._gl.endQuery(glAlgorithm);
  4490. return this;
  4491. }
  4492. /* Time queries */
  4493. private _createTimeQuery(): WebGLQuery {
  4494. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4495. if (timerQuery.createQueryEXT) {
  4496. return timerQuery.createQueryEXT();
  4497. }
  4498. return this.createQuery();
  4499. }
  4500. private _deleteTimeQuery(query: WebGLQuery): void {
  4501. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4502. if (timerQuery.deleteQueryEXT) {
  4503. timerQuery.deleteQueryEXT(query);
  4504. return;
  4505. }
  4506. this.deleteQuery(query);
  4507. }
  4508. private _getTimeQueryResult(query: WebGLQuery): any {
  4509. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4510. if (timerQuery.getQueryObjectEXT) {
  4511. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  4512. }
  4513. return this.getQueryResult(query);
  4514. }
  4515. private _getTimeQueryAvailability(query: WebGLQuery): any {
  4516. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4517. if (timerQuery.getQueryObjectEXT) {
  4518. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  4519. }
  4520. return this.isQueryResultAvailable(query);
  4521. }
  4522. private _currentNonTimestampToken: Nullable<_TimeToken>;
  4523. public startTimeQuery(): Nullable<_TimeToken> {
  4524. let timerQuery = this._caps.timerQuery;
  4525. if (!timerQuery) {
  4526. return null;
  4527. }
  4528. let token = new _TimeToken();
  4529. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  4530. if (this._caps.canUseTimestampForTimerQuery) {
  4531. token._startTimeQuery = this._createTimeQuery();
  4532. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  4533. } else {
  4534. if (this._currentNonTimestampToken) {
  4535. return this._currentNonTimestampToken;
  4536. }
  4537. token._timeElapsedQuery = this._createTimeQuery();
  4538. if (timerQuery.beginQueryEXT) {
  4539. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  4540. } else {
  4541. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  4542. }
  4543. this._currentNonTimestampToken = token;
  4544. }
  4545. return token;
  4546. }
  4547. public endTimeQuery(token: _TimeToken): int {
  4548. let timerQuery = this._caps.timerQuery;
  4549. if (!timerQuery || !token) {
  4550. return -1;
  4551. }
  4552. if (this._caps.canUseTimestampForTimerQuery) {
  4553. if (!token._startTimeQuery) {
  4554. return -1;
  4555. }
  4556. if (!token._endTimeQuery) {
  4557. token._endTimeQuery = this._createTimeQuery();
  4558. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  4559. }
  4560. } else if (!token._timeElapsedQueryEnded) {
  4561. if (!token._timeElapsedQuery) {
  4562. return -1;
  4563. }
  4564. if (timerQuery.endQueryEXT) {
  4565. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  4566. } else {
  4567. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  4568. }
  4569. token._timeElapsedQueryEnded = true;
  4570. }
  4571. let disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  4572. let available: boolean = false;
  4573. if (token._endTimeQuery) {
  4574. available = this._getTimeQueryAvailability(token._endTimeQuery);
  4575. } else if (token._timeElapsedQuery) {
  4576. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  4577. }
  4578. if (available && !disjoint) {
  4579. let result = 0;
  4580. if (this._caps.canUseTimestampForTimerQuery) {
  4581. if (!token._startTimeQuery || !token._endTimeQuery) {
  4582. return -1;
  4583. }
  4584. let timeStart = this._getTimeQueryResult(token._startTimeQuery);
  4585. let timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  4586. result = timeEnd - timeStart;
  4587. this._deleteTimeQuery(token._startTimeQuery);
  4588. this._deleteTimeQuery(token._endTimeQuery);
  4589. token._startTimeQuery = null;
  4590. token._endTimeQuery = null;
  4591. } else {
  4592. if (!token._timeElapsedQuery) {
  4593. return -1;
  4594. }
  4595. result = this._getTimeQueryResult(token._timeElapsedQuery);
  4596. this._deleteTimeQuery(token._timeElapsedQuery);
  4597. token._timeElapsedQuery = null;
  4598. token._timeElapsedQueryEnded = false;
  4599. this._currentNonTimestampToken = null;
  4600. }
  4601. return result;
  4602. }
  4603. return -1;
  4604. }
  4605. private getGlAlgorithmType(algorithmType: number): number {
  4606. return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  4607. }
  4608. // Transform feedback
  4609. public createTransformFeedback(): WebGLTransformFeedback {
  4610. return this._gl.createTransformFeedback();
  4611. }
  4612. public deleteTransformFeedback(value: WebGLTransformFeedback): void {
  4613. this._gl.deleteTransformFeedback(value);
  4614. }
  4615. public bindTransformFeedback(value: Nullable<WebGLTransformFeedback>): void {
  4616. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  4617. }
  4618. public beginTransformFeedback(usePoints: boolean = true): void {
  4619. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  4620. }
  4621. public endTransformFeedback(): void {
  4622. this._gl.endTransformFeedback();
  4623. }
  4624. public setTranformFeedbackVaryings(program: WebGLProgram, value: string[]): void {
  4625. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  4626. }
  4627. public bindTransformFeedbackBuffer(value: Nullable<WebGLBuffer>): void {
  4628. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  4629. }
  4630. 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 {
  4631. let request = Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  4632. this._activeRequests.push(request);
  4633. request.onCompleteObservable.add(request => {
  4634. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4635. });
  4636. return request;
  4637. }
  4638. 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 {
  4639. var onload = (data: string | ArrayBuffer) => {
  4640. loadedFiles[index] = data;
  4641. (<any>loadedFiles)._internalCount++;
  4642. if ((<any>loadedFiles)._internalCount === 6) {
  4643. onfinish(loadedFiles);
  4644. }
  4645. };
  4646. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  4647. if (onErrorCallBack && request) {
  4648. onErrorCallBack(request.status + " " + request.statusText, exception);
  4649. }
  4650. };
  4651. this._loadFile(url, onload, undefined, undefined, true, onerror);
  4652. }
  4653. private _cascadeLoadFiles(rootUrl: string, scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  4654. var loadedFiles: (string | ArrayBuffer)[] = [];
  4655. (<any>loadedFiles)._internalCount = 0;
  4656. for (let index = 0; index < 6; index++) {
  4657. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  4658. }
  4659. }
  4660. // Statics
  4661. public static isSupported(): boolean {
  4662. try {
  4663. var tempcanvas = document.createElement("canvas");
  4664. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4665. return gl != null && !!window.WebGLRenderingContext;
  4666. } catch (e) {
  4667. return false;
  4668. }
  4669. }
  4670. }
  4671. }