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

/**
 *
 * @param {Vector3} result
 * @param {number} origin_x
 * @param {number} origin_y
 * @param {number} origin_z
 * @param {number} direction_x
 * @param {number} direction_y
 * @param {number} direction_z
 * @param {number} px
 * @param {number} py
 * @param {number} pz
 * @returns {number} distance from origin, negative means that the point lies behind the origin in the direction opposite to the ray's own
 */
export function ray3_compute_nearest_point_to_point(
    result,
    origin_x, origin_y, origin_z,
    direction_x, direction_y, direction_z,
    px, py, pz
) {

    // find the closest point
    const sp0_x = px - origin_x;
    const sp0_y = py - origin_y;
    const sp0_z = pz - origin_z;

    //
    const d2 = v3_dot(direction_x, direction_y, direction_z, direction_x, direction_y, direction_z);
    const d3 = v3_dot(direction_x, direction_y, direction_z, sp0_x, sp0_y, sp0_z);

    const t = d3 / d2;

    // compute point on the ray
    const lp_x = direction_x * t + origin_x;
    const lp_y = direction_y * t + origin_y;
    const lp_z = direction_z * t + origin_z;

    result.set(lp_x, lp_y, lp_z);

    return t;
}
