Last active
December 7, 2021 21:05
-
-
Save felipeek/93c873395506868e50ea6f2323eb3399 to your computer and use it in GitHub Desktop.
Check if point lies on a line (2D)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// checks whether a point lies on a line (2D) | |
// l1_x, l1_y -> line's first point | |
// l2_x, l2_y -> line's second point | |
// p_x, p_y -> point of interest | |
// w -> output indicating the weight of the point | |
// returns 1 if point lies on the line, 0 if not | |
// https://gist.github.com/felipeek/93c873395506868e50ea6f2323eb3399 | |
int point_lies_on_line_2d(float l1_x, float l1_y, float l2_x, float l2_y, float p_x, float p_y, float* w) { | |
const float EPSILON = 0.000001f; | |
int vertical_line = (l1_x - l2_x) > -EPSILON && (l1_x - l2_x) < EPSILON; // vertical line | |
int horizontal_line = (l1_y - l2_y) > -EPSILON && (l1_y - l2_y) < EPSILON; // horizontal line | |
if (vertical_line && horizontal_line) { // degenerate case -> line is composed of a single point | |
if (((p_x - l1_x) > -EPSILON && (p_x - l1_x) < EPSILON) && | |
((p_y - l1_y) > -EPSILON && (p_y - l1_y) < EPSILON)) { | |
// in this case, 'w' has no real meaning | |
*w = 0.5f; | |
return 1; | |
} | |
} | |
if (vertical_line) { // vertical line | |
if ((p_x - l1_x) > -EPSILON && (p_x - l1_x) < EPSILON) { // p also lies on same line? | |
float alpha = (p_y - l1_y) / (l2_y - l1_y); | |
if (alpha < 0.0f || alpha > 1.0f) { | |
return 0; | |
} | |
*w = alpha; | |
return 1; | |
} | |
return 0; | |
} | |
if (horizontal_line) { // horizontal line | |
if ((p_y - l1_y) > -EPSILON && (p_y - l1_y) < EPSILON) { // p also lies on same line? | |
float alpha = (p_x - l1_x) / (l2_x - l1_x); | |
if (alpha < 0.0f || alpha > 1.0f) { | |
return 0;; | |
} | |
*w = alpha; | |
return 1; | |
} | |
return 0; | |
} | |
// general case | |
float alpha_x = (p_x - l1_x) / (l2_x - l1_x); | |
if (alpha_x < 0.0f || alpha_x > 1.0f) { | |
return 0; | |
} | |
float alpha_y = (p_y - l1_y) / (l2_y - l1_y); | |
if (alpha_y < 0.0f || alpha_y > 1.0f) { | |
return 0; | |
} | |
float alpha_diff = alpha_x - alpha_y; | |
if (alpha_diff > -EPSILON && alpha_diff < EPSILON) { | |
*w = alpha_x; | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment