Game Development Reference
In-Depth Information
In Figure 7-7, we start with raw modelspace vertex positions. The vertex shader then transforms the
vertices, usually by multiplying with the MVP matrices. Vertices are assembled into appropriate primitive
types, such as points, lines, and triangles. Next the primitives are rasterized into smaller pixel fragments
and passed to the fragment shader. The fragment shader interpolates color, lighting, and texture
coordinates.
Vertex and fragment shaders are written in GLSL, which is a C-style language. We can include the source
in a JavaScript tag or external file. The script type is "x-shader/x-vertex" or "x-shader/x-fragment"
respectively.
The vertex shader is responsible for model view and projection matrices. It also does normal vector and
texture coordinate generation and transformation. Per-vertex lighting can be done in the vertex shader or
these values can be passed on to the fragment shader for per-pixel computation.
Minimally, a vertex shader needs to pass the original position of each vertex onto the fragment shader, as
shown in Listing 7-2.
Listing 7-2. The Simplest Possible Vertex Shader, Which Passes the Input Vertex Positions to the Fragment Shader
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 aVertexPosition;
void main(void) {
gl_Position = aVertexPosition;
}
</script>
The fragment shader operates on parts of a primitive shape. It computes per-pixel color, texture
coordinates, and normals. The fragment shader also applies textures and fog. Minimally, the fragment
shader needs to set the fragment color, as shown in Listing 7-3.
Listing 7-3. The Simplest Possible Fragment Shader, Which Sets Every Fragment to the Same Color (White)
<script id="shader-fs" type="x-shader/x-fragment">
void main(void) {
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
</script>
Using WebGL
Drawing a simple shape
In our first example of actual WebGL usage, we will display a shaded blue square on a green background.
In Listing 7-4, which is the start of our demo, we will define the basic style used, import the jQuery library
from the Google CDN, and also include a local copy of the glmatrix.js file, which can be downloaded
at https://github.com/toji/gl-matrix/downloads . We will also create a canvas element dimension of
500 × 500.
 
Search WWH ::




Custom Search