commonMain.ru.casperix.math.axis_aligned.int32.Box2i.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.axis_aligned.int32
import ru.casperix.math.axis_aligned.Box
import ru.casperix.math.axis_aligned.float32.Box2f
import ru.casperix.math.axis_aligned.float64.Box2d
import ru.casperix.math.iteration.Box2Iterator
import ru.casperix.math.vector.float32.Vector2f
import ru.casperix.math.vector.int32.Vector2i
import kotlinx.serialization.Serializable
@Serializable
data class Box2i(override val min: Vector2i, override val max: Vector2i) : Box {
override val center: Vector2i get() = (max + min) / 2
override val dimension: Vector2i get() = Vector2i.ONE + max - min
override val volume: Int get() = dimension.x * dimension.y
init {
if (!max.greaterOrEq(min)) throw Error("Invalid box height $dimension")
}
override fun isInside(point: Vector2i): Boolean {
return point.greaterOrEq(min) && point.lessOrEq(max)
}
fun isSide(pos: Vector2i): Boolean {
return pos.x == min.x || pos.x == max.x || pos.y == min.y || pos.y == max.y
}
operator fun iterator(): Iterator {
return Box2Iterator(this)
}
fun toBox2f(): Box2f {
return Box2f.byDimension(min.toVector2f(), dimension.toVector2f())
}
fun toBox2d(): Box2d {
return Box2d.byDimension(min.toVector2d(), dimension.toVector2d())
}
override fun toString(): String {
return "Box2i(min=${min}; max=${max})"
}
operator fun Box2i.plus(offset: Vector2i): Box2i {
return Box2i(min + offset, max + offset)
}
fun grow(value: Int): Box2i {
return Box2i(min - Vector2i(value), max + Vector2i(value))
}
companion object {
val ONE = Box2i(Vector2i.ZERO, Vector2i.ONE)
val ZERO = Box2i(Vector2i.ZERO, Vector2i.ZERO)
fun createOrNull(min: Vector2i, max: Vector2i): Box2i? {
if (!(max - min).greaterOrEq(Vector2i.ZERO)) return null
return Box2i(min, max)
}
fun byRadius(center: Vector2i, radius: Vector2i): Box2i {
return Box2i(center - radius, center + radius)
}
fun byCorners(A: Vector2i, B: Vector2i): Box2i {
val min = A.lower(B)
val max = A.upper(B)
return Box2i(min, max)
}
fun byDimension(start: Vector2i, dimension: Vector2i): Box2i {
return Box2i(start, start + dimension - Vector2i.ONE)
}
}
}