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

/**
 * Computes parameter t for the nearest point on the line segment to the given point.
 *
 * t is clamped to [0, 1] and represents position along the line segment from v0 to v1.
 *
 * @param {number} x0
 * @param {number} y0
 * @param {number} z0
 * @param {number} x1
 * @param {number} y1
 * @param {number} z1
 * @param {number} px
 * @param {number} py
 * @param {number} pz
 * @returns {number}
 * @see line3_compute_segment_point_distance_sqr
 */
export function line3_compute_segment_nearest_point_to_point_t(
    x0, y0, z0,
    x1, y1, z1,
    px, py, pz
) {
    // get line delta
    const line_delta_x = x1 - x0;
    const line_delta_y = y1 - y0;
    const line_delta_z = z1 - z0;

    // find closest point
    const sp0_x = px - x0;
    const sp0_y = py - y0;
    const sp0_z = pz - z0;

    //
    const d2 = line_delta_x * line_delta_x + line_delta_y * line_delta_y + line_delta_z * line_delta_z;

    if (d2 === 0) {
        // line is a point
        return 0;
    }

    const d3 = line_delta_x * sp0_x + line_delta_y * sp0_y + line_delta_z * sp0_z;

    const t = clamp01(d3 / d2);

    return t;
}