Computer Graphics using C Examples with Output

Computer Graphics with C Examples


01. Program for drawing line using DDA line drawing method.

C Code


/*	DDA - Digital Differential Analyzer (DDA) algorithm is an incremental scan conversion
	method of line drawing. DDA is used for linear interpolation of variables ovar an
	interval between start and end point. It is used for rasterization of lines, triangles
	and polygons.
*/

// Drawing a line using DDA Algorithm

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

int main(){
  int x1, y1, x2, y2, i;
  float x, y, dx, dy, length;
  int gd = DETECT, gm;

  // Initialise Graphics mode
  detectgraph(&gd, &gm);
  initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

// Step 1 : Read two end points P1(x1, y1) and P2(x2, y2)
  printf(" Enter First Point : ");
  scanf("%d%d", &x1, &y1);
  printf(" Enter Second Point : ");
  scanf("%d%d", &x2, &y2);

// Step 2 : Find approximate length of the line
  if(abs(x2-x1) > abs(y2-y1)){
    length = abs(x2-x1);
  }
  else {
    length = abs(y2-y1);
  }

// Step 3 : Find raster unit :
  dx = (x2-x1) / length;
  dy = (y2-y1) / length;

// Step 4 : set x = x1, y = y1 and i = 0
  x = x1 + 0.5;     // Factor 0.5 is added to round the values
  y = y1 + 0.5;
  i = 0;            // Loop Counter

// Step 5 : Now plot the point (x,y) until i <= length
  while (i <= length){
    putpixel(x, y, GREEN);
    x = x + dx;
    y = y + dy;
    i++;
    delay(10);        
  }
// Step 6 : Stop.
  getch();
  closegraph();
  return 0;
}

Output


02. Program for drawing line using Bresenham's line drawing method.

C Code


/*	Bresenham's Line Drawing Algorithm - This algorithm is accurate and efficient line
	generating algorithm.
	It scan converts line using only incremental integer calculations.
*/

// Drawing a line using Bresanham's Algorithm

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

int main(){
  int x, y, x1, y1, x2, y2, dx, dy, P, i;
  int gd = DETECT, gm;

  // Initialise graphics mode
  detectgraph(&gd, &gm);
  initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

// Step 1 : Read two end points P1(x1, y1) and P2(x2, y2)
  printf(" Enter First Point : ");
  scanf("%d%d", &x1, &y1);
  printf(" Enter Second Point : ");
  scanf("%d%d", &x2, &y2);

// Step 2 : Calculate dx & dy :
  dx = abs(x2 - x1);
  dy = abs(y2 - y1);

// Step 3 : Calculate decision parameter P
  P = 2*dy - dx;

// Step 4 : set x = x1, y = y1 and i = 0
  x = x1;
  y = y1;
  i = 0;            // Loop Counter

// Step 5 : Now plot the point (x,y) until i <= dx
  while(i <= dx){
   putpixel(x, y, GREEN);
    if(P < 0){
      x++;
      P = P + 2*dy;
    }
    else {
      x++;
      y++;
      P = P + 2*dy - 2*dx;
    }
    i++;
    delay(10);

  }

// Step 6 : Stop.
  getch();
  closegraph();
  return 0;
}

Output


03. Program for drawing cicle using DDA circle drawing method

C Code


/*	DDA Circle Drawing Algorithm - The Digital Differential Analyser algorithm uses the
	equation of circle.
	It is used to draw the circle by defining circle as a differential equation :
		2x dx + 2y dy = 0 => dy = -x and dx = y.
	The Circle can be constructed by using, 
		incremental x value = ky and 
		incremental y value = -kx, where k = pow(2, -n) [pow(2, n-1) <= radius < pow(2, n)].
	Applying these incremental steps, 
		x2 = x1 + k*y1
		y2 = y1 - k*x2
*/

// Drawing a Circle using DDA Algorithm
#include<stdio.h>
#include<graphics.h>
#include<math.h>

