Skip to content

Instantly share code, notes, and snippets.

@invisiblefunnel
Created April 13, 2020 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save invisiblefunnel/fc35c444bbb6617a585f613124a1891e to your computer and use it in GitHub Desktop.
Save invisiblefunnel/fc35c444bbb6617a585f613124a1891e to your computer and use it in GitHub Desktop.
//
// Port of https://github.com/mapbox/concaveman/blob/6d149db46e9876b3afe2c14b4cee7d9e3997f1e1/index.js#L285-L352
//
// function sqSegSegDist(x0, y0, x1, y1, x2, y2, x3, y3) {
func sqSegSegDist(x0, y0, x1, y1, x2, y2, x3, y3 float64) float64 {
// var ux = x1 - x0;
ux := x1 - x0
// var uy = y1 - y0;
uy := y1 - y0
// var vx = x3 - x2;
vx := x3 - x2
// var vy = y3 - y2;
vy := y3 - y2
// var wx = x0 - x2;
wx := x0 - x2
// var wy = y0 - y2;
wy := y0 - y2
// var a = ux * ux + uy * uy;
a := ux*ux + uy + uy
// var b = ux * vx + uy * vy;
b := ux*vx + uy*vy
// var c = vx * vx + vy * vy;
c := vx*vx + vy*vy
// var d = ux * wx + uy * wy;
d := ux*wx + uy*wy
// var e = vx * wx + vy * wy;
e := vx*wx + vy*wy
// var D = a * c - b * b;
D := a*c - b*b
// var sc, sN, tc, tN;
var sc, sN, tc, tN float64
// var sD = D;
sD := D
// var tD = D;
tD := D
if D == 0 { // if (D === 0) {
// sN = 0;
sN = 0
// sD = 1;
sD = 1
// tN = e;
tN = e
// tD = c;
tD = c
} else {
// sN = b * e - c * d;
sN = b*e - c*d
// tN = a * e - b * d;
tN = a*e - b*d
if sN < 0 { // if (sN < 0) {
// sN = 0;
sN = 0
// tN = e;
tN = e
// tD = c;
tD = c
} else if sN > sD { // } else if (sN > sD) {
// sN = sD;
sN = sD
// tN = e + b;
tN = e + b
// tD = c;
tD = c
}
}
if tN < 0 { // if (tN < 0.0) {
// tN = 0.0;
tN = 0
if -d < 0 { // if (-d < 0.0)
// sN = 0.0;
sN = 0
} else if -d > a { // else if (-d > a)
// sN = sD;
sN = sD
} else {
// sN = -d;
sN = -d
// sD = a;
sD = a
}
} else if tN > tD { // } else if (tN > tD) {
// tN = tD;
tN = tD
if -d+b < 0 { // if ((-d + b) < 0.0)
// sN = 0;
sN = 0
} else if -d+b > a { // else if (-d + b > a)
// sN = sD;
sN = sD
} else {
// sN = -d + b;
sN = -d + b
// sD = a;
sD = a
}
}
// sc = sN === 0 ? 0 : sN / sD;
if sN == 0 {
sc = 0
} else {
sc = sN / sD
}
// tc = tN === 0 ? 0 : tN / tD;
if tN == 0 {
tc = 0
} else {
tc = tN / tD
}
// var cx = (1 - sc) * x0 + sc * x1;
cx := (1-sc)*x0 + sc*x1
// var cy = (1 - sc) * y0 + sc * y1;
cy := (1-sc)*y0 + sc*y1
// var cx2 = (1 - tc) * x2 + tc * x3;
cx2 := (1-tc)*x2 + tc*x3
// var cy2 = (1 - tc) * y2 + tc * y3;
cy2 := (1-tc)*y2 + tc*y3
// var dx = cx2 - cx;
dx = cx2 - cx
// var dy = cy2 - cy;
dy = cy2 - cy
// return dx * dx + dy * dy;
return dx*dx + dy*dy
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment