0% found this document useful (0 votes)
11 views136 pages

Mod 1

This document provides an overview of computer graphics, including its history, hardware, software, and applications. It discusses the evolution of graphics from early systems to modern techniques, such as raster graphics and the OpenGL API. Key concepts like image formation, light interaction, and the synthetic camera model are also covered, along with programming basics using OpenGL.

Uploaded by

prakyatshetty15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views136 pages

Mod 1

This document provides an overview of computer graphics, including its history, hardware, software, and applications. It discusses the evolution of graphics from early systems to modern techniques, such as raster graphics and the OpenGL API. Key concepts like image formation, light interaction, and the synthetic camera model are also covered, along with programming basics using OpenGL.

Uploaded by

prakyatshetty15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 136

Objectives

• In this lecture, we explore what computer


graphics is about and survey some
application areas
• We start with a historical introduction

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1


Computer Graphics
• Computer graphics deals with all aspects
of creating images with a computer
­ Hardware
­ Software
­ Applications

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 2


Example
• Where did this image come from?

• What hardware/software did we need to


produce it?
Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 3
Preliminary Answer

• Software: Maya for modeling and


rendering but Maya is built on top of
OpenGL
• Hardware: PC with graphics card for
modeling and rendering

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4


Basic Graphics System

Output device

Input devices
Image formed in FB

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 5


CRT

Can be used either as a line-drawing


device (calligraphic) or to display contents
of frame buffer (raster mode)
Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6
Computer Graphics: 1950-1960

• Computer graphics goes back to the


earliest days of computing
­ Strip charts
­ Pen plotters
­ Simple displays using A/D converters to go
from computer to calligraphic CRT
• Cost of refresh for CRT too high
­ Computers slow, expensive, unreliable

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7


Computer Graphics: 1960-1970

• Wireframe graphics
­ Draw only lines
• Sketchpad
• Display Processors
• Storage tube

wireframe representation
of sun object

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


Sketchpad

• Ivan Sutherland’s PhD thesis at MIT


­ Recognized the potential of man-machine
interaction
­ Loop
• Display something
• User moves light pen
• Computer generates new display
­ Sutherland also created many of the now
common algorithms for computer graphics

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 9


Display Processor
• Rather than have the host computer try to
refresh display use a special purpose computer
called a display processor (DPU)

• Graphics stored in display list (display file) on


display processor
• Host compiles display list and sends to DPU
Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1
0
Direct View Storage Tube

• Created by Tektronix
­ Did not require constant refresh
­ Standard interface to computers
• Allowed for standard software
• Plot3D in Fortran
­ Relatively inexpensive
• Opened door to use of computer graphics for CAD
community

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1


1
Computer Graphics: 1970-1980

• Raster Graphics
• Beginning of graphics standards
­ IFIPS
• GKS: European effort
– Becomes ISO 2D standard
• Core: North American effort
– 3D but fails to become ISO standard
• Workstations and PCs

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1


2
Raster Graphics

• Image produced as an array (the raster) of


picture elements (pixels) in the frame
buffer

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1


3
Raster Graphics

• Allows us to go from lines and wire frame


images to filled polygons

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1


4
PCs and Workstations

• Although we no longer make the


distinction between workstations and PCs,
historically they evolved from different
roots
­ Early workstations characterized by
• Networked connection: client-server model
• High-level of interactivity
­ Early PCs included frame buffer as part of user
memory
• Easy to change contents and create images

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1


5
Computer Graphics: 1980-1990

Realism comes to computer graphics

smooth shading environment bump mapping


mapping

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1


6
Computer Graphics: 1980-1990

• Special purpose hardware


­ Silicon Graphics geometry engine
• VLSI implementation of graphics pipeline
• Industry-based standards
­ PHIGS
­ RenderMan
• Networked graphics: X Window System
• Human-Computer Interface (HCI)

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1


7
Computer Graphics: 1990-2000

• OpenGL API
• Completely computer-generated feature-
length movies (Toy Story) are successful
• New hardware capabilities
­ Texture mapping
­ Blending
­ Accumulation, stencil buffers

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1


8
Computer Graphics: 2000-

• Photorealism
• Graphics cards for PCs dominate market
­ Nvidia, ATI
• Game boxes and game players determine
direction of market
• Computer graphics routine in movie
industry: Maya, Lightwave
• Programmable pipelines

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 1


9
Image Formation

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 2


0
Objectives

