Monday, October 25, 2010

Window to viewport transformation

Share Orkut
#include<stdio.h>
#include<graphics.h>
struct point
{
 int x,y;
} pol[10],wmin,wmax,vmin,vmax;
int n;
float trans[3][3],result[3][1],xandy[3][1];
void readpoly()
{
 int i;
 for(i=0;i<n;i++)
 {
  printf("\nEnter the %d co=ordinates ",i+1);
  scanf("%d%d",&pol[i].x,&pol[i].y);
 }
}
void drawpolygon()
{
 int i; 
 for(i=0;i<n;i++)
  line(pol[i].x,pol[i].y,pol[(i+1)%n].x,pol[(i+1)%n].y);
}
void mulmat()
{
 int i,j,k;
 for(i=0;i<3;i++)
 {
  for(j=0;j<1;j++)
  {
   result[i][j]=0.0;
   for(k=0;k<3;k++)
    result[i][j]+=trans[i][k]*xandy[k][j];
  }
 }
}
void transformpoly()
{
 int i; 
 for(i=0;i<n;i++)
 {
  xandy[0][0]=pol[i].x;
  xandy[1][0]=pol[i].y;
  xandy[2][0]=1;
  mulmat();
  pol[i].x=result[0][0];
  pol[i].y=result[1][0];
 }
}
void makeIdentity()
{
 int i,j;
 for(i=0;i<3;i++)
 {
  for(j=0;j<3;j++)
   trans[i][j]=0.0;
  trans[i][i]=1.0;
 }
}
int main()
{
 int gd=DETECT,gm=VGAMAX; 
 int choice,dx,dy;
 float sx,sy;
 printf("\nEnter the minx and miny of window ");
 scanf("%d%d",&wmin.x,&wmin.y);
 printf("\nEnter the maxx and maxy of window ");
 scanf("%d%d",&wmax.x,&wmax.y);
 printf("\nEnter the minx and miny of view port ");
 scanf("%d%d",&vmin.x,&vmin.y);
 printf("\nEnter the maxx and maxy of view port ");
 scanf("%d%d",&vmax.x,&vmax.y);
 while(1)
 {
  makeIdentity();
  printf("\nMENU\n-------\n1.POLYGON\n2.EXIT");
  printf("\nEnter the choice ");
  scanf("%d",&choice);
  switch(choice)
  {
   case 1: printf("\nEnter the no of sides ");
    scanf("%d",&n);
    readpoly();
    initgraph(&gd,&gm,NULL);
    outtextxy(200,10,"Window");
    rectangle(wmin.x,wmin.y,wmax.x,wmax.y);
    drawpolygon();
    break;   
   case 2: exit(0);
   default:printf("\nInvalid choice ");
  }
  getch();
  cleardevice();
  outtextxy(200,10,"View Port");
  sx=(float)(vmax.x-vmin.x)/(float)(wmax.x-wmin.x);
  sy=(float)(vmax.y-vmin.y)/(float)(wmax.y-wmin.y); 
  trans[0][0]=sx;
  trans[0][2]=(1-sx)*(float)wmin.x;
  trans[1][1]=sy;  
  trans[1][2]=(1-sy)*(float)wmin.y;
  transformpoly();
  dx=-wmin.x;
  dy=-wmin.y;
  makeIdentity();
  trans[0][2]=dx;
  trans[1][2]=dy;
  transformpoly();
  dx=vmin.x;
  dy=vmin.y;
  makeIdentity();
  trans[0][2]=dx;
  trans[1][2]=dy;
  transformpoly();
  setcolor(RED);
  rectangle(vmin.x,vmin.y,vmax.x,vmax.y);
  drawpolygon(); 
  while (!kbhit());
  closegraph();
 }
 return 0;
}

No comments:

Post a Comment