0% found this document useful (0 votes)
23 views127 pages

CG Module 1 Fully Updated 18

This document provides an overview of computer graphics and visualization. It discusses that computer graphics deals with creating digital images through techniques like imaging, rendering, modeling, and animation. It lists common graphics applications such as graphs/charts, CAD, VR, scientific visualization, education/training, art, entertainment, image processing, and GUIs. It also describes the basic graphics system pipeline from 3D models to 2D images displayed on a screen.

Uploaded by

Nithin SS
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)
23 views127 pages

CG Module 1 Fully Updated 18

This document provides an overview of computer graphics and visualization. It discusses that computer graphics deals with creating digital images through techniques like imaging, rendering, modeling, and animation. It lists common graphics applications such as graphs/charts, CAD, VR, scientific visualization, education/training, art, entertainment, image processing, and GUIs. It also describes the basic graphics system pipeline from 3D models to 2D images displayed on a screen.

Uploaded by

Nithin SS
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/ 127

COMPUTER GRAPHICS & VISUALIZATION

(18CS62)

Department of Computer Science & Engineering


What is Computer Graphics?
• “Computer graphics is a sub-field of computer science and is concerned
with digitally synthesizing and manipulating visual content.”
• Computer graphics deals with all aspects of creating images with a
computer- Imaging, Rendering, Modeling, Animation.
• Hardware: PC with graphics card for modeling and rendering.
• Software: OpenGL
• Applications: Any
Graphics Applications
• Graphs and charts
• Computer-aided design
• Virtual-Reality Environments
• Scientific visualization
• Education and Training
• Computer art
• Entertainment
• Image Processing
• Graphical User Interfaces
Data plotting with dramatic effect, commonly used to summarize financial,
statistical, mathematical, scientific, engineering, and economic data for research
reports, managerial summaries, consumer information bulletins and other types of
publications
Graphs and charts
• Computer-aided design
• Virtual-Reality Environments
• Scientific visualization
• Education and Training
• Computer art
• Entertainment
• Image Processing
• Graphical User Interfaces
In design of building, automobiles, aircrafts,
watercrafts, spacecrafts, computers, textiles, home
appliances and a multitude of other products

• Graphs and charts


Computer-aided design Los Angeles Airport
• Virtual-Reality Environments
• Scientific visualization
• Education and Training
• Computer art Gear Shaft Design

• Entertainment
• Image Processing CMOS Circuit Design
Contd…
• Graphical User Interfaces
Such animations are often used to train heavy-equipment operators, analyze the
effectiveness of various cabin configuration and control placements, users can
interact with the objects in a 3D scene.

• Graphs and charts


• Computer-aided design
Virtual-Reality Environments
• Scientific visualization
• Education and Training
• Computer art
• Entertainment
• Image Processing
• Graphical User Interfaces
Also called data visualization: produces graphical representations for scientific,
engineering and medical data sets and processes it. Business visualization is used in
connection with data sets related to commerce, industry, and other nonscientific areas.
Also used in understanding and analyzing complex processes and mathematical
functions
• Graphs and charts
• Computer-aided design
• Virtual-Reality Environments
Scientific visualization
• Education and Training
• Computer art
Airflow inside a thunderstorm
• Entertainment
• Image Processing Visible human

Contd…
• Graphical User Interfaces
Computer generated models of physical, financial, political, social, economic, and other
systems are often used as educational aids. Eg: color-coded diagram in operation of a
nuclear reactor, aircraft, naval, spacecraft simulators
• Graphs and charts
• Computer-aided design
• Virtual-Reality Environments
• Scientific visualization
Education and Training Flight Simulation Flight Simulation
• Computer art
• Entertainment
• Image Processing
• Graphical User Interfaces
Driving Simulation
Graphics are used in Fine Art, Commercial Art applications and Mathematical Art. The artist uses a
combination of 3D modeling packages, texture mapping, drawing programs and CAD software.
Mathematical Art is produced using mathematical functions and fractal procedures. Pen plotters create
Automatic Art.

• Graphs and charts


• Computer-aided design
• Virtual-Reality Environments
• Scientific visualization
• Education and Training
Computer art
• Entertainment
• Image Processing
• Graphical User Interfaces
Graphics are commonly used in making motion pictures, music videos and television
shows. Graphics objects can be combined with live actions. Eg. Avtar movie

• Graphs and charts


