import { Mesh } from "three";
import { computeSkinnedMeshVertices } from "./computeSkinnedMeshVertices.js";

/**
 * Rebuild skinned mesh as a regular mesh applying skinning in the process
 * @param {SkinnedMesh} skinned
 * @returns {Mesh}
 */
export function meshFromSkinnedMesh(skinned) {

    const geometry = skinned.geometry;

    const bakedGeometry = geometry.clone();

    delete bakedGeometry.attributes.skinIndex;
    delete bakedGeometry.attributes.skinWeight;

    const positionAttribute = bakedGeometry.getAttribute("position");
    const vertices = positionAttribute.array;

    computeSkinnedMeshVertices(vertices, skinned);

    const mesh = new Mesh(bakedGeometry, skinned.material);

    mesh.position.copy(skinned.position);
    mesh.rotation.copy(skinned.rotation);
    mesh.scale.copy(skinned.scale);

    //apply transform to each vertex
    skinned.updateMatrix();
    skinned.updateMatrixWorld(true);

    const m4 = skinned.matrixWorld.clone();
    m4.invert();

    positionAttribute.applyMatrix4(m4);

    return mesh;
}