summaryrefslogtreecommitdiffstats
path: root/dom/canvas/test/offscreencanvas.js
blob: 50e6a1d53d765409a9e4295debd22af6f189568d (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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/* WebWorker for test_offscreencanvas_*.html */
(function(){

var port = null;

function isInWorker() {
  try {
    return !(self instanceof Window);
  } catch (e) {
    return true;
  }
}

function postMessageGeneral(data) {
  if (isInWorker()) {
    if (port) {
      port.postMessage(data);
    } else {
      postMessage(data);
    }
  } else {
    postMessage(data, "*");
  }
}

function ok(expect, msg) {
  postMessageGeneral({type: "test", result: !!expect, name: msg});
}

function finish() {
  postMessageGeneral({type: "finish"});
}

function drawCount(count) {
  postMessageGeneral({type: "draw", count: count});
}

function sendBlob(blob) {
  postMessageGeneral({type: "blob", blob: blob});
}

function sendImageBitmap(img) {
  if (port) {
    port.postMessage({type: "imagebitmap", bitmap: img});
  } else {
    postMessage({type: "imagebitmap", bitmap: img});
  }
}

//--------------------------------------------------------------------
// WebGL Drawing Functions
//--------------------------------------------------------------------
function createDrawFunc(canvas) {
  var gl;

  try {
    gl = canvas.getContext("experimental-webgl");
  } catch (e) {}

  if (!gl) {
    ok(false, "WebGL is unavailable");
    return null;
  }

  var vertSrc = "attribute vec2 position; \
                 void main(void) { \
                   gl_Position = vec4(position, 0.0, 1.0); \
                 }";

  var fragSrc = "precision mediump float; \
                 void main(void) { \
                   gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0); \
                 }";

  // Returns a valid shader, or null on errors.
  var createShader = function(src, t) {
    var shader = gl.createShader(t);

    gl.shaderSource(shader, src);
    gl.compileShader(shader);

    return shader;
  };

  var createProgram = function(vsSrc, fsSrc) {
    var vs = createShader(vsSrc, gl.VERTEX_SHADER);
    var fs = createShader(fsSrc, gl.FRAGMENT_SHADER);

    var prog = gl.createProgram();
    gl.attachShader(prog, vs);
    gl.attachShader(prog, fs);
    gl.linkProgram(prog);

    if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
      var str = "Shader program linking failed:";
      str += "\nShader program info log:\n" + gl.getProgramInfoLog(prog);
      str += "\n\nVert shader log:\n" + gl.getShaderInfoLog(vs);
      str += "\n\nFrag shader log:\n" + gl.getShaderInfoLog(fs);
      console.log(str);
      ok(false, "Shader program linking failed");
      return null;
    }

    return prog;
  };

  gl.disable(gl.DEPTH_TEST);

  var program = createProgram(vertSrc, fragSrc);
  ok(program, "Creating shader program");

  program.positionAttr = gl.getAttribLocation(program, "position");
  ok(program.positionAttr >= 0, "position attribute should be valid");

  var vertCoordArr = new Float32Array([
    -1, -1,
     1, -1,
    -1,  1,
     1,  1,
  ]);
  var vertCoordBuff = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertCoordBuff);
  gl.bufferData(gl.ARRAY_BUFFER, vertCoordArr, gl.STATIC_DRAW);

  var checkGLError = function(prefix, refValue) {
    if (!refValue) {
      refValue = 0;
    }

    var error = gl.getError();
    ok(error == refValue,
         prefix + 'gl.getError should be 0x' + refValue.toString(16) +
         ', was 0x' + error.toString(16) + '.');
  };

  var testPixel = function(x, y, refData, infoString) {
    var pixel = new Uint8Array(4);
    gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);

    var pixelMatches = pixel[0] == refData[0] &&
                       pixel[1] == refData[1] &&
                       pixel[2] == refData[2] &&
                       pixel[3] == refData[3];
    ok(pixelMatches, infoString);
  };

  var preDraw = function(prefix) {
    gl.clearColor(1.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);

    testPixel(0, 0, [255, 0, 0, 255], prefix + 'Should be red before drawing.');
  };

  var postDraw = function(prefix) {
    testPixel(0, 0, [0, 255, 0, 255], prefix + 'Should be green after drawing.');
  };

  gl.useProgram(program);
  gl.enableVertexAttribArray(program.position);
  gl.vertexAttribPointer(program.position, 2, gl.FLOAT, false, 0, 0);

  // Start drawing
  checkGLError('after setup');

  return function(prefix, needCommitFrame) {
    if (prefix) {
      prefix = "[" + prefix + "] ";
    } else {
      prefix = "";
    }

    gl.viewport(0, 0, canvas.width, canvas.height);
    checkGLError(prefix + "[viewport]");

    preDraw(prefix);
    checkGLError(prefix + "[predraw]");
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
    checkGLError(prefix + "[drawarrays]");
    postDraw(prefix);
    checkGLError(prefix + "[postdraw]");
    if (needCommitFrame) {
      gl.commit();
      checkGLError(prefix + "[commit]");
    }
    checkGLError(prefix);
  };
}

