/*=========================================================================

   Library: iMSTK

   Copyright (c) Kitware, Inc. & Center for Modeling, Simulation,
   & Imaging in Medicine, Rensselaer Polytechnic Institute.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

=========================================================================*/

#include "PxPhysicsAPI.h"

#include <iostream>

#include "../snippets/snippetcommon/SnippetPrint.h"
#include "../snippets/snippetcommon/SnippetPVD.h"
#include "../snippets/snippetutils/SnippetUtils.h"

///
/// \brief This example demonstrates building and linking against PhysX.
///
class DumbErrorCallbakck: public physx::PxErrorCallback
{
public:
  virtual void reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line)
  {
    std::cout << "Message of type " << code
      << " in " << file
      << " @ line " << line
      << ": " << message
      << std::endl;
  }
};

using namespace physx;

PxDefaultAllocator		gAllocator;
PxDefaultErrorCallback	gErrorCallback;

PxFoundation*			gFoundation = NULL;
PxPhysics*				gPhysics = NULL;

PxDefaultCpuDispatcher*	gDispatcher = NULL;
PxScene*				gScene = NULL;

PxMaterial*				gMaterial = NULL;

PxPvd*                  gPvd = NULL;

PxReal chainZ = 10.0f;

PxRigidDynamic* actor1 = NULL;
PxRigidDynamic* actor2 = NULL;

unsigned int count = 0;

PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity = PxVec3(0))
{
    PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f);
    dynamic->setAngularDamping(0.5f);
    dynamic->setLinearVelocity(velocity);
    gScene->addActor(*dynamic);
    return dynamic;
}

// D6 joint with a spring maintaining its position
PxJoint* createDampedD6(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1)
{
    PxD6Joint* j = PxD6JointCreate(*gPhysics, a0, t0, a1, t1);
    j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE);
    j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE);
    j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE);
    j->setDrive(PxD6Drive::eSLERP, PxD6JointDrive(1000, 8000.00, FLT_MAX, true));
    return j;
}

typedef PxJoint* (*JointCreateFunction)(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1);

// create a chain rooted at the origin and extending along the x-axis, all transformed by the argument t.

void createChain(const PxTransform& t, PxU32 length, const PxGeometry& g, PxReal separation, JointCreateFunction createJoint)
{
    PxVec3 offset(0, separation / 2, 0);
    PxTransform localTm(offset);
    PxRigidDynamic* prev = NULL;

    for (PxU32 i = 0; i < length; i++)
    {
        PxRigidDynamic* current = PxCreateDynamic(*gPhysics, t*localTm, g, *gMaterial, 1.0f);
        (*createJoint)(prev, prev ? PxTransform(offset) : t, current, PxTransform(-offset));
        gScene->addActor(*current);
        prev = current;
        localTm.p.y += separation;

        if (i == 4)
        {
            actor1 = current;
        }
        if (i == 11)
        {
            actor2 = current;
        }
    }
    (*createJoint)(prev, PxTransform(offset), NULL, t*PxTransform(PxVec3(0.0f, separation*length, 0.0f)));
}

void initPhysics(bool /*interactive*/)
{
    gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback);
    gPvd = PxCreatePvd(*gFoundation);
    PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10);
    gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL);

    gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd);
    PxInitExtensions(*gPhysics, gPvd);

    PxSceneDesc sceneDesc(gPhysics->getTolerancesScale());
    sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f);
    gDispatcher = PxDefaultCpuDispatcherCreate(2);
    sceneDesc.cpuDispatcher = gDispatcher;
    sceneDesc.filterShader = PxDefaultSimulationFilterShader;
    gScene = gPhysics->createScene(sceneDesc);

    PxPvdSceneClient* pvdClient = gScene->getScenePvdClient();
    if (pvdClient)
    {
        pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true);
        pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true);
        pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true);
    }

    gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f);

    PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial);
    gScene->addActor(*groundPlane);

    //createChain(PxTransform(PxVec3(0.0f, 20.0f, 0.0f)), 15, PxBoxGeometry(2.0f, 0.15f, 0.15f), 4.0f, createLimitedSpherical);
    //createChain(PxTransform(PxVec3(0.0f, 20.0f, -10.0f)), 15, PxBoxGeometry(2.0f, 0.5f, 0.5f), 4.0f, createBreakableFixed);
    createChain(PxTransform(PxVec3(0.0f, 20.0f, -20.0f)), 15, PxBoxGeometry(1.5f, 1.8f, 1.5f), 4.0f, createDampedD6);
}

void stepPhysics(bool /*interactive*/)
{
    // apply force
    if (count > 30000 && count < 50000)
    {
        actor1->addForce(PxVec3(0.0f, 0.0f, -2.5e6f*(20000 - 50000 + count) / 20000), PxForceMode::eFORCE, true);
        actor2->addForce(PxVec3(0.0f, 0.0f, 2.5e6f*(20000 - 50000 + count) / 20000), PxForceMode::eFORCE, true);
    }
    count++;

    if (count > 50000)
    {
        count = 0;
    }

    gScene->simulate(1.0f / 400.0f);
    gScene->fetchResults(true);

    std::cout << count << std::endl;
}

void cleanupPhysics(bool /*interactive*/)
{
    PX_RELEASE(gScene);
    PX_RELEASE(gDispatcher);
    PxCloseExtensions();
    PX_RELEASE(gPhysics);
    if (gPvd)
    {
        PxPvdTransport* transport = gPvd->getTransport();
        gPvd->release();	gPvd = NULL;
        PX_RELEASE(transport);
    }
    PX_RELEASE(gFoundation);

    printf("SnippetJoint done.\n");
}

void keyPress(unsigned char key, const PxTransform& camera)
{
    switch (toupper(key))
    {
    case ' ':
        createDynamic(camera, PxSphereGeometry(6.0f), camera.rotate(PxVec3(0, 0, -1)) * 200);
        break;
    }
}

int snippetMain(int, const char*const*)
{
    static const PxU32 frameCount = 100;
    initPhysics(false);
    for (PxU32 i = 0; i < frameCount; i++)
        stepPhysics(false);
    cleanupPhysics(false);

    return 0;
}

int main(int argc, char** argv)
{
    DumbErrorCallbakck().reportError(
      physx::PxErrorCode::eNO_ERROR, "Hello world!", __FILE__, __LINE__);
    getchar();

    return snippetMain(argc, argv);
}
