
Euclid
A comprehensive library for primitive 2D and 3D geometry in and for F#, without dependencies, designed for precision engineering and computational design.
It runs on JavaScript too.
Is this vibe coded ?
No, from 2019 till 2025 it was crafted by hand with careful attention to performance and correctness.
But of course, the powerful LLMs from 2026 caught a few real bugs, added some functionality,
wrote a lot of tests and helped unify and standardize the public API surface for release 1.0
What is new in Euclid 1.0 ?
The API has been expanded and redesigned, improving naming consistency. Many functions have modified names. For every instance member, there is a corresponding static member with a consistent naming pattern. The code itself is mostly the same.
Features
While most 3D geometry libraries just use a generic type ( often called Vec3 or similar) containing three floats for both points and vectors,
Euclid makes a distinction to preserve semantic meaning and avoid accidental misuse.
A point represents a position in space, while a vector represents a direction and magnitude.
Even unitized vectors are a separate type. They are guaranteed to have a length of 1.0.
This also helps to skip checks for zero length vectors in many operations.
🎯 Core Geometry Types
- Points (Pt, Pnt), Vectors (Vc, Vec), Unit Vectors (UnitVc, UnitVec)
- Lines, Planes, Rectangles, Boxes, Bounding Boxes, Polylines
- Rotations, Quaternions, 4x4 and rigid orthonormal 4x3 matrices
✨ Key Characteristics
- Zero dependencies: lightweight and self-contained
- Double precision: designed for CAD/manufacturing accuracy
- Immutable types: geometry types are immutable for safety and ease of reasoning, except Polyline2D, Polyline3D and FreeBox
- Cross-platform: compiles to .NET, JavaScript, TypeScript and more via Fable
- Performance Focus: All small types are structs, functions are often inline and try to minimize allocations.
Extensions
- use Euclid.Rhino for Rhino3D integration.
- use Euclid.BVH for efficient spatial indexing and collision detection via a bounding-volume-hierarchy tree.
- use Euclid.Kontur for efficient boolean operations on 2d polylines.
Installation
Add Euclid to your F# project via NuGet:
|
Or in F# scripting:
#r "nuget: Euclid"
Quick Start
open Euclid
// Create 3D points and vectors
let point1 = Pnt(1.0, 2.0, 3.0)
let point2 = Pnt(4.0, 5.0, 6.0)
let vector = Vec(1.0, 1.0, 0.0)
// Calculate distance
let distance = point1.DistanceTo point2
// Create and use unit vectors
let unitVec = vector.Unitized // returns a UnitVec
// Transform with 4x4 matrix
let matrix =
Matrix.createShear(3.0, 0, 0, 0, 0, 0)
*** // Combine transformations
Matrix.createRotationZDegrees 45
point1
|> Pnt.move vector
|> Pnt.scale 3.0
|> Pnt.transform matrix
Coordinate System
This library uses a right-handed coordinate system with the Z-axis pointing up.
✅ Same as in: Rhino3D, Blender, SketchUp, Revit, AutoCAD
❌ Different from: Unity, Unreal Engine, Maya
This choice aligns with industry-standard CAD and architectural software.
Design Philosophy
Points vs Vectors
- Points (
Pt,Pnt): Positions in space - Vectors (
Vc,Vec): Directions and displacements
When a 4x4 transformation matrix is applied: - Points: Undergo full transformation (rotation, scaling, translation) - Vectors: Only rotate and scale (no translation)
This follows homogeneous coordinate conventions where vectors have w=0.
A vector in Euclid is just a direction with a magnitude. It has no location in space.
Therefore transformations that depend on a location never apply to vectors:
- A vector cannot be moved. Moving a direction is meaningless; it stays the same vector.
- A vector cannot be rotated around a center point. Only location-bearing types
(points, lines, planes, rectangles, boxes, polylines) can rotate around a center.
Vectors only rotate around the origin (a pure rotation, e.g. Vec.rotate, Vec.rotateOnZ).
The API enforces this: vector types (Vc, Vec, UnitVc, UnitVec) deliberately offer no
move, rotateAround or scaleOn members.
Mutability
All types are immutable, except Polyline2D, Polyline3D and FreeBox.
These three are classes that wrap a flat Resizable array of float coordinates.
Their instance members, such as Move, Rotate, Transform, Reverse or SetPoint, change the instance in place and return unit.
Their static functions, such as Polyline2D.move or Polyline2D.reverse, return a new instance and leave the input unchanged.
Only the indexed point setters and movers, like setPoint and movePoint, and the append functions, like addPoint, mutate as static functions too.
XYs and XYZs give access to the live coordinate buffer.
Call Duplicate() to get an independent copy before you change a shared instance.
Rays
A ray in Euclid is a line extended infinitely in both directions.
Functions with Ray in their name, such as XLine2D.classifyRayIntersection, Line3D.RayClosestParameters
or BBox.IntersectRay, take a finite Line2D or Line3D and treat it as infinite.
Their parameters are measured along that line: 0.0 is at its From point and 1.0 at its To point.
Values below 0.0 or above 1.0 are valid results.
Functions that intersect two rays say Rays, like Line2D.intersectRays and XLine3D.tryIntersectRays.
Naming Conventions
Core Types (2D and 3D):
Type |
2D |
3D |
|---|---|---|
Point |
|
|
Vector |
|
|
Unit Vector |
|
|
Line |
|
|
Polyline |
|
|
Rectangle |
|
|
Bounding Rectangle/Box |
|
|
Member names follow the same split:
2D members that take or return points or vectors usually say Pt or Vc in their name,
and their 3D counterparts say Pnt or Vec.
For example BRect.MinPt and BBox.MinPnt, Tria2D.offsetPt and Tria3D.offsetPnt,
or Line2D.isParallelToVc and Line3D.isParallelToVec.
3D-only Types:
Type |
Description |
|---|---|
|
Parametrized plane (origin + X/Y/Z axes) |
|
Normal plane (origin + normal vector) |
|
Oriented 3D box (origin + 3 axis vectors) |
|
Mutable box-like topology with 8 freely placed corner points |
|
4x4 transformation matrix |
|
4x3 rigid transformation (rotation + translation only) |
|
Unitized quaternion for 3D rotations |
|
2D rotation stored as sine/cosine pair |
Function Patterns
Functions are available in multiple forms:
// Static module function (lowercase, pipeable)
let normalized = Vec.unitize myVector
let moved = Pnt.move myVec myPoint
// Instance method/property (uppercase)
let normalized = myVector.Unitized
let moved = myPoint.Transform myMatrix
// Pipeline style
myPoint
|> Pnt.move (Vec(1, 0, 0))
|> Pnt.rotateOnZDegrees 45.0
|> Pnt.transform myMatrix
Static functions with several arguments are curried, so they work with |> and partial application.
Configuration comes first and the geometry last: Rect3D.createFromPlane sizeX sizeY plane, Points3D.closestPoint pt points.
Natural orders stay: Vec.create x y z, Pnt.lerp start finish factor.
These stay tupled because their argument order is easy to mix up:
functions with more than three arguments of the same type (like Quaternion.create or FreeBox.createFrom4Pts),
create...Unchecked factories, cross and the matrix and quaternion multiply.
If the last argument, the geometry, has another type, the function may still be curried, like Box.offset distBottom distFront distRight distBack distLeft distTop box.
Static constant values are PascalCase, unlike static functions: Vec.XAxis, UnitVec.ZAxis, Pnt.Origin, PPlane.WorldXY, NPlane.WorldXY, Quaternion.Identity.
A function with optional settings comes in two forms. The plain name is curried and uses the defaults.
The name ending in Custom is tupled and takes the settings as optional named arguments:
let p = XLine2D.classifyIntersection lineA lineB
let q = XLine2D.classifyIntersectionCustom(lineA, lineB, tangent = Tangent.``1.0``)
let pl = Polyline2D.offsetCustom(myPolyline, 2.0, loop = true)
A function with only one setting, a tolerance, has no Custom form.
Its name ending in Within is curried and takes the tolerance first, like equalsWithin:
let r = XLine2D.tryIntersectRays lineA lineB
let s = XLine2D.tryIntersectRaysWithin Tangent.``1.0`` lineA lineB
Rotating and Scaling
Rotations and scaling share one curried naming grammar, with the geometry as the last argument:
Function |
Meaning |
|---|---|
|
Rotate around the origin by a |
|
Rotate around the origin by an angle in degrees (2D) |
|
Rotate around the origin by an angle in radians (2D) |
|
Rotate around a center point |
|
Rotate around a center point by an angle in degrees (2D) |
|
Rotate around a center point by an angle in radians (2D) |
|
Scale from the origin |
|
Scale from a center point |
A raw angle argument always names its unit. The name parts of the arguments come in reverse argument order, so the last argument is named first,
as in rotateDegreesAround center degrees geometry and Matrix.createRotationFromDegreesVecAround center axis degrees. The instance members use the same names in PascalCase, e.g. ln.RotateAround cen r.
For repeated rotations, precompute the Rotation2D once and use rotate or rotateAround.
Failure and Tolerance Contracts
The name of a function tells what it does when there is no result or when its input is degenerate:
Form |
Contract |
Example |
|---|---|---|
|
Returns the result. Raises an |
|
|
Returns a |
|
|
Returns a discriminated union that describes the relationship |
|
|
Returns the given fallback instead of failing |
|
|
Skips the documented checks |
|
Intersections of two rays come in both forms, intersectRays and tryIntersectRays.
Intersections of two finite lines only have the try and classify forms, like Line2D.tryIntersect and XLine2D.classifyIntersection,
because two segments that do not reach each other are an ordinary result.
Equality follows the same idea: equalsExact a b compares each coordinate with =,
and equalsWithin tol a b allows each coordinate to differ by up to tol.
The tolerance applies to each coordinate separately, not to the Euclidean distance.
So two 3D points that differ by tol in X, Y and Z are equal, although they are sqrt 3.0 * tol apart.
To compare by distance, use Pnt.distance a b <= tol or Pnt.distanceSq a b <= tol * tol.
Custom Operators
a + b // Point + Vector = Point, Vector + Vector = Vector
a - b // Point - Point = Vector, Point - Vector = Point
a * 2.0 // Scale vector or point
a / 2.0 // Divide (with zero-check)
a *** b // Dot product for vectors, matrix multiplication for matrices
-a // Negate a vector
API Documentation
Full API Reference: goswinr.github.io/Euclid
Platform Support
Thanks to Fable, Euclid can be used not only on .NET but also in JavaScript, TypeScript, Rust, and Python.
The CHECKED_EUCLID compiler flag
Several hot paths contain extra validation that is only compiled in when the DEBUG or the
CHECKED_EUCLID symbol is defined, for example:
NaNandInfinitychecks in thePt,Pnt,VcandVecconstructors- verifying that
UnitVcandUnitVecreally have length 1.0 - range checks in
Rotation2D.createFromSineandcreateFromCosine - index bounds checks in
Polyline2DandPolyline3D -
validation in every unsafe
createUncheckedconstructor: perpendicular and right-handed axes inRect2D,Rect3D,BoxandPPlane, a unitized normal inNPlane, a unitizedQuaternion, and min values not bigger than max values inBRectandBBox
These checks are off by default in release builds because they can be expensive. Some primitive operations are up to 2.5 times slower with them enabled.
CHECKED_EUCLID exists so that the checks can be turned on independently of DEBUG.
This is mostly useful with Fable: Fable compiles the referenced libraries from source
rather than consuming a pre-built assembly, so the symbol actually reaches Euclid's code
and the checks end up in the generated JavaScript or TypeScript, even in a release build.
Enable it in the consuming project file:
|
or on the command line:
|
On .NET the flag only has an effect when Euclid is built from source. The Euclid package on NuGet is pre-compiled without it.
Development
Prerequisites
- .NET SDK 10.0 or later (to have scoped warnings available)
- Node.js (only needed to run the .NET tests in JavaScript and TypeScript via Scriptorium)
Building from Source
|
To build the library and the tests for .NET
|
for JavaScript/TypeScript (compiles the .NET code to JavaScript via Fable)
|
Testing
Tests run on both .NET and JavaScript with TypeScript build verification.
.NET Testing
run the tests from root. (not from within the Test folder)
|
JavaScript Testing
run
|
The test suite ensures cross-platform compatibility and verifies TypeScript type definitions.
Benchmarks
Some more complex algorithms are benchmarked in both .NET and Node JavaScript. See Test/Benchmarks/README.md.
Contributing
Contributions are welcome!
Changelog
See CHANGELOG.md for version history.
License
Examples
Points and Vectors (2D)
open Euclid
// 2D points and vectors
let a = Pt(1.0, 2.0)
let b = Pt(4.0, 6.0)
// Distance between points
let dist = a.DistanceTo b // 5.0
// Midpoint
let mid = Pt.midPt a b // Pt(2.5, 4.0)
// 2D vectors
let v = Vc(3.0, 4.0)
let len = v.Length // 5.0
let half = v.Half // Vc(1.5, 2.0)
let perp = v.Rotate90CCW // perpendicular vector
// Point + vector arithmetic
let moved = a + v // Pt(4.0, 6.0)
let diff = b - a // Vc(3.0, 4.0) : point - point = vector
// Unit vectors (guaranteed length 1.0)
let dir = v.Unitized // UnitVc(0.6, 0.8)
let angle = v.Direction360 // angle in degrees from X-axis
// Dot and cross product
let dot = v.Dot(Vc(1.0, 0.0)) // 3.0
let cross = v.Cross(Vc(1.0, 0.0)) // -4.0 (signed area in 2D)
Points and Vectors (3D)
open Euclid
// 3D points and vectors
let p1 = Pnt(1.0, 2.0, 3.0)
let p2 = Pnt(4.0, 6.0, 3.0)
// Distance, midpoint, lerp
let dist = p1.DistanceTo p2 // 5.0
let mid = Pnt.midPnt p1 p2 // Pnt(2.5, 4.0, 3.0)
let lerp = Pnt.lerp p1 p2 0.25 // 25% from p1 towards p2
// 3D vectors
let v1 = Vec(1.0, 0.0, 0.0)
let v2 = Vec(0.0, 1.0, 0.0)
// Cross product and dot product
let normal = v1.Cross v2 // Vec(0, 0, 1)
let dot = v1.Dot v2 // 0.0
// Angle between vectors
let angle = Vec.angle180 v1 v2 // 90.0 degrees
// Unit vectors
let dir = Vec(3.0, 4.0, 0.0).Unitized // UnitVec(0.6, 0.8, 0.0)
let isPerp = dir.IsPerpendicularTo UnitVec.ZAxis // true
// Convert between 2D and 3D
let pt2d = p1.AsPt // Pt(1.0, 2.0) - drops Z
let pt3d = Pt(1.0, 2.0).WithZ 5.0 // Pnt(1.0, 2.0, 5.0)
Lines
open Euclid
// Create lines from points
let ln2d = Line2D(Pt(0, 0), Pt(10, 0))
let ln3d = Line3D(Pnt(0, 0, 0), Pnt(10, 5, 3))
// Or from coordinates
let ln = Line2D(0.0, 0.0, 10.0, 5.0)
// Line properties
let len = ln2d.Length // 10.0
let midPt = ln2d.Mid // Pt(5, 0)
let vec = ln3d.Vector // Vec from start to end, with the length of the line
let dir = ln3d.UnitTangent // UnitVec of the line direction
// Evaluate at parameter (0.0 = start, 1.0 = end)
let quarterPt = ln2d.EvaluateAt 0.25 // Pt(2.5, 0)
// Extend, shrink, reverse
let longer = ln2d.Extend(2.0, 3.0) // extend 2 at start, 3 at end
let shorter = ln2d.Shrink(1.0, 1.0) // shrink 1 from each end
let flipped = ln2d.Reversed // swap start and end
// Closest point queries
let testPt = Pt(5.0, 3.0)
let closest = ln2d.ClosestPoint testPt // Pt(5, 0) - clamped to segment
let param = ln2d.ClosestParameter testPt // 0.5
// Line-line relationships
let other = Line2D(Pt(5, -5), Pt(5, 5))
let isParallel = ln2d.IsParallelTo other // false
let isPerp = ln2d.IsPerpendicularTo other // true
// Intersection of the two finite lines (returns a voption)
let hit = Line2D.tryIntersect ln2d other // ValueSome (Pt(5, 0))
// Intersection of the two lines extended infinitely
let hitRays = Line2D.tryIntersectRays ln2d other // ValueSome (Pt(5, 0))
let ptRays = Line2D.intersectRays ln2d other // Pt(5, 0), fails if the rays are parallel
// Offset a line
let offsetLn = Line2D.offset 2.0 ln2d // offset by 2.0 to the left
// Move a line
let movedLn = ln2d.Move(Vc(0.0, 5.0)) // move by a vector
Line Intersections (Discriminated Unions)
For detailed intersection analysis, the XLine2D and XLine3D modules return discriminated union types
that let you handle every case explicitly:
open Euclid
let lineA = Line2D(Pt(0, 0), Pt(10, 0))
let lineB = Line2D(Pt(5, -5), Pt(5, 5))
// Finite segment intersection - returns XPt discriminated union
match XLine2D.classifyIntersection lineA lineB with
| XLine2D.XPt.Intersect pt -> printfn $"Lines cross at {pt}"
| XLine2D.XPt.Apart -> printfn "Segments don't reach each other"
| XLine2D.XPt.Parallel -> printfn "Lines are parallel"
| XLine2D.XPt.TooShortA -> printfn "Line A is too short"
| XLine2D.XPt.TooShortB -> printfn "Line B is too short"
| XLine2D.XPt.TooShortBoth -> printfn "Both lines are too short"
// Ray intersection (rays are lines extended infinitely in both directions)
match XLine2D.classifyRayIntersection lineA lineB with
| XLine2D.XRay.Intersect pt -> printfn $"Rays meet at {pt}"
| XLine2D.XRay.Parallel -> printfn "Rays are parallel"
| _ -> ()
// 3D line relationships include skew detection
let ln3A = Line3D(Pnt(0, 0, 0), Pnt(10, 0, 0))
let ln3B = Line3D(Pnt(5, 0, 5), Pnt(5, 10, 5))
match XLine3D.classifyIntersection ln3A ln3B with
| XLine3D.XPnt.Intersect pt -> printfn $"Lines intersect at {pt}"
| XLine3D.XPnt.Skew (ptA, ptB, d) -> printfn $"Closest approach: {d} between {ptA} and {ptB}"
| XLine3D.XPnt.Apart -> printfn "Segments don't reach each other"
| XLine3D.XPnt.Parallel -> printfn "Lines are parallel"
| _ -> ()
Planes
open Euclid
// Normal plane (origin + normal direction)
let npl = NPlane(Pnt(0, 0, 5), UnitVec.ZAxis)
// Distance from plane, and signed distance (positive = same side as normal)
let d = npl.DistanceToPnt (Pnt(3, 4, 2)) // 3.0
let d2 = npl.DistanceToPntSigned (Pnt(3, 4, 2)) // -3.0
// Project a point onto the plane
let proj = npl.ClosestPoint (Pnt(3, 4, 8)) // Pnt(3, 4, 5)
// Angle between plane and vector (0 = parallel, 90 = perpendicular)
let ang = npl.Angle90ToVec (Vec(1, 0, 0)) // 0.0 (vector lies in plane)
// Parametrized plane (full coordinate frame with X, Y, Z axes)
let ppl = PPlane.createFrom3Pnts
(Pnt(0, 0, 0)) // origin
(Pnt(10, 0, 0)) // point on X-axis
(Pnt(0, 10, 0)) // point on Y-axis side
Rectangles
open Euclid
// 2D rectangle from origin, X-direction vector, and Y-size
let rect = Rect2D.createFromVc 5.0 (Vc(10, 0)) (Pt(0, 0))
// From direction and sizes
let dir = UnitVc.rotateDegrees 45.0 UnitVc.XAxis
let rotRect = Rect2D.createFromUnitVc 10.0 5.0 dir (Pt(0, 0))
// Rectangle properties
let area = rect.Area
let cx = rect.SizeX
let cy = rect.SizeY
let center = rect.Center
let c0 = rect.Origin // origin corner
let c2 = rect.FarCorner // diagonally opposite corner
// Point evaluation (u, v parameters from 0 to 1)
let midPoint = rect.EvaluateAt(0.5, 0.5) // center point
Bounding Boxes
open Euclid
// 3D axis-aligned bounding box from points
let points = [Pnt(0, 0, 0); Pnt(10, 5, 3); Pnt(-2, 8, 1)]
let bbox = BBox.createFromSeq points
// BBox properties
let size = bbox.SizeX, bbox.SizeY, bbox.SizeZ // 12.0, 8.0, 3.0
let minPt = bbox.MinPnt // Pnt(-2, 0, 0)
let maxPt = bbox.MaxPnt // Pnt(10, 8, 3)
let center = bbox.Center // Pnt(4, 4, 1.5)
let vol = bbox.Volume // 288.0
// Create from center and sizes
let box2 = BBox.createCentered 10.0 10.0 10.0 (Pnt(0, 0, 0))
// Expand bounding box
let bigger = bbox.Expand 1.0 // expand by 1.0 on all sides
// Check containment
let inside = bbox.ContainsPnt(Pnt(5, 4, 2)) // true
// Union of two bounding boxes
let combined = bbox.Union box2
Polylines
open Euclid
// Create a 2D polyline
let pl2d = Polyline2D.createFromPts [Pt(0, 0); Pt(10, 0); Pt(10, 5); Pt(0, 5)]
// Polyline properties
let len = pl2d.Length // total length
let count = pl2d.PointCount // 4
let segs = pl2d.SegmentCount // 3
// Access segments as Line2D
let firstSeg = pl2d.FirstSegment // Line2D(Pt(0,0), Pt(10,0))
let seg = pl2d.GetSegment(1) // Line2D(Pt(10,0), Pt(10,5))
// Modify (polylines are mutable)
pl2d.SetPoint (2, Pt(12, 5)) // move a vertex
let copy = pl2d.Duplicate() // deep copy
copy.Move(Vc(0, 3)) // instance members change the polyline in place
let movedPl = Polyline2D.move (Vc(0, 3)) pl2d // static functions return a new polyline
// 3D polyline
let pl3d = Polyline3D.createFromPnts [Pnt(0,0,0); Pnt(10,0,0); Pnt(10,5,3)]
let totalLen = pl3d.Length
Transformations with Matrices
open Euclid
let pt = Pnt(5.0, 0.0, 0.0)
// Translation
let m1 = Matrix.createTranslationXYZ 10.0 0.0 0.0
// Rotation (angle in degrees)
let m2 = Matrix.createRotationZDegrees 90.0 // 90 degrees around Z
let m3 = Matrix.createRotationXDegrees 45.0 // 45 degrees around X
// Rotation around arbitrary axis
let m4 = Matrix.createRotationFromDegreesUnitVec UnitVec.ZAxis 30.0
// Rotation around axis at a specific center point
let m5 = Matrix.createRotationFromDegreesVecAround (Pnt(5, 5, 0)) (Vec(0, 0, 1)) 45.0
// Scale
let m6 = Matrix.createScale 2.0 2.0 1.0 // scale X and Y by 2
// Shear
let m7 = Matrix.createShear(0.5, 0, 0, 0, 0, 0) // shear XY by 0.5
// Combine transformations: first m1, then m2, then m6
let combined = m1.Then(m2).Then(m6) // same as m1 *** m2 *** m6
// Apply to points and vectors
let pt2 = pt.Transform combined // full transform (rotate, scale, move)
let v = Vec(1, 0, 0)
let v2 = v.Transform combined // rotate and scale, the translation is ignored
let rigid = RigidMatrix.createRotationZDegrees 90.0
let v3 = v.TransformRigid rigid // rotate without translation
// Functional pipeline style
let result =
pt
|> Pnt.move (Vec(10, 0, 0))
|> Pnt.rotateOnZDegrees 90.0
|> Pnt.scale 2.0
|> Pnt.transform combined
// Matrix from plane to plane
let fromPlane = PPlane.createFrom3Pnts (Pnt(0,0,0)) (Pnt(1,0,0)) (Pnt(0,1,0))
let toPlane = PPlane.createFrom3Pnts (Pnt(5,5,0)) (Pnt(6,5,0)) (Pnt(5,6,0))
let planeXform = Matrix.createPlaneToPlane fromPlane toPlane
// Mirror about a plane
let mirror = Matrix.createMirror fromPlane
Quaternion Rotations
open Euclid
// Create quaternion from axis and angle
let q1 = Quaternion.createFromDegreesVec (Vec(0, 0, 1)) 90.0 // 90 degrees around Z
let q2 = Quaternion.createFromRadiansUnitVec UnitVec.XAxis 1.5708 // Pi/2 around X
// Rotate from one direction to another
let q3 = Quaternion.createFromUnitVecs UnitVec.XAxis UnitVec.YAxis // X -> Y
// Quaternion properties
let angle = q1.AngleInDegrees // 90.0
let axis = q1.Axis // Vec close to (0, 0, 1)
let inv = q1.Inverse // reverse rotation
// Compose rotations: first q1, then q2
let q4 = q1.Then q2
let q5 = q1 |> Quaternion.andThen q2 // same as q1.Then q2
let q6 = q1 *** q2 // Hamilton product: first q2, then q1
// Apply to points and vectors
let rotated = Pnt.rotate q1 (Pnt(1, 0, 0)) // Pnt(0, 1, 0)
// Convert quaternion to matrix
let mat = Matrix.createFromQuaternion q1
Point Cloud Operations
open Euclid
let cloud = ResizeArray [Pnt(0,0,0); Pnt(1,0,0); Pnt(5,5,5); Pnt(10,10,10)]
// Find closest point to a test point
let nearest = Points3D.closestPoint (Pnt(1.1, 0.1, 0.0)) cloud // Pnt(1,0,0)
let idx = Points3D.closestPointIndex (Pnt(1.1, 0.1, 0.0)) cloud // 1
// Closest points between two sets
let setA = ResizeArray [Pnt(0,0,0); Pnt(10,10,10)]
let setB = ResizeArray [Pnt(1,0,0); Pnt(20,20,20)]
let (iA, iB) = Points3D.closestPointsIndices setA setB // (0, 0)
// Most distant point
let farthest = Points3D.mostDistantPoint setB cloud
// center of points
let center = Points3D.center cloud // Pnt(4, 3.75, 3.75)
Error Handling
Euclid uses descriptive custom exceptions instead of silent failures:
open Euclid
// Unitizing a zero vector raises EuclidException
try
let bad = Vec(0, 0, 0).Unitized // fails: can't unitize zero vector
with e ->
printfn $"Caught: {e.Message}"
// Division by near-zero raises EuclidDivByZeroException
// NaN or Infinity in inputs raises EuclidException
// Tolerances are conservative for precision engineering:
// - zeroLengthTolerance = 1e-12 (for divisions, unitizing)
// - isTooSmall = 1e-6 (general smallness check)
type Pnt = new: x: float * y: float * z: float -> Pnt val X: float val Y: float val Z: float override ToString: unit -> string static member ( * ) : a: Pnt * f: float -> Pnt + 1 overload static member (+) : a: Pnt * b: Pnt -> Pnt + 2 overloads static member (-) : a: Pnt * b: Pnt -> Vec + 2 overloads static member (/) : p: Pnt * f: float -> Pnt static member DivideByInt: pt: Pnt * i: int -> Pnt ...
<summary> A struct containing 3 floats, representing an immutable 3D point. X, Y, and Z. A 3D point represents a location in space, but not direction. (use Vec for that.) (2D Points are called 'Pt' ) </summary>
--------------------
Pnt ()
new: x: float * y: float * z: float -> Pnt
type Vec = new: x: float * y: float * z: float -> Vec val X: float val Y: float val Z: float override ToString: unit -> string static member ( * ) : a: Vec * f: float -> Vec + 1 overload static member ( *** ) : a: Vec * b: Vec -> float static member (+) : a: Vec * b: Vec -> Vec static member (-) : a: Vec * b: Vec -> Vec static member (/) : v: Vec * f: float -> Vec ...
<summary> An immutable 3D vector of any length. Made up from 3 floats: X, Y, and Z. A 3D vector represents a direction or translation in space, but not a location. A 4x4 transformation matrix applied to a vector will only rotate and scale the vector but not translate it. (3D unit-vectors of length 1.0 are called 'UnitVec' ) (2D vectors are called 'Vc' ) </summary>
--------------------
Vec ()
new: x: float * y: float * z: float -> Vec
<summary> Returns the 3D vector unitized. Fails with EuclidDivByZeroException if the length of the vector is less than 1e-12 (UtilEuclid.zeroLengthTolerance). </summary>
type Matrix = new: m11: float * m21: float * m31: float * x41: float * m12: float * m22: float * m32: float * y42: float * m13: float * m23: float * m33: float * z43: float * m14: float * m24: float * m34: float * m44: float -> Matrix val M11: float val M21: float val M31: float val X41: float val M12: float val M22: float val M32: float val Y42: float val M13: float ...
<summary>A struct containing 16 floats, representing an immutable 4x4 transformation matrix. The matrix is represented in the following column-vector syntax form: <code> M11 M21 M31 X41 M12 M22 M32 Y42 M13 M23 M33 Z43 M14 M24 M34 M44 </code> Where X41, Y42 and Z43 refer to the translation part of the matrix. Note: Never use the struct default constructor Matrix() as it will create an invalid zero Matrix. Use Matrix.create or Matrix.createUnchecked instead.</summary>
--------------------
Matrix ()
new: m11: float * m21: float * m31: float * x41: float * m12: float * m22: float * m32: float * y42: float * m13: float * m23: float * m33: float * z43: float * m14: float * m24: float * m34: float * m44: float -> Matrix
module XLine2D from Euclid
<summary> A module containing the result types for 2D Line-Line-Intersections and 2D Line-Line relationship queries. </summary>
--------------------
type XLine2D = static member closestParameters: pA: Pt * pB: Pt * vA: Vc * vB: Vc -> struct (float * float) + 1 overload static member doIntersect: pA: Pt * pB: Pt * vA: Vc * vB: Vc -> bool + 1 overload static member doOverlap: pA: Pt * pB: Pt * vA: Vc * vB: Vc * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tolerance: float -> bool + 1 overload static member getClosestParameters: pA: Pt * pB: Pt * vA: Vc * vB: Vc * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> ClParams + 1 overload static member getClosestPoints: pA: Pt * pB: Pt * vA: Vc * vB: Vc * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> ClPts + 1 overload static member getEndsTouching: a: Line2D * b: Line2D * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tolerance: float -> XEnds static member getIntersection: pA: Pt * pB: Pt * vA: Vc * vB: Vc * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> XPt + 1 overload static member getIntersectionParam: pA: Pt * pB: Pt * vA: Vc * vB: Vc * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> XParam + 1 overload static member getRayIntersection: pA: Pt * pB: Pt * vA: Vc * vB: Vc * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> XRay + 1 overload static member getRayIntersectionParam: pA: Pt * pB: Pt * vA: Vc * vB: Vc * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> XRayParam + 1 overload ...
<summary> A type containing only static member functions for computing 2D line intersections. Some functions return Discriminated Unions from the XLine2D module. </summary>
<summary> A module of precalculated tangent values for faster checking the angles between two vectors. The Cross Product length (=determinant) divided by the Dot Product value gives the tangent of the angle between two vectors. If one of vectors has a zero length, the tangent is NaN </summary>
type Polyline2D = new: capacity: int -> Polyline2D member AddPoint: pt: Pt -> unit member AddXY: x: float * y: float -> unit member Clone: unit -> Polyline2D member CloseInPlace: [<Optional; DefaultParameterValue ((1e-06 :> obj))>] toleranceForAddingPoint: float -> unit member ClosestParameter: p: Pt -> float member ClosestParameterXY: x: float * y: float -> float member ClosestPoint: p: Pt -> Pt member ClosestPointIndex: p: Pt -> int member Contains: pt: Pt -> bool ...
<summary> A class holding a list of 2D points representing a mutable 2D Polyline. If the last point is the same as the first point, the Polyline2D is considered closed. The source-of-truth storage is an interleaved float buffer: x0, y0, x1, y1, ... </summary>
--------------------
new: capacity: int -> Polyline2D
type Pt = new: x: float * y: float -> Pt val X: float val Y: float override ToString: unit -> string static member ( * ) : a: Pt * f: float -> Pt + 1 overload static member (+) : p: Pt * v: Vc -> Pt + 2 overloads static member (-) : a: Pt * b: Pt -> Vc + 2 overloads static member (/) : p: Pt * f: float -> Pt static member DivideByInt: pt: Pt * i: int -> Pt member AsFSharpCode: string ...
<summary> Pt is an immutable 2D point. Made up from 2 floats: X and Y.</summary>
<remarks> 3D Points are called 'Pnt' </remarks>
--------------------
Pt ()
new: x: float * y: float -> Pt
type Vc = new: x: float * y: float -> Vc val X: float val Y: float override ToString: unit -> string static member ( * ) : v: Vc * f: float -> Vc + 1 overload static member ( *** ) : a: Vc * b: Vc -> float static member (+) : a: Vc * b: Vc -> Vc static member (-) : a: Vc * b: Vc -> Vc static member (/) : v: Vc * f: float -> Vc static member DivideByInt: v: Vc * i: int -> Vc ...
<summary>Vc is an immutable 2D vector with any length. Made up from 2 floats: X and Y.</summary>
<remarks>2D unit-vectors with length 1.0 are called 'UnitVc'. 3D vectors are called 'Vec'.</remarks>
--------------------
Vc ()
new: x: float * y: float -> Vc
<summary> A struct containing 3 floats, representing a 3D unit vector. All instances of this type are guaranteed to be always unitized. A 3D vector represents a direction or translation in space, but not a location. A 4x4 transformation matrix applied to a vector will only rotate and scale the vector but not translate it. (2D unit-vectors are called 'UnitVc' ) Use UnitVec.create or UnitVec.createUnchecked to create instances. Note: Never use the struct default constructor UnitVec() as it will create an invalid zero length vector. Use UnitVec.create or UnitVec.createUnchecked instead. </summary>
type Line2D = new: fromPt: Pt * toPt: Pt -> Line2D + 1 overload val FromX: float val FromY: float val ToX: float val ToY: float override ToString: unit -> string member AsFSharpCode: string member AsString: string member End: Pt member From: Pt ...
<summary> A struct containing 4 floats, representing an immutable finite line in 2D. </summary>
--------------------
Line2D ()
new: fromPt: Pt * toPt: Pt -> Line2D
new: fromX: float * fromY: float * toX: float * toY: float -> Line2D
type Line3D = new: fromPt: Pnt * toPt: Pnt -> Line3D + 1 overload val FromX: float val FromY: float val FromZ: float val ToX: float val ToY: float val ToZ: float override ToString: unit -> string member AsFSharpCode: string member AsString: string ...
<summary> A struct containing 6 floats, representing an immutable finite line in 3D. </summary>
--------------------
Line3D ()
new: fromPt: Pnt * toPt: Pnt -> Line3D
new: fromX: float * fromY: float * fromZ: float * toX: float * toY: float * toZ: float -> Line3D
<summary> Describes the possible relationships of two finite 2D lines. Returns the intersection point if they intersect. </summary>
<summary> The finite lines are intersecting in one well defined point. </summary>
<summary> The finite 2D lines do not touch each other. Their intersection point is outside of their finite definition. However they are not parallel. XPt.Parallel is used when they are parallel. </summary>
<summary> The lines are parallel or even coincident, within the given tolerance. </summary>
<summary> Line A is shorter than the given minimum length tolerance. </summary>
<summary> Line B is shorter than the given minimum length tolerance. </summary>
<summary> Both Lines are shorter than the given minimum length tolerance. </summary>
<summary> Describes the possible intersection point of two rays (rays are 2D lines extended infinitely in both directions). Returns the intersection point if they intersect. </summary>
<summary> The rays (2d-lines extended infinitely) are intersecting in one well defined point. </summary>
<summary> The lines are parallel or even coincident, within the given tolerance. </summary>
module XLine3D from Euclid
<summary> A module containing the result types for 3D Line-Line-Intersections, 3D Line-Line relationship queries, and Line-Cone intersections. </summary>
--------------------
type XLine3D = static member doIntersect: pA: Pnt * pB: Pnt * vA: Vec * vB: Vec * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] maxSkewDistance: float * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> bool + 1 overload static member doOverlap: pA: Pnt * pB: Pnt * vA: Vec * vB: Vec * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tolerance: float -> bool + 1 overload static member doRaysIntersect: pA: Pnt * pB: Pnt * vA: Vec * vB: Vec * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] maxSkewDistance: float -> bool + 1 overload static member getClosestParameters: pA: Pnt * pB: Pnt * vA: Vec * vB: Vec * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> ClParams + 1 overload static member getClosestPoints: pA: Pnt * pB: Pnt * vA: Vec * vB: Vec * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> ClPts + 1 overload static member getEndsTouching: a: Line3D * b: Line3D * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tolerance: float -> XEnds static member getIntersection: pA: Pnt * pB: Pnt * vA: Vec * vB: Vec * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] maxSkewDistance: float * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> XPnt + 1 overload static member getIntersectionParam: pA: Pnt * pB: Pnt * vA: Vec * vB: Vec * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] maxSkewDistance: float * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> XParam + 1 overload static member getRayClosestParam: pA: Pnt * pB: Pnt * vA: Vec * vB: Vec * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> XRayParam + 1 overload static member getRayIntersection: pA: Pnt * pB: Pnt * vA: Vec * vB: Vec * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] maxSkewDistance: float * [<Optional; DefaultParameterValue ((0.0043633508207 :> obj))>] tangent: float<tangent> * [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tooShortTolerance: float -> XRay + 1 overload ...
<summary> A type containing only static member functions for computing 3D line intersections and closest approaches. Some functions return Discriminated Unions from the XLine3D module. </summary>
<summary> Describes the possible relationships of two finite 3D lines. Returns the intersection or closest point if they intersect or are skew. </summary>
<summary> The finite lines are intersecting in one well defined point (coplanar case). </summary>
<summary> The finite 3D lines are skew (not parallel, not coplanar). Contains the closest points on both lines and the squared distance between them. </summary>
<summary> The finite 3D lines do not touch each other. Their intersection point (or closest approach) is outside of their finite definition. However they are not parallel. XPt.Parallel is used when they are parallel. </summary>
<summary> The lines are parallel, within the given tolerance. They have infinity many or no points in common. </summary>
type NPlane = new: pt: Pnt * n: UnitVec -> NPlane val OriginX: float val OriginY: float val OriginZ: float val NormalX: float val NormalY: float val NormalZ: float member Angle90ToLine: ln: Line3D -> float member Angle90ToPlane: pl: NPlane -> float member Angle90ToVec: v: Vec -> float + 1 overload ...
<summary> A struct containing a point and a unit normal, representing an unparametrized plane defined by a point and a normal vector. As opposed to the PPlane, this plane is not parametrized in X, Y, and Z directions. Internally it is stored as 6 floats (the Origin point coordinates and the normal vector components), just like the PPlane type. The Origin and Normal properties reconstruct the Pnt and UnitVec on demand. Note: Never use the struct default constructor NPlane() as it will create an invalid zero plane. Use NPlane.create or NPlane.createUnchecked instead. </summary>
--------------------
NPlane ()
new: pt: Pnt * n: UnitVec -> NPlane
<summary> A struct containing one 3D point and three 3D unit vectors, representing an immutable parametrized plane or frame with unitized X, Y and Z Direction. Internally it is stored as 12 floats (the Origin point coordinates and the three axis vector components), just like the box type. The Origin, Xaxis, Yaxis and Zaxis properties reconstruct the Pnt and UnitVec on demand. This struct is called 'PPlane'; the other plane 'NPlane' refers to an un-oriented plane consisting only of an origin and a normal. Note: Never use the struct default constructor PPlane() as it will create an invalid zero length PPlane. Use PPlane.create or PPlane.createUnchecked instead. </summary>
<summary> A struct containing a 2D Origin point and two 2D Edge vectors, representing an immutable 2D rectangle with any rotation in 2D space. This implementation guarantees the 2D rectangle to be always valid. That means the X and Y axes are always perpendicular to each other. However the length of one of these axes might still be zero. <code> local Y-axis ^ | | 2 3 +------------+ | | | | | | | | | | local +------------+-----> X-axis 0-Origin 1 </code></summary>
<summary>A struct containing 2 floats, representing a 2D unitized vector. All instances of this type are guaranteed to be always unitized. Never use the struct default constructor UnitVc()! It will create an invalid zero length vector. Use UnitVc.create or UnitVc.createUnchecked instead.</summary>
<remarks>3D unit-vectors are called 'UnitVec'</remarks>
<summary> A struct of 6 floats representing an immutable 3D bounding box. This implementation guarantees the box to always be valid. That means the Min X, Y, and Z values are always smaller or equal to the respective Max values. <code> Z-axis Y-axis ^ / | 7 / 6 MaxPnt | +---------------+ | /| / /| | / | / / | 4 |/ | / 5 / | +---------------+ | | |/ | | | +-----------|---+ | / 3 | / 2 | / | / |/ |/ +---------------+----> X-axis 0 MinPnt 1 From the center of a BBox, the points have these signs of X, Y and Z coordinates: Pt0 (-,-,-) Pt1 (+,-,-) Pt2 (+,-,+) Pt3 (-,-,+) Pt4 (-,+,-) Pt5 (+,+,-) Pt6 (+,+,+) Pt7 (-,+,+) </code></summary>
type Polyline3D = new: capacity: int -> Polyline3D + 1 overload member AddPoint: pt: Pnt -> unit member AddXYZ: x: float * y: float * z: float -> unit member AveragePlane: [<Optional; DefaultParameterValue ((1e-06 :> obj))>] tolerance: float -> NPlane member Clone: unit -> Polyline3D member CloseInPlace: [<Optional; DefaultParameterValue ((1e-06 :> obj))>] toleranceForAddingPoint: float -> unit member ClosestParameter: p: Pnt -> float member ClosestParameterXYZ: x: float * y: float * z: float -> float member ClosestPoint: p: Pnt -> Pnt member ClosestPointIndex: p: Pnt -> int ...
<summary> A class holding a list of 3D points representing a mutable 3D Polyline. If the last point is the same as the first point, the Polyline3D is closed. The source-of-truth storage is an interleaved float buffer: x0, y0, z0, x1, y1, z1, ... </summary>
--------------------
new: capacity: int -> Polyline3D
new: points: Pnt seq -> Polyline3D
<summary>A struct containing 12 floats, representing an immutable 4x3 rigid transformation matrix. This matrix guarantees to NOT scale, shear, flip, mirror, reflect or project. Angles are preserved. Lengths are preserved. Area is preserved. Volume is preserved. Transformations with 4x3 RigidMatrices are faster than with the more general 4x4 Matrices. A rigid matrix is made from a rotational 3x3 part whose columns and rows are orthogonal 3D unit-vectors. The last 1x3 column is the translation part of the matrix. It can be thought of as a 4x4 Orthonormal matrix where the last row would always be 0, 0, 0, 1. Thus it is not stored in the RigidMatrix 4x3 struct. The matrix is represented in the following column-vector syntax form: <code> M11 M21 M31 X41 M12 M22 M32 Y42 M13 M23 M33 Z43 </code> Where X41, Y42 and Z43 refer to the translation part of the RigidMatrix. The Determinant of this matrix is always 1.0. Note: Never use the struct default constructor RigidMatrix() as it will create an invalid zero RigidMatrix. Use RigidMatrix.create instead.</summary>
<summary> A struct containing 4 floats, representing an immutable unitized Quaternion, for arbitrary 3D rotations. This implementation guarantees the Quaternion to be always unitized. Note: Never use the struct default constructor Quaternion() as it will create an invalid zero length Quaternion. Use Quaternion.create or Quaternion.createUnchecked instead. </summary>
<summary> A type containing only static member functions for operating on multiple 3D points or set of 3D points. Aka point-clouds </summary>
Euclid