babylon.engine.ts 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  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 getExponantOfTwo = (value: number, max: number): number => {
  12. var count = 1;
  13. do {
  14. count *= 2;
  15. } while (count < value);
  16. if (count > max)
  17. count = max;
  18. return count;
  19. };
  20. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  21. processFunction: (width: number, height: number) => void) => {
  22. var engine = scene.getEngine();
  23. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  24. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  25. gl.bindTexture(gl.TEXTURE_2D, texture);
  26. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  27. processFunction(potWidth, potHeight);
  28. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  29. if (noMipmap) {
  30. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  31. } else {
  32. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
  33. if (!isCompressed) {
  34. gl.generateMipmap(gl.TEXTURE_2D);
  35. }
  36. }
  37. gl.bindTexture(gl.TEXTURE_2D, null);
  38. engine._activeTexturesCache = [];
  39. texture._baseWidth = width;
  40. texture._baseHeight = height;
  41. texture._width = potWidth;
  42. texture._height = potHeight;
  43. texture.isReady = true;
  44. scene._removePendingData(texture);
  45. };
  46. // ANY
  47. var cascadeLoad = (rootUrl: string, index: number, loadedImages: HTMLImageElement[], scene,
  48. onfinish: (images: HTMLImageElement[]) => void, extensions: string[]) => {
  49. var img: HTMLImageElement;
  50. var onload = () => {
  51. loadedImages.push(img);
  52. scene._removePendingData(img);
  53. if (index != extensions.length - 1) {
  54. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  55. } else {
  56. onfinish(loadedImages);
  57. }
  58. };
  59. var onerror = () => {
  60. scene._removePendingData(img);
  61. };
  62. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  63. scene._addPendingData(img);
  64. };
  65. export class EngineCapabilities {
  66. public maxTexturesImageUnits: number;
  67. public maxTextureSize: number;
  68. public maxCubemapTextureSize: number;
  69. public maxRenderTextureSize: number;
  70. public standardDerivatives: boolean;
  71. public s3tc;
  72. public textureFloat: boolean;
  73. public textureAnisotropicFilterExtension;
  74. public maxAnisotropy: number;
  75. public instancedArrays;
  76. }
  77. export class Engine {
  78. // Const statics
  79. private static _ALPHA_DISABLE = 0;
  80. private static _ALPHA_ADD = 1;
  81. private static _ALPHA_COMBINE = 2;
  82. private static _DELAYLOADSTATE_NONE = 0;
  83. private static _DELAYLOADSTATE_LOADED = 1;
  84. private static _DELAYLOADSTATE_LOADING = 2;
  85. private static _DELAYLOADSTATE_NOTLOADED = 4;
  86. public static get ALPHA_DISABLE(): number {
  87. return Engine._ALPHA_DISABLE;
  88. }
  89. public static get ALPHA_ADD(): number {
  90. return Engine._ALPHA_ADD;
  91. }
  92. public static get ALPHA_COMBINE(): number {
  93. return Engine._ALPHA_COMBINE;
  94. }
  95. public static get DELAYLOADSTATE_NONE(): number {
  96. return Engine._DELAYLOADSTATE_NONE;
  97. }
  98. public static get DELAYLOADSTATE_LOADED(): number {
  99. return Engine._DELAYLOADSTATE_LOADED;
  100. }
  101. public static get DELAYLOADSTATE_LOADING(): number {
  102. return Engine._DELAYLOADSTATE_LOADING;
  103. }
  104. public static get DELAYLOADSTATE_NOTLOADED(): number {
  105. return Engine._DELAYLOADSTATE_NOTLOADED;
  106. }
  107. // Updatable statics so stick with vars here
  108. public static Epsilon = 0.001;
  109. public static CollisionsEpsilon = 0.001;
  110. public static ShadersRepository = "Babylon/Shaders/";
  111. // Public members
  112. public isFullscreen = false;
  113. public isPointerLock = false;
  114. public forceWireframe = false;
  115. public cullBackFaces = true;
  116. public renderEvenInBackground = true;
  117. public scenes = new Array<Scene>();
  118. // Private Members
  119. private _gl: WebGLRenderingContext;
  120. private _renderingCanvas: HTMLCanvasElement;
  121. private _windowIsBackground = false;
  122. private _onBlur: () => void;
  123. private _onFocus: () => void;
  124. private _onFullscreenChange: () => void;
  125. private _onPointerLockChange: () => void;
  126. private _hardwareScalingLevel: number;
  127. private _caps: EngineCapabilities;
  128. private _pointerLockRequested: boolean;
  129. private _alphaTest: boolean;
  130. private _runningLoop = false;
  131. private _renderFunction: () => void;
  132. // Cache
  133. private _loadedTexturesCache = new Array<WebGLTexture>();
  134. public _activeTexturesCache = new Array<BaseTexture>();
  135. private _currentEffect: Effect;
  136. private _cullingState: boolean;
  137. private _compiledEffects = {};
  138. private _vertexAttribArrays: boolean[];
  139. private _depthMask = false;
  140. private _cachedViewport: Viewport;
  141. private _cachedVertexBuffers: any;
  142. private _cachedIndexBuffer: WebGLBuffer;
  143. private _cachedEffectForVertexBuffers: Effect;
  144. private _currentRenderTarget: WebGLTexture;
  145. private _workingCanvas: HTMLCanvasElement;
  146. private _workingContext: CanvasRenderingContext2D;
  147. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?) {
  148. this._renderingCanvas = canvas;
  149. options = options || {};
  150. options.antialias = antialias;
  151. // GL
  152. try {
  153. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  154. } catch (e) {
  155. throw new Error("WebGL not supported");
  156. }
  157. if (!this._gl) {
  158. throw new Error("WebGL not supported");
  159. }
  160. this._onBlur = () => {
  161. this._windowIsBackground = true;
  162. };
  163. this._onFocus = () => {
  164. this._windowIsBackground = false;
  165. };
  166. window.addEventListener("blur", this._onBlur);
  167. window.addEventListener("focus", this._onFocus);
  168. // Textures
  169. this._workingCanvas = document.createElement("canvas");
  170. this._workingContext = this._workingCanvas.getContext("2d");
  171. // Viewport
  172. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  173. this.resize();
  174. // Caps
  175. this._caps = new EngineCapabilities();
  176. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  177. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  178. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  179. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  180. // Extensions
  181. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  182. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  183. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  184. 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');
  185. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  186. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  187. // Depth buffer
  188. this.setDepthBuffer(true);
  189. this.setDepthFunctionToLessOrEqual();
  190. this.setDepthWrite(true);
  191. // Fullscreen
  192. this._onFullscreenChange = () => {
  193. if (document.fullscreen !== undefined) {
  194. this.isFullscreen = document.fullscreen;
  195. } else if (document.mozFullScreen !== undefined) {
  196. this.isFullscreen = document.mozFullScreen;
  197. } else if (document.webkitIsFullScreen !== undefined) {
  198. this.isFullscreen = document.webkitIsFullScreen;
  199. } else if (document.msIsFullScreen !== undefined) {
  200. this.isFullscreen = document.msIsFullScreen;
  201. }
  202. // Pointer lock
  203. if (this.isFullscreen && this._pointerLockRequested) {
  204. canvas.requestPointerLock = canvas.requestPointerLock ||
  205. canvas.msRequestPointerLock ||
  206. canvas.mozRequestPointerLock ||
  207. canvas.webkitRequestPointerLock;
  208. if (canvas.requestPointerLock) {
  209. canvas.requestPointerLock();
  210. }
  211. }
  212. };
  213. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  214. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  215. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  216. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  217. // Pointer lock
  218. this._onPointerLockChange = () => {
  219. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  220. document.webkitPointerLockElement === canvas ||
  221. document.msPointerLockElement === canvas ||
  222. document.pointerLockElement === canvas
  223. );
  224. };
  225. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  226. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  227. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  228. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  229. }
  230. public getAspectRatio(camera: Camera): number {
  231. var viewport = camera.viewport;
  232. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  233. }
  234. public getRenderWidth(): number {
  235. if (this._currentRenderTarget) {
  236. return this._currentRenderTarget._width;
  237. }
  238. return this._renderingCanvas.width;
  239. }
  240. public getRenderHeight(): number {
  241. if (this._currentRenderTarget) {
  242. return this._currentRenderTarget._height;
  243. }
  244. return this._renderingCanvas.height;
  245. }
  246. public getRenderingCanvas(): HTMLCanvasElement {
  247. return this._renderingCanvas;
  248. }
  249. public setHardwareScalingLevel(level: number): void {
  250. this._hardwareScalingLevel = level;
  251. this.resize();
  252. }
  253. public getHardwareScalingLevel(): number {
  254. return this._hardwareScalingLevel;
  255. }
  256. public getLoadedTexturesCache(): WebGLTexture[] {
  257. return this._loadedTexturesCache;
  258. }
  259. public getCaps(): EngineCapabilities {
  260. return this._caps;
  261. }
  262. // Methods
  263. public setDepthFunctionToGreater(): void {
  264. this._gl.depthFunc(this._gl.GREATER);
  265. }
  266. public setDepthFunctionToGreaterOrEqual(): void {
  267. this._gl.depthFunc(this._gl.GEQUAL);
  268. }
  269. public setDepthFunctionToLess(): void {
  270. this._gl.depthFunc(this._gl.LESS);
  271. }
  272. public setDepthFunctionToLessOrEqual(): void {
  273. this._gl.depthFunc(this._gl.LEQUAL);
  274. }
  275. public stopRenderLoop(): void {
  276. this._renderFunction = null;
  277. this._runningLoop = false;
  278. }
  279. public _renderLoop(): void {
  280. var shouldRender = true;
  281. if (!this.renderEvenInBackground && this._windowIsBackground) {
  282. shouldRender = false;
  283. }
  284. if (shouldRender) {
  285. // Start new frame
  286. this.beginFrame();
  287. if (this._renderFunction) {
  288. this._renderFunction();
  289. }
  290. // Present
  291. this.endFrame();
  292. }
  293. if (this._runningLoop) {
  294. // Register new frame
  295. BABYLON.Tools.QueueNewFrame(() => {
  296. this._renderLoop();
  297. });
  298. }
  299. }
  300. public runRenderLoop(renderFunction: () => void): void {
  301. this._runningLoop = true;
  302. this._renderFunction = renderFunction;
  303. BABYLON.Tools.QueueNewFrame(() => {
  304. this._renderLoop();
  305. });
  306. }
  307. public switchFullscreen(requestPointerLock: boolean): void {
  308. if (this.isFullscreen) {
  309. BABYLON.Tools.ExitFullscreen();
  310. } else {
  311. this._pointerLockRequested = requestPointerLock;
  312. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  313. }
  314. }
  315. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  316. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  317. if (this._depthMask) {
  318. this._gl.clearDepth(1.0);
  319. }
  320. var mode = 0;
  321. if (backBuffer)
  322. mode |= this._gl.COLOR_BUFFER_BIT;
  323. if (depthStencil && this._depthMask)
  324. mode |= this._gl.DEPTH_BUFFER_BIT;
  325. this._gl.clear(mode);
  326. }
  327. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  328. var width = requiredWidth || this._renderingCanvas.width;
  329. var height = requiredHeight || this._renderingCanvas.height;
  330. var x = viewport.x || 0;
  331. var y = viewport.y || 0;
  332. this._cachedViewport = viewport;
  333. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  334. }
  335. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  336. this._cachedViewport = null;
  337. this._gl.viewport(x, y, width, height);
  338. }
  339. public beginFrame(): void {
  340. BABYLON.Tools._MeasureFps();
  341. }
  342. public endFrame(): void {
  343. this.flushFramebuffer();
  344. }
  345. public resize(): void {
  346. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  347. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  348. }
  349. public bindFramebuffer(texture: WebGLTexture): void {
  350. this._currentRenderTarget = texture;
  351. var gl = this._gl;
  352. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  353. this._gl.viewport(0, 0, texture._width, texture._height);
  354. this.wipeCaches();
  355. }
  356. public unBindFramebuffer(texture: WebGLTexture): void {
  357. this._currentRenderTarget = null;
  358. if (texture.generateMipMaps) {
  359. var gl = this._gl;
  360. gl.bindTexture(gl.TEXTURE_2D, texture);
  361. gl.generateMipmap(gl.TEXTURE_2D);
  362. gl.bindTexture(gl.TEXTURE_2D, null);
  363. }
  364. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  365. }
  366. public flushFramebuffer(): void {
  367. this._gl.flush();
  368. }
  369. public restoreDefaultFramebuffer(): void {
  370. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  371. this.setViewport(this._cachedViewport);
  372. this.wipeCaches();
  373. }
  374. // VBOs
  375. private _resetVertexBufferBinding(): void {
  376. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  377. this._cachedVertexBuffers = null;
  378. }
  379. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  380. var vbo = this._gl.createBuffer();
  381. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  382. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  383. this._resetVertexBufferBinding();
  384. vbo.references = 1;
  385. return vbo;
  386. }
  387. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  388. var vbo = this._gl.createBuffer();
  389. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  390. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  391. this._resetVertexBufferBinding();
  392. vbo.references = 1;
  393. return vbo;
  394. }
  395. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, length?: number): void {
  396. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  397. //if (length && length != vertices.length) {
  398. // this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices, 0, length));
  399. //} else {
  400. if (vertices instanceof Float32Array) {
  401. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  402. } else {
  403. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  404. }
  405. // }
  406. this._resetVertexBufferBinding();
  407. }
  408. private _resetIndexBufferBinding(): void {
  409. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  410. this._cachedIndexBuffer = null;
  411. }
  412. public createIndexBuffer(indices: number[]): WebGLBuffer {
  413. var vbo = this._gl.createBuffer();
  414. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  415. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  416. this._resetIndexBufferBinding();
  417. vbo.references = 1;
  418. return vbo;
  419. }
  420. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  421. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  422. this._cachedVertexBuffers = vertexBuffer;
  423. this._cachedEffectForVertexBuffers = effect;
  424. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  425. var offset = 0;
  426. for (var index = 0; index < vertexDeclaration.length; index++) {
  427. var order = effect.getAttributeLocation(index);
  428. if (order >= 0) {
  429. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  430. }
  431. offset += vertexDeclaration[index] * 4;
  432. }
  433. }
  434. if (this._cachedIndexBuffer !== indexBuffer) {
  435. this._cachedIndexBuffer = indexBuffer;
  436. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  437. }
  438. }
  439. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  440. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  441. this._cachedVertexBuffers = vertexBuffers;
  442. this._cachedEffectForVertexBuffers = effect;
  443. var attributes = effect.getAttributesNames();
  444. for (var index = 0; index < attributes.length; index++) {
  445. var order = effect.getAttributeLocation(index);
  446. if (order >= 0) {
  447. var vertexBuffer = vertexBuffers[attributes[index]];
  448. if (!vertexBuffer) {
  449. continue;
  450. }
  451. var stride = vertexBuffer.getStrideSize();
  452. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  453. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  454. }
  455. }
  456. }
  457. if (this._cachedIndexBuffer !== indexBuffer) {
  458. this._cachedIndexBuffer = indexBuffer;
  459. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  460. }
  461. }
  462. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  463. buffer.references--;
  464. if (buffer.references === 0) {
  465. this._gl.deleteBuffer(buffer);
  466. return true;
  467. }
  468. return false;
  469. }
  470. public createInstancesBuffer(capacity: number): WebGLBuffer {
  471. var buffer = this._gl.createBuffer();
  472. buffer.capacity = capacity;
  473. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  474. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  475. return buffer;
  476. }
  477. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  478. this._gl.deleteBuffer(buffer);
  479. }
  480. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  481. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  482. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  483. for (var index = 0; index < 4; index++) {
  484. var offsetLocation = offsetLocations[index];
  485. this._gl.enableVertexAttribArray(offsetLocation);
  486. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  487. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  488. }
  489. }
  490. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  491. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  492. for (var index = 0; index < 4; index++) {
  493. var offsetLocation = offsetLocations[index];
  494. this._gl.disableVertexAttribArray(offsetLocation);
  495. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  496. }
  497. }
  498. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  499. if (instancesCount) {
  500. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  501. return;
  502. }
  503. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  504. }
  505. // Shaders
  506. public _releaseEffect(effect: Effect): void {
  507. if (this._compiledEffects[effect._key]) {
  508. delete this._compiledEffects[effect._key];
  509. if (effect.getProgram()) {
  510. this._gl.deleteProgram(effect.getProgram());
  511. }
  512. }
  513. }
  514. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, optionalDefines?: string[],
  515. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  516. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  517. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  518. var name = vertex + "+" + fragment + "@" + defines;
  519. if (this._compiledEffects[name]) {
  520. return this._compiledEffects[name];
  521. }
  522. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, optionalDefines, onCompiled, onError);
  523. effect._key = name;
  524. this._compiledEffects[name] = effect;
  525. return effect;
  526. }
  527. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  528. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  529. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  530. var shaderProgram = this._gl.createProgram();
  531. this._gl.attachShader(shaderProgram, vertexShader);
  532. this._gl.attachShader(shaderProgram, fragmentShader);
  533. this._gl.linkProgram(shaderProgram);
  534. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  535. if (!linked) {
  536. var error = this._gl.getProgramInfoLog(shaderProgram);
  537. if (error) {
  538. throw new Error(error);
  539. }
  540. }
  541. this._gl.deleteShader(vertexShader);
  542. this._gl.deleteShader(fragmentShader);
  543. return shaderProgram;
  544. }
  545. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  546. var results = [];
  547. for (var index = 0; index < uniformsNames.length; index++) {
  548. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  549. }
  550. return results;
  551. }
  552. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  553. var results = [];
  554. for (var index = 0; index < attributesNames.length; index++) {
  555. try {
  556. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  557. } catch (e) {
  558. results.push(-1);
  559. }
  560. }
  561. return results;
  562. }
  563. public enableEffect(effect: Effect): void {
  564. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  565. return;
  566. }
  567. this._vertexAttribArrays = this._vertexAttribArrays || [];
  568. // Use program
  569. this._gl.useProgram(effect.getProgram());
  570. for (var i in this._vertexAttribArrays) {
  571. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  572. continue;
  573. }
  574. this._vertexAttribArrays[i] = false;
  575. this._gl.disableVertexAttribArray(i);
  576. }
  577. var attributesCount = effect.getAttributesCount();
  578. for (var index = 0; index < attributesCount; index++) {
  579. // Attributes
  580. var order = effect.getAttributeLocation(index);
  581. if (order >= 0) {
  582. this._vertexAttribArrays[order] = true;
  583. this._gl.enableVertexAttribArray(order);
  584. }
  585. }
  586. this._currentEffect = effect;
  587. }
  588. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  589. if (!uniform)
  590. return;
  591. this._gl.uniform1fv(uniform, array);
  592. }
  593. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  594. if (!uniform)
  595. return;
  596. this._gl.uniformMatrix4fv(uniform, false, matrices);
  597. }
  598. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  599. if (!uniform)
  600. return;
  601. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  602. }
  603. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  604. if (!uniform)
  605. return;
  606. this._gl.uniform1f(uniform, value);
  607. }
  608. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  609. if (!uniform)
  610. return;
  611. this._gl.uniform2f(uniform, x, y);
  612. }
  613. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  614. if (!uniform)
  615. return;
  616. this._gl.uniform3f(uniform, x, y, z);
  617. }
  618. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  619. if (!uniform)
  620. return;
  621. this._gl.uniform1i(uniform, bool);
  622. }
  623. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  624. if (!uniform)
  625. return;
  626. this._gl.uniform4f(uniform, x, y, z, w);
  627. }
  628. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  629. if (!uniform)
  630. return;
  631. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  632. }
  633. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  634. if (!uniform)
  635. return;
  636. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  637. }
  638. // States
  639. public setState(culling: boolean): void {
  640. // Culling
  641. if (this._cullingState !== culling) {
  642. if (culling) {
  643. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  644. this._gl.enable(this._gl.CULL_FACE);
  645. } else {
  646. this._gl.disable(this._gl.CULL_FACE);
  647. }
  648. this._cullingState = culling;
  649. }
  650. }
  651. public setDepthBuffer(enable: boolean): void {
  652. if (enable) {
  653. this._gl.enable(this._gl.DEPTH_TEST);
  654. } else {
  655. this._gl.disable(this._gl.DEPTH_TEST);
  656. }
  657. }
  658. public setDepthWrite(enable: boolean): void {
  659. this._gl.depthMask(enable);
  660. this._depthMask = enable;
  661. }
  662. public setColorWrite(enable: boolean): void {
  663. this._gl.colorMask(enable, enable, enable, enable);
  664. }
  665. public setAlphaMode(mode: number): void {
  666. switch (mode) {
  667. case BABYLON.Engine.ALPHA_DISABLE:
  668. this.setDepthWrite(true);
  669. this._gl.disable(this._gl.BLEND);
  670. break;
  671. case BABYLON.Engine.ALPHA_COMBINE:
  672. this.setDepthWrite(false);
  673. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  674. this._gl.enable(this._gl.BLEND);
  675. break;
  676. case BABYLON.Engine.ALPHA_ADD:
  677. this.setDepthWrite(false);
  678. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  679. this._gl.enable(this._gl.BLEND);
  680. break;
  681. }
  682. }
  683. public setAlphaTesting(enable: boolean): void {
  684. this._alphaTest = enable;
  685. }
  686. public getAlphaTesting(): boolean {
  687. return this._alphaTest;
  688. }
  689. // Textures
  690. public wipeCaches(): void {
  691. this._activeTexturesCache = [];
  692. this._currentEffect = null;
  693. this._cullingState = null;
  694. this._cachedVertexBuffers = null;
  695. this._cachedIndexBuffer = null;
  696. this._cachedEffectForVertexBuffers = null;
  697. }
  698. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  699. var gl = this._gl;
  700. gl.bindTexture(gl.TEXTURE_2D, texture);
  701. var magFilter = gl.NEAREST;
  702. var minFilter = gl.NEAREST;
  703. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  704. magFilter = gl.LINEAR;
  705. minFilter = gl.LINEAR;
  706. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  707. magFilter = gl.LINEAR;
  708. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  709. }
  710. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  712. gl.bindTexture(gl.TEXTURE_2D, null);
  713. }
  714. public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene): WebGLTexture {
  715. var texture = this._gl.createTexture();
  716. var extension = url.substr(url.length - 4, 4).toLowerCase();
  717. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  718. var isTGA = (extension === ".tga");
  719. scene._addPendingData(texture);
  720. texture.url = url;
  721. texture.noMipmap = noMipmap;
  722. texture.references = 1;
  723. this._loadedTexturesCache.push(texture);
  724. if (isTGA) {
  725. BABYLON.Tools.LoadFile(url, arrayBuffer => {
  726. var data = new Uint8Array(arrayBuffer);
  727. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  728. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  729. Internals.TGATools.UploadContent(this._gl, data);
  730. });
  731. }, null, scene.database, true);
  732. } else if (isDDS) {
  733. BABYLON.Tools.LoadFile(url, data => {
  734. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  735. var loadMipmap = info.mipmapCount > 1 && !noMipmap;
  736. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, true, () => {
  737. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, loadMipmap);
  738. });
  739. }, null, scene.database, true);
  740. } else {
  741. var onload = (img) => {
  742. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  743. var isPot = (img.width == potWidth && img.height == potHeight);
  744. if (!isPot) {
  745. this._workingCanvas.width = potWidth;
  746. this._workingCanvas.height = potHeight;
  747. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  748. }
  749. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  750. });
  751. };
  752. var onerror = () => {
  753. scene._removePendingData(texture);
  754. };
  755. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  756. }
  757. return texture;
  758. }
  759. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean): WebGLTexture {
  760. var texture = this._gl.createTexture();
  761. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  762. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  763. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  764. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
  765. if (!generateMipMaps) {
  766. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
  767. } else {
  768. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR_MIPMAP_LINEAR);
  769. }
  770. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  771. this._activeTexturesCache = [];
  772. texture._baseWidth = width;
  773. texture._baseHeight = height;
  774. texture._width = width;
  775. texture._height = height;
  776. texture.isReady = false;
  777. texture.generateMipMaps = generateMipMaps;
  778. texture.references = 1;
  779. this._loadedTexturesCache.push(texture);
  780. return texture;
  781. }
  782. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  783. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  784. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  785. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  786. if (texture.generateMipMaps) {
  787. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  788. }
  789. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  790. this._activeTexturesCache = [];
  791. texture.isReady = true;
  792. }
  793. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  794. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  795. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  796. // Scale the video if it is a NPOT using the current working canvas
  797. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  798. if (!texture._workingCanvas) {
  799. texture._workingCanvas = document.createElement("canvas");
  800. texture._workingContext = texture._workingCanvas.getContext("2d");
  801. texture._workingCanvas.width = texture._width;
  802. texture._workingCanvas.height = texture._height;
  803. }
  804. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  805. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  806. } else {
  807. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  808. }
  809. if (texture.generateMipMaps) {
  810. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  811. }
  812. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  813. this._activeTexturesCache = [];
  814. texture.isReady = true;
  815. }
  816. public createRenderTargetTexture(size: any, options): WebGLTexture {
  817. // old version had a "generateMipMaps" arg instead of options.
  818. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  819. // in the same way, generateDepthBuffer is defaulted to true
  820. var generateMipMaps = false;
  821. var generateDepthBuffer = true;
  822. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  823. if (options !== undefined) {
  824. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  825. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  826. if (options.samplingMode !== undefined) {
  827. samplingMode = options.samplingMode;
  828. }
  829. }
  830. var gl = this._gl;
  831. var texture = gl.createTexture();
  832. gl.bindTexture(gl.TEXTURE_2D, texture);
  833. var width = size.width || size;
  834. var height = size.height || size;
  835. var magFilter = gl.NEAREST;
  836. var minFilter = gl.NEAREST;
  837. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  838. magFilter = gl.LINEAR;
  839. if (generateMipMaps) {
  840. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  841. } else {
  842. minFilter = gl.LINEAR;
  843. }
  844. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  845. magFilter = gl.LINEAR;
  846. if (generateMipMaps) {
  847. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  848. } else {
  849. minFilter = gl.LINEAR;
  850. }
  851. }
  852. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  853. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  856. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  857. var depthBuffer: WebGLRenderbuffer;
  858. // Create the depth buffer
  859. if (generateDepthBuffer) {
  860. depthBuffer = gl.createRenderbuffer();
  861. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  862. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  863. }
  864. // Create the framebuffer
  865. var framebuffer = gl.createFramebuffer();
  866. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  867. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  868. if (generateDepthBuffer) {
  869. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  870. }
  871. // Unbind
  872. gl.bindTexture(gl.TEXTURE_2D, null);
  873. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  874. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  875. texture._framebuffer = framebuffer;
  876. if (generateDepthBuffer) {
  877. texture._depthBuffer = depthBuffer;
  878. }
  879. texture._width = width;
  880. texture._height = height;
  881. texture.isReady = true;
  882. texture.generateMipMaps = generateMipMaps;
  883. texture.references = 1;
  884. this._activeTexturesCache = [];
  885. this._loadedTexturesCache.push(texture);
  886. return texture;
  887. }
  888. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  889. var gl = this._gl;
  890. var texture = gl.createTexture();
  891. texture.isCube = true;
  892. texture.url = rootUrl;
  893. texture.references = 1;
  894. this._loadedTexturesCache.push(texture);
  895. cascadeLoad(rootUrl, 0, [], scene, imgs => {
  896. var width = getExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  897. var height = width;
  898. this._workingCanvas.width = width;
  899. this._workingCanvas.height = height;
  900. var faces = [
  901. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  902. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  903. ];
  904. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  905. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  906. for (var index = 0; index < faces.length; index++) {
  907. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  908. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  909. }
  910. if (!noMipmap) {
  911. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  912. }
  913. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  914. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  915. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  917. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  918. this._activeTexturesCache = [];
  919. texture._width = width;
  920. texture._height = height;
  921. texture.isReady = true;
  922. }, extensions);
  923. return texture;
  924. }
  925. public _releaseTexture(texture: WebGLTexture): void {
  926. var gl = this._gl;
  927. if (texture._framebuffer) {
  928. gl.deleteFramebuffer(texture._framebuffer);
  929. }
  930. if (texture._depthBuffer) {
  931. gl.deleteRenderbuffer(texture._depthBuffer);
  932. }
  933. gl.deleteTexture(texture);
  934. // Unbind channels
  935. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  936. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  937. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  938. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  939. this._activeTexturesCache[channel] = null;
  940. }
  941. var index = this._loadedTexturesCache.indexOf(texture);
  942. if (index !== -1) {
  943. this._loadedTexturesCache.splice(index, 1);
  944. }
  945. }
  946. public bindSamplers(effect: Effect): void {
  947. this._gl.useProgram(effect.getProgram());
  948. var samplers = effect.getSamplers();
  949. for (var index = 0; index < samplers.length; index++) {
  950. var uniform = effect.getUniform(samplers[index]);
  951. this._gl.uniform1i(uniform, index);
  952. }
  953. this._currentEffect = null;
  954. }
  955. public _bindTexture(channel: number, texture: WebGLTexture): void {
  956. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  957. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  958. this._activeTexturesCache[channel] = null;
  959. }
  960. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  961. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  962. }
  963. public setTexture(channel: number, texture: BaseTexture): void {
  964. if (channel < 0) {
  965. return;
  966. }
  967. // Not ready?
  968. if (!texture || !texture.isReady()) {
  969. if (this._activeTexturesCache[channel] != null) {
  970. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  971. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  972. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  973. this._activeTexturesCache[channel] = null;
  974. }
  975. return;
  976. }
  977. // Video
  978. if (texture instanceof BABYLON.VideoTexture) {
  979. if ((<VideoTexture>texture).update()) {
  980. this._activeTexturesCache[channel] = null;
  981. }
  982. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  983. texture.delayLoad();
  984. return;
  985. }
  986. if (this._activeTexturesCache[channel] == texture) {
  987. return;
  988. }
  989. this._activeTexturesCache[channel] = texture;
  990. var internalTexture = texture.getInternalTexture();
  991. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  992. if (internalTexture.isCube) {
  993. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  994. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  995. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  996. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  997. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  998. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  999. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1000. }
  1001. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1002. } else {
  1003. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1004. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1005. internalTexture._cachedWrapU = texture.wrapU;
  1006. switch (texture.wrapU) {
  1007. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1008. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1009. break;
  1010. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1011. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1012. break;
  1013. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1014. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1015. break;
  1016. }
  1017. }
  1018. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1019. internalTexture._cachedWrapV = texture.wrapV;
  1020. switch (texture.wrapV) {
  1021. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1022. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1023. break;
  1024. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1025. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1026. break;
  1027. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1029. break;
  1030. }
  1031. }
  1032. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1033. }
  1034. }
  1035. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1036. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1037. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1038. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1039. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1040. }
  1041. }
  1042. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1043. var data = new Uint8Array(height * width * 4);
  1044. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1045. return data;
  1046. }
  1047. // Dispose
  1048. public dispose(): void {
  1049. this.stopRenderLoop();
  1050. // Release scenes
  1051. while (this.scenes.length) {
  1052. this.scenes[0].dispose();
  1053. }
  1054. // Release effects
  1055. for (var name in this._compiledEffects) {
  1056. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1057. }
  1058. // Events
  1059. window.removeEventListener("blur", this._onBlur);
  1060. window.removeEventListener("focus", this._onFocus);
  1061. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1062. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1063. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1064. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1065. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1066. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1067. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1068. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1069. }
  1070. // Statics
  1071. public static isSupported(): boolean {
  1072. try {
  1073. var tempcanvas = document.createElement("canvas");
  1074. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1075. return gl != null && !!window.WebGLRenderingContext;
  1076. } catch (e) {
  1077. return false;
  1078. }
  1079. }
  1080. }
  1081. }