• Computer-aided design
• Virtual-Reality Environments
• Scientific visualization
• Education and Training
• Computer art Jurasic Park

Entertainment
• Image Processing
• Graphical User Interfaces
Image processing applies techniques to modify or interpret existing pictures (photographs, TV
scans).to apply image processing methods, the image must be digitized first. Medical
applications also make extensive use of image processing techniques for picture enhancement,
simulations of surgical operations. It used to improve picture quality, analyze or recognize
visual• patterns.
Graphs and charts
• Computer-aided design
• Virtual-Reality Environments
• Scientific visualization
• Education and Training
• Computer art
• Entertainment
Image Processing
• Graphical User Interfaces
User is provided with point and click facility to select menu items, icons and objects on the
screen. User can manage multiple windows simultaneously. Word-processing spreadsheets and
desktop-publishing programs are typical applications that take advantage of such user
interface techniques.
• Graphs and charts
• Computer-aided design
• Virtual-Reality Environments
• Scientific visualization
• Education and Training
• Computer art
• Entertainment
• Image Processing
Graphical User Interfaces
Basic Graphics System

Output device

Input devices

Image formed in FB
From model to image

Model World View NDC Display

Graphics pipeline

Coordinates and transformations


From model to image

Model World View NDC Display

Cylinder:
x2  y2  r 2
0 zh
Geometric modeling Local or modeling coordinates
From model to image

Model World View NDC Display

Position cylinders in scene:

World coordinates
From model to image

Model World View NDC Display

Look at cylinders,
project on virtual screen

Viewing coordinates
Visible surfaces, shading
From model to image

Model World View NDC Display

1
Display:

Normalized Device Coordinates


0 1
From model to image

Model World View NDC Display

0
1024
Display on screen:

768 Device Coordinates


Interaction
Video Display Devices
• Emissive display - Convert electrical energy into light
- Cathode ray tube (CRT)
- Flat panel CRT
- Plasma panels (gas-discharge display)
- Thin-film electroluminescent (EL) display
- Light-emitting diodes
• Non-Emissive display - Optical effect: convert sunlight or light from other source
into graphic patterns.
- Liquid-crystal device (LCD) – flat panel
- Passive-matrix LCD
- Active-matrix LCD
Architectures for displaying objects
• Vector system Architecture (Random-Scan)
 Line drawing and stroke drawing in a random order

• Raster Refresh Architecture(Raster-Scan)


 Horizontal scan line order
Vector System Architecture(Random-Scan),
consists of:
• Vector system consists of: display processor (controller), display buffer memory, CRT
 In addition to the CPU, a special processor, called the Video controller or Display controller, is
used to control the operations of the display device - Connected as an I/O peripheral to the CPU.
 Display buffer memory: stores computer-produced display list or display program- contains
point and line plotting commands
 The commands interpreted by the display processor sends digital and point co-ordinates to
vector generator that converts digital co-ordinate values to analog voltages for beam-deflection
circuits that displays an electron beam writing on the CRT’s phosphor coating.
 Display commands dictate the beam deflection from endpoint to endpoint. This technique is
called Random-Scan - Line drawing and stroke drawing in a random order.
 Display list needed to be refreshed(Display processor must cycle through the display list- e.g
30Hz)
Vector Display
Host Computer
Display Interaction
: cmds
Move 10,15 Display Controller (DC)
LINE 300,400
CHAR Lu, cy
LINE Monitor Keyboard/mouse
:
.
.
. User

:
JMP

display buffer
Raster Display (since 1970s)
• Raster system consists of display processor (input, refreshing, scan converting),
video controller, buffer memory (frame buffer), CRT.
• The refresh buffer stores the display primitives(lines char and solid shaded or
patterned areas), rather than display list or display program.
• Raster: set of horizontal raster lines each a row of individual pixels and thus
stored as a matrix of pixels representing entire screen.
• Video controller reads these pixel contents to produce the actual image on the
screen, one raster line at a time, from top to bottom and then back to top.
• need refresh the raster display (e.g., 60Hz)
Raster Display

Host Computer
Display Interaction
cmds data
Display Processor

Lucy
Video Controller Lucy

Frame buffer Monitor


Basic definitions
 Video raster devices display an image by sequentially
