Add the collision shapes example

This commit is contained in:
Daniel Chappuis 2013-09-10 21:35:56 +02:00
parent 07df001e8b
commit 4bd228e8c0
7 changed files with 1122 additions and 0 deletions

View File

@ -0,0 +1,20 @@
# Minimum cmake version required
cmake_minimum_required(VERSION 2.6)
# Project configuration
PROJECT(CollisionShapes)
# Copy the shaders used for the demo into the build directory
FILE(COPY "../common/opengl-framework/src/shaders/" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/shaders/")
# Copy the meshes used for the demo into the build directory
FILE(COPY "../common/meshes/" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/meshes/")
# Headers
INCLUDE_DIRECTORIES("../common/opengl-framework/src/" "../common/")
# Create the example executable using the
# compiled reactphysics3d static library
ADD_EXECUTABLE(collisionshapes CollisionShapes.cpp Scene.cpp Scene.h "../common/VisualContactPoint.cpp" "../common/ConvexMesh.cpp" "../common/Capsule.cpp" "../common/Sphere.cpp" "../common/Cylinder.cpp" "../common/Cone.cpp" "../common/Box.cpp" "../common/Viewer.cpp")
TARGET_LINK_LIBRARIES(collisionshapes reactphysics3d openglframework)

View File

@ -0,0 +1,152 @@
/********************************************************************************
* ReactPhysics3D physics library, http://code.google.com/p/reactphysics3d/ *
* Copyright (c) 2010-2013 Daniel Chappuis *
*********************************************************************************
* *
* This software is provided 'as-is', without any express or implied warranty. *
* In no event will the authors be held liable for any damages arising from the *
* use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not claim *
* that you wrote the original software. If you use this software in a *
* product, an acknowledgment in the product documentation would be *
* appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source distribution. *
* *
********************************************************************************/
// Libraries
#include "Scene.h"
#include "Viewer.h"
// Declarations
void simulate();
void display();
void finish();
void reshape(int width, int height);
void mouseButton(int button, int state, int x, int y);
void mouseMotion(int x, int y);
void keyboard(unsigned char key, int x, int y);
void init();
// Namespaces
using namespace openglframework;
// Global variables
Viewer* viewer;
Scene* scene;
// Main function
int main(int argc, char** argv) {
// Create and initialize the Viewer
viewer = new Viewer();
Vector2 windowsSize = Vector2(800, 600);
Vector2 windowsPosition = Vector2(100, 100);
bool initOK = viewer->init(argc, argv, "ReactPhysics3D Examples - Collision Shapes",
windowsSize, windowsPosition);
if (!initOK) return 1;
// Create the scene
scene = new Scene(viewer);
init();
// Glut Idle function that is continuously called
glutIdleFunc(simulate);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouseButton);
glutMotionFunc(mouseMotion);
glutKeyboardFunc(keyboard);
glutCloseFunc(finish);
// Glut main looop
glutMainLoop();
return 0;
}
// Simulate function
void simulate() {
// Physics simulation
scene->simulate();
viewer->computeFPS();
// Ask GLUT to render the scene
glutPostRedisplay ();
}
// Initialization
void init() {
// Define the background color (black)
glClearColor(0.0, 0.0, 0.0, 1.0);
}
// Reshape function
void reshape(int newWidth, int newHeight) {
viewer->reshape(newWidth, newHeight);
}
// Called when a mouse button event occurs
void mouseButton(int button, int state, int x, int y) {
viewer->mouseButtonEvent(button, state, x, y);
}
// Called when a mouse motion event occurs
void mouseMotion(int x, int y) {
viewer->mouseMotionEvent(x, y);
}
// Called when the user hits a special key on the keyboard
void keyboard(unsigned char key, int x, int y) {
switch(key) {
// Escape key
case 27:
glutLeaveMainLoop();
break;
// Space bar
case 32:
scene->pauseContinueSimulation();
break;
}
}
// End of the application
void finish() {
// Destroy the viewer and the scene
delete viewer;
delete scene;
}
// Display the scene
void display() {
// Render the scene
scene->render();
// Display the FPS
viewer->displayGUI();
// Swap the buffers
glutSwapBuffers();
// Check the OpenGL errors
GlutViewer::checkOpenGLErrors();
}

View File

@ -0,0 +1,451 @@
/********************************************************************************
* ReactPhysics3D physics library, http://code.google.com/p/reactphysics3d/ *
* Copyright (c) 2010-2013 Daniel Chappuis *
*********************************************************************************
* *
* This software is provided 'as-is', without any express or implied warranty. *
* In no event will the authors be held liable for any damages arising from the *
* use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not claim *
* that you wrote the original software. If you use this software in a *
* product, an acknowledgment in the product documentation would be *
* appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source distribution. *
* *
********************************************************************************/
// Libraries
#include "Scene.h"
// Namespaces
using namespace openglframework;
// Constructor
Scene::Scene(GlutViewer* viewer) : mViewer(viewer), mLight0(0),
mPhongShader("shaders/phong.vert",
"shaders/phong.frag"), mIsRunning(false) {
// Move the light 0
mLight0.translateWorld(Vector3(50, 50, 50));
// Compute the radius and the center of the scene
float radiusScene = 10.0f;
openglframework::Vector3 center(0, 5, 0);
// Set the center of the scene
mViewer->setScenePosition(center, radiusScene);
// Gravity vector in the dynamics world
rp3d::Vector3 gravity(0, rp3d::decimal(-9.81), 0);
// Time step for the physics simulation
rp3d::decimal timeStep = 1.0f / 60.0f;
// Create the dynamics world for the physics simulation
mDynamicsWorld = new rp3d::DynamicsWorld(gravity, timeStep);
// Set the number of iterations of the constraint solver
mDynamicsWorld->setNbIterationsVelocitySolver(15);
// Create the static data for the visual contact points
VisualContactPoint::createStaticData();
float radius = 3.0f;
// Create all the boxes of the scene
for (int i=0; i<NB_BOXES; i++) {
// Position
float angle = i * 30.0f;
openglframework::Vector3 position(radius * cos(angle),
60 + i * (BOX_SIZE.y + 0.8f),
radius * sin(angle));
// Create a sphere and a corresponding rigid in the dynamics world
Box* box = new Box(BOX_SIZE, position , BOX_MASS, mDynamicsWorld);
// The sphere is a moving rigid body
box->getRigidBody()->setIsMotionEnabled(true);
// Change the material properties of the rigid body
rp3d::Material& material = box->getRigidBody()->getMaterial();
material.setBounciness(rp3d::decimal(0.2));
// Add the sphere the list of sphere in the scene
mBoxes.push_back(box);
}
// Create all the spheres of the scene
for (int i=0; i<NB_SPHERES; i++) {
// Position
float angle = i * 35.0f;
openglframework::Vector3 position(radius * cos(angle),
50 + i * (SPHERE_RADIUS + 0.8f),
radius * sin(angle));
// Create a sphere and a corresponding rigid in the dynamics world
Sphere* sphere = new Sphere(SPHERE_RADIUS, position , BOX_MASS, mDynamicsWorld);
// The sphere is a moving rigid body
sphere->getRigidBody()->setIsMotionEnabled(true);
// Change the material properties of the rigid body
rp3d::Material& material = sphere->getRigidBody()->getMaterial();
material.setBounciness(rp3d::decimal(0.2));
// Add the sphere the list of sphere in the scene
mSpheres.push_back(sphere);
}
// Create all the cones of the scene
for (int i=0; i<NB_CONES; i++) {
// Position
float angle = i * 50.0f;
openglframework::Vector3 position(radius * cos(angle),
35 + i * (CONE_HEIGHT + 0.3f),
radius * sin(angle));
// Create a cone and a corresponding rigid in the dynamics world
Cone* cone = new Cone(CONE_RADIUS, CONE_HEIGHT, position , CONE_MASS, mDynamicsWorld);
// The cone is a moving rigid body
cone->getRigidBody()->setIsMotionEnabled(true);
// Change the material properties of the rigid body
rp3d::Material& material = cone->getRigidBody()->getMaterial();
material.setBounciness(rp3d::decimal(0.2));
// Add the cone the list of sphere in the scene
mCones.push_back(cone);
}
// Create all the cylinders of the scene
for (int i=0; i<NB_CYLINDERS; i++) {
// Position
float angle = i * 35.0f;
openglframework::Vector3 position(radius * cos(angle),
25 + i * (CYLINDER_HEIGHT + 0.3f),
radius * sin(angle));
// Create a cylinder and a corresponding rigid in the dynamics world
Cylinder* cylinder = new Cylinder(CYLINDER_RADIUS, CYLINDER_HEIGHT, position ,
CYLINDER_MASS, mDynamicsWorld);
// The cylinder is a moving rigid body
cylinder->getRigidBody()->setIsMotionEnabled(true);
// Change the material properties of the rigid body
rp3d::Material& material = cylinder->getRigidBody()->getMaterial();
material.setBounciness(rp3d::decimal(0.2));
// Add the cylinder the list of sphere in the scene
mCylinders.push_back(cylinder);
}
// Create all the capsules of the scene
for (int i=0; i<NB_CAPSULES; i++) {
// Position
float angle = i * 45.0f;
openglframework::Vector3 position(radius * cos(angle),
15 + i * (CAPSULE_HEIGHT + 0.3f),
radius * sin(angle));
// Create a cylinder and a corresponding rigid in the dynamics world
Capsule* capsule = new Capsule(CAPSULE_RADIUS, CAPSULE_HEIGHT, position ,
CAPSULE_MASS, mDynamicsWorld);
// The cylinder is a moving rigid body
capsule->getRigidBody()->setIsMotionEnabled(true);
// Change the material properties of the rigid body
rp3d::Material& material = capsule->getRigidBody()->getMaterial();
material.setBounciness(rp3d::decimal(0.2));
// Add the cylinder the list of sphere in the scene
mCapsules.push_back(capsule);
}
// Create all the convex meshes of the scene
for (int i=0; i<NB_MESHES; i++) {
// Position
float angle = i * 30.0f;
openglframework::Vector3 position(radius * cos(angle),
5 + i * (CAPSULE_HEIGHT + 0.3f),
radius * sin(angle));
// Create a convex mesh and a corresponding rigid in the dynamics world
ConvexMesh* mesh = new ConvexMesh(position, MESH_MASS, mDynamicsWorld);
// The mesh is a moving rigid body
mesh->getRigidBody()->setIsMotionEnabled(true);
// Change the material properties of the rigid body
rp3d::Material& material = mesh->getRigidBody()->getMaterial();
material.setBounciness(rp3d::decimal(0.2));
// Add the mesh the list of sphere in the scene
mConvexMeshes.push_back(mesh);
}
// Create the floor
openglframework::Vector3 floorPosition(0, 0, 0);
mFloor = new Box(FLOOR_SIZE, floorPosition, FLOOR_MASS, mDynamicsWorld);
// The floor must be a non-moving rigid body
mFloor->getRigidBody()->setIsMotionEnabled(false);
// Change the material properties of the rigid body
rp3d::Material& material = mFloor->getRigidBody()->getMaterial();
material.setBounciness(rp3d::decimal(0.2));
// Start the simulation
startSimulation();
}
// Destructor
Scene::~Scene() {
// Stop the physics simulation
stopSimulation();
// Destroy the shader
mPhongShader.destroy();
// Destroy all the boxes of the scene
for (std::vector<Box*>::iterator it = mBoxes.begin(); it != mBoxes.end(); ++it) {
// Destroy the corresponding rigid body from the dynamics world
mDynamicsWorld->destroyRigidBody((*it)->getRigidBody());
// Destroy the box
delete (*it);
}
// Destroy all the sphere of the scene
for (std::vector<Sphere*>::iterator it = mSpheres.begin(); it != mSpheres.end(); ++it) {
// Destroy the corresponding rigid body from the dynamics world
mDynamicsWorld->destroyRigidBody((*it)->getRigidBody());
// Destroy the sphere
delete (*it);
}
// Destroy all the cones of the scene
for (std::vector<Cone*>::iterator it = mCones.begin(); it != mCones.end(); ++it) {
// Destroy the corresponding rigid body from the dynamics world
mDynamicsWorld->destroyRigidBody((*it)->getRigidBody());
// Destroy the sphere
delete (*it);
}
// Destroy all the cylinders of the scene
for (std::vector<Cylinder*>::iterator it = mCylinders.begin(); it != mCylinders.end(); ++it) {
// Destroy the corresponding rigid body from the dynamics world
mDynamicsWorld->destroyRigidBody((*it)->getRigidBody());
// Destroy the sphere
delete (*it);
}
// Destroy all the capsules of the scene
for (std::vector<Capsule*>::iterator it = mCapsules.begin(); it != mCapsules.end(); ++it) {
// Destroy the corresponding rigid body from the dynamics world
mDynamicsWorld->destroyRigidBody((*it)->getRigidBody());
// Destroy the sphere
delete (*it);
}
// Destroy all the convex meshes of the scene
for (std::vector<ConvexMesh*>::iterator it = mConvexMeshes.begin();
it != mConvexMeshes.end(); ++it) {
// Destroy the corresponding rigid body from the dynamics world
mDynamicsWorld->destroyRigidBody((*it)->getRigidBody());
// Destroy the convex mesh
delete (*it);
}
// Destroy all the visual contact points
for (std::vector<VisualContactPoint*>::iterator it = mContactPoints.begin();
it != mContactPoints.end(); ++it) {
delete (*it);
}
// Destroy the static data for the visual contact points
VisualContactPoint::destroyStaticData();
// Destroy the rigid body of the floor
mDynamicsWorld->destroyRigidBody(mFloor->getRigidBody());
// Destroy the floor
delete mFloor;
// Destroy the dynamics world
delete mDynamicsWorld;
}
// Take a step for the simulation
void Scene::simulate() {
// If the physics simulation is running
if (mIsRunning) {
// Take a simulation step
mDynamicsWorld->update();
// Update the position and orientation of the boxes
for (std::vector<Box*>::iterator it = mBoxes.begin(); it != mBoxes.end(); ++it) {
// Update the transform used for the rendering
(*it)->updateTransform();
}
// Update the position and orientation of the sphere
for (std::vector<Sphere*>::iterator it = mSpheres.begin(); it != mSpheres.end(); ++it) {
// Update the transform used for the rendering
(*it)->updateTransform();
}
// Update the position and orientation of the cones
for (std::vector<Cone*>::iterator it = mCones.begin(); it != mCones.end(); ++it) {
// Update the transform used for the rendering
(*it)->updateTransform();
}
// Update the position and orientation of the cylinders
for (std::vector<Cylinder*>::iterator it = mCylinders.begin(); it != mCylinders.end(); ++it) {
// Update the transform used for the rendering
(*it)->updateTransform();
}
// Update the position and orientation of the capsules
for (std::vector<Capsule*>::iterator it = mCapsules.begin(); it != mCapsules.end(); ++it) {
// Update the transform used for the rendering
(*it)->updateTransform();
}
// Update the position and orientation of the convex meshes
for (std::vector<ConvexMesh*>::iterator it = mConvexMeshes.begin();
it != mConvexMeshes.end(); ++it) {
// Update the transform used for the rendering
(*it)->updateTransform();
}
// Destroy all the visual contact points
for (std::vector<VisualContactPoint*>::iterator it = mContactPoints.begin();
it != mContactPoints.end(); ++it) {
delete (*it);
}
mContactPoints.clear();
// Generate the new visual contact points
const std::vector<rp3d::ContactManifold*>& manifolds = mDynamicsWorld->getContactManifolds();
for (std::vector<rp3d::ContactManifold*>::const_iterator it = manifolds.begin();
it != manifolds.end(); ++it) {
for (unsigned int i=0; i<(*it)->getNbContactPoints(); i++) {
rp3d::ContactPoint* point = (*it)->getContactPoint(i);
const rp3d::Vector3 pos = point->getWorldPointOnBody1();
openglframework::Vector3 position(pos.x, pos.y, pos.z);
VisualContactPoint* visualPoint = new VisualContactPoint(position);
mContactPoints.push_back(visualPoint);
}
}
mFloor->updateTransform();
}
}
// Render the scene
void Scene::render() {
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_CULL_FACE);
// Get the world-space to camera-space matrix
const Camera& camera = mViewer->getCamera();
const openglframework::Matrix4 worldToCameraMatrix = camera.getTransformMatrix().getInverse();
// Bind the shader
mPhongShader.bind();
// Set the variables of the shader
mPhongShader.setMatrix4x4Uniform("projectionMatrix", camera.getProjectionMatrix());
mPhongShader.setVector3Uniform("light0PosCameraSpace", worldToCameraMatrix * mLight0.getOrigin());
mPhongShader.setVector3Uniform("lightAmbientColor", Vector3(0.3f, 0.3f, 0.3f));
Color& diffColLight0 = mLight0.getDiffuseColor();
Color& specColLight0 = mLight0.getSpecularColor();
mPhongShader.setVector3Uniform("light0DiffuseColor", Vector3(diffColLight0.r, diffColLight0.g, diffColLight0.b));
mPhongShader.setVector3Uniform("light0SpecularColor", Vector3(specColLight0.r, specColLight0.g, specColLight0.b));
mPhongShader.setFloatUniform("shininess", 200.0f);
// Render all the boxes of the scene
for (std::vector<Box*>::iterator it = mBoxes.begin(); it != mBoxes.end(); ++it) {
(*it)->render(mPhongShader, worldToCameraMatrix);
}
// Render all the sphere of the scene
for (std::vector<Sphere*>::iterator it = mSpheres.begin(); it != mSpheres.end(); ++it) {
(*it)->render(mPhongShader, worldToCameraMatrix);
}
// Render all the cones of the scene
for (std::vector<Cone*>::iterator it = mCones.begin(); it != mCones.end(); ++it) {
(*it)->render(mPhongShader, worldToCameraMatrix);
}
// Render all the cylinders of the scene
for (std::vector<Cylinder*>::iterator it = mCylinders.begin(); it != mCylinders.end(); ++it) {
(*it)->render(mPhongShader, worldToCameraMatrix);
}
// Render all the capsules of the scene
for (std::vector<Capsule*>::iterator it = mCapsules.begin(); it != mCapsules.end(); ++it) {
(*it)->render(mPhongShader, worldToCameraMatrix);
}
// Render all the convex meshes of the scene
for (std::vector<ConvexMesh*>::iterator it = mConvexMeshes.begin();
it != mConvexMeshes.end(); ++it) {
(*it)->render(mPhongShader, worldToCameraMatrix);
}
// Render all the visual contact points
for (std::vector<VisualContactPoint*>::iterator it = mContactPoints.begin();
it != mContactPoints.end(); ++it) {
(*it)->render(mPhongShader, worldToCameraMatrix);
}
// Render the floor
mFloor->render(mPhongShader, worldToCameraMatrix);
// Unbind the shader
mPhongShader.unbind();
}

