#include "meshnode.h"
#include "SparrowRenderer/mesh.h"
#include "scenetree.h"
#include <glm/ext.hpp>

#include <btBulletCollisionCommon.h>
#include <btBulletDynamicsCommon.h>

void MeshNode::setSceneTree(SceneTree *tree)
{
    GraphicalNode::setSceneTree(tree);
    if(m_scene != nullptr)
        m_scene->registerMeshType(m_geometry.mesh->getFlags());
}

void MeshNode::setDepth(float depth){
    m_geometry.mesh->setDepth(depth);
}

void MeshNode::update()
{
    if(m_transformChanged)
        m_geometry.modelMatrix = m_parentTransform * m_transform;
}

btRigidBody* MeshNode::buildStaticCollider()
{
    btIndexedMesh *bulletMesh = new btIndexedMesh();
    Mesh *m = m_geometry.mesh;
    // vertices
    bulletMesh->m_numVertices = m->positions3D.size();
    bulletMesh->m_vertexBase = (unsigned char*)(m->positions3D.data());
    bulletMesh->m_vertexStride = sizeof(glm::vec3);
    bulletMesh->m_vertexType = PHY_FLOAT;
    // indices
    bulletMesh->m_numTriangles = m->indices.size()/3;
    bulletMesh->m_triangleIndexBase = (unsigned char*)(m->indices.data());
    bulletMesh->m_triangleIndexStride = 3*sizeof(GLuint);
    bulletMesh->m_indexType = PHY_INTEGER;

    // building bullet rigidbody
    btTriangleIndexVertexArray* indexArray = new btTriangleIndexVertexArray();
    indexArray->addIndexedMesh(*bulletMesh, PHY_INTEGER);
    btBvhTriangleMeshShape *shape = new btBvhTriangleMeshShape(indexArray, true);
    shape->setLocalScaling(btVector3(m_transform[0].x, m_transform[1].y, m_transform[2].z));

    btTransform transform;
    transform.setIdentity();
    transform.setOrigin(btVector3(m_transform[3].x, m_transform[3].y, m_transform[3].z));
    // IMPORTANT ! collisions on static meshes does not work if the transform is modified after the rigidbody construction
    m_rigidBody = new btRigidBody(0., nullptr, shape);
    m_rigidBody->setWorldTransform(transform);
    return m_rigidBody;
}
