poly-math-2d
Version:
2D Polygon math: boolean operations, triangulation, graphs, support for holes and non-convex shapes.
50 lines (49 loc) • 2.1 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PolygonMap = void 0;
exports.toPolygonClippingFormat = toPolygonClippingFormat;
const polygon_js_1 = require("./polygon.js");
const polygon_clipping_1 = __importDefault(require("polygon-clipping"));
function toPolygonClippingFormat(pts) {
// polygon-clipping expects Polygon: [ [ [x, y], ... ] ]
if (pts.length === 0)
return [];
const ring = pts.map(p => [p.x, p.y]);
// Close the contour if not closed
if (ring.length > 0 && (ring[0][0] !== ring[ring.length - 1][0] || ring[0][1] !== ring[ring.length - 1][1])) {
ring.push([ring[0][0], ring[0][1]]);
}
return [ring]; // Polygon: array of rings
}
class PolygonMap {
constructor(polygons = []) {
this.polygons = polygons;
}
// Union of two PolygonMap
unionPolygon(other) {
let allPolys = [...this.polygons, ...other.polygons];
if (allPolys.length === 0)
return new PolygonMap([]);
// Collect all polygons for polygon-clipping
const allPolyRings = allPolys.map(p => toPolygonClippingFormat(p.points)); // number[][][]
const result = polygon_clipping_1.default.union(...allPolyRings);
return new PolygonMap(polygon_js_1.Polygon.fromClippingResult(result));
}
// Difference PolygonMap - PolygonMap
differencePolygon(other) {
if (this.polygons.length === 0)
return new PolygonMap([]);
const otherPolyRings = other.polygons.map(p => toPolygonClippingFormat(p.points));
let resultPolys = [];
for (const p of this.polygons) {
const poly = toPolygonClippingFormat(p.points);
const diff = polygon_clipping_1.default.difference(poly, ...otherPolyRings);
resultPolys.push(...polygon_js_1.Polygon.fromClippingResult(diff));
}
return new PolygonMap(resultPolys);
}
}
exports.PolygonMap = PolygonMap;