Depth Texture
HTML
<script src="http://greggman.github.com/webgl-fundamentals/webgl/resources/webgl-utils.js"></script>
<script id="vshader" type="whatever">
attribute vec4 a_position;
varying vec2 v_texcoord;
void main() {
gl_Position = a_position;
v_texcoord = a_position.xy * 0.5 + 0.5;
}
</script>
<script id="fshader" type="whatever">
precision mediump float;
varying vec2 v_texcoord;
uniform sampler2D u_sampler;
void main() {
gl_FragColor = vec4(texture2D(u_sampler, v_texcoord).rgb, 1);
}
</script>
<canvas id="c" width="300" height="300"></canvas>
CSS
canvas { border: 1px solid black; }
JavaScript
var canvas = document.getElementById("c");
var gl = getWebGLContext(canvas);
var program = createProgramFromScripts(
gl, ["vshader", "fshader"], ["a_position"]);
gl.useProgram(program);
var verts = [
1, 1, 1,
-1, 1, 0,
-1, -1, -1,
1, 1, 1,
-1, -1, -1,
1, -1, 0,
];
var vertBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verts), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
// Ugh
gl.RGBA16UI = gl.RGBA16UI || 0x8D76;
gl.RGBA_INTEGER = gl.RGBA_INTEGER || 0x8D99;
gl.RGBA16I = gl.RGBA16I || 0x8D88;
// Likely doesn't work
var colorTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, colorTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16UI, 16, 16, 0, gl.RGBA16UI, gl.UNSIGNED_INT, null);
var error = gl.getError();
if (error) {
alert('This did not work: ' + error);
}
// use the default texture to render with while we render to the depth texture.
gl.bindTexture(gl.TEXTURE_2D, null);
// Render to the depth texture
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 6);
// Now draw with the texture to the canvas
gl.bindTexture(gl.TEXTURE_2D, colorTex);
gl.drawArrays(gl.TRIANGLES, 0, 6);