babylon.engine.ts 196 KB

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