babylon.engine.ts 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string): WebGLShader => {
  3. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4. gl.shaderSource(shader, (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 HALF_FLOAT_OES = 0x8D61;
  12. var getWebGLTextureType = (gl: WebGLRenderingContext, type: number): number => {
  13. if (type === Engine.TEXTURETYPE_FLOAT) {
  14. return gl.FLOAT;
  15. }
  16. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17. // Add Half Float Constant.
  18. return HALF_FLOAT_OES;
  19. }
  20. return gl.UNSIGNED_BYTE;
  21. };
  22. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  23. var magFilter = gl.NEAREST;
  24. var minFilter = gl.NEAREST;
  25. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  26. magFilter = gl.LINEAR;
  27. if (generateMipMaps) {
  28. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  29. } else {
  30. minFilter = gl.LINEAR;
  31. }
  32. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  33. magFilter = gl.LINEAR;
  34. if (generateMipMaps) {
  35. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  36. } else {
  37. minFilter = gl.LINEAR;
  38. }
  39. } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  40. magFilter = gl.NEAREST;
  41. if (generateMipMaps) {
  42. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  43. } else {
  44. minFilter = gl.NEAREST;
  45. }
  46. }
  47. return {
  48. min: minFilter,
  49. mag: magFilter
  50. }
  51. }
  52. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  53. processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  54. var engine = scene.getEngine();
  55. var potWidth = Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  56. var potHeight = Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  57. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  58. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  59. texture._baseWidth = width;
  60. texture._baseHeight = height;
  61. texture._width = potWidth;
  62. texture._height = potHeight;
  63. texture.isReady = true;
  64. processFunction(potWidth, potHeight);
  65. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  66. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  67. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  68. if (!noMipmap && !isCompressed) {
  69. gl.generateMipmap(gl.TEXTURE_2D);
  70. }
  71. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  72. engine.resetTextureCache();
  73. scene._removePendingData(texture);
  74. texture.onLoadedCallbacks.forEach(callback => {
  75. callback();
  76. });
  77. texture.onLoadedCallbacks = [];
  78. };
  79. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  80. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: () => void = null) => {
  81. var img: HTMLImageElement;
  82. var onload = () => {
  83. loadedImages[index] = img;
  84. loadedImages._internalCount++;
  85. scene._removePendingData(img);
  86. if (loadedImages._internalCount === 6) {
  87. onfinish(loadedImages);
  88. }
  89. };
  90. var onerror = () => {
  91. scene._removePendingData(img);
  92. if (onErrorCallBack) {
  93. onErrorCallBack();
  94. }
  95. };
  96. img = Tools.LoadImage(url, onload, onerror, scene.database);
  97. scene._addPendingData(img);
  98. }
  99. var cascadeLoad = (rootUrl: string, scene,
  100. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: () => void = null) => {
  101. var loadedImages: any = [];
  102. loadedImages._internalCount = 0;
  103. for (var index = 0; index < 6; index++) {
  104. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  105. }
  106. };
  107. export class InstancingAttributeInfo {
  108. /**
  109. * Index/offset of the attribute in the vertex shader
  110. */
  111. index: number;
  112. /**
  113. * size of the attribute, 1, 2, 3 or 4
  114. */
  115. attributeSize: number;
  116. /**
  117. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  118. * default is FLOAT
  119. */
  120. attribyteType: number;
  121. /**
  122. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  123. */
  124. normalized: boolean;
  125. /**
  126. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  127. */
  128. offset: number;
  129. /**
  130. * Name of the GLSL attribute, for debugging purpose only
  131. */
  132. attributeName: string;
  133. }
  134. export class EngineCapabilities {
  135. public maxTexturesImageUnits: number;
  136. public maxTextureSize: number;
  137. public maxCubemapTextureSize: number;
  138. public maxRenderTextureSize: number;
  139. public maxVertexAttribs: number;
  140. public standardDerivatives: boolean;
  141. public s3tc: WEBGL_compressed_texture_s3tc;
  142. public textureFloat: boolean;
  143. public textureAnisotropicFilterExtension: EXT_texture_filter_anisotropic;
  144. public maxAnisotropy: number;
  145. public instancedArrays: ANGLE_instanced_arrays;
  146. public uintIndices: boolean;
  147. public highPrecisionShaderSupported: boolean;
  148. public fragmentDepthSupported: boolean;
  149. public textureFloatLinearFiltering: boolean;
  150. public textureFloatRender: boolean;
  151. public textureHalfFloat: boolean;
  152. public textureHalfFloatLinearFiltering: boolean;
  153. public textureHalfFloatRender: boolean;
  154. public textureLOD: boolean;
  155. public drawBuffersExtension;
  156. }
  157. export interface EngineOptions extends WebGLContextAttributes {
  158. limitDeviceRatio?: number;
  159. autoEnableWebVR?: boolean;
  160. }
  161. /**
  162. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  163. */
  164. export class Engine {
  165. // Const statics
  166. private static _ALPHA_DISABLE = 0;
  167. private static _ALPHA_ADD = 1;
  168. private static _ALPHA_COMBINE = 2;
  169. private static _ALPHA_SUBTRACT = 3;
  170. private static _ALPHA_MULTIPLY = 4;
  171. private static _ALPHA_MAXIMIZED = 5;
  172. private static _ALPHA_ONEONE = 6;
  173. private static _DELAYLOADSTATE_NONE = 0;
  174. private static _DELAYLOADSTATE_LOADED = 1;
  175. private static _DELAYLOADSTATE_LOADING = 2;
  176. private static _DELAYLOADSTATE_NOTLOADED = 4;
  177. private static _TEXTUREFORMAT_ALPHA = 0;
  178. private static _TEXTUREFORMAT_LUMINANCE = 1;
  179. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  180. private static _TEXTUREFORMAT_RGB = 4;
  181. private static _TEXTUREFORMAT_RGBA = 5;
  182. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  183. private static _TEXTURETYPE_FLOAT = 1;
  184. private static _TEXTURETYPE_HALF_FLOAT = 2;
  185. // Depht or Stencil test Constants.
  186. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  187. 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.
  188. 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.
  189. 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.
  190. 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.
  191. 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.
  192. 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.
  193. 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.
  194. public static get NEVER(): number {
  195. return Engine._NEVER;
  196. }
  197. public static get ALWAYS(): number {
  198. return Engine._ALWAYS;
  199. }
  200. public static get LESS(): number {
  201. return Engine._LESS;
  202. }
  203. public static get EQUAL(): number {
  204. return Engine._EQUAL;
  205. }
  206. public static get LEQUAL(): number {
  207. return Engine._LEQUAL;
  208. }
  209. public static get GREATER(): number {
  210. return Engine._GREATER;
  211. }
  212. public static get GEQUAL(): number {
  213. return Engine._GEQUAL;
  214. }
  215. public static get NOTEQUAL(): number {
  216. return Engine._NOTEQUAL;
  217. }
  218. // Stencil Actions Constants.
  219. private static _KEEP = 0x1E00;
  220. private static _REPLACE = 0x1E01;
  221. private static _INCR = 0x1E02;
  222. private static _DECR = 0x1E03;
  223. private static _INVERT = 0x150A;
  224. private static _INCR_WRAP = 0x8507;
  225. private static _DECR_WRAP = 0x8508;
  226. public static get KEEP(): number {
  227. return Engine._KEEP;
  228. }
  229. public static get REPLACE(): number {
  230. return Engine._REPLACE;
  231. }
  232. public static get INCR(): number {
  233. return Engine._INCR;
  234. }
  235. public static get DECR(): number {
  236. return Engine._DECR;
  237. }
  238. public static get INVERT(): number {
  239. return Engine._INVERT;
  240. }
  241. public static get INCR_WRAP(): number {
  242. return Engine._INCR_WRAP;
  243. }
  244. public static get DECR_WRAP(): number {
  245. return Engine._DECR_WRAP;
  246. }
  247. public static get ALPHA_DISABLE(): number {
  248. return Engine._ALPHA_DISABLE;
  249. }
  250. public static get ALPHA_ONEONE(): number {
  251. return Engine._ALPHA_ONEONE;
  252. }
  253. public static get ALPHA_ADD(): number {
  254. return Engine._ALPHA_ADD;
  255. }
  256. public static get ALPHA_COMBINE(): number {
  257. return Engine._ALPHA_COMBINE;
  258. }
  259. public static get ALPHA_SUBTRACT(): number {
  260. return Engine._ALPHA_SUBTRACT;
  261. }
  262. public static get ALPHA_MULTIPLY(): number {
  263. return Engine._ALPHA_MULTIPLY;
  264. }
  265. public static get ALPHA_MAXIMIZED(): number {
  266. return Engine._ALPHA_MAXIMIZED;
  267. }
  268. public static get DELAYLOADSTATE_NONE(): number {
  269. return Engine._DELAYLOADSTATE_NONE;
  270. }
  271. public static get DELAYLOADSTATE_LOADED(): number {
  272. return Engine._DELAYLOADSTATE_LOADED;
  273. }
  274. public static get DELAYLOADSTATE_LOADING(): number {
  275. return Engine._DELAYLOADSTATE_LOADING;
  276. }
  277. public static get DELAYLOADSTATE_NOTLOADED(): number {
  278. return Engine._DELAYLOADSTATE_NOTLOADED;
  279. }
  280. public static get TEXTUREFORMAT_ALPHA(): number {
  281. return Engine._TEXTUREFORMAT_ALPHA;
  282. }
  283. public static get TEXTUREFORMAT_LUMINANCE(): number {
  284. return Engine._TEXTUREFORMAT_LUMINANCE;
  285. }
  286. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  287. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  288. }
  289. public static get TEXTUREFORMAT_RGB(): number {
  290. return Engine._TEXTUREFORMAT_RGB;
  291. }
  292. public static get TEXTUREFORMAT_RGBA(): number {
  293. return Engine._TEXTUREFORMAT_RGBA;
  294. }
  295. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  296. return Engine._TEXTURETYPE_UNSIGNED_INT;
  297. }
  298. public static get TEXTURETYPE_FLOAT(): number {
  299. return Engine._TEXTURETYPE_FLOAT;
  300. }
  301. public static get TEXTURETYPE_HALF_FLOAT(): number {
  302. return Engine._TEXTURETYPE_HALF_FLOAT;
  303. }
  304. public static get Version(): string {
  305. return "2.5.-beta";
  306. }
  307. // Updatable statics so stick with vars here
  308. public static CollisionsEpsilon = 0.001;
  309. public static CodeRepository = "src/";
  310. public static ShadersRepository = "src/Shaders/";
  311. // Public members
  312. public isFullscreen = false;
  313. public isPointerLock = false;
  314. public cullBackFaces = true;
  315. public renderEvenInBackground = true;
  316. // To enable/disable IDB support and avoid XHR on .manifest
  317. public enableOfflineSupport = true;
  318. public scenes = new Array<Scene>();
  319. //WebVR
  320. //The new WebVR uses promises.
  321. //this promise resolves with the current devices available.
  322. public vrDisplaysPromise;
  323. private _vrDisplays;
  324. private _vrDisplayEnabled;
  325. private _oldSize: BABYLON.Size;
  326. private _oldHardwareScaleFactor: number;
  327. private _vrAnimationFrameHandler: number;
  328. // Private Members
  329. public _gl: WebGLRenderingContext;
  330. private _renderingCanvas: HTMLCanvasElement;
  331. private _windowIsBackground = false;
  332. private _webGLVersion = "1.0";
  333. private _badOS = false;
  334. public static audioEngine: AudioEngine;
  335. private _onBlur: () => void;
  336. private _onFocus: () => void;
  337. private _onFullscreenChange: () => void;
  338. private _onPointerLockChange: () => void;
  339. private _hardwareScalingLevel: number;
  340. private _caps: EngineCapabilities;
  341. private _pointerLockRequested: boolean;
  342. private _alphaTest: boolean;
  343. private _isStencilEnable: boolean;
  344. private _loadingScreen: ILoadingScreen;
  345. public _drawCalls = new PerfCounter();
  346. private _glVersion: string;
  347. private _glRenderer: string;
  348. private _glVendor: string;
  349. private _videoTextureSupported: boolean;
  350. private _renderingQueueLaunched = false;
  351. private _activeRenderLoops = [];
  352. // FPS
  353. private fpsRange = 60;
  354. private previousFramesDuration = [];
  355. private fps = 60;
  356. private deltaTime = 0;
  357. // States
  358. private _depthCullingState = new Internals._DepthCullingState();
  359. private _stencilState = new Internals._StencilState();
  360. private _alphaState = new Internals._AlphaState();
  361. private _alphaMode = Engine.ALPHA_DISABLE;
  362. // Cache
  363. private _loadedTexturesCache = new Array<WebGLTexture>();
  364. private _maxTextureChannels = 16;
  365. private _activeTexture: number;
  366. private _activeTexturesCache = new Array<WebGLTexture>(this._maxTextureChannels);
  367. private _currentEffect: Effect;
  368. private _currentProgram: WebGLProgram;
  369. private _compiledEffects = {};
  370. private _vertexAttribArraysEnabled: boolean[] = [];
  371. private _cachedViewport: Viewport;
  372. private _cachedVertexBuffers: any;
  373. private _cachedIndexBuffer: WebGLBuffer;
  374. private _cachedEffectForVertexBuffers: Effect;
  375. private _currentRenderTarget: WebGLTexture;
  376. private _uintIndicesCurrentlySet = false;
  377. private _currentBoundBuffer = new Array<WebGLBuffer>();
  378. private _currentFramebuffer: WebGLFramebuffer;
  379. private _currentBufferPointers: Array<{ indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number, buffer: WebGLBuffer }> = [];
  380. private _currentInstanceLocations = new Array<number>();
  381. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  382. private _textureUnits: Int32Array;
  383. private _workingCanvas: HTMLCanvasElement;
  384. private _workingContext: CanvasRenderingContext2D;
  385. private _externalData: StringDictionary<Object>;
  386. private _bindedRenderFunction: any;
  387. /**
  388. * @constructor
  389. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  390. * @param {boolean} [antialias] - enable antialias
  391. * @param options - further options to be sent to the getContext function
  392. */
  393. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = true) {
  394. this._renderingCanvas = canvas;
  395. this._externalData = new StringDictionary<Object>();
  396. options = options || {};
  397. if (antialias != null) {
  398. options.antialias = antialias;
  399. }
  400. if (options.preserveDrawingBuffer === undefined) {
  401. options.preserveDrawingBuffer = false;
  402. }
  403. // Checks if some of the format renders first to allow the use of webgl inspector.
  404. var renderToFullFloat = this._canRenderToFloatTexture();
  405. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  406. // GL
  407. //try {
  408. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  409. // if (this._gl) {
  410. // this._webGLVersion = "2.0";
  411. // }
  412. //} catch (e) {
  413. // // Do nothing
  414. //}
  415. if (!this._gl) {
  416. if (!canvas) {
  417. throw new Error("The provided canvas is null or undefined.");
  418. }
  419. try {
  420. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  421. } catch (e) {
  422. throw new Error("WebGL not supported");
  423. }
  424. }
  425. if (!this._gl) {
  426. throw new Error("WebGL not supported");
  427. }
  428. this._onBlur = () => {
  429. this._windowIsBackground = true;
  430. };
  431. this._onFocus = () => {
  432. this._windowIsBackground = false;
  433. };
  434. window.addEventListener("blur", this._onBlur);
  435. window.addEventListener("focus", this._onFocus);
  436. // Viewport
  437. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  438. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  439. this.resize();
  440. // Caps
  441. this._isStencilEnable = options.stencil;
  442. this._caps = new EngineCapabilities();
  443. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  444. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  445. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  446. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  447. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  448. // Infos
  449. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  450. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  451. if (rendererInfo != null) {
  452. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  453. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  454. }
  455. if (!this._glVendor) {
  456. this._glVendor = "Unknown vendor";
  457. }
  458. if (!this._glRenderer) {
  459. this._glRenderer = "Unknown renderer";
  460. }
  461. // Extensions
  462. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  463. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  464. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  465. 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');
  466. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  467. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  468. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  469. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  470. this._caps.highPrecisionShaderSupported = true;
  471. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  472. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  473. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  474. this._caps.textureFloatRender = renderToFullFloat;
  475. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  476. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  477. this._caps.textureHalfFloatRender = renderToHalfFloat;
  478. if (this._gl.getShaderPrecisionFormat) {
  479. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  480. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  481. }
  482. // Depth buffer
  483. this.setDepthBuffer(true);
  484. this.setDepthFunctionToLessOrEqual();
  485. this.setDepthWrite(true);
  486. // Fullscreen
  487. this._onFullscreenChange = () => {
  488. if (document.fullscreen !== undefined) {
  489. this.isFullscreen = document.fullscreen;
  490. } else if (document.mozFullScreen !== undefined) {
  491. this.isFullscreen = document.mozFullScreen;
  492. } else if (document.webkitIsFullScreen !== undefined) {
  493. this.isFullscreen = document.webkitIsFullScreen;
  494. } else if (document.msIsFullScreen !== undefined) {
  495. this.isFullscreen = document.msIsFullScreen;
  496. }
  497. // Pointer lock
  498. if (this.isFullscreen && this._pointerLockRequested) {
  499. canvas.requestPointerLock = canvas.requestPointerLock ||
  500. canvas.msRequestPointerLock ||
  501. canvas.mozRequestPointerLock ||
  502. canvas.webkitRequestPointerLock;
  503. if (canvas.requestPointerLock) {
  504. canvas.requestPointerLock();
  505. }
  506. }
  507. };
  508. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  509. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  510. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  511. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  512. // Pointer lock
  513. this._onPointerLockChange = () => {
  514. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  515. document.webkitPointerLockElement === canvas ||
  516. document.msPointerLockElement === canvas ||
  517. document.pointerLockElement === canvas
  518. );
  519. };
  520. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  521. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  522. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  523. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  524. if (AudioEngine && !Engine.audioEngine) {
  525. Engine.audioEngine = new AudioEngine();
  526. }
  527. //default loading screen
  528. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas);
  529. //Load WebVR Devices
  530. if (options.autoEnableWebVR) {
  531. this.initWebVR();
  532. }
  533. //Detect if we are running on a faulty buggy OS.
  534. var regexp = /AppleWebKit.*10.[\d] Mobile/
  535. //ua sniffing is the tool of the devil.
  536. this._badOS = regexp.test(navigator.userAgent);
  537. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  538. }
  539. public get webGLVersion(): string {
  540. return this._webGLVersion;
  541. }
  542. /**
  543. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  544. */
  545. public get isStencilEnable(): boolean {
  546. return this._isStencilEnable;
  547. }
  548. private _prepareWorkingCanvas(): void {
  549. if (this._workingCanvas) {
  550. return;
  551. }
  552. this._workingCanvas = document.createElement("canvas");
  553. this._workingContext = this._workingCanvas.getContext("2d");
  554. }
  555. public resetTextureCache() {
  556. for (var index = 0; index < this._maxTextureChannels; index++) {
  557. this._activeTexturesCache[index] = null;
  558. }
  559. }
  560. public getGlInfo() {
  561. return {
  562. vendor: this._glVendor,
  563. renderer: this._glRenderer,
  564. version: this._glVersion
  565. }
  566. }
  567. public getAspectRatio(camera: Camera, useScreen = false): number {
  568. var viewport = camera.viewport;
  569. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  570. }
  571. public getRenderWidth(useScreen = false): number {
  572. if (!useScreen && this._currentRenderTarget) {
  573. return this._currentRenderTarget._width;
  574. }
  575. return this._renderingCanvas.width;
  576. }
  577. public getRenderHeight(useScreen = false): number {
  578. if (!useScreen && this._currentRenderTarget) {
  579. return this._currentRenderTarget._height;
  580. }
  581. return this._renderingCanvas.height;
  582. }
  583. public getRenderingCanvas(): HTMLCanvasElement {
  584. return this._renderingCanvas;
  585. }
  586. public getRenderingCanvasClientRect(): ClientRect {
  587. return this._renderingCanvas.getBoundingClientRect();
  588. }
  589. public setHardwareScalingLevel(level: number): void {
  590. this._hardwareScalingLevel = level;
  591. this.resize();
  592. }
  593. public getHardwareScalingLevel(): number {
  594. return this._hardwareScalingLevel;
  595. }
  596. public getLoadedTexturesCache(): WebGLTexture[] {
  597. return this._loadedTexturesCache;
  598. }
  599. public getCaps(): EngineCapabilities {
  600. return this._caps;
  601. }
  602. public get drawCalls(): number {
  603. return this._drawCalls.current;
  604. }
  605. public get drawCallsPerfCounter(): PerfCounter {
  606. return this._drawCalls;
  607. }
  608. public getDepthFunction(): number {
  609. return this._depthCullingState.depthFunc;
  610. }
  611. public setDepthFunction(depthFunc: number) {
  612. this._depthCullingState.depthFunc = depthFunc;
  613. }
  614. public setDepthFunctionToGreater(): void {
  615. this._depthCullingState.depthFunc = this._gl.GREATER;
  616. }
  617. public setDepthFunctionToGreaterOrEqual(): void {
  618. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  619. }
  620. public setDepthFunctionToLess(): void {
  621. this._depthCullingState.depthFunc = this._gl.LESS;
  622. }
  623. public setDepthFunctionToLessOrEqual(): void {
  624. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  625. }
  626. public getStencilBuffer(): boolean {
  627. return this._stencilState.stencilTest;
  628. }
  629. public setStencilBuffer(enable: boolean): void {
  630. this._stencilState.stencilTest = enable;
  631. }
  632. public getStencilMask(): number {
  633. return this._stencilState.stencilMask;
  634. }
  635. public setStencilMask(mask: number): void {
  636. this._stencilState.stencilMask = mask;
  637. }
  638. public getStencilFunction(): number {
  639. return this._stencilState.stencilFunc;
  640. }
  641. public getStencilFunctionReference(): number {
  642. return this._stencilState.stencilFuncRef;
  643. }
  644. public getStencilFunctionMask(): number {
  645. return this._stencilState.stencilFuncMask;
  646. }
  647. public setStencilFunction(stencilFunc: number) {
  648. this._stencilState.stencilFunc = stencilFunc;
  649. }
  650. public setStencilFunctionReference(reference: number) {
  651. this._stencilState.stencilFuncRef = reference;
  652. }
  653. public setStencilFunctionMask(mask: number) {
  654. this._stencilState.stencilFuncMask = mask;
  655. }
  656. public getStencilOperationFail(): number {
  657. return this._stencilState.stencilOpStencilFail;
  658. }
  659. public getStencilOperationDepthFail(): number {
  660. return this._stencilState.stencilOpDepthFail;
  661. }
  662. public getStencilOperationPass(): number {
  663. return this._stencilState.stencilOpStencilDepthPass;
  664. }
  665. public setStencilOperationFail(operation: number): void {
  666. this._stencilState.stencilOpStencilFail = operation;
  667. }
  668. public setStencilOperationDepthFail(operation: number): void {
  669. this._stencilState.stencilOpDepthFail = operation;
  670. }
  671. public setStencilOperationPass(operation: number): void {
  672. this._stencilState.stencilOpStencilDepthPass = operation;
  673. }
  674. /**
  675. * stop executing a render loop function and remove it from the execution array
  676. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  677. */
  678. public stopRenderLoop(renderFunction?: () => void): void {
  679. if (!renderFunction) {
  680. this._activeRenderLoops = [];
  681. return;
  682. }
  683. var index = this._activeRenderLoops.indexOf(renderFunction);
  684. if (index >= 0) {
  685. this._activeRenderLoops.splice(index, 1);
  686. }
  687. }
  688. public _renderLoop(): void {
  689. var shouldRender = true;
  690. if (!this.renderEvenInBackground && this._windowIsBackground) {
  691. shouldRender = false;
  692. }
  693. if (shouldRender) {
  694. // Start new frame
  695. this.beginFrame();
  696. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  697. var renderFunction = this._activeRenderLoops[index];
  698. renderFunction();
  699. }
  700. // Present
  701. this.endFrame();
  702. }
  703. if (this._activeRenderLoops.length > 0) {
  704. // Register new frame
  705. Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  706. } else {
  707. this._renderingQueueLaunched = false;
  708. }
  709. }
  710. /**
  711. * Register and execute a render loop. The engine can have more than one render function.
  712. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  713. * @example
  714. * engine.runRenderLoop(function () {
  715. * scene.render()
  716. * })
  717. */
  718. public runRenderLoop(renderFunction: () => void): void {
  719. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  720. return;
  721. }
  722. this._activeRenderLoops.push(renderFunction);
  723. if (!this._renderingQueueLaunched) {
  724. this._renderingQueueLaunched = true;
  725. this._bindedRenderFunction = this._renderLoop.bind(this);
  726. Tools.QueueNewFrame(this._bindedRenderFunction);
  727. }
  728. }
  729. /**
  730. * Toggle full screen mode.
  731. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  732. * @param {any} options - an options object to be sent to the requestFullscreen function
  733. */
  734. public switchFullscreen(requestPointerLock: boolean): void {
  735. if (this.isFullscreen) {
  736. Tools.ExitFullscreen();
  737. } else {
  738. this._pointerLockRequested = requestPointerLock;
  739. Tools.RequestFullscreen(this._renderingCanvas);
  740. }
  741. }
  742. public clear(color: any, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  743. this.applyStates();
  744. var mode = 0;
  745. if (backBuffer) {
  746. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  747. mode |= this._gl.COLOR_BUFFER_BIT;
  748. }
  749. if (depth) {
  750. this._gl.clearDepth(1.0);
  751. mode |= this._gl.DEPTH_BUFFER_BIT;
  752. }
  753. if (stencil) {
  754. this._gl.clearStencil(0);
  755. mode |= this._gl.STENCIL_BUFFER_BIT;
  756. }
  757. this._gl.clear(mode);
  758. }
  759. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  760. let gl = this._gl;
  761. // Save state
  762. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  763. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  764. // Change state
  765. gl.enable(gl.SCISSOR_TEST);
  766. gl.scissor(x, y, width, height);
  767. // Clear
  768. this.clear(clearColor, true, true, true);
  769. // Restore state
  770. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  771. if (curScissor === true) {
  772. gl.enable(gl.SCISSOR_TEST);
  773. } else {
  774. gl.disable(gl.SCISSOR_TEST);
  775. }
  776. }
  777. /**
  778. * Set the WebGL's viewport
  779. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  780. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  781. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  782. */
  783. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  784. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  785. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  786. var x = viewport.x || 0;
  787. var y = viewport.y || 0;
  788. this._cachedViewport = viewport;
  789. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  790. }
  791. /**
  792. * Directly set the WebGL Viewport
  793. * The x, y, width & height are directly passed to the WebGL call
  794. * @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.
  795. */
  796. public setDirectViewport(x: number, y: number, width: number, height: number): Viewport {
  797. let currentViewport = this._cachedViewport;
  798. this._cachedViewport = null;
  799. this._gl.viewport(x, y, width, height);
  800. return currentViewport;
  801. }
  802. public beginFrame(): void {
  803. this._measureFps();
  804. }
  805. public endFrame(): void {
  806. //force a flush in case we are using a bad OS.
  807. if (this._badOS) {
  808. this.flushFramebuffer();
  809. }
  810. //submit frame to the vr device, if enabled
  811. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  812. this._vrDisplayEnabled.submitFrame()
  813. }
  814. }
  815. /**
  816. * resize the view according to the canvas' size.
  817. * @example
  818. * window.addEventListener("resize", function () {
  819. * engine.resize();
  820. * });
  821. */
  822. public resize(): void {
  823. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  824. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  825. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  826. }
  827. /**
  828. * force a specific size of the canvas
  829. * @param {number} width - the new canvas' width
  830. * @param {number} height - the new canvas' height
  831. */
  832. public setSize(width: number, height: number): void {
  833. this._renderingCanvas.width = width;
  834. this._renderingCanvas.height = height;
  835. for (var index = 0; index < this.scenes.length; index++) {
  836. var scene = this.scenes[index];
  837. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  838. var cam = scene.cameras[camIndex];
  839. cam._currentRenderId = 0;
  840. }
  841. }
  842. }
  843. //WebVR functions
  844. public initWebVR() {
  845. if (!this.vrDisplaysPromise) {
  846. this._getVRDisplays();
  847. }
  848. }
  849. public enableVR(vrDevice) {
  850. this._vrDisplayEnabled = vrDevice;
  851. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  852. }
  853. public disableVR() {
  854. if (this._vrDisplayEnabled) {
  855. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  856. }
  857. }
  858. private _onVRFullScreenTriggered = () => {
  859. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  860. //get the old size before we change
  861. this._oldSize = new BABYLON.Size(this.getRenderWidth(), this.getRenderHeight());
  862. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  863. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  864. //But actually, no browser follow the specs...
  865. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  866. //get the width and height, change the render size
  867. var leftEye = this._vrDisplayEnabled.getEyeParameters('left');
  868. var width, height;
  869. this.setHardwareScalingLevel(1);
  870. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  871. } else {
  872. //When the specs are implemented, need to uncomment this.
  873. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  874. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  875. this.setSize(this._oldSize.width, this._oldSize.height);
  876. this._vrDisplayEnabled = undefined;
  877. }
  878. }
  879. private _getVRDisplays() {
  880. var getWebVRDevices = (devices: Array<any>) => {
  881. var size = devices.length;
  882. var i = 0;
  883. this._vrDisplays = devices.filter(function (device) {
  884. return devices[i] instanceof VRDisplay;
  885. });
  886. return this._vrDisplays;
  887. }
  888. //using a key due to typescript
  889. if (navigator.getVRDisplays) {
  890. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  891. }
  892. }
  893. public bindFramebuffer(texture: WebGLTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number): void {
  894. this._currentRenderTarget = texture;
  895. this.bindUnboundFramebuffer(texture._framebuffer);
  896. var gl = this._gl;
  897. if (texture.isCube) {
  898. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  899. }
  900. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  901. this.wipeCaches();
  902. }
  903. private bindUnboundFramebuffer(framebuffer: WebGLFramebuffer) {
  904. if (this._currentFramebuffer !== framebuffer) {
  905. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  906. this._currentFramebuffer = framebuffer;
  907. }
  908. }
  909. public unBindFramebuffer(texture: WebGLTexture, disableGenerateMipMaps = false): void {
  910. this._currentRenderTarget = null;
  911. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  912. var gl = this._gl;
  913. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  914. gl.generateMipmap(gl.TEXTURE_2D);
  915. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  916. }
  917. this.bindUnboundFramebuffer(null);
  918. }
  919. public generateMipMapsForCubemap(texture: WebGLTexture) {
  920. if (texture.generateMipMaps) {
  921. var gl = this._gl;
  922. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  923. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  924. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  925. }
  926. }
  927. public flushFramebuffer(): void {
  928. this._gl.flush();
  929. }
  930. public restoreDefaultFramebuffer(): void {
  931. this._currentRenderTarget = null;
  932. this.bindUnboundFramebuffer(null);
  933. this.setViewport(this._cachedViewport);
  934. this.wipeCaches();
  935. }
  936. // VBOs
  937. private _resetVertexBufferBinding(): void {
  938. this.bindArrayBuffer(null);
  939. this._cachedVertexBuffers = null;
  940. }
  941. public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  942. var vbo = this._gl.createBuffer();
  943. this.bindArrayBuffer(vbo);
  944. if (vertices instanceof Float32Array) {
  945. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  946. } else {
  947. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  948. }
  949. this._resetVertexBufferBinding();
  950. vbo.references = 1;
  951. return vbo;
  952. }
  953. public createDynamicVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  954. var vbo = this._gl.createBuffer();
  955. this.bindArrayBuffer(vbo);
  956. if (vertices instanceof Float32Array) {
  957. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  958. } else {
  959. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  960. }
  961. this._resetVertexBufferBinding();
  962. vbo.references = 1;
  963. return vbo;
  964. }
  965. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number, count?: number): void {
  966. this.bindArrayBuffer(vertexBuffer);
  967. if (offset === undefined) {
  968. offset = 0;
  969. }
  970. if (count === undefined) {
  971. if (vertices instanceof Float32Array) {
  972. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  973. } else {
  974. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  975. }
  976. } else {
  977. if (vertices instanceof Float32Array) {
  978. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  979. } else {
  980. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  981. }
  982. }
  983. this._resetVertexBufferBinding();
  984. }
  985. private _resetIndexBufferBinding(): void {
  986. this.bindIndexBuffer(null);
  987. this._cachedIndexBuffer = null;
  988. }
  989. public createIndexBuffer(indices: number[] | Int32Array): WebGLBuffer {
  990. var vbo = this._gl.createBuffer();
  991. this.bindIndexBuffer(vbo);
  992. // Check for 32 bits indices
  993. var arrayBuffer;
  994. var need32Bits = false;
  995. if (this._caps.uintIndices) {
  996. for (var index = 0; index < indices.length; index++) {
  997. if (indices[index] > 65535) {
  998. need32Bits = true;
  999. break;
  1000. }
  1001. }
  1002. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1003. } else {
  1004. arrayBuffer = new Uint16Array(indices);
  1005. }
  1006. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  1007. this._resetIndexBufferBinding();
  1008. vbo.references = 1;
  1009. vbo.is32Bits = need32Bits;
  1010. return vbo;
  1011. }
  1012. public bindArrayBuffer(buffer: WebGLBuffer): void {
  1013. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1014. }
  1015. private bindIndexBuffer(buffer: WebGLBuffer): void {
  1016. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1017. }
  1018. private bindBuffer(buffer: WebGLBuffer, target: number): void {
  1019. if (this._currentBoundBuffer[target] !== buffer) {
  1020. this._gl.bindBuffer(target, buffer);
  1021. this._currentBoundBuffer[target] = buffer;
  1022. }
  1023. }
  1024. public updateArrayBuffer(data: Float32Array): void {
  1025. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1026. }
  1027. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1028. var pointer = this._currentBufferPointers[indx];
  1029. var changed = false;
  1030. if (!pointer) {
  1031. changed = true;
  1032. this._currentBufferPointers[indx] = { indx, size, type, normalized, stride, offset, buffer: buffer };
  1033. } else {
  1034. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1035. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1036. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1037. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1038. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1039. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1040. }
  1041. if (changed) {
  1042. this.bindArrayBuffer(buffer);
  1043. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1044. }
  1045. }
  1046. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1047. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1048. this._cachedVertexBuffers = vertexBuffer;
  1049. this._cachedEffectForVertexBuffers = effect;
  1050. let attributesCount = effect.getAttributesCount();
  1051. var offset = 0;
  1052. for (var index = 0; index < attributesCount; index++) {
  1053. if (index < vertexDeclaration.length) {
  1054. var order = effect.getAttributeLocation(index);
  1055. if (order >= 0) {
  1056. if (!this._vertexAttribArraysEnabled[order]) {
  1057. this._gl.enableVertexAttribArray(order);
  1058. this._vertexAttribArraysEnabled[order] = true;
  1059. }
  1060. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1061. }
  1062. offset += vertexDeclaration[index] * 4;
  1063. } else {
  1064. //disable effect attributes that have no data
  1065. var order = effect.getAttributeLocation(index);
  1066. if (this._vertexAttribArraysEnabled[order]) {
  1067. this._gl.disableVertexAttribArray(order);
  1068. this._vertexAttribArraysEnabled[order] = false;
  1069. }
  1070. }
  1071. }
  1072. }
  1073. if (this._cachedIndexBuffer !== indexBuffer) {
  1074. this._cachedIndexBuffer = indexBuffer;
  1075. this.bindIndexBuffer(indexBuffer);
  1076. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1077. }
  1078. }
  1079. public bindBuffers(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): void {
  1080. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1081. this._cachedVertexBuffers = vertexBuffers;
  1082. this._cachedEffectForVertexBuffers = effect;
  1083. var attributes = effect.getAttributesNames();
  1084. for (var index = 0; index < attributes.length; index++) {
  1085. var order = effect.getAttributeLocation(index);
  1086. if (order >= 0) {
  1087. var vertexBuffer = vertexBuffers[attributes[index]];
  1088. if (!vertexBuffer) {
  1089. if (this._vertexAttribArraysEnabled[order]) {
  1090. this._gl.disableVertexAttribArray(order);
  1091. this._vertexAttribArraysEnabled[order] = false;
  1092. }
  1093. continue;
  1094. }
  1095. if (!this._vertexAttribArraysEnabled[order]) {
  1096. this._gl.enableVertexAttribArray(order);
  1097. this._vertexAttribArraysEnabled[order] = true;
  1098. }
  1099. var buffer = vertexBuffer.getBuffer();
  1100. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1101. if (vertexBuffer.getIsInstanced()) {
  1102. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  1103. this._currentInstanceLocations.push(order);
  1104. this._currentInstanceBuffers.push(buffer);
  1105. }
  1106. }
  1107. }
  1108. }
  1109. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  1110. this._cachedIndexBuffer = indexBuffer;
  1111. this.bindIndexBuffer(indexBuffer);
  1112. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1113. }
  1114. }
  1115. public unbindInstanceAttributes() {
  1116. var boundBuffer;
  1117. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1118. var instancesBuffer = this._currentInstanceBuffers[i];
  1119. if (boundBuffer != instancesBuffer) {
  1120. boundBuffer = instancesBuffer;
  1121. this.bindArrayBuffer(instancesBuffer);
  1122. }
  1123. var offsetLocation = this._currentInstanceLocations[i];
  1124. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  1125. }
  1126. this._currentInstanceBuffers.length = 0;
  1127. this._currentInstanceLocations.length = 0;
  1128. }
  1129. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  1130. buffer.references--;
  1131. if (buffer.references === 0) {
  1132. this._gl.deleteBuffer(buffer);
  1133. return true;
  1134. }
  1135. return false;
  1136. }
  1137. public createInstancesBuffer(capacity: number): WebGLBuffer {
  1138. var buffer = this._gl.createBuffer();
  1139. buffer.capacity = capacity;
  1140. this.bindArrayBuffer(buffer);
  1141. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1142. return buffer;
  1143. }
  1144. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  1145. this._gl.deleteBuffer(buffer);
  1146. }
  1147. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1148. this.bindArrayBuffer(instancesBuffer);
  1149. if (data) {
  1150. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1151. }
  1152. if ((<any>offsetLocations[0]).index !== undefined) {
  1153. let stride = 0;
  1154. for (let i = 0; i < offsetLocations.length; i++) {
  1155. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1156. stride += ai.attributeSize * 4;
  1157. }
  1158. for (let i = 0; i < offsetLocations.length; i++) {
  1159. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1160. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1161. this._gl.enableVertexAttribArray(ai.index);
  1162. this._vertexAttribArraysEnabled[ai.index] = true;
  1163. }
  1164. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1165. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  1166. this._currentInstanceLocations.push(ai.index);
  1167. this._currentInstanceBuffers.push(instancesBuffer);
  1168. }
  1169. } else {
  1170. for (let index = 0; index < 4; index++) {
  1171. let offsetLocation = <number>offsetLocations[index];
  1172. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1173. this._gl.enableVertexAttribArray(offsetLocation);
  1174. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1175. }
  1176. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1177. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  1178. this._currentInstanceLocations.push(offsetLocation);
  1179. this._currentInstanceBuffers.push(instancesBuffer);
  1180. }
  1181. }
  1182. }
  1183. public applyStates() {
  1184. this._depthCullingState.apply(this._gl);
  1185. this._stencilState.apply(this._gl);
  1186. this._alphaState.apply(this._gl);
  1187. }
  1188. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1189. // Apply states
  1190. this.applyStates();
  1191. this._drawCalls.addCount(1, false);
  1192. // Render
  1193. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1194. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1195. if (instancesCount) {
  1196. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1197. return;
  1198. }
  1199. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1200. }
  1201. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1202. // Apply states
  1203. this.applyStates();
  1204. this._drawCalls.addCount(1, false);
  1205. if (instancesCount) {
  1206. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1207. return;
  1208. }
  1209. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1210. }
  1211. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1212. // Apply states
  1213. this.applyStates();
  1214. this._drawCalls.addCount(1, false);
  1215. if (instancesCount) {
  1216. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  1217. return;
  1218. }
  1219. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  1220. }
  1221. // Shaders
  1222. public _releaseEffect(effect: Effect): void {
  1223. if (this._compiledEffects[effect._key]) {
  1224. delete this._compiledEffects[effect._key];
  1225. if (effect.getProgram()) {
  1226. this._gl.deleteProgram(effect.getProgram());
  1227. }
  1228. }
  1229. }
  1230. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  1231. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  1232. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1233. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1234. var name = vertex + "+" + fragment + "@" + defines;
  1235. if (this._compiledEffects[name]) {
  1236. return this._compiledEffects[name];
  1237. }
  1238. var effect = new Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1239. effect._key = name;
  1240. this._compiledEffects[name] = effect;
  1241. return effect;
  1242. }
  1243. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  1244. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  1245. return this.createEffect(
  1246. {
  1247. vertex: "particles",
  1248. fragmentElement: fragmentName
  1249. },
  1250. ["position", "color", "options"],
  1251. ["view", "projection"].concat(uniformsNames),
  1252. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1253. }
  1254. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string, context?: WebGLRenderingContext): WebGLProgram {
  1255. context = context || this._gl;
  1256. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  1257. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  1258. var shaderProgram = context.createProgram();
  1259. context.attachShader(shaderProgram, vertexShader);
  1260. context.attachShader(shaderProgram, fragmentShader);
  1261. context.linkProgram(shaderProgram);
  1262. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  1263. if (!linked) {
  1264. var error = context.getProgramInfoLog(shaderProgram);
  1265. if (error) {
  1266. throw new Error(error);
  1267. }
  1268. }
  1269. context.deleteShader(vertexShader);
  1270. context.deleteShader(fragmentShader);
  1271. return shaderProgram;
  1272. }
  1273. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  1274. var results = [];
  1275. for (var index = 0; index < uniformsNames.length; index++) {
  1276. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1277. }
  1278. return results;
  1279. }
  1280. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  1281. var results = [];
  1282. for (var index = 0; index < attributesNames.length; index++) {
  1283. try {
  1284. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1285. } catch (e) {
  1286. results.push(-1);
  1287. }
  1288. }
  1289. return results;
  1290. }
  1291. public enableEffect(effect: Effect): void {
  1292. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  1293. // if (effect && effect.onBind) {
  1294. // effect.onBind(effect);
  1295. // }
  1296. // return;
  1297. //}
  1298. // Use program
  1299. this.setProgram(effect.getProgram());
  1300. this._currentEffect = effect;
  1301. if (effect.onBind) {
  1302. effect.onBind(effect);
  1303. }
  1304. }
  1305. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  1306. if (!uniform)
  1307. return;
  1308. this._gl.uniform1iv(uniform, array);
  1309. }
  1310. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  1311. if (!uniform || array.length % 2 !== 0)
  1312. return;
  1313. this._gl.uniform2iv(uniform, array);
  1314. }
  1315. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  1316. if (!uniform || array.length % 3 !== 0)
  1317. return;
  1318. this._gl.uniform3iv(uniform, array);
  1319. }
  1320. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  1321. if (!uniform || array.length % 4 !== 0)
  1322. return;
  1323. this._gl.uniform4iv(uniform, array);
  1324. }
  1325. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  1326. if (!uniform)
  1327. return;
  1328. this._gl.uniform1fv(uniform, array);
  1329. }
  1330. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  1331. if (!uniform || array.length % 2 !== 0)
  1332. return;
  1333. this._gl.uniform2fv(uniform, array);
  1334. }
  1335. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  1336. if (!uniform || array.length % 3 !== 0)
  1337. return;
  1338. this._gl.uniform3fv(uniform, array);
  1339. }
  1340. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  1341. if (!uniform || array.length % 4 !== 0)
  1342. return;
  1343. this._gl.uniform4fv(uniform, array);
  1344. }
  1345. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  1346. if (!uniform)
  1347. return;
  1348. this._gl.uniform1fv(uniform, <any>array);
  1349. }
  1350. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  1351. if (!uniform || array.length % 2 !== 0)
  1352. return;
  1353. this._gl.uniform2fv(uniform, <any>array);
  1354. }
  1355. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  1356. if (!uniform || array.length % 3 !== 0)
  1357. return;
  1358. this._gl.uniform3fv(uniform, <any>array);
  1359. }
  1360. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  1361. if (!uniform || array.length % 4 !== 0)
  1362. return;
  1363. this._gl.uniform4fv(uniform, <any>array);
  1364. }
  1365. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1366. if (!uniform)
  1367. return;
  1368. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1369. }
  1370. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1371. if (!uniform)
  1372. return;
  1373. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1374. }
  1375. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1376. if (!uniform)
  1377. return;
  1378. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1379. }
  1380. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1381. if (!uniform)
  1382. return;
  1383. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1384. }
  1385. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1386. if (!uniform)
  1387. return;
  1388. this._gl.uniform1f(uniform, value);
  1389. }
  1390. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  1391. if (!uniform)
  1392. return;
  1393. this._gl.uniform2f(uniform, x, y);
  1394. }
  1395. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  1396. if (!uniform)
  1397. return;
  1398. this._gl.uniform3f(uniform, x, y, z);
  1399. }
  1400. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  1401. if (!uniform)
  1402. return;
  1403. this._gl.uniform1i(uniform, bool);
  1404. }
  1405. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  1406. if (!uniform)
  1407. return;
  1408. this._gl.uniform4f(uniform, x, y, z, w);
  1409. }
  1410. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  1411. if (!uniform)
  1412. return;
  1413. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1414. }
  1415. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  1416. if (!uniform)
  1417. return;
  1418. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1419. }
  1420. // States
  1421. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1422. // Culling
  1423. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1424. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1425. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1426. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1427. if (culling) {
  1428. this._depthCullingState.cullFace = cullFace;
  1429. this._depthCullingState.cull = true;
  1430. } else {
  1431. this._depthCullingState.cull = false;
  1432. }
  1433. }
  1434. // Z offset
  1435. this._depthCullingState.zOffset = zOffset;
  1436. }
  1437. public setDepthBuffer(enable: boolean): void {
  1438. this._depthCullingState.depthTest = enable;
  1439. }
  1440. public getDepthWrite(): boolean {
  1441. return this._depthCullingState.depthMask;
  1442. }
  1443. public setDepthWrite(enable: boolean): void {
  1444. this._depthCullingState.depthMask = enable;
  1445. }
  1446. public setColorWrite(enable: boolean): void {
  1447. this._gl.colorMask(enable, enable, enable, enable);
  1448. }
  1449. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  1450. if (this._alphaMode === mode) {
  1451. return;
  1452. }
  1453. switch (mode) {
  1454. case Engine.ALPHA_DISABLE:
  1455. this._alphaState.alphaBlend = false;
  1456. break;
  1457. case Engine.ALPHA_COMBINE:
  1458. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1459. this._alphaState.alphaBlend = true;
  1460. break;
  1461. case Engine.ALPHA_ONEONE:
  1462. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1463. this._alphaState.alphaBlend = true;
  1464. break;
  1465. case Engine.ALPHA_ADD:
  1466. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1467. this._alphaState.alphaBlend = true;
  1468. break;
  1469. case Engine.ALPHA_SUBTRACT:
  1470. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1471. this._alphaState.alphaBlend = true;
  1472. break;
  1473. case Engine.ALPHA_MULTIPLY:
  1474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1475. this._alphaState.alphaBlend = true;
  1476. break;
  1477. case Engine.ALPHA_MAXIMIZED:
  1478. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1479. this._alphaState.alphaBlend = true;
  1480. break;
  1481. }
  1482. if (!noDepthWriteChange) {
  1483. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  1484. }
  1485. this._alphaMode = mode;
  1486. }
  1487. public getAlphaMode(): number {
  1488. return this._alphaMode;
  1489. }
  1490. public setAlphaTesting(enable: boolean): void {
  1491. this._alphaTest = enable;
  1492. }
  1493. public getAlphaTesting(): boolean {
  1494. return this._alphaTest;
  1495. }
  1496. // Textures
  1497. public wipeCaches(): void {
  1498. this.resetTextureCache();
  1499. this._currentEffect = null;
  1500. this._stencilState.reset();
  1501. this._depthCullingState.reset();
  1502. this.setDepthFunctionToLessOrEqual();
  1503. this._alphaState.reset();
  1504. this._cachedVertexBuffers = null;
  1505. this._cachedIndexBuffer = null;
  1506. this._cachedEffectForVertexBuffers = null;
  1507. }
  1508. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  1509. var gl = this._gl;
  1510. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1511. var magFilter = gl.NEAREST;
  1512. var minFilter = gl.NEAREST;
  1513. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  1514. magFilter = gl.LINEAR;
  1515. minFilter = gl.LINEAR;
  1516. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  1517. magFilter = gl.LINEAR;
  1518. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1519. }
  1520. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1521. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1522. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1523. texture.samplingMode = samplingMode;
  1524. }
  1525. public createTexture(urlOrList: string | Array<string>, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, onLoad: () => void = null, onError: () => void = null, buffer: any = null): WebGLTexture {
  1526. var texture = this._gl.createTexture();
  1527. var url = <string>((urlOrList.constructor === Array) ? urlOrList[0] : urlOrList);
  1528. var extension: string;
  1529. var fromData: any = false;
  1530. if (url.substr(0, 5) === "data:") {
  1531. fromData = true;
  1532. }
  1533. if (!fromData)
  1534. extension = url.substr(url.length - 4, 4).toLowerCase();
  1535. else {
  1536. var oldUrl = url;
  1537. fromData = oldUrl.split(':');
  1538. url = oldUrl;
  1539. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1540. }
  1541. var isDDS = (extension === ".dds");
  1542. var isTGA = (extension === ".tga");
  1543. scene._addPendingData(texture);
  1544. texture.url = url;
  1545. texture.noMipmap = noMipmap;
  1546. texture.references = 1;
  1547. texture.samplingMode = samplingMode;
  1548. texture.onLoadedCallbacks = [onLoad];
  1549. this._loadedTexturesCache.push(texture);
  1550. var onerror = () => {
  1551. scene._removePendingData(texture);
  1552. if (onError) {
  1553. onError();
  1554. }
  1555. };
  1556. var callback: (arrayBuffer: any) => void;
  1557. if (isTGA) {
  1558. callback = (arrayBuffer) => {
  1559. var data = new Uint8Array(arrayBuffer);
  1560. var header = Internals.TGATools.GetTGAHeader(data);
  1561. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  1562. Internals.TGATools.UploadContent(this._gl, data);
  1563. }, samplingMode);
  1564. };
  1565. if (!(fromData instanceof Array))
  1566. Tools.LoadFile(url, arrayBuffer => {
  1567. callback(arrayBuffer);
  1568. }, null, scene.database, true, onerror);
  1569. else
  1570. callback(buffer);
  1571. } else if (isDDS) {
  1572. if (!this.getCaps().s3tc) {
  1573. if (urlOrList instanceof Array) {
  1574. var newList = (<Array<string>>urlOrList).slice(1);
  1575. if (newList.length > 0) {
  1576. return this.createTexture(newList, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer);
  1577. }
  1578. }
  1579. onerror();
  1580. return null;
  1581. }
  1582. callback = (data) => {
  1583. var info = Internals.DDSTools.GetDDSInfo(data);
  1584. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1585. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1586. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1587. }, samplingMode);
  1588. };
  1589. if (!(fromData instanceof Array))
  1590. Tools.LoadFile(url, data => {
  1591. callback(data);
  1592. }, null, scene.database, true, onerror);
  1593. else
  1594. callback(buffer);
  1595. } else {
  1596. var onload = (img) => {
  1597. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1598. var isPot = (img.width === potWidth && img.height === potHeight);
  1599. if (!isPot) {
  1600. this._prepareWorkingCanvas();
  1601. this._workingCanvas.width = potWidth;
  1602. this._workingCanvas.height = potHeight;
  1603. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1604. this._workingContext.imageSmoothingEnabled = false;
  1605. this._workingContext.mozImageSmoothingEnabled = false;
  1606. this._workingContext.oImageSmoothingEnabled = false;
  1607. this._workingContext.webkitImageSmoothingEnabled = false;
  1608. this._workingContext.msImageSmoothingEnabled = false;
  1609. }
  1610. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1611. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1612. this._workingContext.imageSmoothingEnabled = true;
  1613. this._workingContext.mozImageSmoothingEnabled = true;
  1614. this._workingContext.oImageSmoothingEnabled = true;
  1615. this._workingContext.webkitImageSmoothingEnabled = true;
  1616. this._workingContext.msImageSmoothingEnabled = true;
  1617. }
  1618. }
  1619. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1620. }, samplingMode);
  1621. };
  1622. if (!(fromData instanceof Array))
  1623. Tools.LoadImage(url, onload, onerror, scene.database);
  1624. else
  1625. Tools.LoadImage(buffer, onload, onerror, scene.database);
  1626. }
  1627. return texture;
  1628. }
  1629. private _getInternalFormat(format: number): number {
  1630. var internalFormat = this._gl.RGBA;
  1631. switch (format) {
  1632. case Engine.TEXTUREFORMAT_ALPHA:
  1633. internalFormat = this._gl.ALPHA;
  1634. break;
  1635. case Engine.TEXTUREFORMAT_LUMINANCE:
  1636. internalFormat = this._gl.LUMINANCE;
  1637. break;
  1638. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1639. internalFormat = this._gl.LUMINANCE_ALPHA;
  1640. break;
  1641. case Engine.TEXTUREFORMAT_RGB:
  1642. internalFormat = this._gl.RGB;
  1643. break;
  1644. case Engine.TEXTUREFORMAT_RGBA:
  1645. internalFormat = this._gl.RGBA;
  1646. break;
  1647. }
  1648. return internalFormat;
  1649. }
  1650. public updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
  1651. var internalFormat = this._getInternalFormat(format);
  1652. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1653. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1654. if (texture._width % 4 !== 0) {
  1655. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  1656. }
  1657. if (compression) {
  1658. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  1659. } else {
  1660. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1661. }
  1662. if (texture.generateMipMaps) {
  1663. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1664. }
  1665. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1666. this.resetTextureCache();
  1667. texture.isReady = true;
  1668. }
  1669. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): WebGLTexture {
  1670. var texture = this._gl.createTexture();
  1671. texture._baseWidth = width;
  1672. texture._baseHeight = height;
  1673. texture._width = width;
  1674. texture._height = height;
  1675. texture.references = 1;
  1676. this.updateRawTexture(texture, data, format, invertY, compression);
  1677. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1678. // Filters
  1679. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1680. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1681. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1682. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1683. texture.samplingMode = samplingMode;
  1684. this._loadedTexturesCache.push(texture);
  1685. return texture;
  1686. }
  1687. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  1688. var texture = this._gl.createTexture();
  1689. texture._baseWidth = width;
  1690. texture._baseHeight = height;
  1691. if (generateMipMaps) {
  1692. width = Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  1693. height = Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  1694. }
  1695. this.resetTextureCache();
  1696. texture._width = width;
  1697. texture._height = height;
  1698. texture.isReady = false;
  1699. texture.generateMipMaps = generateMipMaps;
  1700. texture.references = 1;
  1701. texture.samplingMode = samplingMode;
  1702. this.updateTextureSamplingMode(samplingMode, texture);
  1703. this._loadedTexturesCache.push(texture);
  1704. return texture;
  1705. }
  1706. public updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void {
  1707. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1708. if (texture.isCube) {
  1709. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  1710. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1711. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1712. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  1713. } else {
  1714. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1715. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1716. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1717. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1718. }
  1719. }
  1720. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false): void {
  1721. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1722. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1723. if (premulAlpha) {
  1724. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  1725. }
  1726. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1727. if (texture.generateMipMaps) {
  1728. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1729. }
  1730. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1731. if (premulAlpha) {
  1732. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  1733. }
  1734. this.resetTextureCache();
  1735. texture.isReady = true;
  1736. }
  1737. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1738. if (texture._isDisabled) {
  1739. return;
  1740. }
  1741. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1742. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1743. try {
  1744. // Testing video texture support
  1745. if (this._videoTextureSupported === undefined) {
  1746. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1747. if (this._gl.getError() !== 0) {
  1748. this._videoTextureSupported = false;
  1749. } else {
  1750. this._videoTextureSupported = true;
  1751. }
  1752. }
  1753. // Copy video through the current working canvas if video texture is not supported
  1754. if (!this._videoTextureSupported) {
  1755. if (!texture._workingCanvas) {
  1756. texture._workingCanvas = document.createElement("canvas");
  1757. texture._workingContext = texture._workingCanvas.getContext("2d");
  1758. texture._workingCanvas.width = texture._width;
  1759. texture._workingCanvas.height = texture._height;
  1760. }
  1761. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1762. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1763. } else {
  1764. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1765. }
  1766. if (texture.generateMipMaps) {
  1767. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1768. }
  1769. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1770. this.resetTextureCache();
  1771. texture.isReady = true;
  1772. } catch (ex) {
  1773. // Something unexpected
  1774. // Let's disable the texture
  1775. texture._isDisabled = true;
  1776. }
  1777. }
  1778. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1779. // old version had a "generateMipMaps" arg instead of options.
  1780. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1781. // in the same way, generateDepthBuffer is defaulted to true
  1782. var generateMipMaps = false;
  1783. var generateDepthBuffer = true;
  1784. var generateStencilBuffer = false;
  1785. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1786. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1787. if (options !== undefined) {
  1788. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1789. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1790. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  1791. type = options.type === undefined ? type : options.type;
  1792. if (options.samplingMode !== undefined) {
  1793. samplingMode = options.samplingMode;
  1794. }
  1795. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  1796. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1797. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1798. }
  1799. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  1800. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  1801. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1802. }
  1803. }
  1804. var gl = this._gl;
  1805. var texture = gl.createTexture();
  1806. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1807. var width = size.width || size;
  1808. var height = size.height || size;
  1809. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1810. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1811. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1812. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1813. }
  1814. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1815. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1818. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1819. var depthStencilBuffer: WebGLRenderbuffer;
  1820. // Create the depth/stencil buffer
  1821. if (generateStencilBuffer) {
  1822. depthStencilBuffer = gl.createRenderbuffer();
  1823. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1824. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  1825. }
  1826. else if (generateDepthBuffer) {
  1827. depthStencilBuffer = gl.createRenderbuffer();
  1828. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1829. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1830. }
  1831. // Create the framebuffer
  1832. var framebuffer = gl.createFramebuffer();
  1833. this.bindUnboundFramebuffer(framebuffer);
  1834. // Manage attachments
  1835. if (generateStencilBuffer) {
  1836. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1837. }
  1838. else if (generateDepthBuffer) {
  1839. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1840. }
  1841. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1842. if (generateMipMaps) {
  1843. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1844. }
  1845. // Unbind
  1846. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1847. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1848. this.bindUnboundFramebuffer(null);
  1849. texture._framebuffer = framebuffer;
  1850. if (generateDepthBuffer) {
  1851. texture._depthBuffer = depthStencilBuffer;
  1852. }
  1853. texture._baseWidth = width;
  1854. texture._baseHeight = height;
  1855. texture._width = width;
  1856. texture._height = height;
  1857. texture.isReady = true;
  1858. texture.generateMipMaps = generateMipMaps;
  1859. texture.references = 1;
  1860. texture.samplingMode = samplingMode;
  1861. texture.type = type;
  1862. this.resetTextureCache();
  1863. this._loadedTexturesCache.push(texture);
  1864. return texture;
  1865. }
  1866. public createRenderTargetCubeTexture(size: number, options?: any): WebGLTexture {
  1867. var gl = this._gl;
  1868. var texture = gl.createTexture();
  1869. var generateMipMaps = true;
  1870. var generateDepthBuffer = true;
  1871. var generateStencilBuffer = false;
  1872. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1873. if (options !== undefined) {
  1874. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1875. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1876. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  1877. if (options.samplingMode !== undefined) {
  1878. samplingMode = options.samplingMode;
  1879. }
  1880. }
  1881. texture.isCube = true;
  1882. texture.references = 1;
  1883. texture.generateMipMaps = generateMipMaps;
  1884. texture.references = 1;
  1885. texture.samplingMode = samplingMode;
  1886. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1887. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1888. for (var face = 0; face < 6; face++) {
  1889. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  1890. }
  1891. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  1892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  1893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1894. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1895. // Create the depth buffer
  1896. var depthStencilBuffer: WebGLRenderbuffer;
  1897. // Create the depth/stencil buffer
  1898. if (generateStencilBuffer) {
  1899. depthStencilBuffer = gl.createRenderbuffer();
  1900. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1901. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  1902. }
  1903. else if (generateDepthBuffer) {
  1904. depthStencilBuffer = gl.createRenderbuffer();
  1905. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1906. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  1907. }
  1908. // Create the framebuffer
  1909. var framebuffer = gl.createFramebuffer();
  1910. this.bindUnboundFramebuffer(framebuffer);
  1911. // Manage attachments
  1912. if (generateStencilBuffer) {
  1913. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1914. }
  1915. else if (generateDepthBuffer) {
  1916. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1917. }
  1918. // Mipmaps
  1919. if (texture.generateMipMaps) {
  1920. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1921. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1922. }
  1923. // Unbind
  1924. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1925. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1926. this.bindUnboundFramebuffer(null);
  1927. texture._framebuffer = framebuffer;
  1928. if (generateDepthBuffer) {
  1929. texture._depthBuffer = depthStencilBuffer;
  1930. }
  1931. texture._width = size;
  1932. texture._height = size;
  1933. texture.isReady = true;
  1934. this.resetTextureCache();
  1935. this._loadedTexturesCache.push(texture);
  1936. return texture;
  1937. }
  1938. public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean, onLoad: () => void = null, onError: () => void = null): WebGLTexture {
  1939. var gl = this._gl;
  1940. var texture = gl.createTexture();
  1941. texture.isCube = true;
  1942. texture.url = rootUrl;
  1943. texture.references = 1;
  1944. texture.onLoadedCallbacks = [];
  1945. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1946. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1947. if (isDDS) {
  1948. Tools.LoadFile(rootUrl, data => {
  1949. var info = Internals.DDSTools.GetDDSInfo(data);
  1950. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1951. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1952. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1953. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1954. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1955. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1956. }
  1957. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1961. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1962. this.resetTextureCache();
  1963. texture._width = info.width;
  1964. texture._height = info.height;
  1965. texture.isReady = true;
  1966. }, null, null, true, onError);
  1967. } else {
  1968. cascadeLoad(rootUrl, scene, imgs => {
  1969. var width = Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1970. var height = width;
  1971. this._prepareWorkingCanvas();
  1972. this._workingCanvas.width = width;
  1973. this._workingCanvas.height = height;
  1974. var faces = [
  1975. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1976. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1977. ];
  1978. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1979. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1980. for (var index = 0; index < faces.length; index++) {
  1981. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1982. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1983. }
  1984. if (!noMipmap) {
  1985. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1986. }
  1987. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1990. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1991. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1992. this.resetTextureCache();
  1993. texture._width = width;
  1994. texture._height = height;
  1995. texture.isReady = true;
  1996. texture.onLoadedCallbacks.forEach(callback => {
  1997. callback();
  1998. });
  1999. if (onLoad) {
  2000. onLoad();
  2001. }
  2002. }, files, onError);
  2003. }
  2004. this._loadedTexturesCache.push(texture);
  2005. return texture;
  2006. }
  2007. public updateTextureSize(texture: WebGLTexture, width: number, height: number) {
  2008. texture._width = width;
  2009. texture._height = height;
  2010. texture._size = width * height;
  2011. texture._baseWidth = width;
  2012. texture._baseHeight = height;
  2013. }
  2014. public createRawCubeTexture(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  2015. callback: (ArrayBuffer) => ArrayBufferView[],
  2016. mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][])): WebGLTexture {
  2017. var gl = this._gl;
  2018. var texture = gl.createTexture();
  2019. scene._addPendingData(texture);
  2020. texture.isCube = true;
  2021. texture.references = 1;
  2022. texture.url = url;
  2023. var internalFormat = this._getInternalFormat(format);
  2024. var textureType = gl.UNSIGNED_BYTE;
  2025. if (type === Engine.TEXTURETYPE_FLOAT) {
  2026. textureType = gl.FLOAT;
  2027. }
  2028. var width = size;
  2029. var height = width;
  2030. var isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  2031. texture._width = width;
  2032. texture._height = height;
  2033. var onerror = () => {
  2034. scene._removePendingData(texture);
  2035. };
  2036. var internalCallback = (data) => {
  2037. var rgbeDataArrays = callback(data);
  2038. var facesIndex = [
  2039. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2040. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2041. ];
  2042. width = texture._width;
  2043. height = texture._height;
  2044. isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  2045. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2046. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2047. if (!noMipmap && isPot) {
  2048. if (mipmmapGenerator) {
  2049. var arrayTemp: ArrayBufferView[] = [];
  2050. // Data are known to be in +X +Y +Z -X -Y -Z
  2051. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  2052. arrayTemp.push(rgbeDataArrays[0]); // +X
  2053. arrayTemp.push(rgbeDataArrays[3]); // -X
  2054. arrayTemp.push(rgbeDataArrays[1]); // +Y
  2055. arrayTemp.push(rgbeDataArrays[4]); // -Y
  2056. arrayTemp.push(rgbeDataArrays[2]); // +Z
  2057. arrayTemp.push(rgbeDataArrays[5]); // -Z
  2058. var mipData = mipmmapGenerator(arrayTemp);
  2059. for (var level = 0; level < mipData.length; level++) {
  2060. var mipSize = width >> level;
  2061. // mipData is order in +X -X +Y -Y +Z -Z
  2062. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  2063. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  2064. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  2065. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  2066. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  2067. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  2068. }
  2069. }
  2070. else {
  2071. // Data are known to be in +X +Y +Z -X -Y -Z
  2072. for (let index = 0; index < facesIndex.length; index++) {
  2073. let faceData = rgbeDataArrays[index];
  2074. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  2075. }
  2076. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2077. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  2078. // By following the webgl standard changes from Revision 7, 2014/11/24
  2079. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  2080. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  2081. Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  2082. // Data are known to be in +X +Y +Z -X -Y -Z
  2083. for (let index = 0; index < facesIndex.length; index++) {
  2084. let faceData = <Float32Array>rgbeDataArrays[index];
  2085. // Create a new RGBA Face.
  2086. let newFaceData = new Float32Array(width * height * 4);
  2087. for (let x = 0; x < width; x++) {
  2088. for (let y = 0; y < height; y++) {
  2089. let index = (y * width + x) * 3;
  2090. let newIndex = (y * width + x) * 4;
  2091. // Map Old Value to new value.
  2092. newFaceData[newIndex + 0] = faceData[index + 0];
  2093. newFaceData[newIndex + 1] = faceData[index + 1];
  2094. newFaceData[newIndex + 2] = faceData[index + 2];
  2095. // Add fully opaque alpha channel.
  2096. newFaceData[newIndex + 3] = 1;
  2097. }
  2098. }
  2099. // Reupload the face.
  2100. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  2101. }
  2102. // Try to generate mipmap again.
  2103. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2104. }
  2105. }
  2106. }
  2107. else {
  2108. noMipmap = true;
  2109. }
  2110. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  2111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2113. }
  2114. else if (textureType === HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  2115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2116. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2117. }
  2118. else {
  2119. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2121. }
  2122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2123. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2124. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2125. texture.isReady = true;
  2126. this.resetTextureCache();
  2127. scene._removePendingData(texture);
  2128. };
  2129. Tools.LoadFile(url, data => {
  2130. internalCallback(data);
  2131. }, onerror, scene.database, true);
  2132. return texture;
  2133. };
  2134. public _releaseTexture(texture: WebGLTexture): void {
  2135. var gl = this._gl;
  2136. if (texture._framebuffer) {
  2137. gl.deleteFramebuffer(texture._framebuffer);
  2138. }
  2139. if (texture._depthBuffer) {
  2140. gl.deleteRenderbuffer(texture._depthBuffer);
  2141. }
  2142. gl.deleteTexture(texture);
  2143. // Unbind channels
  2144. this.unbindAllTextures();
  2145. var index = this._loadedTexturesCache.indexOf(texture);
  2146. if (index !== -1) {
  2147. this._loadedTexturesCache.splice(index, 1);
  2148. }
  2149. }
  2150. private setProgram(program: WebGLProgram): void {
  2151. if (this._currentProgram !== program) {
  2152. this._gl.useProgram(program);
  2153. this._currentProgram = program;
  2154. }
  2155. }
  2156. public bindSamplers(effect: Effect): void {
  2157. this.setProgram(effect.getProgram());
  2158. var samplers = effect.getSamplers();
  2159. for (var index = 0; index < samplers.length; index++) {
  2160. var uniform = effect.getUniform(samplers[index]);
  2161. this._gl.uniform1i(uniform, index);
  2162. }
  2163. this._currentEffect = null;
  2164. }
  2165. private activateTexture(texture: number): void {
  2166. if (this._activeTexture !== texture) {
  2167. this._gl.activeTexture(texture);
  2168. this._activeTexture = texture;
  2169. }
  2170. }
  2171. public _bindTextureDirectly(target: number, texture: WebGLTexture): void {
  2172. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  2173. this._gl.bindTexture(target, texture);
  2174. this._activeTexturesCache[this._activeTexture] = texture;
  2175. }
  2176. }
  2177. public _bindTexture(channel: number, texture: WebGLTexture): void {
  2178. if (channel < 0) {
  2179. return;
  2180. }
  2181. this.activateTexture(this._gl["TEXTURE" + channel]);
  2182. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2183. }
  2184. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  2185. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  2186. }
  2187. public unbindAllTextures(): void {
  2188. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  2189. this.activateTexture(this._gl["TEXTURE" + channel]);
  2190. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2191. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2192. }
  2193. }
  2194. public setTexture(channel: number, uniform: WebGLUniformLocation, texture: BaseTexture): void {
  2195. if (channel < 0) {
  2196. return;
  2197. }
  2198. this._gl.uniform1i(uniform, channel);
  2199. this._setTexture(channel, texture);
  2200. }
  2201. private _setTexture(channel: number, texture: BaseTexture): void {
  2202. // Not ready?
  2203. if (!texture || !texture.isReady()) {
  2204. if (this._activeTexturesCache[channel] != null) {
  2205. this.activateTexture(this._gl["TEXTURE" + channel]);
  2206. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2207. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2208. }
  2209. return;
  2210. }
  2211. // Video
  2212. var alreadyActivated = false;
  2213. if (texture instanceof VideoTexture) {
  2214. this.activateTexture(this._gl["TEXTURE" + channel]);
  2215. alreadyActivated = true;
  2216. texture.update();
  2217. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  2218. texture.delayLoad();
  2219. return;
  2220. }
  2221. var internalTexture = texture.getInternalTexture();
  2222. if (this._activeTexturesCache[channel] === internalTexture) {
  2223. return;
  2224. }
  2225. if (!alreadyActivated) {
  2226. this.activateTexture(this._gl["TEXTURE" + channel]);
  2227. }
  2228. if (internalTexture.isCube) {
  2229. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  2230. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  2231. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  2232. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  2233. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  2234. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  2235. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  2236. }
  2237. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  2238. } else {
  2239. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  2240. if (internalTexture._cachedWrapU !== texture.wrapU) {
  2241. internalTexture._cachedWrapU = texture.wrapU;
  2242. switch (texture.wrapU) {
  2243. case Texture.WRAP_ADDRESSMODE:
  2244. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  2245. break;
  2246. case Texture.CLAMP_ADDRESSMODE:
  2247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  2248. break;
  2249. case Texture.MIRROR_ADDRESSMODE:
  2250. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  2251. break;
  2252. }
  2253. }
  2254. if (internalTexture._cachedWrapV !== texture.wrapV) {
  2255. internalTexture._cachedWrapV = texture.wrapV;
  2256. switch (texture.wrapV) {
  2257. case Texture.WRAP_ADDRESSMODE:
  2258. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  2259. break;
  2260. case Texture.CLAMP_ADDRESSMODE:
  2261. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  2262. break;
  2263. case Texture.MIRROR_ADDRESSMODE:
  2264. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  2265. break;
  2266. }
  2267. }
  2268. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  2269. }
  2270. }
  2271. public setTextureArray(channel: number, uniform: WebGLUniformLocation, textures: BaseTexture[]): void {
  2272. if (channel < 0) {
  2273. return;
  2274. }
  2275. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  2276. this._textureUnits = new Int32Array(textures.length);
  2277. }
  2278. for (let i = 0; i < textures.length; i++) {
  2279. this._textureUnits[i] = channel + i;
  2280. }
  2281. this._gl.uniform1iv(uniform, this._textureUnits);
  2282. for (var index = 0; index < textures.length; index++) {
  2283. this._setTexture(channel + index, textures[index]);
  2284. }
  2285. }
  2286. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  2287. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  2288. var value = texture.anisotropicFilteringLevel;
  2289. if (texture.getInternalTexture().samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  2290. value = 1;
  2291. }
  2292. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  2293. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  2294. texture._cachedAnisotropicFilteringLevel = value;
  2295. }
  2296. }
  2297. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  2298. var data = new Uint8Array(height * width * 4);
  2299. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  2300. return data;
  2301. }
  2302. /**
  2303. * Add an externaly attached data from its key.
  2304. * This method call will fail and return false, if such key already exists.
  2305. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2306. * @param key the unique key that identifies the data
  2307. * @param data the data object to associate to the key for this Engine instance
  2308. * @return true if no such key were already present and the data was added successfully, false otherwise
  2309. */
  2310. public addExternalData<T>(key: string, data: T): boolean {
  2311. return this._externalData.add(key, data);
  2312. }
  2313. /**
  2314. * Get an externaly attached data from its key
  2315. * @param key the unique key that identifies the data
  2316. * @return the associated data, if present (can be null), or undefined if not present
  2317. */
  2318. public getExternalData<T>(key: string): T {
  2319. return <T>this._externalData.get(key);
  2320. }
  2321. /**
  2322. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2323. * @param key the unique key that identifies the data
  2324. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2325. * @return the associated data, can be null if the factory returned null.
  2326. */
  2327. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  2328. return <T>this._externalData.getOrAddWithFactory(key, factory);
  2329. }
  2330. /**
  2331. * Remove an externaly attached data from the Engine instance
  2332. * @param key the unique key that identifies the data
  2333. * @return true if the data was successfully removed, false if it doesn't exist
  2334. */
  2335. public removeExternalData(key): boolean {
  2336. return this._externalData.remove(key);
  2337. }
  2338. public releaseInternalTexture(texture: WebGLTexture): void {
  2339. if (!texture) {
  2340. return;
  2341. }
  2342. texture.references--;
  2343. // Final reference ?
  2344. if (texture.references === 0) {
  2345. var texturesCache = this.getLoadedTexturesCache();
  2346. var index = texturesCache.indexOf(texture);
  2347. if (index > -1) {
  2348. texturesCache.splice(index, 1);
  2349. }
  2350. this._releaseTexture(texture);
  2351. }
  2352. }
  2353. public unbindAllAttributes() {
  2354. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  2355. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  2356. continue;
  2357. }
  2358. this._gl.disableVertexAttribArray(i);
  2359. this._vertexAttribArraysEnabled[i] = false;
  2360. }
  2361. }
  2362. // Dispose
  2363. public dispose(): void {
  2364. this.hideLoadingUI();
  2365. this.stopRenderLoop();
  2366. // Release scenes
  2367. while (this.scenes.length) {
  2368. this.scenes[0].dispose();
  2369. }
  2370. // Release audio engine
  2371. Engine.audioEngine.dispose();
  2372. // Release effects
  2373. for (var name in this._compiledEffects) {
  2374. this._gl.deleteProgram(this._compiledEffects[name]._program);
  2375. }
  2376. // Unbind
  2377. this.unbindAllAttributes();
  2378. this._gl = null;
  2379. //WebVR
  2380. this.disableVR();
  2381. // Events
  2382. window.removeEventListener("blur", this._onBlur);
  2383. window.removeEventListener("focus", this._onFocus);
  2384. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  2385. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  2386. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  2387. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  2388. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  2389. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  2390. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  2391. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  2392. }
  2393. // Loading screen
  2394. public displayLoadingUI(): void {
  2395. this._loadingScreen.displayLoadingUI();
  2396. }
  2397. public hideLoadingUI(): void {
  2398. this._loadingScreen.hideLoadingUI();
  2399. }
  2400. public get loadingScreen(): ILoadingScreen {
  2401. return this._loadingScreen;
  2402. }
  2403. public set loadingScreen(loadingScreen: ILoadingScreen) {
  2404. this._loadingScreen = loadingScreen;
  2405. }
  2406. public set loadingUIText(text: string) {
  2407. this._loadingScreen.loadingUIText = text;
  2408. }
  2409. public set loadingUIBackgroundColor(color: string) {
  2410. this._loadingScreen.loadingUIBackgroundColor = color;
  2411. }
  2412. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  2413. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  2414. }
  2415. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  2416. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  2417. }
  2418. public getVertexShaderSource(program: WebGLProgram): string {
  2419. var shaders = this._gl.getAttachedShaders(program);
  2420. return this._gl.getShaderSource(shaders[0]);
  2421. }
  2422. public getFragmentShaderSource(program: WebGLProgram): string {
  2423. var shaders = this._gl.getAttachedShaders(program);
  2424. return this._gl.getShaderSource(shaders[1]);
  2425. }
  2426. // FPS
  2427. public getFps(): number {
  2428. return this.fps;
  2429. }
  2430. public getDeltaTime(): number {
  2431. return this.deltaTime;
  2432. }
  2433. private _measureFps(): void {
  2434. this.previousFramesDuration.push(Tools.Now);
  2435. var length = this.previousFramesDuration.length;
  2436. if (length >= 2) {
  2437. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  2438. }
  2439. if (length >= this.fpsRange) {
  2440. if (length > this.fpsRange) {
  2441. this.previousFramesDuration.splice(0, 1);
  2442. length = this.previousFramesDuration.length;
  2443. }
  2444. var sum = 0;
  2445. for (var id = 0; id < length - 1; id++) {
  2446. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  2447. }
  2448. this.fps = 1000.0 / (sum / (length - 1));
  2449. }
  2450. }
  2451. private _canRenderToFloatTexture(): boolean {
  2452. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  2453. }
  2454. private _canRenderToHalfFloatTexture(): boolean {
  2455. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  2456. }
  2457. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  2458. private _canRenderToTextureOfType(format: number, extension: string): boolean {
  2459. var tempcanvas = document.createElement("canvas");
  2460. tempcanvas.height = 16;
  2461. tempcanvas.width = 16;
  2462. var gl = <WebGLRenderingContext>(tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  2463. // extension.
  2464. var ext = gl.getExtension(extension);
  2465. if (!ext) {
  2466. return false;
  2467. }
  2468. // setup GLSL program
  2469. var vertexCode = `attribute vec4 a_position;
  2470. void main() {
  2471. gl_Position = a_position;
  2472. }`;
  2473. var fragmentCode = `precision mediump float;
  2474. uniform vec4 u_color;
  2475. uniform sampler2D u_texture;
  2476. void main() {
  2477. gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;
  2478. }`;
  2479. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  2480. gl.useProgram(program);
  2481. // look up where the vertex data needs to go.
  2482. var positionLocation = gl.getAttribLocation(program, "a_position");
  2483. var colorLoc = gl.getUniformLocation(program, "u_color");
  2484. // provide texture coordinates for the rectangle.
  2485. var positionBuffer = gl.createBuffer();
  2486. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  2487. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  2488. -1.0, -1.0,
  2489. 1.0, -1.0,
  2490. -1.0, 1.0,
  2491. -1.0, 1.0,
  2492. 1.0, -1.0,
  2493. 1.0, 1.0]), gl.STATIC_DRAW);
  2494. gl.enableVertexAttribArray(positionLocation);
  2495. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  2496. var whiteTex = gl.createTexture();
  2497. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  2498. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  2499. var tex = gl.createTexture();
  2500. gl.bindTexture(gl.TEXTURE_2D, tex);
  2501. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  2502. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2503. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2504. var fb = gl.createFramebuffer();
  2505. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  2506. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  2507. var cleanup = () => {
  2508. gl.deleteProgram(program);
  2509. gl.disableVertexAttribArray(positionLocation);
  2510. gl.deleteBuffer(positionBuffer);
  2511. gl.deleteFramebuffer(fb);
  2512. gl.deleteTexture(whiteTex);
  2513. gl.deleteTexture(tex);
  2514. };
  2515. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  2516. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  2517. Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  2518. cleanup();
  2519. return false;
  2520. }
  2521. // Draw the rectangle.
  2522. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  2523. gl.uniform4fv(colorLoc, <any>[0, 10, 20, 1]);
  2524. gl.drawArrays(gl.TRIANGLES, 0, 6);
  2525. gl.bindTexture(gl.TEXTURE_2D, tex);
  2526. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  2527. gl.clearColor(1, 0, 0, 1);
  2528. gl.clear(gl.COLOR_BUFFER_BIT);
  2529. gl.uniform4fv(colorLoc, <any>[0, 1 / 10, 1 / 20, 1]);
  2530. gl.drawArrays(gl.TRIANGLES, 0, 6);
  2531. var pixel = new Uint8Array(4);
  2532. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  2533. if (pixel[0] !== 0 ||
  2534. pixel[1] < 248 ||
  2535. pixel[2] < 248 ||
  2536. pixel[3] < 254) {
  2537. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  2538. cleanup();
  2539. return false;
  2540. }
  2541. // Succesfully rendered to "format" texture.
  2542. cleanup();
  2543. return true;
  2544. }
  2545. // Statics
  2546. public static isSupported(): boolean {
  2547. try {
  2548. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  2549. if (navigator.isCocoonJS) {
  2550. return true;
  2551. }
  2552. var tempcanvas = document.createElement("canvas");
  2553. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  2554. return gl != null && !!window.WebGLRenderingContext;
  2555. } catch (e) {
  2556. return false;
  2557. }
  2558. }
  2559. }
  2560. }