All files / services polyline.ts

97.34% Statements 183/188
93.33% Branches 84/90
100% Functions 17/17
97.09% Lines 167/172

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531                                                6x 6x 9x 9x 9x   6x                         3x                         2x                         4x                         4x 4x 4x 4x                         1x                                 51x 102x                                 51x   51x 51x 51x   51x 4x       47x 90x       47x 12x 12x       47x                           13x 13x 13x   13x 4x     9x 9x   9x 36x 59x 59x 4x     59x 31x     28x             28x 11x 11x 13x         3x 3x     11x 8x           9x                           19x 19x 19x   19x 19x   19x 38x 60x             60x 17x 17x 10x         1x 1x       17x 16x           19x                           43x 43x 43x 10x     33x 33x 33x 33x               33x 33x   33x 564x 564x 564x 564x       33x 285x 285x 3x 3x     282x 282x 282x 282x   282x   282x   282x 282x   282x               33x     261x 261x 261x 261x   261x 783x 2349x 7047x         261x 261x   261x 7047x 7047x   264x   737x 363x 363x   363x   217x 217x 217x             261x 217x   44x         33x 285x     65x 65x 65x 65x 65x 65x 65x     65x 233x 233x     211x 211x     211x 43x   43x 43x       168x 168x 168x       65x 65x 22x 28x 28x   6x 6x     6x               6x 6x 6x           65x 22x       65x   24x           65x           33x                                               11x                                               4x   4x   1x         3x     3x          
import { GeometryHelper } from "./geometry-helper";
import * as Inputs from "../inputs";
import { Point } from "./point";
import { Vector } from "./vector";
import { Line } from "./line";
 
/**
 * Contains various methods for polyline. Polyline in bitbybit is a simple object that has points property containing an array of points.
 * { points: number[][] }
 */
export class Polyline {
 
    constructor(private readonly vector: Vector, private readonly point: Point, private readonly line: Line, private readonly geometryHelper: GeometryHelper) { }
 
    /**
     * Calculates total length of polyline by summing distances between consecutive points.
     * Example: points=[[0,0,0], [3,0,0], [3,4,0]] → 3 + 4 = 7
     * @param inputs a polyline
     * @returns length
     * @group get
     * @shortname polyline length
     * @drawable false
     */
    length(inputs: Inputs.Polyline.PolylineDto): number {
        let distanceOfPolyline = 0;
        for (let i = 1; i < inputs.polyline.points.length; i++) {
            const previousPoint = inputs.polyline.points[i - 1];
            const currentPoint = inputs.polyline.points[i];
            distanceOfPolyline += this.point.distance({ startPoint: previousPoint, endPoint: currentPoint });
        }
        return distanceOfPolyline;
    }
 
    /**
     * Counts number of points in polyline.
     * Example: polyline with points=[[0,0,0], [1,0,0], [1,1,0]] → 3
     * @param inputs a polyline
     * @returns nr of points
     * @group get
     * @shortname nr polyline points
     * @drawable false
     */
    countPoints(inputs: Inputs.Polyline.PolylineDto): number {
        return inputs.polyline.points.length;
    }
 
    /**
     * Extracts points array from polyline object.
     * Example: polyline={points:[[0,0,0], [1,0,0]]} → [[0,0,0], [1,0,0]]
     * @param inputs a polyline
     * @returns points
     * @group get
     * @shortname points
     * @drawable true
     */
    getPoints(inputs: Inputs.Polyline.PolylineDto): Inputs.Base.Point3[] {
        return inputs.polyline.points;
    }
 
    /**
     * Reverses point order of polyline (flips direction).
     * Example: points=[[0,0,0], [1,0,0], [2,0,0]] → [[2,0,0], [1,0,0], [0,0,0]]
     * @param inputs a polyline
     * @returns reversed polyline
     * @group convert
     * @shortname reverse polyline
     * @drawable true
     */
    reverse(inputs: Inputs.Polyline.PolylineDto): Inputs.Polyline.PolylinePropertiesDto {
        return { points: inputs.polyline.points.reverse() };
    }
 
    /**
     * Applies transformation matrix to all points in polyline (rotates, scales, or translates).
     * Example: polyline with 4 points, translation [5,0,0] → all points moved +5 in X direction
     * @param inputs a polyline
     * @returns transformed polyline
     * @group transforms
     * @shortname transform polyline
     * @drawable true
     */
    transformPolyline(inputs: Inputs.Polyline.TransformPolylineDto): Inputs.Polyline.PolylinePropertiesDto {
        const transformation = inputs.transformation;
        let transformedControlPoints = inputs.polyline.points;
        transformedControlPoints = this.geometryHelper.transformControlPoints(transformation, transformedControlPoints);
        return { points: transformedControlPoints };
    }
 
    /**
     * Creates a polyline from points array with optional isClosed flag.
     * Example: points=[[0,0,0], [1,0,0], [1,1,0]], isClosed=true → {points:..., isClosed:true}
     * @param inputs points and info if its closed
     * @returns polyline
     * @group create
     * @shortname polyline
     * @drawable true
     */
    create(inputs: Inputs.Polyline.PolylineCreateDto): Inputs.Polyline.PolylinePropertiesDto {
        return {
            points: inputs.points,
            isClosed: inputs.isClosed ?? false,
        };
    }
 
    /**
     * Converts polyline to line segments (each segment as line object with start/end).
     * Closed polylines include closing segment.
     * Example: 3 points → 2 or 3 lines (depending on isClosed)
     * @param inputs polyline
     * @returns lines
     * @group convert
     * @shortname polyline to lines
     * @drawable true
     */
    polylineToLines(inputs: Inputs.Polyline.PolylineDto): Inputs.Base.Line3[] {
        const segments = this.polylineToSegments(inputs);
        return segments.map((segment) => ({
            start: segment[0],
            end: segment[1],
        }));
    }
 
    /**
     * Converts polyline to segment arrays (each segment as [point1, point2]).
     * Closed polylines include closing segment if endpoints differ.
     * Example: 4 points, closed → 4 segments connecting all points in a loop
     * @param inputs polyline
     * @returns segments
     * @group convert
     * @shortname polyline to segments
     * @drawable false
     */
    polylineToSegments(inputs: Inputs.Polyline.PolylineDto): Inputs.Base.Segment3[] {
        const polyline = inputs.polyline;
 
        const segments: Inputs.Base.Segment3[] = [];
        const points = polyline.points;
        const numPoints = points.length;
 
        if (numPoints < 2) {
            return segments;
        }
 
        // Create segments between consecutive points
        for (let i = 0; i < numPoints - 1; i++) {
            segments.push([points[i], points[i + 1]]);
        }
 
        // Add closing segment if the polyline is closed and has enough points
        if (polyline.isClosed && numPoints >= 2) {
            Eif (!this.point.twoPointsAlmostEqual({ point1: points[numPoints - 1], point2: points[0], tolerance: 1e-9 })) {
                segments.push([points[numPoints - 1], points[0]]);
            }
        }
 
        return segments;
    }
 
    /**
     * Finds points where polyline crosses itself (self-intersection points).
     * Skips adjacent segments and deduplicates close points.
     * Example: figure-8 shaped polyline → returns center crossing point
     * @param inputs points of self intersection
     * @returns polyline
     * @group intersections
     * @shortname polyline self intersections
     * @drawable true
     */
    polylineSelfIntersection(inputs: Inputs.Polyline.PolylineToleranceDto): Inputs.Base.Point3[] {
        const { polyline, tolerance } = inputs;
        const lines = this.polylineToLines({ polyline });
        const numSegments = lines.length;
 
        if (numSegments < 3) {
            return [];
        }
 
        const selfIntersectionPoints: Inputs.Base.Point3[] = [];
        const defaultTolerance = tolerance ?? 1e-6;
 
        for (let i = 0; i < numSegments; i++) {
            for (let j = i + 1; j < numSegments; j++) {
                let areAdjacent = (j === i + 1);
                if (!areAdjacent && polyline.isClosed && i === 0 && j === numSegments - 1) {
                    areAdjacent = true;
                }
 
                if (areAdjacent) {
                    continue;
                }
 
                const intersection = this.line.lineLineIntersection({
                    line1: lines[i],
                    line2: lines[j],
                    checkSegmentsOnly: true,
                    tolerance: defaultTolerance,
                });
 
                if (intersection) {
                    let foundClose = false;
                    for (const existingPoint of selfIntersectionPoints) {
                        if (this.point.twoPointsAlmostEqual({
                            point1: intersection,
                            point2: existingPoint,
                            tolerance: defaultTolerance
                        })) {
                            foundClose = true;
                            break;
                        }
                    }
                    if (!foundClose) {
                        selfIntersectionPoints.push(intersection);
                    }
                }
            }
        }
 
        return selfIntersectionPoints;
    }
 
