import { assert } from "../../../../assert.js";
import { ELEMENT_WORD_COUNT } from "../../../../bvh2/bvh3/BVH.js";
import { tetrahedral_mesh_compute_tet_aabb3 } from "../tetrahedral_mesh_compute_tet_aabb3.js";

/**
 *
 * @param {BVH} bvh
 * @param {TetrahedralMesh} mesh
 * @param {number[]} positions
 */
export function tetrahedral_mesh_to_bvh(bvh, mesh, positions) {
    assert.defined(bvh, 'bvh');

    assert.defined(mesh, 'mesh');

    assert.defined(positions, 'positions');
    assert.isArrayLike(positions, 'positions');


    const count = mesh.count;

    bvh.release_all();
    bvh.node_capacity = Math.max(0, count * 2 - 1);

    const float32 = bvh.data_float32;

    for (let tet_index = 0; tet_index < count; tet_index++) {

        const node_id = bvh.allocate_node();

        const address = node_id * ELEMENT_WORD_COUNT

        tetrahedral_mesh_compute_tet_aabb3(
            float32, address,
            mesh, tet_index, positions
        );

        bvh.node_set_user_data(node_id, tet_index);

        bvh.insert_leaf(node_id);

    }

}