Skip to content

Commit

Permalink
Clamp acos when computing rounded corners
Browse files Browse the repository at this point in the history
Due to floating point imprecision, computing the angle between two
vectors with `theta = acos((a . b) / sqrt(|a||b|))` gives NaN when
`(a . b) / sqrt(|a||b|)` is outside the domain of `acos`. We can
use a clamped version of acos to avoid this, which clamps to
[-1, 1].
  • Loading branch information
sftrabbit committed Jan 24, 2017
1 parent 9460444 commit 3f30a98
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/arc.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {path} from "d3-path";
import constant from "./constant";
import {epsilon, pi, halfPi, tau} from "./math";
import {acos, epsilon, pi, halfPi, tau} from "./math";

function arcInnerRadius(d) {
return d.innerRadius;
Expand Down Expand Up @@ -159,7 +159,7 @@ export default function() {
ay = y01 - oc[1],
bx = x11 - oc[0],
by = y11 - oc[1],
kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2),
kc = 1 / Math.sin(acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2),
lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
rc0 = Math.min(rc, (r0 - lc) / (kc - 1));
rc1 = Math.min(rc, (r1 - lc) / (kc + 1));
Expand Down
4 changes: 4 additions & 0 deletions src/math.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@ export var epsilon = 1e-12;
export var pi = Math.PI;
export var halfPi = pi / 2;
export var tau = 2 * pi;

export function acos(x) {
return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);
}

0 comments on commit 3f30a98

Please sign in to comment.