webgl-debug.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. /*
  2. ** Copyright (c) 2012 The Khronos Group Inc.
  3. **
  4. ** Permission is hereby granted, free of charge, to any person obtaining a
  5. ** copy of this software and/or associated documentation files (the
  6. ** "Materials"), to deal in the Materials without restriction, including
  7. ** without limitation the rights to use, copy, modify, merge, publish,
  8. ** distribute, sublicense, and/or sell copies of the Materials, and to
  9. ** permit persons to whom the Materials are furnished to do so, subject to
  10. ** the following conditions:
  11. **
  12. ** The above copyright notice and this permission notice shall be included
  13. ** in all copies or substantial portions of the Materials.
  14. **
  15. ** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
  22. */
  23. // Various functions for helping debug WebGL apps.
  24. WebGLDebugUtils = function() {
  25. /**
  26. * Wrapped logging function.
  27. * @param {string} msg Message to log.
  28. */
  29. var log = function(msg) {
  30. if (window.console && window.console.log) {
  31. window.console.log(msg);
  32. }
  33. };
  34. /**
  35. * Wrapped error logging function.
  36. * @param {string} msg Message to log.
  37. */
  38. var error = function(msg) {
  39. if (window.console && window.console.error) {
  40. window.console.error(msg);
  41. } else {
  42. log(msg);
  43. }
  44. };
  45. /**
  46. * Which arguments are enums based on the number of arguments to the function.
  47. * So
  48. * 'texImage2D': {
  49. * 9: { 0:true, 2:true, 6:true, 7:true },
  50. * 6: { 0:true, 2:true, 3:true, 4:true },
  51. * },
  52. *
  53. * means if there are 9 arguments then 6 and 7 are enums, if there are 6
  54. * arguments 3 and 4 are enums
  55. *
  56. * @type {!Object.<number, !Object.<number, string>}
  57. */
  58. var glValidEnumContexts = {
  59. // Generic setters and getters
  60. 'enable': {1: { 0:true }},
  61. 'disable': {1: { 0:true }},
  62. 'getParameter': {1: { 0:true }},
  63. // Rendering
  64. 'drawArrays': {3:{ 0:true }},
  65. 'drawElements': {4:{ 0:true, 2:true }},
  66. // Shaders
  67. 'createShader': {1: { 0:true }},
  68. 'getShaderParameter': {2: { 1:true }},
  69. 'getProgramParameter': {2: { 1:true }},
  70. 'getShaderPrecisionFormat': {2: { 0: true, 1:true }},
  71. // Vertex attributes
  72. 'getVertexAttrib': {2: { 1:true }},
  73. 'vertexAttribPointer': {6: { 2:true }},
  74. // Textures
  75. 'bindTexture': {2: { 0:true }},
  76. 'activeTexture': {1: { 0:true }},
  77. 'getTexParameter': {2: { 0:true, 1:true }},
  78. 'texParameterf': {3: { 0:true, 1:true }},
  79. 'texParameteri': {3: { 0:true, 1:true, 2:true }},
  80. // texImage2D and texSubImage2D are defined below with WebGL 2 entrypoints
  81. 'copyTexImage2D': {8: { 0:true, 2:true }},
  82. 'copyTexSubImage2D': {8: { 0:true }},
  83. 'generateMipmap': {1: { 0:true }},
  84. // compressedTexImage2D and compressedTexSubImage2D are defined below with WebGL 2 entrypoints
  85. // Buffer objects
  86. 'bindBuffer': {2: { 0:true }},
  87. // bufferData and bufferSubData are defined below with WebGL 2 entrypoints
  88. 'getBufferParameter': {2: { 0:true, 1:true }},
  89. // Renderbuffers and framebuffers
  90. 'pixelStorei': {2: { 0:true, 1:true }},
  91. // readPixels is defined below with WebGL 2 entrypoints
  92. 'bindRenderbuffer': {2: { 0:true }},
  93. 'bindFramebuffer': {2: { 0:true }},
  94. 'checkFramebufferStatus': {1: { 0:true }},
  95. 'framebufferRenderbuffer': {4: { 0:true, 1:true, 2:true }},
  96. 'framebufferTexture2D': {5: { 0:true, 1:true, 2:true }},
  97. 'getFramebufferAttachmentParameter': {3: { 0:true, 1:true, 2:true }},
  98. 'getRenderbufferParameter': {2: { 0:true, 1:true }},
  99. 'renderbufferStorage': {4: { 0:true, 1:true }},
  100. // Frame buffer operations (clear, blend, depth test, stencil)
  101. 'clear': {1: { 0: { 'enumBitwiseOr': ['COLOR_BUFFER_BIT', 'DEPTH_BUFFER_BIT', 'STENCIL_BUFFER_BIT'] }}},
  102. 'depthFunc': {1: { 0:true }},
  103. 'blendFunc': {2: { 0:true, 1:true }},
  104. 'blendFuncSeparate': {4: { 0:true, 1:true, 2:true, 3:true }},
  105. 'blendEquation': {1: { 0:true }},
  106. 'blendEquationSeparate': {2: { 0:true, 1:true }},
  107. 'stencilFunc': {3: { 0:true }},
  108. 'stencilFuncSeparate': {4: { 0:true, 1:true }},
  109. 'stencilMaskSeparate': {2: { 0:true }},
  110. 'stencilOp': {3: { 0:true, 1:true, 2:true }},
  111. 'stencilOpSeparate': {4: { 0:true, 1:true, 2:true, 3:true }},
  112. // Culling
  113. 'cullFace': {1: { 0:true }},
  114. 'frontFace': {1: { 0:true }},
  115. // ANGLE_instanced_arrays extension
  116. 'drawArraysInstancedANGLE': {4: { 0:true }},
  117. 'drawElementsInstancedANGLE': {5: { 0:true, 2:true }},
  118. // EXT_blend_minmax extension
  119. 'blendEquationEXT': {1: { 0:true }},
  120. // WebGL 2 Buffer objects
  121. 'bufferData': {
  122. 3: { 0:true, 2:true }, // WebGL 1
  123. 4: { 0:true, 2:true }, // WebGL 2
  124. 5: { 0:true, 2:true } // WebGL 2
  125. },
  126. 'bufferSubData': {
  127. 3: { 0:true }, // WebGL 1
  128. 4: { 0:true }, // WebGL 2
  129. 5: { 0:true } // WebGL 2
  130. },
  131. 'copyBufferSubData': {5: { 0:true, 1:true }},
  132. 'getBufferSubData': {3: { 0:true }, 4: { 0:true }, 5: { 0:true }},
  133. // WebGL 2 Framebuffer objects
  134. 'blitFramebuffer': {10: { 8: { 'enumBitwiseOr': ['COLOR_BUFFER_BIT', 'DEPTH_BUFFER_BIT', 'STENCIL_BUFFER_BIT'] }, 9:true }},
  135. 'framebufferTextureLayer': {5: { 0:true, 1:true }},
  136. 'invalidateFramebuffer': {2: { 0:true }},
  137. 'invalidateSubFramebuffer': {6: { 0:true }},
  138. 'readBuffer': {1: { 0:true }},
  139. // WebGL 2 Renderbuffer objects
  140. 'getInternalformatParameter': {3: { 0:true, 1:true, 2:true }},
  141. 'renderbufferStorageMultisample': {5: { 0:true, 2:true }},
  142. // WebGL 2 Texture objects
  143. 'texStorage2D': {5: { 0:true, 2:true }},
  144. 'texStorage3D': {6: { 0:true, 2:true }},
  145. 'texImage2D': {
  146. 9: { 0:true, 2:true, 6:true, 7:true }, // WebGL 1 & 2
  147. 6: { 0:true, 2:true, 3:true, 4:true }, // WebGL 1
  148. 10: { 0:true, 2:true, 6:true, 7:true } // WebGL 2
  149. },
  150. 'texImage3D': {
  151. 10: { 0:true, 2:true, 7:true, 8:true },
  152. 11: { 0:true, 2:true, 7:true, 8:true }
  153. },
  154. 'texSubImage2D': {
  155. 9: { 0:true, 6:true, 7:true }, // WebGL 1 & 2
  156. 7: { 0:true, 4:true, 5:true }, // WebGL 1
  157. 10: { 0:true, 6:true, 7:true } // WebGL 2
  158. },
  159. 'texSubImage3D': {
  160. 11: { 0:true, 8:true, 9:true },
  161. 12: { 0:true, 8:true, 9:true }
  162. },
  163. 'copyTexSubImage3D': {9: { 0:true }},
  164. 'compressedTexImage2D': {
  165. 7: { 0: true, 2:true }, // WebGL 1 & 2
  166. 8: { 0: true, 2:true }, // WebGL 2
  167. 9: { 0: true, 2:true } // WebGL 2
  168. },
  169. 'compressedTexImage3D': {
  170. 8: { 0: true, 2:true },
  171. 9: { 0: true, 2:true },
  172. 10: { 0: true, 2:true }
  173. },
  174. 'compressedTexSubImage2D': {
  175. 8: { 0: true, 6:true }, // WebGL 1 & 2
  176. 9: { 0: true, 6:true }, // WebGL 2
  177. 10: { 0: true, 6:true } // WebGL 2
  178. },
  179. 'compressedTexSubImage3D': {
  180. 10: { 0: true, 8:true },
  181. 11: { 0: true, 8:true },
  182. 12: { 0: true, 8:true }
  183. },
  184. // WebGL 2 Vertex attribs
  185. 'vertexAttribIPointer': {5: { 2:true }},
  186. // WebGL 2 Writing to the drawing buffer
  187. 'drawArraysInstanced': {4: { 0:true }},
  188. 'drawElementsInstanced': {5: { 0:true, 2:true }},
  189. 'drawRangeElements': {6: { 0:true, 4:true }},
  190. // WebGL 2 Reading back pixels
  191. 'readPixels': {
  192. 7: { 4:true, 5:true }, // WebGL 1 & 2
  193. 8: { 4:true, 5:true } // WebGL 2
  194. },
  195. // WebGL 2 Multiple Render Targets
  196. 'clearBufferfv': {3: { 0:true }, 4: { 0:true }},
  197. 'clearBufferiv': {3: { 0:true }, 4: { 0:true }},
  198. 'clearBufferuiv': {3: { 0:true }, 4: { 0:true }},
  199. 'clearBufferfi': {4: { 0:true }},
  200. // WebGL 2 Query objects
  201. 'beginQuery': {2: { 0:true }},
  202. 'endQuery': {1: { 0:true }},
  203. 'getQuery': {2: { 0:true, 1:true }},
  204. 'getQueryParameter': {2: { 1:true }},
  205. // WebGL 2 Sampler objects
  206. 'samplerParameteri': {3: { 1:true, 2:true }},
  207. 'samplerParameterf': {3: { 1:true }},
  208. 'getSamplerParameter': {2: { 1:true }},
  209. // WebGL 2 Sync objects
  210. 'fenceSync': {2: { 0:true, 1: { 'enumBitwiseOr': [] } }},
  211. 'clientWaitSync': {3: { 1: { 'enumBitwiseOr': ['SYNC_FLUSH_COMMANDS_BIT'] } }},
  212. 'waitSync': {3: { 1: { 'enumBitwiseOr': [] } }},
  213. 'getSyncParameter': {2: { 1:true }},
  214. // WebGL 2 Transform Feedback
  215. 'bindTransformFeedback': {2: { 0:true }},
  216. 'beginTransformFeedback': {1: { 0:true }},
  217. 'transformFeedbackVaryings': {3: { 2:true }},
  218. // WebGL2 Uniform Buffer Objects and Transform Feedback Buffers
  219. 'bindBufferBase': {3: { 0:true }},
  220. 'bindBufferRange': {5: { 0:true }},
  221. 'getIndexedParameter': {2: { 0:true }},
  222. 'getActiveUniforms': {3: { 2:true }},
  223. 'getActiveUniformBlockParameter': {3: { 2:true }}
  224. };
  225. /**
  226. * Map of numbers to names.
  227. * @type {Object}
  228. */
  229. var glEnums = null;
  230. /**
  231. * Map of names to numbers.
  232. * @type {Object}
  233. */
  234. var enumStringToValue = null;
  235. /**
  236. * Initializes this module. Safe to call more than once.
  237. * @param {!WebGLRenderingContext} ctx A WebGL context. If
  238. * you have more than one context it doesn't matter which one
  239. * you pass in, it is only used to pull out constants.
  240. */
  241. function init(ctx) {
  242. if (glEnums == null) {
  243. glEnums = { };
  244. enumStringToValue = { };
  245. for (var propertyName in ctx) {
  246. if (typeof ctx[propertyName] == 'number') {
  247. glEnums[ctx[propertyName]] = propertyName;
  248. enumStringToValue[propertyName] = ctx[propertyName];
  249. }
  250. }
  251. }
  252. }
  253. /**
  254. * Checks the utils have been initialized.
  255. */
  256. function checkInit() {
  257. if (glEnums == null) {
  258. throw 'WebGLDebugUtils.init(ctx) not called';
  259. }
  260. }
  261. /**
  262. * Returns true or false if value matches any WebGL enum
  263. * @param {*} value Value to check if it might be an enum.
  264. * @return {boolean} True if value matches one of the WebGL defined enums
  265. */
  266. function mightBeEnum(value) {
  267. checkInit();
  268. return (glEnums[value] !== undefined);
  269. }
  270. /**
  271. * Gets an string version of an WebGL enum.
  272. *
  273. * Example:
  274. * var str = WebGLDebugUtil.glEnumToString(ctx.getError());
  275. *
  276. * @param {number} value Value to return an enum for
  277. * @return {string} The string version of the enum.
  278. */
  279. function glEnumToString(value) {
  280. checkInit();
  281. var name = glEnums[value];
  282. return (name !== undefined) ? ("gl." + name) :
  283. ("/*UNKNOWN WebGL ENUM*/ 0x" + value.toString(16) + "");
  284. }
  285. /**
  286. * Returns the string version of a WebGL argument.
  287. * Attempts to convert enum arguments to strings.
  288. * @param {string} functionName the name of the WebGL function.
  289. * @param {number} numArgs the number of arguments passed to the function.
  290. * @param {number} argumentIndx the index of the argument.
  291. * @param {*} value The value of the argument.
  292. * @return {string} The value as a string.
  293. */
  294. function glFunctionArgToString(functionName, numArgs, argumentIndex, value) {
  295. var funcInfo = glValidEnumContexts[functionName];
  296. if (funcInfo !== undefined) {
  297. var funcInfo = funcInfo[numArgs];
  298. if (funcInfo !== undefined) {
  299. if (funcInfo[argumentIndex]) {
  300. if (typeof funcInfo[argumentIndex] === 'object' &&
  301. funcInfo[argumentIndex]['enumBitwiseOr'] !== undefined) {
  302. var enums = funcInfo[argumentIndex]['enumBitwiseOr'];
  303. var orResult = 0;
  304. var orEnums = [];
  305. for (var i = 0; i < enums.length; ++i) {
  306. var enumValue = enumStringToValue[enums[i]];
  307. if ((value & enumValue) !== 0) {
  308. orResult |= enumValue;
  309. orEnums.push(glEnumToString(enumValue));
  310. }
  311. }
  312. if (orResult === value) {
  313. return orEnums.join(' | ');
  314. } else {
  315. return glEnumToString(value);
  316. }
  317. } else {
  318. return glEnumToString(value);
  319. }
  320. }
  321. }
  322. }
  323. if (value === null) {
  324. return "null";
  325. } else if (value === undefined) {
  326. return "undefined";
  327. } else {
  328. return value.toString();
  329. }
  330. }
  331. /**
  332. * Converts the arguments of a WebGL function to a string.
  333. * Attempts to convert enum arguments to strings.
  334. *
  335. * @param {string} functionName the name of the WebGL function.
  336. * @param {number} args The arguments.
  337. * @return {string} The arguments as a string.
  338. */
  339. function glFunctionArgsToString(functionName, args) {
  340. // apparently we can't do args.join(",");
  341. var argStr = "";
  342. var numArgs = args.length;
  343. for (var ii = 0; ii < numArgs; ++ii) {
  344. argStr += ((ii == 0) ? '' : ', ') +
  345. glFunctionArgToString(functionName, numArgs, ii, args[ii]);
  346. }
  347. return argStr;
  348. };
  349. function makePropertyWrapper(wrapper, original, propertyName) {
  350. //log("wrap prop: " + propertyName);
  351. wrapper.__defineGetter__(propertyName, function() {
  352. return original[propertyName];
  353. });
  354. // TODO(gmane): this needs to handle properties that take more than
  355. // one value?
  356. wrapper.__defineSetter__(propertyName, function(value) {
  357. //log("set: " + propertyName);
  358. original[propertyName] = value;
  359. });
  360. }
  361. // Makes a function that calls a function on another object.
  362. function makeFunctionWrapper(original, functionName) {
  363. //log("wrap fn: " + functionName);
  364. var f = original[functionName];
  365. return function() {
  366. //log("call: " + functionName);
  367. var result = f.apply(original, arguments);
  368. return result;
  369. };
  370. }
  371. /**
  372. * Given a WebGL context returns a wrapped context that calls
  373. * gl.getError after every command and calls a function if the
  374. * result is not gl.NO_ERROR.
  375. *
  376. * @param {!WebGLRenderingContext} ctx The webgl context to
  377. * wrap.
  378. * @param {!function(err, funcName, args): void} opt_onErrorFunc
  379. * The function to call when gl.getError returns an
  380. * error. If not specified the default function calls
  381. * console.log with a message.
  382. * @param {!function(funcName, args): void} opt_onFunc The
  383. * function to call when each webgl function is called.
  384. * You can use this to log all calls for example.
  385. * @param {!WebGLRenderingContext} opt_err_ctx The webgl context
  386. * to call getError on if different than ctx.
  387. */
  388. function makeDebugContext(ctx, opt_onErrorFunc, opt_onFunc, opt_err_ctx) {
  389. opt_err_ctx = opt_err_ctx || ctx;
  390. init(ctx);
  391. opt_onErrorFunc = opt_onErrorFunc || function(err, functionName, args) {
  392. // apparently we can't do args.join(",");
  393. var argStr = "";
  394. var numArgs = args.length;
  395. for (var ii = 0; ii < numArgs; ++ii) {
  396. argStr += ((ii == 0) ? '' : ', ') +
  397. glFunctionArgToString(functionName, numArgs, ii, args[ii]);
  398. }
  399. error("WebGL error "+ glEnumToString(err) + " in "+ functionName +
  400. "(" + argStr + ")");
  401. };
  402. // Holds booleans for each GL error so after we get the error ourselves
  403. // we can still return it to the client app.
  404. var glErrorShadow = { };
  405. // Makes a function that calls a WebGL function and then calls getError.
  406. function makeErrorWrapper(ctx, functionName) {
  407. return function() {
  408. if (opt_onFunc) {
  409. opt_onFunc(functionName, arguments);
  410. }
  411. var result = ctx[functionName].apply(ctx, arguments);
  412. var err = opt_err_ctx.getError();
  413. if (err != 0) {
  414. glErrorShadow[err] = true;
  415. opt_onErrorFunc(err, functionName, arguments);
  416. }
  417. return result;
  418. };
  419. }
  420. // Make a an object that has a copy of every property of the WebGL context
  421. // but wraps all functions.
  422. var wrapper = {};
  423. for (var propertyName in ctx) {
  424. if (typeof ctx[propertyName] == 'function') {
  425. if (propertyName != 'getExtension') {
  426. wrapper[propertyName] = makeErrorWrapper(ctx, propertyName);
  427. } else {
  428. var wrapped = makeErrorWrapper(ctx, propertyName);
  429. wrapper[propertyName] = function () {
  430. var result = wrapped.apply(ctx, arguments);
  431. if (!result) {
  432. return null;
  433. }
  434. return makeDebugContext(result, opt_onErrorFunc, opt_onFunc, opt_err_ctx);
  435. };
  436. }
  437. } else {
  438. makePropertyWrapper(wrapper, ctx, propertyName);
  439. }
  440. }
  441. // Override the getError function with one that returns our saved results.
  442. wrapper.getError = function() {
  443. for (var err in glErrorShadow) {
  444. if (glErrorShadow.hasOwnProperty(err)) {
  445. if (glErrorShadow[err]) {
  446. glErrorShadow[err] = false;
  447. return err;
  448. }
  449. }
  450. }
  451. return ctx.NO_ERROR;
  452. };
  453. return wrapper;
  454. }
  455. function resetToInitialState(ctx) {
  456. var isWebGL2RenderingContext = !!ctx.createTransformFeedback;
  457. if (isWebGL2RenderingContext) {
  458. ctx.bindVertexArray(null);
  459. }
  460. var numAttribs = ctx.getParameter(ctx.MAX_VERTEX_ATTRIBS);
  461. var tmp = ctx.createBuffer();
  462. ctx.bindBuffer(ctx.ARRAY_BUFFER, tmp);
  463. for (var ii = 0; ii < numAttribs; ++ii) {
  464. ctx.disableVertexAttribArray(ii);
  465. ctx.vertexAttribPointer(ii, 4, ctx.FLOAT, false, 0, 0);
  466. ctx.vertexAttrib1f(ii, 0);
  467. if (isWebGL2RenderingContext) {
  468. ctx.vertexAttribDivisor(ii, 0);
  469. }
  470. }
  471. ctx.deleteBuffer(tmp);
  472. var numTextureUnits = ctx.getParameter(ctx.MAX_TEXTURE_IMAGE_UNITS);
  473. for (var ii = 0; ii < numTextureUnits; ++ii) {
  474. ctx.activeTexture(ctx.TEXTURE0 + ii);
  475. ctx.bindTexture(ctx.TEXTURE_CUBE_MAP, null);
  476. ctx.bindTexture(ctx.TEXTURE_2D, null);
  477. if (isWebGL2RenderingContext) {
  478. ctx.bindTexture(ctx.TEXTURE_2D_ARRAY, null);
  479. ctx.bindTexture(ctx.TEXTURE_3D, null);
  480. ctx.bindSampler(ii, null);
  481. }
  482. }
  483. ctx.activeTexture(ctx.TEXTURE0);
  484. ctx.useProgram(null);
  485. ctx.bindBuffer(ctx.ARRAY_BUFFER, null);
  486. ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, null);
  487. ctx.bindFramebuffer(ctx.FRAMEBUFFER, null);
  488. ctx.bindRenderbuffer(ctx.RENDERBUFFER, null);
  489. ctx.disable(ctx.BLEND);
  490. ctx.disable(ctx.CULL_FACE);
  491. ctx.disable(ctx.DEPTH_TEST);
  492. ctx.disable(ctx.DITHER);
  493. ctx.disable(ctx.SCISSOR_TEST);
  494. ctx.blendColor(0, 0, 0, 0);
  495. ctx.blendEquation(ctx.FUNC_ADD);
  496. ctx.blendFunc(ctx.ONE, ctx.ZERO);
  497. ctx.clearColor(0, 0, 0, 0);
  498. ctx.clearDepth(1);
  499. ctx.clearStencil(-1);
  500. ctx.colorMask(true, true, true, true);
  501. ctx.cullFace(ctx.BACK);
  502. ctx.depthFunc(ctx.LESS);
  503. ctx.depthMask(true);
  504. ctx.depthRange(0, 1);
  505. ctx.frontFace(ctx.CCW);
  506. ctx.hint(ctx.GENERATE_MIPMAP_HINT, ctx.DONT_CARE);
  507. ctx.lineWidth(1);
  508. ctx.pixelStorei(ctx.PACK_ALIGNMENT, 4);
  509. ctx.pixelStorei(ctx.UNPACK_ALIGNMENT, 4);
  510. ctx.pixelStorei(ctx.UNPACK_FLIP_Y_WEBGL, false);
  511. ctx.pixelStorei(ctx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
  512. // TODO: Delete this IF.
  513. if (ctx.UNPACK_COLORSPACE_CONVERSION_WEBGL) {
  514. ctx.pixelStorei(ctx.UNPACK_COLORSPACE_CONVERSION_WEBGL, ctx.BROWSER_DEFAULT_WEBGL);
  515. }
  516. ctx.polygonOffset(0, 0);
  517. ctx.sampleCoverage(1, false);
  518. ctx.scissor(0, 0, ctx.canvas.width, ctx.canvas.height);
  519. ctx.stencilFunc(ctx.ALWAYS, 0, 0xFFFFFFFF);
  520. ctx.stencilMask(0xFFFFFFFF);
  521. ctx.stencilOp(ctx.KEEP, ctx.KEEP, ctx.KEEP);
  522. ctx.viewport(0, 0, ctx.canvas.width, ctx.canvas.height);
  523. ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT | ctx.STENCIL_BUFFER_BIT);
  524. if (isWebGL2RenderingContext) {
  525. ctx.drawBuffers([ctx.BACK]);
  526. ctx.readBuffer(ctx.BACK);
  527. ctx.bindBuffer(ctx.COPY_READ_BUFFER, null);
  528. ctx.bindBuffer(ctx.COPY_WRITE_BUFFER, null);
  529. ctx.bindBuffer(ctx.PIXEL_PACK_BUFFER, null);
  530. ctx.bindBuffer(ctx.PIXEL_UNPACK_BUFFER, null);
  531. var numTransformFeedbacks = ctx.getParameter(ctx.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS);
  532. for (var ii = 0; ii < numTransformFeedbacks; ++ii) {
  533. ctx.bindBufferBase(ctx.TRANSFORM_FEEDBACK_BUFFER, ii, null);
  534. }
  535. var numUBOs = ctx.getParameter(ctx.MAX_UNIFORM_BUFFER_BINDINGS);
  536. for (var ii = 0; ii < numUBOs; ++ii) {
  537. ctx.bindBufferBase(ctx.UNIFORM_BUFFER, ii, null);
  538. }
  539. ctx.disable(ctx.RASTERIZER_DISCARD);
  540. ctx.pixelStorei(ctx.UNPACK_IMAGE_HEIGHT, 0);
  541. ctx.pixelStorei(ctx.UNPACK_SKIP_IMAGES, 0);
  542. ctx.pixelStorei(ctx.UNPACK_ROW_LENGTH, 0);
  543. ctx.pixelStorei(ctx.UNPACK_SKIP_ROWS, 0);
  544. ctx.pixelStorei(ctx.UNPACK_SKIP_PIXELS, 0);
  545. ctx.pixelStorei(ctx.PACK_ROW_LENGTH, 0);
  546. ctx.pixelStorei(ctx.PACK_SKIP_ROWS, 0);
  547. ctx.pixelStorei(ctx.PACK_SKIP_PIXELS, 0);
  548. ctx.hint(ctx.FRAGMENT_SHADER_DERIVATIVE_HINT, ctx.DONT_CARE);
  549. }
  550. // TODO: This should NOT be needed but Firefox fails with 'hint'
  551. while(ctx.getError());
  552. }
  553. function makeLostContextSimulatingCanvas(canvas) {
  554. var unwrappedContext_;
  555. var wrappedContext_;
  556. var onLost_ = [];
  557. var onRestored_ = [];
  558. var wrappedContext_ = {};
  559. var contextId_ = 1;
  560. var contextLost_ = false;
  561. var resourceId_ = 0;
  562. var resourceDb_ = [];
  563. var numCallsToLoseContext_ = 0;
  564. var numCalls_ = 0;
  565. var canRestore_ = false;
  566. var restoreTimeout_ = 0;
  567. var isWebGL2RenderingContext;
  568. // Holds booleans for each GL error so can simulate errors.
  569. var glErrorShadow_ = { };
  570. canvas.getContext = function(f) {
  571. return function() {
  572. var ctx = f.apply(canvas, arguments);
  573. // Did we get a context and is it a WebGL context?
  574. if ((ctx instanceof WebGLRenderingContext) || (window.WebGL2RenderingContext && (ctx instanceof WebGL2RenderingContext))) {
  575. if (ctx != unwrappedContext_) {
  576. if (unwrappedContext_) {
  577. throw "got different context"
  578. }
  579. isWebGL2RenderingContext = window.WebGL2RenderingContext && (ctx instanceof WebGL2RenderingContext);
  580. unwrappedContext_ = ctx;
  581. wrappedContext_ = makeLostContextSimulatingContext(unwrappedContext_);
  582. }
  583. return wrappedContext_;
  584. }
  585. return ctx;
  586. }
  587. }(canvas.getContext);
  588. function wrapEvent(listener) {
  589. if (typeof(listener) == "function") {
  590. return listener;
  591. } else {
  592. return function(info) {
  593. listener.handleEvent(info);
  594. }
  595. }
  596. }
  597. var addOnContextLostListener = function(listener) {
  598. onLost_.push(wrapEvent(listener));
  599. };
  600. var addOnContextRestoredListener = function(listener) {
  601. onRestored_.push(wrapEvent(listener));
  602. };
  603. function wrapAddEventListener(canvas) {
  604. var f = canvas.addEventListener;
  605. canvas.addEventListener = function(type, listener, bubble) {
  606. switch (type) {
  607. case 'webglcontextlost':
  608. addOnContextLostListener(listener);
  609. break;
  610. case 'webglcontextrestored':
  611. addOnContextRestoredListener(listener);
  612. break;
  613. default:
  614. f.apply(canvas, arguments);
  615. }
  616. };
  617. }
  618. wrapAddEventListener(canvas);
  619. canvas.loseContext = function() {
  620. if (!contextLost_) {
  621. contextLost_ = true;
  622. numCallsToLoseContext_ = 0;
  623. ++contextId_;
  624. while (unwrappedContext_.getError());
  625. clearErrors();
  626. glErrorShadow_[unwrappedContext_.CONTEXT_LOST_WEBGL] = true;
  627. var event = makeWebGLContextEvent("context lost");
  628. var callbacks = onLost_.slice();
  629. setTimeout(function() {
  630. //log("numCallbacks:" + callbacks.length);
  631. for (var ii = 0; ii < callbacks.length; ++ii) {
  632. //log("calling callback:" + ii);
  633. callbacks[ii](event);
  634. }
  635. if (restoreTimeout_ >= 0) {
  636. setTimeout(function() {
  637. canvas.restoreContext();
  638. }, restoreTimeout_);
  639. }
  640. }, 0);
  641. }
  642. };
  643. canvas.restoreContext = function() {
  644. if (contextLost_) {
  645. if (onRestored_.length) {
  646. setTimeout(function() {
  647. if (!canRestore_) {
  648. throw "can not restore. webglcontestlost listener did not call event.preventDefault";
  649. }
  650. freeResources();
  651. resetToInitialState(unwrappedContext_);
  652. contextLost_ = false;
  653. numCalls_ = 0;
  654. canRestore_ = false;
  655. var callbacks = onRestored_.slice();
  656. var event = makeWebGLContextEvent("context restored");
  657. for (var ii = 0; ii < callbacks.length; ++ii) {
  658. callbacks[ii](event);
  659. }
  660. }, 0);
  661. }
  662. }
  663. };
  664. canvas.loseContextInNCalls = function(numCalls) {
  665. if (contextLost_) {
  666. throw "You can not ask a lost contet to be lost";
  667. }
  668. numCallsToLoseContext_ = numCalls_ + numCalls;
  669. };
  670. canvas.getNumCalls = function() {
  671. return numCalls_;
  672. };
  673. canvas.setRestoreTimeout = function(timeout) {
  674. restoreTimeout_ = timeout;
  675. };
  676. function isWebGLObject(obj) {
  677. //return false;
  678. return (obj instanceof WebGLBuffer ||
  679. obj instanceof WebGLFramebuffer ||
  680. obj instanceof WebGLProgram ||
  681. obj instanceof WebGLRenderbuffer ||
  682. obj instanceof WebGLShader ||
  683. obj instanceof WebGLTexture);
  684. }
  685. function checkResources(args) {
  686. for (var ii = 0; ii < args.length; ++ii) {
  687. var arg = args[ii];
  688. if (isWebGLObject(arg)) {
  689. return arg.__webglDebugContextLostId__ == contextId_;
  690. }
  691. }
  692. return true;
  693. }
  694. function clearErrors() {
  695. var k = Object.keys(glErrorShadow_);
  696. for (var ii = 0; ii < k.length; ++ii) {
  697. delete glErrorShadow_[k[ii]];
  698. }
  699. }
  700. function loseContextIfTime() {
  701. ++numCalls_;
  702. if (!contextLost_) {
  703. if (numCallsToLoseContext_ == numCalls_) {
  704. canvas.loseContext();
  705. }
  706. }
  707. }
  708. // Makes a function that simulates WebGL when out of context.
  709. function makeLostContextFunctionWrapper(ctx, functionName) {
  710. var f = ctx[functionName];
  711. return function() {
  712. // log("calling:" + functionName);
  713. // Only call the functions if the context is not lost.
  714. loseContextIfTime();
  715. if (!contextLost_) {
  716. //if (!checkResources(arguments)) {
  717. // glErrorShadow_[wrappedContext_.INVALID_OPERATION] = true;
  718. // return;
  719. //}
  720. var result = f.apply(ctx, arguments);
  721. return result;
  722. }
  723. };
  724. }
  725. function freeResources() {
  726. for (var ii = 0; ii < resourceDb_.length; ++ii) {
  727. var resource = resourceDb_[ii];
  728. if (resource instanceof WebGLBuffer) {
  729. unwrappedContext_.deleteBuffer(resource);
  730. } else if (resource instanceof WebGLFramebuffer) {
  731. unwrappedContext_.deleteFramebuffer(resource);
  732. } else if (resource instanceof WebGLProgram) {
  733. unwrappedContext_.deleteProgram(resource);
  734. } else if (resource instanceof WebGLRenderbuffer) {
  735. unwrappedContext_.deleteRenderbuffer(resource);
  736. } else if (resource instanceof WebGLShader) {
  737. unwrappedContext_.deleteShader(resource);
  738. } else if (resource instanceof WebGLTexture) {
  739. unwrappedContext_.deleteTexture(resource);
  740. }
  741. else if (isWebGL2RenderingContext) {
  742. if (resource instanceof WebGLQuery) {
  743. unwrappedContext_.deleteQuery(resource);
  744. } else if (resource instanceof WebGLSampler) {
  745. unwrappedContext_.deleteSampler(resource);
  746. } else if (resource instanceof WebGLSync) {
  747. unwrappedContext_.deleteSync(resource);
  748. } else if (resource instanceof WebGLTransformFeedback) {
  749. unwrappedContext_.deleteTransformFeedback(resource);
  750. } else if (resource instanceof WebGLVertexArrayObject) {
  751. unwrappedContext_.deleteVertexArray(resource);
  752. }
  753. }
  754. }
  755. }
  756. function makeWebGLContextEvent(statusMessage) {
  757. return {
  758. statusMessage: statusMessage,
  759. preventDefault: function() {
  760. canRestore_ = true;
  761. }
  762. };
  763. }
  764. return canvas;
  765. function makeLostContextSimulatingContext(ctx) {
  766. // copy all functions and properties to wrapper
  767. for (var propertyName in ctx) {
  768. if (typeof ctx[propertyName] == 'function') {
  769. wrappedContext_[propertyName] = makeLostContextFunctionWrapper(
  770. ctx, propertyName);
  771. } else {
  772. makePropertyWrapper(wrappedContext_, ctx, propertyName);
  773. }
  774. }
  775. // Wrap a few functions specially.
  776. wrappedContext_.getError = function() {
  777. loseContextIfTime();
  778. if (!contextLost_) {
  779. var err;
  780. while (err = unwrappedContext_.getError()) {
  781. glErrorShadow_[err] = true;
  782. }
  783. }
  784. for (var err in glErrorShadow_) {
  785. if (glErrorShadow_[err]) {
  786. delete glErrorShadow_[err];
  787. return err;
  788. }
  789. }
  790. return wrappedContext_.NO_ERROR;
  791. };
  792. var creationFunctions = [
  793. "createBuffer",
  794. "createFramebuffer",
  795. "createProgram",
  796. "createRenderbuffer",
  797. "createShader",
  798. "createTexture"
  799. ];
  800. if (isWebGL2RenderingContext) {
  801. creationFunctions.push(
  802. "createQuery",
  803. "createSampler",
  804. "fenceSync",
  805. "createTransformFeedback",
  806. "createVertexArray"
  807. );
  808. }
  809. for (var ii = 0; ii < creationFunctions.length; ++ii) {
  810. var functionName = creationFunctions[ii];
  811. wrappedContext_[functionName] = function(f) {
  812. return function() {
  813. loseContextIfTime();
  814. if (contextLost_) {
  815. return null;
  816. }
  817. var obj = f.apply(ctx, arguments);
  818. obj.__webglDebugContextLostId__ = contextId_;
  819. resourceDb_.push(obj);
  820. return obj;
  821. };
  822. }(ctx[functionName]);
  823. }
  824. var functionsThatShouldReturnNull = [
  825. "getActiveAttrib",
  826. "getActiveUniform",
  827. "getBufferParameter",
  828. "getContextAttributes",
  829. "getAttachedShaders",
  830. "getFramebufferAttachmentParameter",
  831. "getParameter",
  832. "getProgramParameter",
  833. "getProgramInfoLog",
  834. "getRenderbufferParameter",
  835. "getShaderParameter",
  836. "getShaderInfoLog",
  837. "getShaderSource",
  838. "getTexParameter",
  839. "getUniform",
  840. "getUniformLocation",
  841. "getVertexAttrib"
  842. ];
  843. if (isWebGL2RenderingContext) {
  844. functionsThatShouldReturnNull.push(
  845. "getInternalformatParameter",
  846. "getQuery",
  847. "getQueryParameter",
  848. "getSamplerParameter",
  849. "getSyncParameter",
  850. "getTransformFeedbackVarying",
  851. "getIndexedParameter",
  852. "getUniformIndices",
  853. "getActiveUniforms",
  854. "getActiveUniformBlockParameter",
  855. "getActiveUniformBlockName"
  856. );
  857. }
  858. for (var ii = 0; ii < functionsThatShouldReturnNull.length; ++ii) {
  859. var functionName = functionsThatShouldReturnNull[ii];
  860. wrappedContext_[functionName] = function(f) {
  861. return function() {
  862. loseContextIfTime();
  863. if (contextLost_) {
  864. return null;
  865. }
  866. return f.apply(ctx, arguments);
  867. }
  868. }(wrappedContext_[functionName]);
  869. }
  870. var isFunctions = [
  871. "isBuffer",
  872. "isEnabled",
  873. "isFramebuffer",
  874. "isProgram",
  875. "isRenderbuffer",
  876. "isShader",
  877. "isTexture"
  878. ];
  879. if (isWebGL2RenderingContext) {
  880. isFunctions.push(
  881. "isQuery",
  882. "isSampler",
  883. "isSync",
  884. "isTransformFeedback",
  885. "isVertexArray"
  886. );
  887. }
  888. for (var ii = 0; ii < isFunctions.length; ++ii) {
  889. var functionName = isFunctions[ii];
  890. wrappedContext_[functionName] = function(f) {
  891. return function() {
  892. loseContextIfTime();
  893. if (contextLost_) {
  894. return false;
  895. }
  896. return f.apply(ctx, arguments);
  897. }
  898. }(wrappedContext_[functionName]);
  899. }
  900. wrappedContext_.checkFramebufferStatus = function(f) {
  901. return function() {
  902. loseContextIfTime();
  903. if (contextLost_) {
  904. return wrappedContext_.FRAMEBUFFER_UNSUPPORTED;
  905. }
  906. return f.apply(ctx, arguments);
  907. };
  908. }(wrappedContext_.checkFramebufferStatus);
  909. wrappedContext_.getAttribLocation = function(f) {
  910. return function() {
  911. loseContextIfTime();
  912. if (contextLost_) {
  913. return -1;
  914. }
  915. return f.apply(ctx, arguments);
  916. };
  917. }(wrappedContext_.getAttribLocation);
  918. wrappedContext_.getVertexAttribOffset = function(f) {
  919. return function() {
  920. loseContextIfTime();
  921. if (contextLost_) {
  922. return 0;
  923. }
  924. return f.apply(ctx, arguments);
  925. };
  926. }(wrappedContext_.getVertexAttribOffset);
  927. wrappedContext_.isContextLost = function() {
  928. return contextLost_;
  929. };
  930. if (isWebGL2RenderingContext) {
  931. wrappedContext_.getFragDataLocation = function(f) {
  932. return function() {
  933. loseContextIfTime();
  934. if (contextLost_) {
  935. return -1;
  936. }
  937. return f.apply(ctx, arguments);
  938. };
  939. }(wrappedContext_.getFragDataLocation);
  940. wrappedContext_.clientWaitSync = function(f) {
  941. return function() {
  942. loseContextIfTime();
  943. if (contextLost_) {
  944. return wrappedContext_.WAIT_FAILED;
  945. }
  946. return f.apply(ctx, arguments);
  947. };
  948. }(wrappedContext_.clientWaitSync);
  949. wrappedContext_.getUniformBlockIndex = function(f) {
  950. return function() {
  951. loseContextIfTime();
  952. if (contextLost_) {
  953. return wrappedContext_.INVALID_INDEX;
  954. }
  955. return f.apply(ctx, arguments);
  956. };
  957. }(wrappedContext_.getUniformBlockIndex);
  958. }
  959. return wrappedContext_;
  960. }
  961. }
  962. return {
  963. /**
  964. * Initializes this module. Safe to call more than once.
  965. * @param {!WebGLRenderingContext} ctx A WebGL context. If
  966. * you have more than one context it doesn't matter which one
  967. * you pass in, it is only used to pull out constants.
  968. */
  969. 'init': init,
  970. /**
  971. * Returns true or false if value matches any WebGL enum
  972. * @param {*} value Value to check if it might be an enum.
  973. * @return {boolean} True if value matches one of the WebGL defined enums
  974. */
  975. 'mightBeEnum': mightBeEnum,
  976. /**
  977. * Gets an string version of an WebGL enum.
  978. *
  979. * Example:
  980. * WebGLDebugUtil.init(ctx);
  981. * var str = WebGLDebugUtil.glEnumToString(ctx.getError());
  982. *
  983. * @param {number} value Value to return an enum for
  984. * @return {string} The string version of the enum.
  985. */
  986. 'glEnumToString': glEnumToString,
  987. /**
  988. * Converts the argument of a WebGL function to a string.
  989. * Attempts to convert enum arguments to strings.
  990. *
  991. * Example:
  992. * WebGLDebugUtil.init(ctx);
  993. * var str = WebGLDebugUtil.glFunctionArgToString('bindTexture', 2, 0, gl.TEXTURE_2D);
  994. *
  995. * would return 'TEXTURE_2D'
  996. *
  997. * @param {string} functionName the name of the WebGL function.
  998. * @param {number} numArgs The number of arguments
  999. * @param {number} argumentIndx the index of the argument.
  1000. * @param {*} value The value of the argument.
  1001. * @return {string} The value as a string.
  1002. */
  1003. 'glFunctionArgToString': glFunctionArgToString,
  1004. /**
  1005. * Converts the arguments of a WebGL function to a string.
  1006. * Attempts to convert enum arguments to strings.
  1007. *
  1008. * @param {string} functionName the name of the WebGL function.
  1009. * @param {number} args The arguments.
  1010. * @return {string} The arguments as a string.
  1011. */
  1012. 'glFunctionArgsToString': glFunctionArgsToString,
  1013. /**
  1014. * Given a WebGL context returns a wrapped context that calls
  1015. * gl.getError after every command and calls a function if the
  1016. * result is not NO_ERROR.
  1017. *
  1018. * You can supply your own function if you want. For example, if you'd like
  1019. * an exception thrown on any GL error you could do this
  1020. *
  1021. * function throwOnGLError(err, funcName, args) {
  1022. * throw WebGLDebugUtils.glEnumToString(err) +
  1023. * " was caused by call to " + funcName;
  1024. * };
  1025. *
  1026. * ctx = WebGLDebugUtils.makeDebugContext(
  1027. * canvas.getContext("webgl"), throwOnGLError);
  1028. *
  1029. * @param {!WebGLRenderingContext} ctx The webgl context to wrap.
  1030. * @param {!function(err, funcName, args): void} opt_onErrorFunc The function
  1031. * to call when gl.getError returns an error. If not specified the default
  1032. * function calls console.log with a message.
  1033. * @param {!function(funcName, args): void} opt_onFunc The
  1034. * function to call when each webgl function is called. You
  1035. * can use this to log all calls for example.
  1036. */
  1037. 'makeDebugContext': makeDebugContext,
  1038. /**
  1039. * Given a canvas element returns a wrapped canvas element that will
  1040. * simulate lost context. The canvas returned adds the following functions.
  1041. *
  1042. * loseContext:
  1043. * simulates a lost context event.
  1044. *
  1045. * restoreContext:
  1046. * simulates the context being restored.
  1047. *
  1048. * lostContextInNCalls:
  1049. * loses the context after N gl calls.
  1050. *
  1051. * getNumCalls:
  1052. * tells you how many gl calls there have been so far.
  1053. *
  1054. * setRestoreTimeout:
  1055. * sets the number of milliseconds until the context is restored
  1056. * after it has been lost. Defaults to 0. Pass -1 to prevent
  1057. * automatic restoring.
  1058. *
  1059. * @param {!Canvas} canvas The canvas element to wrap.
  1060. */
  1061. 'makeLostContextSimulatingCanvas': makeLostContextSimulatingCanvas,
  1062. /**
  1063. * Resets a context to the initial state.
  1064. * @param {!WebGLRenderingContext} ctx The webgl context to
  1065. * reset.
  1066. */
  1067. 'resetToInitialState': resetToInitialState
  1068. };
  1069. }();