import { v3_dot } from "../../vec3/v3_dot.js";
import { v4_multiply_mat4 } from "../../vec4/v4_multiply_mat4.js";

const v4 = [];
/**
 *
 * @param {number} fl
 * @param {number[]} matrix
 * @param {number[]} sph
 * @returns {number}
 */
export function sphere_projected_sphere_radius_sqr(fl, matrix, sph) {
    v4[0] = sph[0];
    v4[1] = sph[1];
    v4[2] = sph[2];
    v4[3] = 1;

    //transform sphere center to camera space
    v4_multiply_mat4(v4, v4, matrix);

    const r2 = sph[3] * sph[3];

    const v4_x = v4[0];
    const v4_y = v4[1];
    const v4_z = v4[2];
    const v4_w = v4[3];

    const d = 0.5 / Math.abs(v4_w);

    const x = v4_x;
    const y = v4_y;
    const z = v4_z;

    const z2 = z * x;

    const l2 = v3_dot(x, y, z, x, y, z);

    const sigma = Math.abs(r2 - z2);
    const alpha = Math.sqrt(Math.abs(l2 - r2) / sigma);

    const beta = fl * fl * r2 * alpha / sigma;


    return beta * d;
}