• Fundamental imaging notions


• Physical basis for image formation
­ Light
­ Color
­ Perception
• Synthetic camera model
• Other models

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 2


1
Image Formation

• In computer graphics, we form images


which are generally two dimensional using
a process analogous to how images are
formed by physical imaging systems
­ Cameras
­ Microscopes
­ Telescopes
­ Human visual system

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 2


2
Elements of Image Formation

• Objects
• Viewer
• Light source(s)

• Attributes that govern how light interacts


with the materials in the scene
• Note the independence of the objects, the
viewer, and the light source(s)

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 2


3
Light

• Light is the part of the electromagnetic


spectrum that causes a reaction in our
visual systems
• Generally these are wavelengths in the
range of about 350-780 nm (nanometers)
• Long wavelengths appear as reds and
short wavelengths as blues

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 2


4
Ray Tracing and
Geometric Optics
One way to form an image is to
follow rays of light from a
point source finding which
rays enter the lens of the
camera. However, each
ray of light may have
multiple interactions with objects
before being absorbed or going to infinity.

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 2


5
Three-Color Theory

• Human visual system has two types of


sensors
­ Rods: monochromatic, night vision
­ Cones
• Color sensitive
• Three types of cones
• Only three values (the tristimulus
values) are sent to the brain
• Need only match these three values
­ Need only three primary colors

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 2


6
Shadow Mask CRT

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 2


7
Additive and Subtractive Color
• Additive color
­ Form a color by adding amounts of three
primaries
• CRTs, projection systems, positive film
­ Primaries are Red (R), Green (G), Blue (B)
• Subtractive color
­ Form a color by filtering white light with cyan
(C), Magenta (M), and Yellow (Y) filters
• Light-material interactions
• Printing
• Negative film

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 2


8
Pinhole Camera

Use trigonometry to find projection of point at (x,y,z)

xp= -x/z/d yp= -y/z/d zp= d

These are equations of simple perspective

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 2


9
Synthetic Camera Model

projector

p
image plane
projection of p
center of projection

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 3


0
Advantages

• Separation of objects, viewer, light sources


• Two-dimensional graphics is a special case
of three-dimensional graphics
• Leads to simple software API
­ Specify objects, lights, camera, attributes
­ Let implementation determine image
• Leads to fast hardware implementation

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 3


1
Global vs Local Lighting

• Cannot compute color or shade of each


object independently
­ Some objects are blocked from light
­ Light can reflect from object to object
­ Some objects might be translucent

Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 3


2
Why not ray tracing?
• Ray tracing seems more physically based
so why don’t we use it to design a
graphics system?
• Possible and is actually simple for simple
objects such as polygons and quadrics
with simple point sources
• In principle, can produce global lighting
effects such as shadows and multiple
reflections but ray tracing is slow and not
well-suited for interactive applications
Angel: Interactive Computer Graphics5E © Addison-Wesley 2009 3
3
Programming with OpenGL
Part 1: Background

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 3


4
Objectives

• Development of the OpenGL API


• OpenGL Architecture
­ OpenGL as a state machine
• Functions
­ Types
­ Formats

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 3


5
OpenGL

The success of GL lead to OpenGL (1992),


a platform-independent API that was
­ Easy to use
­ Close enough to the hardware to get excellent
performance
­ Focus on rendering
­ Omitted windowing and input to avoid window
system dependencies

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 3


6
OpenGL Libraries
• OpenGL core library
­ OpenGL32 on Windows
­ GL on most unix/linux systems (libGL.a)
• OpenGL Utility Library (GLU)
­ Provides functionality in OpenGL core but
avoids having to rewrite code
• Links with window system
­ GLX for X window systems
­ WGL for Windows
­ AGL for Macintosh

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 3


7
GLUT

• OpenGL Utility Toolkit (GLUT)


­ Provides functionality common to all window
systems
• Open a window
• Get input from mouse and keyboard
• Menus
• Event-driven
­ Code is portable but GLUT lacks the
functionality of a good toolkit for a specific
platform
• No slide bars

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 3


8
Software Organization

application program

OpenGL Motif
widget or similar GLUT
GLX, AGL
or WGL GLU

X, Win32, Mac O/S GL

software and/or hardware

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 3


9
OpenGL Functions
• Primitives
­ Points
­ Line Segments
­ Polygons
• Attributes
• Transformations
­ Viewing
­ Modeling
• Control (GLUT)
• Input (GLUT)
• Query

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4


