babylon.engine.ts 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565
  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.5-alpha";
  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 (let index = 0; index < facesIndex.length; index++) {
  1717. let 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. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  1722. // By following the webgl standard changes from Revision 7, 2014/11/24
  1723. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  1724. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  1725. Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  1726. // Data are known to be in +X +Y +Z -X -Y -Z
  1727. for (let index = 0; index < facesIndex.length; index++) {
  1728. let faceData = <Float32Array>rgbeDataArrays[index];
  1729. // Create a new RGBA Face.
  1730. let newFaceData = new Float32Array(width * height * 4);
  1731. for (let x = 0; x < width; x++) {
  1732. for (let y = 0; y < height; y++) {
  1733. let index = (y * width + x) * 3;
  1734. let newIndex = (y * width + x) * 4;
  1735. // Map Old Value to new value.
  1736. newFaceData[newIndex + 0] = faceData[index + 0];
  1737. newFaceData[newIndex + 1] = faceData[index + 1];
  1738. newFaceData[newIndex + 2] = faceData[index + 2];
  1739. // Add fully opaque alpha channel.
  1740. newFaceData[newIndex + 3] = 1;
  1741. }
  1742. }
  1743. // Reupload the face.
  1744. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  1745. }
  1746. // Try to generate mipmap again.
  1747. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1748. }
  1749. }
  1750. }
  1751. else {
  1752. noMipmap = true;
  1753. }
  1754. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  1755. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  1756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  1757. }
  1758. else {
  1759. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1760. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1761. }
  1762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1764. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1765. texture.isReady = true;
  1766. this.resetTextureCache();
  1767. scene._removePendingData(texture);
  1768. };
  1769. Tools.LoadFile(url, data => {
  1770. internalCallback(data);
  1771. }, onerror, scene.database, true);
  1772. return texture;
  1773. };
  1774. public _releaseTexture(texture: WebGLTexture): void {
  1775. var gl = this._gl;
  1776. if (texture._framebuffer) {
  1777. gl.deleteFramebuffer(texture._framebuffer);
  1778. }
  1779. if (texture._depthBuffer) {
  1780. gl.deleteRenderbuffer(texture._depthBuffer);
  1781. }
  1782. gl.deleteTexture(texture);
  1783. // Unbind channels
  1784. this.unbindAllTextures();
  1785. var index = this._loadedTexturesCache.indexOf(texture);
  1786. if (index !== -1) {
  1787. this._loadedTexturesCache.splice(index, 1);
  1788. }
  1789. }
  1790. public bindSamplers(effect: Effect): void {
  1791. this._gl.useProgram(effect.getProgram());
  1792. var samplers = effect.getSamplers();
  1793. for (var index = 0; index < samplers.length; index++) {
  1794. var uniform = effect.getUniform(samplers[index]);
  1795. this._gl.uniform1i(uniform, index);
  1796. }
  1797. this._currentEffect = null;
  1798. }
  1799. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1800. if (channel < 0) {
  1801. return;
  1802. }
  1803. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1804. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1805. this._activeTexturesCache[channel] = null;
  1806. }
  1807. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1808. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1809. }
  1810. public unbindAllTextures(): void {
  1811. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1812. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1813. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1814. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1815. this._activeTexturesCache[channel] = null;
  1816. }
  1817. }
  1818. public setTexture(channel: number, texture: BaseTexture): void {
  1819. if (channel < 0) {
  1820. return;
  1821. }
  1822. // Not ready?
  1823. if (!texture || !texture.isReady()) {
  1824. if (this._activeTexturesCache[channel] != null) {
  1825. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1826. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1827. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1828. this._activeTexturesCache[channel] = null;
  1829. }
  1830. return;
  1831. }
  1832. // Video
  1833. var alreadyActivated = false;
  1834. if (texture instanceof VideoTexture) {
  1835. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1836. alreadyActivated = true;
  1837. texture.update();
  1838. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1839. texture.delayLoad();
  1840. return;
  1841. }
  1842. if (this._activeTexturesCache[channel] === texture) {
  1843. return;
  1844. }
  1845. this._activeTexturesCache[channel] = texture;
  1846. var internalTexture = texture.getInternalTexture();
  1847. if (!alreadyActivated) {
  1848. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1849. }
  1850. if (internalTexture.isCube) {
  1851. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1852. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1853. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1854. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1855. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1856. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1857. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1858. }
  1859. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1860. } else {
  1861. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1862. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1863. internalTexture._cachedWrapU = texture.wrapU;
  1864. switch (texture.wrapU) {
  1865. case Texture.WRAP_ADDRESSMODE:
  1866. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1867. break;
  1868. case Texture.CLAMP_ADDRESSMODE:
  1869. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1870. break;
  1871. case Texture.MIRROR_ADDRESSMODE:
  1872. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1873. break;
  1874. }
  1875. }
  1876. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1877. internalTexture._cachedWrapV = texture.wrapV;
  1878. switch (texture.wrapV) {
  1879. case Texture.WRAP_ADDRESSMODE:
  1880. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1881. break;
  1882. case Texture.CLAMP_ADDRESSMODE:
  1883. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1884. break;
  1885. case Texture.MIRROR_ADDRESSMODE:
  1886. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1887. break;
  1888. }
  1889. }
  1890. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1891. }
  1892. }
  1893. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1894. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1895. var value = texture.anisotropicFilteringLevel;
  1896. if (texture.getInternalTexture().samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1897. value = 1;
  1898. }
  1899. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  1900. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  1901. texture._cachedAnisotropicFilteringLevel = value;
  1902. }
  1903. }
  1904. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1905. var data = new Uint8Array(height * width * 4);
  1906. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1907. return data;
  1908. }
  1909. /**
  1910. * Add an externaly attached data from its key.
  1911. * This method call will fail and return false, if such key already exists.
  1912. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  1913. * @param key the unique key that identifies the data
  1914. * @param data the data object to associate to the key for this Engine instance
  1915. * @return true if no such key were already present and the data was added successfully, false otherwise
  1916. */
  1917. public addExternalData<T>(key: string, data: T): boolean {
  1918. return this._externalData.add(key, data);
  1919. }
  1920. /**
  1921. * Get an externaly attached data from its key
  1922. * @param key the unique key that identifies the data
  1923. * @return the associated data, if present (can be null), or undefined if not present
  1924. */
  1925. public getExternalData<T>(key: string): T {
  1926. return <T>this._externalData.get(key);
  1927. }
  1928. /**
  1929. * Get an externaly attached data from its key, create it using a factory if it's not already present
  1930. * @param key the unique key that identifies the data
  1931. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  1932. * @return the associated data, can be null if the factory returned null.
  1933. */
  1934. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  1935. return <T>this._externalData.getOrAddWithFactory(key, factory);
  1936. }
  1937. /**
  1938. * Remove an externaly attached data from the Engine instance
  1939. * @param key the unique key that identifies the data
  1940. * @return true if the data was successfully removed, false if it doesn't exist
  1941. */
  1942. public removeExternalData(key): boolean {
  1943. return this._externalData.remove(key);
  1944. }
  1945. public releaseInternalTexture(texture: WebGLTexture): void {
  1946. if (!texture) {
  1947. return;
  1948. }
  1949. texture.references--;
  1950. // Final reference ?
  1951. if (texture.references === 0) {
  1952. var texturesCache = this.getLoadedTexturesCache();
  1953. var index = texturesCache.indexOf(texture);
  1954. if (index > -1) {
  1955. texturesCache.splice(index, 1);
  1956. }
  1957. this._releaseTexture(texture);
  1958. }
  1959. }
  1960. // Dispose
  1961. public dispose(): void {
  1962. this.hideLoadingUI();
  1963. this.stopRenderLoop();
  1964. // Release scenes
  1965. while (this.scenes.length) {
  1966. this.scenes[0].dispose();
  1967. }
  1968. // Release audio engine
  1969. Engine.audioEngine.dispose();
  1970. // Release effects
  1971. for (var name in this._compiledEffects) {
  1972. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1973. }
  1974. // Unbind
  1975. if (this._vertexAttribArraysEnabled) {
  1976. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  1977. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  1978. continue;
  1979. }
  1980. this._gl.disableVertexAttribArray(i);
  1981. }
  1982. }
  1983. this._gl = null;
  1984. // Events
  1985. window.removeEventListener("blur", this._onBlur);
  1986. window.removeEventListener("focus", this._onFocus);
  1987. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1988. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1989. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1990. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1991. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1992. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1993. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1994. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1995. }
  1996. // Loading screen
  1997. public displayLoadingUI(): void {
  1998. this._loadingScreen.displayLoadingUI();
  1999. }
  2000. public hideLoadingUI(): void {
  2001. this._loadingScreen.hideLoadingUI();
  2002. }
  2003. public get loadingScreen(): ILoadingScreen {
  2004. return this._loadingScreen;
  2005. }
  2006. public set loadingScreen(loadingScreen: ILoadingScreen) {
  2007. this._loadingScreen = loadingScreen;
  2008. }
  2009. public set loadingUIText(text: string) {
  2010. this._loadingScreen.loadingUIText = text;
  2011. }
  2012. public set loadingUIBackgroundColor(color: string) {
  2013. this._loadingScreen.loadingUIBackgroundColor = color;
  2014. }
  2015. // FPS
  2016. public getFps(): number {
  2017. return this.fps;
  2018. }
  2019. public getDeltaTime(): number {
  2020. return this.deltaTime;
  2021. }
  2022. private _measureFps(): void {
  2023. this.previousFramesDuration.push(Tools.Now);
  2024. var length = this.previousFramesDuration.length;
  2025. if (length >= 2) {
  2026. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  2027. }
  2028. if (length >= this.fpsRange) {
  2029. if (length > this.fpsRange) {
  2030. this.previousFramesDuration.splice(0, 1);
  2031. length = this.previousFramesDuration.length;
  2032. }
  2033. var sum = 0;
  2034. for (var id = 0; id < length - 1; id++) {
  2035. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  2036. }
  2037. this.fps = 1000.0 / (sum / (length - 1));
  2038. }
  2039. }
  2040. // Statics
  2041. public static isSupported(): boolean {
  2042. try {
  2043. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  2044. if (navigator.isCocoonJS) {
  2045. return true;
  2046. }
  2047. var tempcanvas = document.createElement("canvas");
  2048. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  2049. return gl != null && !!window.WebGLRenderingContext;
  2050. } catch (e) {
  2051. return false;
  2052. }
  2053. }
  2054. }
  2055. }