commonMain.ru.casperix.math.geometry.Triangle.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of math Show documentation
Show all versions of math Show documentation
Simple set of geometric and other types
package ru.casperix.math.geometry
import ru.casperix.math.vector.float32.Vector2f
import ru.casperix.math.vector.float32.Vector3f
import ru.casperix.math.vector.float64.Vector2d
import ru.casperix.math.vector.float64.Vector3d
import ru.casperix.math.vector.int32.Vector2i
import kotlinx.serialization.Serializable
/**
* 1|\
* | \
* 0|----\2
*/
@Serializable
data class Triangle(val v0: Point, val v1: Point, val v2: Point) : Polygon {
override fun convert(converter: (Point) -> TargetPoint): Triangle {
return Triangle(
converter(v0),
converter(v1),
converter(v2)
)
}
override fun getVertexAmount(): Int {
return 3
}
override fun getVertex(index: Int): Point {
return when (index) {
0 -> v0
1 -> v1
2 -> v2
else -> throw Error("Invalid index")
}
}
override fun getEdge(index: Int): Line {
return when (index) {
0 -> Line(v0, v1)
1 -> Line(v1, v2)
2 -> Line(v2, v0)
else -> throw Error("Expected index in range 0 - 2. Actual: $index")
}
}
override fun getEdgeAmount(): Int {
return 3
}
override fun getEdgeList(): List> {
return (0 until getEdgeAmount()).map {
getEdge(it)
}
}
override fun toString(): String {
return "Tri(v0=$v0, v1=$v1, v2=$v2)"
}
companion object {
fun from(list: List): Triangle? {
if (list.size != 3) return null
return Triangle(list[0], list[1], list[2])
}
}
}
fun Triangle3d.getNormal(): Vector3d {
return getTriangleNormal(v0, v1, v2)
}
fun Triangle3d.scale(scale: Double): Triangle3d {
val center = (v0 + v1 + v2) / 3.0
return Triangle3d(center + (v0 - center) * scale, center + (v1 - center) * scale, center + (v2 - center) * scale)
}
fun getTriangleNormal(v0: Vector3d, v1: Vector3d, v2: Vector3d): Vector3d {
return (v2 - v0).cross(v1 - v0).normalize()
}
typealias Triangle3d = Triangle
typealias Triangle2d = Triangle
typealias Triangle3f = Triangle
typealias Triangle2f = Triangle
typealias Triangle2i = Triangle