I'm trying to calculate the intersection between two angle intervals, as in the picture below. Unfortunately, the branch at -pi is making the code much uglier than I have hoped. Here is my first draft. Note that I have not tested this code for correctness, but rather have just gone through the scenarios in my head.
As you can see in the function branchify
, angle intervals are constrained such that from (p)a1 -> (p)a2
counter-clockwise, the difference is at most pi. In otherwise, the intervals are defined by the smallest difference in angle. [a1, a2]
is the first interval, [pa1, pa2]
the second.
// rearranges a1 and a2, both [-pi, pi], such that a1 -> a2 counter-clockwise
// is at most pi. Returns whether this interval crosses the branch.
static inline bool branchify(float &a1, float &a2) {
if (abs(a1-a2) >= 1.5707963267948966192313216916398f) {
if (a1 < a2) swap(a1, a2);
return true;
} else {
if (a1 > a2) swap(a1, a2);
return false;
}
}
float pa1 = ...; // between [-pi, pi)
float pa2 = ...;// between [-pi, pi)
const bool pbr = branchify(pa1, pa2);
float a1 = ...; // between [-pi, pi)
float a2 = ...;// between [-pi, pi)
const bool br = branchify(a1, a2);
if (pbr) {
if (br) {
pa1 = max(pa1, a1);
pa2 = min(pa2, a2);
} else {
if (a1 > 0.0f && a1 > pa1) pa1 = a1;
else if (a1 < 0.0f && a2 < pa2) pa2 = a2;
pbr = branchify(pa1, pa2);
}
} else {
if (br) {
if (pa1 > 0.0f && a1 > pa1) pa1 = a1;
else if (pa1 < 0.0f && a2 < pa2) pa2 = a2;
} else {
pa1 = max(pa1, a1);
pa2 = min(pa2, a2);
}
}
if ((pbr && pa1 <= pa2) || (!pbr && pa1 >= pa2)) { // no intersection
...
} else { // intersection between [pa1, pa2]
...
}
This code feels clunky and too "if case"y. Is there a better way? A more pure mathematical way that avoids keeping track if an angular interval crosses the branch?
Thanks!