All files / services point.ts

98.17% Statements 376/383
92.85% Branches 143/154
100% Functions 62/62
98.03% Lines 350/357

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 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122                                                      3x 3x 3x 3x                         3x                           3x 1x   2x 2x                           47x 47x                           2x 1x   1x 1x 2x                           1x 1x                         1x 1x                         150x 150x                         26x 26x                         4x 4x 4x   4x 10x 10x 10x     4x 4x 4x         4x 4x 4x 4x                                       2x                         2x                         2x                         1059x 1059x 1059x 1059x                         2x 3x                           3x 3x 3x   3x                         1x                         1x                         1x                         3x 3x 3x   3x 4x 4x 4x     3x 4x 4x 4x                           1x                         1x                           3x 3x 3x 3x 3x 27x 27x 27x 27x   3x                           42x 42x 42x 103x 103x 285x 285x 285x       42x 1x 1x 1x 9x       42x 1x 4x       42x                           40x 40x 40x 40x 40x 40x 40x 40x           40x       40x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       40x 3x 3x         37x 37x               37x         37x 247x       37x 37x 247x 1482x 1482x 1482x 1482x       37x 37x       37x 37x               247x           37x 1482x             37x 37x 37x     37x 37x 37x           37x 222x 222x 222x 79x   222x 85x       37x 10x 10x 10x 10x   10x 2x         2x 13x 13x   2x 2x   10x 2x         2x 18x 18x   2x 2x   10x 3x         3x 34x 34x   3x 3x   10x 1x         1x 9x 9x   1x 1x   10x 2x         2x 18x 18x   2x 2x   10x 3x         3x 34x 34x   3x 3x         37x   3x           3x 22x                 3x       3x       3x 22x                   37x 1x 1x   1x         1x 4x 4x   1x 4x 24x 24x           37x 1x 4x   1x 4x 24x           37x 3x         3x     8x 3x   3x         3x     8x 3x       37x                                           12x   12x 12x   12x 12x   12x 4x     8x 8x 8x           8x       8x 1x     7x 1x       6x       6x     6x             6x   6x                               270x   270x 270x   270x 270x   270x 2x     268x 268x   268x       268x   268x 4x     264x 264x   264x               264x   264x                               59x 59x 59x     59x 5x       54x 175x 175x 175x       175x           175x       54x   44x 44x 44x 44x           44x     44x 44x 44x 44x           44x     54x                                     48x   48x   3x         45x     45x                         8x                         8x 8x 8x   8x 2x       6x 6x 6x     6x 6x 6x     6x 6x 6x         6x 2x 2x     4x 1x 1x 1x     4x           6x     6x 12x 12x 12x 6x 6x 6x     6x                         804x 804x 804x 804x                         11x 53x 16x 7x                     247x 247x 247x 247x   247x   247x 1482x 1482x           247x      
import { GeometryHelper } from "./geometry-helper";
import * as Inputs from "../inputs";
import { Transforms } from "./transforms";
import { Vector } from "./vector";
import * as Models from "../models";
import { Lists } from "./lists";
 
/**
 * Contains various methods for points. Point in bitbybit is simply an array containing 3 numbers for [x, y, z].
 * Because of this form Point can be interchanged with Vector, which also is an array in [x, y, z] form.
 * When creating 2D points, z coordinate is simply set to 0 - [x, y, 0].
 */
 
export class Point {
 
    constructor(private readonly geometryHelper: GeometryHelper, private readonly transforms: Transforms, private readonly vector: Vector, private readonly lists: Lists) { }
 
    /**
     * Applies transformation matrix to a single point (rotates, scales, or translates).
     * Example: point=[0,0,0] with translation [5,5,0] → [5,5,0]
     * @param inputs Contains a point and the transformations to apply
     * @returns Transformed point
     * @group transforms
     * @shortname transform point
     * @drawable true
     */
    transformPoint(inputs: Inputs.Point.TransformPointDto): Inputs.Base.Point3 {
        const transformation = inputs.transformation;
        let transformedControlPoints = [inputs.point];
        transformedControlPoints = this.geometryHelper.transformControlPoints(transformation, transformedControlPoints);
        return transformedControlPoints[0];
    }
 
    /**
     * Applies same transformation matrix to multiple points (batch transform).
     * Example: 5 points with rotation 90° → all 5 points rotated together
     * @param inputs Contains points and the transformations to apply
     * @returns Transformed points
     * @group transforms
     * @shortname transform points
     * @drawable true
     */
    transformPoints(inputs: Inputs.Point.TransformPointsDto): Inputs.Base.Point3[] {
        return this.geometryHelper.transformControlPoints(inputs.transformation, inputs.points);
    }
 
    /**
     * Applies different transformation matrices to corresponding points (one transform per point).
     * Arrays must have equal length.
     * Example: 3 points with 3 different translations → each point moved independently
     * @param inputs Contains points and the transformations to apply
     * @returns Transformed points
     * @group transforms
     * @shortname transforms for points
     * @drawable true
     */
    transformsForPoints(inputs: Inputs.Point.TransformsForPointsDto): Inputs.Base.Point3[] {
        if (inputs.points.length !== inputs.transformation.length) {
            throw new Error("You must provide equal nr of points and transformations");
        }
        return inputs.points.map((pt, index) => {
            return this.geometryHelper.transformControlPoints(inputs.transformation[index], [pt])[0];
        });
    }
 
    /**
     * Moves multiple points by a translation vector (same offset for all points).
     * Example: points=[[0,0,0], [1,0,0]], translation=[5,5,0] → [[5,5,0], [6,5,0]]
     * @param inputs Contains points and the translation vector
     * @returns Translated points
     * @group transforms
     * @shortname translate points
     * @drawable true
     */
    translatePoints(inputs: Inputs.Point.TranslatePointsDto): Inputs.Base.Point3[] {
        const translationTransform = this.transforms.translationXYZ({ translation: inputs.translation });
        return this.geometryHelper.transformControlPoints(translationTransform, inputs.points);
    }
 
