#include "coduo_x87emu.h" /* defines EMULATE_X87; x87 shim when it is 1 */

#include "core_math_private.h"

long double DistanceSquared(const vec3_t left, const vec3_t right)
{
#if EMULATE_X87
    /* x87-faithful transcription (stock coduo_lnxded 0x080665e0): each delta
     * right[i]-left[i] is rounded to a float slot (fstps), squared in 80-bit
     * (fld d; fmul d), and the three squares summed left-to-right in 80-bit
     * (faddp). Stock leaves the unrounded 80-bit sum in st0; every caller rounds
     * it to float the instant the call returns (cm_patch_grid_helpers
     * 0x0805449e/0x080544da: call, then fstp DWORD, then fucompp two floats), so
     * rounding to float here reproduces stock's single 80->float rounding and
     * avoids an arm64 80->64->float double round. The x86 #else path keeps the
     * raw 80-bit st0 return, matching stock exactly; the two builds therefore
     * differ only below the caller's float projection. */
    const float deltaX =
        x87f_store_f32(x87f_sub(x87f_load_f32(right[0]), x87f_load_f32(left[0])));
    const float deltaY =
        x87f_store_f32(x87f_sub(x87f_load_f32(right[1]), x87f_load_f32(left[1])));
    const float deltaZ =
        x87f_store_f32(x87f_sub(x87f_load_f32(right[2]), x87f_load_f32(left[2])));
    x87f sum = x87f_mul(x87f_load_f32(deltaX), x87f_load_f32(deltaX));
    sum = x87f_add(sum, x87f_mul(x87f_load_f32(deltaY), x87f_load_f32(deltaY)));
    sum = x87f_add(sum, x87f_mul(x87f_load_f32(deltaZ), x87f_load_f32(deltaZ)));
    return (long double)x87f_store_f32(sum);
#else
    const float deltaX = right[0] - left[0];
    const float deltaY = right[1] - left[1];
    const float deltaZ = right[2] - left[2];

    return ((long double)deltaX * (long double)deltaX) +
           ((long double)deltaY * (long double)deltaY) +
           ((long double)deltaZ * (long double)deltaZ);
#endif
}
