add bresenham line algo, lfutility and Point struct
This commit is contained in:
@@ -71,8 +71,10 @@ int *get_ints(const char *path, size_t *sz) {
|
||||
const char *errstr;
|
||||
n = (int) strtonum(lines[idx], INT_MIN, INT_MAX, &errstr);
|
||||
if (errstr) {
|
||||
printf("Failed to convert %s to int. Returning NULL\n", lines[idx]);
|
||||
exit(1);
|
||||
fprintf(stderr, "Failed to convert %s to int. Returning NULL\n", lines[idx]);
|
||||
free(i);
|
||||
del_lines(lines);
|
||||
return NULL;
|
||||
}
|
||||
i[idx] = n;
|
||||
}
|
||||
|
38
src/lfmath.c
38
src/lfmath.c
@@ -1,4 +1,5 @@
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "lfmath.h"
|
||||
|
||||
@@ -35,3 +36,40 @@ int binstr_to_int(const char *s) {
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
Point *bresenham(int x0, int y0, int x1, int y1, size_t *sz) {
|
||||
Point *line = NULL;
|
||||
size_t n = 0;
|
||||
*sz = 0;
|
||||
|
||||
int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
|
||||
int dy = abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
|
||||
int err = (dx > dy ? dx : -dy) / 2, e2;
|
||||
|
||||
for (;;) {
|
||||
line = realloc(line, sizeof(Point) * ++n);
|
||||
++*sz;
|
||||
line[n - 1].x = x0;
|
||||
line[n - 1].y = y0;
|
||||
|
||||
if (x0 == x1 && y0 == y1) {
|
||||
break;
|
||||
}
|
||||
|
||||
e2 = err;
|
||||
if (e2 > -dx) {
|
||||
err -= dy;
|
||||
x0 += sx;
|
||||
}
|
||||
if (e2 < dy) {
|
||||
err += dx;
|
||||
y0 += sy;
|
||||
}
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
Point *bresenham_p(Point p1, Point p2, size_t *sz) {
|
||||
return bresenham(p1.x, p1.y, p2.x, p2.y, sz);
|
||||
}
|
Reference in New Issue
Block a user