    /**
     * Moves multiple points by corresponding translation vectors (one vector per point).
     * Arrays must have equal length.
     * Example: 3 points with 3 different vectors → each point moved by its corresponding vector
     * @param inputs Contains points and the translation vector
     * @returns Translated points
     * @group transforms
     * @shortname translate points with vectors
     * @drawable true
     */
    translatePointsWithVectors(inputs: Inputs.Point.TranslatePointsWithVectorsDto): Inputs.Base.Point3[] {
        if (inputs.points.length !== inputs.translations.length) {
            throw new Error("You must provide equal nr of points and translations");
        }
        const translationTransforms = this.transforms.translationsXYZ({ translations: inputs.translations });
        return inputs.points.map((pt, index) => {
            return this.geometryHelper.transformControlPoints(translationTransforms[index], [pt])[0];
        });
    }
 
    /**
     * Moves multiple points by separate X, Y, Z values (convenience method for translation).
     * Example: points=[[0,0,0]], x=10, y=5, z=0 → [[10,5,0]]
     * @param inputs Contains points and the translation in x y and z
     * @returns Translated points
     * @group transforms
     * @shortname translate xyz points
     * @drawable true
     */
    translateXYZPoints(inputs: Inputs.Point.TranslateXYZPointsDto): Inputs.Base.Point3[] {
        const translationTransform = this.transforms.translationXYZ({ translation: [inputs.x, inputs.y, inputs.z] });
        return this.geometryHelper.transformControlPoints(translationTransform, inputs.points);
    }
 
    /**
     * Scales multiple points around a center point with different factors per axis.
     * Example: points=[[10,0,0]], center=[5,0,0], scaleXyz=[2,1,1] → [[15,0,0]] (doubles X distance from center)
     * @param inputs Contains points, center point and scale factors
     * @returns Scaled points
     * @group transforms
     * @shortname scale points on center
     * @drawable true
     */
    scalePointsCenterXYZ(inputs: Inputs.Point.ScalePointsCenterXYZDto): Inputs.Base.Point3[] {
        const scaleTransforms = this.transforms.scaleCenterXYZ({ center: inputs.center, scaleXyz: inputs.scaleXyz });
        return this.geometryHelper.transformControlPoints(scaleTransforms, inputs.points);
    }
 
    /**
     * Stretches multiple points along a direction from a center point (directional scaling).
     * Example: points=[[10,0,0]], center=[0,0,0], direction=[1,0,0], scale=2 → [[20,0,0]]
     * @param inputs Contains points, center point, direction and scale factor
     * @returns Stretched points
     * @group transforms
     * @shortname stretch points dir from center
     * @drawable true
     */
    stretchPointsDirFromCenter(inputs: Inputs.Point.StretchPointsDirFromCenterDto): Inputs.Base.Point3[] {
        const stretchTransforms = this.transforms.stretchDirFromCenter({ center: inputs.center, scale: inputs.scale, direction: inputs.direction });
        return this.geometryHelper.transformControlPoints(stretchTransforms, inputs.points);
    }
 
    /**
     * Rotates multiple points around a center point along a custom axis.
     * Example: points=[[10,0,0]], center=[0,0,0], axis=[0,1,0], angle=90° → [[0,0,-10]]
     * @param inputs Contains points, axis, center point and angle of rotation
     * @returns Rotated points
     * @group transforms
     * @shortname rotate points center axis
     * @drawable true
     */
    rotatePointsCenterAxis(inputs: Inputs.Point.RotatePointsCenterAxisDto): Inputs.Base.Point3[] {
        const rotationTransforms = this.transforms.rotationCenterAxis({ center: inputs.center, axis: inputs.axis, angle: inputs.angle });
        return this.geometryHelper.transformControlPoints(rotationTransforms, inputs.points);
    }
 
    /**
     * Calculates axis-aligned bounding box containing all points (min, max, center, width, height, length).
     * Example: points=[[0,0,0], [10,5,3]] → {min:[0,0,0], max:[10,5,3], center:[5,2.5,1.5], width:10, height:5, length:3}
     * @param inputs Points
     * @returns Bounding box of points
     * @group extract
     * @shortname bounding box pts
     * @drawable true
     */
    boundingBoxOfPoints(inputs: Inputs.Point.PointsDto): Inputs.Base.BoundingBox {
        const xVals = [];
        const yVals = [];
        const zVals = [];
 
        inputs.points.forEach(pt => {
            xVals.push(pt[0]);
            yVals.push(pt[1]);
            zVals.push(pt[2]);
        });
 
        const min = [Math.min(...xVals), Math.min(...yVals), Math.min(...zVals)] as Inputs.Base.Point3;
        const max = [Math.max(...xVals), Math.max(...yVals), Math.max(...zVals)] as Inputs.Base.Point3;
        const center = [
            (min[0] + max[0]) / 2,
            (min[1] + max[1]) / 2,
            (min[2] + max[2]) / 2,
        ] as Inputs.Base.Point3;
        const width = max[0] - min[0];
        const height = max[1] - min[1];
        const length = max[2] - min[2];
        return {
            min,
            max,
            center,
            width,
            height,
            length,
        };
    }
 
    /**
     * Calculates distance to the nearest point in a collection.
     * Example: point=[0,0,0], points=[[5,0,0], [10,0,0], [3,0,0]] → 3 (distance to [3,0,0])
     * @param inputs Point from which to measure and points to measure the distance against
     * @returns Distance to closest point
     * @group extract
     * @shortname distance to closest pt
     * @drawable false
     */
    closestPointFromPointsDistance(inputs: Inputs.Point.ClosestPointFromPointsDto): number {
        return this.closestPointFromPointData(inputs).distance;
    }
 
    /**
     * Finds array index of the nearest point in a collection (1-based index, not 0-based).
     * Example: point=[0,0,0], points=[[5,0,0], [10,0,0], [3,0,0]] → 3 (index of [3,0,0])
     * @param inputs Point from which to find the index in a collection of points
     * @returns Closest point index
     * @group extract
     * @shortname index of closest pt
     * @drawable false
     */
    closestPointFromPointsIndex(inputs: Inputs.Point.ClosestPointFromPointsDto): number {
        return this.closestPointFromPointData(inputs).index;
    }
 
    /**
     * Finds the nearest point in a collection to a reference point.
     * Example: point=[0,0,0], points=[[5,0,0], [10,0,0], [3,0,0]] → [3,0,0]
     * @param inputs Point and points collection to find the closest point in
     * @returns Closest point
     * @group extract
     * @shortname closest pt
     * @drawable true
     */
    closestPointFromPoints(inputs: Inputs.Point.ClosestPointFromPointsDto): Inputs.Base.Point3 {
        return this.closestPointFromPointData(inputs).point as Inputs.Base.Point3;
    }
 
    /**
     * Calculates Euclidean distance between two points.
     * Example: start=[0,0,0], end=[3,4,0] → 5 (using Pythagorean theorem: √(3²+4²))
     * @param inputs Coordinates of start and end points
     * @returns Distance
     * @group measure
     * @shortname distance
     * @drawable false
     */
    distance(inputs: Inputs.Point.StartEndPointsDto): number {
        const x = inputs.endPoint[0] - inputs.startPoint[0];
        const y = inputs.endPoint[1] - inputs.startPoint[1];
        const z = inputs.endPoint[2] - inputs.startPoint[2];
        return Math.sqrt(x * x + y * y + z * z);
    }
 
    /**
     * Calculates distances from a start point to multiple end points.
     * Example: start=[0,0,0], endPoints=[[3,0,0], [0,4,0], [5,0,0]] → [3, 4, 5]
     * @param inputs Coordinates of start and end points
     * @returns Distances
     * @group measure
     * @shortname distances to points
     * @drawable false
     */
    distancesToPoints(inputs: Inputs.Point.StartEndPointsListDto): number[] {
        return inputs.endPoints.map(pt => {
            return this.distance({ startPoint: inputs.startPoint, endPoint: pt });
        });
    }
 
    /**
     * Duplicates a point N times (creates array with N copies of the same point).
     * Example: point=[5,5,0], amountOfPoints=3 → [[5,5,0], [5,5,0], [5,5,0]]
     * @param inputs The point to be multiplied and the amount of points to create
     * @returns Distance
     * @group transforms
     * @shortname multiply point
     * @drawable true
     */
    multiplyPoint(inputs: Inputs.Point.MultiplyPointDto): Inputs.Base.Point3[] {
        const points = [];
        for (let i = 0; i < inputs.amountOfPoints; i++) {
            points.push([inputs.point[0], inputs.point[1], inputs.point[2]]);
        }
        return points;
    }
 
    /**
     * Extracts X coordinate from a point.
     * Example: point=[5,10,3] → 5
     * @param inputs The point
     * @returns X coordinate
     * @group get
     * @shortname x coord
     * @drawable false
     */
    getX(inputs: Inputs.Point.PointDto): number {
        return inputs.point[0];
    }
 
    /**
     * Extracts Y coordinate from a point.
     * Example: point=[5,10,3] → 10
     * @param inputs The point
     * @returns Y coordinate
     * @group get
     * @shortname y coord
     * @drawable false
     */
    getY(inputs: Inputs.Point.PointDto): number {
        return inputs.point[1];
    }
 
    /**
     * Extracts Z coordinate from a point.
     * Example: point=[5,10,3] → 3
     * @param inputs The point
     * @returns Z coordinate
     * @group get
     * @shortname z coord
     * @drawable false
     */
    getZ(inputs: Inputs.Point.PointDto): number {
        return inputs.point[2];
    }
 
    /**
     * Calculates centroid (average position) of multiple points.
     * Example: points=[[0,0,0], [10,0,0], [10,10,0]] → [6.67,3.33,0]
     * @param inputs The points
     * @returns point
     * @group extract
     * @shortname average point
     * @drawable true
     */
    averagePoint(inputs: Inputs.Point.PointsDto): Inputs.Base.Point3 {
        const xVals = [];
        const yVals = [];
        const zVals = [];
 
        inputs.points.forEach(pt => {
            xVals.push(pt[0]);
            yVals.push(pt[1]);
            zVals.push(pt[2]);
        });
 
        return [
            xVals.reduce((p, c) => p + c, 0) / inputs.points.length,
            yVals.reduce((p, c) => p + c, 0) / inputs.points.length,
            zVals.reduce((p, c) => p + c, 0) / inputs.points.length,
        ];
    }
 
    /**
     * Creates a 3D point from X, Y, Z coordinates.
     * Example: x=10, y=5, z=3 → [10,5,3]
     * @param inputs xyz information
     * @returns point 3d
     * @group create
     * @shortname point xyz
     * @drawable true
     */
    pointXYZ(inputs: Inputs.Point.PointXYZDto): Inputs.Base.Point3 {
        return [inputs.x, inputs.y, inputs.z];
    }
 
    /**
     * Creates a 2D point from X, Y coordinates.
     * Example: x=10, y=5 → [10,5]
     * @param inputs xy information
     * @returns point 3d
     * @group create
     * @shortname point xy
     * @drawable false
     */
    pointXY(inputs: Inputs.Point.PointXYDto): Inputs.Base.Point2 {
        return [inputs.x, inputs.y];
    }
 
    /**
     * Creates logarithmic spiral points using golden angle or custom widening factor.
     * Generates natural spiral patterns common in nature (sunflower, nautilus shell).
     * Example: numberPoints=100, radius=10, phi=1.618 → 100 points forming outward spiral
     * @param inputs Spiral information
     * @returns Specified number of points in the array along the spiral
     * @group create
     * @shortname spiral
     * @drawable true
     */
    spiral(inputs: Inputs.Point.SpiralDto): Inputs.Base.Point3[] {
        const phi = inputs.phi;
        const b = Math.log(phi) / (Math.PI / inputs.widening);
        const spiral = [];
        const step = inputs.radius / inputs.numberPoints;
        for (let i = 0; i < inputs.radius; i += step) {
            const th = Math.log(i / inputs.factor) / b;
            const x = i * Math.cos(th);
            const y = i * Math.sin(th);
            spiral.push([x ? x : 0, y ? y : 0, 0]);
        }
        return spiral;
    }
 
    /**
     * Creates hexagonal grid center points on XY plane (honeycomb pattern).
     * Grid size controlled by number of hexagons, not width/height.
     * Example: radiusHexagon=1, nrHexagonsX=3, nrHexagonsY=3 → 9 hex centers in grid pattern
     * @param inputs Information about hexagon and the grid
     * @returns Points in the array on the grid
     * @group create
     * @shortname hex grid
     * @drawable true
     */
    hexGrid(inputs: Inputs.Point.HexGridCentersDto): Inputs.Base.Point3[] {
        const xLength = Math.sqrt(Math.pow(inputs.radiusHexagon, 2) - Math.pow(inputs.radiusHexagon / 2, 2));
        const points = [];
        for (let ix = 0; ix < inputs.nrHexagonsX; ix++) {
            const coordX = ix * xLength * 2;
            for (let iy = 0; iy < inputs.nrHexagonsY; iy++) {
                const coordY = (inputs.radiusHexagon + inputs.radiusHexagon / 2) * iy;
                const adjustX = coordX + (iy % 2 === 0 ? 0 : xLength);
                points.push([adjustX, coordY, 0]);
            }
        }
 
        if (inputs.orientOnCenter) {
            const compensateX = points[points.length - 1][0] / 2;
            const compensateY = points[points.length - 1][1] / 2;
            points.forEach((p, index) => {
                points[index] = [p[0] - compensateX, p[1] - compensateY, 0];
            });
        }
 
        if (inputs.pointsOnGround) {
            points.forEach((p, index) => {
                points[index] = [p[0], 0, p[1]];
            });
        }
 
        return points;
    }
 