int main(){
  float start_x, start_y, x1, y1, x2, y2, k;
  int gd = DETECT, gm, r, i, val;

  // Initialise graphics mode
  detectgraph(&gd, &gm);
  initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

// Step 1 : Read the radius (r) of the circle
  printf(" Enter the radius of circle : ");
  scanf("%d", &r);

// Step 2 : Set initial points
  start_x = r * cos(0);
  start_y = r * sin(0);
  x1 = start_x;
  y1 = start_y;
  i = 0;

// Step 3 : Calculate k :
  do {
    val = pow(2, i);
    i++;
  }
  while (val < r);

  k = 1 / pow(2, i - 1);

// Step 4 : Now plot the point (x2, y2)
  do {
    x2 = x1 + y1 * k ;
    y2 = y1 - k * x2;
    putpixel (320 + x2, 240 + y2, WHITE);

    // Step 5 : Reinitialise the current point
    x1 = x2;
    y1 = y2;
    delay(10);
  } // Step 6 : Repeat Steps 4 & 5 while :
  while ((y1 - start_y) < k || (start_x - x1) > k);

// Step 6 : Stop.
  getch();
  closegraph();
  return 0;
}

Output


04. Program for drawing cicle using Bresenham's circle drawing method

C Code


/*	Bresenham's Circle Drawing Algorithm - This algorithm considers the eight-way summetry
	of the circle to generate it. It plots 1/8th part of the circle, 
	i.e. from 90deg to 45deg.
	This algorithm selects nearest pixel position to complete arc.
	It is very significant algorithm and faster than other circle drawing algorithm because
	it use only integer arithmetic.
*/

// Drawing a Circle using Bresenham's Algorithm
#include<stdio.h>
#include<graphics.h>

int main(){
  int gd = DETECT, gm;
  int x, y, xc, yc, r;
  float D;

  // Initialise graphics mode
  detectgraph(&gd, &gm);
  initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

// Step 1 : Input Center of the circle (xc, yc)
  printf(" Enter the center of the circle : ");
  scanf("%d %d", &xc, &yc);

// Step 2 : Input radius (r) of the circle
  printf(" Enter the radius of the circle : ");
  scanf("%d", &r);

  rectangle(0, 0, getmaxx(), getmaxy());

// Step 3 : Calculate Decision Parameter D
  D = (3 - 2) * r;

// Step 4 : Initialize First Point
  x = 0;
  y = r;

// Step 5 : Now, Plot Eight-points by using Eight-way symmetry Concept while x <= y.
  while(x <= y){
    putpixel(xc + x, yc + y, WHITE);
    putpixel(xc - x, yc + y, WHITE);
    putpixel(xc + x, yc - y, WHITE);
    putpixel(xc - x, yc - y, WHITE);
    putpixel(xc + y, yc + x, WHITE);
    putpixel(xc - y, yc + x, WHITE);
    putpixel(xc + y, yc - x, WHITE);
    putpixel(xc - y, yc - x, WHITE);

// Step 6 : Find next pixel position
    if (D <= 0){
      x = x + 1;
      D = D + 4*x + 6;
    }
    else{
      x = x + 1;
      y = y - 1;
      D = D + 4*(x - y) + 10;
    }
    delay(10);
  }

// Step 7 : Stop.
  getch();
  closegraph();
  return 0;
}

Output


05. Program for drawing cicle using Midpoint circle drawing method

C Code


/*	Midpoint Circle Drawing Algorithm - This Midpoint algorithm calculates all the points
	in the first octant of the circle and then prints them along with their mirror points
	in the other seven octants. 
	[because circle is a eight-way symmetric figure]
	It is based on the equation of the circle.
*/

// Drawing a Circle using Midpoint Algorithm
#include<stdio.h>
#include<graphics.h>

int main(){
  int gd = DETECT, gm;
  int x, y, xc, yc, r;
  float P;

  // Initialise graphics mode
  detectgraph(&gd, &gm);
  initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

// Step 1 : Input Center of the circle (xc, yc)
  printf(" Enter the center of the circle : ");
  scanf("%d %d", &xc, &yc);

// Step 2 : Input radius (r) of the circle
  printf(" Enter the radius of the circle : ");
  scanf("%d", &r);

  rectangle(0, 0, getmaxx(), getmaxy());

// Step 3 : Calculate Decision Parameter D
  P = 1.25 - r;

// Step 4 : Initialize First Point
  x = 0;
  y = r;

// Step 5 : Now, Plot Eight-points by using Eight-way symmetry Concept while x <= y.
  while(x <= y){
    putpixel(xc + x, yc + y, WHITE);
    putpixel(xc - x, yc + y, RED);
    putpixel(xc + x, yc - y, GREEN);
    putpixel(xc - x, yc - y, BLUE);
    putpixel(xc + y, yc + x, BLUE);
    putpixel(xc - y, yc + x, GREEN);
    putpixel(xc + y, yc - x, RED);
    putpixel(xc - y, yc - x, WHITE);

// Step 6 : Find next pixel position
    if (P < 0){             // Move Right
      x = x + 1;
      P = P + 2*x + 1;
    }
    else {                  // Move Right + Down
      x = x + 1;
      y = y - 1;
      P = P + 2*(x - y) + 1;
    }
    delay(10);
  }

// Step 7 : Stop.
  getch();
  closegraph();
  return 0;
}

