babylon.engine.ts 183 KB

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