0
OpenGL State

• OpenGL is a state machine


• OpenGL functions are of two types
­ Primitive generating
• Can cause output if primitive is visible
• How vertices are processed and appearance of primitive
are controlled by the state
­ State changing
• Transformation functions
• Attribute functions

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4


1
Lack of Object Orientation

• OpenGL is not object oriented so that


there are multiple functions for a given
logical function
­ glVertex3f
­ glVertex2i
­ glVertex3dv
• Underlying storage mode is the same
• Easy to create overloaded functions in C+
+ but issue is efficiency
Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4
2
OpenGL function format

function name
dimensions

glVertex3f(x,y,z)

belongs to GL library x,y,z are floats

glVertex3fv(p)

p is a pointer to an array

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4


3
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
­ glBegin(GL_POLYGON)
­ glClear(GL_COLOR_BUFFER_BIT)
• include files also define OpenGL data
types: GLfloat, GLdouble,….

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4


4
simple.c
#include <GL/glut.h>
void mydisplay(){
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
glFlush();
}
int main(int argc, char** argv){
glutCreateWindow("simple");
glutDisplayFunc(mydisplay);
glutMainLoop();
}
Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4
5
Event Loop

• Note that the program defines 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

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4


6
Defaults

• simple.c is too simple


• Makes heavy use of state variable default
values for
­ Viewing
­ Colors
­ Window parameters
• Next version will make the defaults more
explicit

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4


7
Notes on compilation

• Unix/linux
­ Include files usually in …/include/GL
­ Compile with –lglut –lglu –lgl loader flags
­ May have to add –L flag for X libraries
­ Mesa implementation included with most linux
distributions
­ Check web for latest versions of Mesa and glut

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4


8
Compilation on Windows

• Visual C++
­ Get glut.h, glut32.lib and glut32.dll from web
­ Create a console application
­ Add opengl32.lib, glut32.lib, glut32.lib to project
settings (under link tab)
• Borland C similar
• Cygwin (linux under Windows)
­ Can use gcc and similar makefile to linux
­ Use –lopengl32 –lglu32 –lglut32 flags

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4


9
A Simple Program
Generate a square on a solid background
simple.c
#include <GL/glut.h>
void mydisplay(){
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
glFlush();
}
int main(int argc, char** argv){
glutCreateWindow("simple");
glutDisplayFunc(mydisplay);
glutMainLoop();
}
Event Loop
• Note that the program defines a display
callback function named mydisplay
o Every glut program must have a display
callback
o The display callback is executed whenever
OpenGL decides the display must be
refreshed, for example when the window is
opened
o The main function ends with the program
entering an event loop
Program Structure
• Most OpenGL programs have a similar structure
that consists of the following functions
o main():
 defines the callback functions
 opens one or more windows with the required properties
 enters event loop (last executable statement)
o init(): sets the state variables
 Viewing
 Attributes
o callbacks
 Display function
 Input and window functions
simple.c revisited
• In this version, we shall see the same
output but we have defined all the
relevant state values through function
calls using the default values
• In particular, we set
o Colors
o Viewing conditions
o Window properties
main.c

#include <GL/glut.h> includes gl.h

int main(int argc, char** argv)


{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("simple"); define window
glutDisplayFunc(mydisplay); properties
init();
display callback
glutMainLoop();
} set OpenGL
state

enter event
loop
GLUT functions

• glutInit allows application to get command line arguments


and initializes system
• gluInitDisplayMode requests properties for the window
(the rendering context)
o RGB color
o Single buffering
o Properties logically ORed together
• glutWindowSize in pixels
• glutWindowPosition from top-left corner of display
• glutCreateWindow create window with title “simple”
• glutDisplayFunc display callback
• glutMainLoop enter infinite event loop
init.c