/* entry point */
function entryFunction(testStr, subtests, offscreenCanvas) {
  var test = testStr;
  var canvas = offscreenCanvas;
  if (test == "webgl_imagebitmap") {
    canvas = new OffscreenCanvas(64, 64);
  }

  if (test != "subworker") {
    ok(canvas, "Canvas successfully transfered to worker");
    ok(canvas.getContext, "Canvas has getContext");

    ok(canvas.width == 64, "OffscreenCanvas width should be 64");
    ok(canvas.height == 64, "OffscreenCanvas height should be 64");
  }

  var draw;

  //------------------------------------------------------------------------
  // Basic WebGL test
  //------------------------------------------------------------------------
  if (test == "webgl") {
    draw = createDrawFunc(canvas);
    if (!draw) {
      finish();
      return;
    }

    var count = 0;
    var iid = setInterval(function() {
      if (count++ > 20) {
        clearInterval(iid);
        ok(true, "Worker is done");
        finish();
        return;
      }
      draw("loop " +count, true);
    }, 0);
  }
  //------------------------------------------------------------------------
  // Test dynamic fallback
  //------------------------------------------------------------------------
  else if (test == "webgl_fallback") {
    draw = createDrawFunc(canvas);
    if (!draw) {
      return;
    }

    var count = 0;
    var iid = setInterval(function() {
      ++count;
      draw("loop " + count, true);
      drawCount(count);
    }, 0);
  }
  //------------------------------------------------------------------------
  // Test toBlob
  //------------------------------------------------------------------------
  else if (test == "webgl_toblob") {
    draw = createDrawFunc(canvas);
    if (!draw) {
      return;
    }

    draw("", false);
    canvas.toBlob().then(function(blob) {
      sendBlob(blob);
    });
  }
  //------------------------------------------------------------------------
  // Test toImageBitmap
  //------------------------------------------------------------------------
  else if (test == "webgl_imagebitmap") {
    draw = createDrawFunc(canvas);
    if (!draw) {
      return;
    }

    draw("", false);
    var imgBitmap = canvas.transferToImageBitmap();
    sendImageBitmap(imgBitmap);
  }
  //------------------------------------------------------------------------
  // Canvas Size Change from Worker
  //------------------------------------------------------------------------
  else if (test == "webgl_changesize") {
    draw = createDrawFunc(canvas);
    if (!draw) {
      finish();
      return;
    }

    draw("64x64", true);

    setTimeout(function() {
      canvas.width = 128;
      canvas.height = 128;
      draw("Increased to 128x128", true);

      setTimeout(function() {
        canvas.width = 32;
        canvas.width = 32;
        draw("Decreased to 32x32", true);

        setTimeout(function() {
          canvas.width = 64;
          canvas.height = 64;
          draw("Increased to 64x64", true);

          ok(true, "Worker is done");
          finish();
        }, 0);
      }, 0);
    }, 0);
  }
  //------------------------------------------------------------------------
  // Using OffscreenCanvas from sub workers
  //------------------------------------------------------------------------
  else if (test == "subworker") {
    /* subworker tests take a list of tests to run on children */
    var stillRunning = 0;
    subtests.forEach(function (subtest) {
      ++stillRunning;
      var subworker = new Worker('offscreencanvas.js');
      subworker.onmessage = function(evt) {
        /* report finish to parent when all children are finished */
        if (evt.data.type == "finish") {
          subworker.terminate();
          if (--stillRunning == 0) {
            ok(true, "Worker is done");
            finish();
          }
          return;
        }
        /* relay all other messages to parent */
        postMessage(evt.data);
      };

      var findTransferables = function(t) {
        if (t.test == "subworker") {
          var result = [];
          t.subtests.forEach(function(test) {
            result = result.concat(findTransferables(test));
          });

          return result;
        } else {
          return [t.canvas];
        }
      };

      subworker.postMessage(subtest, findTransferables(subtest));
    });
  }
};

onmessage = function(evt) {
  port = evt.ports[0];
  entryFunction(evt.data.test, evt.data.subtests, evt.data.canvas);
};

onconnect = function(evt) {
  port = evt.ports[0];

  port.addEventListener('message', function(evt) {
    entryFunction(evt.data.test, evt.data.subtests, evt.data.canvas);
  });

  port.start();
};

if (!isInWorker()) {
  window.entryFunction = entryFunction;
}

})();