babylon.engine.ts 248 KB

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