black clear
color
void init() opaque
{ window
glClearColor (0.0, 0.0, 0.0, 1.0);

glColor3f(1.0, 1.0, 1.0); fill/draw with white

glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
viewing volume
Programming with OpenGL
Part 2: Complete Programs

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 5


8
Objectives

• Simple viewing
­ Two-dimensional viewing as a special case of
three-dimensional viewing
• Fundamental OpenGL primitives
• Attributes

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 5


9
Coordinate Systems
• The units in glVertex are determined by the
application and are called object or problem
coordinates
• The viewing specifications are also in object
coordinates and it is the size of the viewing
volume that determines what will appear in the
image
• Internally, OpenGL will convert to camera (eye)
coordinates and later to screen coordinates
• OpenGL also uses some internal representations
that usually are not visible to the application
Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6
0
OpenGL Camera

• OpenGL places a camera at the origin in


object space pointing in the negative z
direction
• The default viewing volume
is a box centered at the
origin with a side of
length 2

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6


1
Orthographic Viewing

In the default orthographic view, points are


projected forward along the z axis onto the
plane z=0

z=0

z=0

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6


2
Transformations and Viewing
• In OpenGL, projection is carried out by a
projection matrix (transformation)
• There is only one set of transformation functions
so we must set the matrix mode first
glMatrixMode (GL_PROJECTION)
• Transformation functions are incremental so we
start with an identity matrix and alter it with a
projection matrix that gives the view volume
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6


3
Two- and three-
dimensional viewing
• In glOrtho(left, right, bottom, top,
near, far) the near and far distances are
measured from the camera
• Two-dimensional vertex commands place all vertices
in the plane z=0
• If the application is in two dimensions, we can use
the function
gluOrtho2D(left, right,bottom,top)
• In two dimensions, the view or clipping volume
becomes a clipping window

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6


4
mydisplay.c

void mydisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
glFlush();
}

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6


5
OpenGL Primitives

GL_POINTS GL_POLYGON
GL_LINES GL_LINE_STRIP

GL_LINE_LOOP

GL_TRIANGLES
GL_QUAD_STRIP

GL_TRIANGLE_STRIP GL_TRIANGLE_FAN

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6


6
Polygon Issues
• OpenGL will only display polygons correctly that are
­ Simple: edges cannot cross
­ Convex: All points on line segment between two points in a
polygon are also in the polygon
­ Flat: all vertices are in the same plane
• User program can check if above true
­ OpenGL will produce output if these conditions are violated
but it may not be what is desired
• Triangles satisfy all conditions

nonconvex polygon
nonsimple polygon
Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6
7
Attributes

• Attributes are part of the OpenGL state


and determine the appearance of objects
­ Color (points, lines, polygons)
­ Size and width (points, lines)
­ Stipple pattern (lines, polygons)
­ Polygon mode
• Display as filled: solid color or stipple pattern
• Display edges
• Display vertices

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6


8
RGB color
• Each color component is stored separately in
the frame buffer
• Usually 8 bits per component in buffer
• Note in glColor3f the color values range from
0.0 (none) to 1.0 (all), whereas in glColor3ub
the values range from 0 to 255

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 6


9
Indexed Color

• Colors are indices into tables of RGB values


• Requires less memory
­ indices usually 8 bits
­ not as important now
• Memory inexpensive
• Need more colors for shading

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7


0
Color and State
• The color as set by glColor becomes part of the
state and will be used until changed
­ Colors and other attributes are not part of the
object but are assigned when the object is
rendered
• We can create conceptual vertex colors by code
such as
glColor
glVertex
glColor
glVertex

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7


1
Programming with OpenGL
Part 3: Three Dimensions

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7


2
Objectives

• Develop a more sophisticated three-


dimensional example
­ Sierpinski gasket: a fractal
• Introduce hidden-surface removal

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7


3
Three-dimensional Applications
• In OpenGL, two-dimensional applications
are a special case of three-dimensional
graphics
• Going to 3D
­ Not much changes
­ Use glVertex3*( )
­ Have to worry about the order in which
polygons are drawn or use hidden-surface
removal
­ Polygons should be simple, convex, flat

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7


4
Sierpinski Gasket (2D)
• Start with a triangle

• Connect bisectors of sides and remove central


triangle

• Repeat

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7


5
Example

• Five subdivisions

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7


6
The gasket as a fractal

• Consider the filled area (black) and the


perimeter (the length of all the lines around
the filled triangles)
• As we continue subdividing
­ the area goes to zero
­ but the perimeter goes to infinity
• This is not an ordinary geometric object
­ It is neither two- nor three-dimensional
• It is a fractal (fractional dimension) object
Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7
7
Gasket Program
#include <GL/glut.h>

/* initial triangle */

GLfloat v[3][2]={{-1.0, -0.58},


{1.0, -0.58}, {0.0, 1.15}};

int n; /* number of recursive steps */

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7


8
Draw one triangle
void triangle( GLfloat *a, GLfloat *b,
GLfloat *c)