    /**
     * Finds intersection points between two polylines (all segment-segment crossings).
     * Tests all segment pairs and deduplicates close points.
     * Example: crossing polylines forming an X → returns center intersection point
     * @param inputs two polylines and tolerance
     * @returns points
     * @group intersection
     * @shortname two polyline intersection
     * @drawable true
     */
    twoPolylineIntersection(inputs: Inputs.Polyline.TwoPolylinesToleranceDto): Inputs.Base.Point3[] {
        const { polyline1, polyline2, tolerance } = inputs;
        const lines1 = this.polylineToLines({ polyline: polyline1 });
        const lines2 = this.polylineToLines({ polyline: polyline2 });
 
        const intersectionPoints: Inputs.Base.Point3[] = [];
        const defaultTolerance = tolerance ?? 1e-6;
 
        for (const seg1 of lines1) {
            for (const seg2 of lines2) {
                const intersection = this.line.lineLineIntersection({
                    line1: seg1,
                    line2: seg2,
                    checkSegmentsOnly: true,
                    tolerance: defaultTolerance,
                });
 
                if (intersection) {
                    let foundClose = false;
                    for (const existingPoint of intersectionPoints) {
                        if (this.point.twoPointsAlmostEqual({
                            point1: intersection,
                            point2: existingPoint,
                            tolerance: defaultTolerance
                        })) {
                            foundClose = true;
                            break;
                        }
                    }
 
                    if (!foundClose) {
                        intersectionPoints.push(intersection);
                    }
                }
            }
        }
 
        return intersectionPoints;
    }
 
