Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CG Unit1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 126

UNIT I GRAPHICS PRIMITIVES AND SCAN

CONVERSION ALGORITHMS

1
CONTENT OF UNIT 1
Introduction, graphics primitives - pixel, resolution, aspect
ratio, frame buffer. Display devices, applications of
computer graphics.
Introduction to OpenGL - OpenGL architecture, primitives
and attributes, simple modelling and rendering of two-
and three-dimensional geometric objects, GLUT,
interaction, events and call-backs picking. (Simple
Interaction with the Mouse and Keyboard)
Scan conversion: Line drawing algorithms: Digital
Differential Analyzer (DDA), Bresenham. Circle drawing
algorithms: DDA, Bresenham, and Midpoint.
Computer Graphics
⚫ The computer is an information processing machine. It is a tool for
storing, manipulating and correlating data.
⚫ There are many ways to communicate the processed information to the
user.
⚫ The computer graphics is one of the most effective and commonly
used ways to communicate the processed information to the user.
⚫ It displays the information in the form of graphics objects such as
pictures, charts, graphs and diagrams instead of simple text.
⚫ Thus we can say that computer graphics makes it possible to express data
in pictorial form.
⚫ The picture or graphics object may be an engineering drawing, business
graphs, architectural structures, a single frame from an animated movie
or a machine parts illustrated for a service manual.
Advantages of Computer Graphics
⚫ Ahigh quality graphics displays of personal computer provide one
of the most natural means of communicating with a computer.
⚫ It has an ability to show moving pictures, and thus it is possible to
produce animations with computer graphics.
⚫ With computer graphics use can also control the animation by
adjusting the speed, the portion of the total scene in view, the
geometric relationship of the objects in the scene to one another,
the amount of detail shown and so on.
⚫ The computer graphics also provides facility called update
dynamics.
⚫ With update dynamics it is possible to change the shape, color
or other properties of the objects being viewed.
Applications of Computer Graphics

⚫ User interfaces: It is now a well established fact that


graphical interfaces provide an attractive and easy interaction
between users and computers.The built-in graphics provided
with user interfaces use visual control items such as buttons,
menus, icons , scroll bar etc, which allows user to interact
with computer only by mouse-click. Typing is necessary
only to input text to be stored and manipulated.
⚫ Plotting of graphics and chart: In industry, business,
government, and educational organizations, computer graphics is
most commonly used to create 2D and 3D graphs of mathematical,
physical and economic functions in form of histograms, bars and pie-
charts.These graphs and charts are very useful for decision making.

⚫ Computer-aided drafting and design: The computer aided


drafting uses graphics to design components and systems electrical,
mechanical, electromechanical and electronic devices such as
automobile bodies, structures of building, airplane, ships very large scale
integrated chips, optical systems and computer networks.
⚫ Simulation and Animation: Use of graphics in simulation
makes mathematic models and mechanical systems more
realistic and easy to study.The interactive graphics
supported byanimation software proved their use in
production of animated movies and cartoons films.
⚫ Art and Commerce: There is a lot of development in the
tools provided by computer graphics. This allows user to
create artistic pictures which express message and attract
attentions. Such pictures are very useful in advertising.
⚫ Process Control: By the use of computer now it is
possible to control various processes in the industry from
a remote control room. In such cases, process systems and
processing parameters are shown on the computer with
graphic symbols and identifications.This makes it easy for
operator to monitor and control various processing
parameters at a time.
⚫ Cartography: Computer graphics is also used to represent
geographic maps, weather maps, oceanographic charts,
counter maps, population density maps and so on.

⚫ Image processing: in computer graphics, a computer


is used to create pictures. Image processing, on the other
hands, applies techniques to modify or interpret existing
picture such as photographs and scanned image.
⚫ Education and training: computer graphics can be
used to generate models of physical aids. Models of physical
systems, physiological systems, population trends, or
equipment, such as color coded diagram can help trainees to
understand the operation of the system.
Pixel
⚫ In computer graphics, pictures or graphics objects are
presented as a collection of discrete picture elements called
pixels.
⚫ The pixel is the smallest addressable screen element.
⚫ It is the smallest piece of the display screen which we can
control.
⚫ The control is achieved bysetting the intensity and color of
the pixel which compose the screen.
⚫ Each pixel on the graphics display does not represent
mathematical point. Rather, it represents a region which
theoretically can contain an infinite number of points.
Frame Buffer
⚫ The frame buffer is the video memory that is used to hold or
map the image that display on the screen.
⚫ The portion of the memory reserved for holding the
bitmapped image that is sent to the display device is called as
frame buffer.
⚫ Picture definition is stored in memory area called the refresh
buffer or frame buffer.
⚫ Aframe buffer with one bit/pixel is called bitmap. Aframe
buffer with multiple bits/pixel is called pixmap.
⚫ The information in the buffer typically consists of color
values for every pixel(point that can be)displayed on the
screen.
⚫ Aframebuffer (frame buffer,or sometimes framestore)
is a portion of random-access memory (RAM) containing
a bitmap that drives a video display.
⚫ The information in the buffer typically consists of color
values for every pixel to be shown on the display.
⚫ Color values are commonly stored in 1
bit binary (monochrome), 4-bit palettized, 8-bit palettized,
16-bit high color and 24-bit true color formats.
Aspect Ratio
⚫ Aspect ratio is the ratio of width to height.
⚫ In computer graphics, the relative horizontal and vertical
sizes.
⚫ For example, if a graphic has an aspect ratio of 2:1, it

