package com.tiedup.remake.client.renderer.obj;

/**
 * Immutable record representing a triangular face in an OBJ model.
 * Contains exactly 3 vertices forming a triangle.
 */
public record ObjFace(ObjVertex v0, ObjVertex v1, ObjVertex v2) {
    /**
     * Get the vertices as an array for iteration.
     */
    public ObjVertex[] vertices() {
        return new ObjVertex[] { v0, v1, v2 };
    }

    /**
     * Calculate the face normal from vertices (cross product of edges).
     * Useful when the OBJ file doesn't provide normals.
     */
    public float[] calculateNormal() {
        // Edge vectors
        float e1x = v1.x() - v0.x();
        float e1y = v1.y() - v0.y();
        float e1z = v1.z() - v0.z();

        float e2x = v2.x() - v0.x();
        float e2y = v2.y() - v0.y();
        float e2z = v2.z() - v0.z();

        // Cross product
        float nx = e1y * e2z - e1z * e2y;
        float ny = e1z * e2x - e1x * e2z;
        float nz = e1x * e2y - e1y * e2x;

        // Normalize
        float len = (float) Math.sqrt(nx * nx + ny * ny + nz * nz);
        if (len > 0.0001f) {
            nx /= len;
            ny /= len;
            nz /= len;
        }

        return new float[] { nx, ny, nz };
    }
}
