babylon.engine.ts 124 KB

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