Output


06. Program to perform Mirror Reflection about a line

C Code


//  Program to perform Mirror Reflection about a line

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

// Function to calculate reflected co-ordinates
void reflectPoint(float x, float y, float m, float c, float *x_new, float *y_new){
  float denom = 1 + m * m;
  *x_new = (x * (1 - m * m) + 2 * m * (y - c)) / denom;
  *y_new = (y * (m * m - 1) + 2 * m * x + 2 * c) / denom;
}

int main() {
    int gd = DETECT, gm;
    float x1, y1, x2, y2, x3, y3;   // Original Triangle Vertices
    float rx1, ry1, rx2, ry2, rx3, ry3;   // Reflected Vertices
    float m, c;     // Slope and Intercept of the Mirror line
    
    int scr_x1, scr_y1, scr_x2, scr_y2, scr_x3, scr_y3;     // Screen Coordinates
    int scr_rx1, scr_ry1, scr_rx2, scr_ry2, scr_rx3, scr_ry3;
    int Lx1, Ly1, Lx2, Ly2;     // Mirror Line Coordinates

    // Initialize graphics mode
    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

    // Input the coordinates of the point
    printf("Enter the coordinates of the Triangle: ");
    scanf("%f %f %f %f %f %f", &x1, &y1, &x2, &y2, &x3, &y3);

    // Input the slope (m) and intercept (c) of the line y = mx + c
    printf("Enter the slope (m) and y-intercept (c) of the line y = mx + c: ");
    scanf("%f %f", &m, &c);

    // Reflect each Vertex
    reflectPoint(x1, y1, m, c, &rx1, &ry1);
    reflectPoint(x2, y2, m, c, &rx2, &ry2);
    reflectPoint(x3, y3, m, c, &rx3, &ry3);

    // Draw X and Y axes
    line(0, getmaxy() / 2, getmaxx(), getmaxy() / 2); // X-axis
    line(getmaxx() / 2, 0, getmaxx() / 2, getmaxy()); // Y-axis

    // Calculate screen coordinates
    scr_x1 = getmaxx() / 2 + x1; 
    scr_y1 = getmaxy() / 2 - y1; 
    scr_x2 = getmaxx() / 2 + x2;
    scr_y2 = getmaxy() / 2 - y2; 
    scr_x3 = getmaxx() / 2 + x3;
    scr_y3 = getmaxy() / 2 - y3;     

    scr_rx1 = getmaxx() / 2 + rx1;
    scr_ry1 = getmaxy() / 2 - ry1; 
    scr_rx2 = getmaxx() / 2 + rx2; 
    scr_ry2 = getmaxy() / 2 - ry2;
    scr_rx3 = getmaxx() / 2 + rx3; 
    scr_ry3 = getmaxy() / 2 - ry3;
    

    // Draw the line y = mx + c
    setcolor(YELLOW);
    Lx1 = 0; // left-most point of the screen
    Ly1 = getmaxy() / 2 - (m * (-getmaxx() / 2) + c); // y when x = -maxX/2
    Lx2 = getmaxx(); // right-most point of the screen
    Ly2 = getmaxy() / 2 - (m * (getmaxx() / 2) + c); // y when x = maxX/2
    line(Lx1, Ly1, Lx2, Ly2);
    outtextxy(Lx2 - 200, Ly2 - 10, "Mirror Line [y = mx + c]");

    // Draw the original point
    setcolor(RED);
    line(scr_x1, scr_y1, scr_x2, scr_y2);
    line(scr_x2, scr_y2, scr_x3, scr_y3);
    line(scr_x3, scr_y3, scr_x1, scr_y1);
    outtextxy(scr_x1 + 10, scr_y1, "Original");

    // Draw the reflected point
    setcolor(GREEN);
    line(scr_rx1, scr_ry1, scr_rx2, scr_ry2);
    line(scr_rx2, scr_ry2, scr_rx3, scr_ry3);
    line(scr_rx3, scr_ry3, scr_rx1, scr_ry1);
    outtextxy(scr_rx1 + 10, scr_ry1, "Reflected");

    // Hold the screen
    getch();

    // Close the graphics mode
    closegraph();
    return 0;
}