means that the width is twice as large as the height.


⚫ When resizing graphics, it is important to maintain
the aspect ratio to avoid stretching the graphic out of
proportion.
⚫ The term is also used to describe the dimensions of a display
resolution. For example, aresolution of 800x600 has an
aspect ratio of 4:3.
Resolution
⚫ Resolution Refers to the sharpness and clarity of an image.
⚫ It refers to the number of dots on the screen.
⚫ It is expressed asapair of numbers that give the number of
dots on a horizontal line and the number such vertical lines.
⚫ Four resolutions are in common use today.
1. 640*480
2. 800*600
3. 1024*768
4. 1280*1024
⚫ The term is most often used to describe monitors, printers,
and bit-mapped graphic images.
Color Depth
⚫ Color depth(number of colors) is determined by the
number of bits assigned to hold color value.
⚫ The number of bits used to hold a screen pixel.Also called
"pixel depth" and "bit depth," the color depth is the
maximum number of colors that can be displayed.
1. 1 bit-2 colors(black n white)
2. 4 bits-16 colors
3. 8 bits-256 colors
4. 16 bits -32 thousand colors
5. 24 bits- 16 million (high color)
6. 32 bits- latest(true color)
Refresh rate
⚫ Refresh rate is nothing but the speed by which a particular
dot on the screen is getting printed.
⚫ The refresh rate is the number of times a display's image is
repainted or refreshed per second.
⚫ The refresh rate is expressed in hertz so a refresh rate of
75 means the image is refreshed 75 times in a second.
⚫ The refresh rate for each display depends on the video card
used.
Accelerator

⚫ Accelerator chip is an integrated chip existing on the display


adapter.
⚫ It is used to draw readymade shapes like drawing lines and
boxes, filling the color in the box, filling the background
color and managing the mouse pointer.
Display Devices
⚫ There are several hardware devices which may be used to
display images.
1. Video Display Devices:
There are two types of video monitors-
i. Monochrome display monitor
ii. Color display monitor
⚫ Let us first see the Monochrome display monitor(Black n
White).
⚫ Display devices are also known as output devices.
⚫ Most commonly used output device in a graphics system is
video monitor.
CRT

Monochrome
Color CRT
CRT

Raster Scan Random Scan


(Shadow Mask) (Beam penetration method)
Monochrome display monitor
⚫ There are two techniques used for producing images on the
CRT screen.
1. Vector scan/Random scan display
2. Raster scan display
Raster Scan Display
Buffers in Raster Display
Random/Vector Scan Display
⚫ Advantages:
a) They operate at any resolution, geometry and aspect ratio
without the need for rescaling the image.
b) CRTs run at the highest pixel resolutions generally available.
c) Produce a very dark black and the highest contrast levels
normally available. Suitable for use even in dimly lit or dark
environments.
d)CRTs produce the very best color and gray-scale and are the
reference standard for all professional calibrations. They have
a perfectly smooth gray-scale with an infinite number of
intensity levels. Other display technologies are expected to
reproduce the natural power-law Gamma curve of a CRT,
but can only do so approximately.
e) CRTs have fast response times and no motion artifacts. Best
for rapidly moving or changing images.
f) CRTs are less expensive than comparable displays using
other display technologies.
Color Display Monitor
Introduction to OpenGL -
⚫ OpenGL is a software interface that allows the
programmer to create 2D and 3D graphics images.
⚫ OpenGL is both a standard API and the
implementation of that API.
⚫ OpenGL is independent of the hardware, operating,
and windowing systems in use.
⚫ The fact that it is windowing-system independent,
makes it portable.
⚫ OpenGL program must interface with the
windowing system of the platform where the
graphics are to be displayed.
⚫ OpenGL's rendering commands, however are
"primitive".You can tell the program to draw
points, lines, and polygons, and you have to build
more complex entities upon these.
⚫ There are no special-purpose functions that you can
call to create graphs, contour plots, maps, or any of
the other elements we are used to getting from "old
standby programs”.
Why OpenGL?
• Device independence
• Platform independence
– SGI Irix, Linux, Windows
• Abstractions (GL, GLU, GLUT)
• Open source
• Hardware-independent software
interface
• Support of client-server protocol
• Other APIs
– OpenInventor (object-oriented toolkit)
– DirectX (Microsoft), Java3D (Sun)
Graphics Programming
using OpenGL
Brief Overview of OpenGL

OpenGL is a software interface that allows the programmer to


create 2D and 3D graphics images. OpenGL is both a standard API and
the implementation of that API. You can call the functions that comprise
OpenGL from a program you write and expect to see the same results no
matter where your program is running.

OpenGL is independent of the hardware, operating, and windowing


systems in use. The fact that it is windowing-system independent, makes
it portable. OpenGL program must interface with the windowing system of
the platform where the graphics are to be displayed. Therefore, a number
of windowing toolkits have been developed for use with OpenGL.

OpenGL functions in a client/server environment. That is, the


