Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-3d

Source of release 0.9.5

0.9.5 / src / geometries / box.lucb

## A hard-edged box, centred at the origin, with independent UVs per face.
import interop
import errors
from luce_geocore.geocore import Geometry, Vertex, Bounds, Vector3

pub struct BoxGeometry: Geometry:
    let half: Vector3

    pub func init(width: f64 = 1.0, height: f64 = 1.0, depth: f64 = 1.0) -> !:
        if not (width > 0.0 and width <= 1000000.0 and height > 0.0 and height <= 1000000.0 and depth > 0.0 and depth <= 1000000.0):
            error(errors.invalid, "box dimensions must be in (0,1000000]")
        self.half = Vector3(width * 0.5, height * 0.5, depth * 0.5)

    pub func vertex_count() -> i64:
        return 24

    pub func index_count() -> i64:
        return 36

    pub func vertex(index: i64) -> interop.Outcome[Vertex]:
        if index < 0 or index >= 24:
            return errors.failure[Vertex](errors.invalid, "box vertex index outside 0..23")
        let face = index // 4
        let corner = index % 4
        let u = 1.0 if corner == 1 or corner == 2 else 0.0
        let v = 1.0 if corner >= 2 else 0.0
        let a = u * 2.0 - 1.0
        let b = v * 2.0 - 1.0
        let h = self.half
        var position = Vector3()
        var normal = Vector3()
        if face == 0:
            position = Vector3(h.x, b * h.y, -a * h.z)
            normal = Vector3(1.0, 0.0, 0.0)
        elif face == 1:
            position = Vector3(-h.x, b * h.y, a * h.z)
            normal = Vector3(-1.0, 0.0, 0.0)
        elif face == 2:
            position = Vector3(a * h.x, h.y, -b * h.z)
            normal = Vector3(0.0, 1.0, 0.0)
        elif face == 3:
            position = Vector3(a * h.x, -h.y, b * h.z)
            normal = Vector3(0.0, -1.0, 0.0)
        elif face == 4:
            position = Vector3(a * h.x, b * h.y, h.z)
            normal = Vector3(0.0, 0.0, 1.0)
        else:
            position = Vector3(-a * h.x, b * h.y, -h.z)
            normal = Vector3(0.0, 0.0, -1.0)
        return errors.success[Vertex](Vertex(position, normal, u, v))

    pub func index(offset: i64) -> interop.Outcome[i64]:
        if offset < 0 or offset >= 36:
            return errors.failure[i64](errors.invalid, "box index outside 0..35")
        let corner = offset % 6
        let face_index = corner if corner < 3 else (0 if corner == 3 else corner - 2)
        return errors.success[i64]((offset // 6) * 4 + face_index)

    pub func bounds() -> Bounds:
        return Bounds(self.half.multiply_scalar(-1.0), self.half)

    pub func close():
        _ = self

pub let box_geometry_type: interop.Type[BoxGeometry] = interop.Type[BoxGeometry]("BoxGeometry", BoxGeometry.close, main_thread = true)