View File

@ -0,0 +1,153 @@
/********************************************************************************
* ReactPhysics3D physics library, http://code.google.com/p/reactphysics3d/ *
* Copyright (c) 2010-2013 Daniel Chappuis *
*********************************************************************************
* *
* This software is provided 'as-is', without any express or implied warranty. *
* In no event will the authors be held liable for any damages arising from the *
* use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not claim *
* that you wrote the original software. If you use this software in a *
* product, an acknowledgment in the product documentation would be *
* appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source distribution. *
* *
********************************************************************************/
#ifndef SCENE_H
#define SCENE_H
// Libraries
#include "openglframework.h"
#include "reactphysics3d.h"
#include "Sphere.h"
#include "Box.h"
#include "Cone.h"
#include "Cylinder.h"
#include "Capsule.h"
#include "ConvexMesh.h"
#include "VisualContactPoint.h"
// Constants
const int NB_BOXES = 3;
const int NB_SPHERES = 3;
const int NB_CONES = 3;
const int NB_CYLINDERS = 3;
const int NB_CAPSULES = 3;
const int NB_MESHES = 3;
const openglframework::Vector3 BOX_SIZE(2, 2, 2);
const float SPHERE_RADIUS = 1.5f;
const float CONE_RADIUS = 2.0f;
const float CONE_HEIGHT = 3.0f;
const float CYLINDER_RADIUS = 1.0f;
const float CYLINDER_HEIGHT = 5.0f;
const float CAPSULE_RADIUS = 1.0f;
const float CAPSULE_HEIGHT = 1.0f;
const openglframework::Vector3 FLOOR_SIZE(20, 0.5f, 20); // Floor dimensions in meters
const float BOX_MASS = 1.0f;
const float CONE_MASS = 1.0f;
const float CYLINDER_MASS = 1.0f;
const float CAPSULE_MASS = 1.0f;
const float MESH_MASS = 1.0f;
const float FLOOR_MASS = 100.0f; // Floor mass in kilograms
// Class Scene
class Scene {
private :
// -------------------- Attributes -------------------- //
/// Pointer to the viewer
openglframework::GlutViewer* mViewer;
/// Light 0
openglframework::Light mLight0;
/// Phong shader
openglframework::Shader mPhongShader;
/// All the spheres of the scene
std::vector<Box*> mBoxes;
std::vector<Sphere*> mSpheres;
std::vector<Cone*> mCones;
std::vector<Cylinder*> mCylinders;
std::vector<Capsule*> mCapsules;
/// All the convex meshes of the scene
std::vector<ConvexMesh*> mConvexMeshes;
/// All the visual contact points
std::vector<VisualContactPoint*> mContactPoints;
/// Box for the floor
Box* mFloor;
/// Dynamics world used for the physics simulation
rp3d::DynamicsWorld* mDynamicsWorld;
/// True if the physics simulation is running
bool mIsRunning;
public:
// -------------------- Methods -------------------- //
/// Constructor
Scene(openglframework::GlutViewer* viewer);
/// Destructor
~Scene();
/// Take a step for the simulation
void simulate();
/// Stop the simulation
void stopSimulation();
/// Start the simulation
void startSimulation();
/// Pause or continue simulation
void pauseContinueSimulation();
/// Render the scene
void render();
};
// Stop the simulation
inline void Scene::stopSimulation() {
mDynamicsWorld->stop();
mIsRunning = false;
}
// Start the simulation
inline void Scene::startSimulation() {
mDynamicsWorld->start();
mIsRunning = true;
}
// Pause or continue simulation
inline void Scene::pauseContinueSimulation() {
if (mIsRunning) {
stopSimulation();
}
else {
startSimulation();
}
}
#endif

