Programming with Open. GL Part 1: Background Sai Keung Wong (黃世強 ) Computer Science National Chiao Tung University, Taiwan E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 1
Objectives • Development of the Open. GL API • Open. GL Architecture Open. GL as a state machine Open. GL as a data flow machine • Functions Types Formats • Simple program E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 2
Early History of APIs • IFIPS (1973) formed two committees to come up with a standard graphics API Graphical Kernel System (GKS) • 2 D but contained good workstation model Core • Both 2 D and 3 D GKS adopted as IS 0 and later ANSI standard (1980 s) • GKS not easily extended to 3 D (GKS 3 D) Far behind hardware development E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 3
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) E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 4
SGI and GL • Silicon Graphics (SGI) revolutionized the graphics workstation by implementing the pipeline in hardware (1982) • To access the system, application programmers used a library called GL • With GL, it was relatively simple to program three dimensional interactive applications E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 5
Open. GL The success of GL lead to Open. GL (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 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 6
Open. GL Evolution • Originally controlled by an Architectural Review Board (ARB) Members included SGI, Microsoft, Nvidia, HP, 3 DLabs, IBM, ……. Now Kronos Group Was relatively stable (through version 2. 5) • Backward compatible • Evolution reflected new hardware capabilities – 3 D texture mapping and texture objects – Vertex and fragment programs Allows platform specific features through extensions E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 7
Modern Open. GL • 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 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 8
Rasterisation • Rasterisation (or rasterization) is the task of taking an image described in a vector graphics format (shapes) and converting it into a raster image (pixels or dots) for output on a video display or printer, or for storage in a bitmap file format. http: //en. wikipedia. org/wiki/Rasterisation E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 9
Simple Illustration object moves up clipped away projection plane image on the projection plane pixels E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 rasterization 10
Rasterization for a Triangle
Open. GL 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 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 12
Other Versions • Open. GL ES Embedded systems Version 1. 0 simplified Open. GL 2. 1 Version 2. 0 simplified Open. GL 3. 1 • Shader based • Web. GL Javascript implementation of ES 2. 0 Supported on newer browsers • Open. GL 4. 1 and 4. 2 Add geometry shaders and tessellator E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 13
What About Direct X? • Windows only • Advantages Better control of resources Access to high level functionality • Disadvantages New versions not backward compatible Windows only • Recent advances in shaders are leading to convergence with Open. GL E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 14
Open. GL Libraries • Open. GL core library Open. GL 32 on Windows GL on most unix/linux systems (lib. GL. a) • Open. GL Utility Library (GLU) Provides functionality in Open. GL core but avoids having to rewrite code Will only work with legacy code • Links with window system GLX for X window systems WGL for Windows AGL for Macintosh E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 15
GLUT • Open. GL Utility Toolkit (GLUT) Provides functionality common to all window systems • • Open a window Get input from mouse and keyboard Menus Event driven Code is portable but GLUT lacks the functionality of a good toolkit for a specific platform • No slide bars E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 16
freeglut • GLUT was created long ago and has been unchanged Amazing that it works with Open. GL 3. 1 Some functionality can’t work since it requires deprecated functions • freeglut updates GLUT Added capabilities Context checking E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 17
GLEW • Open. GL Extension Wrangler Library • Makes it easy to access Open. GL extensions available on a particular system • Avoids having to have specific entry points in Windows code • Application needs only to include glew. h and run a glew. Init() E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 18
Software Organization E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 19
Open. GL Architecture E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 20
Open. GL Functions • Primitives Points Line Segments Triangles • Attributes • Transformations Viewing Modeling • Control (GLUT) • Input (GLUT) • Query E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 21
Open. GL State • Open. GL is a state machine • Open. GL functions are of two types Primitive generating • Can cause output if primitive is visible • How vertices are processed and appearance of primitive are controlled by the state State changing • Transformation functions • Attribute functions • Under 3. 1 most state variables are defined by the application and sent to the shaders E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 22
Lack of Object Orientation • Open. GL is not object oriented so that there are multiple functions for a given logical function gl. Uniform 3 f gl. Uniform 2 i gl. Uniform 3 dv • Underlying storage mode is the same • Easy to create overloaded functions in C++ but issue is efficiency E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 23
Open. GL function format function name dimensions gl. Uniform 3 f(x, y, z) belongs to GL library x, y, z are floats gl. Uniform 3 fv(p) p is a pointer to an array E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 24
Open. GL #defines • Most constants are defined in the include files gl. h, glu. h and glut. h Note #include <GL/glut. h> should automatically include the others Examples gl. Enable(GL_DEPTH_TEST) gl. Clear(GL_COLOR_BUFFER_BIT) • include files also define Open. GL data types: GLfloat, GLdouble, …. E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 25
Open. GL and GLSL • Shader based Open. GL is based less on a state machine model than a data flow model • Most state variables, attributes and related pre 3. 1 Open. GL functions have been deprecated • Action happens in shaders • Job is application is to get data to GPU E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 26
GLSL • Open. GL 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 • New Open. GL functions to compile, link and get information to shaders E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 27
A Simple Program (? ) Generate a square on a solid background E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 28
It used to be easy #include <GL/glut. h> void mydisplay(){ gl. Clear(GL_COLOR_BUFFER_BIT); gl. Begin(GL_QUAD; gl. Vertex 2 f(-0. 5, -0. 5); gl. Vertex 2 f(-0, 5, 0, 5); gl. Vertex 2 f(0. 5, 0. 5); gl. Vertex 2 f(0. 5, -0. 5); gl. End() } int main(int argc, char** argv){ glut. Create. Window("simple"); glut. Display. Func(mydisplay); glut. Main. Loop(); } E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 29
What happened • Most Open. GL functions deprecated • Makes heavy use of state variable default values that no longer exist Viewing Colors Window parameters • Next version will make the defaults more explicit • However, processing loop is the same E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 30
simple. c #include <GL/glut. h> void mydisplay(){ gl. Clear(GL_COLOR_BUFFER_BIT); // need to fill in this part // and add in shaders } int main(int argc, char** argv){ glut. Create. Window("simple"); glut. Display. Func(mydisplay); glut. Main. Loop(); } E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 31
Event Loop • Note that the program specifies a display callback function named mydisplay Every glut program must have a display callback The display callback is executed whenever Open. GL decides the display must be refreshed, for example when the window is opened The main function ends with the program entering an event loop E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 32
Notes on compilation • See website and ftp for examples • Unix/linux Include files usually in …/include/GL Compile with –lglut –lgl loader flags May have to add –L flag for X libraries Mesa implementation included with most linux distributions Check web for latest versions of Mesa and glut E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 33
Compilation on Windows • Visual C++ Get glut. h, glut 32. lib and glut 32. dll from web Install in same places as corresponding Open. GL files Create an empty application Add glut 32. lib to project settings (under link tab) Same for freeglut and GLEW • Cygwin (linux under Windows) Can use gcc and similar makefile to linux Use –lopengl 32–lglut 32 flags E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 34
Programming with Open. GL Part 2: Complete Programs Sai Keung Wong (黃世強 ) Computer Science National Chiao Tung University, Taiwan E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 35
Objectives • Build a complete first program Introduce shaders Introduce a standard program structure • Simple viewing Two dimensional viewing as a special case of three dimensional viewing • Initialization steps and program structure E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 36
Program Structure • Most Open. GL programs have a similar structure that consists of the following functions main(): • specifies the callback functions • opens one or more windows with the required properties • enters event loop (last executable statement) init(): sets the state variables • Viewing • Attributes init. Shader(): read, compile and link shaders callbacks • Display function • Input and window functions E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 37
simple. c revisited • main() function similar to last lecture Mostly GLUT functions • init() will allow more flexible colors • init. Shader() will hides details of setting up shaders for now • Key issue is that we must form a data array to send to GPU and then render it E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 38
main. c #include <GL/glew. h> #include <GL/glut. h> includes gl. h int main(int argc, char** argv) { glut. Init(&argc, argv); glut. Init. Display. Mode(GLUT_SINGLE|GLUT_RGB); glut. Init. Window. Size(500, 500); glut. Init. Window. Position(0, 0); specify window properties glut. Create. Window("simple"); glut. Display. Func(mydisplay); display callback glew. Init(); set Open. GL state and initialize shaders init(); glut. Main. Loop(); } enter event loop E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 39
GLUT functions • glut. Init allows application to get command line arguments and initializes system • glu. Init. Display. Mode requests properties for the window (the rendering context) RGB color Single buffering Properties logically ORed together • glut. Window. Size in pixels • glut. Window. Position from top left corner of display • glut. Create. Window create window with title “simple” • glut. Display. Func display callback • glut. Main. Loop enter infinite event loop E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 40
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 gl. Vertex Creates bottleneck between CPU and GPU Removed from Open. GL 3. 1 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 41
Retained Mode Graphics • Put all vertex and 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 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 42
Display Callback • Once we get data to GLU, we can initiate the rendering with a simple callback void mydisplay() { gl. Clear(GL_COLOR_BUFFER_BIT); gl. Draw. Arrays(GL_TRIANGLES, 0, 3); gl. Flush(); } • Arrays are buffer objects that contain vertex arrays E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 43
Vertex Arrays • Vertices can have many attributes Position Color Texture Coordinates Application data • A vertex array holds these data • Using types in vec. h point 2 vertices[3] = {point 2(0. 0, 0. 0), point 2( 0. 0, 1. 0), point 2(1. 0, 1. 0)}; E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 44
Vertex Array Object • Bundles all vertex data (positions, colors, . . , ) • Get name for buffer then bind Glunit abuffer; gl. Gen. Vertex. Arrays(1, &abuffer); gl. Bind. Vertex. Array(abuffer); • At this point we have a current vertex array but no contents • Use of gl. Bind. Vertex. Array lets us switch between VBOs E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 45
Buffer Object • Buffers objects allow us to transfer large amounts of data to the GPU • Need to create, bind and identify data Gluint buffer; gl. Gen. Buffers(1, &buffer); gl. Bind. Buffer(GL_ARRAY_BUFFER, buffer); gl. Buffer. Data(GL_ARRAY_BUFFER, sizeof(points), points); • Data in current vertex array is sent to GPU E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 46
Initialization • Vertex array objects and buffer objects can be set up on init() • Also set clear color and other Ope. GL parameters • Also set up shaders as part of initialization Read Compile Link • First let’s consider a few other issues E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 47
Coordinate Systems • The units in points are determined by the application and are called object, world, model or problem coordinates • Viewing specifications usually are also in object coordinates • Eventually pixels will be produced in window coordinates • Open. GL also uses some internal representations that usually are not visible to the application but are important in the shaders E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 48
Open. GL Camera • Open. GL places a camera at the origin in object space pointing in the negative z direction • The default viewing volume is a box centered at the origin with sides of length 2 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 49
Orthographic Viewing In the default orthographic view, points are projected forward along the z axis onto the plane z=0 z=0 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 50
Viewports • Do not have use the entire window for the image: gl. Viewport(x, y, w, h) • Values in pixels (window coordinates) E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 51
Transformations and Viewing • In Open. GL, projection is carried out by a projection matrix (transformation) • Transformation functions are also used for changes in coordinate systems • Pre 3. 0 Open. GL had a set of transformation functions which have been deprecated • Three choices Application code GLSL functions vec. h and mat. h E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 52
Programming with Open. GL Part 3: Shaders Sai Keung Wong (黃世強 ) Computer Science National Chiao Tung University, Taiwan E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 53
Objectives • Simple Shaders Vertex shader Fragment shaders • Programming shaders with GLSL • Finish first program E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 54
Vertex Shader Applications • Moving vertices Morphing Wave motion Fractals • Lighting More realistic models Cartoon shaders E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 55
Fragment Shader Applications Per fragment lighting calculations per vertex lighting per fragment lighting E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 56
Fragment Shader Applications Texture mapping smooth shading environment mapping bump mapping E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 57
Writing Shaders • First programmable shaders were programmed in an assembly like manner • Open. GL extensions added for vertex and fragment shaders • Cg (C for graphics) C like language for programming shaders Works with both Open. GL and Direct. X Interface to Open. GL complex • Open. GL Shading Language (GLSL) E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 58
GLSL • Open. GL Shading Language • Part of Open. GL 2. 0 and up • High level C like language • New data types Matrices Vectors Samplers • As of Open. GL 3. 1, application must provide shaders E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 59
Simple Vertex Shader input from application in vec 4 v. Position; must link to variable void main(void) in application { gl_Position = v. Position; } built in variable E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 60
Execution Model Vertex data Shader Program Application Program GPU Vertex Shader gl. Draw. Arrays Primitive Assembly Vertex E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 61
Simple Fragment Program void main(void) { gl_Frag. Color = vec 4(1. 0, 0. 0, 1. 0); } E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 62
Execution Model Application Shader Program Rasterizer Fragment Shader Frame Buffer Fragment Color E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 63
Data Types • C types: int, float, bool • Vectors: float vec 2, vec 3, vec 4 Also int (ivec) and boolean (bvec) • Matrices: mat 2, mat 3, mat 4 Stored by columns Standard referencing m[row][column] • C++ style constructors vec 3 a =vec 3(1. 0, 2. 0, 3. 0) vec 2 b = vec 2(a) E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 64
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. mat 3 func(mat 3 a) E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 65
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 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 66
Attribute Qualifier • Attribute qualified variables can change at most once per vertex • There a few built in variables such as gl_Position but most have been deprecated • User defined (in application program) Use in qualifier to get to shader in float temperature in vec 3 velocity E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 67
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 bounding box of a primitive E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 68
Varying Qualified • Variables that are passed from vertex shader to fragment shader • Automatically interpolated by the rasterizer • Old style used the varying qualifier varying vec 4 color; • Now use out in vertex shader and in in the fragment shader out vec 4 color; E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 69
Example: Vertex Shader const vec 4 red = vec 4(1. 0, 0. 0, 1. 0); out vec 3 color_out; void main(void) { gl_Position = v. Position; color_out = red; } E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 70
Required Fragment Shader in vec 3 color_out; void main(void) { gl_Frag. Color = color_out; } // in latest version use form // out vec 4 fragcolor; // fragcolor = color_out; E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 71
Passing values • call by value-return • Variables are copied in • Returned values are copied back • Three possibilities in out inout (deprecated) E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 72
Operators and Functions • Standard C functions Trigonometric Arithmetic Normalize, reflect, length • Overloading of vector and matrix types mat 4 a; vec 4 b, c, d; c = b*a; // a column vector stored as a 1 d array d = a*b; // a row vector stored as a 1 d array E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 73
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 vec 4 a; a. yz = vec 2(1. 0, 2. 0); E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 74
Programming with Open. GL Part 4: Color and Attributes Sai Keung Wong (黃世強 ) Computer Science National Chiao Tung University, Taiwan E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 75
Objectives • Expanding primitive set • Adding color • Vertex attributes • Uniform variables E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 76
Open. GL Primitives GL_POINTS GL_LINE_STRIP GL_LINE_LOOP GL_TRIANGLES GL_TRIANGLE_STRIP GL_TRIANGLE_FAN E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 77
Examples for Open. GL Primitives GLfloat p[10][3] = … gl. Begin ( GL_POINTS ) ; for ( int i = 0; i< 10; ++i ) { gl. Color 3 f… gl. Vertex 3 fv ( p[i] ); } gl. End( ); struct my. Line { GLfloat p 0[3], p 1[3]; }; my. Triangle my. Line[64]; gl. Begin ( GL_TRIANGLESS ) ; for ( int i = 0; i< 64; ++i ) { gl. Color 3 f… gl. Vertex 3 fv ( my. Tri[i]. p 0 ); gl. Color 3 f… gl. Vertex 3 fv ( my. Tri[i]. p 1 ); } gl. End( ); 78 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012
Examples for Open. GL Primitives struct my. Triangle { GLfloat p 0[3], p 1[3], p 2[3]; }; my. Triangle my. Tri[128]; gl. Begin ( GL_TRIANGLES_STRIP ) ; for ( int i = 0; i< 128; ++i ) { gl. Normal 3 f … gl. Vertex 3 fv ( my. Tri[i]. p 0 ); gl. Normal 3 f … gl. Vertex 3 fv ( my. Tri[i]. p 1 ); gl. Normal 3 f … gl. Vertex 3 fv (my. Tri[i]. p 2 ); } gl. End( ); my. Triangle my. Tri[128]; gl. Begin ( GL_TRIANGLESS ) ; for ( int i = 0; i< 128; ++i ) { gl. Normal 3 f … gl. Vertex 3 fv ( my. Tri[i]. p 0 ); gl. Normal 3 f … gl. Vertex 3 fv ( my. Tri[i]. p 1 ); gl. Normal 3 f … gl. Vertex 3 fv (my. Tri[i]. p 2 ); } gl. End( ); p 0 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 p 1 79
Polygon Issues • Open. GL 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) • Open. GL 4. 1 contains a tessellator nonsimple polygon nonconvex polygon E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 80
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 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 81
Good and Bad Triangles • Long thin triangles render badly • Equilateral triangles render well • Maximize minimum angle • Delaunay triangulation for unstructured points E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 82
Triangularization • Convex polygon d c b a • Start with abc, remove b, then acd, …. E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 83
Non-convex (concave) E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 84
Recursive Division • Find leftmost vertex and split E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 85
Attributes • Attributes determine the appearance of objects Color (points, lines, polygons) Size and width (points, lines) Stipple pattern (lines, polygons) Polygon mode • Display as filled: solid color or stipple pattern • Display edges • Display vertices • Only a few (gl. Point. Size) are supported by Open. GL functions E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 86
RGB color • Each color component is stored separately in the frame buffer • Usually 8 bits per component in buffer • Color values can range from 0. 0 (none) to 1. 0 (all) using floats or over the range from 0 to 255 using unsigned bytels E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 87
Indexed Color • Colors are indices into tables of RGB values • Requires less memory indices usually 8 bits not as important now • Memory inexpensive • Need more colors for shading E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 88
Smooth Color • Default is smooth shading Open. GL interpolates vertex colors across visible polygons • Alternative is flat shading Color of first vertex determines fill color Handle in shader E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 89
Setting Colors • Colors are ultimately set in the fragment shader but can be determined in either shader or in the application • Application color: pass to vertex shader as a uniform variable (next lecture) or as a vertex attribute • Vertex shader color: pass to fragment shader as varying variable (next lecture) • Fragment color: can alter via shader code E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 90
Programming with Open. GL Part 5: More GLSL Sai Keung Wong (黃世強 ) Computer Science National Chiao Tung University, Taiwan E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 91
Objectives • Coupling shaders to applications Reading Compiling Linking • Vertex Attributes • Setting up uniform variables • Example applications E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 92
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 E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 93
Program Object • Container for shaders Can contain multiple shaders Other GLSL functions GLuint my. Prog. Obj; my. Prog. Obj = gl. Create. Program(); /* define shader objects here */ gl. Use. Program(my. Prog. Obj); gl. Link. Program(my. Prog. Obj); E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 94
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. Shader. Source • If the shader is in a file, we can write a reader to convert the file to a string E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 95
Shader Reader #include <stdio. h> static char* read. Shader. Source(const char* shader. File) { FILE* fp = fopen(shader. File, "r"); if ( fp == NULL ) { return NULL; } fseek(fp, 0 L, SEEK_END); long size = ftell(fp); E. Angel and D. Shreiner: Interactive Computer Graphics 6 E © Addison-Wesley 2012 96
Shader Reader (cont) fseek(fp, 0 L, SEEK_SET); char* buf = new char[size + 1]; fread(buf, 1, size, fp); buf[size] = '