github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/ui/ccl/src/views/clusterviz/util/pathmath.ts (about) 1 // Copyright 2017 The Cockroach Authors. 2 // 3 // Licensed as a CockroachDB Enterprise file under the Cockroach Community 4 // License (the "License"); you may not use this file except in compliance with 5 // the License. You may obtain a copy of the License at 6 // 7 // https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt 8 9 import * as d3 from "d3"; 10 11 import * as vector from "src/util/vector"; 12 13 // createArcPath returns an svg arc object. startAngle and endAngle are 14 // expressed in radians. 15 export function createArcPath( 16 innerR: number, outerR: number, startAngle: number, endAngle: number, cornerRadius: number, 17 ) { 18 return d3.svg.arc() 19 .innerRadius(innerR) 20 .outerRadius(outerR) 21 .cornerRadius(cornerRadius) 22 .startAngle(startAngle) 23 .endAngle(endAngle)(null); 24 } 25 26 export function arcAngleFromPct(pct: number) { 27 return Math.PI * (pct * 1.25 - .625); 28 } 29 30 export function angleFromPct(pct: number) { 31 return Math.PI * (-1.25 + 1.25 * pct); 32 } 33 34 // findClosestPoint locates the closest point on the vector starting 35 // from point s and extending through u (t=1), nearest to point p. 36 // Returns an empty vector if the closest point is either start or end 37 // point or located before or after the line segment defined by [s, 38 // e]. 39 export function findClosestPoint(s: [number, number], e: [number, number], p: [number, number]): [number, number] { 40 // u = e - s 41 // v = s+tu - p 42 // d = length(v) 43 // d = length((s-p) + tu) 44 // d = sqrt(([s-p].x + tu.x)^2 + ([s-p].y + tu.y)^2) 45 // d = sqrt([s-p].x^2 + 2[s-p].x*tu.x + t^2u.x^2 + [s-p].y^2 + 2[s-p].y*tu.y + t^2*u.y^2) 46 // ...minimize with first derivative with respect to t 47 // 0 = 2[s-p].x*u.x + 2tu.x^2 + 2[s-p].y*u.y + 2tu.y^2 48 // 0 = [s-p].x*u.x + tu.x^2 + [s-p].y*u.y + tu.y^2 49 // t*(u.x^2 + u.y^2) = [s-p].x*u.x + [s-p].y*u.y 50 // t = ([s-p].x*u.x + [s-p].y*u.y) / (u.x^2 + u.y^2) 51 const u = vector.sub(e, s); 52 const d = vector.sub(s, p); 53 const t = -(d[0] * u[0] + d[1] * u[1]) / (u[0] * u[0] + u[1] * u[1]); 54 if (t <= 0 || t >= 1) { 55 return [0, 0]; 56 } 57 return vector.add(s, vector.mult(u, t)); 58 }