lecture 2 : programming with opengl · 2019. 2. 25. · opengl #defines • most constants are...
TRANSCRIPT
Lecture 2 : Programming with OpenGL
Slides: E. Angel and D. Shreiner: Interactive Computer Graphics 6E © Addison-Wesley 2012
CITS3003 Graphics & Animation
Objectives
• OpenGL libraries
• OpenGL architecture
• OpenGL types and functions
• A simple program
2
Modern OpenGL
• Allows the computer program to achieve fast graphics performance by using GPU rather than CPU
• Allows applications to control GPU through programs known as shaders
• It is the application’s job is to send data to GPU
• GPU then does all the rendering
3
Software Organization
• The application programs can use GLEW, GL, GLUT functions but not directly access to GLX, Xlib, etc.
• The program can therefore be recompiled with the GLUT libraries for other operating systems.
4uses
uses
High level Low level
4
OpenGL Types
• In OpenGL, we use basic OpenGL types, e.g. GLfloat, GLdouble, GLint, etc (equivalent to float, double, and int in C/C++)
• Additional data types are supplied in header files vec.h and mat.h from Angel and Shreiner, e.g. vec2, vec3, mat2, point2, point3, etc.
5
State Machine
• We can think of the entire graphics system as a state machine, a black box that contains a finite-state machine.
• This state machine has inputs coming from the application program. These inputs can change the state of the machine or can cause the machine to produce a visible output.
Graphics system as a black box
6
State Machine (cont.)• From the perspective of the API, there are two
types of graphics functions:1. Functions that define primitives that flow through the
state machine. These functions• define how vertices are processed (the appearance of
primitives are controlled by the state of the machine)• can cause output if the primitive is visible
2. Functions that either change the state inside the machine or return the state information, e.g.• Transformation functions• Attribute functions• In OpenGL, most state variables are defined by the application
and sent to the shaders
7
OpenGL Functions
• OpenGL provides a range of functions for specifying:• Primitives
o Pointso Line Segmentso Triangles
• Attributes• Transformations
o Viewingo Modeling
• Control (GLUT)• Input (GLUT)• Query
8
What are OpenGL Primitives?
GL_TRIANGLE_STRIP GL_TRIANGLE_FAN
GL_POINTS
GL_LINES
GL_LINE_LOOP
GL_LINE_STRIP
GL_TRIANGLES
9
What are attributes?
• Attributes are properties associated with the primitives that give them their different appearances, e.g.• Color (for points, lines, polygons)
• Size and width (for points, lines)
• Stipple pattern (for lines, polygons)
• Polygon mode
• Display as filled: solid color or stipple pattern
• Display edges
• Display vertices
• Note: glPointSize: The actual size that is displayed on the screen will be different. More on this later.
10
OpenGL functions:Lack of Object Orientation
• OpenGL is not object oriented so that there are multiple functions for a given logical function, e.g., the following are the same function but for different parameter types:o glUniform3f
o glUniform2i
o glUniform3dv
• The underlying storage mode is the same
• It is easy to create overloaded functions in C++ but the issue is efficiency
11
Format of OpenGL functions
glUniform3f(x,y,z)
belongs to GL library
function name
x,y,z are floats
glUniform3fv(p)
p is a pointer to an array
dimensions
12
glUniform — Specify the value of a uniform variable for the current program object
OpenGL #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: the functions glEnable and glClear
are both declared in gl.h
• The OpenGL data types GLfloat, GLdouble,….are also declared in gl.h
13
What is GLSL?
• GLSL is short for OpenGL Shading Language
• It is a C-like language with:o Built-in Matrix and vector types (2, 3, 4 dimensional)
o Overloaded operators
o C++ like constructors
• It is similar to Nvidia’s Cg and Microsoft HLSL
• Code sent to shaders as source code
• New OpenGL functions to compile, link and get information to shaders
14
A Simple Program
simple.cpp - Generates a white square on a black background
15
A Simple Program (cont.)
• Most OpenGL programs have a similar structure that consists of the following functions:
o main(): creates the window, calls the init() function, specifies callback functions (more about this in a later topic) relevant to the application, enters event loop (last executable statement)
o init(): defines the vertices, attributes, etc. of the objects to be rendered, specifies the shader programs (more about this later)
o display(): this is a callback function that defines what to draw whenever the window is refreshed.
16
simple.cpp#include <GL/glut.h>
void init() {
// code to be inserted here
}
void mydisplay(){
glClear(GL_COLOR_BUFFER_BIT);
// need to fill in this part
// and add in shaders
}
int main(int argc, char** argv){
glutCreateWindow("simple");
init();
glutDisplayFunc(mydisplay);
glutMainLoop();
}
includes gl.h
set up OpenGL state
and initialize shaders
enter event loop
create a window
with “simple” as
its title
17
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 OpenGL decides the display must be refreshed, for example when the window is opened
• The main function ends with the program entering an event loop
18
simple.cpp – the complete program#include “Angel.h”
using namespace std;
const int NumTriangles = 2; // 2 triangles to be displayedconst int NumVertices = 3 * NumTriangles;
vec3 points[NumVertices] = {vec3( -0.5, -0.5, 0.0 ), vec3( 0.5, -0.5, 0.0 ), vec3( -0.5, 0.5, 0.0 ),vec3( 0.5, 0.5, 0.0 ), vec3( -0.5, 0.5, 0.0 ), vec3( 0.5, -0.5, 0.0 )
};
void init( void ){
// Create a vertex array objectGLuint vao;glGenVertexArrays( 1, &vao );glBindVertexArray( vao );
19
simple.cpp – the complete program// Create and initialize a buffer objectGLuint buffer;glGenBuffers( 1, &buffer );glBindBuffer( GL_ARRAY_BUFFER, buffer );
// First, we create a buffer of the size we need to store the six pointsglBufferData( GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW );// Load shaders and use the resulting shader programGLuint program = InitShader( "vertex.glsl", "fragment.glsl" );glUseProgram( program );
// Initialize the vertex position attribute from the vertex shaderGLuint vPos = glGetAttribLocation( program, "vPosition" );glEnableVertexAttribArray( vPos );glVertexAttribPointer( vPos, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );
glClearColor( 0.0, 0.0, 0.0, 0.0 ); /* black background */
}
The two shaderprograms are compiled here to give a GLuintoutput. See InitShader.cpp.
20
Does data need normalization?
stride
simple.cpp – the complete programvoid display( void ){
glClear( GL_COLOR_BUFFER_BIT );glDrawArrays( GL_TRIANGLES, 0, NumVertices ); // draw the two trianglesglFlush(); // draw it now!
}
int main( int argc, char **argv ){
glutInit( &argc, argv );glutInitDisplayMode( GLUT_RGBA );glutInitWindowSize( 256, 256 );glutCreateWindow( "simple" );
init();glutDisplayFunc( display );glutMainLoop();
}21
Specifies the startingindex in the enabled array
Vertex shader for simple.cpp
Contents of the file vertex.glsl
attribute vec4 vPosition;
void main(){
gl_Position = vPosition;}
Must be the same as the name chosen in simple.cpp (see the 2nd parameter passed to the glGetAttribLocation function.
Built-in variable name in GLSL, denoting the vertex coordinates in 4-dimensions.
Application program is simple.cpp. It must work with two shader programs, written in GLSL. They must work together.
22
Fragment shader for simple.cpp
Contents of the file fragment.glsl
void main(){
gl_FragColor = vec4( 1.0, 1.0, 1.0, 1.0 );}
Built-in variable name in GLSL, denoting the colour (as a 4D vector) to be put at that vertex.
23
Notes on compilation
• See website and ftp for examples
• Unix/linuxo Header files are usually in /usr/include/GL
o Compile with –lglut and –lgl loader flags
o May have to add –L flag for directory of X libraries
o Mesa implementation is included with most linuxdistributions
o Check the web for latest versions of Mesa and glut
24
Compilation on Windows
• Visual C++o Get glut.h, glut32.lib and glut32.dll from web
o Install in same places as corresponding OpenGL files
o Create an empty application
o Add glut32.lib to project settings (under link tab)
o Same for freeglut and GLEW
• Cygwin (linux under Windows)
o Can use gcc and similar makefile to linux
o Use –lopengl32 and –lglut32 flags
25
Part of example1.cpp// Two-Dimensional Sierpinski Gasket
#include "Angel.h"const int NumPoints = 5000;
void init( ){
vec2 points[NumPoints];vec2 vertices[3] = { vec2( -1.0, -1.0 ), vec2( 0.0, 1.0 ), vec2( 1.0, -1.0 ) };// Select an arbitrary initial point inside of the trianglepoints[0] = vec2( 0.25, 0.50 );
for ( int i = 1; i < NumPoints; ++i ) {int j = rand() % 3; // pick a vertex at random// Compute the point halfway between the selected vertex and the previous pointpoints[i] = ( points[i - 1] + vertices[j] ) / 2.0;
}. . .
}
26
Further Reading
“Interactive Computer Graphics – A Top-Down Approach with Shader-Based OpenGL” by Edward Angel and Dave Shreiner, 6th Ed, 2012
• Sec. 2.4 Primitives and Attributes (up to Sec. 2.4.1)
• Sec. 2.3.1 Graphics Functions
• Sec. 2.3.2 Graphics Pipeline and State Machine
• Sec. 8.10 Graphics and the Internet
• (Advanced) Appendix A.2
27