Lab Report-04
Course Code: CSE 422
Course Title: Computer Graphics Lab
Submitted To:
Md Shakil Ahmed(MSA)
Lectural
Department of CSE
Daffodil International University
Submitted by:
Name: Mir Saem Hasan
ID: 211-15-4066
Section: 59_C1
Department of CSE
Daffodil International University
Report: Line Drawing using DDA Algorithm in OpenGL
1. Objective
To implement and demonstrate the Digital Differential Analyzer (DDA) algorithm for line
drawing using OpenGL, with a red line drawn on a white background.
2.Theory:
The Digital Differential Analyzer (DDA) algorithm is a rasterization method used to draw lines
on a pixel grid. It calculates intermediate points between the start and end points of a line by
incrementing one coordinate at a time and calculating the corresponding other coordinate using
the line's slope.
Given two points, (x1,y1)(x_1, y_1)(x1,y1) and (x2,y2)(x_2, y_2)(x2,y2), the slope mmm is
calculated as:
The line's equation y=mx+cy = mx + cy=mx+c is used to calculate the next points by
incrementing xxx and updating y based on the slope.
3. Code
#include<GL/gl.h>
#include<GL/glut.h>
#include<stdio.h>
float x1, y1, x2, y2, m, i, j;
int dx = 0, dy = 0;
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0); // Line color set to red
glBegin(GL_POINTS);
if (dx == -1)
{
for (i = x1, j = y1; i <= x2; i += 1, j += m)
{
glVertex3f((i / 100), (j / 100), 0.0);
}
}
else if (dx == 1)
{
for (i = x1, j = y1; i <= x2; i += (1 / m), j += i)
{
glVertex3f((i / 100), (j / 100), 0.0);
}
}
glEnd();
glFlush();
}
void init(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0); // Background color set to white
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}
int main(int argc, char** argv)
{
printf("Enter first point: ");
scanf("%f %f", &x1, &y1);
printf("Enter second point: ");
scanf("%f %f", &x2, &y2);
m = (y2 - y1) / (x2 - x1);
if ((x1 > x2) && (y1 > y2))
{
dx = -1;
}
else
{
dx = 1;
}
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("DDA Algorithm");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
4. Output
Upon running the program, a 500x500 pixel window opens displaying a simple house. The house
has the following features:
Fig:01
6. Conclusion
The DDA algorithm is effective for drawing lines by incrementing coordinates based on the
slope. It is simple to implement in OpenGL and can be adapted for various line drawing needs.
The background and line colors were correctly modified and displayed according to the
requirements.