Você está na página 1de 39

Computer Graphics

Dr. Julian Guerrero


August-December 2010
Computer Graphics
Topic 1.2
Graphics Libraries: Definition and visualization
of basic geometric objects, events, color,
lighting and texture
Images

Elements that make up a picture?


Output primitives
Points, lines, polylines, text, filled regions, raster
elements (pixels)
Vector vs. Raster images
Each has attributes: color, width, intensity…

Many images are eventually are displayed as


raster images
Vector Images
 Polylines, text, filled regions
Images created with these primitives are defined by a
series of instructions that place each primitive and
specify their attributes
 Different primitives may have different attributes

Advantages
 May be coded in small programs, saves space

Disadvantages
 Limited flexibility for use, as only attributes can be used as
control parameters
Elementary Drawing Tools

 We can draw using primitives


 For example:
 SetPixel(x, y, color)
 Draw a point* at (x,y) using color
 Alternate names: putPixel(), SetPixel(),
drawPoint()
 line(x1, x2)
 Draw a straight line between point x1 and x2
 drawLine(), Line()

* A point does not necessarily mean a pixel


Elementary Drawing Tools

Alternate approach: Introduce the concept


of current position (cp) as in a pen plotter
Elementary drawing functions;
moveTo(x,y)
lineTo(x,y)

Must keep track of cp – update it as we move


and draw
Elementary Drawing Tools

These commands draw an aligned square


Aligned: Each side is parallel to one of the axes

moveto(1,1) 2
lineto(2,1)
lineto(2,2) 1
lineto(1,2)
lineto(1,1)
moveto(0,0) (0,0) 1 2
Elementary Drawing Tools

 For any given system, an enthusiastic


programmer (e.g. you) can develop a whole
toolkit of more complex functions using these
elementary tools
Graphics applications can be written using these
Problem?
 Each graphic display uses different basic commands, and
has a different collection of tools for producing the
corresponding graphic primitives
 Porting the program (converting it from one environment
to another) can become very time-consuming and difficult
Raster Images
 Made up of many cells called pixels (picture elements)

 Normally, the eye doesn’t see the individual cells

 Pixels are stored in an array or matrix, called pixel map


or bitmap
 The size of the matrix per unit length defines the resolution of the
bitmap

 Each pixel has an intensity value, which defines the


shades of gray or color (pixel depth)
Raster Images
 Advantages
Easily stored and accessed in computers
Discrete representation of data
Fixed (at times large) size

 Disadvantages
“Pixelation”
Pixels are too large to represent the smallest features
in the image
Curves are represented as jagged, discontinuous
lines
Questions?
So, what do we need to start drawing?

 Environment that allows us to write and execute


programs
Must include hardware to display images

 Library of software tools that perform actual


drawing of graphics primitives
Example: OpenGL
 SW tool for generating 2D and 3D graphics
 Standard, cross platform (device independent)
specification
 Application program interface (API)
Graphics API

Interface between the application program


and hardware
Provides instructions and primitives to use, in
this case, graphics libraries
API takes care of lower levels of communication
with HW

Application Graphics
Hardware
Program Library (API)
Graphics Architectures: Pipeline

 Display process
Refresh the display continuously

 Pipeline renders (rasterization-based) a 2D


scene based on a 3D representation of the
objects in the scene, properties of these objects,
and the order in which instructions are executed

INPUT OUTPUT
Instruction Instruction Instruction
(3D geometry) 1 2 3 (pixels)
Device Independent Programming
 When the same code can be compiled and run on a
variety of graphics environments and produce nearly
identical graphical output
 Porting is now simply installing appropriate libraries on a new
machine

 OpenGL is open source (you can contribute too!) and is freely


available
 Large number of industrial companies use OpenGL

 OpenGL is most powerful when drawing images of complex 3D


scenes, but works well for 2D drawing too
 In this manner, provides a unified approach to graphics
Main OpenGL Libraries
 Basic GL: The fundamental OpenGL library. It provides
the functions that are a permanent part of OpenGL.
Functions start with “GL.”

 GLUT: GL Utility Toolkit. Used for opening windows,


developing and managing menus, managing events.

 GLU: GL Utility Library. High level routines to handle


certain matrix operations, drawing of quadric surfaces
(spheres, cylinders), decomposition of non-convex, non-
simple polygons.
Windows-Based Programming

 Modern graphics systems are windows-based,


which manage multiple overlapping windows.

 In addition to generating input primitives a


program can process, using a pointing device a
user can:
Move windows
Resize windows
i.e. generate events
Event-Driven Programming
 Windows-based programs are mostly event-
driven
Respond to a mouse click, a mouse move, keyboard
input, resizing a window, etc.
Operating system automatically manages an event
queue
 Keeps track which events occurred
 Keeps track of the order in which they occurred

 Event-driven program
Programmer writes callback functions, to be executed
(called) when a certain event occurs
Upon completion, application resumes where it left off
Event-Driven Programming
 This is how OpenGL functions

 Our program should contain callback functions


for each type of event, not for all events
One function for a keyboard stroke, not a callback
for when “a” is pressed

 Event-driven is opposite of sequential


Sequential: do this, then do that, then…
Event-driven: loop, wait, until something happens
Obviously, can be some overlap
Registering Callback Functions
 We must associate a type of event with a specific
programmer-defined function, the run main loop
(glutMainLoop())

 Examples in OpenGL (GLUT):


 glutDisplayFunc(myDisplay). When the system determines
that a screen window should be redrawn, it issues a redraw
event.
 When first opened, when window is exposed..

 glutReshapeFunc(myReshape). Event from when a window is


reshaped.

 glutMouseFunction(myMouse). Related to events generated


when mouse buttons are pushed.
Registering Callback Functions
 Other examples in OpenGL:
 glutMotionFunc(myMotionFunc). Generates an event
when the mouse is moved with a button pressed.

 glutPassiveMotionFunc(…). Generates an event


when the mouse is moved (e.g. enters a windows) when
no buttons are pressed.

 glutKeyboardFunc(myKeyboard). This registers the


function myKeyboard() with the event of pressing and
releasing some key on the keyboard. Also, x and y
coordinates of mouse at the time of the event are also
registered.
Basic Structure of OpenGL Program
#includes

init_function(…) {…}

display_callback(…) {
// Drawing happens here
}

keyboard_callback(…) {…}

other_callback(…) {…}

main(…) {
init_function(…)

// Register callbacks

main_loop()
}
Initialization

 Every (graphics) program begins with some


initialization
Establish desired display mode
Set up coordinate system
 Coordinates measured in pixels
 a) Display switched to graphics mode
 b), c) Screen windows for graphics
Initialization - Opening a Window
 OpenGL does NOT provide window control on specific systems
 Device independent, right?
 DOES provide basic commands to open a window on any system
 glutInit(&argc, argv) - Initializes toolkit using standard
arguments for passing command line information.
 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB) -
Specifies how the display should be initialized. In this case, single buffer
using RGB color format (note “or” function).
 glutInitWindowSize(640, 480) - Specifies window size, in
pixels.
 glutInitWindowPosition(100, 150) - Specifies that
window’s upper left corner should be 100 pixels from the left edge and
150 down from the top.
 glutCreateWindow(“Name”) - Opens and displays the
window on-screen, with the title “Name.”
Basic Graphic Primitives in OpenGL
 All drawing functions are placed in the callback
associated with a draw or redraw event

 Coordinate system must be established


 In example: 640 x 480, (0 to 639, 0 to 479)

(0,479)
Name

(0,0) (639,0)
x
Basic Graphic Primitives in OpenGL
 Recall graphic primitives
 Points, lines, polylines, polygons…
 Most of these are defined by vertices (corners)

 In OpenGL, pass a list of vertices to draw these primitives


 First, call function glBegin()
 List vertices
 Then call function glEnd()

glBegin(GL_POINTS); // draw individual points


glVertex2i(100, 50); // the points
glVertex2i(100, 130);
glVertex2i(150, 130);
glEnd();
Basic Graphic Primitives in OpenGL
 Constants built into OpenGL
 GL_POINTS
 GL_LINES
 GL_POLYGON
…

 Many functions have variations


 glVertex2i(), glColor3f()

