Further math refactor and simplifications

This commit is contained in:
Mark Tolmacs 2024-09-23 17:13:40 +02:00
parent 41885b4bb3
commit 0e2f8c958e
No known key found for this signature in database
18 changed files with 262 additions and 175 deletions

View file

@ -6,6 +6,8 @@ import type {
Degrees,
Vector,
ViewportPoint,
GenericPoint,
Extent,
} from "./types";
import { PRECISION } from "./utils";
import { vectorFromPoint, vectorScale } from "./vector";
@ -259,3 +261,73 @@ export const isPointWithinBounds = <
q[1] >= Math.min(p[1], r[1])
);
};
/**
* The extent (width and height) of a set of points.
*
* @param points The points to calculate the extent for
* @returns
*/
export const pointExtent = (points: readonly GenericPoint[]): Extent => {
const xs = points.map((point) => point[0]);
const ys = points.map((point) => point[1]);
return {
width: Math.max(...xs) - Math.min(...xs),
height: Math.max(...ys) - Math.min(...ys),
} as Extent;
};
/**
* Rescale the set of points from the top leftmost point as origin
*
* @param dimension 0 for rescaling only x, 1 for y
* @param newSize The target size
* @param points The points to restcale
* @param normalize Whether to normalize the result
*/
// TODO: Center should be parametric and should use pointScaleFromOrigin()
export const pointRescaleFromTopLeft = <Point extends GenericPoint>(
dimension: 0 | 1,
newSize: number,
points: readonly Point[],
normalize: boolean,
): Point[] => {
const coordinates = points.map((point) => point[dimension]);
const maxCoordinate = Math.max(...coordinates);
const minCoordinate = Math.min(...coordinates);
const size = maxCoordinate - minCoordinate;
const scale = size === 0 ? 1 : newSize / size;
let nextMinCoordinate = Infinity;
const scaledPoints = points.map((point): Point => {
const newCoordinate = point[dimension] * scale;
const newPoint = [...point];
newPoint[dimension] = newCoordinate;
if (newCoordinate < nextMinCoordinate) {
nextMinCoordinate = newCoordinate;
}
return newPoint as Point;
});
if (!normalize) {
return scaledPoints;
}
if (scaledPoints.length === 2) {
// we don't translate two-point lines
return scaledPoints;
}
const translation = minCoordinate - nextMinCoordinate;
const nextPoints = scaledPoints.map((scaledPoint) =>
pointFromPair<Point>(
scaledPoint.map((value, currentDimension) => {
return currentDimension === dimension ? value + translation : value;
}) as [number, number],
),
);
return nextPoints;
};