Output


07. Program for filling polygon using Boundary Fill Method

C Code


//  Program for filling polygon using Boundary Fill Method.

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

// Function to draw polygon
void polygon(int x[], int y[], int n){
  int i;
  moveto(x[0], y[0]);
  for (i = 1; i < n; i++){
    lineto(x[i], y[i]);
    getch();
  }
  lineto(x[0], y[0]);
}

// Boundary Fill Function
void boundaryfill(int x, int y, int bc, int nc){
  int c = getpixel(x, y);

  // If the color of the pixel isnot equal to Boundary Color and new Fill Color 
  if (c != bc && c != nc){
    putpixel(x, y, nc);
    boundaryfill(x - 1, y, bc, nc);
    boundaryfill(x + 1, y, bc, nc);
    boundaryfill(x, y - 1, bc, nc);
    boundaryfill(x, y + 1, bc, nc);
  }
}

// Main Function
void main(){
  int gd = DETECT, gm;
  int bound, fill, bc, nc, oc, ch;
  int x[10], y[10], newx[10], newy[10], xseed, yseed, n, i;
    
  // Initialise graphics mode
  detectgraph(&gd, &gm);
  initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

  printf("-::::::: POLYGON BOUNDARY FILLING :::::::-\n\n");
  // Input the coordinates of the Polygon
  printf(" Enter the degree : ");
  scanf("%d", &n);
  printf(" Enter the co-ordinates\n");
  for (i = 0; i < n; i++){
    printf(" Enter the co-ordinate %d (x, y) : ", i+1);
    scanf("%d%d", &x[i], &y[i]);
  }

  // Input the Boundary Color & Filling Color Value
  printf(" Enter the Boundary Color Value : ");
  scanf("%d", &bound);
  printf(" Enter the Filling Color Value : ");
  scanf("%d", &fill);
  setcolor(bound);
  
  // Drawing Polygon
  polygon(x, y, n);
  
  // Selecting Seedpoint
  printf(" Enter the Seedpoint which lies inside the polygon : ");
  scanf("%d%d", &xseed, &yseed);
  
  // Filling Polygon with Boundary Fill Method
  boundaryfill(xseed, yseed, bound, fill);
  getch();
  closegraph();
}

Output


08. Program for filling polygon using Flood Fill Method.

C Code


//  Program for filling polygon using Flood Fill Method.

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

// Function to draw polygon
void polygon(int x[], int y[], int n){
  int i;
  moveto(x[0], y[0]);
  for (i = 1; i < n; i++){
    lineto(x[i], y[i]);
    getch();
  }
  lineto(x[0], y[0]);
}

// Flood Fill Function
void floodfilling(int x, int y, int oc, int nc){
  
  // If the color of the pixel is equal to Old Color 
  if (getpixel(x, y) == oc){
    putpixel(x, y, nc);
    floodfilling(x-1, y, oc, nc);
    floodfilling(x+1, y, oc, nc);
    floodfilling(x, y-1, oc, nc);
    floodfilling(x, y+1, oc, nc);
  }
}

// Main Function
void main(){
  int gd = DETECT, gm;
  int nc, oc, xseed, yseed;
  int x[10], y[10], n, i;

  // Initialise graphics mode
  detectgraph(&gd, &gm);
  initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

  printf("-::::::: POLYGON FLOOD FILLING :::::::-\n\n");
  // Input the coordinates of the Polygon
  printf(" Enter the degree : ");
  scanf("%d", &n);
  printf(" Enter the co-ordinates\n");
  for (i = 0; i < n; i++){
    printf(" Enter the co-ordinate %d (x, y) : ", i+1);
    scanf("%d%d", &x[i], &y[i]);
  }

  // Input the Filling Color Value
  printf("\n Enter the New Filling Color Value : ");
  scanf("%d", &nc);

  // Drawing Polygon
  polygon(x, y, n);
  
  // Selecting Seedpoint
  printf("\n Enter the Seedpoint which lies inside the polygon : ");
  scanf("%d%d", &xseed, &yseed);

  // Filling Polygon with Flood Fill Method  
  floodfilling(xseed, yseed, 0, nc);
  getch();
  closegraph();
}

