import { ELEMENT_WORD_COUNT } from "../../../../../core/bvh2/bvh3/BVH.js";
import { array_sort_quick } from "../../../../../core/collection/array/array_sort_quick.js";
import {
    aabb3_unsigned_distance_sqr_to_point
} from "../../../../../core/geom/3d/aabb/aabb3_unsigned_distance_sqr_to_point.js";

/**
 *
 * @param {BVH} bvh
 * @param {number[]|Uint32Array} node_list
 * @param {number} node_list_offset
 * @param {number} node_list_size
 * @param {number} ref_x
 * @param {number} ref_y
 * @param {number} ref_z
 */
export function sort_bvh_nodes_by_distance_to_point(
    bvh,
    node_list, node_list_offset, node_list_size,
    ref_x, ref_y, ref_z
) {
    if (node_list_size <= 1) {
        // no sort necessary
        return;
    }

    /*
     For performance, we bind data directly to avoid extra copies required to read out AABB
     */
    const float32 = bvh.__data_float32;
    array_sort_quick(node_list, (node) => {
            const address = node * ELEMENT_WORD_COUNT;

            const aabb_distance_sqr = aabb3_unsigned_distance_sqr_to_point(
                float32[address], float32[address + 1], float32[address + 2],
                float32[address + 3], float32[address + 4], float32[address + 5],
                ref_x, ref_y, ref_z
            );

            return aabb_distance_sqr;
        },
        null,
        node_list_offset, node_list_offset + node_list_size - 1
    );

}