    /**
     * Sorts scrambled segments into connected polylines by matching endpoints.
     * Uses spatial hashing for efficient connection finding.
     * Example: 10 random segments that form 2 connected paths → 2 polylines
     * @param inputs segments
     * @returns polylines
     * @group sort
     * @shortname segments to polylines
     * @drawable true
     */
    sortSegmentsIntoPolylines(inputs: Inputs.Polyline.SegmentsToleranceDto): Inputs.Base.Polyline3[] {
        const tolerance = inputs.tolerance ?? 1e-5; // Default tolerance
        const segments = inputs.segments;
        if (!segments || segments.length === 0) {
            return [];
        }
 
        const toleranceSq = tolerance * tolerance;
        const numSegments = segments.length;
        const used = new Array<boolean>(numSegments).fill(false);
        const results: Inputs.Base.Polyline3[] = [];
 
        // --- Spatial Hash Map ---
        interface EndpointInfo {
            segmentIndex: number;
            endpointIndex: 0 | 1;
            coords: Inputs.Base.Point3;
        }
        const endpointMap = new Map<string, EndpointInfo[]>();
        const invTolerance = 1.0 / tolerance;
 
        const getGridKey = (p: Inputs.Base.Point3): string => {
            const ix = Math.round(p[0] * invTolerance);
            const iy = Math.round(p[1] * invTolerance);
            const iz = Math.round(p[2] * invTolerance);
            return `${ix},${iy},${iz}`;
        };
 
        // 1. Build the spatial map
        for (let i = 0; i < numSegments; i++) {
            const segment = segments[i];
            if (this.point.twoPointsAlmostEqual({ point1: segment[0], point2: segment[1], tolerance: tolerance })) {
                used[i] = true; // Mark degenerate as used
                continue;
            }
 
            const key0 = getGridKey(segment[0]);
            const key1 = getGridKey(segment[1]);
            const info0: EndpointInfo = { segmentIndex: i, endpointIndex: 0, coords: segment[0] };
            const info1: EndpointInfo = { segmentIndex: i, endpointIndex: 1, coords: segment[1] };
 
            if (!endpointMap.has(key0)) endpointMap.set(key0, []);
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            endpointMap.get(key0)!.push(info0);
 
            if (key1 !== key0) {
                if (!endpointMap.has(key1)) endpointMap.set(key1, []);
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                endpointMap.get(key1)!.push(info1);
            } else E{
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                endpointMap.get(key0)!.push(info1); // Add both endpoints if same key
            }
        }
 
        // --- Helper to find connecting segment ---
        const findConnection = (
            pointToMatch: Inputs.Base.Point3
        ): EndpointInfo | undefined => {
            const searchKeys: string[] = [];
            const px = Math.round(pointToMatch[0] * invTolerance);
            const py = Math.round(pointToMatch[1] * invTolerance);
            const pz = Math.round(pointToMatch[2] * invTolerance);
 
            for (let dx = -1; dx <= 1; dx++) {
                for (let dy = -1; dy <= 1; dy++) {
                    for (let dz = -1; dz <= 1; dz++) {
                        searchKeys.push(`${px + dx},${py + dy},${pz + dz}`);
                    }
                }
            }
 
            let bestMatch: EndpointInfo | undefined = undefined;
            let minDistanceSq = toleranceSq;
 
            for (const searchKey of searchKeys) {
                const candidates = endpointMap.get(searchKey);
                if (!candidates) continue;
 
                for (const candidate of candidates) {
                    // Only consider segments not already used in *any* polyline
                    if (!used[candidate.segmentIndex]) {
                        const diffVector = this.vector.sub({ first: candidate.coords, second: pointToMatch });
                        const distSq = this.vector.lengthSq({ vector: diffVector as Inputs.Base.Vector3 });
 
                        if (distSq < minDistanceSq) {
                            // Check with precise method if it's a potential best match
                            Eif (this.point.twoPointsAlmostEqual({ point1: candidate.coords, point2: pointToMatch, tolerance: tolerance })) {
                                bestMatch = candidate;
                                minDistanceSq = distSq; // Update min distance found
                            }
                        }
                    }
                }
            }
            // No need for final check here, already done inside the loop
            if (bestMatch && !used[bestMatch.segmentIndex]) { // Double check used status
                return bestMatch;
            }
            return undefined;
        };
 
 
        // 2. Iterate and chain segments
        for (let i = 0; i < numSegments; i++) {
            if (used[i]) continue; // Skip if already part of a polyline
 
            // Start a new polyline
            used[i] = true; // Mark the starting segment as used
            const startSegment = segments[i];
            const currentPoints: Inputs.Base.Point3[] = [startSegment[0], startSegment[1]];
            let currentHead = startSegment[0];
            let currentTail = startSegment[1];
            let isClosed = false;
            let iterations = 0;
 
            // Extend forward (tail)
            while (iterations++ < numSegments) {
                const nextMatch = findConnection(currentTail);
                if (!nextMatch) break; // No unused segment connects to the tail
 
                // We found a potential next segment
                const nextSegment = segments[nextMatch.segmentIndex];
                const pointToAdd = (nextMatch.endpointIndex === 0) ? nextSegment[1] : nextSegment[0];
 
                // Check for closure *before* adding the point
                if (this.point.twoPointsAlmostEqual({ point1: pointToAdd, point2: currentHead, tolerance: tolerance })) {
                    isClosed = true;
                    // Mark the closing segment as used
                    used[nextMatch.segmentIndex] = true;
                    break; // Closed loop found
                }
 
                // Not closing, so add the point and mark the segment used
                used[nextMatch.segmentIndex] = true;
                currentPoints.push(pointToAdd);
                currentTail = pointToAdd;
            }
 
            // Extend backward (head) - only if not already closed
            iterations = 0;
            if (!isClosed) {
                while (iterations++ < numSegments) {
                    const prevMatch = findConnection(currentHead);
                    if (!prevMatch) break; // No unused segment connects to the head
 
                    const prevSegment = segments[prevMatch.segmentIndex];
                    const pointToAdd = (prevMatch.endpointIndex === 0) ? prevSegment[1] : prevSegment[0];
 
                    // Check for closure against the current tail *before* adding
                    Iif (this.point.twoPointsAlmostEqual({ point1: pointToAdd, point2: currentTail, tolerance: tolerance })) {
                        isClosed = true;
                        // Mark the closing segment as used
                        used[prevMatch.segmentIndex] = true;
                        break; // Closed loop found
                    }
 
                    // Not closing, add point to beginning and mark segment used
                    used[prevMatch.segmentIndex] = true;
                    currentPoints.unshift(pointToAdd);
                    currentHead = pointToAdd;
                }
            }
 
            // Final closure check (might be redundant now, but harmless)
            // This catches cases like A->B, B->A which form a 2-point closed loop
            if (!isClosed && currentPoints.length >= 2) {
                isClosed = this.point.twoPointsAlmostEqual({ point1: currentHead, point2: currentTail, tolerance: tolerance });
            }
 
            // Remove duplicate point for closed loops with more than 2 points
            if (isClosed && currentPoints.length > 2) {
                // Check if the first and last points are indeed the ones needing merging
                Iif (this.point.twoPointsAlmostEqual({ point1: currentPoints[currentPoints.length - 1], point2: currentPoints[0], tolerance: tolerance })) {
                    currentPoints.pop();
                }
            }
 
            // Add the completed polyline (even if it's just the starting segment)
            results.push({
                points: currentPoints,
                isClosed: isClosed,
            });
        }
 
        return results;
    }
 