application program producing the graphics may run on a machine other
than the one on which the graphics are displayed.The server part of
OpenGL, which runs on the workstation where the graphics are displayed,
can access whatever physical graphics device or frame buffer is available
on that machine.
OpenGL's rendering commands, however are "primitive". You can tell the
program to draw points, lines, and polygons, and you have to build more complex
entities upon these. There are no special-purpose functions that you can call to
create graphs, contour plots, maps, or any of the other elements we are used to
getting from "old standby programs”. With OpenGL, you have to build these
things up yourself.

With OpenGL any commands that you execute are executed immediately.
That is, when you tell the program to draw something, it does it right away. You
also have the option of putting commands into display lists. A display list is a not-
editable list of OpenGL commands stored for later execution. You can execute the
same display list more than once. For example, you can use display lists to
redraw the graphics whenever the user resizes the window. You can use a display
list to draw the same shape more than once if it repeats as an element of the
picture.

OpenGL is hardware-independent. Many different vendors have written


implementations that run on different hardware. These implementations are all
written to the same OpenGL standard and are required to pass strict conformance
tests. Vendors with licenses include SGI, AT&T, DEC, Evans & Sutherland,
Hitachi, IBM, Intel, Intergraph, Kendall Square Research, Kubota Pacific,
Microsoft, NEC, and RasterOps. The RS/6000 version comes with X and Motif
extensions. However X is not required to run OpenGL since OpenGL also
runs with other windowing systems.
Features in OpenGL
⚫ 3DTransformations
- Rotations, scaling, translation, perspective
⚫ Colour models
-Values: R, G, B, alpha.
⚫ Lighting
- Flat shading, Gouraud shading, Phong shading
⚫ Rendering
-Texture mapping
⚫ Modeling
- non-uniform rational B-spline (NURB) curves, surfaces
OpenGL Operation
Display
List
Per- Rasteri-
Vertex zation
Eval- Opns. &
Comm- uator primitive Per-
ands assembly fragment
opns.
Pixel
opns. Texture
memory
What is to be Frame
drawn? buffer
How it is to be
drawn?
OpenGL Operation
Can accumulate some
commands in a display list
for processing at a later
Display time (Batch mode). Or can
Lists proceed immediately
through the pipeline
Per-
Comm- Per-
Eval- Vertex Rasteri-
ands frag-
uator Opns. & zation ment
primitive
opns.
assembly
Texture
Pixel
memory
opns.
Frame
buffer
OpenGL Provides an efficient means
for approximating curve
Operation and surface geometry by
evaluating polynomial
Display
commands of input values
Lists

Per- Per-
Eval- Vertex Raster- frag-
Comm- uator ization ment
opns. &
ands opns.
primitive
assembly
Texture
Pixel memory
opns.
Frame
buffer
OpenGL Process geometric primitives -
points, line segments, and
Operation polygons as vertices and are
transformed, lit, and clipped
Display to the viewport in preparation
Lists for the next stage.

Per- Per-
Comm- Eval- Raster- frag-
ands Vertex
uator opns. & ization ment
primitive opns.
assembly
Texture
Pixel memory
opns.
Frame
buffer
OpenGL Produces a series of
frame buffer addresses
Operation and associated values
using a two-dimensional
Display description of a point,
Lists line segment, or polygon

Per- Per-
Eval- Vertex Raster- frag-
Comm- uator ization ment
ands opns &
primitive opns.
assembly
Texture
Pixel memory
opns.
Frame
buffer
OpenGL Z-buffering, and blending
of incoming pixel colors
Operation with stored colors, and
masking and other logical
Display
operations on pixel values
Lists

Per- Per-
Eval- Vertex Raster- frag-
Comm- uator ization ment
opns &
ands opns.
primitive
assembly
Texture
Pixel memory
opns.
Frame
buffer
OpenGL Input data can be in
the form of pixels
Operation (image for texture
mapping) is processed
Display
in the pixel operations
Lists
stage.
Per- Per-
Eval- Vertex Raster- frag-
Comm- uator ops & ization ment
ands primitive opns
assembly
Texture
Pixel memory
opns
Frame
buffer
⚫ Commands: what is to be drawn? How it is to be drawn?
⚫ Display list: Can accumulate some commands in a display
list for processing at alater time (Batch mode). Or can
proceed immediately through the pipeline.
⚫ Evaluators: Provides an efficient means for approximating
curve and surface geometry by evaluating polynomial
commands of input values.
⚫ Per- Vertex opns. & Primitive assembly: Process
geometric primitives -points, line segments, and polygons as
vertices and are transformed, lit, and clipped to the viewport
in preparation for the next stage.
⚫ Rasterization: Produces a series of frame buffer addresses
and associated values using a two-dimensional description of
a point, line segment, or polygon.
⚫ Perfragment oprations:Z-buffering, and blending of
incoming pixel colors with stored colors, and masking and
other logical operations on pixel values.
⚫ Pixel oprations:Input data can be in the form of pixels
(image for texture mapping) is processed in the pixel
operations stage.
Abstractions
• Windowing toolkit (key, mouse
GLUT handler, window events)

• Viewing –perspective/orthographic
GLU • Image scaling, polygon tessellation
• Sphere, cylinders, quadratic surfaces

• Primitives - points, line, polygons


GL • Shading and Colour
• Translation, rotation, scaling
• Viewing, Clipping, Texture
• Hidden surface removal
OpenGL Drawing Primitives

