Advertisements
Home > Cpp Graphics > C++ Graphics – 03 – Line program by DDA Algorithm

C++ Graphics – 03 – Line program by DDA Algorithm


Line Program by DDA or Digital differential Analyzer algorithm.

This algorithm is used for linear interpolation of variables over an interval between start and end point.

The DDA starts by calculating the smaller of dy or dx for a unit increment of the other. A line is then sampled at unit intervals in one coordinate and corresponding integer values nearest the line path are determined for the other coordinate.

Considering a line with positive slope, if the slope is less than or equal to 1, we sample at unit x intervals (dx=1) and compute successive y values as

DDA 01

Subscript k takes integer values starting from 0, for the 1st point and increases by 1 until endpoint is reached. y value is rounded off to nearest integer to correspond to a screen pixel.

For lines with slope greater than 1, we reverse the role of x and y i.e. we sample at dy=1 and calculate consecutive x values as

DDA 02

Similar calculations are carried out to determine pixel positions along a line with negative slope. Thus, if the absolute value of the slope is less than 1, we set dx=1 if dda 03 i.e. the starting extreme point is at the left.

#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>

void lineDDA(int x1, int y1, int x2, int y2) {
	int x, y, k;
	float dy = y2-y1;
	float dx = x2-x1;
	int step, xinc, yinc;

	if (abs(dx) > abs(dy))
		step = dx;
	else
		step = dy;

	x = x1;
	y = y1;
	putpixel(x, y, WHITE);

	xinc = dx/step;
	yinc = dy/step;

	for(k=0; k<step; k++){
		x += xinc;
		y += yinc;
		putpixel(x, y, WHITE);
		}
	}

void main() {
	int gd=DETECT, gm;
	initgraph(&gd, &gm, "\\tc");
	lineDDA(300, 100, 100, 400);
	getch();
	}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: