import {
    compute_triangle_group_aabb3
} from "../../../engine/graphics/sh3/path_tracer/geometry/compute_triangle_group_aabb3.js";
import { min2 } from "../../math/min2.js";

/**
 * Build the BVH by relying on BVH's own incremental insertion mechanism
 * @param {BVH} bvh
 * @param {number[]|Float32Array} index_array
 * @param {number[]|Float32Array} positions_array
 * @param {number} [batch_size] can batch triangles in groups of up-to this many triangles per BVH leaf
 */
export function ebvh_build_for_geometry_incremental(
    bvh,
    index_array, positions_array,
    batch_size = 1
) {

    bvh.release_all();
    const triangle_count = index_array.length / 3;

    const leaf_node_count = Math.ceil(triangle_count / batch_size);

    const leaf_aabb = [];

    for (let i = 0; i < leaf_node_count; i++) {

        const index_start = i * batch_size;
        const index_end = min2(triangle_count, index_start + batch_size);

        const group_size = index_end - index_start;

        compute_triangle_group_aabb3(leaf_aabb, 0, index_array, positions_array, index_start * 3, group_size, 3);

        const node_index = bvh.allocate_node();
        bvh.node_set_aabb(node_index, leaf_aabb);
        bvh.node_set_user_data(node_index, i);

        bvh.insert_leaf(node_index);
    }
}
