- A 3D Canvas
- WebGL ES
- Compiling Shaders
- Passing Data to the GPU
- Overall
Compiling Shaders
The heavy lifting in OpenGL ES[md]and, by extension, WebGL[md]is done by shaders. In an OpenGL ES program, you quite often embed these shaders in strings in C source files and then load them. WebGL provides a somewhat cleaner mechanism. You can embed code in HTML documents inside <script> tags[md]that's how you provide JavaScript code. You can embed GLSL programs in exactly the same way. The only difference is that you use either x-shader/x-fragment or x-shader/x-vertex as the type, rather than text/javascript.
If you also specify an id attribute on these scripts, you can reference them from JavaScript by using getElementById(). To compile a fragment shader that's embedded in the HTML, you'd use something like this sequence:
var gl = canvas.getContext('webgl'); var vShaderSource = document.getElementById('vShader'); var vShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vShader, vShaderSource); gl.compileShader(vShaderSource);
First you get the WebGL context and then the shader source. Next, you create a shader program object, which allocates some space for the shader program and the associated resources in the OpenGL stack. Notice how the values that would be global constants in a header in OpenGL ES are uppercase properties of the context object in WebGL. This structure mirrors how JOGL is designed.
The final two steps associate the shader source with the shader object and then compile it. If all goes well, vShader will then contain an object referencing a compiled shader, which is loaded onto the GPU and can be run. If something goes wrong, you can check the compile status parameter of the shader to find out what happened.
This sequence skipped over a lot of error-checking. Fortunately, the Khronos Group makes a utils3d.js file available that provides a lot of convenience functions for you, including functions for setting up the context with a fragment and vertex shader. The initWebGL() function in utils3d.js will set up a WebGL context for you and compile vertex and fragment shaders from script elements specified by ID. You can use this shortcut instead of creating the same code every time you use WebGL, but it's worth understanding how it all works.