    /**
     * Calculates the maximum possible half-line fillet radius for each corner
     * of a given polyline. For a closed polyline, it includes the corners
     * connecting the last segment back to the first.
     *
     * The calculation uses the 'half-line' constraint, meaning the fillet's
     * tangent points must lie within the first half of each segment connected
     * to the corner.
     *
     * @param inputs Defines the polyline points, whether it's closed, and an optional tolerance.
     * @returns An array containing the maximum fillet radius calculated for each corner.
     *          The order corresponds to corners P[1]...P[n-2] for open polylines,
     *          and P[1]...P[n-2], P[0], P[n-1] for closed polylines.
     *          Returns an empty array if the polyline has fewer than 3 points.
     * @group fillet
     * @shortname polyline max fillet radii
     * @drawable false
     */
    maxFilletsHalfLine(
        inputs: Inputs.Polyline.PolylineToleranceDto
    ): number[] {
        return this.point.maxFilletsHalfLine({
            points: inputs.polyline.points,
            checkLastWithFirst: inputs.polyline.isClosed,
            tolerance: inputs.tolerance,
        });
    }
 
    /**
     * Calculates the single safest maximum fillet radius that can be applied
     * uniformly to all corners of a polyline, based on the 'half-line' constraint.
     * This is determined by finding the minimum of the maximum possible fillet
     * radii calculated for each individual corner.
     *
     * @param inputs Defines the polyline points, whether it's closed, and an optional tolerance.
     * @returns The smallest value from the results of calculatePolylineMaxFillets.
     *          Returns 0 if the polyline has fewer than 3 points or if any
     *          calculated maximum radius is 0.
     * @group fillet
     * @shortname polyline safest fillet radius
     * @drawable false
     */
    safestFilletRadius(
        inputs: Inputs.Polyline.PolylineToleranceDto
    ): number {
        const allMaxRadii = this.maxFilletsHalfLine(inputs);
 
        if (allMaxRadii.length === 0) {
            // No corners, or fewer than 3 points. No fillet possible.
            return 0;
        }
 
        // Find the minimum radius among all calculated maximums.
        // If any corner calculation resulted in 0, the safest radius is 0.
        const safestRadius = Math.min(...allMaxRadii);
 
        // Ensure we don't return a negative radius if Math.min had weird input (shouldn't happen here)
        return Math.max(0, safestRadius);
    }
 
}