import { aabb3_array_combine } from "../../../core/geom/3d/aabb/aabb3_array_combine.js";
import { aabb3_from_threejs_geometry } from "../../../core/geom/3d/aabb/aabb3_from_threejs_geometry.js";
import { aabb3_matrix4_project } from "../../../core/geom/3d/aabb/aabb3_matrix4_project.js";
import { m4_multiply } from "../../../core/geom/3d/mat4/m4_multiply.js";
import { ensureGeometryBoundingBox } from "../util/ensureGeometryBoundingBox.js";

const scratch_aabb3_array_0 = new Float32Array(6);
const scratch_aabb3_array_1 = new Float32Array(6);

/**
 *
 * @param {number[]|Float32Array} result
 * @param {Object3D} object
 * @param {number[]|Float32Array} transform 4x4 transform matrix to be used as a root transform instead of whatever is set on the object, this lets us compute local-space bounds without having to modify the source object
 */
export function expand_aabb_by_transformed_three_object(result, object, transform) {

    /**
     * @type {BufferGeometry}
     */
    const geometry = object.geometry;

    if (geometry !== undefined) {

        ensureGeometryBoundingBox(geometry);
        aabb3_from_threejs_geometry(scratch_aabb3_array_0,geometry);

        aabb3_matrix4_project(scratch_aabb3_array_1, scratch_aabb3_array_0, transform);

        aabb3_array_combine(result,0, result,0, scratch_aabb3_array_1,0);
    }

    const children = object.children;
    const child_count = children.length;

    for (let i = 0; i < child_count; i++) {
        const child_matrix = new Float32Array(16);

        const child = children[i];

        m4_multiply(child_matrix, transform, child.matrix.elements)

        expand_aabb_by_transformed_three_object(result, child, child_matrix);
    }

}
