Skip to content

Point3D.kt

src/jvmMain/kotlin/afield/geometry/path/planning/Point3D.kt · 39 lines

@file:afield.runtime.completion.CompletionCategory("Math")

package afield.geometry.path.planning

import kotlin.math.sqrt

A small immutable 3D point type used by the path-planning curves in this package.

Point3D carries finite double coordinates with the vector operations a curve needs: addition, difference, scaling, Point3D.dot, Point3D.cross, Point3D.length and Point3D.normalized. CubicBezier3D is built from it.

data class Point3D(val x: Double, val y: Double, val z: Double)

Immutable double-precision coordinates; units are chosen by the caller.

init { require(x.isFinite() && y.isFinite() && z.isFinite()) { "Coordinates must be finite" } }

operator fun plus(b: Point3D) = Point3D(x+b.x, y+b.y, z+b.z)

Coordinate-wise addition, returning a new value.

operator fun minus(b: Point3D) = Point3D(x-b.x, y-b.y, z-b.z)

Coordinate-wise difference, also usable as a displacement.

operator fun unaryMinus() = this * -1.0

Negates all coordinates without changing this value.

operator fun times(scale: Double) = Point3D(x*scale, y*scale, z*scale)

Multiplies every coordinate by scale; non-finite results are rejected.

infix fun dot(b: Point3D) = x*b.x+y*b.y+z*b.z

Euclidean dot product, treating the coordinates as vectors.

infix fun cross(b: Point3D) = Point3D(y*b.z-z*b.y, z*b.x-x*b.z, x*b.y-y*b.x)

Right-handed cross product, treating the coordinates as vectors.

val length: Double get() = sqrt(this dot this)

Euclidean distance from the origin in the caller's units.

fun normalized(): Point3D { val n=length; require(n.isFinite() && n>0); return this*(1.0/n) }

Unit direction; rejects zero length and lengths that overflow.

companion object { val ORIGIN = Point3D(0.0,0.0,0.0) }

fun distanceTo(b: Point3D): Double = (this-b).length

Euclidean distance to b in the caller's units.