import { v3_length_sqr } from "../../vec3/v3_length_sqr.js";

/**
 * Compute face normal for a triangle
 * @param {number[]|Float32Array|Float64Array} result X,Y,Z normalized vector is written here
 * @param {number} result_offset offset into result array where to start writing
 * @param {number} a_x
 * @param {number} a_y
 * @param {number} a_z
 * @param {number} b_x
 * @param {number} b_y
 * @param {number} b_z
 * @param {number} c_x
 * @param {number} c_y
 * @param {number} c_z
 */
export function v3_compute_triangle_normal(
    result, result_offset,
    a_x, a_y, a_z,
    b_x, b_y, b_z,
    c_x, c_y, c_z
) {

    //compute CB and AB vectors
    const vCBx = c_x - b_x;
    const vCBy = c_y - b_y;
    const vCBz = c_z - b_z;

    const vABx = a_x - b_x;
    const vABy = a_y - b_y;
    const vABz = a_z - b_z;

    //compute triangle normal
    const crossX = vCBy * vABz - vCBz * vABy;
    const crossY = vCBz * vABx - vCBx * vABz;
    const crossZ = vCBx * vABy - vCBy * vABx;

    const l_sqr = v3_length_sqr(crossX, crossY, crossZ);

    if (l_sqr === 0) {
        // degenerate triangle, provide arbitrary invalid result
        result[result_offset] = 0;
        result[result_offset + 1] = 1;
        result[result_offset + 2] = 0;
        return;
    }

    const l_inv = 1 / Math.sqrt(l_sqr);

    const x = crossX * l_inv;
    const y = crossY * l_inv;
    const z = crossZ * l_inv;

    result[result_offset] = x;
    result[result_offset + 1] = y;
    result[result_offset + 2] = z;
}