WebGL
MIT  IAP 2011
Andor Salga (Seneca College)
Benoit Jacob (Mozilla)
Material partly taken from LearningWebGL.com
MIT IAP 2011
WebGL (Web Graphics Library)
 Lowlevel graphics API for JavaScript
 Based on OpenGL ES 2.0
 No plugin required
 Well integrated with the DOM (e.g. texture from DOM element)
 Works on Firefox 4+, WebKit, Chrome/Chromium 9+, and soon Opera
 Can run bits of code on the GPU
 These are known as shaders
 They are compiled at runtime
 Vertex & Fragment shaders
 Vertex shaders compute vertex positions
 Fragment shaders compute pixel colors
 Similar syntax to C
 Strongly typed
float f = 42; // error
 Defer as much as possible into shaders
Example 1  Simple triangle
Example 1  Simple triangle
Vertex Operation
⇓
Rasterization
⇓
Fragment Operation
⇓
FrameBuffer
Matrices (1/4)  Overview
Oversimplifying:
 A matrix is a 3x3 or 4x4 array of numbers representing a geometric transformation
 A rotation is represented by a 3x3 matrix. Not every 3x3 matrix is a rotation.
 Translations can only be represented as 4x4 matrices.
Matrices (2/4)  General form
r_{11}

r_{12}

r_{13}

t_{1}

r_{21}

r_{22}

r_{23}

t_{2}

r_{31}

r_{32}

r_{33}

t_{3}

0

0

0

1

 The topleft 3x3 block is the rotation and scaling.
 The topright 3x1 block is the translation.
 The bottom row is almost always 0, 0, 0, 1.
Matrices (3/4)  Products
 M×V is the vector obtained by applying transformation matrix M to vector V.
 M_{1}×M_{2} is the transformation matrix consisting in applying M_{2} and then M_{1}.
 Order of matrix multiplication matters:
M_{1}×M_{2} ≠ M_{2}×M_{1}
Matrices (4/4)  4D vectors
 WebGL does 3D geometry but often uses 4D vectors.
 Given 3D vector (x, y, z), you get the corresponding 4D vector by appending 1: (x, y, z, 1)
 If instead you append 0, as in (x, y, z, 0), then you get a socalled direction: such a 4D vector is not affected by translations.
Example 3.1  Need depth test
Example 3.1  Need depth test
Diff: enabling depth test
Example 3.2  Using depth test
Example 3.2  Using depth test
 Dynamically change vertex color
 Lighting is Simulated
 Ambient
 Directional
Example 4  Lighting (click me!)
 Per vertex lighting
 Normals
 Calculating directional light
 A_{x} B_{x} + A_{y} B_{y} + A_{z} B_{z} = A B cos (A,B)
Many Objects vs. Texture Mapping
 Drawing many colored objects
 Drawing one textured object
Example 5  Texture Mapping
 Texture = Image
 Texture coordinates (UV)
 Pinning image onto vertices
 Use power of two textures (32x32, 64x128, etc.)
Example 5  Texture Mapping
Example 6  Texture Mapping (LINEAR)
Example 6  Texture Mapping (LINEAR)
Example 7  Texture Mapping (MIP Maps)
Example 7  Texture Mapping (MIP Maps)
 Error console
 console.log('foo') vs. alert('foo')
 WebGL.getError();
Thank You!
Questions?
Benoit Jacob (Mozilla)
Andor Salga (Seneca College)
MIT IAP 2011