import { Vector3 } from "three";

export default function closestPointOnLineSegment(p: Vector3, a: Vector3, b: Vector3) {
    const ab = new Vector3().subVectors(b, a);
    const ap = new Vector3().subVectors(p, a);

    const abLengthSq = ab.lengthSq();
    const dot = ap.dot(ab);
    const t = Math.max(0, Math.min(1, dot / abLengthSq));

    return new Vector3().copy(a).add(ab.multiplyScalar(t));
}