本节中,我们使用Iñigo Quilez片元渲染器所渲染的影子玩具——曼德尔球[1],将这个例子转化成一个WebCL内核,如图12.4所示。WebGL使用两个纹理三角形对画面进行填充。WebCL每帧都会生成新的纹理。因此,考虑到画布的大小(width,height),WebCL将会生成width x height个像素点。
// retrieva a <canvas> object with id glcanvas in HTML pagevar canvas =documnet.getElementById("glcanvas");// Try to grab the standard context. If it fails, fallback to experimental.var gl =canvas.getContext("webcl") ||canvas.getContext("experimental-webgl");// Create OpenGL texture objectTexture =gl.createTexture();gl.bindTexture(gl.TEXTURE_2D, Texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA, TextureWidth, TextureHeight,0,gl.RGBA,gl.UNSIGNED_BYTE,null);gl.bindTexture(gl.TEXTURE_2D,null);// Create OpenCL representation (a WebCLImage) of OpenGL texturetry{ clTexture =context.createFormGLTexture2D(cl.MEM_WRITE_ONLY,gl.TEXTURE_2D,0, Texture);} catch(ex) {throw"Error: Failed to create WebCLImage."+ ex;}// To use this texture, somewhere in your code, do as usual:glBindTexture(gl.TEXTURE_2D, Texture);
__kernel
void compute(__write_only image2d_t pix, uint width, uint height){
const int x = get_global_id(0);
const int y = get_global_id(1);
// compute pixel color as a float4
write_imagef(pix, (in2)(x, y), color);
}