|
| 1 | +d3.geom = {}; |
| 2 | +// Note: requires coordinates to be clockwise and convex! |
| 3 | +d3.geom.polygon = function(coordinates) { |
| 4 | + var n = coordinates.length; |
| 5 | + |
| 6 | + coordinates.area = function() { |
| 7 | + var i = 0, |
| 8 | + a = coordinates[n - 1][0] * coordinates[0][1], |
| 9 | + b = coordinates[n - 1][1] * coordinates[0][0]; |
| 10 | + while (++i < n) { |
| 11 | + a += coordinates[i - 1][0] * coordinates[i][1]; |
| 12 | + b += coordinates[i - 1][1] * coordinates[i][0]; |
| 13 | + } |
| 14 | + return (a - b) * .5; |
| 15 | + }; |
| 16 | + |
| 17 | + // The Sutherland-Hodgman clipping algorithm. |
| 18 | + coordinates.intersection = function(subject) { |
| 19 | + var output = subject, |
| 20 | + input, |
| 21 | + i = -1, |
| 22 | + j, |
| 23 | + m, |
| 24 | + a = coordinates[n - 1], |
| 25 | + b, |
| 26 | + c, |
| 27 | + d; |
| 28 | + while (++i < n) { |
| 29 | + input = output.slice(); |
| 30 | + output = []; |
| 31 | + b = coordinates[i]; |
| 32 | + c = input[(m = input.length) - 1]; |
| 33 | + j = -1; |
| 34 | + while (++j < m) { |
| 35 | + d = input[j]; |
| 36 | + if (d3_geom_polygonInside(d, a, b)) { |
| 37 | + if (!d3_geom_polygonInside(c, a, b)) { |
| 38 | + output.push(d3_geom_polygonIntersect(c, d, a, b)); |
| 39 | + } |
| 40 | + output.push(d); |
| 41 | + } else if (d3_geom_polygonInside(c, a, b)) { |
| 42 | + output.push(d3_geom_polygonIntersect(c, d, a, b)); |
| 43 | + } |
| 44 | + c = d; |
| 45 | + } |
| 46 | + a = b; |
| 47 | + } |
| 48 | + return output; |
| 49 | + }; |
| 50 | + |
| 51 | + return coordinates; |
| 52 | +}; |
| 53 | + |
| 54 | +function d3_geom_polygonInside(p, a, b) { |
| 55 | + return (b[0] - a[0]) * (p[1] - a[1]) >= (b[1] - a[1]) * (p[0] - a[0]); |
| 56 | +} |
| 57 | + |
| 58 | +// Intersect two infinite lines cd and ab. |
| 59 | +function d3_geom_polygonIntersect(c, d, a, b) { |
| 60 | + var x1 = c[0], x2 = d[0], x3 = a[0], x4 = b[0], |
| 61 | + y1 = c[1], y2 = d[1], y3 = a[1], y4 = b[1], |
| 62 | + x13 = x1 - x3, |
| 63 | + x21 = x2 - x1, |
| 64 | + x43 = x4 - x3, |
| 65 | + y13 = y1 - y3, |
| 66 | + y21 = y2 - y1, |
| 67 | + y43 = y4 - y3, |
| 68 | + ua = (x43 * y13 - y43 * x13) / (y43 * x21 - x43 * y21); |
| 69 | + return [x1 + ua * x21, y1 + ua * y21]; |
| 70 | +} |
0 commit comments