[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Public WebGL] Asynchronous context creation



Context creation via getContext can take some time, depending on the operating system, drivers, and so on. Pages may create lots of small WebGL contexts to composit into a larger page. This can take enough time to perceptibly slow page loads. I'd propose the following, which is a very small tweak to the proposal in the "Canvas.getContext error handling" thread [1]:

var ctx = canvas.getContext("webgl", {async: true});
assert(ctx.isContextLost()); // guaranteed

function initWebGL(event)

{
ÂÂÂ // init ctx normally
}

function webGLError(event)

{
ÂÂÂ alert("WebGL error: " + event.statusMessage);
ÂÂÂ event.preventDefault(); // permit recovery if it becomes possible later
}

canvas.addEventListener("webglcontextrestored", initWebGL, false);
canvas.addEventListener("webglcontextlost", webGLError, false);

webglcontextrestored or webglcontextlost would be fired from the event loop (not from getContext), indicating that initialization succeeded or failed. The context would initially be lost.

This is natural to _javascript_ developers, following the callback mechanism used by other async APIs like XHR and FileReader. Note that browsers wouldn't be required to actually initialize contexts in a thread; only the API semantics would actually be required.

This also encourages an initialization pattern where handling context loss is straightforward. Currently, people tend to first write code without considering context loss, and need to refactor later to support it, which often is simply never done. Context restoration would still need to be tested by developers, of course, but the likelihood of it just working is much higher.

(For those not familiar with DOM Events and the event loop, note that in the above sample code, it's guaranteed safe to call addEventListener after calling getContext. Those events are fired from a queued task, which won't run until the user code returns to the event loop. This mechanism is used by all modern web APIs.)


[1] https://www.khronos.org/webgl/public-mailing-list/archives/1104/msg00096.html

--
Glenn Maynard