add bresenham line algo, lfutility and Point struct
This commit is contained in:
parent
8b2a459252
commit
238ce2c2d2
@ -1,6 +1,8 @@
|
||||
#ifndef LIBFLINT_H_MATH
|
||||
#define LIBFLINT_H_MATH
|
||||
|
||||
#include "lfutility.h"
|
||||
|
||||
int max_int(int a, int b);
|
||||
|
||||
int min_int(int a, int b);
|
||||
@ -9,4 +11,8 @@ int clamp_int(int i, int low, int high);
|
||||
|
||||
int binstr_to_int(const char *s);
|
||||
|
||||
Point *bresenham(int x0, int y0, int x1, int y1, size_t *sz);
|
||||
|
||||
Point *bresenham_p(Point p1, Point p2, size_t *sz);
|
||||
|
||||
#endif // LIBFLINT_H_MATH
|
||||
|
9
include/lfutility.h
Normal file
9
include/lfutility.h
Normal file
@ -0,0 +1,9 @@
|
||||
#ifndef LIBFLINT_H_UTILITY
|
||||
#define LIBFLINT_H_UTILITY
|
||||
|
||||
typedef struct Point {
|
||||
int x;
|
||||
int y;
|
||||
} Point;
|
||||
|
||||
#endif // LIBFLINT_H_UTILITY
|
@ -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);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user