summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/webcodecs/webgl-test-utils.js
blob: f623a6c9861b23596c5e2c808273ba5c1c5c39ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

WebGLTestUtils = (function() {
  /**
   * Converts a WebGL enum to a string
   * @param {!WebGLContext} gl The WebGLContext to use.
   * @param {number} value The enum value.
   * @return {string} The enum as a string.
   */
  var glEnumToString = function(gl, value) {
    for (var p in gl) {
      if (gl[p] == value) {
        return p;
      }
    }
    return '0x' + value.toString(16);
  };

  var lastError = '';

  /**
   * Returns the last compiler/linker error.
   * @return {string} The last compiler/linker error.
   */
  var getLastError = function() {
    return lastError;
  };

  // clang-format off

  /**
   * A vertex shader for a single texture.
   * @type {string}
   */
  var simpleTextureVertexShader = [
    'attribute vec4 vPosition;',  //
    'attribute vec2 texCoord0;',
    'varying vec2 texCoord;',
    'void main() {',
    '    gl_Position = vPosition;',
    '    texCoord = texCoord0;',
    '}'
  ].join('\n');

  /**
   * A fragment shader for a single texture.
   * @type {string}
   */
  var simpleTextureFragmentShader = [
    'precision mediump float;',
    'uniform sampler2D tex;',
    'varying vec2 texCoord;',
    'void main() {',
    '    gl_FragData[0] = texture2D(tex, texCoord);',
    '}'
  ].join('\n');

  // clang-format on

  /**
   * Creates a simple texture vertex shader.
   * @param {!WebGLContext} gl The WebGLContext to use.
   * @return {!WebGLShader}
   */
  var setupSimpleTextureVertexShader = function(gl) {
    return loadShader(gl, simpleTextureVertexShader, gl.VERTEX_SHADER);
  };

  /**
   * Creates a simple texture fragment shader.
   * @param {!WebGLContext} gl The WebGLContext to use.
   * @return {!WebGLShader}
   */
  var setupSimpleTextureFragmentShader = function(gl) {
    return loadShader(gl, simpleTextureFragmentShader, gl.FRAGMENT_SHADER);
  };

  /**
   * Creates a program, attaches shaders, binds attrib locations, links the
   * program and calls useProgram.
   * @param {!Array.<!WebGLShader>} shaders The shaders to attach .
   * @param {!Array.<string>} opt_attribs The attribs names.
   * @param {!Array.<number>} opt_locations The locations for the attribs.
   */
  var setupProgram = function(gl, shaders, opt_attribs, opt_locations) {
    var realShaders = [];
    var program = gl.createProgram();
    for (var ii = 0; ii < shaders.length; ++ii) {
      var shader = shaders[ii];
      if (typeof shader == 'string') {
        var element = document.getElementById(shader);
        if (element) {
          shader = loadShaderFromScript(gl, shader);
        } else {
          shader = loadShader(
              gl, shader, ii ? gl.FRAGMENT_SHADER : gl.VERTEX_SHADER);
        }
      }
      gl.attachShader(program, shader);
    }
    if (opt_attribs) {
      for (var ii = 0; ii < opt_attribs.length; ++ii) {
        gl.bindAttribLocation(
            program, opt_locations ? opt_locations[ii] : ii, opt_attribs[ii]);
      }
    }
    gl.linkProgram(program);

    // Check the link status
    var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (!linked) {
      gl.deleteProgram(program);
      return null;
    }

    gl.useProgram(program);
    return program;
  };

  /**
   * Creates a simple texture program.
   * @param {!WebGLContext} gl The WebGLContext to use.
   * @param {number} opt_positionLocation The attrib location for position.
   * @param {number} opt_texcoordLocation The attrib location for texture
   *     coords.
   * @return {WebGLProgram}
   */
  var setupSimpleTextureProgram = function(
      gl, opt_positionLocation, opt_texcoordLocation) {
    opt_positionLocation = opt_positionLocation || 0;
    opt_texcoordLocation = opt_texcoordLocation || 1;
    var vs = setupSimpleTextureVertexShader(gl);
    var fs = setupSimpleTextureFragmentShader(gl);
    if (!vs || !fs) {
      return null;
    }
    var program = setupProgram(
        gl, [vs, fs], ['vPosition', 'texCoord0'],
        [opt_positionLocation, opt_texcoordLocation]);
    if (!program) {
      gl.deleteShader(fs);
      gl.deleteShader(vs);
    }
    gl.useProgram(program);
    return program;
  };

  /**
   * Creates buffers for a textured unit quad and attaches them to vertex
   * attribs.
   * @param {!WebGLContext} gl The WebGLContext to use.
   * @param {number} opt_positionLocation The attrib location for position.
   * @param {number} opt_texcoordLocation The attrib location for texture
   *     coords.
   * @return {!Array.<WebGLBuffer>} The buffer objects that were
   *      created.
   */
  var setupUnitQuad = function(gl, opt_positionLocation, opt_texcoordLocation) {
    opt_positionLocation = opt_positionLocation || 0;
    opt_texcoordLocation = opt_texcoordLocation || 1;
    var objects = [];

    var vertexObject = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject);
    gl.bufferData(
        gl.ARRAY_BUFFER, new Float32Array([
          1.0, 1.0, 0.0, -1.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0,
          -1.0, 0.0, 1.0, -1.0, 0.0
        ]),
        gl.STATIC_DRAW);
    gl.enableVertexAttribArray(opt_positionLocation);
    gl.vertexAttribPointer(opt_positionLocation, 3, gl.FLOAT, false, 0, 0);
    objects.push(vertexObject);

    var vertexObject = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject);
    gl.bufferData(
        gl.ARRAY_BUFFER,
        new Float32Array(
            [1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0]),
        gl.STATIC_DRAW);
    gl.enableVertexAttribArray(opt_texcoordLocation);
    gl.vertexAttribPointer(opt_texcoordLocation, 2, gl.FLOAT, false, 0, 0);
    objects.push(vertexObject);
    return objects;
  };

  /**
   * Creates a program and buffers for rendering a textured quad.
   * @param {!WebGLContext} gl The WebGLContext to use.
   * @param {number} opt_positionLocation The attrib location for position.
   * @param {number} opt_texcoordLocation The attrib location for texture
   *     coords.
   * @return {!WebGLProgram}
   */
  var setupTexturedQuad = function(
      gl, opt_positionLocation, opt_texcoordLocation) {
    var program = setupSimpleTextureProgram(
        gl, opt_positionLocation, opt_texcoordLocation);
    setupUnitQuad(gl, opt_positionLocation, opt_texcoordLocation);
    return program;
  };

  /**
   * Draws a previously setup quad.
   * @param {!WebGLContext} gl The WebGLContext to use.
   * @param {!Array.<number>} opt_color The color to fill clear with before
   *        drawing. A 4 element array where each element is in the range 0 to
   *        255. Default [255, 255, 255, 255]
   */
  var drawQuad = function(gl, opt_color) {
    opt_color = opt_color || [255, 255, 255, 255];
    gl.clearColor(
        opt_color[0] / 255, opt_color[1] / 255, opt_color[2] / 255,
        opt_color[3] / 255);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES, 0, 6);
  };

  /**
   * Links a WebGL program, throws if there are errors.
   * @param {!WebGLContext} gl The WebGLContext to use.
   * @param {!WebGLProgram} program The WebGLProgram to link.
   * @param {function(string): void) opt_errorCallback callback for errors.
   */
  var linkProgram = function(gl, program, opt_errorCallback) {
    // Link the program
    gl.linkProgram(program);

    // Check the link status
    var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (!linked) {
      // something went wrong with the link
      gl.deleteProgram(program);
      return false;
    }

    return true;
  };

  /**
   * Loads a shader.
   * @param {!WebGLContext} gl The WebGLContext to use.
   * @param {string} shaderSource The shader source.
   * @param {number} shaderType The type of shader.
   * @param {function(string): void) opt_errorCallback callback for errors.
   * @return {!WebGLShader} The created shader.
   */
  var loadShader =
      function(gl, shaderSource, shaderType, opt_errorCallback) {
    var errFn = opt_errorCallback || (_ => {});
    // Create the shader object
    var shader = gl.createShader(shaderType);
    if (shader == null) {
      errFn('*** Error: unable to create shader \'' + shaderSource + '\'');
      return null;
    }

    // Load the shader source
    gl.shaderSource(shader, shaderSource);
    var err = gl.getError();
    if (err != gl.NO_ERROR) {
      errFn(
          '*** Error loading shader \'' + shader +
          '\':' + glEnumToString(gl, err));
      return null;
    }

    // Compile the shader
    gl.compileShader(shader);

    // Check the compile status
    var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (!compiled) {
      // Something went wrong during compilation; get the error
      lastError = gl.getShaderInfoLog(shader);
      errFn('*** Error compiling shader \'' + shader + '\':' + lastError);
      gl.deleteShader(shader);
      return null;
    }

    return shader;
  }

  /**
   * Loads shaders from source, creates a program, attaches the shaders and
   * links.
   * @param {!WebGLContext} gl The WebGLContext to use.
   * @param {string} vertexShader The vertex shader.
   * @param {string} fragmentShader The fragment shader.
   * @param {function(string): void) opt_errorCallback callback for errors.
   * @return {!WebGLProgram} The created program.
   */
  var loadProgram = function(
      gl, vertexShader, fragmentShader, opt_errorCallback) {
    var program = gl.createProgram();
    gl.attachShader(
        program,
        loadShader(gl, vertexShader, gl.VERTEX_SHADER, opt_errorCallback));
    gl.attachShader(
        program,
        loadShader(gl, fragmentShader, gl.FRAGMENT_SHADER, opt_errorCallback));
    return linkProgram(gl, program, opt_errorCallback) ? program : null;
  };

  return {
    drawQuad: drawQuad,
    getLastError: getLastError,
    glEnumToString: glEnumToString,
    loadProgram: loadProgram,
    loadShader: loadShader,
    setupProgram: setupProgram,
    setupSimpleTextureFragmentShader: setupSimpleTextureFragmentShader,
    setupSimpleTextureProgram: setupSimpleTextureProgram,
    setupSimpleTextureVertexShader: setupSimpleTextureVertexShader,
    setupTexturedQuad: setupTexturedQuad,
    setupUnitQuad: setupUnitQuad,
  };
}());