    /**
     * Creates hexagonal grid scaled to fit within specified width/height bounds (auto-calculates hex size).
     * Returns center points and hex vertices. Supports pointy-top or flat-top orientation.
     * Example: width=10, height=10, nrHexagonsInHeight=3 → hex grid filling 10×10 area with 3 rows
     * @param inputs Information about the desired grid dimensions and hexagon counts.
     * @returns An object containing the array of center points and an array of hexagon vertex arrays.
     * @group create
     * @shortname scaled hex grid to fit
     * @drawable false
     */
    hexGridScaledToFit(inputs: Inputs.Point.HexGridScaledToFitDto): Models.Point.HexGridData {
        let width = inputs.width;
        let height = inputs.height;
        let nrHexagonsInHeight = inputs.nrHexagonsInHeight;
        let nrHexagonsInWidth = inputs.nrHexagonsInWidth;
        let extendTop = inputs.extendTop ?? false;
        let extendBottom = inputs.extendBottom ?? false;
        let extendLeft = inputs.extendLeft ?? false;
        let extendRight = inputs.extendRight ?? false;
        const {
 
            flatTop = false,
            centerGrid = false,
            pointsOnGround = false
        } = inputs;
 
        // we flip the width and height if the hexagons are flat-topped and will then rotate resuls afterwards as default
        // computes pointy-top hexagons
        if (flatTop) {
            const oldWidth = width;
            width = inputs.height;
            height = oldWidth;
            const oldNrHexagonsInWidth = nrHexagonsInWidth;
            nrHexagonsInWidth = nrHexagonsInHeight;
            nrHexagonsInHeight = oldNrHexagonsInWidth;
            const extendTopOld = extendTop;
            const extendBottomOld = extendBottom;
            const extendLeftOld = extendLeft;
            const extendRightOld = extendRight;
            extendTop = extendLeftOld;
            extendBottom = extendRightOld;
            extendLeft = extendBottomOld;
            extendRight = extendTopOld;
        }
 
        // --- Input Validation ---
        if (width <= 0 || height <= 0 || nrHexagonsInWidth < 1 || nrHexagonsInHeight < 1) {
            console.warn("Hex grid dimensions and counts must be positive.");
            return { centers: [], hexagons: [], shortestDistEdge: undefined, longestDistEdge: undefined, maxFilletRadius: undefined };
        }
 
        // --- Generate Unscaled Regular Grid Centers (Radius = 1) ---
        // Use the *existing* hexGrid function, ensuring it doesn't center or project yet.
        const BASE_RADIUS = 1.0;
        const unscaledCenters = this.hexGrid({
            radiusHexagon: BASE_RADIUS,
            nrHexagonsX: nrHexagonsInWidth,
            nrHexagonsY: nrHexagonsInHeight,
            orientOnCenter: false, // Important: Do not center here
            pointsOnGround: false  // Keep on XY plane for now
        });
 
        Iif (unscaledCenters.length === 0) {
            return { centers: [], hexagons: [], shortestDistEdge: undefined, longestDistEdge: undefined, maxFilletRadius: undefined }; // Return empty if base grid failed
        }
 
        // --- Generate Unscaled Regular Hexagon Vertices (Radius = 1) ---
        const unscaledHexagons: Inputs.Base.Point3[][] = unscaledCenters.map(center =>
            this.getRegularHexagonVertices(center, BASE_RADIUS)
        );
 
        // --- Determine Dimensions of the Unscaled Grid Bounding Box ---
        let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
        for (const hex of unscaledHexagons) {
            for (const vertex of hex) {
                if (vertex[0] < minX) minX = vertex[0];
                if (vertex[0] > maxX) maxX = vertex[0];
                if (vertex[1] < minY) minY = vertex[1];
                if (vertex[1] > maxY) maxY = vertex[1];
            }
        }
 
        const unscaledWidth = maxX - minX;
        const unscaledHeight = maxY - minY;
 
        // --- Step 4: Calculate Scaling Factors ---
        // Handle potential zero dimensions if only 1 hex (W/H would be based on hex size)
        const scaleX = (unscaledWidth > 1e-9) ? width / unscaledWidth : 1;
        const scaleY = (unscaledHeight > 1e-9) ? height / unscaledHeight : 1;
        // If unscaled W/H is 0 (e.g., 1x1 grid), scale=1 means the final hex will have
        // width/height derived from its regular R=1 shape, not fitting totalW/H.
        // This might need adjustment if a single hex *must* fill the total W/H.
        // For now, assume nrU/nrV > 1 or accept R=1 size for single hex.
 
        // --- Scale Centers and Vertices ---
        // Scale relative to the min corner of the unscaled grid (minX, minY)
        let scaledCenters: Inputs.Base.Point3[] = unscaledCenters.map(p => [
            (p[0] - minX) * scaleX,
            (p[1] - minY) * scaleY,
            0 // Keep Z=0 for now
        ]);
 
        let scaledHexagons: Inputs.Base.Point3[][] = unscaledHexagons.map(hex =>
            hex.map(v => [
                (v[0] - minX) * scaleX,
                (v[1] - minY) * scaleY,
                0 // Keep Z=0 for now
            ])
        );
 
        let shortestDistEdge = Infinity;
        let longestDistEdge = -Infinity;
        let maxFilletRadius = 0;
 
        // --- Calculate Shortes/Longest & Extensions ---
        Eif (scaledHexagons.length !== 0) {
            const firstHex = scaledHexagons[0];
            maxFilletRadius = this.safestPointsMaxFilletHalfLine({
                points: firstHex,
                checkLastWithFirst: true,
                tolerance: 1e-7
            });
            // Calculate the shortest and longest edge distances
            firstHex.forEach((pt, index) => {
                const nextPt = firstHex[(index + 1) % firstHex.length];
                const dist = this.distance({ startPoint: pt, endPoint: nextPt });
                if (dist < shortestDistEdge) {
                    shortestDistEdge = dist;
                }
                if (dist > longestDistEdge) {
                    longestDistEdge = dist;
                }
            });
 
            if (extendTop || extendBottom || extendLeft || extendRight) {
                const pt1Pointy = firstHex[0];
                const pt2Pointy = firstHex[1];
                const cellHeight = pt1Pointy[1] - pt2Pointy[1];
                const cellWidth = pt2Pointy[0] - pt1Pointy[0];
 
                if (extendTop && !extendBottom) {
                    const transform: Inputs.Point.StretchPointsDirFromCenterDto = {
                        center: [0, 0, 0],
                        direction: [0, 1, 0],
                        scale: height / (height - cellHeight),
                    };
                    scaledHexagons = scaledHexagons.map(hex => {
                        transform.points = hex;
                        return this.stretchPointsDirFromCenter(transform);
                    });
                    transform.points = scaledCenters;
                    scaledCenters = this.stretchPointsDirFromCenter(transform);
                }
                if (extendBottom && !extendTop) {
                    const transform: Inputs.Point.StretchPointsDirFromCenterDto = {
                        center: [0, height, 0],
                        direction: [0, -1, 0],
                        scale: height / (height - cellHeight),
                    };
                    scaledHexagons = scaledHexagons.map(hex => {
                        transform.points = hex;
                        return this.stretchPointsDirFromCenter(transform);
                    });
                    transform.points = scaledCenters;
                    scaledCenters = this.stretchPointsDirFromCenter(transform);
                }
                if (extendTop && extendBottom) {
                    const transform: Inputs.Point.StretchPointsDirFromCenterDto = {
                        center: [0, height / 2, 0],
                        direction: [0, 1, 0],
                        scale: height / (height - cellHeight * 2),
                    };
                    scaledHexagons = scaledHexagons.map(hex => {
                        transform.points = hex;
                        return this.stretchPointsDirFromCenter(transform);
                    });
                    transform.points = scaledCenters;
                    scaledCenters = this.stretchPointsDirFromCenter(transform);
                }
                if (extendLeft && !extendRight) {
                    const transform: Inputs.Point.StretchPointsDirFromCenterDto = {
                        center: [width, 0, 0],
                        direction: [1, 0, 0],
                        scale: width / (width - cellWidth),
                    };
                    scaledHexagons = scaledHexagons.map(hex => {
                        transform.points = hex;
                        return this.stretchPointsDirFromCenter(transform);
                    });
                    transform.points = scaledCenters;
                    scaledCenters = this.stretchPointsDirFromCenter(transform);
                }
                if (extendRight && !extendLeft) {
                    const transform: Inputs.Point.StretchPointsDirFromCenterDto = {
                        center: [0, 0, 0],
                        direction: [1, 0, 0],
                        scale: width / (width - cellWidth),
                    };
                    scaledHexagons = scaledHexagons.map(hex => {
                        transform.points = hex;
                        return this.stretchPointsDirFromCenter(transform);
                    });
                    transform.points = scaledCenters;
                    scaledCenters = this.stretchPointsDirFromCenter(transform);
                }
                if (extendLeft && extendRight) {
                    const transform: Inputs.Point.StretchPointsDirFromCenterDto = {
                        center: [width / 2, 0, 0],
                        direction: [1, 0, 0],
                        scale: width / (width - cellWidth * 2),
                    };
                    scaledHexagons = scaledHexagons.map(hex => {
                        transform.points = hex;
                        return this.stretchPointsDirFromCenter(transform);
                    });
                    transform.points = scaledCenters;
                    scaledCenters = this.stretchPointsDirFromCenter(transform);
                }
            }
        }
 
        if (flatTop) {
            // width and height are swapped
            scaledCenters = this.rotatePointsCenterAxis({
                points: scaledCenters,
                center: [width / 2, height / 2, 0],
                axis: [0, 0, 1],
                angle: 90
            });
            scaledHexagons = scaledHexagons.map(hex => {
                return this.rotatePointsCenterAxis({
                    points: hex,
                    center: [width / 2, height / 2, 0],
                    axis: [0, 0, 1],
                    angle: 90
                });
            });
 
            // translate to new center
            const vecTranslation = this.vector.sub({
                first: [height / 2, width / 2, 0],
                second: [width / 2, height / 2, 0]
            }) as Inputs.Base.Vector3;
            scaledCenters = this.translatePoints({
                points: scaledCenters,
                translation: vecTranslation
            });
            scaledHexagons = scaledHexagons.map(hex => {
                return this.translatePoints({
                    points: hex,
                    translation: vecTranslation
                });
            });
        }
 
 
        // --- Apply Optional Centering ---
        // Center the scaled grid (currently starting at [0,0]) around [0,0]
        if (centerGrid) {
            let shiftX = width / 2;
            let shiftY = height / 2;
 
            Iif (flatTop) {
                shiftX = height / 2;
                shiftY = width / 2;
            }
 
            for (let i = 0; i < scaledCenters.length; i++) {
                scaledCenters[i][0] -= shiftX;
                scaledCenters[i][1] -= shiftY;
            }
            for (let i = 0; i < scaledHexagons.length; i++) {
                for (let j = 0; j < scaledHexagons[i].length; j++) {
                    scaledHexagons[i][j][0] -= shiftX;
                    scaledHexagons[i][j][1] -= shiftY;
                }
            }
        }
 
        // --- Apply Optional Ground Projection ---
        if (pointsOnGround) {
            for (let i = 0; i < scaledCenters.length; i++) {
                scaledCenters[i] = [scaledCenters[i][0], 0, scaledCenters[i][1]];
            }
            for (let i = 0; i < scaledHexagons.length; i++) {
                for (let j = 0; j < scaledHexagons[i].length; j++) {
                    scaledHexagons[i][j] = [scaledHexagons[i][j][0], 0, scaledHexagons[i][j][1]];
                }
            }
        }
 
        // We need to adjust orders to be column first and then row first if we choose flat top
        if(flatTop){
            const grouped = this.lists.groupNth<Inputs.Base.Point3[]>({
                list: scaledHexagons.reverse(),
                nrElements: inputs.nrHexagonsInWidth,
                keepRemainder: true,
            });
            const res = this.lists.flipLists({
                list: grouped
            });
            res.forEach(s => s.reverse());
            scaledHexagons = res.flat();
 
            const groupedCenters = this.lists.groupNth<Inputs.Base.Point3>({
                list: scaledCenters.reverse(),
                nrElements: inputs.nrHexagonsInWidth,
                keepRemainder: true,
            });
            const resCenters = this.lists.flipLists({
                list: groupedCenters
            });
            resCenters.forEach(s => s.reverse());
            scaledCenters = resCenters.flat();
        }
 
        // --- Return Result ---
        return {
            centers: scaledCenters,
            hexagons: scaledHexagons,
            shortestDistEdge,
            longestDistEdge,
            maxFilletRadius
        };
    }
 
