SlideShare a Scribd company logo
Apresentação do Curso
Universidade Federal do Ma
Depto de Informática
Introdução à Computação Gráfica
Prof. Anselmo C. de Paiva
“A picture is a poem without words.”
― Horace
} Lecture Notes:
} Prof. Anselmo Paiva - UFMA
} Prof. Andy van Dam – Brown Univ.
} CS123 – INTR. TO COMPUTER GRAPHICS
} Book: Computer Graphics: Principles and Practice (3rd Ed.)
} Prof. Edward Angel - Univ. of New Mexico
} CS 352: Computer Graphics
} Book:
¨ Ed Angel and Dave Shreiner, Interactive Computer Graphics, A Top-down Approach with WebGL(Eighth Edition),
Addison-Wesley
¨ interactivecomputergraphics.com
} www.cs.unm.edu/~angel/BOOK/INTERACTIVE_COMPUTER_GRAPHICS
} Prof. Fredo Durand and Barb Cutler - MIT
} MIT EECS 6.837
Material do curso baseado em
2
Recursos na Web
} www.cs.unm.edu/~angel/BOOK
} Interactivecomputergraphics.com
} www.opengl.org
} get.webgl.org
} www.kronos.org/webgl
} www.chromeexperiments.com/webgl
} learningwebgl.com
3
} Introdução
} Dispositivos Gráficos
} Software Gráfico 2D
} Transformações Geométrica 2D e 3D
} Geometria Computacional
} 3D Rendering
} Projeções
} Modelos de Iluminação
} Rasterização e Clipping
} Ray Tracing
Programa
4
} Frequências:
} Resumo de cada aula a ser postado no google classroom até 48 horas após a aula
} Notas:
} Provas (Pi), Listas de exercício (Li), Trabalhos de Implementação (Ti)
Notai = 0,7 *Pi+ 0,2 *Ti+0,1*Li
} Listas de Exercício:
} Manuscritas (digitalizadas/fotografadas) e inseridas no Google Classroom
} Trabalhos de Implementação
} Individuais apresentado para o professor
} Regras da Resolução seguidas rigorosamente.
Avaliação
Prof. Anselmo C. de Paiva - DEINF-UFMA - Introdução à Computação Gráfica 5
} Polygons are rendered
} Normally one at a time
} Into a frame buffer.
} Is fast
} Support simplistic lighting models
} images do not necessarily look realistic.
} Single primitive
} the polygon
} everything must be made up of flat surfaces.
Polygon Based Rendering
POLYGON RENDERING
Primeira Parte do Curso
Prof. Anselmo C. de Paiva - DEINF-UFMA - Introdução à Computação Gráfica
7
Shutterbug –
Orthographic View
Shutterbug – Perspective View
Shutterbug
–Depth Cueing
Shutterbug –
Depth Clipping
Shutterbug –
Colored Edges
Shutterbug –
Hidden line
removal
Shutterbug – Flat shading
Shutterbug – Gouraud shading
Shutterbug – Gouraud/specular
Shutterbug – Gouraud/Phong Shading
Shutterbug –Curved surfaces
Shutterbug – Improved illumination
Shutterbug –Texture mapping
Shutterbug – Reflections
} Example: Draw a triangle
} Each application consists of (at least) two files
} HTML file and a JavaScript file
} HTML
} describes page
} includes utilities
} includes shaders
} JavaScript
} contains the graphics
WebGL Introduction
22
} Can run WebGL on any recent browser
} Chrome
} Firefox
} Safari
} IE
} Code written in JavaScript (JS)
} JS runs within browser
} Use local resources
} Uses local GPU
Coding in WebGL
23
<html>
<script id="vertex-shader" type="x-shader/x-vertex">
...
</script>
<script id="fragment-shader" type="x-shader/x-fragment">
...
</script>
<script type="text/javascript" src="../Common/initShaders.js">
...
</script>
<script type="text/javascript" src="triangle.js">
...
</script>
<canvas id="gl-canvas" width="512" height="512"> </canvas>
</html>
Example: triangle.html
24
Example Triangle.html
Vertex Shader
<html>
<script id="vertex-shader" type="x-
shader/x-vertex">
#version 300 es
in vec4 aPosition;
void main()
{
gl_Position = aPosition;
}
</script>
Fragment Shader
<script id="fragment-shader" type="x-
shader/x-fragment">
#version 300 es
precision mediump float;
out vec4 fColor;
void main()
{
fColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}
</script>
25
"use strict";
var gl;
var points;
window.onload = function init()
{
var canvas = document.getElementById( "gl-canvas" );
gl = canvas.getContext('webgl2');
if (!gl) { alert( "WebGL 2.0 not available"); }
// Initialize data
points = new Float32Array([-1, -1 , 0, 1 , 1, -1 ]);
// Configure WebGL
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 1.0, 1.0, 1.0, 1.0 );
// Load shaders and init 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, points, gl.STATIC_DRAW );
// Associate out shader variables buffer
var aPosition = gl.getAttribLocation(program, "aPosition" );
gl.vertexAttribPointer( aPosition, 2, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( aPosition );
render();
};
function render() {
gl.clear( gl.COLOR_BUFFER_BIT );
gl.drawArrays( gl.TRIANGLES, 0, 3 );
}
JS File
26
Exercise
} Download triangle.html and triangle.js to your computer from
Google Classroom
} Run the file
} Edit the two files to change the color and display more than one
triangle
27
} JavaScript (JS) is the language of the Web
} All browsers will execute JS code
} JavaScript is an interpreted object-oriented language
} References
} Flanagan, JavaScript: The Definitive Guide, O’Reilly
} Crockford, JavaScript, The Good Parts, O’Reilly
} Many Web tutorials
} Is JS slow?
} JS engines in browsers are getting much faster
} Not a key issues for graphics since once we get the data to the GPU it doesn’t matter how we got the data
there
} JS is a (too) big language
} We don’t need to use it all
} Choose parts we want to use
} Don’t try to make your code look like C or Java
JavaScript Notes
28
} Very few native types:
} numbers
} strings
} booleans
} Only one numerical type: 32 bit float
} var x = 1;
} var x = 1.0; // same
} potential issue in loops
} two operators for equality == and ===
} Dynamic typing
} Scoping
} Different from other languages
} Function scope
} variables are hoisted within a function
} can use a variable before it is declared
} Note functions are first class objects in
JS
JS Notes
29
} JS arrays are objects
} inherit methods
} var a = [1, 2, 3];
is not the same as in C++ or Java
} a.length // 3
} a.push(4); // length now 4
} a.pop(); // 4
} avoids use of many loops and indexing
} Problem for WebGL which expects C-
style arrays
} Typed Arrays
} JS has typed arrays that are like C
arrays
var a = new Float32Array(3)
var b = new Uint8Array(3)
} Generally, we work with standard JS
arrays and convert to typed arrays
only when we need to send data to
the GPU with the flatten function in
MV.js
JS Arrays
30
} We will use only core JS and HTML
} no extras or variants
} No additional packages
} CSS
} JQuery
} Focus on graphics
} examples may lack beauty
} You are welcome to use other variants as long as I can run them from your URL
A Minimalist Approach
31
Rendering Pipeline
Rendering
Pipeline
Rendering Pipeline
Scene Description:
} Geometric Model
} Polygon Mesh Vertex
} Polygon Vertex
} View (camera specification)
} Lighting Data
} Texture Data
33
Image:
– Color values for pixels
frame buffer
} Primitives are processed in a series of stages
} Each stage forwards its result on to the next stage
} Can be drawn and implemented in different ways
} Stages in hardware or software
} Optimizations & additional programmability are available at some
stages
Rendering Pipeline
} 3D models defined in their own coordinate system (object space)
} Modeling transforms orient the models within a common cordinate frame
(world space)
} Positioning in scene
Rendering Pipeline
} Vertices lit (shaded) according to material properties, surface properties
(normal) and light source
} Local lighting model (Diffuse, Ambient, Phong, etc.)
Rendering Pipeline
} Maps world space to eye space
} Viewing positions is transformed to original & direction is oriented along some
axis (usually z)
Rendering Pipeline
} Portions of the object outside the view volume (view frustum) are removed
Rendering Pipeline
} The objects are projected to the 2D image place (screen space)
Rendering Pipeline
39
} Rasterizes objects into pixels
} Interpolate values as we go (color, depth, etc.)
Rendering Pipeline
40
Rendering Pipeline
} Cg preferred way of 3d models
} Collection of polygons, or faces, that form “skin” of object
} More flexible, represents complex surfaces better
} Examples:
} Human face
} Animal structures
} Furniture, etc
} Set of surface polygons that enclose an object interior, polygon mesh
} De facto: triangles, triangle mesh.
Polygonal Meshes
42
} Ubiquitous in CG because:
} no restriction on the shape and complexity of object
to be modeled
} volumes bounded by planar surfaces
} approximate curved surfaces
} trade off accuracy and speed
} either closer piecewise linear approximation
} or less space and lower processing/rendering time
} accuracy is application dependent: CAD vs. games
} plenty of algorithms and hardware to render
visually appealing shaded versions of polygonal
objects
} computers are very good at executing repetitive,
simple tasks, fast
What is a polygonal mesh?
43
} connected mesh of simple planar polygons that encloses a finite amount of
space.
} special case of a polygon mesh that satisfies the following properties:
} Every edge is shared by exactly two faces.
} At least three edges meet at each vertex.
} Faces do not interpenetrate. Faces at most touch along a common edge.
} Euler’s formula
} If F, E, V represent the number of faces, vertices and edges of a polyhedron, then
V + F - E = 2.
Polyhedron
} Method 1:
} Vertex List
} Normal List
} Face List (Polygon List)
} Method 2:
} Vertex List
} Edge List
} Face List (Polygon List)
Polygon Mesh Representation
} Vertex list:
} Array with the (x,y,z) of each vertex
} Polygon list
} Array with vértices connected to each polygon face
Data Structures – Vertex List
} Shared Edges
} Are drawn twice
} Alternatively: can store mesh by edge list
Vertex List Issue
Prof. Anselmo C. de Paiva - DEINF-UFMA
48
Edge List
49
Vertices and Faces - E.g. Cube
0
1
2 3
4
5
6 7
0
1
2
3
4
5
Face Index
Vertex Index
Data representation using vertex, face and normal lists:
Vertex List Normal List Polygon List
30 30 30 0.0 0.0 1.0 0 1 2 3
-30 30 30 0.0 0.0 -1.0 4 7 6 5
-30 -30 30 0.0 1.0 0.0 0 4 5 1
30 -30 30 -1.0 0.0 0.0 1 5 6 2
30 30 -30 0.0 -1.0 0.0 2 6 7 3
-30 30 -30 1.0 0.0 0.0 3 7 4 0
-30 -30 -30
30 -30 -30
Data representation using vertex, face and edge lists:
Vertex List Edge List Polygon List
x[i] y[i] z[i] L[j] M[j] P[k] Q[k] R[k] S[k]
30 30 30 0 1 0 1 2 3
-30 30 30 1 2 4 7 6 5
-30 -30 30 2 3 0 4 5 1
30 -30 30 3 0 1 5 6 2
30 30 -30 4 5 2 6 7 3
-30 30 -30 5 6 3 7 4 0
-30 -30 -30 6 7
30 -30 -30 7 4
0 4
1 5
2 6
3 7
} Fill the lists for Method 1 and Method 2 of Polygion meshes representation for
the Thetrahedron of the figure.
Exercise
} If the object is defined only by a set of nodes (vertices), and a set of lines
connecting the nodes, then the resulting object representation is called a wire-
frame model.
} Very suitable for engineering applications.
} Simplest 3D Model - easy to construct.
} Easy to clip and manipulate.
} Not suitable for building realistic models.
Wire-Frame Models
Wire Frame Model - The Teapot
Mesh Resolution
56
} Use the right-hand rule = conter-clockwise encirclement of outward-pointing
normal
} Focus on direction of traversal
} Orders {v1, v0, v3} and {v3, v2, v1} are same (ccw)
} Order {v1, v2, v3} is diferent (clockwise)
} What is outward-pointing normal
Polygon Traversal Condition
57
} Direction each polygon is facing
} Each mesh polygon has a normal vector
} Used in shading
Normal Vector
58
} Vertex list:
} Array with the (x,y,z) of each vertex
} Polygon list
} Array with vértices connected to each polygon face
Data Structures – Vertex List
} Shared Edges
} Are drawn twice
} Alternatively: can store mesh by edge list
Vertex List Issue
} Define global arrays for vertices and colors
typedef vex3 point3;
point3 vertices[] = {point3(-1.0,-1.0,-1.0),
point3(1.0,-1.0,-1.0), point3(1.0,1.0,-1.0),
point3(-1.0,1.0,-1.0), point3(-1.0,-1.0,1.0),
point3(1.0,-1.0,1.0), point3(1.0,1.0,1.0),
point3(-1.0,1.0,1.0)};
typedef vec3 color3;
color3 colors[] = {color3(0.0,0.0,0.0),
color3(1.0,0.0,0.0), color3(1.0,1.0,0.0),
color(0.0,1.0,0.0), color3(0.0,0.0,1.0),
color3(1.0,0.0,1.0), color3(1.0,1.0,1.0),
color3(0.0,1.0,1.0});
Modeling a Cube
} Draw a triangle from a list of indices into the array vertices and assign a color to
each index
void triangle(int a, int b, int c, int d)
{
vcolors[i] = colors[d];
position[i] = vertices[a];
vcolors[i+1] = colors[d]);
position[i+1] = vertices[a];
vcolors[i+2] = colors[d];
position[i+2] = vertices[a];
i+=3;
}
Drawing a triangle from a list of indices
void colorcube( )
{
quad(0,3,2,1);
quad(2,3,7,6);
quad(0,4,7,3);
quad(1,2,6,5);
quad(4,5,6,7);
quad(0,1,5,4);
}
// quad generates two triangles for each face and assigns colors to the vertices
int Index = 0;
void quad( int a, int b, int c, int d )
{
colors[Index] = vertex_colors[a]; points[Index] = vertices[a];
Index++;
colors[Index] = vertex_colors[b]; points[Index] = vertices[b];
Index++;
colors[Index] = vertex_colors[c]; points[Index] = vertices[c];
Index++;
colors[Index] = vertex_colors[a]; points[Index] = vertices[a];
Index++;
colors[Index] = vertex_colors[c]; points[Index] = vertices[c];
Index++;
colors[Index] = vertex_colors[d]; points[Index] = vertices[d];
Index++;
}
Draw cube from faces
Edge List
64
List Of Faces
65
} Vertex and face tables, analogous to 2D vertex
and edge tables
} Each vertex listed once, triangles listed as
ordered triplets of indices into the vertex table
} Edges inferred from triangles
} It’s often useful to store associated faces with
vertices (i.e. computing normals: vertex
normal average of surrounding face normals)
} Vertices listed in counter clockwise order in
face table.
} No longer just because of convention. CCW
order differentiates front and back of face
TriangularMeshRepresentation
VERTEX BUFFER OBJECTS AND SHADER
ATTRIBUTES
For Further Reading
} Angel 7th Ed:
} Most parts of Chapter 2.
} Beginning WebGL:
} Chapter 1: vertex Buffer Objects, Attributes & Uniforms, Adding Color.
} Chapter 2: Graphics Pipelines, GL Shading Language.
} Chapter 9: Debugging.
Triangle Example
<!DOCTYPE html>
<html>
<head>
<script id="vertex-shader" type="x-
shader/x-vertex">
attribute vec4 vPosition;
void main(){
gl_Position = vPosition;
}
</script>
precision mediump float;
void main(){
gl_FragColor = vec4( 1.0, 0.0,
0.0, 1.0 );
}
</script>
<script type="text/javascript”
src="../Common/webgl-utils.js"> </script>
<script type="text/javascript"
src="../Common/initShaders.js"> </script>
<script type="text/javascript”
src="../Common/MV.js"> </script>
<script type="text/javascript"
src="triangle.js"></script>
</head>
<body>
<canvas id="gl-canvas" width="512" height="512">
Oops ... your browser doesn't support the HTML5
canvas element
</canvas>
</body>
</html>
HTML File (triangle.html)
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" );
}
// Three Vertices
var vertices = [
vec2( -1, -1 ),
vec2( 0, 1 ),
vec2( 1, -1 )
];
// Configure WebGL
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 1.0, 1.0, 1.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 );
render();
};
function render() {
gl.clear( gl.COLOR_BUFFER_BIT );
gl.drawArrays( gl.TRIANGLES, 0, 3 );
}
triangle.js
Recap: Vertex Buffer and Shader Attributes
Within the Javascript code, we have:
var bufferId = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );
gl.bufferData( gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW );
...
var vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );
Within the vertex shader (in HTML), we have:
<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec4 vPosition;
void main(){
gl_Position = vPosition;
}
Angel and Shreiner:
Interactive
In OpenGL, we use vertex
buffer data to define the 3
vertex positions of the
triangle.
The vertex shader then
computes the screen positions
of the vertices.
And then Fragment shader fills
the inside of the triangle with a
lot of pixels.
Today’s Exercise #1
} Change the shaders to display a green triangle.
} Q1: Do you need to change the JavaScript code?
} Q2: What if we want to change the color within the JavaScript code?
Example 1: Green & Blue Triangles
<html>
<head>
<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec4 vPosition;
void main() {
gl_Position = vPosition;
}
</script>
<script id="fragment-shader" type="x-shader/x-fragment">
precision mediump float;
uniform vec4 fColor;
void main() {
gl_FragColor = fColor;
}
</script>
Example 1: Green & Blue Triangles (HTML code)
window.onload = function init()
{
var canvas = document.getElementById( "gl-canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
// Three Vertices
var vertices = [
vec3( -1, -1, 0 ),
vec3( -0.5, 1, 0 ),
vec3( 0, -1, 0 ),
vec3( 0, -1, 0 ),
vec3( 0.5, 1, 0 ),
vec3( 1, -1, 0 )
];
Example 1: Green & Blue Triangles
(JavaScript code)
// Associate our shader variables with our data buffer
var vPosition = gl.getAttribLocation( program,
"vPosition" );
gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
var fColor = gl.getUniformLocation( program, "fColor" );
gl.clear( gl.COLOR_BUFFER_BIT );
gl.uniform4f( fColor, 0.0, 1.0, 0.0, 1.0 );
gl.drawArrays( gl.TRIANGLES, 0, 3 );
gl.uniform4f( fColor, 0.0, 0.0, 1.0, 1.0 );
gl.drawArrays( gl.TRIANGLES, 3, 3 );
};
(JavaScript code)
// Configure WebGL
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 1.0, 1.0, 1.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 );
A Quick Summary So Far
} Uniform parameters offer communication between shaders and
main (JS) program.
} Q1: Any other types of communication?
} A: Will discuss vertex attributes later.
} Q2: I want to know more about shaders!
} Q3: I still don’t know how vertex array buffer works?
} A: Our next topics (using SIGGRAPH 2014 materials)
SHADERS AND GLSL
Vertex Shaders
} A shader that’s executed for each vertex
} Each instantiation can generate one vertex
} Outputs are passed on to rasterizer where they are interpolated and available
to fragment shaders
} Position output in clip coordinates
} There are lots of effects we can do in vertex shaders
} Changing coordinate systems
} Moving vertices
} Per vertex lighting: height fields
} A shader that’s executed for each “potential” pixel
} fragments still need to pass several tests before making it to the framebuffer
} There are lots of effects we can do in fragment shaders
} Per-fragment lighting
} Texture and bump Mapping
} Environment (Reflection) Maps
Fragment Shaders
GLSL
} OpenGL Shading Language
} C like language with some C++ features
} 2-4 dimensional matrix and vector types
} Both vertex and fragment shaders are written in GLSL
} Each shader has a main()
GLSL Data Types
} Scalar types:float, int, bool
} Vector types:vec2, vec3, vec4
ivec2, ivec3, ivec4
bvec2, bvec3, bvec4
} Matrix types: mat2, mat3, mat4
} Texture sampling: sampler1D, sampler2D,
sampler3D, samplerCube
} C++ Style Constructors
vec3 a = vec3(1.0, 2.0, 3.0);
} Standard C/C++ arithmetic and logic operators
} Overloaded operators for matrix and vector operations
mat4 m;
vec4 a, b, c;
b = a*m;
c = m*a;
Operators
} Access vector components using either:
} [ ] (C-style array indexing)
} xyzw, rgba or strq (named components)
} For example:
vec3 v;
v[1], v.y, v.g, v.t - all refer to the same element
} Component swizzling:
vec3 a, b;
a.xy = b.yx;
Components and Swizzling
} attribute
} vertex attributes from application
} varying
} copy vertex attributes and other variables from vertex shaders to fragment shaders
} values are interpolated by rasterizer
varying vec2 texCoord;
varying vec4 color;
} uniform
} shader-constant variable from application
uniform float time;
uniform vec4 rotation;
Qualifiers
Functions
} Built in
} Arithmetic: sqrt, power, abs
} Trigonometric: sin, asin
} Graphical: length, reflect
} User defined
} gl_Position
} (required) output position from vertex shader
} gl_FragColor
} (required) output color from fragment shader
} gl_FragCoord
} input fragment position
} gl_FragDepth
} input depth value in fragment shader
Built-in Variables
attribute vec4 vPosition;
attribute vec4 vColor;
varying vec4 fColor;
void main()
{
fColor = vColor;
gl_Position = vPosition;
}
Simple Vertex Shader for Cube Example
precision mediump float;
varying vec4 fColor;
void main()
{
gl_FragColor = fColor;
}
Simple Fragment Shader for Cube Example
} Shaders need to be compiled
and linked to form an
executable shader program
} WebGL provides the compiler
and linker
} A WebGL program must contain
vertex and fragment shaders
Getting Your Shaders into WebGL
Create
Shader
Load Shader
Source
Compile Shader
Create Program
Attach Shader
to Program
Link Program
gl.createProgram()
gl.shaderSource()
gl.compileShader()
gl.createShader()
gl.attachShader()
gl.linkProgram()
Use Program gl.useProgram()
These steps
need to be
repeated for
each type of
shader in
the shader
program
A Simpler Way
} We’ve created a function for this course to make it easier to load your
shaders
} available at course website
initShaders(vFile, fFile );
} initShaders takes two filenames
} vFile path to the vertex shader file
} fFile for the fragment shader file
} Fails if shaders don’t compile, or program doesn’t link
VERTEX BUFFER OBJECTS
} Geometric objects are represented using vertices
} A vertex is a collection of generic attributes
} positional coordinates
} colors
} texture coordinates
} any other data associated with that point in space
} Position stored in 4 dimensional homogeneous coordinates
} Vertex data must be stored in vertex buffer objects (VBOs)
Representing Geometric Objects
p =
x
y
z
w
é
ë
ê
ê
ê
ê
ù
û
ú
ú
ú
ú
} All primitives are specified by vertices
OpenGL Geometric Primitives
GL_TRIANGLE_STRIP
GL_TRIANGLE_FAN
GL_LINES GL_LINE_LOOP
GL_LINE_STRIP
GL_TRIANGLES
GL_POINTS
} Vertex data must be stored in a Vertex Buffer Object (VBO)
} To set up a VBO we must
} create an empty by calling gl.createBuffer(); ()
} bind a specific VBO for initialization by calling
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
} load data into VBO using (for our points)
gl.bufferData( gl.ARRAY_BUFFER, flatten(points),
gl.STATIC_DRAW );
Storing Vertex Attributes
} Associate shader variables with vertex arrays
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 );
var vBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW );
var vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
Vertex Array Code
A Quick Note on Buffers & Attributes
} createBuffer(), bindBuffer(), and bufferData() tell
OpenGL where the actual data is stored in the
memory.
} vertexAttribPointer() and
enableVertexAttribArray() tells OpenGL which
shader attributes will use them.
} So far, we ignore the last three parameters of vertexAttribPointer(), e.g.,
vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );
} Exercise #1: Look up the definition of vertexAttribPointer()
https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVer
} Exercise #2: See a different use of vertexAttribPointer() at:
https://github.com/openglredbook/examples/blob/master/src/04-
gouraud/04-gouraud.cpp
vertexAttribPointer()
struct VertexData {
GLubyte color[4];
GLfloat position[4];
};
VertexData vertices[NumVertices] = { ... };
glGenBuffers(NumBuffers, Buffers);
glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices),
vertices, GL_STATIC_DRAW);
glVertexAttribPointer(vColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(VertexData), BUFFER_OFFSET(0) );
glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData),
BUFFER_OFFSET(sizeof(vertices[0].color)) );
glEnableVertexAttribArray(vColor);
glEnableVertexAttribArray(vPosition)
An Advanced Example of vertexAttribPointer()
Example 2: Per-Vertex Color
} HTML code
<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec4 vPosition;
attribute vec4 vColor;
varying vec4 fColor;
void main() {
fColor = vColor;
gl_Position = vPosition;
}
</script>
<script id="fragment-shader" type="x-shader/x-fragment">
precision mediump float;
varying vec4 fColor; // Note that this will be interpolated ...
void main() {
gl_FragColor = fColor;
}
</script>
Example 2: Per-Vertex Color
} window.onload = function init() {
var canvas = document.getElementById( "gl-
canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't
available" ); }
// Three Vertices
var vertices = [
vec3( -1, -1, 0 ),
vec3( 0, 1, 0 ),
vec3( 1, -1, 0 )
];
var colors = [
vec3( 1, 0, 0 ),
vec3( 0, 1, 0 ),
vec3( 0, 0, 1 )
];
// Configure WebGL
//
gl.viewport( 0, 0, canvas.width,
canvas.height );
gl.clearColor( 1.0, 1.0, 1.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 );
Example 2: Per-Vertex Color - Javascript Code
// Associate our shader variables with our data buffer
var vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
// Repeat the above process for the color attributes of the vertices.
var cBufferId = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, cBufferId );
gl.bufferData( gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW );
var vColor = gl.getAttribLocation( program, "vColor" );
gl.vertexAttribPointer( vColor, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vColor );
render();
};
Example 2: Per-Vertex Color - Javascript Code
Debugging Tips
} Typos in JavaScript code may not produce any error message.
} Try typing a wrong variable name (e.g., vColor à fColor) or wrong
function name (e.g., getAttributeLocation) and see what happens.
} Syntax errors like these will show up in the Console panel of the
Chrome Developer Tools.
Homework #1
} Draw at least two triangles like Example 1, with per-vertex colors
like Example 2.
• Render a cube with a different color for each face
• Our example demonstrates:
– simple object modeling
• building up 3D objects from geometric primitives
• building geometric primitives from vertices
– initializing vertex data
– organizing data for rendering
– interactivity
– animation
Our Second Program
} We’ll build each cube face from individual triangles
} Need to determine how much storage is required
} (6 faces)(2 triangles/face)(3 vertices/triangle)
var numVertices = 36;
} To simplify communicating with GLSL, we’ll use a package MV.js which contains a vec3
object similar to GLSL’s vec3 type
Initializing the Cube’s Data
} Before we can initialize our VBO, we need to stage the data
} Our cube has two attributes per vertex
} position
} color
} We create two arrays to hold the VBO data
var points = [];
var colors = [];
Initializing the Cube’s Data (cont’d)
} Vertices of a unit cube centered at
origin
} sides aligned with axes
var vertices = [
vec4( -0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, -0.5, -0.5, 1.0 ),
vec4( -0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, -0.5, -0.5, 1.0 )
];
} We’ll also set up an array of RGBA colors
} We can use vec3 or vec4 or just JS array
var vertexColors = [
[ 0.0, 0.0, 0.0, 1.0 ], // black
[ 1.0, 0.0, 0.0, 1.0 ], // red
[ 1.0, 1.0, 0.0, 1.0 ], // yellow
[ 0.0, 1.0, 0.0, 1.0 ], // green
[ 0.0, 0.0, 1.0, 1.0 ], // blue
[ 1.0, 0.0, 1.0, 1.0 ], // magenta
[ 0.0, 1.0, 1.0, 1.0 ], // cyan
[ 1.0, 1.0, 1.0, 1.0 ] // white
];
Cube Data
1
7
4
6
7
2
3
0
} A JS array is an object with attributes and methods such as length, push() and
pop()
} fundamentally different from C-style array
} cannot send directly to WebGL functions
} use flatten() function to extract data from JS array
gl.bufferData( gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW );
Arrays in JS
} To simplify generating the geometry, we use a convenience function quad()
} create two triangles for each face and assigns colors to the vertices
function quad(a, b, c, d) {
var indices = [ a, b, c, a, c, d ];
for ( var i = 0; i < indices.length; ++i ) {
points.push( vertices[indices[i]] );
// for vertex colors use
//colors.push( vertexColors[indices[i]] );
// for solid colored faces use
colors.push(vertexColors[a]);
}
Generating a Cube Face from Vertices
} Generate 12 triangles for the cube
} 36 vertices with 36 colors
function colorCube() {
quad( 1, 0, 3, 2 );
quad( 2, 3, 7, 6 );
quad( 3, 0, 4, 7 );
quad( 6, 5, 1, 2 );
quad( 4, 5, 6, 7 );
quad( 5, 4, 0, 1 );
}
Generating the Cube from Faces
1
7
4
6
7
2
3
0

