# @rickosborne/planar

A small collection of 2D Cartesian and graphics related data structures and algorithms.
Built on [@rickosborne/typical](https://www.npmjs.com/package/@rickosborne/typical) for types, [@rickosborne/guard](https://www.npmjs.com/package/@rickosborne/guard) for guards, and [@rickosborne/foundation](https://www.npmjs.com/package/@rickosborne/foundation) for basic data structures and algorithms.
## Usage

Install via your favorite package manager.

Each package supports CommonJS `require`, ESM `import`, and TypeScript usage.

You also have a choice: barrel imports or direct imports.

Barrel imports mean you're going to require/import everything from the same package-level namespace:

```typescript
// CommonJS
const { isPlainObject, isListOf } = require("@rickosborne/guard");
// ESM / TypeScript
import { isPlainObject, isListOf } from "@rickosborne/guard";
```

Implications:

- Nice and simple.
- Your build system needs to do tree-shaking well ... or you'll end up adding the entire package even if you only import two functions.

The other option is to use direct imports:

```typescript
// CommonJS
const { isPlainObject } = require("@rickosborne/guard/is-object");
const { isListOf } = require("@rickosborne/guard/is-list-of");
// ESM / TypeScript
import { isPlainObject } from "@rickosborne/guard/is-object.js";
import { isListOf } from "@rickosborne/guard/is-list-of.js";
```

Implications:

- You (probably) don't have to worry about tree-shaking as your build (likely) ends up with only the functions you need.

If you're using a modern build system, there aren't any strong reasons to prefer one way over the other.
It's really just down to your personal preference.

### A quick note about file extensions

Do you need to use file extensions?
And if so, which extensions?

Honestly ... this is a dumpster fire question.
It really comes down to your own setup and configuration.

Within each package itself:

- The CommonJS files all have `.cjs` extensions.
- The ESM files all have `.mjs` extensions.
- Node subpath exports have been set up to send `.js` imports to the `.cjs` (via `require`) or `.mjs` (via `import`) files, depending on your setup.

So, in theory, the only extension which _won't_ work would be `.ts` because the source isn't included.

If you run into a problem with a particular configuration, file a GitHub issue with:

- Your `tsconfig.json`'s `module`, `moduleResolution`, and `target` settings.
- Your `package.json`'s `type` and `imports` settings.
- An example of another package which imports correctly for you.

## License

This package is licensed as [CC-BY-NC-SA-4.0] unless otherwise noted.
That is, Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International.

[CC-BY-NC-SA-4.0]: https://creativecommons.org/licenses/by-nc-sa/4.0/


***

## API

### Enums

#### Orientation

<a id="api-orientation"></a>

```typescript
 enum Orientation 
```

Measure of the turn of an angle, based on the order of the three points which define it.


### Functions

#### angle

<a id="api-angle"></a>

```typescript
angle: (area: number, orientation: Orientation, rad: number) => Angle
```

#### angleMeasures

<a id="api-anglemeasures"></a>

```typescript
angleMeasures: (a: Point, b: Point, c: Point) => AngleMeasures
```

Calculate the intermediary values used in measuring an angle defined by the intersection of two line segments along three points: A, B, and C.


#### boundingBoxOf

<a id="api-boundingboxof"></a>

```typescript
boundingBoxOf: (shape: Shape | LineSegment) => Rect
```

Calculate the bounding box of the given shape, meaning a minimum point plus a width and height. Note that the <kbd>x</kbd> and <kbd>y</kbd> values will be the numeric minimums, which will be bottom-left in Cartesian space and top-left in pixel space.


#### boundingBoxOfCircle

<a id="api-boundingboxofcircle"></a>

```typescript
boundingBoxOfCircle: (circle: Circle) => Rect
```

Calculate the bounding box of the given circle, meaning a minimum point plus a width and height. Note that the <kbd>x</kbd> and <kbd>y</kbd> values will be the numeric minimums, which will be bottom-left in Cartesian space and top-left in pixel space.


#### boundingBoxOfLineSegment

<a id="api-boundingboxoflinesegment"></a>

```typescript
boundingBoxOfLineSegment: (segment: LineSegment) => Rect
```

Calculate the bounding box which would contain the given line segment.


#### boundingBoxOfPath

<a id="api-boundingboxofpath"></a>

```typescript
boundingBoxOfPath: (path: Path) => Rect
```

Calculate the bounding box which would contain the points in the given path.


#### cartesianOrientationOfPolygon

<a id="api-cartesianorientationofpolygon"></a>

```typescript
cartesianOrientationOfPolygon: (poly: Polygon) => Orientation
```

Calculate the orientation of a polygon as defined by the order of its points and its signed area. This does not necessarily imply the polygon is convex. This version uses Cartesian coordinates, where the origin is in the bottom left. See also [gfxOrientationOfPolygon](#api-gfxorientationofpolygon).


#### centroidOfPolygon

<a id="api-centroidofpolygon"></a>

```typescript
centroidOfPolygon: (poly: Polygon) => Point
```

Calculate the centroid of a polygon, which is the weighted mean of its points. If the polygon has zero signed area, the centroid of the polygon's bounding box will be returned. The centroid is not guaranteed to be within the polygon if it is not convex.


#### detailedIsConvex

<a id="api-detailedisconvex"></a>

```typescript
detailedIsConvex: (poly: Polygon) => IsConvex
```

More detailed check to see if a polygon is convex. Tracks "bad" points and returns them if found. Slower than [fastIsConvex](#api-fastisconvex), and doesn't necessarily return a better result, though it may give more information in scenarios where you want to try to split the polygon into smaller convex polygons.


#### fastIsConvex

<a id="api-fastisconvex"></a>

```typescript
fastIsConvex: (poly: Polygon) => boolean
```

Performs a rudimentary check of a polygon, calculating angles at each vertex and checking for sign flips in the line segment cross products. The result may not be reliable for symmetric shapes where the signed areas cancel out. This version also does not track "bad" points.


#### gfxOrientationOfPolygon

<a id="api-gfxorientationofpolygon"></a>

```typescript
gfxOrientationOfPolygon: (poly: Polygon) => Orientation
```

Calculate the orientation of a polygon as defined by the order of its points and its signed area. This does not necessarily imply the polygon is convex. This version uses graphics coordinates, where the origin is in the top left. See also [cartesianOrientationOfPolygon](#api-cartesianorientationofpolygon).


#### isCircle

<a id="api-iscircle"></a>

```typescript
isCircle: (obj: unknown) => obj is Circle
```

Guard for whether the given value has <kbd>x</kbd> and <kbd>y</kbd> coordinates plus a radius <kbd>r</kbd> measure. May have more!


#### isDirectedSegment

<a id="api-isdirectedsegment"></a>

```typescript
isDirectedSegment: (obj: unknown) => obj is DirectedSegment
```

Guard for whether the given value has <kbd>a</kbd> and <kbd>b</kbd> [Point](#api-point) properties. May have more!


#### isLineSegment

<a id="api-islinesegment"></a>

```typescript
isLineSegment: (obj: unknown) => obj is LineSegment
```

Guard for whether the given value has <kbd>blue</kbd> and <kbd>gold</kbd> [Point](#api-point) properties. May have more!


#### isPath

<a id="api-ispath"></a>

```typescript
isPath: (obj: unknown, deep?: boolean) => obj is Path
```

Guard for whether the given value has a list of points. It will not exhaustively check the points for validity unless <kbd>deep</kbd> is true.


#### isPoint

<a id="api-ispoint"></a>

```typescript
isPoint: (obj: unknown) => obj is Point
```

Guard for whether the given value has <kbd>x</kbd> and <kbd>y</kbd> coordinates. May have more!


#### isRect

<a id="api-isrect"></a>

```typescript
isRect: (obj: unknown) => obj is Rect
```

Guard for whether the given value has <kbd>x</kbd> and <kbd>y</kbd> coordinates plus <kbd>w</kbd> and <kbd>h</kbd> measures. May have more!


#### measureAngle

<a id="api-measureangle"></a>

```typescript
measureAngle: (a: Point, b: Point, c: Point) => Angle
```

Given three points which define the ordered intersection of two line segments, calculate the angle between them.


#### measureAngles

<a id="api-measureangles"></a>

```typescript
measureAngles: (poly: Polygon) => PolygonWithRadians
```

Upgrade a polygon to include angle measurements for its vertices.


#### perimeterOfPolygon

<a id="api-perimeterofpolygon"></a>

```typescript
perimeterOfPolygon: (poly: Polygon) => number
```

#### point

<a id="api-point"></a>

```typescript
point: (x: number, y: number) => Point
```

#### pointAdd

<a id="api-pointadd"></a>

```typescript
pointAdd: (a: Point, b: Point) => Point
```

#### pointEq

<a id="api-pointeq"></a>

```typescript
pointEq: (a: Point, b: Point) => boolean
```

#### polygonFromLineSegment

<a id="api-polygonfromlinesegment"></a>

```typescript
polygonFromLineSegment: (segment: LineSegment) => Polygon
```

Convert the given [LineSegment](#api-linesegment) to [Polygon](#api-polygon) format. Arbitrarily places the left/bottom point first and right/top point second.


#### polygonFromRect

<a id="api-polygonfromrect"></a>

```typescript
polygonFromRect: (rect: Rect) => Polygon
```

Convert the given [Rect](#api-rect) to [Polygon](#api-polygon) format.


#### prettyRad

<a id="api-prettyrad"></a>

```typescript
prettyRad: (rad: number, epsilon?: number) => string
```

Try to figure out a reasonably human-readable fraction for the given angle in radians.


#### reversePolygon

<a id="api-reversepolygon"></a>

```typescript
reversePolygon: <P extends Polygon>(poly: P) => P
```

Reverse the point order of a polygon, while keeping the starting point the same.


#### signedAreaOfPolygon

<a id="api-signedareaofpolygon"></a>

```typescript
signedAreaOfPolygon: (poly: Polygon) => number
```

Calculate the [signed area](https://en.wikipedia.org/wiki/Signed_area) of a polygon.


#### signOf

<a id="api-signof"></a>

```typescript
signOf: (n: number) => Sign
```

Reduce a number to a unit (1) with a sign.


### TypeAliases

#### Angle

<a id="api-angle"></a>

```typescript
type Angle = {
    area: number;
    orientation: Orientation;
    rad: number;
};
```

An angle between two line segments, often as an interior angle for a polygon.


#### AngleMeasures

<a id="api-anglemeasures"></a>

```typescript
type AngleMeasures = {
    abx: number;
    aby: number;
    bcx: number;
    bcy: number;
    area: number;
    orientation: Orientation;
};
```

Mixin for the intermediary values used for calculating angles defined by the intersection of two line segments across three points: A, B, and C.


#### Circle

<a id="api-circle"></a>

```typescript
type Circle = Point & {
    r: number;
};
```

An equal radius out from a center point.


#### ConvexWithOrientation

<a id="api-convexwithorientation"></a>

```typescript
type ConvexWithOrientation = {
    convex: true;
    orientation: Orientation.Counter | Orientation.Clockwise;
};
```

Result of a calculation of whether a polygon is convex indicating the polygon is complex.


#### DirectedSegment

<a id="api-directedsegment"></a>

```typescript
type DirectedSegment = {
    a: Point;
    b: Point;
};
```

A directed line segment joining two points in a specific order.


#### IsConvex

<a id="api-isconvex"></a>

```typescript
type IsConvex = Either<ConvexWithOrientation, NotConvex>;
```

Result of a calculation of whether a polygon is convex.


#### LineSegment

<a id="api-linesegment"></a>

```typescript
type LineSegment = {
    blue: Point;
    gold: Point;
};
```

An undirected line segment joining two points.


#### NotConvex

<a id="api-notconvex"></a>

```typescript
type NotConvex = {
    badPoints?: number[];
    convex: false;
    firstOrientation?: Orientation | undefined;
    overallOrientation?: Orientation | undefined;
};
```

Result of a calculation of whether a polygon is convex, indicating that it does not seem to be, or is still unknown.


#### Path

<a id="api-path"></a>

```typescript
type Path = {
    points: Point[];
};
```

An ordered sequence of points.


#### Point

<a id="api-point"></a>

```typescript
type Point = {
    x: number;
    y: number;
};
```

Coordinates in 2D space.


#### Polygon

<a id="api-polygon"></a>

```typescript
type Polygon = Path;
```

An ordered sequence of points, generally assuming the last point connects back around to the first.


#### PolygonWithRadians

<a id="api-polygonwithradians"></a>

```typescript
type PolygonWithRadians = {
    points: WithAngles<Point>[];
};
```

A sequence of points where the interior angle at each has been measured.


#### Rect

<a id="api-rect"></a>

```typescript
type Rect = Point & {
    h: number;
    w: number;
};
```

A rectangle with no rotation. Note that this structure does not encode whether the origin point is in the bottom left (Cartesian) or top left (graphics).


#### Shape

<a id="api-shape"></a>

```typescript
type Shape = Polygon | Rect | Circle;
```

For algorithms which work on basic shapes.


#### Sign

<a id="api-sign"></a>

```typescript
type Sign = -1 | 0 | 1;
```

Could be an [Orientation](#api-orientation), or just a simple indication of the sign of a number.


#### WithAngles

<a id="api-withangles"></a>

```typescript
type WithAngles<T extends object> = T & Angle;
```

Mixin which adds angle information to some other type.


### Variables

#### CCW

<a id="api-ccw"></a>

```typescript
CCW = Orientation.Counter
```

Shorter version of [Orientation.Counter](#api-orientation-counter).


#### CONVEX_TRUE_CCW

<a id="api-convex-true-ccw"></a>

```typescript
CONVEX_TRUE_CCW: IsConvex
```

Basic shared value for a true [IsConvex](#api-isconvex) result with a counterclockwise orientation.


#### CONVEX_TRUE_CW

<a id="api-convex-true-cw"></a>

```typescript
CONVEX_TRUE_CW: IsConvex
```

Basic shared value for a true [IsConvex](#api-isconvex) result with a clockwise orientation.


#### CW

<a id="api-cw"></a>

```typescript
CW = Orientation.Clockwise
```

Shorter version of [Orientation.Clockwise](#api-orientation-clockwise).


#### EPSILON

<a id="api-epsilon"></a>

```typescript
EPSILON = 0.00001
```

#### ORIGIN

<a id="api-origin"></a>

```typescript
ORIGIN: Readonly<{
    x: 0;
    y: 0;
}>
```

#### PI

<a id="api-pi"></a>

```typescript
PI: number
```

#### PI_2

<a id="api-pi-2"></a>

```typescript
PI_2: number
```

#### PI_2_3

<a id="api-pi-2-3"></a>

```typescript
PI_2_3: number
```

#### PI_3

<a id="api-pi-3"></a>

```typescript
PI_3: number
```

#### PI_3_4

<a id="api-pi-3-4"></a>

```typescript
PI_3_4: number
```

#### PI_4

<a id="api-pi-4"></a>

```typescript
PI_4: number
```

#### PI_5

<a id="api-pi-5"></a>

```typescript
PI_5: number
```

#### PI_6

<a id="api-pi-6"></a>

```typescript
PI_6: number
```

#### PI_7

<a id="api-pi-7"></a>

```typescript
PI_7: number
```

#### PI_8

<a id="api-pi-8"></a>

```typescript
PI_8: number
```

#### PI_9

<a id="api-pi-9"></a>

```typescript
PI_9: number
```

#### SQRT_2

<a id="api-sqrt-2"></a>

```typescript
SQRT_2: number
```

#### SQRT_3

<a id="api-sqrt-3"></a>

```typescript
SQRT_3: number
```

#### SQRT_5

<a id="api-sqrt-5"></a>

```typescript
SQRT_5: number
```

#### STRAIGHT

<a id="api-straight"></a>

```typescript
STRAIGHT = Orientation.Straight
```

Shorter version of [Orientation.Straight](#api-orientation-straight).


#### TWO_PI

<a id="api-two-pi"></a>

```typescript
TWO_PI: number
```