OpenGL supports several basic primitive types, including points,


lines, quadrilaterals, and general polygons. All of these primitives are
specified using a sequence of vertices.

glVertex2i(Glint xi, Glint yi);


glVertex3f(Glfloat x, Glfloat y, Glfloat z);
Glfloat vertex[3];

glBegin(GL_LINES);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glEND();

Define a pair of points as:

glBegin(GL_POINTS);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glEND();
The numbers indicate the order in which the vertices have been specified.
Note that for the GL_LINES primitive only every second vertex causes a line
segment to be drawn. Similarly, for the GL_TRIANGLES primitive, every third vertex
causes a triangle to be drawn. Note that for the GL_TRIANGLE_STRIP and
GL_TRIANGLE_FAN primitives, a new triangle is produced for every additional
vertex. All of the closed primitives shown below are solid-filled, with the exception
of GL_LINE_LOOP, which only draws lines connecting the vertices.
The following code fragment illustrates an example of how the
primitive type is specified and how the sequence of vertices are
passed to OpenGL. It assumes that a window has already been opened
and that an appropriate 2D coordinate system has already been
established.

// draw several isolated points

GLfloat pt[2] = {3.0, 4.0};


glBegin(GL_POINTS);
glVertex2f(1.0, 2.0); // x=1, y=2
glVertex2f(2.0, 3.0); // x=2, y=3
glVertex2fv(pt); // x=3, y=4
glVertex2i(4,5); // x=4, y=5
glEnd();
The following code fragment specifies a 3D polygon to be drawn,
in this case a simple square. Note that in this case the same square could
have been drawn using the GL_QUADS and GL_QUAD_STRIP primitives.

GLfloat p1[3] = {0,0,1};


GLfloat p2[3] = {1,0,1};
GLfloat p3[3] = {1,1,1};
GLfloat p4[3] = {0,1,1};

glBegin(GL_POLYGON);
glVertex3fv(p1);
glVertex3fv(p2);
glVertex3fv(p3);
glVertex3fv(p4);
glEnd();
3D Viewing Pipeline
object world clip
coordinates coordinates coordinates

VM P
v1,v2,…, vN clip
modelview projection
matrix matrix
normalized device window
coordinates coordinates

VP
perspective
viewport matrix
division
From F. S. Hill Jr., Computer Graphics using OpenGL
OpenGL functions for setting up transformations

modelling transformation
(modelview matrix)
glTranslatef()
glRotatef()
glScalef()

viewing transformation
(modelview matrix)
gluLookAt()

projection transformation
(projection matrix)
glFrustum()
gluPerspective()
glOrtho()
gluOrtho2D()

viewing transformation
glViewport()
Structure of a GLUT Program
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE |
GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Interactive rotating
cube"); // with size & position
glutDisplayFunc(display);
// display callback, routines for drawing
glutKeyboardFunc(myKeyHandler);
// keyboard callback
glutMouseFunc(myMouseClickHandler);
// mouse callback
glutMotionFunc(myMouseMotionHandler);
// mouse move callback
init();
glutMainLoop();
}
void display() {...}
void myKeyHandler( unsigned char key, int x,
int y) {...}
void myMouseClickHandler( int button, int
state, int x, int y ) {...}
void myMouseMotionHandler( int x, int y) {...}
glutInitDisplaymode()

Before opening a graphics window, we need to decide on the


