import { detailed_sphere_frustum_intersection_test } from "./detailed_sphere_frustum_intersection_test.js";

/**
 *
 * @param {number} light_x
 * @param {number} light_y
 * @param {number} light_z
 * @param {number} radius
 * @param {number[]|Float32Array} points
 * @param {number[]|Float32Array|Float64Array} planes
 * @returns {boolean}
 */
export function point_light_inside_volume(
    light_x, light_y, light_z, radius,
    points, planes
) {
    let j = 0;
    let outside_plane_count = 0;
    let outside_plane_bitfield = 0;

    // validate if the sphere intersects the plane-bound space

    // query_bvh_frustum_from_objects.checks_sphere++;

    for (; j < 6; j++) {

        const plane_address = j * 4;

        const plane_normal_x = planes[plane_address];
        const plane_normal_y = planes[plane_address + 1];
        const plane_normal_z = planes[plane_address + 2];
        const plane_constant = planes[plane_address + 3];

        /*
         compute distance from the center of the sphere to the plane
         NOTE: inlined computation of distance from point to plane
         */
        const distance = (plane_normal_x * light_x + plane_normal_y * light_y + plane_normal_z * light_z) + plane_constant;

        // query_bvh_frustum_from_objects.checks_sphere_plane++;

        if (distance < 0) {
            // center of the sphere is below the plane

            if (distance >= -radius) {

                // sphere intersects the plane

                outside_plane_count++;

                const plane_bit_mask = 1 << j;

                outside_plane_bitfield |= plane_bit_mask;
            } else {
                // sphere is entirely below the plane

                // query_bvh_frustum_from_objects.rejection_sphere_count++;

                return false;
            }
        }

    }

    if (outside_plane_count < 2) {
        return true;
    } else {
        return detailed_sphere_frustum_intersection_test(
            radius, light_x, light_y, light_z,
            outside_plane_count, outside_plane_bitfield,
            points
        );
    }
}
