import { max2 } from "../../../math/max2.js";

/**
 * Compute squared distance to point, value is negative if the point is inside the box
 * @param {number} x0
 * @param {number} y0
 * @param {number} z0
 * @param {number} x1
 * @param {number} y1
 * @param {number} z1
 * @param {number} point_x
 * @param {number} point_y
 * @param {number} point_z
 * @returns {number}
 */
export function aabb3_signed_distance_sqr_to_point(
    x0, y0, z0,
    x1, y1, z1,
    point_x, point_y, point_z
) {
    //do projection
    const xp0 = x0 - point_x;
    const xp1 = point_x - x1;
    const yp0 = y0 - point_y;
    const yp1 = point_y - y1;
    const zp0 = z0 - point_z;
    const zp1 = point_z - z1;

    //calculate separation in each axis
    let dx = max2(xp0, xp1);
    let dy = max2(yp0, yp1);
    let dz = max2(zp0, zp1);

    const max_dist = Math.max(dx, dy, dz);

    if (max_dist > 0) {
        // non-penetrating, clamp axis
        dx = max2(dx, 0);
        dy = max2(dy, 0);
        dz = max2(dz, 0);

        // straight-line distance
        return dx * dx + dy * dy + dz * dz;
    } else {

        // penetration, negative distance
        return -(max_dist * max_dist);
    }
}