glVertex2i(…)
type of
argument
gl
basic number of
library
command arguments
OpenGL Data Types
 Specific data types defined for internal OpenGL functions
 Variations in data types exist between systems
 e.g. 16 bit or 32 bit integers
 e.g. no standard size for float or double

Suffix Data Type Typical C++ Type OpenGL Type Name


b 8 bit integer signed char GLbyte
s 16 bit integer short GLshort
i 32 bit integer int or long GLint, GLsizei
f 32 bit floating point float GLfloat, GLclampf
d 64 bit floating point double GLdouble, GLclampd
ub 8 bit unsigned number unsigned char GLubyte,GLboolean
us 16 bit unsigned number unsigned short GLushort
ui 32 bit unsigned number unsigned int/long GLuint, GLenum, GLbitfield
OpenGL State Variables - Attributes
 Current point size
 glPointSize(float)
 e.g. float = 3.0, point is square with 3 pixels on a side

 Current color of drawing


 glColor3f(red, green, blue)
 Background color set using:
 glClearColor(red, green, blue, alpha)
 Call glClear(GL_COLOR_BUFFER_BIT) to clear entire window

 Current screen window size

…
Line Drawings
 Simple OpenGL constant

glBegin(GL_LINES);
glVertex2i(40, 100);
glVertex2i(200, 97);
glEnd();

 We can write our own line function, e.g.

void drawLine(GLint x1, GLint y1, GLint x2, GLint y2){


glBegin(GL_LINES);
glVertex2i( x1, y1 );
glVertex2i( x2, y2 );
glEnd();
}
Line Drawings
 If more than two vertices are specified between
glBegin(GL_LINES) and glEnd(), lines are formed
between pairs

glBegin(GL_LINES);
glVertex2i( 10, 20 ); // first line
glVertex2i( 40, 20 ); // first line
glVertex2i( 20, 10 ); // second line
glVertex2i( 20, 40 ); // second line
glEnd();

 Attributes – called BEFORE glBegin(…)


 Color: glColor3f()
 Line width: glLineWidth( float)
Polylines
 What is a polyline?
 Multiple lines, a collection of lines segments, joined end to end
 OpenGL calls this a “line strip”

glBegin(GL_LINE_STRIP);
glVertex2i( 20, 10 );
glVertex2i( 50, 10 ); GL_LINE_STRIP
glVertex2i( 20, 80 );
glVertex2i( 50, 80 );
glEnd();
glFlush();

 Can replace GL_LINE_STRIP with


GL_LINE_LOOP and this will GL_LINE_LOOP
generate a polygon
 This cannot, however, generate a filled polygon
Polygons
For general polygons: GL_POLYGON
Can generate general polygons using
glBegin(), glEnd() and this type
Can fill these polygons
Restrictions
• Polygons must be simple
• Polygons must be convex

Convex Polygon: A polygon is convex if it


contains every line segment delimited by any
two points on its boundary
Other Graphic Primitives
 GL_TRIANGLE
 Takes vertices 3 at a time, separate
triangle for each
 Vertices ordered counterclockwise

 GL_QUADS
 Takes vertices 4 at a time,
counterclockwise

 GL_TRIANGLE_STRIP
 Draws triangles based on triplets of
vertices
 v0, v1, v2; v2, v1, v3; v2, v3, v4; …
 All traversed in same order
(counterclockwise)

 glRecti(GLint x1, GLint y1,


GLint x2, GLint y2)
 Draw a rectangle with opposite
corners (x1, y1) and (x2, y2)
 Special polygon case
Other Graphic Primitives
 GL_TRIANGLE_FAN
 Draws triangles based on
triplets of vertices
 v0, v1, v2; v0, v2, v3; v0, v3,
v4; …
 All traversed in same order
(counterclockwise)

 GL_QUAD_STRIP
 Draws quads based on
foursomes of vertices
 v0, v1, v3, v2; v2, v3, v5, v4;
v4, v5, v7, v6; …
 All traversed in same order
(counterclockwise)
Questions?
In-Class Exercise

 Implement a basic OpenGL C++ program


(Handout)

 When finished, replace the teapot with a cube


constructed with GL_QUADS commands, using
different colors
glColor3f(…)
glBegin(…), glEnd(…)
glVertex3f(…)

Você também pode gostar