babylon.engine.ts 102 KB

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