drawing out the pixels of the scan lines that form the
raster.
• Raster: A rectangular array of points or dots.
• Pixel (Pel, picture elements): One dot or picture element of the raster, defined as
smallest addressable area on screen.
• Scan line: A row of pixels.
• Resolution: # of pixel positions that can be plotted.
• Aspect Ratio: # of horizontal points to vertical points(or vice versa).
• Depth: # of bits per pixel in a frame buffer.
• Bitmap: a frame buffer with one bit per pixel
• Pixmap: a frame buffer with multiple bits per pixel.
• Horizontal retrace: return to the left of the screen, after refreshing each scan
line.
• Vertical retrace: electron beam returns to the top left corner of the screen to
begin the next frame.
• Refresh rates are described in units of cycles per seconds, or Hertz(Hz).
Graphics Software
• There are two broad classifications for computer-graphics software
• Special-purpose packages: Special-purpose packages are designed for
nonprogrammers
• Example: generate pictures, graphs, charts, painting programs or CAD systems in
some application area without worrying about the graphics procedure
• General programming packages: general programming package provides a library
of graphics functions that can be used in a programming language such as C, C++,
Java, or FORTRAN.
• Example: GL (Graphics Library), OpenGL, VRML (Virtual-Reality Modeling
Language), Java 2D And Java 3D
NOTE: A set of graphics functions is often called a computer-graphics application
programming interface (CG API)
Graphics Programming/ Software
• Development of the OpenGL API (Open Graphics Library Application Program
Interface)
• OpenGL Architecture
• OpenGL as a state machine
• Functions
• Types
• Formats
• Simple program
Early History of APIs
• IFIPS (1973) formed two committees to come up with a standard graphics API
• Graphical Kernel System (GKS) Two versions 2D & 3D
• 2D but contained good workstation model
• Core
• Both 2D and 3D
• GKS adopted as IS0 and later ANSI standard (1980s)
• GKS not easily extended to 3D (GKS-3D)
• Far behind hardware development
PHIGS
• Programmers Hierarchical Graphics System (PHIGS)
• Arose from CAD community
• Database model with retained graphics (structures)
• X Window System
• DEC/MIT effort
• Client-server architecture with graphics
• PEX combined the two
• Not easy to use (all the defects of each)
SGI
• Silicon Graphics (SGI) revolutionized the graphics workstation by
implementing the pipeline in hardware (1982)
• To use the system, application programmers used a library called GL
• With GL, it was relatively simple to program three dimensional interactive
applications
• Low-level 3D API • WebGL is a JavaScript interface • Java FX
for OpenGL-ES-2.x API,
• These APIs for 3D computer • JMonkey Engine
promoted by Khronos. This is
graphics are particularly popular: gaining more interest recently, as • JT Open from Siemens PLM
• Direct3D (a subset of DirectX) this enables applications to use Software
native graphics.
• Glide • Mobile 3D Graphics API (M3G;
• Mantle developed by AMD. • High-level 3D API JSR-184)

• There are also higher-level • OGRE


• Metal developed by Apple.
3D scene-graph APIs which • OpenGL Performer
• MonoGame provide additional functionality
on top of the lower-level • OpenSceneGraph
• OpenGL and the OpenGL
Shading Language rendering API. Such libraries • OpenSG
under active development
• OpenGL ES 3D API for include: • QSDK
embedded devices • VTK
• ClanLib
• QuickDraw 3D developed by
Apple Computer starting in • Crystal Space
1995, abandoned in 1998 • HOOPS 3D Graphics System
• RenderMan, RenderWare • Horde3D
• LibGCM • Irrlicht Engine
• Web-based API • Java 3D
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
OpenGL Evolution
• Controlled by an Architectural Review Board (ARB)
• Members include SGI, Microsoft, Nvidia, HP, 3DLabs,IBM,…….
• Relatively stable (present version 1.4)
• Evolution reflects new hardware capabilities
 3D texture mapping and texture objects
 Vertex programs
