All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.ru.casperix.math.axis_aligned.float32.Box2f.kt Maven / Gradle / Ivy

package ru.casperix.math.axis_aligned.float32

import ru.casperix.math.axis_aligned.Box
import ru.casperix.math.axis_aligned.float64.Box2d
import ru.casperix.math.axis_aligned.int32.Box2i
import ru.casperix.math.vector.float32.Vector2f
import kotlinx.serialization.Serializable

@Serializable
data class Box2f(override val min: Vector2f, override val max: Vector2f) : Box {
    override val center: Vector2f get() = (max + min) * 0.5f
    override val dimension: Vector2f get() = max - min
    override val volume: Float get() = dimension.x * dimension.y


    init {
        if (!min.isFinite() || !max.isFinite()) throw Error("Box is invalid ($min => $max)")
        if (!min.lessOrEq(max)) throw Error("$min > $max mst be valid for $Box2d");
    }

    override fun isInside(point: Vector2f): Boolean {
        return min.x <= point.x && point.x <= max.x && min.y <= point.y && point.y <= max.y
    }

    fun toBox2i(): Box2i? {
        try {
            return Box2i(min.toVector2i(), max.toVector2i())
        } catch (t: Throwable) {
            return null
        }
    }

    override fun toString(): String {
        return "Box2d(min=${min}; max=${max})"
    }

    fun grow(value: Float): Box2f {
        return Box2f(min - Vector2f(value), max + Vector2f(value))
    }

    operator fun plus(offset: Vector2f): Box2f {
        return Box2f(min + offset, max + offset)
    }

    companion object {
        val ONE = Box2f(Vector2f.ZERO, Vector2f.ONE)
        val ZERO = Box2f(Vector2f.ZERO, Vector2f.ZERO)

        fun createOrNull(min: Vector2f, max: Vector2f): Box2f? {
            if (!min.lessOrEq(max)) return null
            return Box2f(min, max)
        }

        fun byCorners(A: Vector2f, B: Vector2f): Box2f {
            val min = A.lower(B)
            val max = A.upper(B)
            return Box2f(min, max)
        }

        fun byRadius(center: Vector2f, radius: Vector2f): Box2f {
            return Box2f(center - radius, center + radius)
        }

        fun byDimension(start: Vector2f, dimension: Vector2f): Box2f {
            return Box2f(start, start + dimension)
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy