PDA

View Full Version : Render line



sharonGL
03-27-2005, 08:17 PM
I got a code from online tutorial which could drawn program. But I madea slight modification which ask the user to input the coordinate for the startinng and end points of line to be drawn. However, I face some problem which always get trapped at the dos prompt, but never get the program to render the line. Please let me know what is wrong. Thanks.

sharonGL
03-27-2005, 08:22 PM
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <GL/glut.h>


#define ESC 27
int Height=400, Width=400;


void swapd(int *a, int *b)
{
int tmp;

tmp=*a;*a=*b;*b=tmp;
}


void writepixel(int x, int y, int flag)
{

glBegin(GL_POINTS);
if (flag==0) glVertex2i (x,y);
else if (flag==1) glVertex2i (y,x);
else if (flag==10) glVertex2i (x,-y);
else if (flag==11) glVertex2i (y,-x);
glEnd();
}


void line(int x0,int y0,int xn,int yn)
{ /* Bresenham's midpoint line algorithm */
int dx, dy, incrE, incrNE, d, x, y, flag = 0;

if (xn<x0) { swapd(&amp;x0,&amp;xn); swapd(&amp;y0,&amp;yn); }
if (yn<y0) { y0 = -y0; yn = -yn; flag=10; }

dy=yn-y0; dx=xn-x0;

if (dx<dy) { swapd(&amp;x0,&amp;y0); swapd(&amp;xn,&amp;yn); swapd(&amp;dy,&amp;dx); flag++;}

x=x0; y=y0;
d=2*dy-dx; incrE=2*dy; incrNE=2*(dy-dx);

while (x<xn+1) {
writepixel(x,y,flag); /* write framebuffer */

x++; /* consider next pixel */
if (d<=0) { d+=incrE; }
else { y++; d+=incrNE; };
}
}


void display(void)
{
int x0, y0, xn, yn;

printf(" Please enter coordinate of x0 and y0\n");
scanf("%d %d", &amp;x0,&amp;y0);


printf(" Please enter coordinate of x1 and y1\n");
scanf("%d %d", &amp;xn,&amp;yn);

x0 = (x0 % Width) - Width/2;
y0 = (y0 % Height) - Height/2;
xn = (xn % Width) - Width/2;
yn = (yn % Height) - Height/2;

glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1, 1, 1);
line(x0, y0, xn, yn);
glFlush();
}



static void Reshape(int w, int h)
{
//1. clear the framebuffer to black color
glClearColor (0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);

//2. coordinate adjusted if window reshaped
Width = w; Height = h;

//3. adjust the size of the drawing area
glViewport (0, 0, Width, Height);

glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho(-Width/2, Width/2, -Height/2, Height/2, -1.0, 1.0);
}


static void Key(unsigned char key, int x, int y)
{
switch (key) {
case ESC:
exit(0);

default: display();
}
}


int main(int argc, char **argv)
{
glutInit(&amp;argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(Width, Height);

glutCreateWindow("Bresenham Line");


glutKeyboardFunc(Key);
glutReshapeFunc(Reshape);
glutDisplayFunc(display);

glutMainLoop();
}