• Allows for platform specific features through extensions
OpenGL Libraries
• OpenGL core library
• OpenGL32 on Windows
• GL on most unix/linux systems
• 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 Widows
• AGL for Macintosh
GLUT
• OpenGL Utility Library (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
• Slide bars
OpenGL Functions
• Primitives
• Points
• Line Segments
• Polygons
• Attributes
• Transformations
• Viewing
• Modeling
• Control
• Input (GLUT)
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 processes and appearance of primitive are controlled by the state
• State changing
• Transformation functions
• Attribute functions
Lack of Object Orientation
• OpenGL is not object oriented so that there are multiple functions for a
given logical function, e.g. glVertex3f, glVertex2i,
glVertex3dv,…..
• Underlying storage mode is the same
• Easy to create overloaded functions in C++ but issue is efficiency
OpenGL Function Format
function name
3 is Dimension can be 2 or 3

glVertex3f(x,y,z)

belongs to GL library x,y,z are floats

glVertex3fv(p)

p is a pointer to an array
OpenGL #defines
• Most constants are defined in the include files gl.h, glu.h and
glut.h
• Note #include <glut.h> should automatically include the others
• Examples
• glBegin(GL_PLOYGON)
• glClear(GL_COLOR_BUFFER_BIT)
• Include files also define OpenGL data types: Glfloat, Gldouble,….
Program Structure
• Most OpenGL programs have a similar structure that consists of the following functions
• main():
• defines the callback functions
• opens one or more windows with the required properties
• enters event loop (last executable statement)
• init(): sets the state variables
• viewing
• Attributes
• callbacks
• Display function
• Input and window functions
Header Files
• In all graphics programs, we will need to include the header file for the
OpenGL core library.
• #include <GL/glut.h>//GL in windows
• Step 1: initialization of GLUT
• We are using the OpenGL Utility Toolkit, our first step is to initialize
GLUT. This initialization function could also process any command line
arguments, but we will not need to use these parameters for our first
example programs. We perform the GLUT initialization with the
statement
• glutInit (&argc, argv);
• Step 2: title
• We can state that a display window is to be created on the screen with a
given caption for the title bar. This is accomplished with the function
glutCreateWindow ("An Example OpenGL Program");
• where the single argument for this function can be any character string
that we want to use for the display-window title.
• Step 3: Specification of the display window
• Then we need to specify what the display window is to contain. For this, we
create a picture using OpenGL functions and pass the picture definition to the
GLUT routine glutDisplayFunc, which assigns our picture to the display window.
• Example: suppose we have the OpenGL code for describing a line segment in a
procedure called lineSegment.  Then the following function call passes the
line-segment description to the display window: glutDisplayFunc
(lineSegment);
• Step 4: one more GLUT function
• But the display window is not yet on the screen. We need one more GLUT
function to complete the window-processing operations. After execution
of the following statement, all display windows that we have created,
including their graphic content, are now activated: glutMainLoop ( );
This function must be the last one in our program. It displays the initial
graphics and puts the program into an infinite loop that checks for input
from devices such as a mouse or keyboard.
• Step 5: these parameters using
additional GLUT functions
• Although the display window that we
created will be in some default location
and size, we can set these parameters
using additional GLUT functions.
• GLUT Function 1: ➔ We use the
glutInitWindowPosition function to give
an initial location for the upper left corner
of the display window.
• ➔ This position is specified in integer
screen coordinates, whose origin is at the
upper-left corner of the screen.
• GLUT Function 2: After the display window is on the screen, we can
reposition and resize it.
• GLUT Function 3: ➔ We can also set a number of other options for the
display window, such as buffering and a choice of color modes, with the
glutInitDisplayMode function.
• ➔ Arguments for this routine are assigned symbolic GLUT constants.
• ➔ Example: the following command specifies that a single refresh buffer is to
be used for the display window and that we want to use the color mode which
uses red, green, and blue (RGB) components to select color values:
• glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
• ➔ The values of the constants passed to this function are combined using a
logical or operation.
A Complete OpenGL Program ➔ There are still a few
more tasks to perform before we have all the parts that
we need for a complete program.
• Step 1: to set background color
• ➔ For the display window, we can choose a background color.
• ➔ Using RGB color values, we set the background color for the display window to be
white, with the OpenGL function: glClearColor (1.0, 1.0, 1.0, 0.0);
• ➔ The first three arguments in this function set the red, green, and blue component colors
to the value 1.0, giving us a white background color for the display window. ➔ If, instead
of 1.0, we set each of the component colors to 0.0, we would get a black background.
• ➔ The fourth parameter in the glClearColor function is called the alpha value for the
specified color. One use for the alpha value is as a “blending” parameter.
• Step 2: to set window color ➔ To get the assigned window color displayed, we
need to invoke the following OpenGL function:
• glClear (GL_COLOR_BUFFER_BIT); ➔ The argument GL COLOR BUFFER
BIT is an OpenGL symbolic constant specifying that it is the bit values in the color
buffer (refresh buffer) that are to be set to the values indicated in the glClearColor
function. (OpenGL has several different kinds of buffers that can be manipulated.
• Step 3: to set color to object ➔ In addition to setting the background color for the
display window, we can choose a variety of color schemes for the objects we want
to display in a scene.
• ➔ For our initial programming example, we will simply set the object color to be a
dark green
• glColor3f (0.0, 0.4, 0.2);
• ➔ We can set the projection type (mode) and other viewing parameters
that we need with the following two functions:
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 200.0, 0.0, 150.0);
➔ This specifies that an orthogonal projection is to be used to map the
contents of a twodimensional rectangular area of world coordinates to the
screen, and that the xcoordinate values within this rectangle range from 0.0
to 200.0 with y-coordinate values ranging from 0.0 to 150.0.
• ➔ Finally, we need to call the appropriate OpenGL routines to create our
line segment.
• ➔ The following code defines a two-dimensional, straight-line segment
with integer,
• ➔ Cartesian endpoint coordinates (180, 15) and (10, 145).
• glBegin (GL_LINES);
• glVertex2i (180, 15);
• glVertex2i (10, 145);
• glEnd ( );
• ➔ Now we are ready to put all the pieces together:
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
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
Graphics Pipelines
• Graphics processes generally execute sequentially
• Typical ‘pipeline’ model
• There are two ‘graphics’ pipelines
• The Geometry or 3D pipeline
• The Imaging or 2D pipeline

7/5/23
Narendra V G CSE MIT 60
10:13:49 AM
2D Graphics Pipeline
Clipping
Object window to
Object Applying
subset viewport
World Coordinates world window
mapping

Simple 2D Drawing Pipeline

Object
Display Rasterization
Screen coordinates
Rasterization (Scan Conversion)

• Convert high-level geometry description to pixel colors in the


frame buffer
• Example: given vertex x, y coordinates determine pixel colors to
draw line
• Two ways to create an image: Viewport
Rasterization
Transformation
• Scan existing photograph
• Procedurally compute values (rendering)
Rasterization
• A fundamental computer graphics function
• Determine the pixels’ colors, illuminations, textures, etc.
• Implemented by graphics hardware
• Rasterization algorithms
• Lines
• Circles
• Triangles
• Polygons
Rasterization Operations
• Drawing lines on the screen
• Manipulating pixel maps (pixmaps): copying, scaling, rotating,
etc
• Compositing images, defining and modifying regions
• Drawing and filling polygons
• Previously glBegin(GL_POLYGON), etc
• Aliasing and anti-aliasing methods
Line drawing algorithm
• Programmer specifies (x,y) values of end pixels
• Need algorithm to figure out which intermediate pixels are on line path
• Pixel (x,y) values constrained to integer values
• Actual computed intermediate line values may be floats
• Rounding may be required. E.g. computed point
(10.48, 20.51) rounded to (10, 21)
• Rounded pixel value is off actual line path (jaggy!!)
• Sloped lines end up having jaggies
• Vertical, horizontal lines, no jaggies
Line Drawing Algorithm
Line: (3,2) -> (9,6)

6
5
? Which intermediate
4
pixels to turn on?
3
2
1

0 1 2 3 4 5 6 7 8 9 10 11 12
Line Drawing Algorithm
• Slope-intercept line equation
• y = mx + b Equation of Line where m is slope & b is intercept
• Given two end points (x0,y0), (x1, y1), how to compute m and b?
dy y1  y 0 b  y 0  m * x0
m 
dx x1  x0

(x1,y1)
dy

(x0,y0)
dx
Line Drawing Algorithm
• Numerical example of finding slope m:
• (Ax, Ay) = (23, 41), (Bx, By) = (125, 96)

By  Ay 96  41 55
m    0.5392
Bx  Ax 125  23 102
Digital Differential Analyzer (DDA): Line
Drawing Algorithm
Walk through the line, starting at (x0,y0)

Constrain x, y increments to values in [0,1] range

Case a: x is incrementing faster (m < 1)


 Step in x=1 increments, compute and round y (x1,y1)
dy
Case b: y is incrementing faster (m > 1)
(x0,y0)
 Step in y=1 increments, compute and round x dx
DDA Line Drawing Algorithm (Case a: m <
1) x = x0 y = y0

y k 1  y k  m Illuminate pixel (x, round(y))


(x1,y1)
x = x0 + 1 y = y0 + 1 * m

Illuminate pixel (x, round(y))

x=x+1 y=y+1*m

Illuminate pixel (x, round(y))

Until x == x1
(x0, y0)
DDA Line Drawing Algorithm (Case b: m >
1)
1 x = x0 y = y0
x k 1  xk  (x1,y1)
m Illuminate pixel (round(x), y)

y = y0 + 1 x = x0 + 1 * 1/m

Illuminate pixel (round(x), y)

y=y+1 x = x + 1 /m

Illuminate pixel (round(x), y)

(x0,y0) Until y == y1
DDA Line Drawing Algorithm Pseudocode
compute m;
if m < 1:
{
float y = y0; // initial value
for(int x = x0;x <= x1; x++, y += m)
setPixel(x, round(y));
}
else // m > 1 or m = 1
{
float x = x0; // initial value
for(int y = y0;y <= y1; y++, x += 1/m)
setPixel(round(x), y);
} Note: setPixel(x, y) writes current color into pixel in column x and row y in
frame buffer
Draw a line from (1,1) to (8,7)
Assignment
DDA Line Drawing Algorithm
Drawbacks
• DDA is the simplest line drawing algorithm
• Not very efficient
• Round operation is expensive
• Optimized algorithms typically used.
• Integer DDA
• Eg. Bresenham algorithm (Hill, 10.4.1)
• Bresenham algorithm
• Incremental algorithm: current value uses previous value
• Integers only: avoid floating point arithmetic
• Several versions of algorithm: we’ll describe midpoint version of
algorithm
Bresenham’s Line-Drawing Algorithm
• Accurate and efficient
• Uses only incremental integer calculations

 The method is described for a line segment with a positive slope less
than one
 The method generalizes to line segments of other slopes by
considering the symmetry between the various octants and quadrants
of the xy plane
Bresenham’s Line-Drawing Algorithm

• Decide what is the


13 Specified next pixel position
line path
• (11,11) or (11,12)
12

11

10

10 11 12 13
Bresenham’s Line-Drawing Algorithm

yk+3 • For the pixel position


xk+1=xk+1, which one we
yk+2
y=mx+b should choose:
yk+1 • (xk+1,yk) or (xk+1, yk+1)
yk

xk xk+1 xk+2 xk+3


Bresenham’s Approach
• y=m(xk + 1)+b
yk+1
dupper
y
• dlower=y-yk
dlower =m(xk + 1)+b-yk
yk

• dupper=(yk+1)-y
xk+1
= yk+1 -m(xk + 1)-b
• dlower- dupper= 2m(xk + 1)-2yk+2b-1
• Rearrange it to have integer calculations:
m=Δy/Δx
Decision parameter: pk= Δx(dlower- dupper)=2Δy.xk - 2Δx. yk + c
The Decision Parameter
Decision parameter: pk= Δx(dlower- dupper)=2Δy.xk - 2Δx. yk + c

• pk has the same sign with dlower- dupper since Δx>0.


• c is constant and has the value c= 2Δy + Δx(2b-1)
• c is independent of the pixel positions and is eliminated from decision parameter pk.
• If dlower< dupper then pk is negative.
• Plot the lower pixel (East)
• Otherwise
• Plot the upper pixel (North East)
Successive decision parameter
• At step k+1
pk+1= 2Δy.xk+1 - 2Δx. yk+1 + c

• Subtracting two subsequent decision parameters yields:


pk+1-pk= 2Δy.(xk+1-xk) - 2Δx. (yk+1-yk)
• xk+1=xk+1 so
pk+1= pk + 2Δy - 2Δx. (yk+1-yk)
• yk+1-yk is either 0 or 1 depending on the sign of pk
• First parameter p0
• p0=2 Δy - Δx
Bresenham's Line-Drawing Algorithm for |m| < 1

1. Input the twoline endpoints and store the left endpoint in (x0 ,y0).
2. Load (x0 ,y0) into the frame buffer; that is, plot the first point.
3. Calculate constants Δx, Δy, 2Δy, and 2Δy - 2Δx, and obtain the starting value for the decision
parameter as
p0=2 Δy - Δx
4. At each xk along the line, starting at k = 0, perform the following test:
If pk < 0, the next point to plot is (xk+1, yk) and
pk+1=pk + 2Δy
Otherwise, the next point to plot is (xk+1, yk+1) and
pk+1=pk + 2Δy - 2Δx
5. Repeat step 4 Δx -1 times.
Trivial Situations: Do not need Bresenham

 m0  horizontal line


 m  1  line y   x
 m  vertical line
Example
• Draw the line with endpoints (20,10) and (30, 18).
• Δx=30-20=10, Δy=18-10=8,
• p0 = 2Δy – Δx=16-10=6
• 2Δy=16, and 2Δy - 2Δx=-4
• Plot the initial position at (20,10), then
Example
Example
• Line end points: ( x0 , y0 )  (5,8); ( x1 , y1 )  (9,11)
• Deltas:
dx  4; dy  3

initially p (5,8)  2(dy )-(dx)


 64  2  0
p  2  NE
Pseudocode
/* Bresenham line-drawing procedure for |m| < 1.0. */
void lineBres (int x0, int y0, int xEnd, int yEnd)
{
int dx = fabs (xEnd - x0), dy = fabs(yEnd - y0);
int x, y, p = 2 * dy - dx;
int twoDy = 2 * dy, twoDyMinusDx = 2 * (dy - dx);
/* Determine which endpoint to use as start position. */
if (x0 > xEnd) {
x = xEnd; y = yEnd; xEnd = x0;
}
else {
x = x0; y = y0;
}
setPixel (x, y);
Pseudocode
while (x < xEnd) {
x++;
if (p < 0)
p += twoDy;
else {
y++;
p += twoDyMinusDx;
}
setPixel (x, y);
}
}
Circle Generation with mid-point
• Implicit: f(x,y) = x2+y2-R2
If f(x,y) = 0 then it is on the circle.
f(x,y) > 0 then it is outside the circle.
f(x,y) < 0 then it is inside the circle.

Let Us try to adapt the Bresenham midpoint


approach
Again, exploit symmetries
Circle Symmetry
Generalising the Bresenham midpoint
approach
• Set up decision parameters for finding the closest pixel to the cırcumference at
each sampling step
• Avoid square root calculations by considering the squares of the pixel separation distances
• Use direct comparison without squaring.
Adapt the midpoint test idea: test the halfway position between pixels to
determine if this midpoint is inside or outside the curve
This gives the midpoint algorithm for circles
Can be adapted to other curves: conic sections
Eight-way Symmetry
only one octant’s calculation needed
The 2nd Octant is a good arc to draw

• Decision variable d is x 2 + y 2 – r 2
• Implicit formulation F(x,y) = x 2 + y 2 – r 2

• For (x,y) on the circle, F(x,y) = 0


• F(x,y) > 0  (x,y) Outside
• F(x,y) < 0  (x,y) Inside
F (M) >= 0  SE
current
pixel E
ideal
curve M

SE
F (M) < 0  E

E
ideal
curve
M

SE
As in the Bresenham line algorithm we use a decision
variable to direct the selection of pixels.
Use the implicit form of the circle equation
p = F (M ) = x 2 + y 2 – r 2
Candidate pixels are () and (- 1) Midpoint coordinates are (-
1/2)
Assuming we have just plotted point at (xk,yk) we determine whether move E or SE by
evaluating the circle function at the midpoint between the two candidate pixel positions
1
𝑝 𝑘=𝐹 𝑐𝑖𝑟𝑐 (𝑥𝑘 +1, 𝑦 𝑘 − )
2
pk is the decision variable
if pk <0 the midpoint is inside the circle
Thus the pixel above the midpoint is closer to the ideal circle, and we select pixel on
scan line yk. i.e. Go E
If pk >0 the midpoint is outside the circle.
Thus the pixel below the midpoint is closer to the ideal circle, and we select pixel
on scan line yk-1. i.e. Go SE

Calculate successive decision parameter values p by incremental calculations.

1
𝑝 𝑘+1=𝐹 𝑐𝑖𝑟𝑐 (𝑥 𝑘+1+1, 𝑦 𝑘+1 − )
2
recursive definition for successive decision parameter values p

( )

Where yk+1 = yk if p<0 (move E)


yk+1 = yk-1 if p>0 (move SE) yk+1 and xk+1 can also be defined
recursively
Initialisation

x0 = 0, y0 = r
Initial decision variable found by evaluating circle function at first midpoint test
position

p0  Fcirc (1, r  1 )
2
 1  (r  1 ) 2  r 2
2
5
 r
4
For integer radius r p0 can be rounded to p0 =1-r
since all increments are integer.
• r=10
Let us see one
example
For Circle drawing keep this table handy.
• End of Module 1

You might also like