View File

@ -0,0 +1,149 @@
/********************************************************************************
* ReactPhysics3D physics library, http://code.google.com/p/reactphysics3d/ *
* Copyright (c) 2010-2013 Daniel Chappuis *
*********************************************************************************
* *
* This software is provided 'as-is', without any express or implied warranty. *
* In no event will the authors be held liable for any damages arising from the *
* use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not claim *
* that you wrote the original software. If you use this software in a *
* product, an acknowledgment in the product documentation would be *
* appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source distribution. *
* *
********************************************************************************/
// Libraries
#include "ConvexMesh.h"
// Constructor
ConvexMesh::ConvexMesh(const openglframework::Vector3 &position, float mass,
reactphysics3d::DynamicsWorld* dynamicsWorld)
: openglframework::Mesh() {
// Load the mesh from a file
openglframework::MeshReaderWriter::loadMeshFromFile("meshes/convexmesh.obj", *this);
// Calculate the normals of the mesh
calculateNormals();
// Initialize the position where the sphere will be rendered
translateWorld(position);
// Create the collision shape for the rigid body (convex mesh shape)
// ReactPhysics3D will clone this object to create an internal one. Therefore,
// it is OK if this object is destroyed right after calling Dynamics::createRigidBody()
rp3d::decimal* verticesArray = (rp3d::decimal*) getVerticesPointer();
rp3d::ConvexMeshShape collisionShape(verticesArray, mVertices.size(),
sizeof(openglframework::Vector3));
// Add the edges information of the mesh into the convex mesh collision shape.
// This is optional but it really speed up the convex mesh collision detection at the
// cost of some additional memory to store the edges inside the collision shape.
for (unsigned int i=0; i<getNbFaces(); i++) { // For each triangle face of the mesh
// Get the three vertex IDs of the vertices of the face
unsigned int v1 = getVertexIndexInFace(i, 0);
unsigned int v2 = getVertexIndexInFace(i, 1);
unsigned int v3 = getVertexIndexInFace(i, 2);
// Add the three edges into the collision shape
collisionShape.addEdge(v1, v2);
collisionShape.addEdge(v1, v3);
collisionShape.addEdge(v2, v3);
}
collisionShape.setIsEdgesInformationUsed(true);// Enable the fast collision detection with edges
// Compute the inertia tensor of the body using its collision shape
rp3d::Matrix3x3 inertiaTensor;
collisionShape.computeLocalInertiaTensor(inertiaTensor, mass);
// Initial position and orientation of the rigid body
rp3d::Vector3 initPosition(position.x, position.y, position.z);
rp3d::Quaternion initOrientation = rp3d::Quaternion::identity();
rp3d::Transform transform(initPosition, initOrientation);
// Create a rigid body corresponding to the sphere in the dynamics world
mRigidBody = dynamicsWorld->createRigidBody(transform, mass, inertiaTensor, collisionShape);
}
// Destructor
ConvexMesh::~ConvexMesh() {
// Destroy the mesh
destroy();
}
// Render the sphere at the correct position and with the correct orientation
void ConvexMesh::render(openglframework::Shader& shader,
const openglframework::Matrix4& worldToCameraMatrix) {
// Bind the shader
shader.bind();
// Set the model to camera matrix
const openglframework::Matrix4 localToCameraMatrix = worldToCameraMatrix * mTransformMatrix;
shader.setMatrix4x4Uniform("localToCameraMatrix", localToCameraMatrix);
// Set the normal matrix (inverse transpose of the 3x3 upper-left sub matrix of the
// model-view matrix)
const openglframework::Matrix3 normalMatrix =
localToCameraMatrix.getUpperLeft3x3Matrix().getInverse().getTranspose();
shader.setMatrix3x3Uniform("normalMatrix", normalMatrix);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
if (hasTexture()) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
glVertexPointer(3, GL_FLOAT, 0, getVerticesPointer());
glNormalPointer(GL_FLOAT, 0, getNormalsPointer());
if(hasTexture()) {
glTexCoordPointer(2, GL_FLOAT, 0, getUVTextureCoordinatesPointer());
}
// For each part of the mesh
for (unsigned int i=0; i<getNbParts(); i++) {
glDrawElements(GL_TRIANGLES, getNbFaces(i) * 3,
GL_UNSIGNED_INT, getIndicesPointer());
}
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
if (hasTexture()) {
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
// Unbind the shader
shader.unbind();
}
// Update the transform matrix of the sphere
void ConvexMesh::updateTransform() {
// Get the interpolated transform of the rigid body
rp3d::Transform transform = mRigidBody->getInterpolatedTransform();
// Compute the transform used for rendering the sphere
float matrix[16];
transform.getOpenGLMatrix(matrix);
openglframework::Matrix4 newMatrix(matrix[0], matrix[4], matrix[8], matrix[12],
matrix[1], matrix[5], matrix[9], matrix[13],
matrix[2], matrix[6], matrix[10], matrix[14],
matrix[3], matrix[7], matrix[11], matrix[15]);
// Apply the scaling matrix to have the correct sphere dimensions
mTransformMatrix = newMatrix;
}

View File

@ -0,0 +1,72 @@
/********************************************************************************
* ReactPhysics3D physics library, http://code.google.com/p/reactphysics3d/ *
* Copyright (c) 2010-2013 Daniel Chappuis *
*********************************************************************************
* *
* This software is provided 'as-is', without any express or implied warranty. *
* In no event will the authors be held liable for any damages arising from the *
* use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not claim *
* that you wrote the original software. If you use this software in a *
* product, an acknowledgment in the product documentation would be *
* appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source distribution. *
* *
********************************************************************************/
#ifndef CONVEX_MESH_H
#define CONVEX_MESH_H
// Libraries
#include "openglframework.h"
#include "reactphysics3d.h"
// Class ConvexMesh
class ConvexMesh : public openglframework::Mesh {
private :
// -------------------- Attributes -------------------- //
/// Rigid body used to simulate the dynamics of the mesh
rp3d::RigidBody* mRigidBody;
// -------------------- Methods -------------------- //
public :
// -------------------- Methods -------------------- //
/// Constructor
ConvexMesh(const openglframework::Vector3& position, float mass,
rp3d::DynamicsWorld* dynamicsWorld);
/// Destructor
~ConvexMesh();
/// Return a pointer to the rigid body of the mesh
rp3d::RigidBody* getRigidBody();
/// Update the transform matrix of the mesh
void updateTransform();
/// Render the mesh at the correct position and with the correct orientation
void render(openglframework::Shader& shader,
const openglframework::Matrix4& worldToCameraMatrix);
};
// Return a pointer to the rigid body of the mesh
inline rp3d::RigidBody* ConvexMesh::getRigidBody() {
return mRigidBody;
}
#endif

View File

@ -0,0 +1,125 @@
# Blender v2.66 (sub 0) OBJ File: ''
# www.blender.org
v 0.000000 -1.000000 0.000000
v 0.723607 -0.447220 0.525725
v -0.276388 -0.447220 0.850649
v -0.894426 -0.447216 0.000000
v -0.276388 -0.447220 -0.850649
v 0.723607 -0.447220 -0.525725
v 0.276388 0.447220 0.850649
v -0.723607 0.447220 0.525725
v -0.723607 0.447220 -0.525725
v 0.276388 0.447220 -0.850649
v 0.894426 0.447216 0.000000
v 0.000000 1.000000 0.000000
v 0.425323 -0.850654 0.309011
v 0.262869 -0.525738 0.809012
v -0.162456 -0.850654 0.499995
v 0.425323 -0.850654 -0.309011
v 0.850648 -0.525736 0.000000
v -0.688189 -0.525736 0.499997
v -0.525730 -0.850652 0.000000
v -0.688189 -0.525736 -0.499997
v -0.162456 -0.850654 -0.499995
v 0.262869 -0.525738 -0.809012
v 0.951058 0.000000 -0.309013
v 0.951058 0.000000 0.309013
v 0.587786 0.000000 0.809017
v 0.000000 0.000000 1.000000
v -0.587786 0.000000 0.809017
v -0.951058 0.000000 0.309013
v -0.951058 0.000000 -0.309013
v -0.587786 0.000000 -0.809017
v 0.000000 0.000000 -1.000000
v 0.587786 0.000000 -0.809017
v 0.688189 0.525736 0.499997
v -0.262869 0.525738 0.809012
v -0.850648 0.525736 0.000000
v -0.262869 0.525738 -0.809012
v 0.688189 0.525736 -0.499997
v 0.525730 0.850652 0.000000
v 0.162456 0.850654 0.499995
v -0.425323 0.850654 0.309011
v -0.425323 0.850654 -0.309011
v 0.162456 0.850654 -0.499995
s off
f 1 13 15
f 2 13 17
f 1 15 19
f 1 19 21
f 1 21 16
f 2 17 24
f 3 14 26
f 4 18 28
f 5 20 30
f 6 22 32
f 2 24 25
f 3 26 27
f 4 28 29
f 5 30 31
f 6 32 23
f 7 33 39
f 8 34 40
f 9 35 41
f 10 36 42
f 11 37 38
f 15 14 3
f 15 13 14
f 13 2 14
f 17 16 6
f 17 13 16
f 13 1 16
f 19 18 4
f 19 15 18
f 15 3 18
f 21 20 5
f 21 19 20
f 19 4 20
f 16 22 6
f 16 21 22
f 21 5 22
f 24 23 11
f 24 17 23
f 17 6 23
f 26 25 7
f 26 14 25
f 14 2 25
f 28 27 8
f 28 18 27
f 18 3 27
f 30 29 9
f 30 20 29
f 20 4 29
f 32 31 10
f 32 22 31
f 22 5 31
f 25 33 7
f 25 24 33
f 24 11 33
f 27 34 8
f 27 26 34
f 26 7 34
f 29 35 9
f 29 28 35
f 28 8 35
f 31 36 10
f 31 30 36
f 30 9 36
f 23 37 11
f 23 32 37
f 32 10 37
f 39 38 12
f 39 33 38
f 33 11 38
f 40 39 12
f 40 34 39
f 34 7 39
f 41 40 12
f 41 35 40
f 35 8 40
f 42 41 12
f 42 36 41
f 36 9 41
f 38 42 12
f 38 37 42
f 37 10 42