CAP 4703CAP 4703Computer Graphic Computer Graphic
MethodsMethodsProf. Roy LevowProf. Roy Levow
Lecture 2Lecture 2
2-Dimensional Drawing2-Dimensional Drawingwith OpenGLwith OpenGL
Two-dimensional objects are a Two-dimensional objects are a special case of three-dimensional special case of three-dimensional figuresfigures
The drawing is limited (by the The drawing is limited (by the programmer) to a planeprogrammer) to a plane
Viewing is normally an orthogonal Viewing is normally an orthogonal view, perpendicular to the drawing view, perpendicular to the drawing planeplane
Sierpinski GasketSierpinski Gasket
A simple but interesting exampleA simple but interesting example Start with any triangleStart with any triangle1.1. Pick an internal point at randomPick an internal point at random2.2. Pick a vertex at randomPick a vertex at random3.3. Find the midpoint between 1 and 2Find the midpoint between 1 and 24.4. Display this pointDisplay this point5.5. Replace initial point with this oneReplace initial point with this one6.6. Repeat from step 2Repeat from step 2
Sierpinski Gasket ConstructionSierpinski Gasket Construction
OpenGL Program forOpenGL Program forSierpinski GasketSierpinski Gasket
main(){initialize_the_system();for (some_number_of_points){
pt = generate_a_point();display_the_point(pt);
}cleanup();return 0;
}
Points or VerticesPoints or Vertices
Points are represented by vectors Points are represented by vectors with an entry for each coordinatewith an entry for each coordinate
p = (x, y, z) in 3 dimensionsp = (x, y, z) in 3 dimensions p = (x, y, 0) gives 2 dimensions by p = (x, y, 0) gives 2 dimensions by
always setting z to 0always setting z to 0 OpenGL allows up to 4 dimensionsOpenGL allows up to 4 dimensions Internal representation is always the Internal representation is always the
samesame
OpenGL VerticesOpenGL Vertices
Vertex creating functions have Vertex creating functions have general namegeneral name
glVertex*glVertex* The suffix is 2 or 3 charactersThe suffix is 2 or 3 characters
– Number of dimensions: 2, 3, or 4Number of dimensions: 2, 3, or 4– Data type: i = integer, f = float, Data type: i = integer, f = float,
d = doubled = double
– Optional v if pointerOptional v if pointer
Underlying RepresentationUnderlying Representation
OpenGL data types are defined in OpenGL data types are defined in header fileheader file
#define GLfloat float#define GLfloat float
so a header might look likeso a header might look like
glVertex2i(GLint xi, GLint yi)glVertex2i(GLint xi, GLint yi)
oror
glVertex3f(GLfloat xf, GLfloat yf,glVertex3f(GLfloat xf, GLfloat yf,
GLfloat zf)GLfloat zf)
Representation (cont.)Representation (cont.)
For the vector formFor the vector formGLfloat vertex[3];GLfloat vertex[3];
and then useand then use
glVertex3fv(vertex);glVertex3fv(vertex);
Defining Geometric ObjectsDefining Geometric Objects
Objects are defined by collections of Objects are defined by collections of point constructors bounded by calls point constructors bounded by calls to glBegin and glEndto glBegin and glEnd
A line is defined byA line is defined by
glBegin(GL_LINES);glBegin(GL_LINES);
glVertex2f(x1, y1);glVertex2f(x1, y1);
glVertex2f(x2, y2);glVertex2f(x2, y2);
glEnd();glEnd();
OpenGL Code forOpenGL Code for Sierpinski Gasket Sierpinski Gasket
See p. 41 of textSee p. 41 of text
Code leaves many open questions Code leaves many open questions by using default valuesby using default values
1.1. colorscolors2.2. image positionimage position3.3. sizesize4.4. clipping?clipping?5.5. persistencepersistence
A Resulting ImageA Resulting Image
Coordinate SystemCoordinate System
Early systems depended on specific Early systems depended on specific device mappingdevice mapping
Device-independent graphics broke Device-independent graphics broke linklink
Use application or problem Use application or problem coordinate system to define imagecoordinate system to define image
Use device coordinates, raster Use device coordinates, raster coordinates, screen coordinates for coordinates, screen coordinates for devicedevice
CoordinatesCoordinates
Application coordinates can be Application coordinates can be integer or real and multi-dimensionalinteger or real and multi-dimensional
Screen or raster coordinates are Screen or raster coordinates are always integer and essentially 2-always integer and essentially 2-dimensionaldimensional
Graphics program maps application Graphics program maps application coordinates onto device coordinatescoordinates onto device coordinates
App to Device MappingApp to Device Mapping
Classes for OpenGL FunctionsClasses for OpenGL Functions
1.1. Primitives – draw points, line Primitives – draw points, line segments, polygons, text, curves, segments, polygons, text, curves, surfacessurfaces
2.2. Attributes – specify display Attributes – specify display characteristics of objects: color, fill, characteristics of objects: color, fill, line width, fontline width, font
3.3. Viewing – determine aspects of Viewing – determine aspects of view: position and angle of camera, view: position and angle of camera, view port size, …view port size, …
Function Classes (cont)Function Classes (cont)
4.4. Transformations – change Transformations – change appearance or characteristics of appearance or characteristics of objects: rotate, scale, translateobjects: rotate, scale, translate
5.5. Input – handle keyboard, mouse, Input – handle keyboard, mouse, etc.etc.
6.6. Control – communicate with window Control – communicate with window systemsystem
7.7. Inquiry – get display information: Inquiry – get display information: size, raster value, …size, raster value, …
OpenGL InterfaceOpenGL Interface
Graphics Utility Interface (GLU)Graphics Utility Interface (GLU)– Creates common objects like spheresCreates common objects like spheres
GL Utility Toolkit (GLUT)GL Utility Toolkit (GLUT)– Provides generic interface to window Provides generic interface to window
systemsystem GLX for Unix/Linux and GLX for Unix/Linux and
wgl for Microsoft Windowswgl for Microsoft Windows– provide low-level glue to window systemprovide low-level glue to window system
Library OrganizationLibrary Organization
Using LibrariesUsing Libraries
Header filesHeader files– #include <GL/glut.h>#include <GL/glut.h>– #include <GL/gl.h>#include <GL/gl.h>– #include <GL/glu.h>#include <GL/glu.h>
On some systems the GL/ is not usedOn some systems the GL/ is not used
PrimitivesPrimitives
OpenGL supports both geometric OpenGL supports both geometric primitives and raster primitivesprimitives and raster primitives
Geometric PrimitivesGeometric Primitives
Points = GL_POINTSPoints = GL_POINTS– vertex displayed with size >= 1 pixelvertex displayed with size >= 1 pixel
Line segments = GL_LINESLine segments = GL_LINES– defined by pairs of vertices as endpoints defined by pairs of vertices as endpoints
of segmentsof segments Polygons = GL_LINE_STRIPE or Polygons = GL_LINE_STRIPE or
GL_LINE_LOOPGL_LINE_LOOP– Loop is closed, stripe is notLoop is closed, stripe is not
Primitive ExamplesPrimitive Examples
Properties of PolygonsProperties of Polygons
Defined by line loop borderDefined by line loop border Simple if no edges crossSimple if no edges cross Convex if every line Convex if every line
segment connecting pair segment connecting pair of points on of points on boundary or boundary or inside lies inside lies completely completely insideinside
Polygon Types in OpenGLPolygon Types in OpenGL
Polygons are either filled regions Polygons are either filled regions (default) or boundaries(default) or boundaries
Set with glPolygonModeSet with glPolygonMode To get polygon with boundary must To get polygon with boundary must
draw twice, once as filled and once draw twice, once as filled and once as boundary or line loopas boundary or line loop
Special PolygonsSpecial Polygons
GL_TRIANGLES, GL_QUADSGL_TRIANGLES, GL_QUADS– Groups of 3 or 4 points are grouped as Groups of 3 or 4 points are grouped as
triangles or quadrilateralstriangles or quadrilaterals
Special PolygonsSpecial Polygons
GL_TRIANGLE_STRIPE, GL_TRIANGLE_STRIPE, GL_QUAD_STRIPE, GL_TRIANGEL_FANGL_QUAD_STRIPE, GL_TRIANGEL_FAN– Contiguous stripe or fan of triangles or Contiguous stripe or fan of triangles or
quadrilateralsquadrilaterals
Drawing a SphereDrawing a Sphere
Draw great circlesDraw great circles Fill between latitudes Fill between latitudes
with quad stripswith quad strips Fill caps with Fill caps with
triangle fanstriangle fans Code on p.52Code on p.52
TextText
May be raster – from bit mapMay be raster – from bit map– FastFast– Does not scale wellDoes not scale well– Poor in rotation other than 90Poor in rotation other than 90oo
Vector – from drawn curvesVector – from drawn curves– Slow to drawSlow to draw– Scales, rotates, etc. wellScales, rotates, etc. well
Raster textRaster text
ColorColor
The physiology of vision leads to 3-The physiology of vision leads to 3-color theorycolor theory
Any color can be produced by a Any color can be produced by a combination of red, green, and blue combination of red, green, and blue at intensities that produce the same at intensities that produce the same response in the cones as the true response in the cones as the true colorcolor
Colors in OpenGLColors in OpenGL
Colors are stored using 4 attributes, Colors are stored using 4 attributes, RGBARGBA
A = Alpha channelA = Alpha channel– Controls opacity or transparencyControls opacity or transparency
Color values can be integers in range Color values can be integers in range from 0 to max component valuefrom 0 to max component value– 0 – 255 for 24-bit color0 – 255 for 24-bit color
Real numbers between 0.0 and 1.0Real numbers between 0.0 and 1.0
Colors in OpenGL (cont)Colors in OpenGL (cont)
Colors are set with glColor* functionsColors are set with glColor* functions– * is two characters, nt* is two characters, nt
n = 3 or 4 color valuesn = 3 or 4 color valuest = date type: i, f, etc.t = date type: i, f, etc.
Clearing Frame BufferClearing Frame Buffer
To get predictable results a program To get predictable results a program must first clear the frame buffermust first clear the frame buffer
glClearColor(1.0, 1.0, 1.0, 1.0)glClearColor(1.0, 1.0, 1.0, 1.0)– sets color to whitesets color to white
Indexed ColorIndexed Color
OpenGL also supports indexed colorOpenGL also supports indexed color– Saves space when only a limited Saves space when only a limited
number of distince colors are usednumber of distince colors are used
Indexed Color (cont)Indexed Color (cont)
Set color in table withSet color in table with
glutSetColor(int color, GLfloat glutSetColor(int color, GLfloat red,red,
GLfloat blue, GLfloat green)GLfloat blue, GLfloat green) Access color in table withAccess color in table with
glIndexi(element)glIndexi(element)
ViewingViewing
Based on synthetic camera modelBased on synthetic camera model If nothing is specified, there are If nothing is specified, there are
default viewing parametersdefault viewing parameters– Rarely usedRarely used– Would force us to fit model world to Would force us to fit model world to
cameracamera Prefer flexibility of setting viewing Prefer flexibility of setting viewing
parametersparameters
Two-Dimensional ViewingTwo-Dimensional Viewing
Selected rectangle from 2-Selected rectangle from 2-dimensional world is displayeddimensional world is displayed
Called viewing rectangle or clipping Called viewing rectangle or clipping rectanglerectangle
Viewing VolumeViewing Volume
2-dimensional viewing is special case 2-dimensional viewing is special case of 3-dimensional viewingof 3-dimensional viewing– viewing volumeviewing volume
Default is Default is
2 x 2 x 2 2 x 2 x 2
cube centered cube centered
at at (0,0,0)(0,0,0)
Orthographic ProjectionOrthographic Projection
Projects point (x,y,z) onto (x,y,0)Projects point (x,y,z) onto (x,y,0) View is perpendicular to plane x=0View is perpendicular to plane x=0 Set viewing rectagle withSet viewing rectagle with
void glOrtho(GLdouble left, void glOrtho(GLdouble left,
GLdouble right, GLdouble right,
GLdouble bottom,GLdouble bottom,
GLdouble top)GLdouble top)
Matrix ModesMatrix Modes
Graphic pipelines perform matrix Graphic pipelines perform matrix transformations on images at each transformations on images at each stagestage
Most important matrices areMost important matrices are– model-viewmodel-view– projectionprojection
State includes bothState includes both
Manipulating Mode MatricesManipulating Mode Matrices
Matrix mode operations operate on Matrix mode operations operate on matrix for currently selected modematrix for currently selected mode– Model-view is defaultModel-view is default
Mode is set withMode is set withglMatrixMode(mode)glMatrixMode(mode)mode = GL_PROJECTION, GL_MODELVIEW, mode = GL_PROJECTION, GL_MODELVIEW,
etc.etc. Always return to model-view to Always return to model-view to
insure consistencyinsure consistency
Control FunctionsControl Functions
Depend on particular window systemDepend on particular window system GLUT provides standard set of basic GLUT provides standard set of basic
operationsoperations– We will consider only theseWe will consider only these
Window ControlWindow Control
Operations only on display window Operations only on display window for the programfor the program
Initialization – glutInitInitialization – glutInit Creation – glutCreateWindowCreation – glutCreateWindow Display mode –Display mode – glutInitDisplayModeglutInitDisplayMode
– RGB or indexedRGB or indexed– hidden-surface removalhidden-surface removal– singer or double bufferingsinger or double buffering
Example CodeExample Code
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(480, 480);
glutWindowPosition(0, 0);
glutCreateWindow(“sample");
Aspect Ratio and ViewportsAspect Ratio and Viewports
Ratio of width to length is aspect Ratio of width to length is aspect ratioratio
If aspect ratio of viewing rectangle If aspect ratio of viewing rectangle and window differ, image will be and window differ, image will be stretched and distortedstretched and distorted
Viewport defines region of screen in Viewport defines region of screen in which to display imagewhich to display image– Can eliminate distortionCan eliminate distortion
DistortionDistortion
ViewportViewport
Set viewport withSet viewport withvoid glViewport(GLint x, GLint y,void glViewport(GLint x, GLint y,
GLsizei w, GLsizei h)GLsizei w, GLsizei h)
GLUT Main LoopGLUT Main Loop
If we simply run an OpenGL program If we simply run an OpenGL program it will display the image and exitit will display the image and exit– may not allow time to see itmay not allow time to see it– could sleep program to keep window could sleep program to keep window
open but this is limited solutionopen but this is limited solution GLUT provides controls to avoid thisGLUT provides controls to avoid this Keep program running waiting for Keep program running waiting for
eventeventvoid glutMainLoop(void)void glutMainLoop(void)
Glut DisplayGlut Display
To display an image, code a function To display an image, code a function to create the image and have GLUT to create the image and have GLUT call itcall it
image drawing function takes no image drawing function takes no arguments and returns no resultarguments and returns no result– Any parameters must be passed through Any parameters must be passed through
global variablesglobal variables
void glutDisplayFunc(void (*func)(void))void glutDisplayFunc(void (*func)(void))
Simple Main ProgramSimple Main Program
#include <GL/glut.h>void main(int argc, char **argv){ glutInit(&argc, argv); glutInitDisplayMode
(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(500, 500); glutWindowPosition(0, 0);
Simple Main Program (cont)Simple Main Program (cont)
glutCreateWindow(“My Image"); glutDisplayFunc(display);
myinit(); glutMainLoop();}
Program StructureProgram Structure
Key componentsKey components– initializationinitialization– display callback functiondisplay callback function– mainmain
Gasket ProgramGasket Program..\code\gasket.c..\code\gasket.c – 2-d – 2-d..\code\gasket2.c..\code\gasket2.c – 3-d with colors – 3-d with colors../code/gasket3.c../code/gasket3.c – 3-d with polygons – 3-d with polygons
Hidden Surface RemovalHidden Surface Removal
Z-buffer algorithmZ-buffer algorithm Z coordinate determines depthZ coordinate determines depth Point nearer camera obscures one Point nearer camera obscures one
with greater depthwith greater depth StepsSteps
– Init with GLUT_DEPTHInit with GLUT_DEPTH– glEnable(GL_DEPTH_TESTglEnable(GL_DEPTH_TEST
can also disablecan also disable
– clear before redrawingclear before redrawing
Sample HSR ProgramSample HSR Program
void display(){
glClear(GL_COLOR_BUFFER_BIT |GL_DEPTH_BUFFER_BIT)
tetrahedron(n)glFlush();
}