babylon.engine.ts 221 KB

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