Headlines
Loading...
Computer graphics program -Scanline polygon fill

Computer graphics program -Scanline polygon fill

Scanline polygon fill program.
Code
# include<stdio.h>
# include<conio.h>
# include<malloc.h>
# include<graphics.h>
# include<math.h>
# include<dos.h>

struct POINT *Head=NULL,*end=NULL,*p=NULL,*temp=NULL;

struct POINT
{
 int x,y;
 struct POINT *next;
};

void Insert(int x, int y)
{
 p = (struct POINT * ) malloc (sizeof(struct POINT));
 p->next = NULL;
 p->x = x;
 p->y = y;
 if( Head == NULL )
  Head = p;
 else
  end->next = p;
 end = p;
}

int SIGN(float d)
{
 if (d > 0)
  return(1);
 else if (d < 0)
  return(-1);
 else
  return(0);
}

void main()
{
 int gd = DETECT,gm;
 float Ypre,x1,y1,x2,y2;
 int len,i,j;
 float dx,dy,pdy,x,y;
 

int POLYGON[4][2]={{100,300},{300,300},{100,100},{300,100}};
 initgraph(&gd,&gm,"c:\\tc\\bgi");
 cleardevice();
 setbkcolor(15);

 setcolor(8);
 for (i=0;i<3;i++)
line(POLYGON[i][0],POLYGON[i][1],POLYGON[i+1][0],POLYGON[i+1][1]);
line(POLYGON[0][0],POLYGON[0][1],POLYGON[3][0],POLYGON[3][1]);
 getch();
 cleardevice();

 Ypre = POLYGON[0][1];
 for(i=0;i<=3;i++)
 {
  x1 = POLYGON[i][0];
  y1 = POLYGON[i][1];
  x2 = POLYGON[(i+1) % 4][0];
  y2 = POLYGON[(i+1) % 4][1];

  if( y2-y1 > 0 && i != 0)
   y1 = Ypre + 1 ;
  else if ( y2-y1 < 0 && i != 0)
   y1 = Ypre;
  else if(y1 == y2)
   continue;

  len = fabs(y2 - y1);

  dx = ((1.0 * (x2 - x1)) / len);
  dy = ((1.0 * (y2 - y1)) / len);

  y=y1;
  x=x1+0.5*SIGN(dx);
  for(j=0; j<=len; j++)
  {
   Insert(ceil(x),y);
   x = x + dx;
   y = y + dy;
  }

  if( y2-y1 > 0 )
   Ypre = y2;
  else if ( y2-y1 < 0 )
   Ypre = y2-1 ;
 }

 

while(1)
 {
  temp = Head;
  i = 0;
  while(temp->next != NULL)
  {
   if( temp->y <= temp->next->y )
   {
if( (temp->y == temp->next->y) && (temp->x > temp->next->x) )
    {
     x = temp->next->x;
     temp->next->x = temp->x;
     temp->x = x;
     i=1;
    }
    else if((temp->y == temp->next->y) &&
      (temp->x <= temp->next->x) )
    {
     temp=temp->next;
     continue;
    }
    else
    {
     x = temp->next->x;
     y = temp->next->y;
     temp->next->x = temp->x;
     temp->next->y = temp->y;
     temp->x = x;
     temp->y = y;
     i=1;
    }
   }
   temp = temp->next;
  }
  if(temp->next == NULL && i == 0 )
   break;
 }

 temp = Head;
 setcolor(8);
 while(temp!= NULL )
 {
  line(temp->x,temp->y,temp->next->x,temp->next->y);
  //delay(50);
  temp = temp->next->next;
 }

 

setcolor(8);
 for (i=0;i<3;i++)

line(POLYGON[i][0],POLYGON[i][1],POLYGON[i+1][0],POLYGON[i+1][1]);
line(POLYGON[0][0],POLYGON[0][1],POLYGON[3][0],POLYGON[3][1]);

 temp = Head;
 while(temp->next != NULL )
 {
  end = temp->next;
  free (temp);
  temp = end;
 }
 free(Head);
 free(p);
 getch();
}
*** PLEASE checkout the Best deals from for top sites like Amazon, Flipkart etc ***