计算机代写 1 OpenGL Basics

1 OpenGL Basics
R. Mukundan Department of Computer Science and Software Engineering University of Canterbury, .

Lecture Outline

Copyright By PowCoder代写 加微信 powcoder

 A basic OpenGL program
 GLUT built-in objects
 Modelling-rendering-animation pipeline  Points and vectors
 Primitives: Triangles, quads
 Model and color definitions
 Camera and Lights
 Event processing
R. Mukundan, CSSE, University of Canterbury

OpenGL 2 Core Libraries
 OpenGL: Basic API, preloaded into the system. glVertex3f, glColor4f, glPushMatrix, glMatrixMode, glLightfv,
glTranslatef, glRotatef, glFrustum, glOrtho, …
 GLU (OpenGL Utility Library): Higher level functions for drawing and viewing.
gluLookAt, gluPerspective, gluOrtho2D, gluCylinder, …
 GLUT (OpenGL Utility Toolkit): Platform independent interface for the native window system, call-back based event processing, and some built-in geometrical objects.
glutCreateWindow, glutMouseFunc, glutSolidTeapot
http://freeglut.sourceforge.net/
R. Mukundan, CSSE, University of Canterbury

A Basic OpenGL Program
Teapot.cpp
#include
void display(void) {
All display commands
void initialize(void) {
Parameter/state initialization
int main(…) {
R. Mukundan, CSSE, University of Canterbury
GLUT initialization

Teapot.cpp [1]
int main(int argc, char **argv) {
Display buffers
glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_DEPTH); glutInitWindowSize(600, 600); glutInitWindowPosition(0, 0); glutCreateWindow(“Teapot”);
initialize();
glutDisplayFunc(display);
glutMainLoop();
Display callback
return 0; }
Do not place any code here!
R. Mukundan, CSSE, University of Canterbury

Teapot.cpp [2]
void initialize(void) {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION); glLoadIdentity();
glFrustum(-5.0, 5.0, -5.0, 5.0, 10.0, 1000.0);
Background colour
OpenGL state
R. Mukundan, CSSE, University of Canterbury

Teapot.cpp [3]
void display(void) {
float light_pos[4] = {0., 10., 10., 1.0};
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
Camera Position
gluLookAt(0, 0, 12, 0, 0, 0, 0, 1, 0); glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
glColor3f(0.0, 1.0, 1.0); glutSolidTeapot(1.0); glFlush();
Light’s Position
R. Mukundan, CSSE, University of Canterbury
A GLUT built-in object

GLUT Built-in Objects
Sphere Torus Cone
Tetrahedron Cube
GLUT-GLU-Objects.pdf
Icosahedron
R. Mukundan, CSSE, University of Canterbury

Platonic Solids
Tetrahedron Cube Icosahedron
 Platonic solids are geometrical shapes formed using identical regular (equilateral and equiangular) polygons
 The same number of faces and edges meet at each vertex. That is, all vertices have the same valence.
 Only 5 platonic solids exist.
 Dodecahedron (12 faces, 20 vertices) is the dual shape of icosahedron (20 faces, 12 vertices). Similarly the cube (hexahedron) and octahedron are dual shapes.
R. Mukundan, CSSE, University of Canterbury

Subdivisions of an Icosahedron
Two Types of Spheres
R. Mukundan, CSSE, University of Canterbury
Icosphere Geodesic Sphere
glutWireSphere()

A Simple Model Using Only GLUT Objects
R. Mukundan, CSSE, University of Canterbury

Basic Pipeline
Illumination Models
User Designed Models
Procedurally Generated Models
Procedurally Generated Animation
Primitives
Modelling Built-in Software Models
https://www.turbosquid.com/
Keyframe Animation
Physics Based Animation
https://www.textures.com/
R. Mukundan, CSSE, University of Canterbury

Modelling and Rendering: Example
R. Mukundan, CSSE, University of Canterbury

Modelling and Rendering: Example
R. Mukundan, CSSE, University of Canterbury

Coordinate Frame
Three-dimensional points (x, y, z) and vectors are always defined in a right-handed coordinate reference frame.
Direction of rotation from x to y axis.
In the direction of the z axis.
R. Mukundan, CSSE, University of Canterbury

(6, 10, 3) P
Points and Vectors
(7, 8, 0) Q
(13, 2, 3) x
z Unit Vectors
3D components of a vector
• Specifying transformations
• Directions of light sources
• Spotlight direction
• normal vectors
(10, 12, 5)
3D coordinates of a point
• Defining vertices of primitives
• Positions of light sources
• Camera position and orientation • …etc.
• … etc. R. Mukundan, CSSE, University of Canterbury
1 (0,1,0) 1
1 (1, 0, 0) (0, 0, 1)

Vectors: Examples
(-sin, cos, 0)
(cos, sin, 0) xx
(-1, -1, 0)
(1, -1, 0)
Length of a vector (x, y, z): 𝑥2 +𝑦2 +𝑧2
Vector addition
R. Mukundan, CSSE, University of Canterbury

Homogeneous Coordinates
We use homogeneous coordinates to distinguish between points and vectors. (x, y, z, 1) is a point while (x, y, z, 0) is a vector.
Point (4, 3, 0, 1) (4, 3, 0)
Vector (4, 3, 0, 0) (19, 7, 6)
(15, 10, 6)
Vector (4, 3, 0, 0)
(0.8, 0.6, 0, 0)
Unit Vector
glVertex3f (4.0, 3.0, 0)
glVertex4f (4.0, 3.0, 0, 1)
glVertex4f (4.0, 3.0, 0, 0)
R. Mukundan, CSSE, University of Canterbury
glTranslatef (4.0, 3.0, 0);

Model Definition
3D models can be constructed using a collection of triangles. (Triangle meshes)
glBegin(GL_TRIANGLES); glVertex3f(x1, y1, z1); glVertex3f(x2, y2, z2); glVertex3f(x3, y3, z3); glVertex3f(x4, y4, z4); glVertex3f(x5, y5, z5); glVertex3f(x6, y6, z6);
glVertex3f(x7, y7, z7);
(x3,y3,z3)
Important!
(x2,y2,z2)
(x1,y1,z1)
(x6,y6,z6)
(x4,y4,z4)
(x5,y5,z5)
The vertices are always specified in anti-clockwise sense with respect to the outward normal.
R. Mukundan, CSSE, University of Canterbury

Model Definition
Some 3D models are constructed using only quadrilaterals.
(Quad meshes) Example
Primitive Type
glBegin(GL_QUADS); glVertex3f(x1, y1, z1); glVertex3f(x2, y2, z2); glVertex3f(x3, y3, z3); glVertex3f(x4, y4, z4);
glVertex3f(x5, y5, z5);
glVertex3f(x6, y6, z6);
(x4,y4,z4) (x3,y3,z3)
(x1,y1,z1) (x2,y2,z2)
R. Mukundan, CSSE, University of Canterbury

Geometrical Objects
 Two other primitive types, GL_TRIANGLE_STRIP and GL_QUAD_STRIP, are also commonly used in object modelling. These will be introduced later..
 Several mesh file formats for storing object definitions exist: OBJ, PLY, OFF, DXF, 3DS, MAX, X3D … etc. In addition to geometry data, a mesh file may also contain several other useful information such as normal components, texture coordinates, colour values, and material properties.
 Complex mesh geometries containing a large number of polygons are often stored in a compressed binary form.
19536 Triangles 69451 Triangles
R. Mukundan, CSSE, University of Canterbury

Object File Format (OFF)
The simplest ASCII mesh file format.
Always begins with keyword OFF
-0.5 -0.5 0.5
0.5 -0.5 0.5
0.5 0.5 0.5 -0.5 0.5 0.5 -0.5 -0.5 -0.5
0.5 -0.5 -0.5
0.5 0.5 -0.5
-0.5 0.5 -0.5
40123 41562 43267 43740 40451 47654
Number of vertices, polygons and edges
Vertex coordinates
R. Mukundan, CSSE, University of Canterbury
Note anti-clockwise ordering of vertices
Face definition: No. of verts,
face indices

Model Loaders
 A 3D model loader function parses a mesh file and extracts vertex, face and other related information required for
rendering the model.
Vertex Coordinates
x[], y[], z[] t1[], t2[], t3[], t4[]
Face Definition
loadMeshFile()
Mesh file parser
glBegin(GL_QUADS); glVertex3f(…);
glVertex3f(…);
R. Mukundan, CSSE, University of Canterbury

Colors are defined using the additive RGB color space, with 3 components R, G, B, and an optional 4th alpha (transparency)
component.
Normalized Color Values
R. Mukundan, CSSE, University of Canterbury
(255,255,255)
Note: The maximum value of any normalized color component is 1.
glColor3f(0, 1, 1); glColor4f(0, 1, 1, 1); glColor3ub(0, 255, 255);

Color Arithmetic
Complementary Colours: Red + Cyan = White
(1,0,0) + (0,1,1) = (1,1,1)
Green + Magenta = White
(0,1,0) + (1,0,1) = (1,1,1)
Blue + Yellow = White
(0,0,1) + (1,1,0) = (1,1,1)
White – Red = Cyan
(1,1,1) + (1,0,0) = (0,1,1)
Red*0.5 = Dark Red
(1, 0, 0)*0.5 = (0.5, 0, 0)
R. Mukundan, CSSE, University of Canterbury

Color Arithmetic
Scaling a color by a factor k (0  k  1) gives a darker shade of that color k = 1 k = 0.5 k = 0.2 k = 0.
(1, 0, 1) (0.5, 0., 0.5) (0.2, 0., 0.2) (0., 0., 0.)
Two colors C1 and C2 are blended using a linear combination  C1 +  C2, where  +  = 1.
 = 1,  = 0 (1, 0, 1)
 = 0.5,  = 0.5 (1, 0.5, 0.5)
 = 0,  = 1 (1, 1, 0)
R. Mukundan, CSSE, University of Canterbury

 Colors are used as material properties and light properties.
 A light’s color is usually specified as white (1,1,1).
 The color on a diffusely reflecting surface varies from the specified material color to black (0,0,0), depending on the orientation of the surface with respect to the light source.
k = cos(), where  is the angle between the vector towards the light source and the normal vector.
R. Mukundan, CSSE, University of Canterbury

 In OpenGL, you can select up to 8 light sources:
 GL_LIGHT0, GL_LIGHT1, …, GL_LIGHT7 0…7  A light source is selected using glEnable(GL_LIGHT#) ;
 You should also enable lighting calculations using glEnable(GL_LIGHTING);
 Positioning light sources:
 Omni-directional point sources:
(x, y, z) glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
float light_pos[] = {10, -3.5, 200, 1}
 Directional light sources:
float light_pos[] = {10, -3.5, 200, 0}
glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
R. Mukundan, CSSE, University of Canterbury
(x, y, z) 28

In OpenGL, a light source is just a virtual point. This position is used only to modulate the colour values at vertices based on the angle between the light vector and the surface normal.
Light’s position
R. Mukundan, CSSE, University of Canterbury
Walls don’t obstruct light!

Real Camera:
OpenGL Virtual Camera:
Focal length
Projection
R. Mukundan, CSSE, University of Canterbury

OpenGL uses a simple perspective projection model based on a view frustum specified along the view axis of the camera. Only those vertices that fall within the view frustum are processed.
R. Mukundan, CSSE, University of Canterbury
Projection Plane
(Near plane)
View Frustum

View Near Frustum
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(left, right, bottom, top, near, far);
R. Mukundan, CSSE, University of Canterbury

Alternate definition using field of view (fov) and aspect ratio:
Aspect Ratio =
Width Height
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(fov, aspect, near, far);
R. Mukundan, CSSE, University of Canterbury

Camera Projection
Near Plane
R. Mukundan, CSSE, University of Canterbury

FOV Reduction
gluPerspective(fov, aspect, near, far);
R. Mukundan, CSSE, University of
 The OpenGL functions glFrustum, gluPerspective specify the projection mechanism. They only “select the lens of the camera”.
 We need to position the camera within the scene at the required location and orientation. This is done using the gluLookAt(..) function.
 By positioning and orienting the camera, you are actually defining a transformation from the world coordinate space (using which the scene is constructed) to the local coordinate space of the camera (eye coordinate frame).
R. Mukundan, CSSE, University of Canterbury

Camera View
Eye Coordinate Frame
The camera/viewer is at the origin of the eye coordinate frame.
World Coordinate Frame
R. Mukundan, CSSE, University of Axis

Camera Position
View Frustum
(e , e , e ) xyz
(l , l , l ) xyz
Look point
World Coordinate Frame
gluLookAt(ex,ey,ez, lx,ly,lz, 0,1,0);
Camera Look Approximate position point Up-vector
R. Mukundan, CSSE, University of Canterbury

Camera Orientation
 The position and the look-point together define the camera’s view axis (and therefore the ze axis).
 We have to fix the rotation of the camera about the view axis. This is done by specifying the approximate up-vector – usually defined as (0, 1, 0). The camera’s true up-vector (ye) then gets fixed on the plane containing the approximate up- vector and the view axis.
Approx. Up-Vector (0, 1, 0)
R. Mukundan, CSSE, University of Canterbury

Camera Orientation
A teapot is placed at the point (3, 0, 0) along the x-axis.
The camera is located at (6, 2, 0).
gluLookAt( 6, 2, 0, 3, 0, 0, 0,1,0 );
gluLookAt( 6, 2, 4, 3, 0, 0, 0,1,0 );
gluLookAt( 6, 2, 4, 0, 0, 4, 0,1,0 );
Camera looks at a point on the z axis 40
R. Mukundan, CSSE, University of moved along the z direction

Camera Orientation
The up-vector is usually specified as (0, 1, 0). Changing the components of the up vector causes a rotation of the camera about the view axis.
gluLookAt( 6, 2, 0, 3, 0, 0, 0,1,0 );
gluLookAt( 6, 2, 0, 3, 0, 0, 0,0,1 );
Camera rotated
towards the +z
gluLookAt( 6, 2, 4,
3, 0, 0, 0,-1,0 );
Inverted up-vector!
R. Mukundan, CSSE, University of Canterbury

Event Processing (Interactive Graphics)
 A graphics application should allow the user to interact with it through keyboard and mouse inputs.
 The program should be able to receive inputs (egs. a key is pressed, mouse button clicked, mouse dragged) or actions (window resized, a time period has elapsed, a display refresh requested) while the application is running. These inputs and actions are called events.
 The program should be able to respond to events by executing certain functions. Such functions are called event handlers or call-back functions.
 GLUT provides an effective event-driven functionality common to all window systems.
R. Mukundan, CSSE, University of Canterbury

User Interaction (Demo)
R. Mukundan, CSSE, University of Canterbury

Event-Driven Programming
All call-back functions must be registered within the program.
Event Handler
Event Handler
Event Handler
Event Dispatcher
Mouse clicked.
Mouse dragged.
A key is pressed.
The window is resized. A menu is selected.
A time period has elapsed
R. Mukundan, CSSE, University of Canterbury
Event Queue
Application
User defined call-back functions

Keyboard Events
 A keyboard event is generated when the user presses a key that represents a printable (ASCII) character.
 The call-back function is registered using glutKeyboardFunc(keyboard);
 The call-back function signature is keyboard(unsigned char key, int x, int y)
key = key pressed
x, y = GLUT coordinates of the mouse position within the
window, at time of key press (rarely used)
R. Mukundan, CSSE, University of Canterbury

Keyboard Event Example
void keyboard(unsigned char key, int x, int y){
switch(key)
case ‘a’: rotn += 5; break; case ‘d’: rotn -= 5; break; case ‘w’: step = 2; break; case ‘x’: step = -2; break;
glutPostRedisplay();
//turn left //turn right //move forward //move backward
//update display
void main( int argc, char **argv)
glutKeyboardFunc(keyboard);
display-refresh event
R. Mukundan, CSSE, University of Canterbury

Special Keyboard Event
Specialkeysrepresentnon-printablecharacters. Egs: Arrow keys, Function keys F1..F12, PageUp, PageDown etc.
Registeredusing glutSpecialFunc(special);  Call-back signature:
special(int key, int x, int y);
where key is one of the following:
 Function keys: GLUT_KEY_F1, … GLUT_KEY_F12
 Arrow keys: GLUT_KEY_UP, GLUT_KEY_DOWN, GLUT_KEY_LEFT, GLUT_KEY_RIGHT
 Other keys: GLUT_KEY_HOME, GLUT_KEY_END, GLUT_KEY_PAGE_UP, GLUT_KEY_PAGE_DOWN, GLUT_KEY_INSERT
x, y : GLUT coordinates of the current mouse position.
R. Mukundan, CSSE, University of Canterbury

Special Keyboard Callback Example
void special(int key, int x, int y)
if(key == GLUT_KEY_F1) glutFullScreen(); else if(key == GLUT_KEY_F2) animate();
else if(key == GLUT_KEY_LEFT) angle -= 5;
else if(key == GLUT_KEY_RIGHT) angle += 5;
glutPostRedisplay();
void main( int argc, char **argv)
glutSpecialFunc(special);
R. Mukundan, CSSE, University of Canterbury

Mouse Event
 A mouse event occurs when a user presses or releases a mouse button inside a window. The call-back function is registered using
glutMouseFunc(mouse);
 The call-back function signature is:
mouse(int button, int state, int x, int y);
Button: The mouse button that is pressed. GLUT_LEFT_BUTTON, GLUT_RIGHT_BUTTON, GLUT_MIDDLE_BUTTON
 State: The state of the button. GLUT_UP, GLUT_DOWN
x, y: GLUT coordinates of the mouse position within the
R. Mukundan, CSSE, University of Canterbury

Mouse Event Example
void mouse(int b, int s, int x, int y)
int xpoint, ypoint;
if(b == GLUT_LEFT_BUTTON && s == GLUT_DOWN) {
xpoint = x;
ypoint = winHeight – y;
drawDot(xpoint, ypoint); }
glutPostRedisplay();
//update display
void main( int argc, char **argv) { …
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMainLoop();
R. Mukundan, CSSE, University of Canterbury

Input Using Mouse Events (Demo)
R. Mukundan, CSSE, University of Canterbury

Mouse Motion Events
 Mouse Motion Event
 Mouse is moved while one or more buttons are pressed. The
call-back function is registered using
glutMotionFunc(motion);
 Mouse Passive Motion Event
 Mouse is moved while no buttons are pressed. The call-back
function is registered using
glutPassiveMotionFunc(passiveMotion);
 Call-back signatures:
motion(int x, int y); passiveMotion(int x, int y);
R. Mukundan, CSSE, University of Canterbury

Display Call-back
Thedisplaycall-back functionisexecutedwheneverthe native windows system decides that the window must be refreshed.
 The window is opened
 The window is re-sized
 An overlapping window is moved etc.
 The call-back function is registered using glutDisplayFunc(display);
 A window redraw event can also be generated by the user at any time by calling the function
glutPostRedisplay()
R. Mukundan, CSSE, University of Canterbury

Window Reshape Event
 The reshape event is triggered when the graphics window is resized. It is also triggered immediately before a window’s first display call-back. The call-back is registered using
glutReshapeFunc(reshape);
 The call-back signature is
reshape(int width, int height);
 Example:
void reshape(int width, int height)
float aspectCurr = (float)width/(float)height;
if(aspectCurr > aspectReqd)
glViewport(0, 0, height*as

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com