`depth' of the buffers associated with the window. The following table
shows the types of parameters that can be stored on a per-pixel basis:

The various GLUT_* options are invoked together by OR-ing them


together, as illustrated in the example code, which creates a graphics
window which has only a single copy of all buffers (GLUT_SINGLE), does
not have an alpha buffer (GLUT_RGB), and has a depth buffer
(GLUT_DEPTH).

RGB Red, green and blue, GLUT_RGB


Typically 8 bits per pixel
A Alpha or accumulation buffer, GLUT_RGBA
Used for composting images
Z Depth value, used for GLUT_DEPTH
Z-buffer visibility tests
Double buffer Extra copy of all buffers, GLUT_DOUBLE
Used for smoothing animation
Stencil buffer Several extra bits, GLUT_STENCIL
Useful in composting images
glutInitWindowPosition(), glutInitWindowSize(), glutCreateWindow()

These calls assign an initial position, size, and name to the window
and create the window itself.

glClearColor(), glMatrixMode(), glLoadIdentity(), glOrtho()

glClearColor() sets the colour to be used when clearing the window. The
remaining calls are used to define the type of camera projection. In this
case, an orthographic projection is specified using a call to
glOrtho(x1,x2,y1,y2,z1,z2). This defines the field of view of the camera, in
this case 0<=x<=10, 0<=y<=10, -1<=z<=1.

glutDisplayFunc(display), glutMainLoop()

This provides the name of the function you would like to have
called whenever glut thinks the window needs to be redrawn. Thus, when
the window is first created and whenever the window is uncovered or
moved, the user-defined display() function will be called.

glutDisplayFunc() registers the call-back function, while glutMainLoop()


hands execution control over to the glut library.
Viewing in 2D
void init(void) {
glClearColor(0.0, 0.0, 0.0, 0.0);
glColor3f(1.0f, 0.0f, 1.0f);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

gluOrtho2D(
0.0, // left
screenWidth, // right
0.0, // bottom
screenHeight); // top
}
Drawing in 2D
GL_LINES
glBegin(GL_POINTS); glVertex2d(x1, y1);
GL_LINE_STRIP
glVertex2d(x2, y2); GL_LINE_LOOP
. GL_POLYGON

.
.
glVertex2d(xn, yn); glEnd();
Drawing a square in OpenGL

The following code fragment demonstrates a very simple OpenGL


program which opens a graphics window and draws a square. It also
prints 'helllo world' in the console window. The code is illustrative of the
use of the glut library in opening the graphics window and managing the
display loop.

glutInit()

Following the initial print statement, the glutInit() call initializes the
GLUT library and also processes any command line options related to
glut. These command line options are window-system dependent.

display()

The display() call-back function clears the screen, sets the


current colour to red and draws a square polygon. The last call, glFlush(),
forces previously issued OpenGL commands to begin execution.
Assigning Colours

OpenGL maintains a current drawing colour as part of


its state information.

The glColor() function calls are used to change the


current drawing colour - assigned using the glColor function
call.

Like glVertex(), this function exists in various


instantiations. Colour components are specified in the order of
red, green, blue. Colour component values are in the range
[0...1], where 1 corresponds to maximum intensity.

For unsigned bytes, the range corresponds to [0...255].


All primitives following the fragment of code given below
would be drawn in green, assuming no additional glColor()
function calls are used.
Assigning Colours
Current drawing colour maintained as a
state.
Colour components - red, green, blue in
range [0...1] as float or [0…255] as unsigned
byte
GLfloat myColour[3] = {0, 0, 1}; // blue

glColor3fv( myColour ); // using vector of


floats

glColor3f(1.0, 0.0, 0.0); // red using floats

glColor3ub(0, 255, 0); // green using


unsigned bytes
A fourth value called alpha is often appended to the colour
vector. This can be used assign a desired level of transparency to a
primitive and finds uses in compositing multiple images together. An
alpha value of 0.0 defines an opaque colour, while an alpha value of 1.0
corresponds to complete transparency.

The screen can be cleared to a particular colour as follows:

glClearcolor(1.0, 1.0, 1.0, 0.0); // sets the clear colour to


white and opaque

glClear( GL_COLOR_BUFFER_BIT); // clears the colour


frame buffer
Line Drawing Algorithms
1. DDA Line Algorithm
2. Bresenham Line Algorithm
DDA Algorithm
1. Introduction
Digital Differential Analyser is an
an algorithm for scan-converting lines
The original differential analyzer
was a physical machine developed by
Vannevar Bush at MIT in the 1930’s
in order to solve ordinary differential equations.
It calculates pixel positions along a line by taking unit step
increment along one direction and calculating corresponding
coordinate position based on the rate of change of the coordinate
(Dx or Dy ) (Incremental Approach)
DDA Algorithm
2. Basic Concept
For each part of the line the following holds true:
Dy
m=  Dy = mDx
Dx
If Dx = 1 i.e. 1 pixel then …
Dy = m
i.e. for each pixel we move right (along the x axis), we need to
move down (along the y-axis) by m pixels.
In pixels, the gradient represents how many pixels we step
upwards (Dy) for every step to the right (Dx)
DDA Algorithm
3. Derivation
Assume that 0<m<1, Dx > 0 and Dy >0
For a point P(xi, yi ) on a line we know that
yi = mxi + b
At next position P(xi+1, yi+1 )
yi+1 = mxi+1+ b
Having unit step increment along x-axis means xi+1 = xi + 1
Therefore yi+1 = m(xi + 1)+ b
= mxi + m + b
= mxi + b + m
= yi + m
DDA Algorithm
4. Simple Algorithm
1. Input (x1,y1) and (x2,y2)
2. Let x = x1; y = y1;
m = (y2-y1)/(x2-x1);
3. Draw pixel (x, y)
4. WHILE (x < x2) //i.e. we reached the
second endpoint
5. {
x = x + 1; //step right by one pixel
y = y + m; //step down by m pixels
Draw pixel (ROUND(x), ROUND(y));
}
DDA ALGORITHM
5. Example
Sample at unit x:
xk +1 = xk + Dx
= xk + 1
Corresponding y pos.:
yk +1 = yk + Dy
= yk + m  Dx
= yk + m  (1)
DDA ALGORITHM
5. Example
Sample at unit x:
xk +1 = xk + Dx
= xk + 1
Corresponding y pos.:
yk +1 = yk + Dy
= yk + m  Dx
= yk + m  (1)
DDA ALGORITHM
5. Example
Sample at unit x:
xk +1 = xk + Dx
= xk + 1
Corresponding y pos.:
yk +1 = yk + Dy
= yk + m  Dx
= yk + m  (1)
DDA ALGORITHM
5. Example
Sample at unit x:
xk +1 = xk + Dx
= xk + 1
Corresponding y pos.:
yk +1 = yk + Dy
= yk + m  Dx
= yk + m  (1)
DDA ALGORITHM
5. Example
Sample at unit x:
xk +1 = xk + Dx
= xk + 1
Corresponding y pos.:
yk +1 = yk + Dy
= yk + m  Dx
= yk + m  (1)
DDA ALGORITHM
5. Example
Sample at unit x:
xk +1 = xk + Dx
= xk + 1
Corresponding y pos.:
yk +1 = yk + Dy
= yk + m  Dx
= yk + m  (1)
DDA ALGORITHM
5. Example
Sample at unit x:
xk +1 = xk + Dx
= xk + 1
Corresponding y pos.:
yk +1 = yk + Dy
= yk + m  Dx
= yk + m  (1)
Consider endpoints:
P1(0,0), P2(7,4)
DDA Algorithm
7. Y-Version (|m|>1)
If the slope is very steep (i.e. Dy is much
greater than Dx) then there’s a problem.
i.e. m is much greater than 1

This is because we only draw one pixel


for each x value (each time we step
right)

Solution: if the slope is too big, step for


y instead
DDA Algorithm
8. Generic solution
Modify Basic idea Dy = mDx m0
1
Dx = Dy
m
Take unit step increment along direction having more rate of change, and
compute the coordinates for the other position to maximize the number of
points to be computed along the path of line and avoid discontinuities

xi + 1 := xi + 1
yi + 1 := yi + m 0  m 1

or Why?
yi + 1 := yi + 1
1
xi + 1 := xi + 1 m
m
discontinuity !!
DDA Algorithm - Generic solution

What is m<0 ?
We must see the sign of Dx and Dy

Various Dx>0 Dx>0 Dx<0 Dx<0


Cases Dy>0 Dy<0 Dy>0 Dy<0

xi+1 = xi + 1 xi+1 = xi + 1 xi+1 = xi - 1 xi+1 = xi - 1


|m|<1 yi+1 = yi + m yi+1 = yi - m yi+1 = yi + m yi+1 = yi – m
(or swap points)
xi+1 = xi + xi+1 = xi + 1/m xi+1 = xi - xi+1 = xi - 1/m
|m|>1 1/m yi+1 = yi - 1 1/m yi+1 = yi – 1
yi+1simple
Or can we have = yi + 1solution??????? yi+1 = yi + 1 (or swap points)
DDA Algorithm
1. Input (x1,y1) and (x2,y2)
2. Compute
dx = x2-x1 and dy = y2-y1
m = dx/dy
3. If abs(dx)>abs(dy)
step = abs(dx)
else
step = abs(dy)
4. Compute xinc = dx/step
yinc = dy/step
5. Initialize x = x1 and y = y1
6. Draw pixel (x, y)
7. For k = 1 to steps do //we reach the other endpoint
{
x = x + xinc;
y = y + yinc;
Draw pixel (ROUND(x), ROUND(y));
}
DDA Algorithm

8. Limitations
Rounding integers takes time

Variables y and m must be a real or fractional binary because the


slope is a fraction

Real variables have limited precision, summing an inexact slope m


repetitively introduces a cumulative error buildup
DDA Algorithm
X Y Rounded { x, y }
Rounding Error
Note that the actual pixel position is 1.0 0.33 { 1, 0 }
actually stored as a REAL number (in
C/C++/java a float or a double) 2.0 0.66 { 2, 0 }

3.0 0.99 { 3, 1 }
But we Round Off to the nearest whole
number just before we draw the pixel. 4.0 1.32 { 4, 1 }

e.g. if m=.333 …
Bresenham’s Line Algorithm
1. Introduction
One disadvantage of DDA is the ROUNDing part which can be
expensive
Developed by Jack Bresenham
at IBM in the early 1960s
One of the earliest algorithms in
computer graphics
The Algorithm is based on essentially
the same principles but is completely
based on integer variables
Bresenham’s Line Algorithm
2. Basic Concept
Find the closest integer coordinates to the actual line path using
only integer arithmetic
Candidate for the next pixel position

Specified
Line Path
0  m 1
Specified
No division, Efficient comparison, No floating point operations
Line Path
Bresenham’s Line Algorithm

3. Derivation
The algorithm is derived for a line having slope 0< m < 1 in
the first quadrant.
Pixel position along the line are plotted by taking unit step
increments along the x-direction and determining y-
coordinate value of the nearest pixel to the line at each step.
Can be generalized for all the cases
Bresenham’s Line Algorithm
Let us assume that P(xk, yk ) is the currently plotted pixel. Q(xk+1,
yk+1 ) (xk+1, y ) is the next point along the actual path of line.
We need to decide next pixel to be plotted from two candidate
positions Q1(xk+1, yk ) or Q2(xk+1, yk+1)

yk + 1 Q2
d2
yk + 2 y Q

yk + 1 Q2 d1
yk P
Q
Q1
y = mx + b yk P
Q1

xk + 1
xk xk + 1 xk + 2
0  m  1, xk  xl , k  l
Bresenham’s Line Algorithm
Given the equation of line
y = mx + b
Thus actual value of y at x = xk+1 is given by
y = mxk+1 + b = m(xk + 1) + b
Let d1 = | QQ1|= distance of yk from actual value of y
= y – yk = m(xk + 1) + b – yk
d2 = | QQ2| = distance of actual value of y from yk +1
= yk+1 – y = (yk + 1)– [m(xk + 1) + b]
The difference between these 2 separations is
d1-d2 = 2m(xk + 1) + 2b –yk– (yk+ 1)
= 2m(xk + 1) – 2 yk + 2b – 1
Bresenham’s Line Algorithm
we can define a decision parameter pk for the kth step to by
simplifying above equation such that the sign of Pk is the same
as the sign of d1-d2, but involves only integer calculations.
Define Pk = Δx ( d1-d2)
= Dx(2m( xk + 1) − 2 yk + 2b − 1)
Dy
= Dx(2 ( xk + 1) − 2 yk + 2b − 1)
Dx
= 2Dy  xk − 2Dx  yk + 2Dy + Dx(2b − 1)
= 2Dy  xk − 2Dx  yk + c
where c = 2 Δy + Δx( 2 b − 1 ) a constant
Bresenham’s Line Algorithm
If pk< 0
 ( d1-d2) <0
 distance d1 is less than d2
 yk is closer to line-path
Hence Q1(xk+1, yk ) is the better choice
else
Q2(xk+1, yk+1) is the better choice

Thus if the parameter pk is negative lower pixel is plotted


else upper pixel is plotted
Bresenham’s Line Algorithm
To put pk in the iterative form, we derived that
pk = 2Dy.xk − 2Dx. yk + c
Replacing k = k + 1
pk + 1 = 2Dy.xk + 1 − 2Dx. yk + 1 + c
subtract pk from pk + 1
pk + 1 − pk = 2Dy ( xk + 1 − xk ) − 2Dx( yk + 1 − yk )
pk + 1 = pk + 2Dy − 2Dx( yk + 1 − yk )
 yk if pk  0
yk + 1 = 
 yk + 1 otherwise
 pk + 2Dy if pk  0
 pk + 1 = 
 pk + 2Dy − 2Dx otherwise
Bresenham’s Line Algorithm
The first parameter p0 is directly computed as:
p0 = 2 Δy.x0 - 2 Δx.y0 + c
= 2 Δy.x0 - 2 Δx.y0 + 2 Δy + Δx (2b-1)

Since (x0,y0) satisfies the line equation , we also have


y0 = Δy/ Δx * x0 + b
b = y0 - Δy/ Δx * x0

Combining the above 2 equations , we will have


p0 = 2Δy – Δx
The constants 2Δy, 2Δy – Δx and 2Δy-2Δx are calculated once.
Bresenham’s Line Algorithm
STEPS FOR BRESENHAM’S LINE DRAWING ALGORITHM (for |m| < 1.0)
1. Input the two line end-points (x0, y0) and (x1, y1)
2. Plot the point (x0, y0)
3. Compute Δx = x1 - x0 , Δy = y1 - y0
4. Initialize p0 = 2Δy – Δx
5. 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)
pk = pk +2Δy
else
the next point to plot is (xk+1, yk+1)
pk = pk +2Δy – 2Δx
6. Repeat step 5 (Δx – 1) times
7. Plot the point (x1, y1)
8. Exit
Bresenham’s Line Algorithm
4. General solution
The algorithm can be generalized for all slopes
Cases/ Case I Case II Case III Case IV
slope Dx>0 , Dy>0 Dx>0, Dy<0 Dx<0, Dy>0 Dx<0, Dy<0
p = 2dy-dx p = 2dy-dx swap points swap points
|m|<1 for x = x1 to x2 for x = x1 to x2
Case II Case I
if p<0 if p<0
p = p+ 2dy p = p+ 2dy
else { y=y+1 else { y=y-1
p = p+2(dy-dx)} p = p+2(dy-dx)}
p = 2dx-dy p = 2dx-dy swap points swap points
for y= y1 to y2 for y= y2 to y1
|m|>1 Case II Case I
if p<0 if p<0
p = p+ 2dx p = p+ 2dx
else { x=x+1 else { x=x+1
p = p+2(dx-dy)} p = p+2(dx-dy)}
Bresenham’s Line Algorithm
5. Exercise
Calculate pixel positions that made up the line connecting endpoints: (12,
10) and (17, 14).
1. (x0, y0) = ?
2. Dx = ?, Dy =?, 2Dy = ?, 2Dy – 2Dx =?
3. p0 = 2Dy – Dx =?

k pk (xk+1, yk+1)
Bresenham’s Line Algorithm
5. Exercise
Calculate pixel positions that made up the line connecting endpoints:
(12, 10) and (17, 14).
1. (x0, y0) = (12,10)
2. Dx = 5, Dy =4, 2Dy = 8, 2Dy – 2Dx =-2
3. p0 = 2Dy – Dx =3

k pk (xk+1, yk+1)
0 3

2
Bresenham’s Line Algorithm
5. Exercise
Calculate pixel positions that made up the line connecting endpoints:
(12, 10) and (17, 14).
1. (x0, y0) = (12,10)
2. Dx = 5, Dy =4, 2Dy = 8, 2Dy – 2Dx =-2
3. p0 = 2Dy – Dx =3
k pk (xk+1, yk+1)
0 3 (13, 11)

1 1 (14, 12)

2 -1 (15, 12)

3 7 (16, 13)

4 5 (17, 14)
Bresenham’s Line Algorithm
5. Exercise: Trace for (20,10) to (30,18)
k pk (xk+1,yk+1)
18
17
16
15
14
13
12
11
10
20 21 22 23 24 25 26 27 28 29 30
Bresenham’s Line Algorithm
Answer
k pk (xk+1,yk+1)
18
0 6 (21,11)
17 1 2 (22,12)
16 2 -2 (23,12)
15 3 14 (24,13)
14 4 10 (25,14)
13 5 6 (26,15)
12 6 2 (27,16)
11 7 -2 (28,16)
10 8 14 (29,17)
20 21 22 23 24 25 26 27 28 29 30 9 10 (30,18)
Circle Drawing Algorithms

1. DDA Circle Algorithm


2. Bresenham’s Circle Algorithm
3. Midpoint Circle Algorithm
Scan Converting Circle
Eight-Way Symmetry
So we can use learned eight-way symmetry to make our circle
drawing algorithm more efficient
Now circle points are computed
only in one octant,
(-x, y) (x, y)
rest of the circle are
found by symmetry.
Centre can be shifted while (-y, x) (y, x)
plotting
R
2
(-y, -x) (y, -x)

(-x, -y) (x, -y)


Scan Converting Circle
We define a routine that plots circle pixels with centre (h,k) in
all the eight octants
put_circle_pixel(x,y,h,k)
{
Put_pixel(h+x, k+y)
Put_pixel(h-x, k+y)
Put_pixel(h-x, k-y)
Put_pixel(h+x, k-y)
Put_pixel(h+y, k+x)
Put_pixel(h-y, k+x)
Put_pixel(h-y, k-x)
Put_pixel(h+y, k-x)
}
DDA Circle Algorithm
DDA Circle Algorithm
Bresenham’s Circle Algorithm
Bresenham’s Circle Algorithm
Bresenham’s Circle Algorithm
Bresenham’s Circle Algorithm

The remaining points can be plotted by 8 way symmetry .


Midpoint Circle Algorithm
1. Introduction
Similarly to the case with lines, there is an incremental algorithm
for drawing circles – the mid-point circle algorithm.
In the mid-point circle algorithm we use implicit equation of the
circle.
Integer calculations are used to compute the circle points in one
octant, rest of the seven points are plotted using eight way
symmetry.
The equations derived will be similar to Bresenham’s circle
algorithm
Midpoint Circle Algorithm
2. Basic Concept
We will first calculate pixel positions for a circle centered around
the origin (0,0). Centre is shifted later on.
Note that along the circle section from x=0 to x=y in the first
octant, the slope of the curve varies from 0 to -1
Circle function around the origin is given by
fcircle(x,y) = x2 + y2 – r2
Any point (x,y) on the boundary of the circle satisfies the
equation and circle function is zero
Midpoint Circle Algorithm
For a point in the interior of the circle, the circle function is
negative and for a point outside the circle, the function is positive
Thus, we have a discriminator function
fcircle(x,y) < 0 if (x,y) is inside the circle boundary
fcircle(x,y) = 0 if (x,y) is on the circle boundary
fcircle(x,y) > 0 if (x,y) is outside the circle boundary
The algorithm does the above test at mid point fcircle(x,y-½), if it lies
inside outer point is plotted, else inner is considered to be the better
choice
Midpoint Circle Algorithm

1 2 3 4
Midpoint Circle Algorithm

M
5

1 2 3 4
Midpoint Circle Algorithm

6
M
5

1 2 3 4
Midpoint Circle Algorithm
3. Derivation
Let us assume that P(xk, yk ) is the
currently plotted pixel. Q(xk+1,
yk+1 )  (xk+1, y ) is the next
point along the actual circle path.
We need to decide next pixel to
be plotted from among candidate
positions Q1(xk+1, yk ) or
Q2(xk+1, yk-1)
Midpoint Circle Algorithm
Our decision parameter is the circle function evaluated at the
midpoint between these two pixels

pk = fcircle (xk +1, yk-1/2) = (xk +1)2 + (yk -1/2)2 – r2

If pk < 0 ,
this midpoint is inside the circle and
the pixel on the scan line yk is closer to the circle boundary.
Otherwise,
the mid position is outside or on the circle boundary,
and we select the pixel on the scan line yk-1
Midpoint Circle Algorithm
Successive decision parameters are obtained using incremental
calculations
pk = (xk +1)2 + (yk – ½ )2 – r2
Put k = k+1
pk+1 = [(xk+1)+1]2 + (yk+1 – ½ )2 – r2
= (xk+2)2 + (yk+1 – ½ )2 – r2
subtracting pk from pk+1
pk+1 – Pk = (xk+2)2 + (yk+1 – ½ )2 – [(xk +1)2 + (yk – ½ )2] or
pk+1 = Pk+2(xk+1) + (yk+1 – ½)2 – (yk – ½)2+1
Where yk+1 is either yk or yk-1, depending on the sign of pk
Midpoint Circle Algorithm
If pk< 0
 Q1(xk+1, yk ) was the next choice
 yk+1 = yk
 (yk+1 – ½)2 – (yk – ½)2= 0
 pk+1 = pk + 2.xk +3
else
Q2(xk+1, yk-1) was the next choice
 yk+1 = yk+1
 (yk+1 – ½)2 – (yk – ½)2 = – 2.yk +2
 pk+1 = pk + 2(xk – yk )+ 5
Midpoint circle algorithm

Initial decision parameter is obtained by evaluating the


circle function at the start position (x0,y0) = (0,r)
p0 = fcircle(1, r – 1/2)
= 1+ (r – 1/2)2 – r2
= 5/4 – r
If radius r is specified as an integer, we can round p0 to
p0 = 1 – r
Midpoint circle algorithm

You might also like