    /**
     * Calculates the maximum possible fillet radius at a corner formed by two line segments
     * sharing an endpoint (C), such that the fillet arc is tangent to both segments
     * and lies entirely within them.
     * @param inputs three points and the tolerance
     * @returns the maximum fillet radius
     * @group fillet
     * @shortname max fillet radius
     * @drawable false
     */
    maxFilletRadius(
        inputs: Inputs.Point.ThreePointsToleranceDto
    ): number {
        const { start: p1, center: p2, end: c, tolerance = 1e-7 } = inputs;
 
        const v1 = this.vector.sub({ first: p1, second: c }) as Inputs.Base.Vector3;
        const v2 = this.vector.sub({ first: p2, second: c }) as Inputs.Base.Vector3;
 
        const len1 = this.vector.length({ vector: v1 });
        const len2 = this.vector.length({ vector: v2 });
 
        if (len1 < tolerance || len2 < tolerance) {
            return 0;
        }
 
        const normV1 = this.vector.normalized({ vector: v1 });
        const normV2 = this.vector.normalized({ vector: v2 });
        Iif (!normV1 || !normV2) {
            return 0;
        }
 
        // Calculate the cosine of the angle between the vectors
        // Clamp to [-1, 1] to avoid potential domain errors with acos due to floating point inaccuracies
        const cosAlpha = Math.max(-1.0, Math.min(1.0, this.vector.dot({ first: normV1, second: normV2 })));
 
        // Check for collinearity
        // If vectors point in the same direction (angle ~ 0), no fillet
        if (cosAlpha > 1.0 - tolerance) {
            return 0;
        }
        // If vectors point in opposite directions (angle ~ 180 deg), no corner for a fillet
        if (cosAlpha < -1.0 + tolerance) {
            return 0;
        }
 
        // Calculate the angle alpha (0 < alpha < PI)
        const alpha = Math.acos(cosAlpha);
 
        // Calculate tan(alpha / 2)
        // alpha/2 is between 0 and PI/2, so tan is positive and non-zero
        const tanHalfAlpha = Math.tan(alpha / 2.0);
 
        // If tanHalfAlpha is extremely small (alpha near 0, shouldn't happen due to collinearity check), return 0
        Iif (tanHalfAlpha < tolerance) {
            return 0;
        }
 
        // The distance 'd' from corner C to the tangent point must be less than or equal to the segment lengths.
        // d = r / tan(alpha/2) <= min(len1, len2)
        // r <= min(len1, len2) * tan(alpha/2)
        const maxRadius = Math.min(len1, len2) * tanHalfAlpha;
 
        return maxRadius;
    }
 
