From bec7b93f13450a02ca62995992d1f488d2ff24be Mon Sep 17 00:00:00 2001 From: Karsten Schmidt Date: Mon, 13 Jul 2020 01:40:48 +0100 Subject: [PATCH] feat(geom-clip-line): add clipLineSegmentPoly() --- packages/geom-clip-line/src/clip-poly.ts | 26 +++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/packages/geom-clip-line/src/clip-poly.ts b/packages/geom-clip-line/src/clip-poly.ts index 9a7a96e626..68628e0b3b 100644 --- a/packages/geom-clip-line/src/clip-poly.ts +++ b/packages/geom-clip-line/src/clip-poly.ts @@ -1,4 +1,8 @@ -import { intersectRayPolylineAll } from "@thi.ng/geom-isec"; +import { + intersectLinePolylineAll, + intersectRayPolylineAll, + pointInPolygon2, +} from "@thi.ng/geom-isec"; import { direction, ReadonlyVec, Vec } from "@thi.ng/vectors"; /** @@ -24,3 +28,23 @@ export const clipLinePoly = ( } return segments; }; + +export const clipLineSegmentPoly = ( + a: ReadonlyVec, + b: ReadonlyVec, + pts: ReadonlyVec[] +) => { + const isecs = intersectLinePolylineAll(a, b, pts, true).isec; + const isAInside = pointInPolygon2(a, pts); + const isBInside = pointInPolygon2(b, pts); + if (!isecs) { + return isAInside && isBInside ? [[a, b]] : undefined; + } + isAInside && (isecs).unshift(a); + isBInside && (isecs).push(b); + const segments: Vec[][] = []; + for (let i = 0, n = isecs.length - 1; i < n; i += 2) { + segments.push([isecs[i], isecs[i + 1]]); + } + return segments; +};