simple line algorithm

Started by
1 comment, last by PredeX 22 years, 2 months ago
This is not even optimized or anything, im just tryin to have a sloped line and all i get is a horizontal line, and i dont know why!?! Well heres the code...
      
#include <conio.h>
#include <dos.h>

#define MODE13H	 0x13
#define TEXTMODE 0x00

unsigned char far *video_buffer=(unsigned char far *)0xA0000000L;

void video_mode(int mode)
{
	union REGS inregs, outregs;

	inregs.h.ah=0;
	inregs.h.al=mode;
	int86(0x10,&inregs, &outregs);
}

void plot_pixel(int x, int y, int color)
{
	int offset;
	offset= ((y<<8)+(y<<6))+x;
	video_buffer[offset]=(unsigned char)color;
}


void slope_line(int x1, int y1, int x2, int y2, int color)
{
	int x_length, y_length, temp, x, y, i;
	float x_step, y_step;//coordinates for pixel-plotting


	x_length = ABS((x2 - x1)); 	y_length = ABS((y2 -y1));
					//Absolute Values!


	if(x_length > y_length)
	{
		if(x1 > x2)  //exchanging coordinates?? 

		{
		//if x-coord are exchanged, exchange y-coord

                        temp = x1;  x1 = x2;  x2 = temp; 
			temp = y1;  y1 = y2;  y2 =temp; 
		}//end if x1<x2


		y_step=(float)((y2 - y1)/(x2 - x1));
		y=(float)y1; 	//use y for pixel-plotting

		for(x=x1,i=0; x <= x2, i<=x_length; ++x, ++i)
		{
			y +=(float)y_step*i;
			plot_pixel(x,y,(unsigned char)color);
  		}//end for x <= x2

	}//end if x_length > y_length

	else
	{
		if(y1 > y2)   //exchanging coordinates??

		{
      	                temp = y1;  y1 = y2;  y2 = temp;
			temp = x1;  x1 = x2;  x2 = temp;
		}//end if y1 > y2


		x_step = ((x2 - x1)/(y2 - y1));
		x=x1; 	//x is used for pixel-plotting

		for(y= y1, i=0; y <= y2, i<=y_length; ++y, ++i)
		{
                        x +=(float)x_step*i;
			plot_pixel(x,y,(unsigned char)color);
		}//end for y <= y2

	}//end else

}

int main()
{

	video_mode(MODE13H);
	slope_line(0,150,200,130,15);

	while(!kbhit())
		;

	video_mode(TEXTMODE);

	return 0;
}
    
Edited by - PredeX on February 8, 2002 8:21:03 AM Edited by - PredeX on February 8, 2002 8:21:48 AM
Let us learn to dream, gentleman, and the we may perhaps find the truth - F. A. Kekulé
Advertisement
Stop that now and try to implement the well-known line algorithm of Bresenham...
I know that I don't know nothing... Operation Ivy
I didn''t read it completely (quick scan), but I found at least 3 problems so far.. which could be the cause of your problem...

y_step=(float)((y2 - y1)/(x2 - x1));
y = (float)y1;

x_step = ((x2 - x1)/(y2 - y1));
x = x1;

change these lines to:
y_step=(y2 - y1)/(float)(x2 - x1);
y = (float)y1;

x_step = (x2 - x1)/(float)(y2 - y1);
x = (float)x1;


Also, make x, y float instead of ints.
Then change these lines:
y +=(float)y_step*i;
x +=(float)x_step*i;

To this:
y += y_step;
x += x_step;

and you don''t have to deal with ''i'' anymore.

Billy

This topic is closed to new replies.

Advertisement