babylon.engine.ts 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453
  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 getWebGLTextureType = (gl: WebGLRenderingContext, type: number): number => {
  12. var textureType = gl.UNSIGNED_BYTE;
  13. if (type === Engine.TEXTURETYPE_FLOAT)
  14. textureType = gl.FLOAT;
  15. return textureType;
  16. };
  17. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  18. var magFilter = gl.NEAREST;
  19. var minFilter = gl.NEAREST;
  20. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  21. magFilter = gl.LINEAR;
  22. if (generateMipMaps) {
  23. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  24. } else {
  25. minFilter = gl.LINEAR;
  26. }
  27. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  28. magFilter = gl.LINEAR;
  29. if (generateMipMaps) {
  30. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  31. } else {
  32. minFilter = gl.LINEAR;
  33. }
  34. } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  35. magFilter = gl.NEAREST;
  36. if (generateMipMaps) {
  37. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  38. } else {
  39. minFilter = gl.NEAREST;
  40. }
  41. }
  42. return {
  43. min: minFilter,
  44. mag: magFilter
  45. }
  46. }
  47. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  48. processFunction: (width: number, height: number) => void, onLoad: () => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  49. var engine = scene.getEngine();
  50. var potWidth = Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  51. var potHeight = Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  52. gl.bindTexture(gl.TEXTURE_2D, texture);
  53. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  54. texture._baseWidth = width;
  55. texture._baseHeight = height;
  56. texture._width = potWidth;
  57. texture._height = potHeight;
  58. texture.isReady = true;
  59. processFunction(potWidth, potHeight);
  60. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  61. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  62. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  63. if (!noMipmap && !isCompressed) {
  64. gl.generateMipmap(gl.TEXTURE_2D);
  65. }
  66. gl.bindTexture(gl.TEXTURE_2D, null);
  67. engine.resetTextureCache();
  68. scene._removePendingData(texture);
  69. if (onLoad) {
  70. onLoad();
  71. }
  72. };
  73. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  74. onfinish: (images: HTMLImageElement[]) => void) => {
  75. var img: HTMLImageElement;
  76. var onload = () => {
  77. loadedImages[index] = img;
  78. loadedImages._internalCount++;
  79. scene._removePendingData(img);
  80. if (loadedImages._internalCount === 6) {
  81. onfinish(loadedImages);
  82. }
  83. };
  84. var onerror = () => {
  85. scene._removePendingData(img);
  86. };
  87. img = Tools.LoadImage(url, onload, onerror, scene.database);
  88. scene._addPendingData(img);
  89. }
  90. var cascadeLoad = (rootUrl: string, scene,
  91. onfinish: (images: HTMLImageElement[]) => void, files: string[]) => {
  92. var loadedImages: any = [];
  93. loadedImages._internalCount = 0;
  94. for (var index = 0; index < 6; index++) {
  95. partialLoad(files[index], index, loadedImages, scene, onfinish);
  96. }
  97. };
  98. export class InstancingAttributeInfo {
  99. /**
  100. * Index/offset of the attribute in the vertex shader
  101. */
  102. index: number;
  103. /**
  104. * size of the attribute, 1, 2, 3 or 4
  105. */
  106. attributeSize: number;
  107. /**
  108. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  109. * default is FLOAT
  110. */
  111. attribyteType: number;
  112. /**
  113. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  114. */
  115. normalized: boolean;
  116. /**
  117. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  118. */
  119. offset: number;
  120. /**
  121. * Name of the GLSL attribute, for debugging purpose only
  122. */
  123. attributeName: string;
  124. }
  125. export class EngineCapabilities {
  126. public maxTexturesImageUnits: number;
  127. public maxTextureSize: number;
  128. public maxCubemapTextureSize: number;
  129. public maxRenderTextureSize: number;
  130. public standardDerivatives: boolean;
  131. public s3tc;
  132. public textureFloat: boolean;
  133. public textureAnisotropicFilterExtension;
  134. public maxAnisotropy: number;
  135. public instancedArrays;
  136. public uintIndices: boolean;
  137. public highPrecisionShaderSupported: boolean;
  138. public fragmentDepthSupported: boolean;
  139. public textureFloatLinearFiltering: boolean;
  140. public textureLOD: boolean;
  141. public drawBuffersExtension;
  142. }
  143. /**
  144. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  145. */
  146. export class Engine {
  147. // Const statics
  148. private static _ALPHA_DISABLE = 0;
  149. private static _ALPHA_ADD = 1;
  150. private static _ALPHA_COMBINE = 2;
  151. private static _ALPHA_SUBTRACT = 3;
  152. private static _ALPHA_MULTIPLY = 4;
  153. private static _ALPHA_MAXIMIZED = 5;
  154. private static _ALPHA_ONEONE = 6;
  155. private static _DELAYLOADSTATE_NONE = 0;
  156. private static _DELAYLOADSTATE_LOADED = 1;
  157. private static _DELAYLOADSTATE_LOADING = 2;
  158. private static _DELAYLOADSTATE_NOTLOADED = 4;
  159. private static _TEXTUREFORMAT_ALPHA = 0;
  160. private static _TEXTUREFORMAT_LUMINANCE = 1;
  161. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  162. private static _TEXTUREFORMAT_RGB = 4;
  163. private static _TEXTUREFORMAT_RGBA = 5;
  164. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  165. private static _TEXTURETYPE_FLOAT = 1;
  166. public static get ALPHA_DISABLE(): number {
  167. return Engine._ALPHA_DISABLE;
  168. }
  169. public static get ALPHA_ONEONE(): number {
  170. return Engine._ALPHA_ONEONE;
  171. }
  172. public static get ALPHA_ADD(): number {
  173. return Engine._ALPHA_ADD;
  174. }
  175. public static get ALPHA_COMBINE(): number {
  176. return Engine._ALPHA_COMBINE;
  177. }
  178. public static get ALPHA_SUBTRACT(): number {
  179. return Engine._ALPHA_SUBTRACT;
  180. }
  181. public static get ALPHA_MULTIPLY(): number {
  182. return Engine._ALPHA_MULTIPLY;
  183. }
  184. public static get ALPHA_MAXIMIZED(): number {
  185. return Engine._ALPHA_MAXIMIZED;
  186. }
  187. public static get DELAYLOADSTATE_NONE(): number {
  188. return Engine._DELAYLOADSTATE_NONE;
  189. }
  190. public static get DELAYLOADSTATE_LOADED(): number {
  191. return Engine._DELAYLOADSTATE_LOADED;
  192. }
  193. public static get DELAYLOADSTATE_LOADING(): number {
  194. return Engine._DELAYLOADSTATE_LOADING;
  195. }
  196. public static get DELAYLOADSTATE_NOTLOADED(): number {
  197. return Engine._DELAYLOADSTATE_NOTLOADED;
  198. }
  199. public static get TEXTUREFORMAT_ALPHA(): number {
  200. return Engine._TEXTUREFORMAT_ALPHA;
  201. }
  202. public static get TEXTUREFORMAT_LUMINANCE(): number {
  203. return Engine._TEXTUREFORMAT_LUMINANCE;
  204. }
  205. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  206. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  207. }
  208. public static get TEXTUREFORMAT_RGB(): number {
  209. return Engine._TEXTUREFORMAT_RGB;
  210. }
  211. public static get TEXTUREFORMAT_RGBA(): number {
  212. return Engine._TEXTUREFORMAT_RGBA;
  213. }
  214. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  215. return Engine._TEXTURETYPE_UNSIGNED_INT;
  216. }
  217. public static get TEXTURETYPE_FLOAT(): number {
  218. return Engine._TEXTURETYPE_FLOAT;
  219. }
  220. public static get Version(): string {
  221. return "2.4.0-beta";
  222. }
  223. // Updatable statics so stick with vars here
  224. public static CollisionsEpsilon = 0.001;
  225. public static CodeRepository = "src/";
  226. public static ShadersRepository = "src/Shaders/";
  227. // Public members
  228. public isFullscreen = false;
  229. public isPointerLock = false;
  230. public cullBackFaces = true;
  231. public renderEvenInBackground = true;
  232. // To enable/disable IDB support and avoid XHR on .manifest
  233. public enableOfflineSupport = true;
  234. public scenes = new Array<Scene>();
  235. // Private Members
  236. public _gl: WebGLRenderingContext;
  237. private _renderingCanvas: HTMLCanvasElement;
  238. private _windowIsBackground = false;
  239. private _webGLVersion = "1.0";
  240. public static audioEngine: AudioEngine;
  241. private _onBlur: () => void;
  242. private _onFocus: () => void;
  243. private _onFullscreenChange: () => void;
  244. private _onPointerLockChange: () => void;
  245. private _hardwareScalingLevel: number;
  246. private _caps: EngineCapabilities;
  247. private _pointerLockRequested: boolean;
  248. private _alphaTest: boolean;
  249. private _loadingScreen: ILoadingScreen;
  250. private _drawCalls = 0;
  251. private _glVersion: string;
  252. private _glRenderer: string;
  253. private _glVendor: string;
  254. private _videoTextureSupported: boolean;
  255. private _renderingQueueLaunched = false;
  256. private _activeRenderLoops = [];
  257. // FPS
  258. private fpsRange = 60;
  259. private previousFramesDuration = [];
  260. private fps = 60;
  261. private deltaTime = 0;
  262. // States
  263. private _depthCullingState = new Internals._DepthCullingState();
  264. private _alphaState = new Internals._AlphaState();
  265. private _alphaMode = Engine.ALPHA_DISABLE;
  266. // Cache
  267. private _loadedTexturesCache = new Array<WebGLTexture>();
  268. private _maxTextureChannels = 16;
  269. private _activeTexturesCache = new Array<BaseTexture>(this._maxTextureChannels);
  270. private _currentEffect: Effect;
  271. private _compiledEffects = {};
  272. private _vertexAttribArrays: boolean[];
  273. private _cachedViewport: Viewport;
  274. private _cachedVertexBuffers: any;
  275. private _cachedIndexBuffer: WebGLBuffer;
  276. private _cachedEffectForVertexBuffers: Effect;
  277. private _currentRenderTarget: WebGLTexture;
  278. private _uintIndicesCurrentlySet = false;
  279. private _workingCanvas: HTMLCanvasElement;
  280. private _workingContext: CanvasRenderingContext2D;
  281. private _externalData: StringDictionary<Object>;
  282. private _bindedRenderFunction: any;
  283. /**
  284. * @constructor
  285. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  286. * @param {boolean} [antialias] - enable antialias
  287. * @param options - further options to be sent to the getContext function
  288. */
  289. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: { antialias?: boolean, preserveDrawingBuffer?: boolean, limitDeviceRatio?: number }, adaptToDeviceRatio = true) {
  290. this._renderingCanvas = canvas;
  291. this._externalData = new StringDictionary<Object>();
  292. options = options || {};
  293. options.antialias = antialias;
  294. if (options.preserveDrawingBuffer === undefined) {
  295. options.preserveDrawingBuffer = false;
  296. }
  297. // GL
  298. //try {
  299. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  300. // if (this._gl) {
  301. // this._webGLVersion = "2.0";
  302. // }
  303. //} catch (e) {
  304. // // Do nothing
  305. //}
  306. if (!this._gl) {
  307. try {
  308. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  309. } catch (e) {
  310. throw new Error("WebGL not supported");
  311. }
  312. }
  313. if (!this._gl) {
  314. throw new Error("WebGL not supported");
  315. }
  316. this._onBlur = () => {
  317. this._windowIsBackground = true;
  318. };
  319. this._onFocus = () => {
  320. this._windowIsBackground = false;
  321. };
  322. window.addEventListener("blur", this._onBlur);
  323. window.addEventListener("focus", this._onFocus);
  324. // Viewport
  325. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  326. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  327. this.resize();
  328. // Caps
  329. this._caps = new EngineCapabilities();
  330. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  331. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  332. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  333. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  334. // Infos
  335. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  336. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  337. if (rendererInfo != null) {
  338. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  339. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  340. }
  341. if (!this._glVendor) {
  342. this._glVendor = "Unknown vendor";
  343. }
  344. if (!this._glRenderer) {
  345. this._glRenderer = "Unknown renderer";
  346. }
  347. // Extensions
  348. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  349. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  350. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  351. 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');
  352. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  353. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  354. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  355. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  356. this._caps.highPrecisionShaderSupported = true;
  357. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  358. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  359. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  360. if (this._gl.getShaderPrecisionFormat) {
  361. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  362. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  363. }
  364. // Depth buffer
  365. this.setDepthBuffer(true);
  366. this.setDepthFunctionToLessOrEqual();
  367. this.setDepthWrite(true);
  368. // Fullscreen
  369. this._onFullscreenChange = () => {
  370. if (document.fullscreen !== undefined) {
  371. this.isFullscreen = document.fullscreen;
  372. } else if (document.mozFullScreen !== undefined) {
  373. this.isFullscreen = document.mozFullScreen;
  374. } else if (document.webkitIsFullScreen !== undefined) {
  375. this.isFullscreen = document.webkitIsFullScreen;
  376. } else if (document.msIsFullScreen !== undefined) {
  377. this.isFullscreen = document.msIsFullScreen;
  378. }
  379. // Pointer lock
  380. if (this.isFullscreen && this._pointerLockRequested) {
  381. canvas.requestPointerLock = canvas.requestPointerLock ||
  382. canvas.msRequestPointerLock ||
  383. canvas.mozRequestPointerLock ||
  384. canvas.webkitRequestPointerLock;
  385. if (canvas.requestPointerLock) {
  386. canvas.requestPointerLock();
  387. }
  388. }
  389. };
  390. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  391. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  392. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  393. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  394. // Pointer lock
  395. this._onPointerLockChange = () => {
  396. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  397. document.webkitPointerLockElement === canvas ||
  398. document.msPointerLockElement === canvas ||
  399. document.pointerLockElement === canvas
  400. );
  401. };
  402. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  403. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  404. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  405. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  406. if (AudioEngine && !Engine.audioEngine) {
  407. Engine.audioEngine = new AudioEngine();
  408. }
  409. //default loading screen
  410. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas);
  411. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  412. }
  413. public get webGLVersion(): string {
  414. return this._webGLVersion;
  415. }
  416. private _prepareWorkingCanvas(): void {
  417. if (this._workingCanvas) {
  418. return;
  419. }
  420. this._workingCanvas = document.createElement("canvas");
  421. this._workingContext = this._workingCanvas.getContext("2d");
  422. }
  423. public resetTextureCache() {
  424. for (var index = 0; index < this._maxTextureChannels; index++) {
  425. this._activeTexturesCache[index] = null;
  426. }
  427. }
  428. public getGlInfo() {
  429. return {
  430. vendor: this._glVendor,
  431. renderer: this._glRenderer,
  432. version: this._glVersion
  433. }
  434. }
  435. public getAspectRatio(camera: Camera, useScreen = false): number {
  436. var viewport = camera.viewport;
  437. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  438. }
  439. public getRenderWidth(useScreen = false): number {
  440. if (!useScreen && this._currentRenderTarget) {
  441. return this._currentRenderTarget._width;
  442. }
  443. return this._renderingCanvas.width;
  444. }
  445. public getRenderHeight(useScreen = false): number {
  446. if (!useScreen && this._currentRenderTarget) {
  447. return this._currentRenderTarget._height;
  448. }
  449. return this._renderingCanvas.height;
  450. }
  451. public getRenderingCanvas(): HTMLCanvasElement {
  452. return this._renderingCanvas;
  453. }
  454. public getRenderingCanvasClientRect(): ClientRect {
  455. return this._renderingCanvas.getBoundingClientRect();
  456. }
  457. public setHardwareScalingLevel(level: number): void {
  458. this._hardwareScalingLevel = level;
  459. this.resize();
  460. }
  461. public getHardwareScalingLevel(): number {
  462. return this._hardwareScalingLevel;
  463. }
  464. public getLoadedTexturesCache(): WebGLTexture[] {
  465. return this._loadedTexturesCache;
  466. }
  467. public getCaps(): EngineCapabilities {
  468. return this._caps;
  469. }
  470. public get drawCalls(): number {
  471. return this._drawCalls;
  472. }
  473. // Methods
  474. public resetDrawCalls(): void {
  475. this._drawCalls = 0;
  476. }
  477. public getDepthFunction(): number {
  478. return this._depthCullingState.depthFunc;
  479. }
  480. public setDepthFunction(depthFunc: number) {
  481. this._depthCullingState.depthFunc = depthFunc;
  482. }
  483. public setDepthFunctionToGreater(): void {
  484. this._depthCullingState.depthFunc = this._gl.GREATER;
  485. }
  486. public setDepthFunctionToGreaterOrEqual(): void {
  487. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  488. }
  489. public setDepthFunctionToLess(): void {
  490. this._depthCullingState.depthFunc = this._gl.LESS;
  491. }
  492. public setDepthFunctionToLessOrEqual(): void {
  493. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  494. }
  495. /**
  496. * stop executing a render loop function and remove it from the execution array
  497. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  498. */
  499. public stopRenderLoop(renderFunction?: () => void): void {
  500. if (!renderFunction) {
  501. this._activeRenderLoops = [];
  502. return;
  503. }
  504. var index = this._activeRenderLoops.indexOf(renderFunction);
  505. if (index >= 0) {
  506. this._activeRenderLoops.splice(index, 1);
  507. }
  508. }
  509. public _renderLoop(): void {
  510. var shouldRender = true;
  511. if (!this.renderEvenInBackground && this._windowIsBackground) {
  512. shouldRender = false;
  513. }
  514. if (shouldRender) {
  515. // Start new frame
  516. this.beginFrame();
  517. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  518. var renderFunction = this._activeRenderLoops[index];
  519. renderFunction();
  520. }
  521. // Present
  522. this.endFrame();
  523. }
  524. if (this._activeRenderLoops.length > 0) {
  525. // Register new frame
  526. Tools.QueueNewFrame(this._bindedRenderFunction);
  527. } else {
  528. this._renderingQueueLaunched = false;
  529. }
  530. }
  531. /**
  532. * Register and execute a render loop. The engine can have more than one render function.
  533. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  534. * @example
  535. * engine.runRenderLoop(function () {
  536. * scene.render()
  537. * })
  538. */
  539. public runRenderLoop(renderFunction: () => void): void {
  540. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  541. return;
  542. }
  543. this._activeRenderLoops.push(renderFunction);
  544. if (!this._renderingQueueLaunched) {
  545. this._renderingQueueLaunched = true;
  546. this._bindedRenderFunction = this._renderLoop.bind(this);
  547. Tools.QueueNewFrame(this._bindedRenderFunction);
  548. }
  549. }
  550. /**
  551. * Toggle full screen mode.
  552. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  553. */
  554. public switchFullscreen(requestPointerLock: boolean): void {
  555. if (this.isFullscreen) {
  556. Tools.ExitFullscreen();
  557. } else {
  558. this._pointerLockRequested = requestPointerLock;
  559. Tools.RequestFullscreen(this._renderingCanvas);
  560. }
  561. }
  562. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  563. this.applyStates();
  564. if (backBuffer) {
  565. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  566. }
  567. if (depthStencil && this._depthCullingState.depthMask) {
  568. this._gl.clearDepth(1.0);
  569. }
  570. var mode = 0;
  571. if (backBuffer) {
  572. mode |= this._gl.COLOR_BUFFER_BIT;
  573. }
  574. if (depthStencil && this._depthCullingState.depthMask) {
  575. mode |= this._gl.DEPTH_BUFFER_BIT;
  576. }
  577. this._gl.clear(mode);
  578. }
  579. /**
  580. * Set the WebGL's viewport
  581. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  582. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  583. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  584. */
  585. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  586. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  587. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  588. var x = viewport.x || 0;
  589. var y = viewport.y || 0;
  590. this._cachedViewport = viewport;
  591. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  592. }
  593. /**
  594. * Directly set the WebGL Viewport
  595. * The x, y, width & height are directly passed to the WebGL call
  596. * @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.
  597. */
  598. public setDirectViewport(x: number, y: number, width: number, height: number): Viewport {
  599. let currentViewport = this._cachedViewport;
  600. this._cachedViewport = null;
  601. this._gl.viewport(x, y, width, height);
  602. return currentViewport;
  603. }
  604. public beginFrame(): void {
  605. this._measureFps();
  606. }
  607. public endFrame(): void {
  608. //this.flushFramebuffer();
  609. }
  610. /**
  611. * resize the view according to the canvas' size.
  612. * @example
  613. * window.addEventListener("resize", function () {
  614. * engine.resize();
  615. * });
  616. */
  617. public resize(): void {
  618. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  619. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  620. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  621. for (var index = 0; index < this.scenes.length; index++) {
  622. var scene = this.scenes[index];
  623. if (scene.debugLayer.isVisible()) {
  624. scene.debugLayer._syncPositions();
  625. }
  626. }
  627. }
  628. /**
  629. * force a specific size of the canvas
  630. * @param {number} width - the new canvas' width
  631. * @param {number} height - the new canvas' height
  632. */
  633. public setSize(width: number, height: number): void {
  634. this._renderingCanvas.width = width;
  635. this._renderingCanvas.height = height;
  636. for (var index = 0; index < this.scenes.length; index++) {
  637. var scene = this.scenes[index];
  638. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  639. var cam = scene.cameras[camIndex];
  640. cam._currentRenderId = 0;
  641. }
  642. }
  643. }
  644. public bindFramebuffer(texture: WebGLTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number): void {
  645. this._currentRenderTarget = texture;
  646. var gl = this._gl;
  647. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  648. if (texture.isCube) {
  649. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  650. } else {
  651. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  652. }
  653. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  654. this.wipeCaches();
  655. }
  656. public unBindFramebuffer(texture: WebGLTexture, disableGenerateMipMaps = false): void {
  657. this._currentRenderTarget = null;
  658. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  659. var gl = this._gl;
  660. gl.bindTexture(gl.TEXTURE_2D, texture);
  661. gl.generateMipmap(gl.TEXTURE_2D);
  662. gl.bindTexture(gl.TEXTURE_2D, null);
  663. }
  664. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  665. }
  666. public generateMipMapsForCubemap(texture: WebGLTexture) {
  667. if (texture.generateMipMaps) {
  668. var gl = this._gl;
  669. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  670. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  671. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  672. }
  673. }
  674. public flushFramebuffer(): void {
  675. this._gl.flush();
  676. }
  677. public restoreDefaultFramebuffer(): void {
  678. this._currentRenderTarget = null;
  679. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  680. this.setViewport(this._cachedViewport);
  681. this.wipeCaches();
  682. }
  683. // VBOs
  684. private _resetVertexBufferBinding(): void {
  685. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  686. this._cachedVertexBuffers = null;
  687. }
  688. public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  689. var vbo = this._gl.createBuffer();
  690. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  691. if (vertices instanceof Float32Array) {
  692. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  693. } else {
  694. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  695. }
  696. this._resetVertexBufferBinding();
  697. vbo.references = 1;
  698. return vbo;
  699. }
  700. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  701. var vbo = this._gl.createBuffer();
  702. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  703. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  704. this._resetVertexBufferBinding();
  705. vbo.references = 1;
  706. return vbo;
  707. }
  708. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number): void {
  709. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  710. if (offset === undefined) {
  711. offset = 0;
  712. }
  713. if (vertices instanceof Float32Array) {
  714. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  715. } else {
  716. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  717. }
  718. this._resetVertexBufferBinding();
  719. }
  720. private _resetIndexBufferBinding(): void {
  721. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  722. this._cachedIndexBuffer = null;
  723. }
  724. public createIndexBuffer(indices: number[] | Int32Array): WebGLBuffer {
  725. var vbo = this._gl.createBuffer();
  726. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  727. // Check for 32 bits indices
  728. var arrayBuffer;
  729. var need32Bits = false;
  730. if (this._caps.uintIndices) {
  731. for (var index = 0; index < indices.length; index++) {
  732. if (indices[index] > 65535) {
  733. need32Bits = true;
  734. break;
  735. }
  736. }
  737. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  738. } else {
  739. arrayBuffer = new Uint16Array(indices);
  740. }
  741. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  742. this._resetIndexBufferBinding();
  743. vbo.references = 1;
  744. vbo.is32Bits = need32Bits;
  745. return vbo;
  746. }
  747. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  748. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  749. this._cachedVertexBuffers = vertexBuffer;
  750. this._cachedEffectForVertexBuffers = effect;
  751. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  752. var offset = 0;
  753. for (var index = 0; index < vertexDeclaration.length; index++) {
  754. var order = effect.getAttributeLocation(index);
  755. if (order >= 0) {
  756. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  757. }
  758. offset += vertexDeclaration[index] * 4;
  759. }
  760. }
  761. if (this._cachedIndexBuffer !== indexBuffer) {
  762. this._cachedIndexBuffer = indexBuffer;
  763. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  764. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  765. }
  766. }
  767. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  768. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  769. this._cachedVertexBuffers = vertexBuffers;
  770. this._cachedEffectForVertexBuffers = effect;
  771. var attributes = effect.getAttributesNames();
  772. for (var index = 0; index < attributes.length; index++) {
  773. var order = effect.getAttributeLocation(index);
  774. if (order >= 0) {
  775. var vertexBuffer = vertexBuffers[attributes[index]];
  776. if (!vertexBuffer) {
  777. continue;
  778. }
  779. var stride = vertexBuffer.getStrideSize();
  780. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  781. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  782. }
  783. }
  784. }
  785. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  786. this._cachedIndexBuffer = indexBuffer;
  787. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  788. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  789. }
  790. }
  791. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  792. buffer.references--;
  793. if (buffer.references === 0) {
  794. this._gl.deleteBuffer(buffer);
  795. return true;
  796. }
  797. return false;
  798. }
  799. public createInstancesBuffer(capacity: number): WebGLBuffer {
  800. var buffer = this._gl.createBuffer();
  801. buffer.capacity = capacity;
  802. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  803. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  804. return buffer;
  805. }
  806. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  807. this._gl.deleteBuffer(buffer);
  808. }
  809. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  810. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  811. if (data) {
  812. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  813. }
  814. if ((<any>offsetLocations[0]).index !== undefined) {
  815. let stride = 0;
  816. for (let i = 0; i < offsetLocations.length; i++) {
  817. let ai = <InstancingAttributeInfo>offsetLocations[i];
  818. stride += ai.attributeSize * 4;
  819. }
  820. for (let i = 0; i < offsetLocations.length; i++) {
  821. let ai = <InstancingAttributeInfo>offsetLocations[i];
  822. this._gl.enableVertexAttribArray(ai.index);
  823. this._gl.vertexAttribPointer(ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  824. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  825. }
  826. } else {
  827. for (let index = 0; index < 4; index++) {
  828. let offsetLocation = <number>offsetLocations[index];
  829. this._gl.enableVertexAttribArray(offsetLocation);
  830. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  831. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  832. }
  833. }
  834. }
  835. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  836. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  837. if ((<any>offsetLocations[0]).index !== undefined) {
  838. for (let i = 0; i < offsetLocations.length; i++) {
  839. let ai = <InstancingAttributeInfo>offsetLocations[i];
  840. this._gl.disableVertexAttribArray(ai.index);
  841. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 0);
  842. }
  843. } else {
  844. for (let index = 0; index < 4; index++) {
  845. let offsetLocation = <number>offsetLocations[index];
  846. this._gl.disableVertexAttribArray(offsetLocation);
  847. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  848. }
  849. }
  850. }
  851. public applyStates() {
  852. this._depthCullingState.apply(this._gl);
  853. this._alphaState.apply(this._gl);
  854. }
  855. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  856. // Apply states
  857. this.applyStates();
  858. this._drawCalls++;
  859. // Render
  860. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  861. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  862. if (instancesCount) {
  863. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  864. return;
  865. }
  866. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  867. }
  868. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  869. // Apply states
  870. this.applyStates();
  871. this._drawCalls++;
  872. if (instancesCount) {
  873. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  874. return;
  875. }
  876. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  877. }
  878. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  879. // Apply states
  880. this.applyStates();
  881. this._drawCalls++;
  882. if (instancesCount) {
  883. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  884. return;
  885. }
  886. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  887. }
  888. // Shaders
  889. public _releaseEffect(effect: Effect): void {
  890. if (this._compiledEffects[effect._key]) {
  891. delete this._compiledEffects[effect._key];
  892. if (effect.getProgram()) {
  893. this._gl.deleteProgram(effect.getProgram());
  894. }
  895. }
  896. }
  897. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  898. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  899. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  900. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  901. var name = vertex + "+" + fragment + "@" + defines;
  902. if (this._compiledEffects[name]) {
  903. return this._compiledEffects[name];
  904. }
  905. var effect = new Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  906. effect._key = name;
  907. this._compiledEffects[name] = effect;
  908. return effect;
  909. }
  910. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  911. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  912. return this.createEffect(
  913. {
  914. vertex: "particles",
  915. fragmentElement: fragmentName
  916. },
  917. ["position", "color", "options"],
  918. ["view", "projection"].concat(uniformsNames),
  919. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  920. }
  921. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  922. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  923. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  924. var shaderProgram = this._gl.createProgram();
  925. this._gl.attachShader(shaderProgram, vertexShader);
  926. this._gl.attachShader(shaderProgram, fragmentShader);
  927. this._gl.linkProgram(shaderProgram);
  928. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  929. if (!linked) {
  930. var error = this._gl.getProgramInfoLog(shaderProgram);
  931. if (error) {
  932. throw new Error(error);
  933. }
  934. }
  935. this._gl.deleteShader(vertexShader);
  936. this._gl.deleteShader(fragmentShader);
  937. return shaderProgram;
  938. }
  939. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  940. var results = [];
  941. for (var index = 0; index < uniformsNames.length; index++) {
  942. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  943. }
  944. return results;
  945. }
  946. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  947. var results = [];
  948. for (var index = 0; index < attributesNames.length; index++) {
  949. try {
  950. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  951. } catch (e) {
  952. results.push(-1);
  953. }
  954. }
  955. return results;
  956. }
  957. public enableEffect(effect: Effect): void {
  958. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  959. if (effect && effect.onBind) {
  960. effect.onBind(effect);
  961. }
  962. return;
  963. }
  964. this._vertexAttribArrays = this._vertexAttribArrays || [];
  965. // Use program
  966. this._gl.useProgram(effect.getProgram());
  967. for (var i in this._vertexAttribArrays) {
  968. //make sure this is a number)
  969. var iAsNumber = +i;
  970. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  971. continue;
  972. }
  973. this._vertexAttribArrays[iAsNumber] = false;
  974. this._gl.disableVertexAttribArray(iAsNumber);
  975. }
  976. var attributesCount = effect.getAttributesCount();
  977. for (var index = 0; index < attributesCount; index++) {
  978. // Attributes
  979. var order = effect.getAttributeLocation(index);
  980. if (order >= 0) {
  981. this._vertexAttribArrays[order] = true;
  982. this._gl.enableVertexAttribArray(order);
  983. }
  984. }
  985. this._currentEffect = effect;
  986. if (effect.onBind) {
  987. effect.onBind(effect);
  988. }
  989. }
  990. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  991. if (!uniform)
  992. return;
  993. this._gl.uniform1fv(uniform, <any>array);
  994. }
  995. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  996. if (!uniform || array.length % 2 !== 0)
  997. return;
  998. this._gl.uniform2fv(uniform, <any>array);
  999. }
  1000. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  1001. if (!uniform || array.length % 3 !== 0)
  1002. return;
  1003. this._gl.uniform3fv(uniform, <any>array);
  1004. }
  1005. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  1006. if (!uniform || array.length % 4 !== 0)
  1007. return;
  1008. this._gl.uniform4fv(uniform, <any>array);
  1009. }
  1010. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1011. if (!uniform)
  1012. return;
  1013. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1014. }
  1015. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1016. if (!uniform)
  1017. return;
  1018. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1019. }
  1020. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1021. if (!uniform)
  1022. return;
  1023. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1024. }
  1025. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1026. if (!uniform)
  1027. return;
  1028. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1029. }
  1030. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1031. if (!uniform)
  1032. return;
  1033. this._gl.uniform1f(uniform, value);
  1034. }
  1035. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  1036. if (!uniform)
  1037. return;
  1038. this._gl.uniform2f(uniform, x, y);
  1039. }
  1040. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  1041. if (!uniform)
  1042. return;
  1043. this._gl.uniform3f(uniform, x, y, z);
  1044. }
  1045. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  1046. if (!uniform)
  1047. return;
  1048. this._gl.uniform1i(uniform, bool);
  1049. }
  1050. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  1051. if (!uniform)
  1052. return;
  1053. this._gl.uniform4f(uniform, x, y, z, w);
  1054. }
  1055. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  1056. if (!uniform)
  1057. return;
  1058. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1059. }
  1060. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  1061. if (!uniform)
  1062. return;
  1063. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1064. }
  1065. // States
  1066. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1067. // Culling
  1068. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1069. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1070. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1071. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1072. if (culling) {
  1073. this._depthCullingState.cullFace = cullFace;
  1074. this._depthCullingState.cull = true;
  1075. } else {
  1076. this._depthCullingState.cull = false;
  1077. }
  1078. }
  1079. // Z offset
  1080. this._depthCullingState.zOffset = zOffset;
  1081. }
  1082. public setDepthBuffer(enable: boolean): void {
  1083. this._depthCullingState.depthTest = enable;
  1084. }
  1085. public getDepthWrite(): boolean {
  1086. return this._depthCullingState.depthMask;
  1087. }
  1088. public setDepthWrite(enable: boolean): void {
  1089. this._depthCullingState.depthMask = enable;
  1090. }
  1091. public setColorWrite(enable: boolean): void {
  1092. this._gl.colorMask(enable, enable, enable, enable);
  1093. }
  1094. public setAlphaMode(mode: number): void {
  1095. if (this._alphaMode === mode) {
  1096. return;
  1097. }
  1098. switch (mode) {
  1099. case Engine.ALPHA_DISABLE:
  1100. this.setDepthWrite(true);
  1101. this._alphaState.alphaBlend = false;
  1102. break;
  1103. case Engine.ALPHA_COMBINE:
  1104. this.setDepthWrite(false);
  1105. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1106. this._alphaState.alphaBlend = true;
  1107. break;
  1108. case Engine.ALPHA_ONEONE:
  1109. this.setDepthWrite(false);
  1110. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1111. this._alphaState.alphaBlend = true;
  1112. break;
  1113. case Engine.ALPHA_ADD:
  1114. this.setDepthWrite(false);
  1115. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1116. this._alphaState.alphaBlend = true;
  1117. break;
  1118. case Engine.ALPHA_SUBTRACT:
  1119. this.setDepthWrite(false);
  1120. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1121. this._alphaState.alphaBlend = true;
  1122. break;
  1123. case Engine.ALPHA_MULTIPLY:
  1124. this.setDepthWrite(false);
  1125. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1126. this._alphaState.alphaBlend = true;
  1127. break;
  1128. case Engine.ALPHA_MAXIMIZED:
  1129. this.setDepthWrite(false);
  1130. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1131. this._alphaState.alphaBlend = true;
  1132. break;
  1133. }
  1134. this._alphaMode = mode;
  1135. }
  1136. public getAlphaMode(): number {
  1137. return this._alphaMode;
  1138. }
  1139. public setAlphaTesting(enable: boolean): void {
  1140. this._alphaTest = enable;
  1141. }
  1142. public getAlphaTesting(): boolean {
  1143. return this._alphaTest;
  1144. }
  1145. // Textures
  1146. public wipeCaches(): void {
  1147. this.resetTextureCache();
  1148. this._currentEffect = null;
  1149. this._depthCullingState.reset();
  1150. this._alphaState.reset();
  1151. this._cachedVertexBuffers = null;
  1152. this._cachedIndexBuffer = null;
  1153. this._cachedEffectForVertexBuffers = null;
  1154. }
  1155. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  1156. var gl = this._gl;
  1157. gl.bindTexture(gl.TEXTURE_2D, texture);
  1158. var magFilter = gl.NEAREST;
  1159. var minFilter = gl.NEAREST;
  1160. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  1161. magFilter = gl.LINEAR;
  1162. minFilter = gl.LINEAR;
  1163. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  1164. magFilter = gl.LINEAR;
  1165. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1166. }
  1167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1169. gl.bindTexture(gl.TEXTURE_2D, null);
  1170. texture.samplingMode = samplingMode;
  1171. }
  1172. 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 {
  1173. var texture = this._gl.createTexture();
  1174. var extension: string;
  1175. var fromData: any = false;
  1176. if (url.substr(0, 5) === "data:") {
  1177. fromData = true;
  1178. }
  1179. if (!fromData)
  1180. extension = url.substr(url.length - 4, 4).toLowerCase();
  1181. else {
  1182. var oldUrl = url;
  1183. fromData = oldUrl.split(':');
  1184. url = oldUrl;
  1185. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1186. }
  1187. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1188. var isTGA = (extension === ".tga");
  1189. scene._addPendingData(texture);
  1190. texture.url = url;
  1191. texture.noMipmap = noMipmap;
  1192. texture.references = 1;
  1193. texture.samplingMode = samplingMode;
  1194. this._loadedTexturesCache.push(texture);
  1195. var onerror = () => {
  1196. scene._removePendingData(texture);
  1197. if (onError) {
  1198. onError();
  1199. }
  1200. };
  1201. var callback: (arrayBuffer: any) => void;
  1202. if (isTGA) {
  1203. callback = (arrayBuffer) => {
  1204. var data = new Uint8Array(arrayBuffer);
  1205. var header = Internals.TGATools.GetTGAHeader(data);
  1206. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  1207. Internals.TGATools.UploadContent(this._gl, data);
  1208. }, onLoad, samplingMode);
  1209. };
  1210. if (!(fromData instanceof Array))
  1211. Tools.LoadFile(url, arrayBuffer => {
  1212. callback(arrayBuffer);
  1213. }, onerror, scene.database, true);
  1214. else
  1215. callback(buffer);
  1216. } else if (isDDS) {
  1217. callback = (data) => {
  1218. var info = Internals.DDSTools.GetDDSInfo(data);
  1219. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1220. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1221. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1222. }, onLoad, samplingMode);
  1223. };
  1224. if (!(fromData instanceof Array))
  1225. Tools.LoadFile(url, data => {
  1226. callback(data);
  1227. }, onerror, scene.database, true);
  1228. else
  1229. callback(buffer);
  1230. } else {
  1231. var onload = (img) => {
  1232. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1233. var isPot = (img.width === potWidth && img.height === potHeight);
  1234. if (!isPot) {
  1235. this._prepareWorkingCanvas();
  1236. this._workingCanvas.width = potWidth;
  1237. this._workingCanvas.height = potHeight;
  1238. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1239. this._workingContext.imageSmoothingEnabled = false;
  1240. this._workingContext.mozImageSmoothingEnabled = false;
  1241. this._workingContext.oImageSmoothingEnabled = false;
  1242. this._workingContext.webkitImageSmoothingEnabled = false;
  1243. this._workingContext.msImageSmoothingEnabled = false;
  1244. }
  1245. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1246. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1247. this._workingContext.imageSmoothingEnabled = true;
  1248. this._workingContext.mozImageSmoothingEnabled = true;
  1249. this._workingContext.oImageSmoothingEnabled = true;
  1250. this._workingContext.webkitImageSmoothingEnabled = true;
  1251. this._workingContext.msImageSmoothingEnabled = true;
  1252. }
  1253. }
  1254. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1255. }, onLoad, samplingMode);
  1256. };
  1257. if (!(fromData instanceof Array))
  1258. Tools.LoadImage(url, onload, onerror, scene.database);
  1259. else
  1260. Tools.LoadImage(buffer, onload, onerror, scene.database);
  1261. }
  1262. return texture;
  1263. }
  1264. private _getInternalFormat(format: number): number {
  1265. var internalFormat = this._gl.RGBA;
  1266. switch (format) {
  1267. case Engine.TEXTUREFORMAT_ALPHA:
  1268. internalFormat = this._gl.ALPHA;
  1269. break;
  1270. case Engine.TEXTUREFORMAT_LUMINANCE:
  1271. internalFormat = this._gl.LUMINANCE;
  1272. break;
  1273. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1274. internalFormat = this._gl.LUMINANCE_ALPHA;
  1275. break;
  1276. case Engine.TEXTUREFORMAT_RGB:
  1277. internalFormat = this._gl.RGB;
  1278. break;
  1279. case Engine.TEXTUREFORMAT_RGBA:
  1280. internalFormat = this._gl.RGBA;
  1281. break;
  1282. }
  1283. return internalFormat;
  1284. }
  1285. public updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
  1286. var internalFormat = this._getInternalFormat(format);
  1287. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1288. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1289. if (texture._width % 4 !== 0) {
  1290. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  1291. }
  1292. if (compression) {
  1293. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  1294. } else {
  1295. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1296. }
  1297. if (texture.generateMipMaps) {
  1298. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1299. }
  1300. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1301. this.resetTextureCache();
  1302. texture.isReady = true;
  1303. }
  1304. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): WebGLTexture {
  1305. var texture = this._gl.createTexture();
  1306. texture._baseWidth = width;
  1307. texture._baseHeight = height;
  1308. texture._width = width;
  1309. texture._height = height;
  1310. texture.references = 1;
  1311. this.updateRawTexture(texture, data, format, invertY, compression);
  1312. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1313. // Filters
  1314. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1315. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1316. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1317. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1318. texture.samplingMode = samplingMode;
  1319. this._loadedTexturesCache.push(texture);
  1320. return texture;
  1321. }
  1322. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number, forceExponantOfTwo = true): WebGLTexture {
  1323. var texture = this._gl.createTexture();
  1324. texture._baseWidth = width;
  1325. texture._baseHeight = height;
  1326. if (forceExponantOfTwo) {
  1327. width = Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  1328. height = Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  1329. }
  1330. this.resetTextureCache();
  1331. texture._width = width;
  1332. texture._height = height;
  1333. texture.isReady = false;
  1334. texture.generateMipMaps = generateMipMaps;
  1335. texture.references = 1;
  1336. texture.samplingMode = samplingMode;
  1337. this.updateTextureSamplingMode(samplingMode, texture);
  1338. this._loadedTexturesCache.push(texture);
  1339. return texture;
  1340. }
  1341. public updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void {
  1342. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1343. if (texture.isCube) {
  1344. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  1345. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1346. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1347. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1348. } else {
  1349. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1350. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1351. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1352. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1353. }
  1354. }
  1355. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false): void {
  1356. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1357. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1358. if (premulAlpha) {
  1359. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  1360. }
  1361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1362. if (texture.generateMipMaps) {
  1363. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1364. }
  1365. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1366. this.resetTextureCache();
  1367. texture.isReady = true;
  1368. }
  1369. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1370. if (texture._isDisabled) {
  1371. return;
  1372. }
  1373. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1374. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1375. try {
  1376. // Testing video texture support
  1377. if (this._videoTextureSupported === undefined) {
  1378. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1379. if (this._gl.getError() !== 0) {
  1380. this._videoTextureSupported = false;
  1381. } else {
  1382. this._videoTextureSupported = true;
  1383. }
  1384. }
  1385. // Copy video through the current working canvas if video texture is not supported
  1386. if (!this._videoTextureSupported) {
  1387. if (!texture._workingCanvas) {
  1388. texture._workingCanvas = document.createElement("canvas");
  1389. texture._workingContext = texture._workingCanvas.getContext("2d");
  1390. texture._workingCanvas.width = texture._width;
  1391. texture._workingCanvas.height = texture._height;
  1392. }
  1393. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1394. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1395. } else {
  1396. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1397. }
  1398. if (texture.generateMipMaps) {
  1399. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1400. }
  1401. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1402. this.resetTextureCache();
  1403. texture.isReady = true;
  1404. } catch (ex) {
  1405. // Something unexpected
  1406. // Let's disable the texture
  1407. texture._isDisabled = true;
  1408. }
  1409. }
  1410. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1411. // old version had a "generateMipMaps" arg instead of options.
  1412. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1413. // in the same way, generateDepthBuffer is defaulted to true
  1414. var generateMipMaps = false;
  1415. var generateDepthBuffer = true;
  1416. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1417. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1418. if (options !== undefined) {
  1419. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1420. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1421. type = options.type === undefined ? type : options.type;
  1422. if (options.samplingMode !== undefined) {
  1423. samplingMode = options.samplingMode;
  1424. }
  1425. if (type === Engine.TEXTURETYPE_FLOAT) {
  1426. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1427. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1428. }
  1429. }
  1430. var gl = this._gl;
  1431. var texture = gl.createTexture();
  1432. gl.bindTexture(gl.TEXTURE_2D, texture);
  1433. var width = size.width || size;
  1434. var height = size.height || size;
  1435. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1436. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1437. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1438. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1439. }
  1440. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1441. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1442. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1443. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1444. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1445. var depthBuffer: WebGLRenderbuffer;
  1446. // Create the depth buffer
  1447. if (generateDepthBuffer) {
  1448. depthBuffer = gl.createRenderbuffer();
  1449. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1450. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1451. }
  1452. // Create the framebuffer
  1453. var framebuffer = gl.createFramebuffer();
  1454. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1455. if (generateDepthBuffer) {
  1456. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1457. }
  1458. if (generateMipMaps) {
  1459. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1460. }
  1461. // Unbind
  1462. gl.bindTexture(gl.TEXTURE_2D, null);
  1463. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1464. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1465. texture._framebuffer = framebuffer;
  1466. if (generateDepthBuffer) {
  1467. texture._depthBuffer = depthBuffer;
  1468. }
  1469. texture._width = width;
  1470. texture._height = height;
  1471. texture.isReady = true;
  1472. texture.generateMipMaps = generateMipMaps;
  1473. texture.references = 1;
  1474. texture.samplingMode = samplingMode;
  1475. this.resetTextureCache();
  1476. this._loadedTexturesCache.push(texture);
  1477. return texture;
  1478. }
  1479. public createRenderTargetCubeTexture(size: number, options?: any): WebGLTexture {
  1480. var gl = this._gl;
  1481. var texture = gl.createTexture();
  1482. var generateMipMaps = true;
  1483. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1484. if (options !== undefined) {
  1485. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1486. if (options.samplingMode !== undefined) {
  1487. samplingMode = options.samplingMode;
  1488. }
  1489. }
  1490. texture.isCube = true;
  1491. texture.references = 1;
  1492. texture.generateMipMaps = generateMipMaps;
  1493. texture.references = 1;
  1494. texture.samplingMode = samplingMode;
  1495. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1496. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1497. for (var face = 0; face < 6; face++) {
  1498. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  1499. }
  1500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  1501. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  1502. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1504. // Create the depth buffer
  1505. var depthBuffer = gl.createRenderbuffer();
  1506. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1507. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  1508. // Create the framebuffer
  1509. var framebuffer = gl.createFramebuffer();
  1510. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1511. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1512. // Mipmaps
  1513. if (texture.generateMipMaps) {
  1514. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1515. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1516. }
  1517. // Unbind
  1518. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1519. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1520. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1521. texture._framebuffer = framebuffer;
  1522. texture._depthBuffer = depthBuffer;
  1523. this.resetTextureCache();
  1524. texture._width = size;
  1525. texture._height = size;
  1526. texture.isReady = true;
  1527. return texture;
  1528. }
  1529. public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean): WebGLTexture {
  1530. var gl = this._gl;
  1531. var texture = gl.createTexture();
  1532. texture.isCube = true;
  1533. texture.url = rootUrl;
  1534. texture.references = 1;
  1535. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1536. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1537. if (isDDS) {
  1538. Tools.LoadFile(rootUrl, data => {
  1539. var info = Internals.DDSTools.GetDDSInfo(data);
  1540. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1541. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1542. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1543. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1544. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1545. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1546. }
  1547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1551. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1552. this.resetTextureCache();
  1553. texture._width = info.width;
  1554. texture._height = info.height;
  1555. texture.isReady = true;
  1556. }, null, null, true);
  1557. } else {
  1558. cascadeLoad(rootUrl, scene, imgs => {
  1559. var width = Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1560. var height = width;
  1561. this._prepareWorkingCanvas();
  1562. this._workingCanvas.width = width;
  1563. this._workingCanvas.height = height;
  1564. var faces = [
  1565. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1566. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1567. ];
  1568. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1569. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1570. for (var index = 0; index < faces.length; index++) {
  1571. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1572. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1573. }
  1574. if (!noMipmap) {
  1575. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1576. }
  1577. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1578. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1579. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1580. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1581. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1582. this.resetTextureCache();
  1583. texture._width = width;
  1584. texture._height = height;
  1585. texture.isReady = true;
  1586. }, files);
  1587. }
  1588. return texture;
  1589. }
  1590. public updateTextureSize(texture: WebGLTexture, width: number, height: number) {
  1591. texture._width = width;
  1592. texture._height = height;
  1593. texture._size = width * height;
  1594. texture._baseWidth = width;
  1595. texture._baseHeight = height;
  1596. }
  1597. public createRawCubeTexture(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  1598. callback: (ArrayBuffer) => ArrayBufferView[],
  1599. mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][])): WebGLTexture {
  1600. var gl = this._gl;
  1601. var texture = gl.createTexture();
  1602. scene._addPendingData(texture);
  1603. texture.isCube = true;
  1604. texture.references = 1;
  1605. texture.url = url;
  1606. var internalFormat = this._getInternalFormat(format);
  1607. var textureType = gl.UNSIGNED_BYTE;
  1608. if (type === Engine.TEXTURETYPE_FLOAT) {
  1609. textureType = gl.FLOAT;
  1610. }
  1611. var width = size;
  1612. var height = width;
  1613. var isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  1614. texture._width = width;
  1615. texture._height = height;
  1616. var onerror = () => {
  1617. scene._removePendingData(texture);
  1618. };
  1619. var internalCallback = (data) => {
  1620. var rgbeDataArrays = callback(data);
  1621. var facesIndex = [
  1622. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1623. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1624. ];
  1625. width = texture._width;
  1626. height = texture._height;
  1627. isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  1628. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1629. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1630. if (!noMipmap && isPot) {
  1631. if (mipmmapGenerator) {
  1632. var arrayTemp: ArrayBufferView[] = [];
  1633. // Data are known to be in +X +Y +Z -X -Y -Z
  1634. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  1635. arrayTemp.push(rgbeDataArrays[0]); // +X
  1636. arrayTemp.push(rgbeDataArrays[3]); // -X
  1637. arrayTemp.push(rgbeDataArrays[1]); // +Y
  1638. arrayTemp.push(rgbeDataArrays[4]); // -Y
  1639. arrayTemp.push(rgbeDataArrays[2]); // +Z
  1640. arrayTemp.push(rgbeDataArrays[5]); // -Z
  1641. var mipData = mipmmapGenerator(arrayTemp);
  1642. for (var level = 0; level < mipData.length; level++) {
  1643. var mipSize = width >> level;
  1644. // mipData is order in +X -X +Y -Y +Z -Z
  1645. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  1646. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  1647. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  1648. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  1649. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  1650. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  1651. }
  1652. }
  1653. else {
  1654. // Data are known to be in +X +Y +Z -X -Y -Z
  1655. for (var index = 0; index < facesIndex.length; index++) {
  1656. var faceData = rgbeDataArrays[index];
  1657. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  1658. }
  1659. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1660. }
  1661. }
  1662. else {
  1663. noMipmap = true;
  1664. }
  1665. if (textureType == gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  1666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  1667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  1668. }
  1669. else {
  1670. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1672. }
  1673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1674. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1675. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1676. texture.isReady = true;
  1677. this.resetTextureCache();
  1678. scene._removePendingData(texture);
  1679. };
  1680. Tools.LoadFile(url, data => {
  1681. internalCallback(data);
  1682. }, onerror, scene.database, true);
  1683. return texture;
  1684. };
  1685. public _releaseTexture(texture: WebGLTexture): void {
  1686. var gl = this._gl;
  1687. if (texture._framebuffer) {
  1688. gl.deleteFramebuffer(texture._framebuffer);
  1689. }
  1690. if (texture._depthBuffer) {
  1691. gl.deleteRenderbuffer(texture._depthBuffer);
  1692. }
  1693. gl.deleteTexture(texture);
  1694. // Unbind channels
  1695. this.unbindAllTextures();
  1696. var index = this._loadedTexturesCache.indexOf(texture);
  1697. if (index !== -1) {
  1698. this._loadedTexturesCache.splice(index, 1);
  1699. }
  1700. }
  1701. public bindSamplers(effect: Effect): void {
  1702. this._gl.useProgram(effect.getProgram());
  1703. var samplers = effect.getSamplers();
  1704. for (var index = 0; index < samplers.length; index++) {
  1705. var uniform = effect.getUniform(samplers[index]);
  1706. this._gl.uniform1i(uniform, index);
  1707. }
  1708. this._currentEffect = null;
  1709. }
  1710. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1711. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1712. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1713. this._activeTexturesCache[channel] = null;
  1714. }
  1715. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1716. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1717. }
  1718. public unbindAllTextures(): void {
  1719. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1720. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1721. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1722. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1723. this._activeTexturesCache[channel] = null;
  1724. }
  1725. }
  1726. public setTexture(channel: number, texture: BaseTexture): void {
  1727. if (channel < 0) {
  1728. return;
  1729. }
  1730. // Not ready?
  1731. if (!texture || !texture.isReady()) {
  1732. if (this._activeTexturesCache[channel] != null) {
  1733. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1734. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1735. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1736. this._activeTexturesCache[channel] = null;
  1737. }
  1738. return;
  1739. }
  1740. // Video
  1741. var alreadyActivated = false;
  1742. if (texture instanceof VideoTexture) {
  1743. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1744. alreadyActivated = true;
  1745. texture.update();
  1746. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1747. texture.delayLoad();
  1748. return;
  1749. }
  1750. if (this._activeTexturesCache[channel] === texture) {
  1751. return;
  1752. }
  1753. this._activeTexturesCache[channel] = texture;
  1754. var internalTexture = texture.getInternalTexture();
  1755. if (!alreadyActivated) {
  1756. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1757. }
  1758. if (internalTexture.isCube) {
  1759. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1760. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1761. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1762. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1763. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1764. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1765. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1766. }
  1767. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1768. } else {
  1769. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1770. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1771. internalTexture._cachedWrapU = texture.wrapU;
  1772. switch (texture.wrapU) {
  1773. case Texture.WRAP_ADDRESSMODE:
  1774. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1775. break;
  1776. case Texture.CLAMP_ADDRESSMODE:
  1777. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1778. break;
  1779. case Texture.MIRROR_ADDRESSMODE:
  1780. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1781. break;
  1782. }
  1783. }
  1784. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1785. internalTexture._cachedWrapV = texture.wrapV;
  1786. switch (texture.wrapV) {
  1787. case Texture.WRAP_ADDRESSMODE:
  1788. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1789. break;
  1790. case Texture.CLAMP_ADDRESSMODE:
  1791. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1792. break;
  1793. case Texture.MIRROR_ADDRESSMODE:
  1794. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1795. break;
  1796. }
  1797. }
  1798. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1799. }
  1800. }
  1801. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1802. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1803. var value = texture.anisotropicFilteringLevel;
  1804. if (texture.getInternalTexture().samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1805. value = 1;
  1806. }
  1807. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  1808. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  1809. texture._cachedAnisotropicFilteringLevel = value;
  1810. }
  1811. }
  1812. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1813. var data = new Uint8Array(height * width * 4);
  1814. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1815. return data;
  1816. }
  1817. /**
  1818. * Add an externaly attached data from its key.
  1819. * This method call will fail and return false, if such key already exists.
  1820. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  1821. * @param key the unique key that identifies the data
  1822. * @param data the data object to associate to the key for this Engine instance
  1823. * @return true if no such key were already present and the data was added successfully, false otherwise
  1824. */
  1825. public addExternalData<T>(key: string, data: T): boolean {
  1826. return this._externalData.add(key, data);
  1827. }
  1828. /**
  1829. * Get an externaly attached data from its key
  1830. * @param key the unique key that identifies the data
  1831. * @return the associated data, if present (can be null), or undefined if not present
  1832. */
  1833. public getExternalData<T>(key: string): T {
  1834. return <T>this._externalData.get(key);
  1835. }
  1836. /**
  1837. * Get an externaly attached data from its key, create it using a factory if it's not already present
  1838. * @param key the unique key that identifies the data
  1839. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  1840. * @return the associated data, can be null if the factory returned null.
  1841. */
  1842. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  1843. return <T>this._externalData.getOrAddWithFactory(key, factory);
  1844. }
  1845. /**
  1846. * Remove an externaly attached data from the Engine instance
  1847. * @param key the unique key that identifies the data
  1848. * @return true if the data was successfully removed, false if it doesn't exist
  1849. */
  1850. public removeExternalData(key): boolean {
  1851. return this._externalData.remove(key);
  1852. }
  1853. public releaseInternalTexture(texture: WebGLTexture): void {
  1854. if (!texture) {
  1855. return;
  1856. }
  1857. texture.references--;
  1858. // Final reference ?
  1859. if (texture.references === 0) {
  1860. var texturesCache = this.getLoadedTexturesCache();
  1861. var index = texturesCache.indexOf(texture);
  1862. if (index > -1) {
  1863. texturesCache.splice(index, 1);
  1864. }
  1865. this._releaseTexture(texture);
  1866. }
  1867. }
  1868. // Dispose
  1869. public dispose(): void {
  1870. this.hideLoadingUI();
  1871. this.stopRenderLoop();
  1872. // Release scenes
  1873. while (this.scenes.length) {
  1874. this.scenes[0].dispose();
  1875. }
  1876. // Release audio engine
  1877. Engine.audioEngine.dispose();
  1878. // Release effects
  1879. for (var name in this._compiledEffects) {
  1880. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1881. }
  1882. // Unbind
  1883. for (var i in this._vertexAttribArrays) {
  1884. //making sure this is a string
  1885. var iAsNumber = +i;
  1886. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  1887. continue;
  1888. }
  1889. this._gl.disableVertexAttribArray(iAsNumber);
  1890. }
  1891. this._gl = null;
  1892. // Events
  1893. window.removeEventListener("blur", this._onBlur);
  1894. window.removeEventListener("focus", this._onFocus);
  1895. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1896. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1897. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1898. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1899. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1900. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1901. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1902. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1903. }
  1904. // Loading screen
  1905. public displayLoadingUI(): void {
  1906. this._loadingScreen.displayLoadingUI();
  1907. }
  1908. public hideLoadingUI(): void {
  1909. this._loadingScreen.hideLoadingUI();
  1910. }
  1911. public get loadingScreen(): ILoadingScreen {
  1912. return this._loadingScreen;
  1913. }
  1914. public set loadingScreen(loadingScreen: ILoadingScreen) {
  1915. this._loadingScreen = loadingScreen;
  1916. }
  1917. public set loadingUIText(text: string) {
  1918. this._loadingScreen.loadingUIText = text;
  1919. }
  1920. public set loadingUIBackgroundColor(color: string) {
  1921. this._loadingScreen.loadingUIBackgroundColor = color;
  1922. }
  1923. // FPS
  1924. public getFps(): number {
  1925. return this.fps;
  1926. }
  1927. public getDeltaTime(): number {
  1928. return this.deltaTime;
  1929. }
  1930. private _measureFps(): void {
  1931. this.previousFramesDuration.push(Tools.Now);
  1932. var length = this.previousFramesDuration.length;
  1933. if (length >= 2) {
  1934. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  1935. }
  1936. if (length >= this.fpsRange) {
  1937. if (length > this.fpsRange) {
  1938. this.previousFramesDuration.splice(0, 1);
  1939. length = this.previousFramesDuration.length;
  1940. }
  1941. var sum = 0;
  1942. for (var id = 0; id < length - 1; id++) {
  1943. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  1944. }
  1945. this.fps = 1000.0 / (sum / (length - 1));
  1946. }
  1947. }
  1948. // Statics
  1949. public static isSupported(): boolean {
  1950. try {
  1951. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1952. if (navigator.isCocoonJS) {
  1953. return true;
  1954. }
  1955. var tempcanvas = document.createElement("canvas");
  1956. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1957. return gl != null && !!window.WebGLRenderingContext;
  1958. } catch (e) {
  1959. return false;
  1960. }
  1961. }
  1962. }
  1963. }