cse3431-webGL-GLSL.key
1
Introduction to Computer Graphics
with WebGL
Ed Angel
Professor Emeritus of Computer Science
Founding Director, Arts, Research, Technology and Science
Laboratory
University of New Mexico
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
2
Models and Architectures
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
3
Objectives
•Learn the basic design of a graphics
system
• Introduce pipeline architecture
•Examine software components for an
interactive graphics system
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
4
Image Formation Revisited
•Can we mimic the synthetic camera model
to design graphics hardware software?
•Application Programmer Interface (API)
Need only specify
• Objects
• Materials
• Viewer
• Lights
•But how is the API implemented?
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
5
Physical Approaches
• Ray tracing: follow rays of light from center of
projection until they either are absorbed by
objects or go off to infinity
Can handle global effects
• Multiple reflections
• Translucent objects
Slow
Must have whole data base
available at all times
• Radiosity: Energy based approach
Very slow
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
6
Practical Approach
•Process objects one at a time in the order
they are generated by the application
Can consider only local lighting
•Pipeline architecture
•All steps can be implemented in hardware
on the graphics card
application
program display
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
7
Vertex Processing
•Much of the work in the pipeline is in converting
object representations from one coordinate
system to another
Object coordinates
Camera (eye) coordinates
Screen coordinates
•Every change of coordinates is equivalent to a
matrix transformation
•Vertex processor also computes vertex colors
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
8
Projection
•Projection is the process that combines
the 3D viewer with the 3D objects to
produce the 2D image
Perspective projections: all projectors meet at the
center of projection
Parallel projection: projectors are parallel, center
of projection is replaced by a direction of
projection
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
9
Primitive Assembly
Vertices must be collected into geometric
objects before clipping and rasterization
can take place
Line segments
Polygons
Curves and surfaces
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
10
Clipping
Just as a real camera cannot “see” the
whole world, the virtual camera can only
see part of the world or object space
Objects that are not within this volume are said to
be clipped out of the scene
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
11
Rasterization
• If an object is not clipped out, the appropriate pixels
in the frame buffer must be assigned colors
•Rasterizer produces a set of fragments for each
object
• Fragments are “potential pixels”
Have a location in frame bufffer
Color and depth attributes
•Vertex attributes are interpolated over objects by
the rasterizer
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
12
Fragment Processing
•Fragments are processed to determine the
color of the corresponding pixel in the
frame buffer
•Colors can be determined by texture
mapping or interpolation of vertex colors
•Fragments may be blocked by other
fragments closer to the camera
Hidden-surface removal
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
13
The Programmer’s Interface
•Programmer sees the graphics system
through a software interface: the
Application Programmer Interface (API)
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
14
API Contents
•Functions that specify what we need to
form an image
Objects
Viewer
Light Source(s)
Materials
•Other information
Input from devices such as mouse and keyboard
Capabilities of system
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
15
Object Specification
•Most APIs support a limited set of
primitives including
Points (0D object)
Line segments (1D objects)
Polygons (2D objects)
Some curves and surfaces
• Quadrics
• Parametric polynomials
•All are defined through locations in space
or vertices
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
16
Example (old style)
glBegin(GL_POLYGON)
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 0.0, 1.0);
glEnd( );
type of object
location of vertex
end of object definition
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Example (GPU based)
17
var points = [
vec3(0.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0),
];
•Put geometric data in an array
•Send array to GPU
•Tell GPU to render as triangle
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
18
Camera Specification
•Six degrees of freedom
Position of center of lens
Orientation
•Lens
•Film size
•Orientation of film plane
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
19
Lights and Materials
•Types of lights
Point sources vs distributed sources
Spot lights
Near and far sources
Color properties
•Material properties
Absorption: color properties
Scattering
• Diffuse
• Specular
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
20
Programming with WebGL
Part 1: Background
•Ed Angel
•Professor Emeritus of Computer Science
•University of New Mexico
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
21
Objectives
•Development of the OpenGL API
•OpenGL Architecture
OpenGL as a state machine
OpenGL as a data flow machine
•Functions
Types
Formats
•Simple program
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
22
Early History of APIs
• IFIPS (1973) formed two committees to
come up with a standard graphics API
Graphical Kernel System (GKS)
• 2D but contained good workstation model
Core
• Both 2D and 3D
GKS adopted as IS0 and later ANSI standard
(1980s)
•GKS not easily extended to 3D (GKS-3D)
Far behind hardware development
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
23
PHIGS and X
•Programmers Hierarchical Graphics
System (PHIGS)
Arose from CAD community
Database model with retained graphics
(structures)
•X Window System
DEC/MIT effort
Client-server architecture with graphics
•PEX combined the two
Not easy to use (all the defects of each)
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
25
OpenGL
The success of GL lead to OpenGL (1992),
a platform-independent API that was
Easy to use
Close enough to the hardware to get excellent
performance
Focus on rendering
Omitted windowing and input to avoid window
system dependencies
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
26
OpenGL Evolution
•Originally controlled by an Architectural Review Board
(ARB)
Members included SGI, Microsoft, Nvidia, HP, 3DLabs,
IBM,…….
Now Kronos Group
Was relatively stable (through version 2.5)
• Backward compatible
• Evolution reflected new hardware capabilities
– 3D texture mapping and texture objects
– Vertex and fragment programs
Allows platform specific features through extensions
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Modern OpenGL
•Performance is achieved by using GPU
rather than CPU
•Control GPU through programs called
shaders
•Application’s job is to send data to GPU
•GPU does all rendering
27Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Immediate Mode Graphics
•Geometry specified by vertices
Locations in space( 2 or 3 dimensional)
Points, lines, circles, polygons, curves, surfaces
• Immediate mode
Each time a vertex is specified in application, its
location is sent to the GPU
Old style uses glVertex
Creates bottleneck between CPU and GPU
Removed from OpenGL 3.1 and OpenGL ES 2.0
28Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Retained Mode Graphics
•Put all vertex attribute data in array
•Send array to GPU to be rendered
immediately
•Almost OK but problem is we would have
to send array over each time we need
another render of it
•Better to send array over and store on
GPU for multiple renderings
29Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
OpenGL 3.1
•Totally shader-based
No default shaders
Each application must provide both a vertex and a
fragment shader
•No immediate mode
•Few state variables
•Most 2.5 functions deprecated
•Backward compatibility not required
Exists a compatibility extension
30Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Other Versions
•OpenGL ES
Embedded systems
Version 1.0 simplified OpenGL 2.1
Version 2.0 simplified OpenGL 3.1
• Shader based
•WebGL
Javascript implementation of ES 2.0
Supported on newer browsers
•OpenGL 4.1, 4.2, …..
Add geometry, tessellation, compute shaders
31Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
33
OpenGL Architecture
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
35
A OpenGL Simple Program
Generate a square on a solid background
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
It used to be easy
36
#include
void mydisplay(){
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_QUAD;
glVertex2f(-0.5, -0.5);
glVertex2f(-0,5, 0,5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd()
}
int main(int argc, char** argv){
glutCreateWindow(“simple”);
glutDisplayFunc(mydisplay);
glutMainLoop();
}
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
37
What happened?
•Most OpenGL functions deprecated
immediate vs retained mode
make use of GPU
•Makes heavy use of state variable default
values that no longer exist
Viewing
Colors
Window parameters
•However, processing loop is the same
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Execution in Browser
38
Application
program
Browser Web
Server
Canvas
HTML
JS
files
URL
Web Page
JS Engine
CPU/GPU
Framebuffer
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
39
Event Loop
•Remember that the sample program
specifies a render function which is a
event listener or callback function
Every program should have a render callback
For a static application we need only execute the
render function once
In a dynamic application, the render function can
call itself recursively but each redrawing of the
display must be triggered by an event
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
40
Lack of Object Orientation
•All versions of OpenGL are not object
oriented so that there are multiple functions
for a given logical function
•Example: sending values to shaders
gl.uniform3f
gl.uniform2i
gl.uniform3dv
•Underlying storage mode is the same
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
41
WebGL function format
gl.uniform3f(x,y,z)
belongs to WebGL canvas
function name
x,y,z are variables
gl.uniform3fv(p)
p is an array
dimension
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
42
WebGL constants
•Most constants are defined in the canvas
object
In desktop OpenGL, they were in #include files
such as gl.h
•Examples
desktop OpenGL
•glEnable(GL_DEPTH_TEST);
WebGL
•gl.enable(gl.DEPTH_TEST)
gl.clear(gl.COLOR_BUFFER_BIT)
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
WebGL and GLSL
•WebGL requires shaders and is based
less on a state machine model than a data
flow model
•Most state variables, attributes and related
pre 3.1 OpenGL functions have been
deprecated
•Action happens in shaders
•Job of application is to get data to GPU
43Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
GLSL
•OpenGL Shading Language
•C-like with
Matrix and vector types (2, 3, 4 dimensional)
Overloaded operators
C++ like constructors
•Similar to Nvidia’s Cg and Microsoft HLSL
•Code sent to shaders as source code
•WebGL functions compile, link and get
information to shaders
44Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Square Program
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
WebGL
•Five steps
Describe page (HTML file)
• request WebGL Canvas
• read in necessary files
Define shaders (HTML file)
• could be done with a separate file (browser dependent)
Compute or specify data (JS file)
Send data to GPU (JS file)
Render data (JS file)
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
square.html
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Shaders
•We assign names to the shaders that we can use
in the JS file
•These are trivial pass-through (do nothing)
shaders that set the two required built-in variables
gl_Position
gl_FragColor
•Note both shaders are full programs
•Note vector type vec4
•Must set precision in fragment shader
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
square.html (cont)
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Files
•../Common/webgl-utils.js: Standard
utilities for setting up WebGL context in
Common directory on website
•../Common/initShaders.js: contains
JS and WebGL code for reading, compiling
and linking the shaders
•../Common/MV.js: our matrix-vector
package
•square.js: the application file
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
square.js
var gl;
var points;
window.onload = function init(){
var canvas = document.getElementById( “gl-canvas” );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( “WebGL isn’t available” );
}
// Four Vertices
var vertices = [
vec2( -0.5, -0.5 ),
vec2( -0.5, 0.5 ),
vec2( 0.5, 0.5 ),
vec2( 0.5, -0.5)
];
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Notes
•onload: determines where to start
execution when all code is loaded
•canvas gets WebGL context from HTML file
• vertices use vec2 type in MV.js
•JS array is not the same as a C or Java
array
object with methods
vertices.length // 4
•Values in clip coordinates
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
square.js (cont)
// Configure WebGL
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
// Load shaders and initialize attribute buffers
var program = initShaders( gl, “vertex-shader”, “fragment-shader” );
gl.useProgram( program );
// Load the data into the GPU
var bufferId = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
gl.bufferData( gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW );
// Associate out shader variables with our data buffer
var vPosition = gl.getAttribLocation( program, “vPosition” );
gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
!51
Canvas and OpenGL
From square.html:
From square.js
gl.viewport( 0, 0, canvas.width, canvas.height );
• In clip coordinates the viewport in WebGL is [-1,1]
• Normally we set it by the projection transformation
gl.viewport( 0, 0, canvas.width, canvas.height ); —- gl.viewport( 0, 0, canvas.width/2.0, canvas.height/2.0 );
x
y
(0,0) Width
(512,512)
Height
(-1,-1)
(1,1)
(512,512)
(0,0)
• So, the viewport transformation decides which part of the
window the image will cover
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.viewport( 0, 0, canvas.width/2.0, canvas.height/2.0 );
gl.viewport( 0, 0, canvas.width, canvas.height/2.0 );
!52
Canvas and OpenGL
x
y
(1,1)
(-1,-1)
!53
Canvas and OpenGL
• Where is z?
• By convention from the screen towards your eyes (right-handed system)
x
y
(1,1)
(-1,-1)
Notes
•initShaders used to load, compile and
link shaders to form a program object
• Load data onto GPU by creating a vertex
buffer object on the GPU
Note use of flatten() to convert JS array to an
array of float32’s
•Finally we must connect variable in
program with variable in shader
need name, type, location in buffer
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
square.js (cont)
render();
}; // end of onload()
function render() {
gl.clear( gl.COLOR_BUFFER_BIT );
gl.drawArrays( gl.TRIANGLE_FAN, 0, 4 );
}
0
1 2
3
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Triangles, Fans or Strips
gl.drawArrays( gl.TRIANGLES, 0, 6 ); // 0, 1, 2, 0, 2, 3
0
1 2
3
gl.drawArrays( gl.TRIANGLE_STRIP, 0, 4 ); // 0, 1, 3, 2
gl.drawArrays( gl.TRIANGLE_FAN, 0, 4 ); // 0, 1 , 2, 3
0
1 2
3
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
7
Writing Shaders
•First programmable shaders were
programmed in an assembly-like manner
•OpenGL extensions added functions for
vertex and fragment shaders
•Cg (C for graphics) C-like language for
programming shaders
Works with both OpenGL and DirectX
Interface to OpenGL complex
•OpenGL Shading Language (GLSL)
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
8
GLSL
•OpenGL Shading Language
•Part of OpenGL 2.0 and up
•High level C-like language
•New data types
Matrices
Vectors
Samplers
•As of OpenGL 3.1, application must
provide shaders
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
9
Simple Vertex Shader
attribute vec4 vPosition;
void main(void)
{
gl_Position = vPosition;
}
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
10
Execution Model
Vertex
Shader
GPU
Primitive
Assembly
Application
Program
gl.drawArrays Vertex
Vertex data
Shader Program
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
11
Simple Fragment Program
precision mediump float;
void main(void)
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
12
Execution Model
Fragment
Shader
Application
Frame BufferRasterizer
Fragment Fragment
Color
Shader Program
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
15
Data Types
•C types: int, float, bool
•Vectors:
float vec2, vec3, vec4
Also int (ivec) and boolean (bvec)
•Matrices: mat2, mat3, mat4
Stored by columns
Standard referencing m[row][column]
•C++ style constructors
vec3 a =vec3(1.0, 2.0, 3.0)
vec2 b = vec2(a)
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
16
No Pointers
•There are no pointers in GLSL
•We can use C structs which
can be copied back from functions
•Because matrices and vectors are basic
types they can be passed into and output
from GLSL functions, e.g.
mat3 func(mat3 a)
• variables passed by copying
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
17
Qualifiers
• GLSL has many of the same qualifiers such as
const as C/C++
• Need others due to the nature of the execution
model
• Variables can change
Once per primitive
Once per vertex
Once per fragment
At any time in the application
•Vertex attributes are interpolated by the rasterizer
into fragment attributes
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
18
Attribute Qualifier
•Attribute-qualified variables can change at
most once per vertex
•There are a few built in variables such as
gl_Position but most have been deprecated
•User defined (in application program)
attribute float temperature
attribute vec3 velocity
recent versions of GLSL use in and out
qualifiers to get to and from shaders
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
19
Uniform Qualified
•Variables that are constant for an entire
primitive
•Can be changed in application and sent to
shaders
•Cannot be changed in shader
•Used to pass information to shader such
as the time or a bounding box of a
primitive or transformation matrices
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
20
Varying Qualified
•Variables that are passed from vertex shader
to fragment shader
•Automatically interpolated by the rasterizer
•With WebGL, GLSL uses the varying qualifier
in both shaders
varying vec4 color;
•More recent versions of WebGL use out in
vertex shader and in in the fragment shader
out vec4 color; //vertex shader
in vec4 color; // fragment shader
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Our Naming Convention
•attributes passed to vertex shader have names
beginning with v (v Position, vColor) in both the
application and the shader
Note that these are different entities with the same
name
•Varying variables begin with f (fColor) in both
shaders
must have same name
•Uniform variables are unadorned and can have the
same name in application and shaders
21Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
22
Example: Vertex Shader
attribute vec4 vPosition ;
attribute vec4 vColor;
varying vec4 fColor;
void main()
{
gl_Position = vPosition;
fColor = vColor;
}
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
23
Corresponding Fragment
Shader
precision mediump float;
varying vec4 fColor;
void main()
{
gl_FragColor = fColor;
}
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Sending Colors from
Application
var cBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(colors),
gl.STATIC_DRAW );
var vColor = gl.getAttribLocation( program, “vColor” );
gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vColor );
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
//glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid
* pointer);
Sending a Uniform Variable
25
// in application
vec4 color = vec4(1.0, 0.0, 0.0, 1.0);
colorLoc = gl.getUniformLocation( program, ”color” );
gl.uniform4f( colorLoc, color);
// in fragment shader (similar in vertex shader)
uniform vec4 color;
void main()
{
gl_FragColor = color;
}
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
26
Operators and Functions
•Standard C functions
Trigonometric
Arithmetic
Normalize, reflect, length
•Overloading of vector and matrix types
mat4 a;
vec4 b, c, d;
c = b*a; // a column vector stored as a 1d array
d = a*b; // a row vector stored as a 1d array
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
27
Swizzling and Selection
•Can refer to array elements by element
using [] or selection (.) operator with
x, y, z, w
r, g, b, a
s, t, p, q
a[2], a.b, a.z, a.p are the same
•Swizzling operator lets us manipulate
components
vec4 a, b;
a.yz = vec2(1.0, 2.0, 3.0, 4.0);
b = a.yxzw;
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
31
WebGLPrimitives
GL_TRIANGLE_STRIP GL_TRIANGLE_FAN
GL_POINTS
GL_LINES
GL_LINE_LOOP
GL_LINE_STRIP
GL_TRIANGLES
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
32
Polygon Issues
•WebGL will only display triangles
Simple: edges cannot cross
Convex: All points on line segment between two points in a
polygon are also in the polygon
Flat: all vertices are in the same plane
•Application program must tessellate a polygon into
triangles (triangulation)
•OpenGL 4.1 contains a tessellator but not WebGL
nonsimple polygon
nonconvex polygon
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Polygon Testing
•Conceptually simple to test for simplicity
and convexity
•Time consuming
•Earlier versions assumed both and left
testing to the application
•Present version only renders triangles
•Need algorithm to triangulate an arbitrary
polygon
33Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Good and Bad Triangles
• Long thin triangles render badly
• Equilateral triangles render well
• Maximize minimum angle
• Delaunay triangulation for unstructured points
34Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Triangularization
•Convex polygon
•Start with abc, remove b, then acd, ….
35
a
c
b
d
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Non-convex (concave)
36Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Recursive Division
•Find leftmost vertex and split
37Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Linking Shaders with Application
•Read shaders
•Compile shaders
•Create a program object
•Link everything together
•Link variables in application with variables
in shaders
Vertex attributes
Uniform variables
46Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Program Object
•Container for shaders
Can contain multiple shaders
Other GLSL functions
var program = gl.createProgram();
gl.attachShader( program, vertShdr );
gl.attachShader( program, fragShdr );
gl.linkProgram( program );
47Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Reading a Shader
•Shaders are added to the program object
and compiled
•Usual method of passing a shader is as a
null-terminated string using the function
• gl.shaderSource( fragShdr, fragElem.text );
• If shader is in HTML file, we can get it into
application by getElementById method
• If the shader is in a file, we can write a
reader to convert the file to a string
48Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Adding a Vertex Shader
var vertShdr;
var vertElem =
document.getElementById( vertexShaderId );
vertShdr = gl.createShader( gl.VERTEX_SHADER );
gl.shaderSource( vertShdr, vertElem.text );
gl.compileShader( vertShdr );
// after program object created
gl.attachShader( program, vertShdr );
49Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Shader Reader
•Following code may be a security issue
with some browsers if you try to run it
locally
Cross Origin Request
50
function getShader(gl, shaderName, type) {
var shader = gl.createShader(type);
shaderScript = loadFileAJAX(shaderName);
if (!shaderScript) {
alert(“Could not find shader source:
“+shaderName);
}
}
Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Precision Declaration
• In GLSL for WebGL we must specify
desired precision in fragment shaders
artifact inherited from OpenGL ES
ES must run on very simple embedded devices
that may not support 32-bit floating point
All implementations must support mediump
No default for float in fragment shader
•Can use preprocessor directives (#ifdef) to
check if highp supported and, if not,
default to mediump
51Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015
Pass Through Fragment Shader
#ifdef GL_FRAGMENT_SHADER_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif
varying vec4 fcolor;
void main(void)
{
gl_FragColor = fcolor;
}
52Angel and Shreiner: Interactive Computer Graphics 7E © Addison-Wesley 2015