babylon.engine.ts 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  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. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  473. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  474. return buffer;
  475. }
  476. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  477. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  478. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  479. for (var index = 0; index < 4; index++) {
  480. var offsetLocation = offsetLocations[index];
  481. this._gl.enableVertexAttribArray(offsetLocation);
  482. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  483. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  484. }
  485. }
  486. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  487. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  488. for (var index = 0; index < 4; index++) {
  489. var offsetLocation = offsetLocations[index];
  490. this._gl.disableVertexAttribArray(offsetLocation);
  491. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  492. }
  493. }
  494. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  495. if (instancesCount) {
  496. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  497. return;
  498. }
  499. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  500. }
  501. // Shaders
  502. public _releaseEffect(effect: Effect): void {
  503. if (this._compiledEffects[effect._key]) {
  504. delete this._compiledEffects[effect._key];
  505. if (effect.getProgram()) {
  506. this._gl.deleteProgram(effect.getProgram());
  507. }
  508. }
  509. }
  510. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, optionalDefines?: string[],
  511. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  512. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  513. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  514. var name = vertex + "+" + fragment + "@" + defines;
  515. if (this._compiledEffects[name]) {
  516. return this._compiledEffects[name];
  517. }
  518. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, optionalDefines, onCompiled, onError);
  519. effect._key = name;
  520. this._compiledEffects[name] = effect;
  521. return effect;
  522. }
  523. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  524. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  525. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  526. var shaderProgram = this._gl.createProgram();
  527. this._gl.attachShader(shaderProgram, vertexShader);
  528. this._gl.attachShader(shaderProgram, fragmentShader);
  529. this._gl.linkProgram(shaderProgram);
  530. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  531. if (!linked) {
  532. var error = this._gl.getProgramInfoLog(shaderProgram);
  533. if (error) {
  534. throw new Error(error);
  535. }
  536. }
  537. this._gl.deleteShader(vertexShader);
  538. this._gl.deleteShader(fragmentShader);
  539. return shaderProgram;
  540. }
  541. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  542. var results = [];
  543. for (var index = 0; index < uniformsNames.length; index++) {
  544. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  545. }
  546. return results;
  547. }
  548. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  549. var results = [];
  550. for (var index = 0; index < attributesNames.length; index++) {
  551. try {
  552. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  553. } catch (e) {
  554. results.push(-1);
  555. }
  556. }
  557. return results;
  558. }
  559. public enableEffect(effect: Effect): void {
  560. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  561. return;
  562. }
  563. this._vertexAttribArrays = this._vertexAttribArrays || [];
  564. // Use program
  565. this._gl.useProgram(effect.getProgram());
  566. for (var i in this._vertexAttribArrays) {
  567. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  568. continue;
  569. }
  570. this._vertexAttribArrays[i] = false;
  571. this._gl.disableVertexAttribArray(i);
  572. }
  573. var attributesCount = effect.getAttributesCount();
  574. for (var index = 0; index < attributesCount; index++) {
  575. // Attributes
  576. var order = effect.getAttributeLocation(index);
  577. if (order >= 0) {
  578. this._vertexAttribArrays[order] = true;
  579. this._gl.enableVertexAttribArray(order);
  580. }
  581. }
  582. this._currentEffect = effect;
  583. }
  584. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  585. if (!uniform)
  586. return;
  587. this._gl.uniform1fv(uniform, array);
  588. }
  589. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  590. if (!uniform)
  591. return;
  592. this._gl.uniformMatrix4fv(uniform, false, matrices);
  593. }
  594. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  595. if (!uniform)
  596. return;
  597. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  598. }
  599. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  600. if (!uniform)
  601. return;
  602. this._gl.uniform1f(uniform, value);
  603. }
  604. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  605. if (!uniform)
  606. return;
  607. this._gl.uniform2f(uniform, x, y);
  608. }
  609. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  610. if (!uniform)
  611. return;
  612. this._gl.uniform3f(uniform, x, y, z);
  613. }
  614. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  615. if (!uniform)
  616. return;
  617. this._gl.uniform1i(uniform, bool);
  618. }
  619. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  620. if (!uniform)
  621. return;
  622. this._gl.uniform4f(uniform, x, y, z, w);
  623. }
  624. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  625. if (!uniform)
  626. return;
  627. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  628. }
  629. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  630. if (!uniform)
  631. return;
  632. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  633. }
  634. // States
  635. public setState(culling: boolean): void {
  636. // Culling
  637. if (this._cullingState !== culling) {
  638. if (culling) {
  639. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  640. this._gl.enable(this._gl.CULL_FACE);
  641. } else {
  642. this._gl.disable(this._gl.CULL_FACE);
  643. }
  644. this._cullingState = culling;
  645. }
  646. }
  647. public setDepthBuffer(enable: boolean): void {
  648. if (enable) {
  649. this._gl.enable(this._gl.DEPTH_TEST);
  650. } else {
  651. this._gl.disable(this._gl.DEPTH_TEST);
  652. }
  653. }
  654. public setDepthWrite(enable: boolean): void {
  655. this._gl.depthMask(enable);
  656. this._depthMask = enable;
  657. }
  658. public setColorWrite(enable: boolean): void {
  659. this._gl.colorMask(enable, enable, enable, enable);
  660. }
  661. public setAlphaMode(mode: number): void {
  662. switch (mode) {
  663. case BABYLON.Engine.ALPHA_DISABLE:
  664. this.setDepthWrite(true);
  665. this._gl.disable(this._gl.BLEND);
  666. break;
  667. case BABYLON.Engine.ALPHA_COMBINE:
  668. this.setDepthWrite(false);
  669. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  670. this._gl.enable(this._gl.BLEND);
  671. break;
  672. case BABYLON.Engine.ALPHA_ADD:
  673. this.setDepthWrite(false);
  674. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  675. this._gl.enable(this._gl.BLEND);
  676. break;
  677. }
  678. }
  679. public setAlphaTesting(enable: boolean): void {
  680. this._alphaTest = enable;
  681. }
  682. public getAlphaTesting(): boolean {
  683. return this._alphaTest;
  684. }
  685. // Textures
  686. public wipeCaches(): void {
  687. this._activeTexturesCache = [];
  688. this._currentEffect = null;
  689. this._cullingState = null;
  690. this._cachedVertexBuffers = null;
  691. this._cachedIndexBuffer = null;
  692. this._cachedEffectForVertexBuffers = null;
  693. }
  694. public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene): WebGLTexture {
  695. var texture = this._gl.createTexture();
  696. var extension = url.substr(url.length - 4, 4).toLowerCase();
  697. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  698. var isTGA = (extension === ".tga");
  699. scene._addPendingData(texture);
  700. texture.url = url;
  701. texture.noMipmap = noMipmap;
  702. texture.references = 1;
  703. this._loadedTexturesCache.push(texture);
  704. if (isTGA) {
  705. BABYLON.Tools.LoadFile(url, arrayBuffer => {
  706. var data = new Uint8Array(arrayBuffer);
  707. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  708. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  709. Internals.TGATools.UploadContent(this._gl, data);
  710. });
  711. }, null, scene.database, true);
  712. } else if (isDDS) {
  713. BABYLON.Tools.LoadFile(url, data => {
  714. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  715. var loadMipmap = info.mipmapCount > 1 && !noMipmap;
  716. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, true, () => {
  717. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, loadMipmap);
  718. });
  719. }, null, scene.database, true);
  720. } else {
  721. var onload = (img) => {
  722. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  723. var isPot = (img.width == potWidth && img.height == potHeight);
  724. if (!isPot) {
  725. this._workingCanvas.width = potWidth;
  726. this._workingCanvas.height = potHeight;
  727. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  728. }
  729. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  730. });
  731. };
  732. var onerror = () => {
  733. scene._removePendingData(texture);
  734. };
  735. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  736. }
  737. return texture;
  738. }
  739. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean): WebGLTexture {
  740. var texture = this._gl.createTexture();
  741. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  742. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  743. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  744. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
  745. if (!generateMipMaps) {
  746. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
  747. } else {
  748. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR_MIPMAP_LINEAR);
  749. }
  750. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  751. this._activeTexturesCache = [];
  752. texture._baseWidth = width;
  753. texture._baseHeight = height;
  754. texture._width = width;
  755. texture._height = height;
  756. texture.isReady = false;
  757. texture.generateMipMaps = generateMipMaps;
  758. texture.references = 1;
  759. this._loadedTexturesCache.push(texture);
  760. return texture;
  761. }
  762. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  763. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  764. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  765. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  766. if (texture.generateMipMaps) {
  767. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  768. }
  769. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  770. this._activeTexturesCache = [];
  771. texture.isReady = true;
  772. }
  773. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  774. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  775. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  776. // Scale the video if it is a NPOT using the current working canvas
  777. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  778. if (!texture._workingCanvas) {
  779. texture._workingCanvas = document.createElement("canvas");
  780. texture._workingContext = texture._workingCanvas.getContext("2d");
  781. texture._workingCanvas.width = texture._width;
  782. texture._workingCanvas.height = texture._height;
  783. }
  784. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  785. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  786. } else {
  787. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  788. }
  789. if (texture.generateMipMaps) {
  790. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  791. }
  792. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  793. this._activeTexturesCache = [];
  794. texture.isReady = true;
  795. }
  796. public createRenderTargetTexture(size: any, options): WebGLTexture {
  797. // old version had a "generateMipMaps" arg instead of options.
  798. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  799. // in the same way, generateDepthBuffer is defaulted to true
  800. var generateMipMaps = false;
  801. var generateDepthBuffer = true;
  802. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  803. if (options !== undefined) {
  804. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  805. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  806. if (options.samplingMode !== undefined) {
  807. samplingMode = options.samplingMode;
  808. }
  809. }
  810. var gl = this._gl;
  811. var texture = gl.createTexture();
  812. gl.bindTexture(gl.TEXTURE_2D, texture);
  813. var width = size.width || size;
  814. var height = size.height || size;
  815. var magFilter = gl.NEAREST;
  816. var minFilter = gl.NEAREST;
  817. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  818. magFilter = gl.LINEAR;
  819. if (generateMipMaps) {
  820. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  821. } else {
  822. minFilter = gl.LINEAR;
  823. }
  824. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  825. magFilter = gl.LINEAR;
  826. if (generateMipMaps) {
  827. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  828. } else {
  829. minFilter = gl.LINEAR;
  830. }
  831. }
  832. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  833. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  834. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  835. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  836. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  837. var depthBuffer: WebGLRenderbuffer;
  838. // Create the depth buffer
  839. if (generateDepthBuffer) {
  840. depthBuffer = gl.createRenderbuffer();
  841. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  842. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  843. }
  844. // Create the framebuffer
  845. var framebuffer = gl.createFramebuffer();
  846. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  847. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  848. if (generateDepthBuffer) {
  849. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  850. }
  851. // Unbind
  852. gl.bindTexture(gl.TEXTURE_2D, null);
  853. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  854. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  855. texture._framebuffer = framebuffer;
  856. if (generateDepthBuffer) {
  857. texture._depthBuffer = depthBuffer;
  858. }
  859. texture._width = width;
  860. texture._height = height;
  861. texture.isReady = true;
  862. texture.generateMipMaps = generateMipMaps;
  863. texture.references = 1;
  864. this._activeTexturesCache = [];
  865. this._loadedTexturesCache.push(texture);
  866. return texture;
  867. }
  868. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  869. var gl = this._gl;
  870. var texture = gl.createTexture();
  871. texture.isCube = true;
  872. texture.url = rootUrl;
  873. texture.references = 1;
  874. this._loadedTexturesCache.push(texture);
  875. cascadeLoad(rootUrl, 0, [], scene, imgs => {
  876. var width = getExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  877. var height = width;
  878. this._workingCanvas.width = width;
  879. this._workingCanvas.height = height;
  880. var faces = [
  881. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  882. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  883. ];
  884. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  885. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  886. for (var index = 0; index < faces.length; index++) {
  887. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  888. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  889. }
  890. if (!noMipmap) {
  891. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  892. }
  893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  894. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  895. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  896. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  897. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  898. this._activeTexturesCache = [];
  899. texture._width = width;
  900. texture._height = height;
  901. texture.isReady = true;
  902. }, extensions);
  903. return texture;
  904. }
  905. public _releaseTexture(texture: WebGLTexture): void {
  906. var gl = this._gl;
  907. if (texture._framebuffer) {
  908. gl.deleteFramebuffer(texture._framebuffer);
  909. }
  910. if (texture._depthBuffer) {
  911. gl.deleteRenderbuffer(texture._depthBuffer);
  912. }
  913. gl.deleteTexture(texture);
  914. // Unbind channels
  915. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  916. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  917. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  918. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  919. this._activeTexturesCache[channel] = null;
  920. }
  921. var index = this._loadedTexturesCache.indexOf(texture);
  922. if (index !== -1) {
  923. this._loadedTexturesCache.splice(index, 1);
  924. }
  925. }
  926. public bindSamplers(effect: Effect): void {
  927. this._gl.useProgram(effect.getProgram());
  928. var samplers = effect.getSamplers();
  929. for (var index = 0; index < samplers.length; index++) {
  930. var uniform = effect.getUniform(samplers[index]);
  931. this._gl.uniform1i(uniform, index);
  932. }
  933. this._currentEffect = null;
  934. }
  935. public _bindTexture(channel: number, texture: WebGLTexture): void {
  936. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  937. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  938. this._activeTexturesCache[channel] = null;
  939. }
  940. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  941. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  942. }
  943. public setTexture(channel: number, texture: BaseTexture): void {
  944. if (channel < 0) {
  945. return;
  946. }
  947. // Not ready?
  948. if (!texture || !texture.isReady()) {
  949. if (this._activeTexturesCache[channel] != null) {
  950. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  951. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  952. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  953. this._activeTexturesCache[channel] = null;
  954. }
  955. return;
  956. }
  957. // Video
  958. if (texture instanceof BABYLON.VideoTexture) {
  959. if ((<VideoTexture>texture).update()) {
  960. this._activeTexturesCache[channel] = null;
  961. }
  962. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  963. texture.delayLoad();
  964. return;
  965. }
  966. if (this._activeTexturesCache[channel] == texture) {
  967. return;
  968. }
  969. this._activeTexturesCache[channel] = texture;
  970. var internalTexture = texture.getInternalTexture();
  971. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  972. if (internalTexture.isCube) {
  973. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  974. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  975. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  976. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  977. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  978. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  979. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  980. }
  981. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  982. } else {
  983. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  984. if (internalTexture._cachedWrapU !== texture.wrapU) {
  985. internalTexture._cachedWrapU = texture.wrapU;
  986. switch (texture.wrapU) {
  987. case BABYLON.Texture.WRAP_ADDRESSMODE:
  988. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  989. break;
  990. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  991. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  992. break;
  993. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  994. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  995. break;
  996. }
  997. }
  998. if (internalTexture._cachedWrapV !== texture.wrapV) {
  999. internalTexture._cachedWrapV = texture.wrapV;
  1000. switch (texture.wrapV) {
  1001. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1002. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1003. break;
  1004. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1005. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1006. break;
  1007. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1008. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1009. break;
  1010. }
  1011. }
  1012. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1013. }
  1014. }
  1015. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1016. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1017. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1018. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1019. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1020. }
  1021. }
  1022. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1023. var data = new Uint8Array(height * width * 4);
  1024. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1025. return data;
  1026. }
  1027. // Dispose
  1028. public dispose(): void {
  1029. this.stopRenderLoop();
  1030. // Release scenes
  1031. while (this.scenes.length) {
  1032. this.scenes[0].dispose();
  1033. }
  1034. // Release effects
  1035. for (var name in this._compiledEffects) {
  1036. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1037. }
  1038. // Events
  1039. window.removeEventListener("blur", this._onBlur);
  1040. window.removeEventListener("focus", this._onFocus);
  1041. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1042. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1043. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1044. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1045. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1046. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1047. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1048. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1049. }
  1050. // Statics
  1051. public static isSupported(): boolean {
  1052. try {
  1053. var tempcanvas = document.createElement("canvas");
  1054. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1055. return gl != null && !!window.WebGLRenderingContext;
  1056. } catch (e) {
  1057. return false;
  1058. }
  1059. }
  1060. }
  1061. }