Introduction to Computer GraphicsLecture 4OpenGL IntroAssignment 1
X-Axis ShearShear along x axis (What is the matrix for y axis shear?)xyxy
X-Axis ShearShear along x axis (What is the matrix for y axis shear?)xyxy
Reflect About X Axisxx
Reflect About X AxisWhat is the matrix for reflect about Y axis?xx
OpenGL Design GoalsSGIs design goals for OpenGL:High-performance (hardware-accelerated) graphics APISome hardware independence Natural, terse API with some built-in extensibilityOpenGL has become a standard because:It doesnt try to do too muchOnly renders the image, doesnt manage windows, etc.No high-level animation, modeling, sound (!), etc.It does enoughUseful rendering effects + high performanceIt is promoted by SGI (& Microsoft, half-heartedly)
OpenGL is Not AloneGLUTThe OpenGL Utility ToolkitInterface to windowing system and OSProvides handy shape primitives (torus, teapot, cube)FLTKFast Light ToolkitGraphical User Interface (GUI) builderBoostAdditional libraries that work with STL
The Big PictureWho gets control of the main control loop?FLTK the code that waits for user input and processes itMust be responsive to user do as I sayGLUT the code that controls the window and refreshMust be responsive to windowing system and OSOpenGL the code that controls what is drawnMust be responsive to the program that specifies where objects are located. If something moves, I want to see it.
The Big PictureWho gets control of the main control loop?Answer: FLTKWell try to hide the details from you for nowBut be aware of the conflict that existsFLTK must be aware of GLUT and OpenGL state at all timesMust give code compute cycles when neededWell discuss OpenGL as if it were standalone
OpenGLSimple Example no color or lights or texturesAn array of 100 vertices (x,y,z)double verts[100][3]An array of 30 triangles (made of three verts) int tri[30][3]An array of 10 matrix transformationsdouble trans[10][16]
OpenGLMain LoopWhile (1) doDetermine the 10 matrix transformationsMultiply transformations together (composite them)Apply resulting transformation to each triangleRender each triangle
Determine the 10 matrix transformationsWe know how to build the matrices by hand orUse the GL implementationsglScale (theta degrees about (u, v, w) axis)glRotate (x, y, and z amounts)glTranslate (x, y, and z amounts)
Multiply transformations together (composite them)We know how to do matrix multiplication orUse the GL implementationsEach call to glTranslate, glRotate, glScale. automatically multiplies new transformation by product of previous transformations, MODELVIEW matrixRemember order of matrix multiplication and why this is a good way to do things
Apply resulting transformation by each triangleFor each triangle, access its three pointsglBegin (GL_TRIANGLES)glVertex (point1); glVertex(point2); glVertex(point3)glEnd();Multiply each point by MODELVIEW matrixFeed the three transformed points to a GL function that projects 3-D triangles to 2-D screen spacePROJECTION matrix defines virtual cameraAspect ratio, clipping planes, camera type
RenderGL rendererGiven the 2-D coordinates of triangle verticesOpenGL determines which pixels to illuminateIt repeats this for all triangles
OpenGL Main LoopRendering is a pipelined processObject CoordinatesEye CoordinatesClip CoordinatesDevice CoordinatesWindow CoordinatesMODELVIEWmatrixPROJECTIONmatrixPerspective divisionViewporttransformation
Immediate ModeThis example demonstrates GLs Immediate ModeEvery triangle is transformed immediately to screen spaceIt is then thrown awayIf you repeat the same triangles each frame, use a Display Listdisplay list caches vertices to optimize pipeline
Adding Extra FeaturesGL is a state machineThere are many variables stored as globalsWhat color to use glColor()All subsequent vertices will be assigned that colorWhat rendering mode (wireframe or solid)All subsequent polygons will be rendered that wayWhat matrix is active (MODELVIEW or PROJECTION) glMatrixMode()All subsequent matrix commands will affect that matrix
Adding Extra FeaturesSetting different transformations to different trianglesNot all triangles should be affected by same transformation matrixthink of limbs of an armYou can change a matrix at willglMatrixMode (GL_MODELVIEW)glLoadIdentity ();Or you can store previous results for future useglPushMatrix() and glPopMatrix()Puts a copy of current matrix on top of stack (or deletes top matrix)
WireframeWireframe with depth-cueing
Wireframe with antialiasingFlat-shaded polygons
Smooth-shaded polygonsTexture maps and shadows
Close-upWith Fog
Modeling TransformationsglTranslate (x, y, z)Post-multiplies the current matrix by a matrix that moves the object by the given x-, y-, and z-valuesglRotate (theta, x, y, z)Post-multiplies the current matrix by a matrix that rotates the object in a counterclockwise direction about the ray from the origin through the point (x, y, z)
Modeling TransformationsglScale (x, y, z)Post-multiplies the current matrix by a matrix that stretches, shrinks, or reflects an object along the axes.
Matrix MultiplcationsCertain commands affect the current matrix in OpenGLglMatrixMode() sets the current matrixglLoadIdentity() replaces the current matrix with an identity matrixglTranslate() postmultiplies the current matrix with a translation matrixgluPerspective() postmultiplies the current matrix with a perspective projection matrixIt is important that you understand the order in which OpenGL concatenates matrices
Matrix Operations In OpenGLIn OpenGL:Vertices are multiplied by the MODELVIEW matrixThe resulting vertices are multiplied by the projection matrixExample: Suppose you want to scale an object, translate it, apply a lookat transformation, and view it under perspective projection. What order should you make calls?
Matrix Operations in OpenGLProblem: scale an object, translate it, apply a lookat transformation, and view it under perspectiveA correct code fragment:glMatrixMode(GL_PERSPECTIVE);glLoadIdentity();gluPerspective();glMatrixMode(GL_MODELVIEW);glLoadIdentity();gluLookAt();glTranslate();glScale();/* Draw the object...*/
Matrix Operations in OpenGLProblem: scale an object, translate it, apply a lookat transformation, and view it under perspectiveAn incorrect code fragment:glMatrixMode(GL_PERSPECTIVE);glLoadIdentity();glTranslate();glScale();gluPerspective();glMatrixMode(GL_MODELVIEW);glLoadIdentity();gluLookAt();/* Draw the object...*/
Multiplication OrderglMatrixMode (MODELVIEW);glLoadIdentity();glMultMatrix(N);glMultMatrix(M);glMultMatrix(L);glBegin(POINTS);glVertex3f(v);glEnd();Modelview matrix successively contains:I(dentity), N, NM, NML
The transformed vertex is:NMLv = N(M(Lv))
Manipulating Matrix StacksObservation: Certain model transformations are shared among many modelsWe want to avoid continuously reloading the same sequence of transformationsglPushMatrix ( ) push all matrices in current stack down one level and copy topmost matrix of stackglPopMatrix ( )pop the top matrix off the stack
OpenGL: ConventionsFunctions in OpenGL start with glMost functions just gl (e.g., glColor()) Functions starting with glu are utility functions (e.g., gluLookAt())Functions starting with glx are for interfacing with the X Windows system (e.g., in gfx.c)
OpenGL: ConventionsFunction names indicate argument type and numberFunctions ending with f take floatsFunctions ending with i take intsFunctions ending with b take bytesFunctions ending with ub take unsigned bytesFunctions that end with v take an array.ExamplesglColor3f() takes 3 floatsglColor4fv() takes an array of 4 floats
OpenGL: ConventionsVariables written in CAPITAL lettersExample: GLUT_SINGLE, GLUT_RGBusually constantsuse the bitwise or command (x | y) to combine constants
OpenGL: Simple UseOpen a window and attach OpenGL to itSet projection parameters (e.g., field of view)Setup lighting, if anyMain rendering loopSet camera pose with gluLookAt() Camera position specified in world coordinatesRender polygons of modelSimplest case: vertices of polygons in world coordinates
OpenGL: Simple UseOpen a window and attach OpenGL to itglutCreateWindow() or FLTK window method
OpenGL: Perspective ProjectionSet projection parameters (e.g., field of view) Typically, we use a perspective projectionDistant objects appear smaller than near objects Vanishing point at center of screenDefined by a view frustum (draw it)Other projections: orthographic, isometric
Setting up CameraglMatrixMode(GL_MODELVIEW);glLoadIdentity();gluLookAt(eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);eye[XYZ]: camera position in world coordinateslook[XYZ]: a point centered in cameras viewup[XYZ]: a vector defining the cameras verticalCreates a matrix that transforms points in world coordinates to camera coordinatesCamera at originLooking down -Z axisUp vector aligned with Y axis
OpenGL: Perspective ProjectionIn OpenGL: Projections implemented by projection matrixgluPerspective() creates a perspective projection matrix:glSetMatrix(GL_PROJECTION);glLoadIdentity(); //load an identity matrixgluPerspective(vfov, aspect, near, far);Parameters to gluPerspective():vfov: vertical field of viewaspect: window width/heightnear, far: distance to near & far clipping planes
OpenGL: LightingSetup lighting, if anySimplest option: change the current color between polygons or verticesglColor() sets the current colorOr OpenGL provides a simple lighting model:Set parameters for light(s)Intensity, position, direction & falloff (if applicable) Set material parameters to describe how light reflects from the surfaceWont go into details now; check the red book if interested
OpenGL: Specifying GeometryGeometry in OpenGL consists of a list of vertices in between calls to glBegin() and glEnd()A simple example: telling GL to render a triangleglBegin(GL_POLYGON);glVertex3f(x1, y1, z1);glVertex3f(x2, y2, z2);glVertex3f(x3, y3, z3);glEnd();Usage: glBegin(geomtype) where geomtype is:Points, lines, polygons, triangles, quadrilaterals, etc...
Primitive TypesGL_POINTSGL_LINE{S | _STRIP | _LOOP}GL_TRIANGLE{S | _STRIP | _FAN}GL_QUAD{S | _STRIP}GL_POLYGON
GL_POLYGONList of vertices defines polygon edgesPolygon must be convex
Non-planar PolygonsImagine polygon with non-planar verticesSome perspectives will be rendered as concave polygonsThese concave polygons may not rasterize correctly
OpenGL: More ExamplesExample: GL supports quadrilaterals:glBegin(GL_QUADS);glVertex3f(-1, 1, 0); glVertex3f(-1, -1, 0);glVertex3f(1, -1, 0);glVertex3f(1, 1, 0);glEnd();This type of operation is called immediate-mode rendering; each command happens immediately
OpenGL: Drawing TrianglesYou can draw multiple triangles between glBegin(GL_TRIANGLES) and glEnd():float v1[3], v2[3], v3[3], v4[3];...glBegin(GL_TRIANGLES);glVertex3fv(v1); glVertex3fv(v2); glVertex3fv(v3);glVertex3fv(v1); glVertex3fv(v3); glVertex3fv(v4);glEnd();Each set of 3 vertices forms a triangleWhat do the triangles drawn above look like?How much redundant computation is happening?
OpenGL: Triangle StripsAn OpenGL triangle strip primitive reduces this redundancy by sharing vertices:glBegin(GL_TRIANGLE_STRIP);glVertex3fv(v0);glVertex3fv(v1);glVertex3fv(v2);glVertex3fv(v3);glVertex3fv(v4);glVertex3fv(v5);glEnd();triangle 0 is v0, v1, v2triangle 1 is v2, v1, v3 (why not v1, v2, v3?)triangle 2 is v2, v3, v4triangle 3 is v4, v3, v5 (again, not v3, v4, v5)v0v2v1v3v4v5
OpenGL: More ExamplesExample: GL supports quadrilaterals:glBegin(GL_QUADS);glVertex3f(-1, 1, 0); glVertex3f(-1, -1, 0);glVertex3f(1, -1, 0);glVertex3f(1, 1, 0);glEnd();This type of operation is called immediate-mode rendering; each command happens immediately
OpenGL: Front/Back RenderingEach polygon has two sides, front and backOpenGL can render the two differentlyThe ordering of vertices in the list determines which is the front side:When looking at the front side, the vertices go counterclockwiseThis is basically the right-hand ruleNote that this still holds after perspective projection
OpenGL: Drawing TrianglesYou can draw multiple triangles between glBegin(GL_TRIANGLES) and glEnd():float v1[3], v2[3], v3[3], v4[3];...glBegin(GL_TRIANGLES);glVertex3fv(v1); glVertex3fv(v2); glVertex3fv(v3);glVertex3fv(v1); glVertex3fv(v3); glVertex3fv(v4);glEnd();Each set of 3 vertices forms a triangleWhat do the triangles drawn above look like?How much redundant computation is happening?
OpenGL: Triangle StripsAn OpenGL triangle strip primitive reduces this redundancy by sharing vertices:glBegin(GL_TRIANGLE_STRIP);glVertex3fv(v0);glVertex3fv(v1);glVertex3fv(v2);glVertex3fv(v3);glVertex3fv(v4);glVertex3fv(v5);glEnd();triangle 0 is v0, v1, v2triangle 1 is v2, v1, v3 (why not v1, v2, v3?)triangle 2 is v2, v3, v4triangle 3 is v4, v3, v5 (again, not v3, v4, v5)v0v2v1v3v4v5
Double BufferingAvoids displaying partially rendered frame bufferOpenGL generates one raster image while another raster image is displayed on monitorglxSwapBuffers (Display *dpy, Window, w)glutSwapBuffers (void)
Top Related