/* display one triangle */


{
glVertex2fv(a);
glVertex2fv(b);
glVertex2fv(c);
}

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7


9
Triangle Subdivision
void divide_triangle(GLfloat *a, GLfloat *b, GLfloat *c,
int m)
{
/* triangle subdivision using vertex numbers */
point2 v0, v1, v2;
int j;
if(m>0)
{
for(j=0; j<2; j++) v0[j]=(a[j]+b[j])/2;
for(j=0; j<2; j++) v1[j]=(a[j]+c[j])/2;
for(j=0; j<2; j++) v2[j]=(b[j]+c[j])/2;
divide_triangle(a, v0, v1, m-1);
divide_triangle(c, v1, v2, m-1);
divide_triangle(b, v2, v0, m-1);
}
else(triangle(a,b,c));
/* draw triangle at end of recursion */
}

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


0
display and init Functions
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
divide_triangle(v[0], v[1], v[2], n);
glEnd();
glFlush();
}
void myinit()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-2.0, 2.0, -2.0, 2.0);
glMatrixMode(GL_MODELVIEW);
glClearColor (1.0, 1.0, 1.0,1.0)
glColor3f(0.0,0.0,0.0);
}

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


1
main Function
int main(int argc, char **argv)
{
n=4;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow(“2D Gasket");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


2
Efficiency Note

By having the glBegin and glEnd in the


display callback rather than in the function
triangle and using GL_TRIANGLES
rather than GL_POLYGON in glBegin,
we call glBegin and glEnd only once for
the entire gasket rather than once for
each triangle

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


3
Moving to 3D

• We can easily make the program three-


dimensional by using
GLfloat v[3][3]
glVertex3f
glOrtho
• But that would not be very interesting
• Instead, we can start with a tetrahedron

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


4
3D Gasket

• We can subdivide each of the four faces

• Appears as if we remove a solid


tetrahedron from the center leaving four
smaller tetrahedra

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


5
Example

after 5 iterations

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


6
triangle code
void triangle( GLfloat *a, GLfloat *b,
GLfloat *c)
{
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
}

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


7
subdivision code
void divide_triangle(GLfloat *a, GLfloat *b,
GLfloat *c, int m)
{
GLfloat v1[3], v2[3], v3[3];
int j;
if(m>0)
{
for(j=0; j<3; j++) v1[j]=(a[j]+b[j])/2;
for(j=0; j<3; j++) v2[j]=(a[j]+c[j])/2;
for(j=0; j<3; j++) v3[j]=(b[j]+c[j])/2;
divide_triangle(a, v1, v2, m-1);
divide_triangle(c, v2, v3, m-1);
divide_triangle(b, v3, v1, m-1);
}
else(triangle(a,b,c));
}

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


8
tetrahedron code
void tetrahedron( int m)
{
glColor3f(1.0,0.0,0.0);
divide_triangle(v[0], v[1], v[2], m);
glColor3f(0.0,1.0,0.0);
divide_triangle(v[3], v[2], v[1], m);
glColor3f(0.0,0.0,1.0);
divide_triangle(v[0], v[3], v[1], m);
glColor3f(0.0,0.0,0.0);
divide_triangle(v[0], v[2], v[3], m);
}

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8


9
Almost Correct
• Because the triangles are drawn in the order
they are defined in the program, the front
triangles are not always rendered in front of
triangles behind them
get this
want this

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 9


0
Hidden-Surface Removal
• We want to see only those surfaces in front of
other surfaces
• OpenGL uses a hidden-surface method called
the z-buffer algorithm that saves depth
information as objects are rendered so that only
the front objects appear in the image

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 9


1
Using the z-buffer algorithm
• The algorithm uses an extra buffer, the z-buffer, to
store depth information as geometry travels down the
pipeline
• It must be
­ Requested in main.c
• glutInitDisplayMode
(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH)
­ Enabled in init.c
• glEnable(GL_DEPTH_TEST)
­ Cleared in the display callback
• glClear(GL_COLOR_BUFFER_BIT |
GL_DEPTH_BUFFER_BIT)

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 9


2
Surface vs Volume Subdvision

• In our example, we divided the surface of


each face
• We could also divide the volume using the
same midpoints
• The midpoints define four smaller
tetrahedrons, one for each vertex
• Keeping only these tetrahedrons removes
a volume in the middle
• See text for code

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 9


3
Volume Subdivision

Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 9


4
How will you display text in Computer
Graphics???
TEXT in Computer Graphics

Two forms of Text in CG


1.Stroke Text
2.Raster Text (BitmapText)
TEXT in Computer Graphics
Stroke Text

• Constructed as other Geometric objects


• Use vertices to define line segments or
curves.
TEXT in Computer Graphics
Stroke Text Advantages

• Detailed view of text


• Use of Geometric Transformations
TEXT in Computer Graphics
Stroke Text Disadvantages

• Defining 256-character stroke font can be


complex
• Consume significant memory and
processing time
• Slow rendering of stroke characters
TEXT in Computer Graphics
Raster Text

• Characters defined as rectangles of bits


called bit blocks
• Each block defines a character
• Size can be increased by replicating
pixels
TEXT in Computer Graphics
GLUT library provides a few pre defined
raster and stroke character sets

Eg :
glutBitmapCharacter(GLUT_BITMAP_8_BY_13,c)

8 13 pixels Bitmap character.


c is number of ASCII characters to be placed on
display
Color
RGB Color
• Separate buffers for Red, Green, Blue
images.
• Each pixel has separate R,G,B
components that correspond to memory
locations.
Color
RGBA System

• Four color System


• Fourth color, (A or alpha) , stored in
Frame Buffer along with RGB values
• A=0.0 indicates Fully transparent
• A=1.0 indicates Fully Opaque
Color
Indexed Color

Provided a solution that allowed applications


to display wide range of colors
Indexed Color
• Colors are indices into tables of RGB
values
• Requires less memory
o indices usually 8 bits
o not as important now
 Memory inexpensive
 Need more colors for shading
Setting Color Attributes
• Three attributes have to be set
o The clear color. Set to white
glClearColor(1.0, 1.0, 1.0, 1.0);
o Set rendering color
glColor3f(1.0, 1.0, 1.0);
o Set the size of rendered points
glPointSize(2.0);
Chapter 3
Input and Interaction
Objectives
• Introduce the basic input devices
o Physical Devices
o Logical Devices
o Input Modes
• Event-driven input
• Introduce double buffering for smooth
animations
• Programming event input with GLUT
Project Sketchpad
• Ivan Sutherland (MIT 1963) established
the basic interactive paradigm that
characterizes interactive computer
graphics:
o User sees an object on the display
o User points to (picks) the object with an input
device (light pen, mouse, trackball)
o Object changes (moves, rotates, morphs)
o Repeat
• Measure of a device is what the device
returns to the user program
• Trigger of a device is a physical input on
the device with which the user can signal
the computer
Graphical Input
• Devices can be described either by
o Physical properties
 Mouse
 Keyboard
 Trackball
o Logical Properties
 What is returned to program via API
 A position
 An object identifier
• Modes
o How and when input is obtained
 Request or event
Physical Devices

mouse trackball
light pen

data tablet joy stick space ball


Logical Devices
• Consider the C and C++ code
o C++: cin >> x;
o C: scanf (“%d”, &x);
• What is the input device?
o Can’t tell from the code
o Could be keyboard, file, output from another
program
• The code provides logical input
o A number (an int) is returned to the program
regardless of the physical device
Graphical Logical Devices
• Graphical input is more varied than input to
standard programs which is usually numbers,
characters, or bits
• Two older APIs (GKS, PHIGS) defined six types of
logical input
o Locator: return a position
o Pick: return ID of an object
o String: return strings of characters
o Stroke: return array of positions
o Valuator: return floating point number
o Choice: return one of n items
X Window Input
• The X Window System introduced a client-server
model for a network of workstations
o Client: OpenGL program
o Graphics Server: bitmap display with a pointing
device and a keyboard
Input Modes
• Input devices contain a trigger which can
be used to send a signal to the operating
system
o Button on mouse
o Pressing or releasing a key
• When triggered, input devices return
information (their measure) to the system
o Mouse returns position information
o Keyboard returns ASCII code
Request Mode
• Input provided to program only when user
triggers the device
• Typical of keyboard input
o Can erase (backspace), edit, correct until enter
(return) key (the trigger) is depressed
Event Mode
• Most systems have more than one input
device, each of which can be triggered at
an arbitrary time by a user
• Each trigger generates an event whose
measure is put in an event queue which
can be examined by the user program
Sample Mode
Event Types
• Window: resize, expose, iconify
• Mouse: click one or more buttons
• Motion: move mouse
• Keyboard: press or release a key
• Idle: nonevent
o Define what should be done if no other event is
in queue
Chapter 3
Input and Interaction
continued…
Callbacks
• Programming interface for event-driven
input
• Define a callback function for each type of
event the graphics system recognizes
• This user-supplied function is executed
when the event occurs
• GLUT example:
glutMouseFunc(mymouse)

mouse callback function


GLUT callbacks
GLUT recognizes a subset of the events
recognized by any particular window system
(Windows, X, Macintosh)
• glutDisplayFunc
• glutMouseFunc
• glutReshapeFunc
• glutKeyboardFunc
• glutIdleFunc
• glutMotionFunc, glutPassiveMotionFunc
The mouse callback
glutMouseFunc(mymouse)
void mymouse(GLint button, GLint state,
GLint x, GLint y)
• Returns
o which button (GLUT_LEFT_BUTTON,
GLUT_MIDDLE_BUTTON,
GLUT_RIGHT_BUTTON) caused event
o state of that button (GLUT_UP,
GLUT_DOWN)
o Position in window
Terminating a program
• In our original programs, there was no
way to terminate them through OpenGL
• We can use the simple mouse callback

void mouse(int btn, int state, int x, int y)


{
if(btn==GLUT_RIGHT_BUTTON && state==GLUT_DOWN)
exit(0);
}
Drawing squares at cursor
location
void mymouse(int btn, int state, int x, int y)
{
if(btn==GLUT_RIGHT_BUTTON && state==GLUT_DOWN)
exit(0);
if(btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
drawSquare(x, y);
}
void drawSquare(int x, int y)
{
y=w-y; /* invert y position */
glColor3ub( (char) rand()%256, (char) rand )%256, (char) rand()%256); /* a
random color */
glBegin(GL_POLYGON);
glVertex2f(x+size, y+size);
glVertex2f(x-size, y+size);
glVertex2f(x-size, y-size);
glVertex2f(x+size, y-size);
glEnd();
}
Using the motion callback
• We can draw squares (or anything else)
continuously as long as a mouse button is
depressed by using the motion callback
o glutMotionFunc(drawSquare)
• We can draw squares without depressing
a button using the passive motion
callback
o glutPassiveMotionFunc(drawSquare)
Using the keyboard
glutKeyboardFunc(mykey)
void mykey(unsigned char key,
int x, int y)
• Returns ASCII code of key depressed and
mouse location

void mykey()
{
if(key == ‘Q’ | key == ‘q’)
exit(0);
}
Special and Modifier Keys

• GLUT defines the special keys in glut.h


o Function key 1: GLUT_KEY_F1
o Up arrow key: GLUT_KEY_UP
 if(key == ‘GLUT_KEY_F1’ ……
Reshaping the window

• We can reshape and resize the OpenGL


display window by pulling the corner of
the window
• What happens to the display?
o Must redraw from application
o Two possibilities
 Display part of world
 Display whole world but force to fit in new
window
 Can alter aspect ratio
Reshape possiblities

original

reshaped
The Reshape callback
glutReshapeFunc(myreshape)
void myreshape( int w, int h)
• Returns width and height of new window (in
pixels)
• A redisplay is posted automatically at end of
execution of the callback
• GLUT has a default reshape callback but you
probably want to define your own
• The reshape callback is good place to put
viewing functions because it is invoked
when the window is first opened
Viewports
• Do not have use the entire window for the
image: glViewport(x,y,w,h)
• Values in pixels (screen coordinates)
Menus

• GLUT supports pop-up menus


o A menu can have submenus
• Three steps
o Define entries for the menu
o Define action for each menu item
 Action carried out if entry selected
o Attach menu to a mouse button
Defining a simple menu
• In main.c
menu_id = glutCreateMenu(mymenu);
glutAddmenuEntry(“clear Screen”, 1);

gluAddMenuEntry(“exit”, 2);
clear screen
glutAttachMenu(GLUT_RIGHT_BUTTON);
exit

entries that appear when identifiers


right button depressed
Menu actions
• Menu callback
void mymenu(int id)
{
if(id == 1) glClear();
if(id == 2) exit(0);
}
• Note each menu has an id that is returned when it is
created
• Add submenus by
glutAddSubMenu(char *submenu_name, submenu id)

entry in parent menu

You might also like