    /**
     * Calculates the maximum possible fillet radius at a corner C, such that the fillet arc
     * is tangent to both segments (P1-C, P2-C) and the tangent points lie within
     * the first half of each segment (measured from C).
     * @param inputs three points and the tolerance
     * @returns the maximum fillet radius
     * @group fillet
     * @shortname max fillet radius half line
     * @drawable false
     */
    maxFilletRadiusHalfLine(
        inputs: Inputs.Point.ThreePointsToleranceDto
    ): number {
        const { start: p1, center: p2, end: c, tolerance = 1e-7 } = inputs;
 
        const v1 = this.vector.sub({ first: p1, second: c }) as Inputs.Base.Vector3;
        const v2 = this.vector.sub({ first: p2, second: c }) as Inputs.Base.Vector3;
 
        const len1 = this.vector.length({ vector: v1 });
        const len2 = this.vector.length({ vector: v2 });
 
        if (len1 < tolerance || len2 < tolerance) {
            return 0;
        }
 
        const normV1 = this.vector.normalized({ vector: v1 });
        const normV2 = this.vector.normalized({ vector: v2 });
 
        Iif (!normV1 || !normV2) {
            return 0;
        }
 
        const cosAlpha = Math.max(-1.0, Math.min(1.0, this.vector.dot({ first: normV1, second: normV2 })));
 
        if (cosAlpha > 1.0 - tolerance || cosAlpha < -1.0 + tolerance) {
            return 0; // Collinear
        }
 
        const alpha = Math.acos(cosAlpha);
        const tanHalfAlpha = Math.tan(alpha / 2.0);
 
        Iif (tanHalfAlpha < tolerance) {
            return 0;
        }
 
        // The distance 'd' from corner C to the tangent point must be less than or equal
        // to HALF the length of each segment.
        // d = r / tan(alpha/2) <= min(len1 / 2, len2 / 2)
        // r <= min(len1 / 2, len2 / 2) * tan(alpha/2)
        const maxRadius = Math.min(len1 / 2.0, len2 / 2.0) * tanHalfAlpha;
 
        return maxRadius;
    }
 
    /**
     * Calculates the maximum possible fillet radius at each corner of a polyline formed by 
     * formed by a series of points. The fillet radius is calculated for each internal
     * corner and optionally for the closing corners if the polyline is closed.
     * @param inputs Points, checkLastWithFirst flag, and tolerance
     * @returns Array of maximum fillet radii for each corner
     * @group fillet
     * @shortname max fillets half line
     * @drawable false
     */
    maxFilletsHalfLine(
        inputs: Inputs.Point.PointsMaxFilletsHalfLineDto
    ): number[] {
        const { points, checkLastWithFirst = false, tolerance = 1e-7 } = inputs;
        const n = points.length;
        const results: number[] = [];
 
        // Need at least 3 points to form a corner
        if (n < 3) {
            return results;
        }
 
        // 1. Calculate fillets for internal corners (P[1] to P[n-2])
        for (let i = 1; i < n - 1; i++) {
            const p_prev = points[i - 1];
            const p_corner = points[i];
            const p_next = points[i + 1];
 
            // Map geometric points to the DTO structure used by calculateMaxFilletRadiusHalfLine
            // DTO: { start: P_prev, center: P_next, end: P_corner, tolerance }
            const cornerInput: Inputs.Point.ThreePointsToleranceDto = {
                start: p_prev,
                center: p_next,
                end: p_corner,
                tolerance: tolerance
            };
            results.push(this.maxFilletRadiusHalfLine(cornerInput));
        }
 
        // 2. Calculate fillets for closing corners if it's a closed polyline
        if (checkLastWithFirst && n >= 3) {
            // Corner at P[0] (formed by P[n-1]-P[0] and P[1]-P[0])
            const p_prev_start = points[n - 1]; // Previous point is the last point
            const p_corner_start = points[0];
            const p_next_start = points[1];
            const startCornerInput: Inputs.Point.ThreePointsToleranceDto = {
                start: p_prev_start,
                center: p_next_start,
                end: p_corner_start,
                tolerance: tolerance
            };
            results.push(this.maxFilletRadiusHalfLine(startCornerInput));
 
            // Corner at P[n-1] (formed by P[n-2]-P[n-1] and P[0]-P[n-1])
            const p_prev_end = points[n - 2];
            const p_corner_end = points[n - 1];
            const p_next_end = points[0];     // Next point wraps around to the first point
            const endCornerInput: Inputs.Point.ThreePointsToleranceDto = {
                start: p_prev_end,
                center: p_next_end,
                end: p_corner_end,
                tolerance: tolerance
            };
            results.push(this.maxFilletRadiusHalfLine(endCornerInput));
        }
 
        return results;
    }
 