More Related Content

Similar to Introducao ao Curso Anselmo Cardoso de Paiva Ufma

Intro to GPGPU Programming with Cuda
Intro to GPGPU Programming with CudaIntro to GPGPU Programming with Cuda
Intro to GPGPU Programming with Cuda
Rob Gillen
 
3D WebGIS using Opensource software
3D WebGIS using Opensource software3D WebGIS using Opensource software
3D WebGIS using Opensource software
Parthesh Bulbule
 
An effective RGB color selection for complex 3D object structure in scene gra...
An effective RGB color selection for complex 3D object structure in scene gra...An effective RGB color selection for complex 3D object structure in scene gra...
An effective RGB color selection for complex 3D object structure in scene gra...
IJECEIAES
 
The Intersection of Game Engines & GPUs: Current & Future (Graphics Hardware ...
The Intersection of Game Engines & GPUs: Current & Future (Graphics Hardware ...The Intersection of Game Engines & GPUs: Current & Future (Graphics Hardware ...
The Intersection of Game Engines & GPUs: Current & Future (Graphics Hardware ...
Johan Andersson
 

Similar to Introducao ao Curso Anselmo Cardoso de Paiva Ufma (20)

Intro to GPGPU Programming with Cuda
Intro to GPGPU Programming with CudaIntro to GPGPU Programming with Cuda
Intro to GPGPU Programming with Cuda
 
High-Performance Graph Analysis and Modeling
High-Performance Graph Analysis and ModelingHigh-Performance Graph Analysis and Modeling
High-Performance Graph Analysis and Modeling
 
FastV2C-HandNet - ICICC 2020
FastV2C-HandNet - ICICC 2020FastV2C-HandNet - ICICC 2020
FastV2C-HandNet - ICICC 2020
 
CS 354 Pixel Updating
CS 354 Pixel UpdatingCS 354 Pixel Updating
CS 354 Pixel Updating
 
NVIDIA CUDA
NVIDIA CUDANVIDIA CUDA
NVIDIA CUDA
 
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
 
CS 354 Programmable Shading
CS 354 Programmable ShadingCS 354 Programmable Shading
CS 354 Programmable Shading
 
Towards Utilizing GPUs in Information Visualization
Towards Utilizing GPUs in Information VisualizationTowards Utilizing GPUs in Information Visualization
Towards Utilizing GPUs in Information Visualization
 
CS 354 Introduction
CS 354 IntroductionCS 354 Introduction
CS 354 Introduction
 
Analysis of KinectFusion
Analysis of KinectFusionAnalysis of KinectFusion
Analysis of KinectFusion
 
Attentive Relational Networks for Mapping Images to Scene Graphs
Attentive Relational Networks for Mapping Images to Scene GraphsAttentive Relational Networks for Mapping Images to Scene Graphs
Attentive Relational Networks for Mapping Images to Scene Graphs
 
3DRepo
3DRepo3DRepo
3DRepo
 
Accelerating Real Time Applications on Heterogeneous Platforms
Accelerating Real Time Applications on Heterogeneous PlatformsAccelerating Real Time Applications on Heterogeneous Platforms
Accelerating Real Time Applications on Heterogeneous Platforms
 
NvFX GTC 2013
NvFX GTC 2013NvFX GTC 2013
NvFX GTC 2013
 
Design and Implementation of Multiplier Using Kcm and Vedic Mathematics by Us...
Design and Implementation of Multiplier Using Kcm and Vedic Mathematics by Us...Design and Implementation of Multiplier Using Kcm and Vedic Mathematics by Us...
Design and Implementation of Multiplier Using Kcm and Vedic Mathematics by Us...
 
3D WebGIS using Opensource software
3D WebGIS using Opensource software3D WebGIS using Opensource software
3D WebGIS using Opensource software
 
An effective RGB color selection for complex 3D object structure in scene gra...
An effective RGB color selection for complex 3D object structure in scene gra...An effective RGB color selection for complex 3D object structure in scene gra...
An effective RGB color selection for complex 3D object structure in scene gra...
 
I017425763
I017425763I017425763
I017425763
 
The Intersection of Game Engines & GPUs: Current & Future (Graphics Hardware ...
The Intersection of Game Engines & GPUs: Current & Future (Graphics Hardware ...The Intersection of Game Engines & GPUs: Current & Future (Graphics Hardware ...
The Intersection of Game Engines & GPUs: Current & Future (Graphics Hardware ...
 
An35225228
An35225228An35225228
An35225228
 

Recently uploaded

The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
heathfieldcps1
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
ashishpaul799
 

Recently uploaded (20)

The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
An Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptxAn Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptx
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 

Introducao ao Curso Anselmo Cardoso de Paiva Ufma

  • 1. Apresentação do Curso Universidade Federal do Ma Depto de Informática Introdução à Computação Gráfica Prof. Anselmo C. de Paiva “A picture is a poem without words.” ― Horace
  • 2. } Lecture Notes: } Prof. Anselmo Paiva - UFMA } Prof. Andy van Dam – Brown Univ. } CS123 – INTR. TO COMPUTER GRAPHICS } Book: Computer Graphics: Principles and Practice (3rd Ed.) } Prof. Edward Angel - Univ. of New Mexico } CS 352: Computer Graphics } Book: ¨ Ed Angel and Dave Shreiner, Interactive Computer Graphics, A Top-down Approach with WebGL(Eighth Edition), Addison-Wesley ¨ interactivecomputergraphics.com } www.cs.unm.edu/~angel/BOOK/INTERACTIVE_COMPUTER_GRAPHICS } Prof. Fredo Durand and Barb Cutler - MIT } MIT EECS 6.837 Material do curso baseado em 2
  • 3. Recursos na Web } www.cs.unm.edu/~angel/BOOK } Interactivecomputergraphics.com } www.opengl.org } get.webgl.org } www.kronos.org/webgl } www.chromeexperiments.com/webgl } learningwebgl.com 3
  • 4. } Introdução } Dispositivos Gráficos } Software Gráfico 2D } Transformações Geométrica 2D e 3D } Geometria Computacional } 3D Rendering } Projeções } Modelos de Iluminação } Rasterização e Clipping } Ray Tracing Programa 4
  • 5. } Frequências: } Resumo de cada aula a ser postado no google classroom até 48 horas após a aula } Notas: } Provas (Pi), Listas de exercício (Li), Trabalhos de Implementação (Ti) Notai = 0,7 *Pi+ 0,2 *Ti+0,1*Li } Listas de Exercício: } Manuscritas (digitalizadas/fotografadas) e inseridas no Google Classroom } Trabalhos de Implementação } Individuais apresentado para o professor } Regras da Resolução seguidas rigorosamente. Avaliação Prof. Anselmo C. de Paiva - DEINF-UFMA - Introdução à Computação Gráfica 5
  • 6. } Polygons are rendered } Normally one at a time } Into a frame buffer. } Is fast } Support simplistic lighting models } images do not necessarily look realistic. } Single primitive } the polygon } everything must be made up of flat surfaces. Polygon Based Rendering
  • 7. POLYGON RENDERING Primeira Parte do Curso Prof. Anselmo C. de Paiva - DEINF-UFMA - Introdução à Computação Gráfica 7
  • 19. Shutterbug – Improved illumination
  • 22. } Example: Draw a triangle } Each application consists of (at least) two files } HTML file and a JavaScript file } HTML } describes page } includes utilities } includes shaders } JavaScript } contains the graphics WebGL Introduction 22
  • 23. } Can run WebGL on any recent browser } Chrome } Firefox } Safari } IE } Code written in JavaScript (JS) } JS runs within browser } Use local resources } Uses local GPU Coding in WebGL 23
  • 24. <html> <script id="vertex-shader" type="x-shader/x-vertex"> ... </script> <script id="fragment-shader" type="x-shader/x-fragment"> ... </script> <script type="text/javascript" src="../Common/initShaders.js"> ... </script> <script type="text/javascript" src="triangle.js"> ... </script> <canvas id="gl-canvas" width="512" height="512"> </canvas> </html> Example: triangle.html 24
  • 25. Example Triangle.html Vertex Shader <html> <script id="vertex-shader" type="x- shader/x-vertex"> #version 300 es in vec4 aPosition; void main() { gl_Position = aPosition; } </script> Fragment Shader <script id="fragment-shader" type="x- shader/x-fragment"> #version 300 es precision mediump float; out vec4 fColor; void main() { fColor = vec4( 1.0, 0.0, 0.0, 1.0 ); } </script> 25
  • 26. "use strict"; var gl; var points; window.onload = function init() { var canvas = document.getElementById( "gl-canvas" ); gl = canvas.getContext('webgl2'); if (!gl) { alert( "WebGL 2.0 not available"); } // Initialize data points = new Float32Array([-1, -1 , 0, 1 , 1, -1 ]); // Configure WebGL gl.viewport( 0, 0, canvas.width, canvas.height ); gl.clearColor( 1.0, 1.0, 1.0, 1.0 ); // Load shaders and init 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, points, gl.STATIC_DRAW ); // Associate out shader variables buffer var aPosition = gl.getAttribLocation(program, "aPosition" ); gl.vertexAttribPointer( aPosition, 2, gl.FLOAT, false, 0, 0 ); gl.enableVertexAttribArray( aPosition ); render(); }; function render() { gl.clear( gl.COLOR_BUFFER_BIT ); gl.drawArrays( gl.TRIANGLES, 0, 3 ); } JS File 26
  • 27. Exercise } Download triangle.html and triangle.js to your computer from Google Classroom } Run the file } Edit the two files to change the color and display more than one triangle 27
  • 28. } JavaScript (JS) is the language of the Web } All browsers will execute JS code } JavaScript is an interpreted object-oriented language } References } Flanagan, JavaScript: The Definitive Guide, O’Reilly } Crockford, JavaScript, The Good Parts, O’Reilly } Many Web tutorials } Is JS slow? } JS engines in browsers are getting much faster } Not a key issues for graphics since once we get the data to the GPU it doesn’t matter how we got the data there } JS is a (too) big language } We don’t need to use it all } Choose parts we want to use } Don’t try to make your code look like C or Java JavaScript Notes 28
  • 29. } Very few native types: } numbers } strings } booleans } Only one numerical type: 32 bit float } var x = 1; } var x = 1.0; // same } potential issue in loops } two operators for equality == and === } Dynamic typing } Scoping } Different from other languages } Function scope } variables are hoisted within a function } can use a variable before it is declared } Note functions are first class objects in JS JS Notes 29
  • 30. } JS arrays are objects } inherit methods } var a = [1, 2, 3]; is not the same as in C++ or Java } a.length // 3 } a.push(4); // length now 4 } a.pop(); // 4 } avoids use of many loops and indexing } Problem for WebGL which expects C- style arrays } Typed Arrays } JS has typed arrays that are like C arrays var a = new Float32Array(3) var b = new Uint8Array(3) } Generally, we work with standard JS arrays and convert to typed arrays only when we need to send data to the GPU with the flatten function in MV.js JS Arrays 30
  • 31. } We will use only core JS and HTML } no extras or variants } No additional packages } CSS } JQuery } Focus on graphics } examples may lack beauty } You are welcome to use other variants as long as I can run them from your URL A Minimalist Approach 31
  • 33. Rendering Pipeline Scene Description: } Geometric Model } Polygon Mesh Vertex } Polygon Vertex } View (camera specification) } Lighting Data } Texture Data 33 Image: – Color values for pixels frame buffer
  • 34. } Primitives are processed in a series of stages } Each stage forwards its result on to the next stage } Can be drawn and implemented in different ways } Stages in hardware or software } Optimizations & additional programmability are available at some stages Rendering Pipeline
  • 35. } 3D models defined in their own coordinate system (object space) } Modeling transforms orient the models within a common cordinate frame (world space) } Positioning in scene Rendering Pipeline
  • 36. } Vertices lit (shaded) according to material properties, surface properties (normal) and light source } Local lighting model (Diffuse, Ambient, Phong, etc.) Rendering Pipeline
  • 37. } Maps world space to eye space } Viewing positions is transformed to original & direction is oriented along some axis (usually z) Rendering Pipeline
  • 38. } Portions of the object outside the view volume (view frustum) are removed Rendering Pipeline
  • 39. } The objects are projected to the 2D image place (screen space) Rendering Pipeline 39
  • 40. } Rasterizes objects into pixels } Interpolate values as we go (color, depth, etc.) Rendering Pipeline 40
  • 42. } Cg preferred way of 3d models } Collection of polygons, or faces, that form “skin” of object } More flexible, represents complex surfaces better } Examples: } Human face } Animal structures } Furniture, etc } Set of surface polygons that enclose an object interior, polygon mesh } De facto: triangles, triangle mesh. Polygonal Meshes 42
  • 43. } Ubiquitous in CG because: } no restriction on the shape and complexity of object to be modeled } volumes bounded by planar surfaces } approximate curved surfaces } trade off accuracy and speed } either closer piecewise linear approximation } or less space and lower processing/rendering time } accuracy is application dependent: CAD vs. games } plenty of algorithms and hardware to render visually appealing shaded versions of polygonal objects } computers are very good at executing repetitive, simple tasks, fast What is a polygonal mesh? 43
  • 44. } connected mesh of simple planar polygons that encloses a finite amount of space. } special case of a polygon mesh that satisfies the following properties: } Every edge is shared by exactly two faces. } At least three edges meet at each vertex. } Faces do not interpenetrate. Faces at most touch along a common edge. } Euler’s formula } If F, E, V represent the number of faces, vertices and edges of a polyhedron, then V + F - E = 2. Polyhedron
  • 45. } Method 1: } Vertex List } Normal List } Face List (Polygon List) } Method 2: } Vertex List } Edge List } Face List (Polygon List) Polygon Mesh Representation
  • 46. } Vertex list: } Array with the (x,y,z) of each vertex } Polygon list } Array with vértices connected to each polygon face Data Structures – Vertex List
  • 47. } Shared Edges } Are drawn twice } Alternatively: can store mesh by edge list Vertex List Issue
  • 48. Prof. Anselmo C. de Paiva - DEINF-UFMA 48
  • 50. Vertices and Faces - E.g. Cube 0 1 2 3 4 5 6 7 0 1 2 3 4 5 Face Index Vertex Index
  • 51. Data representation using vertex, face and normal lists: Vertex List Normal List Polygon List 30 30 30 0.0 0.0 1.0 0 1 2 3 -30 30 30 0.0 0.0 -1.0 4 7 6 5 -30 -30 30 0.0 1.0 0.0 0 4 5 1 30 -30 30 -1.0 0.0 0.0 1 5 6 2 30 30 -30 0.0 -1.0 0.0 2 6 7 3 -30 30 -30 1.0 0.0 0.0 3 7 4 0 -30 -30 -30 30 -30 -30
  • 52. Data representation using vertex, face and edge lists: Vertex List Edge List Polygon List x[i] y[i] z[i] L[j] M[j] P[k] Q[k] R[k] S[k] 30 30 30 0 1 0 1 2 3 -30 30 30 1 2 4 7 6 5 -30 -30 30 2 3 0 4 5 1 30 -30 30 3 0 1 5 6 2 30 30 -30 4 5 2 6 7 3 -30 30 -30 5 6 3 7 4 0 -30 -30 -30 6 7 30 -30 -30 7 4 0 4 1 5 2 6 3 7
  • 53. } Fill the lists for Method 1 and Method 2 of Polygion meshes representation for the Thetrahedron of the figure. Exercise
  • 54. } If the object is defined only by a set of nodes (vertices), and a set of lines connecting the nodes, then the resulting object representation is called a wire- frame model. } Very suitable for engineering applications. } Simplest 3D Model - easy to construct. } Easy to clip and manipulate. } Not suitable for building realistic models. Wire-Frame Models
  • 55. Wire Frame Model - The Teapot
  • 57. } Use the right-hand rule = conter-clockwise encirclement of outward-pointing normal } Focus on direction of traversal } Orders {v1, v0, v3} and {v3, v2, v1} are same (ccw) } Order {v1, v2, v3} is diferent (clockwise) } What is outward-pointing normal Polygon Traversal Condition 57
  • 58. } Direction each polygon is facing } Each mesh polygon has a normal vector } Used in shading Normal Vector 58
  • 59. } Vertex list: } Array with the (x,y,z) of each vertex } Polygon list } Array with vértices connected to each polygon face Data Structures – Vertex List
  • 60. } Shared Edges } Are drawn twice } Alternatively: can store mesh by edge list Vertex List Issue
  • 61. } Define global arrays for vertices and colors typedef vex3 point3; point3 vertices[] = {point3(-1.0,-1.0,-1.0), point3(1.0,-1.0,-1.0), point3(1.0,1.0,-1.0), point3(-1.0,1.0,-1.0), point3(-1.0,-1.0,1.0), point3(1.0,-1.0,1.0), point3(1.0,1.0,1.0), point3(-1.0,1.0,1.0)}; typedef vec3 color3; color3 colors[] = {color3(0.0,0.0,0.0), color3(1.0,0.0,0.0), color3(1.0,1.0,0.0), color(0.0,1.0,0.0), color3(0.0,0.0,1.0), color3(1.0,0.0,1.0), color3(1.0,1.0,1.0), color3(0.0,1.0,1.0}); Modeling a Cube
  • 62. } Draw a triangle from a list of indices into the array vertices and assign a color to each index void triangle(int a, int b, int c, int d) { vcolors[i] = colors[d]; position[i] = vertices[a]; vcolors[i+1] = colors[d]); position[i+1] = vertices[a]; vcolors[i+2] = colors[d]; position[i+2] = vertices[a]; i+=3; } Drawing a triangle from a list of indices
  • 63. void colorcube( ) { quad(0,3,2,1); quad(2,3,7,6); quad(0,4,7,3); quad(1,2,6,5); quad(4,5,6,7); quad(0,1,5,4); } // quad generates two triangles for each face and assigns colors to the vertices int Index = 0; void quad( int a, int b, int c, int d ) { colors[Index] = vertex_colors[a]; points[Index] = vertices[a]; Index++; colors[Index] = vertex_colors[b]; points[Index] = vertices[b]; Index++; colors[Index] = vertex_colors[c]; points[Index] = vertices[c]; Index++; colors[Index] = vertex_colors[a]; points[Index] = vertices[a]; Index++; colors[Index] = vertex_colors[c]; points[Index] = vertices[c]; Index++; colors[Index] = vertex_colors[d]; points[Index] = vertices[d]; Index++; } Draw cube from faces
  • 66. } Vertex and face tables, analogous to 2D vertex and edge tables } Each vertex listed once, triangles listed as ordered triplets of indices into the vertex table } Edges inferred from triangles } It’s often useful to store associated faces with vertices (i.e. computing normals: vertex normal average of surrounding face normals) } Vertices listed in counter clockwise order in face table. } No longer just because of convention. CCW order differentiates front and back of face TriangularMeshRepresentation
  • 67. VERTEX BUFFER OBJECTS AND SHADER ATTRIBUTES
  • 68. For Further Reading } Angel 7th Ed: } Most parts of Chapter 2. } Beginning WebGL: } Chapter 1: vertex Buffer Objects, Attributes & Uniforms, Adding Color. } Chapter 2: Graphics Pipelines, GL Shading Language. } Chapter 9: Debugging.
  • 70. <!DOCTYPE html> <html> <head> <script id="vertex-shader" type="x- shader/x-vertex"> attribute vec4 vPosition; void main(){ gl_Position = vPosition; } </script> precision mediump float; void main(){ gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); } </script> <script type="text/javascript” src="../Common/webgl-utils.js"> </script> <script type="text/javascript" src="../Common/initShaders.js"> </script> <script type="text/javascript” src="../Common/MV.js"> </script> <script type="text/javascript" src="triangle.js"></script> </head> <body> <canvas id="gl-canvas" width="512" height="512"> Oops ... your browser doesn't support the HTML5 canvas element </canvas> </body> </html> HTML File (triangle.html)
  • 71. 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" ); } // Three Vertices var vertices = [ vec2( -1, -1 ), vec2( 0, 1 ), vec2( 1, -1 ) ]; // Configure WebGL gl.viewport( 0, 0, canvas.width, canvas.height ); gl.clearColor( 1.0, 1.0, 1.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 ); render(); }; function render() { gl.clear( gl.COLOR_BUFFER_BIT ); gl.drawArrays( gl.TRIANGLES, 0, 3 ); } triangle.js
  • 72. Recap: Vertex Buffer and Shader Attributes Within the Javascript code, we have: var bufferId = gl.createBuffer(); gl.bindBuffer( gl.ARRAY_BUFFER, bufferId ); gl.bufferData( gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW ); ... var vPosition = gl.getAttribLocation( program, "vPosition" ); gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 ); Within the vertex shader (in HTML), we have: <script id="vertex-shader" type="x-shader/x-vertex"> attribute vec4 vPosition; void main(){ gl_Position = vPosition; }
  • 73. Angel and Shreiner: Interactive In OpenGL, we use vertex buffer data to define the 3 vertex positions of the triangle. The vertex shader then computes the screen positions of the vertices. And then Fragment shader fills the inside of the triangle with a lot of pixels.
  • 74. Today’s Exercise #1 } Change the shaders to display a green triangle. } Q1: Do you need to change the JavaScript code? } Q2: What if we want to change the color within the JavaScript code?
  • 75. Example 1: Green & Blue Triangles
  • 76. <html> <head> <script id="vertex-shader" type="x-shader/x-vertex"> attribute vec4 vPosition; void main() { gl_Position = vPosition; } </script> <script id="fragment-shader" type="x-shader/x-fragment"> precision mediump float; uniform vec4 fColor; void main() { gl_FragColor = fColor; } </script> Example 1: Green & Blue Triangles (HTML code)
  • 77. window.onload = function init() { var canvas = document.getElementById( "gl-canvas" ); gl = WebGLUtils.setupWebGL( canvas ); if ( !gl ) { alert( "WebGL isn't available" ); } // Three Vertices var vertices = [ vec3( -1, -1, 0 ), vec3( -0.5, 1, 0 ), vec3( 0, -1, 0 ), vec3( 0, -1, 0 ), vec3( 0.5, 1, 0 ), vec3( 1, -1, 0 ) ]; Example 1: Green & Blue Triangles (JavaScript code)
  • 78. // Associate our shader variables with our data buffer var vPosition = gl.getAttribLocation( program, "vPosition" ); gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 ); gl.enableVertexAttribArray( vPosition ); var fColor = gl.getUniformLocation( program, "fColor" ); gl.clear( gl.COLOR_BUFFER_BIT ); gl.uniform4f( fColor, 0.0, 1.0, 0.0, 1.0 ); gl.drawArrays( gl.TRIANGLES, 0, 3 ); gl.uniform4f( fColor, 0.0, 0.0, 1.0, 1.0 ); gl.drawArrays( gl.TRIANGLES, 3, 3 ); }; (JavaScript code) // Configure WebGL gl.viewport( 0, 0, canvas.width, canvas.height ); gl.clearColor( 1.0, 1.0, 1.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 );
  • 79. A Quick Summary So Far } Uniform parameters offer communication between shaders and main (JS) program. } Q1: Any other types of communication? } A: Will discuss vertex attributes later. } Q2: I want to know more about shaders! } Q3: I still don’t know how vertex array buffer works? } A: Our next topics (using SIGGRAPH 2014 materials)
  • 81. Vertex Shaders } A shader that’s executed for each vertex } Each instantiation can generate one vertex } Outputs are passed on to rasterizer where they are interpolated and available to fragment shaders } Position output in clip coordinates } There are lots of effects we can do in vertex shaders } Changing coordinate systems } Moving vertices } Per vertex lighting: height fields
  • 82. } A shader that’s executed for each “potential” pixel } fragments still need to pass several tests before making it to the framebuffer } There are lots of effects we can do in fragment shaders } Per-fragment lighting } Texture and bump Mapping } Environment (Reflection) Maps Fragment Shaders
  • 83. GLSL } OpenGL Shading Language } C like language with some C++ features } 2-4 dimensional matrix and vector types } Both vertex and fragment shaders are written in GLSL } Each shader has a main()
  • 84. GLSL Data Types } Scalar types:float, int, bool } Vector types:vec2, vec3, vec4 ivec2, ivec3, ivec4 bvec2, bvec3, bvec4 } Matrix types: mat2, mat3, mat4 } Texture sampling: sampler1D, sampler2D, sampler3D, samplerCube } C++ Style Constructors vec3 a = vec3(1.0, 2.0, 3.0);
  • 85. } Standard C/C++ arithmetic and logic operators } Overloaded operators for matrix and vector operations mat4 m; vec4 a, b, c; b = a*m; c = m*a; Operators
  • 86. } Access vector components using either: } [ ] (C-style array indexing) } xyzw, rgba or strq (named components) } For example: vec3 v; v[1], v.y, v.g, v.t - all refer to the same element } Component swizzling: vec3 a, b; a.xy = b.yx; Components and Swizzling
  • 87. } attribute } vertex attributes from application } varying } copy vertex attributes and other variables from vertex shaders to fragment shaders } values are interpolated by rasterizer varying vec2 texCoord; varying vec4 color; } uniform } shader-constant variable from application uniform float time; uniform vec4 rotation; Qualifiers
  • 88. Functions } Built in } Arithmetic: sqrt, power, abs } Trigonometric: sin, asin } Graphical: length, reflect } User defined
  • 89. } gl_Position } (required) output position from vertex shader } gl_FragColor } (required) output color from fragment shader } gl_FragCoord } input fragment position } gl_FragDepth } input depth value in fragment shader Built-in Variables
  • 90. attribute vec4 vPosition; attribute vec4 vColor; varying vec4 fColor; void main() { fColor = vColor; gl_Position = vPosition; } Simple Vertex Shader for Cube Example
  • 91. precision mediump float; varying vec4 fColor; void main() { gl_FragColor = fColor; } Simple Fragment Shader for Cube Example
  • 92. } Shaders need to be compiled and linked to form an executable shader program } WebGL provides the compiler and linker } A WebGL program must contain vertex and fragment shaders Getting Your Shaders into WebGL Create Shader Load Shader Source Compile Shader Create Program Attach Shader to Program Link Program gl.createProgram() gl.shaderSource() gl.compileShader() gl.createShader() gl.attachShader() gl.linkProgram() Use Program gl.useProgram() These steps need to be repeated for each type of shader in the shader program
  • 93. A Simpler Way } We’ve created a function for this course to make it easier to load your shaders } available at course website initShaders(vFile, fFile ); } initShaders takes two filenames } vFile path to the vertex shader file } fFile for the fragment shader file } Fails if shaders don’t compile, or program doesn’t link
  • 95. } Geometric objects are represented using vertices } A vertex is a collection of generic attributes } positional coordinates } colors } texture coordinates } any other data associated with that point in space } Position stored in 4 dimensional homogeneous coordinates } Vertex data must be stored in vertex buffer objects (VBOs) Representing Geometric Objects p = x y z w é ë ê ê ê ê ù û ú ú ú ú
  • 96. } All primitives are specified by vertices OpenGL Geometric Primitives GL_TRIANGLE_STRIP GL_TRIANGLE_FAN GL_LINES GL_LINE_LOOP GL_LINE_STRIP GL_TRIANGLES GL_POINTS
  • 97. } Vertex data must be stored in a Vertex Buffer Object (VBO) } To set up a VBO we must } create an empty by calling gl.createBuffer(); () } bind a specific VBO for initialization by calling gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer ); } load data into VBO using (for our points) gl.bufferData( gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW ); Storing Vertex Attributes
  • 98. } Associate shader variables with vertex arrays 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 ); var vBuffer = gl.createBuffer(); gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer ); gl.bufferData( gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW ); var vPosition = gl.getAttribLocation( program, "vPosition" ); gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 ); gl.enableVertexAttribArray( vPosition ); Vertex Array Code
  • 99. A Quick Note on Buffers & Attributes } createBuffer(), bindBuffer(), and bufferData() tell OpenGL where the actual data is stored in the memory. } vertexAttribPointer() and enableVertexAttribArray() tells OpenGL which shader attributes will use them.
  • 100. } So far, we ignore the last three parameters of vertexAttribPointer(), e.g., vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 ); } Exercise #1: Look up the definition of vertexAttribPointer() https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVer } Exercise #2: See a different use of vertexAttribPointer() at: https://github.com/openglredbook/examples/blob/master/src/04- gouraud/04-gouraud.cpp vertexAttribPointer()
  • 101. struct VertexData { GLubyte color[4]; GLfloat position[4]; }; VertexData vertices[NumVertices] = { ... }; glGenBuffers(NumBuffers, Buffers); glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(vColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(VertexData), BUFFER_OFFSET(0) ); glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), BUFFER_OFFSET(sizeof(vertices[0].color)) ); glEnableVertexAttribArray(vColor); glEnableVertexAttribArray(vPosition) An Advanced Example of vertexAttribPointer()
  • 103. } HTML code <script id="vertex-shader" type="x-shader/x-vertex"> attribute vec4 vPosition; attribute vec4 vColor; varying vec4 fColor; void main() { fColor = vColor; gl_Position = vPosition; } </script> <script id="fragment-shader" type="x-shader/x-fragment"> precision mediump float; varying vec4 fColor; // Note that this will be interpolated ... void main() { gl_FragColor = fColor; } </script> Example 2: Per-Vertex Color
  • 104. } window.onload = function init() { var canvas = document.getElementById( "gl- canvas" ); gl = WebGLUtils.setupWebGL( canvas ); if ( !gl ) { alert( "WebGL isn't available" ); } // Three Vertices var vertices = [ vec3( -1, -1, 0 ), vec3( 0, 1, 0 ), vec3( 1, -1, 0 ) ]; var colors = [ vec3( 1, 0, 0 ), vec3( 0, 1, 0 ), vec3( 0, 0, 1 ) ]; // Configure WebGL // gl.viewport( 0, 0, canvas.width, canvas.height ); gl.clearColor( 1.0, 1.0, 1.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 ); Example 2: Per-Vertex Color - Javascript Code
  • 105. // Associate our shader variables with our data buffer var vPosition = gl.getAttribLocation( program, "vPosition" ); gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 ); gl.enableVertexAttribArray( vPosition ); // Repeat the above process for the color attributes of the vertices. var cBufferId = gl.createBuffer(); gl.bindBuffer( gl.ARRAY_BUFFER, cBufferId ); gl.bufferData( gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW ); var vColor = gl.getAttribLocation( program, "vColor" ); gl.vertexAttribPointer( vColor, 3, gl.FLOAT, false, 0, 0 ); gl.enableVertexAttribArray( vColor ); render(); }; Example 2: Per-Vertex Color - Javascript Code
  • 106. Debugging Tips } Typos in JavaScript code may not produce any error message. } Try typing a wrong variable name (e.g., vColor à fColor) or wrong function name (e.g., getAttributeLocation) and see what happens. } Syntax errors like these will show up in the Console panel of the Chrome Developer Tools.
  • 107. Homework #1 } Draw at least two triangles like Example 1, with per-vertex colors like Example 2.
  • 108. • Render a cube with a different color for each face • Our example demonstrates: – simple object modeling • building up 3D objects from geometric primitives • building geometric primitives from vertices – initializing vertex data – organizing data for rendering – interactivity – animation Our Second Program
  • 109. } We’ll build each cube face from individual triangles } Need to determine how much storage is required } (6 faces)(2 triangles/face)(3 vertices/triangle) var numVertices = 36; } To simplify communicating with GLSL, we’ll use a package MV.js which contains a vec3 object similar to GLSL’s vec3 type Initializing the Cube’s Data
  • 110. } Before we can initialize our VBO, we need to stage the data } Our cube has two attributes per vertex } position } color } We create two arrays to hold the VBO data var points = []; var colors = []; Initializing the Cube’s Data (cont’d)
  • 111. } Vertices of a unit cube centered at origin } sides aligned with axes var vertices = [ vec4( -0.5, -0.5, 0.5, 1.0 ), vec4( -0.5, 0.5, 0.5, 1.0 ), vec4( 0.5, 0.5, 0.5, 1.0 ), vec4( 0.5, -0.5, 0.5, 1.0 ), vec4( -0.5, -0.5, -0.5, 1.0 ), vec4( -0.5, 0.5, -0.5, 1.0 ), vec4( 0.5, 0.5, -0.5, 1.0 ), vec4( 0.5, -0.5, -0.5, 1.0 ) ]; } We’ll also set up an array of RGBA colors } We can use vec3 or vec4 or just JS array var vertexColors = [ [ 0.0, 0.0, 0.0, 1.0 ], // black [ 1.0, 0.0, 0.0, 1.0 ], // red [ 1.0, 1.0, 0.0, 1.0 ], // yellow [ 0.0, 1.0, 0.0, 1.0 ], // green [ 0.0, 0.0, 1.0, 1.0 ], // blue [ 1.0, 0.0, 1.0, 1.0 ], // magenta [ 0.0, 1.0, 1.0, 1.0 ], // cyan [ 1.0, 1.0, 1.0, 1.0 ] // white ]; Cube Data 1 7 4 6 7 2 3 0
  • 112. } A JS array is an object with attributes and methods such as length, push() and pop() } fundamentally different from C-style array } cannot send directly to WebGL functions } use flatten() function to extract data from JS array gl.bufferData( gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW ); Arrays in JS
  • 113. } To simplify generating the geometry, we use a convenience function quad() } create two triangles for each face and assigns colors to the vertices function quad(a, b, c, d) { var indices = [ a, b, c, a, c, d ]; for ( var i = 0; i < indices.length; ++i ) { points.push( vertices[indices[i]] ); // for vertex colors use //colors.push( vertexColors[indices[i]] ); // for solid colored faces use colors.push(vertexColors[a]); } Generating a Cube Face from Vertices
  • 114. } Generate 12 triangles for the cube } 36 vertices with 36 colors function colorCube() { quad( 1, 0, 3, 2 ); quad( 2, 3, 7, 6 ); quad( 3, 0, 4, 7 ); quad( 6, 5, 1, 2 ); quad( 4, 5, 6, 7 ); quad( 5, 4, 0, 1 ); } Generating the Cube from Faces 1 7 4 6 7 2 3 0