omnidirectional lines

This commit is contained in:
Ole Morud
2022-06-06 22:35:41 +02:00
parent d91e3525ed
commit 05b8914244

View File

@@ -38,32 +38,42 @@ void dot(Canvas* c, uint x, uint y){
* Draws a line from (start_x, start_y) to (end_x, end_y) * Draws a line from (start_x, start_y) to (end_x, end_y)
*/ */
void line(Canvas* c, uint start_x, uint start_y, uint end_x, uint end_y){ void line(Canvas* c, uint start_x, uint start_y, uint end_x, uint end_y){
#ifndef abs int dx = end_x - start_x;
#define abs(x) ((x<0)?(-x):(x)) int dy = end_y - start_y;
int dx = abs(end_x - start_x); if (dx<0) dx *= -1;
int dy = abs(end_y - start_y); if (dy<0) dy *= -1;
dx++;
dy++;
if((dx>=dy && start_x>end_x) || ( dx<dy && start_y>end_y)){
int temp;
temp = end_x;
end_x = start_x;
start_x = temp;
temp = end_y;
end_y = start_y;
start_y = temp;
}
int direction_x = start_x < end_x ? 1 : -1; int direction_x = start_x < end_x ? 1 : -1;
int direction_y = start_y < end_y ? 1 : -1; int direction_y = start_y < end_y ? 1 : -1;
printf("dx:%i dy:%i direction:%i,%i \n", dx, dy, direction_x, direction_y);
if(dx>=dy){ if(dx>=dy){
float small = direction_y * (float)dy/(float)dx; float small = direction_y * (float)dy/(float)dx;
for(int i=0; i<dx+1; i++){ for(int i=0; i<dx; i++){
dot(c, start_x + i*direction_x, start_y + i*small); dot(c, start_x + i*direction_x, start_y + i*small);
} }
}else{ }else{
float small = direction_x * (float)dx/(float)dy; float small = direction_x * (float)dx/(float)dy;
for(int i=0; i<dy+1; i++){ for(int i=0; i<dy; i++){
dot(c, start_x + i*small, start_y + i*direction_y); dot(c, start_x + i*small, start_y + i*direction_y);
} }
} }
#undef abs
#endif
} }
@@ -83,11 +93,10 @@ int main(){
Canvas a = {10, 10, data}; Canvas a = {10, 10, data};
//line(&a, 1, 1, 8, 8); //line(&a, 1, 1, 8, 8);
line(&a, 8, 8, 1, 1); //line(&a, 8, 8, 1, 1);
//line(&a, 5, 5, 8, 8); //line(&a, 0, 5, 8, 8);
line(&a, 8, 8, 0, 5);
dot(&a, 0, 0);
dot(&a, 9, 9);
render(&a); render(&a);