babylon.engine.ts 244 KB

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