    /**
     * Calculates the single safest maximum fillet radius that can be applied
     * uniformly to all corners of collection of points, 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 points, whether it's closed, and an optional tolerance.
     * @returns The smallest value from the results of pointsMaxFilletsHalfLine.
     *          Returns 0 if the polyline has fewer than 3 points or if any
     *          calculated maximum radius is 0.
     * @group fillet
     * @shortname safest fillet radii points
     * @drawable false
     */
    safestPointsMaxFilletHalfLine(
        inputs: Inputs.Point.PointsMaxFilletsHalfLineDto
    ): 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);
    }
 
    /**
     * Removes consecutive duplicate points from array within tolerance.
     * Example: [[0,0,0], [0,0,0], [1,0,0], [1,0,0], [2,0,0]] → [[0,0,0], [1,0,0], [2,0,0]]
     * @param inputs points, tolerance and check first and last
     * @returns Points in the array without consecutive duplicates
     * @group clean
     * @shortname remove duplicates
     * @drawable true
     */
    removeConsecutiveDuplicates(inputs: Inputs.Point.RemoveConsecutiveDuplicatesDto): Inputs.Base.Point3[] {
        return this.geometryHelper.removeConsecutivePointDuplicates(inputs.points, inputs.checkFirstAndLast, inputs.tolerance);
    }
 
    /**
     * Calculates normal vector from three points using cross product (perpendicular to plane).
     * Example: p1=[0,0,0], p2=[1,0,0], p3=[0,1,0] → [0,0,1] (pointing up from XY plane)
     * @param inputs Three points and the reverse normal flag
     * @returns Normal vector
     * @group create
     * @shortname normal from 3 points
     * @drawable true
     */
    normalFromThreePoints(inputs: Inputs.Point.ThreePointsNormalDto): Inputs.Base.Vector3 {
        const p1 = inputs.point1;
        const p2 = inputs.point2;
        const p3 = inputs.point3;
 
        if (!p1 || !p2 || !p3 || p1.length !== 3 || p2.length !== 3 || p3.length !== 3) {
            throw new Error("All points must be arrays of 3 numbers [x, y, z]");
        }
 
        // Calculate vector A = p2 - p1
        const ax = p2[0] - p1[0];
        const ay = p2[1] - p1[1];
        const az = p2[2] - p1[2];
 
        // Calculate vector B = p3 - p1
        const bx = p3[0] - p1[0];
        const by = p3[1] - p1[1];
        const bz = p3[2] - p1[2];
 
        // Calculate the cross product N = A x B
        let nx = (ay * bz) - (az * by);
        let ny = (az * bx) - (ax * bz);
        let nz = (ax * by) - (ay * bx);
 
        // Check for collinear points (resulting in a zero vector)
        // A zero vector indicates the points don't form a unique plane.
        // You might want to handle this case depending on your application.
        if (nx === 0 && ny === 0 && nz === 0) {
            console.warn("Points are collinear or coincident; cannot calculate a unique normal.");
            return undefined; // Or return [0, 0, 0] if that's acceptable
        }
 
        if (inputs.reverseNormal) {
            nx = -nx;
            ny = -ny;
            nz = -nz;
        }
 
        return this.vector.normalized({ vector: [nx, ny, nz] }) as Inputs.Base.Vector3;
    }
 
    private closestPointFromPointData(inputs: Inputs.Point.ClosestPointFromPointsDto): {
        index: number, point: Inputs.Base.Point3, distance: number
    } {
        let distance = Number.MAX_SAFE_INTEGER;
        let closestPointIndex: number;
        let point: Inputs.Base.Point3;
        for (let i = 0; i < inputs.points.length; i++) {
            const pt = inputs.points[i];
            const currentDist = this.distance({ startPoint: inputs.point, endPoint: pt });
            if (currentDist < distance) {
                distance = currentDist;
                closestPointIndex = i;
                point = pt as Inputs.Base.Point3;
            }
        }
        return { index: closestPointIndex + 1, distance, point };
    }
 
    /**
     * Checks if two points are approximately equal within tolerance (distance-based comparison).
     * Example: point1=[1.0000001, 2.0, 3.0], point2=[1.0, 2.0, 3.0], tolerance=1e-6 → true
     * @param inputs Two points and the tolerance
     * @returns true if the points are almost equal
     * @group measure
     * @shortname two points almost equal
     * @drawable false
     */
    twoPointsAlmostEqual(inputs: Inputs.Point.TwoPointsToleranceDto): boolean {
        const p1 = inputs.point1;
        const p2 = inputs.point2;
        const dist = this.distance({ startPoint: p1, endPoint: p2 });
        return dist < inputs.tolerance;
    }
 
    /**
     * Sorts points lexicographically (by X, then Y, then Z coordinates).
     * Example: [[5,0,0], [1,0,0], [3,0,0]] → [[1,0,0], [3,0,0], [5,0,0]]
     * @param inputs points
     * @returns sorted points
     * @group sort
     * @shortname sort points
     * @drawable true
     */
    sortPoints(inputs: Inputs.Point.PointsDto): Inputs.Base.Point3[] {
        return [...inputs.points].sort((a, b) => {
            if (a[0] !== b[0]) return a[0] - b[0];
            if (a[1] !== b[1]) return a[1] - b[1];
            return a[2] - b[2];
        });
    }
 
    /**
     * Calculates the 6 vertices of a regular flat-top hexagon.
     * @param center The center point [x, y, z].
     * @param radius The radius (distance from center to vertex).
     * @returns An array of 6 Point3 vertices in counter-clockwise order.
     */
    private getRegularHexagonVertices(center: Inputs.Base.Point3, radius: number): Inputs.Base.Point3[] {
        const vertices: Inputs.Base.Point3[] = [];
        const cx = center[0];
        const cy = center[1];
        const cz = center[2];
 
        const angleStep = Math.PI / 3;
 
        for (let i = 0; i < 6; i++) {
            const angle = angleStep * i;
            vertices.push([
                cx + radius * Math.sin(angle),
                cy + radius * Math.cos(angle),
                cz // Maintain original Z
            ]);
        }
        return vertices;
    }
}