Output


09. Program to perform line clipping using Cohen-Sutherland Algorithm.

C Code


// Line Clipping using Cohen Sutherland Method

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

// Declaration of clipping & outcode function
clipping(float, float, float,float);
int outcode(float, float);

// Clipping Window Coordinates
float xleft, xright, ybottom, ytop;

void main(){
  int gd = DETECT, gm;
  float x1, y1, x2, y2; // Line Coordinates

  // Initialise graphics mode
  detectgraph(&gd, &gm);
  initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
  xleft = 200, xright = 400, ybottom = 300, ytop = 200;

  setcolor(GREEN);
  outtextxy(xleft- 70, ytop - 15, "(200,150)");
  outtextxy(xright, ytop - 15, "(400,150)");
  outtextxy(xleft - 70, ybottom + 10, "(200,300)");
  outtextxy(xright, ybottom + 10, "(400,300)");
  outtextxy(xleft, ybottom + 30, "[Before Clipping]");

  setcolor(WHITE);
  printf(" -::::::: COHEN SUTHERLAND LINE CLIPPING :::::::-\n\n");
  // Read the co-ordinates of the line
  printf(" Enter the points of the line : ");
  scanf("%f%f%f%f", &x1, &y1, &x2, &y2);
  // Drawing Clipping Window
  setcolor(GREEN);
  rectangle(xleft, ytop, xright, ybottom);
  // Drawing line
  setcolor(WHITE);
  line((int)x1, (int)y1, (int)x2, (int)y2);
  getch();
  // Calling Line Clipping Function
  clipping(x1, y1, x2, y2);
  getch();
  closegraph();
}

// Assigns a 4-bit region code based on the position of the point 
// relative to the clipping window
int outcode(float x, float y){
  int temp = 0;
  if (x < xleft)          // Left of window
    temp = temp | 1;
  if (x > xright)         // Right of window
    temp = temp | 2;
  if (y > ybottom)        // Below of window
    temp = temp | 4;
  if (y < ytop)           // Abow of window
    temp = temp | 8;
  return temp;        // Return region code
}

// Line Clipping Function
clipping(float x1, float y1, float x2, float y2){
  int code1, code2, chk;
  float x, y, m;

  // Region codes for the two endpoints.
  code1 = outcode(x1, y1);  
  code2 = outcode(x2, y2);  
  
  // Finding new end points of the clipped line
  while((code1 != 0) || (code2 != 0)){
    m = (float) (y2 - y1) / (x2 - x1);    // Slope
    chk = code1 & code2;
    if(chk != 0)      // The line is completely outside/invisible
      return;
    if(code1 == 0)    // The line is partially visible
      chk = code2;
    else
      chk = code1;
    
    // Calculates the new intersection points of the line 
    // with the clipping window edges
    if((chk & 1) != 0){       // Left edge
      x = xleft;
      y = y1 + m * (xleft - x1);
    }
    if((chk & 2) != 0){       // Right edge
      x = xright;
      y = y1 + m * (xright - x1);
    }
    if((chk & 4) != 0){       // Bottom edge
      y = ybottom;
      x = x1 + (ybottom - y1) / m;
    }
    if((chk & 8) != 0){       // Top edge
      y = ytop;
      x = x1 + (ytop - y1) / m;
    }

    if(chk == code1){
      x1 = x; y1 = y;         // Update start point
      code1 = outcode(x, y);
    }
    else if(chk == code2){
      x2 = x; y2 = y;         // Update end point
      code2 = outcode(x, y);
    }
  }

  // Drawing new Window
  cleardevice();
  setcolor(GREEN);
  rectangle(xleft, ytop, xright, ybottom);
  outtextxy(xleft - 70, ytop - 15, "(200,150)");
  outtextxy(xright, ytop - 15, "(400,150)");
  outtextxy(xleft - 70, ybottom + 10, "(200,300)");
  outtextxy(xright, ybottom + 10, "(400,300)");
  outtextxy(xleft, ybottom + 30, "[After Clipping]");
  
  // Drawing Clipped line in the Window
  setcolor(YELLOW);
  line((int)x1, (int)y1, (int)x2, (int)y2);
  return;
}

Output


Comments

Popular posts from this blog

Python Programming Examples with Output