import { v3_length } from "../../../../../core/geom/vec3/v3_length.js";

/**
 * Build orthonormal matrix from direction vector
 * @param {number[]} out
 * @param {number} out_offset
 * @param {number} dir_x
 * @param {number} dir_y
 * @param {number} dir_z
 */
export function v3_orthonormal_matrix_from_normal(out, out_offset, dir_x, dir_y, dir_z) {
    // we build orthonormal vectors with respect to the direction vector
    let o1_x, o1_y, o1_z;

    if (Math.abs(dir_x) > Math.abs(dir_z)) {
        o1_x = -dir_y;
        o1_y = dir_x;
        o1_z = 0;
    } else {
        o1_x = 0;
        o1_y = -dir_z;
        o1_z = dir_y;
    }

    // normalize orthonormal vector
    const o1_norm = 1 / v3_length(o1_x, o1_y, o1_z);

    o1_x *= o1_norm;
    o1_y *= o1_norm;
    o1_z *= o1_norm;

    const o2_x = dir_y * o1_z - dir_z * o1_y;
    const o2_y = dir_z * o1_x - dir_x * o1_z;
    const o2_z = dir_x * o1_y - dir_y * o1_x;

    out[out_offset] = o1_x;
    out[out_offset + 1] = o1_y;
    out[out_offset + 2] = o1_z;

    out[out_offset + 3] = o2_x;
    out[out_offset + 4] = o2_y;
    out[out_offset + 5] = o2_z;

    out[out_offset + 6] = dir_x;
    out[out_offset + 7] = dir_y;
    out[out_offset + 8] = dir_z;
}