Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(384)

Side by Side Diff: third_party/webgl/sdk/tests/conformance/resources/webgl-test-utils.js

Issue 9373009: Check in webgl conformance tests r16844 from khronos. (Closed) Base URL: svn://chrome-svn/chrome/trunk/deps/
Patch Set: Created 8 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 WebGLTestUtils = (function() {
6
7 /**
8 * Wrapped logging function.
9 * @param {string} msg The message to log.
10 */
11 var log = function(msg) {
12 if (window.console && window.console.log) {
13 window.console.log(msg);
14 }
15 };
16
17 /**
18 * Wrapped logging function.
19 * @param {string} msg The message to log.
20 */
21 var error = function(msg) {
22 if (window.console) {
23 if (window.console.error) {
24 window.console.error(msg);
25 }
26 else if (window.console.log) {
27 window.console.log(msg);
28 }
29 }
30 };
31
32 /**
33 * Turn off all logging.
34 */
35 var loggingOff = function() {
36 log = function() {};
37 error = function() {};
38 };
39
40 /**
41 * Converts a WebGL enum to a string
42 * @param {!WebGLContext} gl The WebGLContext to use.
43 * @param {number} value The enum value.
44 * @return {string} The enum as a string.
45 */
46 var glEnumToString = function(gl, value) {
47 for (var p in gl) {
48 if (gl[p] == value) {
49 return p;
50 }
51 }
52 return "0x" + value.toString(16);
53 };
54
55 var lastError = "";
56
57 /**
58 * Returns the last compiler/linker error.
59 * @return {string} The last compiler/linker error.
60 */
61 var getLastError = function() {
62 return lastError;
63 };
64
65 /**
66 * Whether a haystack ends with a needle.
67 * @param {string} haystack String to search
68 * @param {string} needle String to search for.
69 * @param {boolean} True if haystack ends with needle.
70 */
71 var endsWith = function(haystack, needle) {
72 return haystack.substr(haystack.length - needle.length) === needle;
73 };
74
75 /**
76 * Whether a haystack starts with a needle.
77 * @param {string} haystack String to search
78 * @param {string} needle String to search for.
79 * @param {boolean} True if haystack starts with needle.
80 */
81 var startsWith = function(haystack, needle) {
82 return haystack.substr(0, needle.length) === needle;
83 };
84
85 /**
86 * A vertex shader for a single texture.
87 * @type {string}
88 */
89 var simpleTextureVertexShader = [
90 'attribute vec4 vPosition;',
91 'attribute vec2 texCoord0;',
92 'varying vec2 texCoord;',
93 'void main() {',
94 ' gl_Position = vPosition;',
95 ' texCoord = texCoord0;',
96 '}'].join('\n');
97
98 /**
99 * A fragment shader for a single texture.
100 * @type {string}
101 */
102 var simpleTextureFragmentShader = [
103 'precision mediump float;',
104 'uniform sampler2D tex;',
105 'varying vec2 texCoord;',
106 'void main() {',
107 ' gl_FragData[0] = texture2D(tex, texCoord);',
108 '}'].join('\n');
109
110 /**
111 * Creates a simple texture vertex shader.
112 * @param {!WebGLContext} gl The WebGLContext to use.
113 * @return {!WebGLShader}
114 */
115 var setupSimpleTextureVertexShader = function(gl) {
116 return loadShader(gl, simpleTextureVertexShader, gl.VERTEX_SHADER);
117 };
118
119 /**
120 * Creates a simple texture fragment shader.
121 * @param {!WebGLContext} gl The WebGLContext to use.
122 * @return {!WebGLShader}
123 */
124 var setupSimpleTextureFragmentShader = function(gl) {
125 return loadShader(
126 gl, simpleTextureFragmentShader, gl.FRAGMENT_SHADER);
127 };
128
129 /**
130 * Creates a program, attaches shaders, binds attrib locations, links the
131 * program and calls useProgram.
132 * @param {!Array.<!WebGLShader>} shaders The shaders to attach .
133 * @param {!Array.<string>} opt_attribs The attribs names.
134 * @param {!Array.<number>} opt_locations The locations for the attribs.
135 */
136 var setupProgram = function(gl, shaders, opt_attribs, opt_locations) {
137 var program = gl.createProgram();
138 for (var ii = 0; ii < shaders.length; ++ii) {
139 gl.attachShader(program, shaders[ii]);
140 }
141 if (opt_attribs) {
142 for (var ii = 0; ii < opt_attribs.length; ++ii) {
143 gl.bindAttribLocation(
144 program,
145 opt_locations ? opt_locations[ii] : ii,
146 opt_attribs[ii]);
147 }
148 }
149 gl.linkProgram(program);
150
151 // Check the link status
152 var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
153 if (!linked) {
154 // something went wrong with the link
155 lastError = gl.getProgramInfoLog (program);
156 error("Error in program linking:" + lastError);
157
158 gl.deleteProgram(program);
159 return null;
160 }
161
162 gl.useProgram(program);
163 return program;
164 };
165
166 /**
167 * Creates a simple texture program.
168 * @param {!WebGLContext} gl The WebGLContext to use.
169 * @param {number} opt_positionLocation The attrib location for position.
170 * @param {number} opt_texcoordLocation The attrib location for texture coords.
171 * @return {WebGLProgram}
172 */
173 var setupSimpleTextureProgram = function(
174 gl, opt_positionLocation, opt_texcoordLocation) {
175 opt_positionLocation = opt_positionLocation || 0;
176 opt_texcoordLocation = opt_texcoordLocation || 1;
177 var vs = setupSimpleTextureVertexShader(gl);
178 var fs = setupSimpleTextureFragmentShader(gl);
179 if (!vs || !fs) {
180 return null;
181 }
182 var program = setupProgram(
183 gl,
184 [vs, fs],
185 ['vPosition', 'texCoord0'],
186 [opt_positionLocation, opt_texcoordLocation]);
187 if (!program) {
188 gl.deleteShader(fs);
189 gl.deleteShader(vs);
190 }
191 gl.useProgram(program);
192 return program;
193 };
194
195 /**
196 * Creates buffers for a textured unit quad and attaches them to vertex attribs.
197 * @param {!WebGLContext} gl The WebGLContext to use.
198 * @param {number} opt_positionLocation The attrib location for position.
199 * @param {number} opt_texcoordLocation The attrib location for texture coords.
200 * @return {!Array.<WebGLBuffer>} The buffer objects that were
201 * created.
202 */
203 var setupUnitQuad = function(gl, opt_positionLocation, opt_texcoordLocation) {
204 opt_positionLocation = opt_positionLocation || 0;
205 opt_texcoordLocation = opt_texcoordLocation || 1;
206 var objects = [];
207
208 var vertexObject = gl.createBuffer();
209 gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject);
210 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
211 1.0, 1.0, 0.0,
212 -1.0, 1.0, 0.0,
213 -1.0, -1.0, 0.0,
214 1.0, 1.0, 0.0,
215 -1.0, -1.0, 0.0,
216 1.0, -1.0, 0.0]), gl.STATIC_DRAW);
217 gl.enableVertexAttribArray(opt_positionLocation);
218 gl.vertexAttribPointer(opt_positionLocation, 3, gl.FLOAT, false, 0, 0);
219 objects.push(vertexObject);
220
221 var vertexObject = gl.createBuffer();
222 gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject);
223 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
224 1.0, 1.0,
225 0.0, 1.0,
226 0.0, 0.0,
227 1.0, 1.0,
228 0.0, 0.0,
229 1.0, 0.0]), gl.STATIC_DRAW);
230 gl.enableVertexAttribArray(opt_texcoordLocation);
231 gl.vertexAttribPointer(opt_texcoordLocation, 2, gl.FLOAT, false, 0, 0);
232 objects.push(vertexObject);
233 return objects;
234 };
235
236 /**
237 * Creates a program and buffers for rendering a textured quad.
238 * @param {!WebGLContext} gl The WebGLContext to use.
239 * @param {number} opt_positionLocation The attrib location for position.
240 * @param {number} opt_texcoordLocation The attrib location for texture coords.
241 * @return {!WebGLProgram}
242 */
243 var setupTexturedQuad = function(
244 gl, opt_positionLocation, opt_texcoordLocation) {
245 var program = setupSimpleTextureProgram(
246 gl, opt_positionLocation, opt_texcoordLocation);
247 setupUnitQuad(gl, opt_positionLocation, opt_texcoordLocation);
248 return program;
249 };
250
251 /**
252 * Creates a unit quad with only positions of a given rez
253 * @param {!WebGLContext} gl The WebGLContext to use.
254 * @param {number} gridRez The resolution of the mesh grid.
255 * @param {number} opt_positionLocation The attrib location for position.
256 */
257 var setupQuad = function (
258 gl, gridRes, opt_positionLocation, opt_flipOddTriangles) {
259 var positionLocation = opt_positionLocation || 0;
260 var objects = [];
261
262 var vertsAcross = gridRes + 1;
263 var numVerts = vertsAcross * vertsAcross;
264 var positions = new Float32Array(numVerts * 3);
265 var indices = new Uint16Array(6 * gridRes * gridRes);
266
267 var poffset = 0;
268
269 for (var yy = 0; yy <= gridRes; ++yy) {
270 for (var xx = 0; xx <= gridRes; ++xx) {
271 positions[poffset + 0] = -1 + 2 * xx / gridRes;
272 positions[poffset + 1] = -1 + 2 * yy / gridRes;
273 positions[poffset + 2] = 0;
274
275 poffset += 3;
276 }
277 }
278
279 var tbase = 0;
280 for (var yy = 0; yy < gridRes; ++yy) {
281 var index = yy * vertsAcross;
282 for (var xx = 0; xx < gridRes; ++xx) {
283 indices[tbase + 0] = index + 0;
284 indices[tbase + 1] = index + 1;
285 indices[tbase + 2] = index + vertsAcross;
286 indices[tbase + 3] = index + vertsAcross;
287 indices[tbase + 4] = index + 1;
288 indices[tbase + 5] = index + vertsAcross + 1;
289
290 if (opt_flipOddTriangles) {
291 indices[tbase + 4] = index + vertsAcross + 1;
292 indices[tbase + 5] = index + 1;
293 }
294
295 index += 1;
296 tbase += 6;
297 }
298 }
299
300 var buf = gl.createBuffer();
301 gl.bindBuffer(gl.ARRAY_BUFFER, buf);
302 gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
303 gl.enableVertexAttribArray(positionLocation);
304 gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0);
305 objects.push(buf);
306
307 var buf = gl.createBuffer();
308 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buf);
309 gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
310 objects.push(buf);
311
312 return objects;
313 };
314
315 /**
316 * Fills the given texture with a solid color
317 * @param {!WebGLContext} gl The WebGLContext to use.
318 * @param {!WebGLTexture} tex The texture to fill.
319 * @param {number} width The width of the texture to create.
320 * @param {number} height The height of the texture to create.
321 * @param {!Array.<number>} color The color to fill with. A 4 element array
322 * where each element is in the range 0 to 255.
323 * @param {number} opt_level The level of the texture to fill. Default = 0.
324 */
325 var fillTexture = function(gl, tex, width, height, color, opt_level) {
326 opt_level = opt_level || 0;
327 var numPixels = width * height;
328 var size = numPixels * 4;
329 var buf = new Uint8Array(size);
330 for (var ii = 0; ii < numPixels; ++ii) {
331 var off = ii * 4;
332 buf[off + 0] = color[0];
333 buf[off + 1] = color[1];
334 buf[off + 2] = color[2];
335 buf[off + 3] = color[3];
336 }
337 gl.bindTexture(gl.TEXTURE_2D, tex);
338 gl.texImage2D(
339 gl.TEXTURE_2D, opt_level, gl.RGBA, width, height, 0,
340 gl.RGBA, gl.UNSIGNED_BYTE, buf);
341 };
342
343 /**
344 * Creates a textures and fills it with a solid color
345 * @param {!WebGLContext} gl The WebGLContext to use.
346 * @param {number} width The width of the texture to create.
347 * @param {number} height The height of the texture to create.
348 * @param {!Array.<number>} color The color to fill with. A 4 element array
349 * where each element is in the range 0 to 255.
350 * @return {!WebGLTexture}
351 */
352 var createColoredTexture = function(gl, width, height, color) {
353 var tex = gl.createTexture();
354 fillTexture(gl, tex, width, height, color);
355 return tex;
356 };
357
358 /**
359 * Draws a previously setup quad.
360 * @param {!WebGLContext} gl The WebGLContext to use.
361 * @param {!Array.<number>} opt_color The color to fill clear with before
362 * drawing. A 4 element array where each element is in the range 0 to
363 * 255. Default [255, 255, 255, 255]
364 */
365 var drawQuad = function(gl, opt_color) {
366 opt_color = opt_color || [255, 255, 255, 255];
367 gl.clearColor(
368 opt_color[0] / 255,
369 opt_color[1] / 255,
370 opt_color[2] / 255,
371 opt_color[3] / 255);
372 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
373 gl.drawArrays(gl.TRIANGLES, 0, 6);
374 };
375
376 /**
377 * Checks that a portion of a canvas is 1 color.
378 * @param {!WebGLContext} gl The WebGLContext to use.
379 * @param {number} x left corner of region to check.
380 * @param {number} y bottom corner of region to check.
381 * @param {number} width width of region to check.
382 * @param {number} height width of region to check.
383 * @param {!Array.<number>} color The color to fill clear with before drawing. A
384 * 4 element array where each element is in the range 0 to 255.
385 * @param {string} msg Message to associate with success. Eg ("should be red").
386 * @param {number} errorRange Optional. Acceptable error in
387 * color checking. 0 by default.
388 */
389 var checkCanvasRect = function(gl, x, y, width, height, color, msg, errorRange) {
390 errorRange = errorRange || 0;
391 var buf = new Uint8Array(width * height * 4);
392 gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, buf);
393 for (var i = 0; i < width * height; ++i) {
394 var offset = i * 4;
395 for (var j = 0; j < color.length; ++j) {
396 if (Math.abs(buf[offset + j] - color[j]) > errorRange) {
397 testFailed(msg);
398 var was = buf[offset + 0].toString();
399 for (j = 1; j < color.length; ++j) {
400 was += "," + buf[offset + j];
401 }
402 debug('at (' + (i % width) + ', ' + Math.floor(i / width) +
403 ') expected: ' + color + ' was ' + was);
404 return;
405 }
406 }
407 }
408 testPassed(msg);
409 };
410
411 /**
412 * Checks that an entire canvas is 1 color.
413 * @param {!WebGLContext} gl The WebGLContext to use.
414 * @param {!Array.<number>} color The color to fill clear with before drawing. A
415 * 4 element array where each element is in the range 0 to 255.
416 * @param {string} msg Message to associate with success. Eg ("should be red").
417 * @param {number} errorRange Optional. Acceptable error in
418 * color checking. 0 by default.
419 */
420 var checkCanvas = function(gl, color, msg, errorRange) {
421 checkCanvasRect(gl, 0, 0, gl.canvas.width, gl.canvas.height, color, msg, error Range);
422 };
423
424 /**
425 * Loads a texture, calls callback when finished.
426 * @param {!WebGLContext} gl The WebGLContext to use.
427 * @param {string} url URL of image to load
428 * @param {function(!Image): void} callback Function that gets called after
429 * image has loaded
430 * @return {!WebGLTexture} The created texture.
431 */
432 var loadTexture = function(gl, url, callback) {
433 var texture = gl.createTexture();
434 gl.bindTexture(gl.TEXTURE_2D, texture);
435 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
436 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
437 var image = new Image();
438 image.onload = function() {
439 gl.bindTexture(gl.TEXTURE_2D, texture);
440 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
441 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, imag e);
442 callback(image);
443 };
444 image.src = url;
445 return texture;
446 };
447
448 /**
449 * Creates a webgl context.
450 * @param {!Canvas} opt_canvas The canvas tag to get context from. If one is not
451 * passed in one will be created.
452 * @return {!WebGLContext} The created context.
453 */
454 var create3DContext = function(opt_canvas, opt_attributes) {
455 opt_canvas = opt_canvas || document.createElement("canvas");
456 var context = null;
457 try {
458 context = opt_canvas.getContext("webgl", opt_attributes);
459 } catch(e) {}
460 if (!context) {
461 try {
462 context = opt_canvas.getContext("experimental-webgl", opt_attributes);
463 } catch(e) {}
464 }
465 if (!context) {
466 testFailed("Unable to fetch WebGL rendering context for Canvas");
467 }
468 return context;
469 }
470
471 /**
472 * Gets a GLError value as a string.
473 * @param {!WebGLContext} gl The WebGLContext to use.
474 * @param {number} err The webgl error as retrieved from gl.getError().
475 * @return {string} the error as a string.
476 */
477 var getGLErrorAsString = function(gl, err) {
478 if (err === gl.NO_ERROR) {
479 return "NO_ERROR";
480 }
481 for (var name in gl) {
482 if (gl[name] === err) {
483 return name;
484 }
485 }
486 return err.toString();
487 };
488
489 /**
490 * Wraps a WebGL function with a function that throws an exception if there is
491 * an error.
492 * @param {!WebGLContext} gl The WebGLContext to use.
493 * @param {string} fname Name of function to wrap.
494 * @return {function} The wrapped function.
495 */
496 var createGLErrorWrapper = function(context, fname) {
497 return function() {
498 var rv = context[fname].apply(context, arguments);
499 var err = context.getError();
500 if (err != 0)
501 throw "GL error " + getGLErrorAsString(err) + " in " + fname;
502 return rv;
503 };
504 };
505
506 /**
507 * Creates a WebGL context where all functions are wrapped to throw an exception
508 * if there is an error.
509 * @param {!Canvas} canvas The HTML canvas to get a context from.
510 * @return {!Object} The wrapped context.
511 */
512 function create3DContextWithWrapperThatThrowsOnGLError(canvas) {
513 var context = create3DContext(canvas);
514 var wrap = {};
515 for (var i in context) {
516 try {
517 if (typeof context[i] == 'function') {
518 wrap[i] = createGLErrorWrapper(context, i);
519 } else {
520 wrap[i] = context[i];
521 }
522 } catch (e) {
523 error("createContextWrapperThatThrowsOnGLError: Error accessing " + i);
524 }
525 }
526 wrap.getError = function() {
527 return context.getError();
528 };
529 return wrap;
530 };
531
532 /**
533 * Tests that an evaluated expression generates a specific GL error.
534 * @param {!WebGLContext} gl The WebGLContext to use.
535 * @param {number} glError The expected gl error.
536 * @param {string} evalSTr The string to evaluate.
537 */
538 var shouldGenerateGLError = function(gl, glError, evalStr) {
539 var exception;
540 try {
541 eval(evalStr);
542 } catch (e) {
543 exception = e;
544 }
545 if (exception) {
546 testFailed(evalStr + " threw exception " + exception);
547 } else {
548 var err = gl.getError();
549 if (err != glError) {
550 testFailed(evalStr + " expected: " + getGLErrorAsString(gl, glError) + ". Was " + getGLErrorAsString(gl, err) + ".");
551 } else {
552 testPassed(evalStr + " was expected value: " + getGLErrorAsString(gl, glEr ror) + ".");
553 }
554 }
555 };
556
557 /**
558 * Tests that the first error GL returns is the specified error.
559 * @param {!WebGLContext} gl The WebGLContext to use.
560 * @param {number} glError The expected gl error.
561 * @param {string} opt_msg
562 */
563 var glErrorShouldBe = function(gl, glError, opt_msg) {
564 opt_msg = opt_msg || "";
565 var err = gl.getError();
566 if (err != glError) {
567 testFailed("getError expected: " + getGLErrorAsString(gl, glError) +
568 ". Was " + getGLErrorAsString(gl, err) + " : " + opt_msg);
569 } else {
570 testPassed("getError was expected value: " +
571 getGLErrorAsString(gl, glError) + " : " + opt_msg);
572 }
573 };
574
575 /**
576 * Links a WebGL program, throws if there are errors.
577 * @param {!WebGLContext} gl The WebGLContext to use.
578 * @param {!WebGLProgram} program The WebGLProgram to link.
579 * @param {function(string): void) opt_errorCallback callback for errors.
580 */
581 var linkProgram = function(gl, program, opt_errorCallback) {
582 errFn = opt_errorCallback || testFailed;
583 // Link the program
584 gl.linkProgram(program);
585
586 // Check the link status
587 var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
588 if (!linked) {
589 // something went wrong with the link
590 var error = gl.getProgramInfoLog (program);
591
592 errFn("Error in program linking:" + error);
593
594 gl.deleteProgram(program);
595 }
596 };
597
598 /**
599 * Sets up WebGL with shaders.
600 * @param {string} canvasName The id of the canvas.
601 * @param {string} vshader The id of the script tag that contains the vertex
602 * shader source.
603 * @param {string} fshader The id of the script tag that contains the fragment
604 * shader source.
605 * @param {!Array.<string>} attribs An array of attrib names used to bind
606 * attribs to the ordinal of the name in this array.
607 * @param {!Array.<number>} opt_clearColor The color to cla
608 * @return {!WebGLContext} The created WebGLContext.
609 */
610 var setupWebGLWithShaders = function(
611 canvasName, vshader, fshader, attribs) {
612 var canvas = document.getElementById(canvasName);
613 var gl = create3DContext(canvas);
614 if (!gl) {
615 testFailed("No WebGL context found");
616 }
617
618 // create our shaders
619 var vertexShader = loadShaderFromScript(gl, vshader);
620 var fragmentShader = loadShaderFromScript(gl, fshader);
621
622 if (!vertexShader || !fragmentShader) {
623 return null;
624 }
625
626 // Create the program object
627 program = gl.createProgram();
628
629 if (!program) {
630 return null;
631 }
632
633 // Attach our two shaders to the program
634 gl.attachShader (program, vertexShader);
635 gl.attachShader (program, fragmentShader);
636
637 // Bind attributes
638 for (var i in attribs) {
639 gl.bindAttribLocation (program, i, attribs[i]);
640 }
641
642 linkProgram(gl, program);
643
644 gl.useProgram(program);
645
646 gl.clearColor(0,0,0,1);
647 gl.clearDepth(1);
648
649 gl.enable(gl.DEPTH_TEST);
650 gl.enable(gl.BLEND);
651 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
652
653 gl.program = program;
654 return gl;
655 };
656
657 /**
658 * Loads text from an external file. This function is synchronous.
659 * @param {string} url The url of the external file.
660 * @param {!function(bool, string): void} callback that is sent a bool for
661 * success and the string.
662 */
663 var loadTextFileAsync = function(url, callback) {
664 log ("loading: " + url);
665 var error = 'loadTextFileSynchronous failed to load url "' + url + '"';
666 var request;
667 if (window.XMLHttpRequest) {
668 request = new XMLHttpRequest();
669 if (request.overrideMimeType) {
670 request.overrideMimeType('text/plain');
671 }
672 } else {
673 throw 'XMLHttpRequest is disabled';
674 }
675 try {
676 request.open('GET', url, true);
677 request.onreadystatechange = function() {
678 if (request.readyState == 4) {
679 var text = '';
680 // HTTP reports success with a 200 status. The file protocol reports
681 // success with zero. HTTP does not use zero as a status code (they
682 // start at 100).
683 // https://developer.mozilla.org/En/Using_XMLHttpRequest
684 var success = request.status == 200 || request.status == 0;
685 if (success) {
686 text = request.responseText;
687 }
688 log("loaded: " + url);
689 callback(success, text);
690 }
691 };
692 request.send(null);
693 } catch (e) {
694 log("failed to load: " + url);
695 callback(false, '');
696 }
697 };
698
699 /**
700 * Recursively loads a file as a list. Each line is parsed for a relative
701 * path. If the file ends in .txt the contents of that file is inserted in
702 * the list.
703 *
704 * @param {string} url The url of the external file.
705 * @param {!function(bool, Array<string>): void} callback that is sent a bool
706 * for success and the array of strings.
707 */
708 var getFileListAsync = function(url, callback) {
709 var files = [];
710
711 var getFileListImpl = function(url, callback) {
712 var files = [];
713 if (url.substr(url.length - 4) == '.txt') {
714 loadTextFileAsync(url, function() {
715 return function(success, text) {
716 if (!success) {
717 callback(false, '');
718 return;
719 }
720 var lines = text.split('\n');
721 var prefix = '';
722 var lastSlash = url.lastIndexOf('/');
723 if (lastSlash >= 0) {
724 prefix = url.substr(0, lastSlash + 1);
725 }
726 var fail = false;
727 var count = 1;
728 var index = 0;
729 for (var ii = 0; ii < lines.length; ++ii) {
730 var str = lines[ii].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
731 if (str.length > 4 &&
732 str[0] != '#' &&
733 str[0] != ";" &&
734 str.substr(0, 2) != "//") {
735 var names = str.split(/ +/);
736 new_url = prefix + str;
737 if (names.length == 1) {
738 new_url = prefix + str;
739 ++count;
740 getFileListImpl(new_url, function(index) {
741 return function(success, new_files) {
742 log("got files: " + new_files.length);
743 if (success) {
744 files[index] = new_files;
745 }
746 finish(success);
747 };
748 }(index++));
749 } else {
750 var s = "";
751 var p = "";
752 for (var jj = 0; jj < names.length; ++jj) {
753 s += p + prefix + names[jj];
754 p = " ";
755 }
756 files[index++] = s;
757 }
758 }
759 }
760 finish(true);
761
762 function finish(success) {
763 if (!success) {
764 fail = true;
765 }
766 --count;
767 log("count: " + count);
768 if (!count) {
769 callback(!fail, files);
770 }
771 }
772 }
773 }());
774
775 } else {
776 files.push(url);
777 callback(true, files);
778 }
779 };
780
781 getFileListImpl(url, function(success, files) {
782 // flatten
783 var flat = [];
784 flatten(files);
785 function flatten(files) {
786 for (var ii = 0; ii < files.length; ++ii) {
787 var value = files[ii];
788 if (typeof(value) == "string") {
789 flat.push(value);
790 } else {
791 flatten(value);
792 }
793 }
794 }
795 callback(success, flat);
796 });
797 };
798
799 /**
800 * Gets a file from a file/URL
801 * @param {string} file the URL of the file to get.
802 * @return {string} The contents of the file.
803 */
804 var readFile = function(file) {
805 var xhr = new XMLHttpRequest();
806 xhr.open("GET", file, false);
807 xhr.send();
808 return xhr.responseText.replace(/\r/g, "");
809 };
810
811 var readFileList = function(url) {
812 var files = [];
813 if (url.substr(url.length - 4) == '.txt') {
814 var lines = readFile(url).split('\n');
815 var prefix = '';
816 var lastSlash = url.lastIndexOf('/');
817 if (lastSlash >= 0) {
818 prefix = url.substr(0, lastSlash + 1);
819 }
820 for (var ii = 0; ii < lines.length; ++ii) {
821 var str = lines[ii].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
822 if (str.length > 4 &&
823 str[0] != '#' &&
824 str[0] != ";" &&
825 str.substr(0, 2) != "//") {
826 var names = str.split(/ +/);
827 if (names.length == 1) {
828 new_url = prefix + str;
829 files = files.concat(readFileList(new_url));
830 } else {
831 var s = "";
832 var p = "";
833 for (var jj = 0; jj < names.length; ++jj) {
834 s += p + prefix + names[jj];
835 p = " ";
836 }
837 files.push(s);
838 }
839 }
840 }
841 } else {
842 files.push(url);
843 }
844 return files;
845 };
846
847 /**
848 * Loads a shader.
849 * @param {!WebGLContext} gl The WebGLContext to use.
850 * @param {string} shaderSource The shader source.
851 * @param {number} shaderType The type of shader.
852 * @param {function(string): void) opt_errorCallback callback for errors.
853 * @return {!WebGLShader} The created shader.
854 */
855 var loadShader = function(gl, shaderSource, shaderType, opt_errorCallback) {
856 var errFn = opt_errorCallback || error;
857 // Create the shader object
858 var shader = gl.createShader(shaderType);
859 if (shader == null) {
860 errFn("*** Error: unable to create shader '"+shaderSource+"'");
861 return null;
862 }
863
864 // Load the shader source
865 gl.shaderSource(shader, shaderSource);
866 var err = gl.getError();
867 if (err != gl.NO_ERROR) {
868 errFn("*** Error loading shader '" + shader + "':" + glEnumToString(gl, err) );
869 return null;
870 }
871
872 // Compile the shader
873 gl.compileShader(shader);
874
875 // Check the compile status
876 var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
877 if (!compiled) {
878 // Something went wrong during compilation; get the error
879 lastError = gl.getShaderInfoLog(shader);
880 errFn("*** Error compiling shader '" + shader + "':" + lastError);
881 gl.deleteShader(shader);
882 return null;
883 }
884
885 return shader;
886 }
887
888 /**
889 * Loads a shader from a URL.
890 * @param {!WebGLContext} gl The WebGLContext to use.
891 * @param {file} file The URL of the shader source.
892 * @param {number} type The type of shader.
893 * @param {function(string): void) opt_errorCallback callback for errors.
894 * @return {!WebGLShader} The created shader.
895 */
896 var loadShaderFromFile = function(gl, file, type, opt_errorCallback) {
897 var shaderSource = readFile(file);
898 return loadShader(gl, shaderSource, type, opt_errorCallback);
899 };
900
901 /**
902 * Gets the content of script.
903 */
904 var getScript = function(scriptId) {
905 var shaderScript = document.getElementById(scriptId);
906 if (!shaderScript) {
907 throw("*** Error: unknown script element" + scriptId);
908 }
909 return shaderScript.text;
910 };
911
912 /**
913 * Loads a shader from a script tag.
914 * @param {!WebGLContext} gl The WebGLContext to use.
915 * @param {string} scriptId The id of the script tag.
916 * @param {number} opt_shaderType The type of shader. If not passed in it will
917 * be derived from the type of the script tag.
918 * @param {function(string): void) opt_errorCallback callback for errors.
919 * @return {!WebGLShader} The created shader.
920 */
921 var loadShaderFromScript = function(
922 gl, scriptId, opt_shaderType, opt_errorCallback) {
923 var shaderSource = "";
924 var shaderType;
925 var shaderScript = document.getElementById(scriptId);
926 if (!shaderScript) {
927 throw("*** Error: unknown script element " + scriptId);
928 }
929 shaderSource = shaderScript.text;
930
931 if (!opt_shaderType) {
932 if (shaderScript.type == "x-shader/x-vertex") {
933 shaderType = gl.VERTEX_SHADER;
934 } else if (shaderScript.type == "x-shader/x-fragment") {
935 shaderType = gl.FRAGMENT_SHADER;
936 } else if (shaderType != gl.VERTEX_SHADER && shaderType != gl.FRAGMENT_SHADE R) {
937 throw("*** Error: unknown shader type");
938 return null;
939 }
940 }
941
942 return loadShader(
943 gl, shaderSource, opt_shaderType ? opt_shaderType : shaderType,
944 opt_errorCallback);
945 };
946
947 var loadStandardProgram = function(gl) {
948 var program = gl.createProgram();
949 gl.attachShader(program, loadStandardVertexShader(gl));
950 gl.attachShader(program, loadStandardFragmentShader(gl));
951 linkProgram(gl, program);
952 return program;
953 };
954
955 /**
956 * Loads shaders from files, creates a program, attaches the shaders and links.
957 * @param {!WebGLContext} gl The WebGLContext to use.
958 * @param {string} vertexShaderPath The URL of the vertex shader.
959 * @param {string} fragmentShaderPath The URL of the fragment shader.
960 * @param {function(string): void) opt_errorCallback callback for errors.
961 * @return {!WebGLProgram} The created program.
962 */
963 var loadProgramFromFile = function(
964 gl, vertexShaderPath, fragmentShaderPath, opt_errorCallback) {
965 var program = gl.createProgram();
966 gl.attachShader(
967 program,
968 loadShaderFromFile(
969 gl, vertexShaderPath, gl.VERTEX_SHADER, opt_errorCallback));
970 gl.attachShader(
971 program,
972 loadShaderFromFile(
973 gl, fragmentShaderPath, gl.FRAGMENT_SHADER, opt_errorCallback));
974 linkProgram(gl, program, opt_errorCallback);
975 return program;
976 };
977
978 /**
979 * Loads shaders from script tags, creates a program, attaches the shaders and
980 * links.
981 * @param {!WebGLContext} gl The WebGLContext to use.
982 * @param {string} vertexScriptId The id of the script tag that contains the
983 * vertex shader.
984 * @param {string} fragmentScriptId The id of the script tag that contains the
985 * fragment shader.
986 * @param {function(string): void) opt_errorCallback callback for errors.
987 * @return {!WebGLProgram} The created program.
988 */
989 var loadProgramFromScript = function loadProgramFromScript(
990 gl, vertexScriptId, fragmentScriptId, opt_errorCallback) {
991 var program = gl.createProgram();
992 gl.attachShader(
993 program,
994 loadShaderFromScript(
995 gl, vertexScriptId, gl.VERTEX_SHADER, opt_errorCallback));
996 gl.attachShader(
997 program,
998 loadShaderFromScript(
999 gl, fragmentScriptId, gl.FRAGMENT_SHADER, opt_errorCallback));
1000 linkProgram(gl, program, opt_errorCallback);
1001 return program;
1002 };
1003
1004 /**
1005 * Loads shaders from source, creates a program, attaches the shaders and
1006 * links.
1007 * @param {!WebGLContext} gl The WebGLContext to use.
1008 * @param {string} vertexShader The vertex shader.
1009 * @param {string} fragmentShader The fragment shader.
1010 * @param {function(string): void) opt_errorCallback callback for errors.
1011 * @return {!WebGLProgram} The created program.
1012 */
1013 var loadProgram = function(
1014 gl, vertexShader, fragmentShader, opt_errorCallback) {
1015 var program = gl.createProgram();
1016 gl.attachShader(
1017 program,
1018 loadShader(
1019 gl, vertexShader, gl.VERTEX_SHADER, opt_errorCallback));
1020 gl.attachShader(
1021 program,
1022 loadShader(
1023 gl, fragmentShader, gl.FRAGMENT_SHADER, opt_errorCallback));
1024 linkProgram(gl, program, opt_errorCallback);
1025 return program;
1026 };
1027
1028 /**
1029 * Loads shaders from source, creates a program, attaches the shaders and
1030 * links but expects error.
1031 *
1032 * GLSL 1.0.17 10.27 effectively says that compileShader can
1033 * always succeed as long as linkProgram fails so we can't
1034 * rely on compileShader failing. This function expects
1035 * one of the shader to fail OR linking to fail.
1036 *
1037 * @param {!WebGLContext} gl The WebGLContext to use.
1038 * @param {string} vertexShaderScriptId The vertex shader.
1039 * @param {string} fragmentShaderScriptId The fragment shader.
1040 * @return {WebGLProgram} The created program.
1041 */
1042 var loadProgramFromScriptExpectError = function(
1043 gl, vertexShaderScriptId, fragmentShaderScriptId) {
1044 var vertexShader = loadShaderFromScript(gl, vertexShaderScriptId);
1045 if (!vertexShader) {
1046 return null;
1047 }
1048 var fragmentShader = loadShaderFromScript(gl, fragmentShaderScriptId);
1049 if (!fragmentShader) {
1050 return null;
1051 }
1052 var linkSuccess = true;
1053 var program = gl.createProgram();
1054 gl.attachShader(program, vertexShader);
1055 gl.attachShader(program, fragmentShader);
1056 linkSuccess = true;
1057 linkProgram(gl, program, function() {
1058 linkSuccess = false;
1059 });
1060 return linkSuccess ? program : null;
1061 };
1062
1063 var basePath;
1064 var getBasePath = function() {
1065 if (!basePath) {
1066 var expectedBase = "webgl-test-utils.js";
1067 var scripts = document.getElementsByTagName('script');
1068 for (var script, i = 0; script = scripts[i]; i++) {
1069 var src = script.src;
1070 var l = src.length;
1071 if (src.substr(l - expectedBase.length) == expectedBase) {
1072 basePath = src.substr(0, l - expectedBase.length);
1073 }
1074 }
1075 }
1076 return basePath;
1077 };
1078
1079 var loadStandardVertexShader = function(gl) {
1080 return loadShaderFromFile(
1081 gl, getBasePath() + "vertexShader.vert", gl.VERTEX_SHADER);
1082 };
1083
1084 var loadStandardFragmentShader = function(gl) {
1085 return loadShaderFromFile(
1086 gl, getBasePath() + "fragmentShader.frag", gl.FRAGMENT_SHADER);
1087 };
1088
1089 /**
1090 * Loads an image asynchronously.
1091 * @param {string} url URL of image to load.
1092 * @param {!function(!Element): void} callback Function to call
1093 * with loaded image.
1094 */
1095 var loadImageAsync = function(url, callback) {
1096 var img = document.createElement('img');
1097 img.onload = function() {
1098 callback(img);
1099 };
1100 img.src = url;
1101 };
1102
1103 /**
1104 * Loads an array of images.
1105 * @param {!Array.<string>} urls URLs of images to load.
1106 * @param {!function(!{string, img}): void} callback. Callback
1107 * that gets passed map of urls to img tags.
1108 */
1109 var loadImagesAsync = function(urls, callback) {
1110 var count = 1;
1111 var images = { };
1112 function countDown() {
1113 --count;
1114 if (count == 0) {
1115 callback(images);
1116 }
1117 }
1118 function imageLoaded(url) {
1119 return function(img) {
1120 images[url] = img;
1121 countDown();
1122 }
1123 }
1124 for (var ii = 0; ii < urls.length; ++ii) {
1125 ++count;
1126 loadImageAsync(urls[ii], imageLoaded(urls[ii]));
1127 }
1128 countDown();
1129 };
1130
1131 var getUrlArguments = function() {
1132 var args = {};
1133 try {
1134 var s = window.location.href;
1135 var q = s.indexOf("?");
1136 var e = s.indexOf("#");
1137 if (e < 0) {
1138 e = s.length;
1139 }
1140 var query = s.substring(q + 1, e);
1141 var pairs = query.split("&");
1142 for (var ii = 0; ii < pairs.length; ++ii) {
1143 var keyValue = pairs[ii].split("=");
1144 var key = keyValue[0];
1145 var value = decodeURIComponent(keyValue[1]);
1146 args[key] = value;
1147 }
1148 } catch (e) {
1149 throw "could not parse url";
1150 }
1151 return args;
1152 };
1153
1154 return {
1155 create3DContext: create3DContext,
1156 create3DContextWithWrapperThatThrowsOnGLError:
1157 create3DContextWithWrapperThatThrowsOnGLError,
1158 checkCanvas: checkCanvas,
1159 checkCanvasRect: checkCanvasRect,
1160 createColoredTexture: createColoredTexture,
1161 drawQuad: drawQuad,
1162 endsWith: endsWith,
1163 getFileListAsync: getFileListAsync,
1164 getLastError: getLastError,
1165 getScript: getScript,
1166 getUrlArguments: getUrlArguments,
1167 glEnumToString: glEnumToString,
1168 glErrorShouldBe: glErrorShouldBe,
1169 fillTexture: fillTexture,
1170 loadImageAsync: loadImageAsync,
1171 loadImagesAsync: loadImagesAsync,
1172 loadProgram: loadProgram,
1173 loadProgramFromFile: loadProgramFromFile,
1174 loadProgramFromScript: loadProgramFromScript,
1175 loadProgramFromScriptExpectError: loadProgramFromScriptExpectError,
1176 loadShader: loadShader,
1177 loadShaderFromFile: loadShaderFromFile,
1178 loadShaderFromScript: loadShaderFromScript,
1179 loadStandardProgram: loadStandardProgram,
1180 loadStandardVertexShader: loadStandardVertexShader,
1181 loadStandardFragmentShader: loadStandardFragmentShader,
1182 loadTextFileAsync: loadTextFileAsync,
1183 loadTexture: loadTexture,
1184 log: log,
1185 loggingOff: loggingOff,
1186 error: error,
1187 setupProgram: setupProgram,
1188 setupQuad: setupQuad,
1189 setupSimpleTextureFragmentShader: setupSimpleTextureFragmentShader,
1190 setupSimpleTextureProgram: setupSimpleTextureProgram,
1191 setupSimpleTextureVertexShader: setupSimpleTextureVertexShader,
1192 setupTexturedQuad: setupTexturedQuad,
1193 setupUnitQuad: setupUnitQuad,
1194 setupWebGLWithShaders: setupWebGLWithShaders,
1195 startsWith: startsWith,
1196 shouldGenerateGLError: shouldGenerateGLError,
1197 readFile: readFile,
1198 readFileList: readFileList,
1199
1200 none: false
1201 };
1202
1203 }());
1204
1205
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698