This commit is contained in:
Erwin Coumans (Google)
2014-09-01 09:21:26 -07:00
158 changed files with 10227 additions and 8272 deletions

View File

@@ -60,7 +60,7 @@ IF(MSVC)
IF (NOT USE_MSVC_RUNTIME_LIBRARY_DLL)
#We statically link to reduce dependancies
FOREACH(flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
FOREACH(flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO )
IF(${flag_var} MATCHES "/MD")
STRING(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
ENDIF(${flag_var} MATCHES "/MD")
@@ -231,18 +231,30 @@ IF (APPLE)
ENDIF()
OPTION(BUILD_BULLET3 "Set when you want to build Bullet 3" ON)
IF(BUILD_BULLET3)
OPTION(BUILD_BULLET3_DEMOS "Set when you want to build the Bullet 3 demos" ON)
IF(APPLE)
MESSAGE("Mac OSX Version is ${_CURRENT_OSX_VERSION}")
IF(_CURRENT_OSX_VERSION VERSION_LESS 10.9)
MESSAGE("Mac OSX below 10.9 has no OpenGL 3 support so please disable the BUILD_OPENGL3_DEMOS option")
#unset(BUILD_OPENGL3_DEMOS CACHE)
OPTION(BUILD_OPENGL3_DEMOS "Set when you want to build the OpenGL3+ demos" OFF)
ELSE()
OPTION(BUILD_OPENGL3_DEMOS "Set when you want to build the OpenGL3+ demos" ON)
ENDIF()
ELSE()
OPTION(BUILD_OPENGL3_DEMOS "Set when you want to build Bullet 3 OpenGL3+ demos" ON)
ENDIF()
ELSE(BUILD_BULLET3)
unset(BUILD_BULLET3_DEMOS CACHE)
OPTION(BUILD_BULLET3_DEMOS "Set when you want to build the Bullet 3 demos" OFF)
unset(BUILD_OPENGL3_DEMOS CACHE)
OPTION(BUILD_OPENGL3_DEMOS "Set when you want to build Bullet 3 OpenGL3+ demos" OFF)
ENDIF(BUILD_BULLET3)
IF(BUILD_BULLET3_DEMOS)
IF(BUILD_OPENGL3_DEMOS)
IF(EXISTS ${BULLET_PHYSICS_SOURCE_DIR}/Demos3 AND IS_DIRECTORY ${BULLET_PHYSICS_SOURCE_DIR}/Demos3)
SUBDIRS(Demos3)
SUBDIRS(btgui)
ENDIF()
ENDIF(BUILD_BULLET3_DEMOS)
ENDIF(BUILD_OPENGL3_DEMOS)
OPTION(BUILD_EXTRAS "Set when you want to build the extras" ON)
IF(BUILD_EXTRAS)
@@ -267,10 +279,10 @@ ENDIF()
IF(INSTALL_LIBS)
SET (LIB_SUFFIX "" CACHE STRING "Define suffix of directory name (32/64)" )
SET (LIB_DESTINATION "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}" CACHE STRING "Library directory name")
SET (LIB_DESTINATION "lib${LIB_SUFFIX}" CACHE STRING "Library directory name")
## the following are directories where stuff will be installed to
SET(INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/include/bullet/" CACHE PATH "The subdirectory to the header prefix")
SET(PKGCONFIG_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}/pkgconfig/" CACHE STRING "Base directory for pkgconfig files")
SET(INCLUDE_INSTALL_DIR "include/bullet/" CACHE PATH "The subdirectory to the header prefix")
SET(PKGCONFIG_INSTALL_PREFIX "lib${LIB_SUFFIX}/pkgconfig/" CACHE STRING "Base directory for pkgconfig files")
IF(NOT WIN32)
CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/bullet.pc.cmake ${CMAKE_CURRENT_BINARY_DIR}/bullet.pc @ONLY)
INSTALL(
@@ -297,7 +309,7 @@ list (APPEND BULLET_LIBRARIES LinearMath)
list (APPEND BULLET_LIBRARIES BulletCollision)
list (APPEND BULLET_LIBRARIES BulletDynamics)
list (APPEND BULLET_LIBRARIES BulletSoftBody)
set (BULLET_USE_FILE ${CMAKE_INSTALL_PREFIX}/${BULLET_CONFIG_CMAKE_PATH}/UseBullet.cmake)
set (BULLET_USE_FILE ${BULLET_CONFIG_CMAKE_PATH}/UseBullet.cmake)
configure_file ( ${CMAKE_CURRENT_SOURCE_DIR}/BulletConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/BulletConfig.cmake
@ONLY ESCAPE_QUOTES

View File

@@ -24,18 +24,12 @@ IF (USE_GLUT)
SET(SharedDemoSubdirs OpenGL )
ENDIF(BUILD_CPU_DEMOS)
IF(BUILD_MULTITHREADING)
SUBDIRS( MultiThreadedDemo OpenCLClothDemo )
ENDIF(BUILD_MULTITHREADING)
SUBDIRS(
${SharedDemoSubdirs}
Benchmarks
)
IF(BUILD_MULTITHREADING)
SUBDIRS( ThreadingDemo VectorAdd_OpenCL )
ENDIF()
ENDIF(GLUT_FOUND)
ELSE (USE_GLUT)

View File

@@ -0,0 +1,298 @@
#ifndef COMMON_MULTI_BODY_SETUP_H
#define COMMON_MULTI_BODY_SETUP_H
//todo: replace this 'btBulletDynamicsCommon.h' header with specific used header files
#include "btBulletDynamicsCommon.h"
#include "CommonPhysicsSetup.h"
#include "BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h"
#include "BulletDynamics/Featherstone/btMultiBodyConstraintSolver.h"
#include "BulletDynamics/Featherstone/btMultiBodyPoint2Point.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
struct CommonMultiBodySetup : public CommonPhysicsSetup
{
//keep the collision shapes, for deletion/cleanup
btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher;
btMultiBodyConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration;
btMultiBodyDynamicsWorld* m_dynamicsWorld;
//data for picking objects
class btRigidBody* m_pickedBody;
class btTypedConstraint* m_pickedConstraint;
class btMultiBodyPoint2Point* m_pickingMultiBodyPoint2Point;
btVector3 m_oldPickingPos;
btVector3 m_hitPos;
btScalar m_oldPickingDist;
bool m_prevCanSleep;
CommonMultiBodySetup()
:m_broadphase(0),
m_dispatcher(0),
m_solver(0),
m_collisionConfiguration(0),
m_dynamicsWorld(0),
m_pickedBody(0),
m_pickedConstraint(0),
m_pickingMultiBodyPoint2Point(0),
m_prevCanSleep(false)
{
}
virtual void createEmptyDynamicsWorld()
{
///collision configuration contains default setup for memory, collision setup
m_collisionConfiguration = new btDefaultCollisionConfiguration();
//m_collisionConfiguration->setConvexConvexMultipointIterations();
///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
m_broadphase = new btDbvtBroadphase();
m_solver = new btMultiBodyConstraintSolver;
m_dynamicsWorld = new btMultiBodyDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);
m_dynamicsWorld->setGravity(btVector3(0, -10, 0));
}
virtual void stepSimulation(float deltaTime)
{
if (m_dynamicsWorld)
{
m_dynamicsWorld->stepSimulation(deltaTime);
}
}
virtual void exitPhysics()
{
removePickingConstraint();
//cleanup in the reverse order of creation/initialization
//remove the rigidbodies from the dynamics world and delete them
if (m_dynamicsWorld)
{
int i;
for (i = m_dynamicsWorld->getNumConstraints() - 1; i >= 0; i--)
{
m_dynamicsWorld->removeConstraint(m_dynamicsWorld->getConstraint(i));
}
for (i = m_dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--)
{
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState())
{
delete body->getMotionState();
}
m_dynamicsWorld->removeCollisionObject(obj);
delete obj;
}
}
//delete collision shapes
for (int j = 0; j<m_collisionShapes.size(); j++)
{
btCollisionShape* shape = m_collisionShapes[j];
delete shape;
}
m_collisionShapes.clear();
delete m_dynamicsWorld;
delete m_solver;
delete m_broadphase;
delete m_dispatcher;
delete m_collisionConfiguration;
}
virtual void syncPhysicsToGraphics(GraphicsPhysicsBridge& gfxBridge)
{
if (m_dynamicsWorld)
{
gfxBridge.syncPhysicsToGraphics(m_dynamicsWorld);
}
}
virtual void debugDraw()
{
if (m_dynamicsWorld)
{
m_dynamicsWorld->debugDrawWorld();
}
}
virtual bool pickBody(const btVector3& rayFromWorld, const btVector3& rayToWorld)
{
if (m_dynamicsWorld==0)
return false;
btCollisionWorld::ClosestRayResultCallback rayCallback(rayFromWorld, rayToWorld);
m_dynamicsWorld->rayTest(rayFromWorld, rayToWorld, rayCallback);
if (rayCallback.hasHit())
{
btVector3 pickPos = rayCallback.m_hitPointWorld;
btRigidBody* body = (btRigidBody*)btRigidBody::upcast(rayCallback.m_collisionObject);
if (body)
{
//other exclusions?
if (!(body->isStaticObject() || body->isKinematicObject()))
{
m_pickedBody = body;
m_pickedBody->setActivationState(DISABLE_DEACTIVATION);
//printf("pickPos=%f,%f,%f\n",pickPos.getX(),pickPos.getY(),pickPos.getZ());
btVector3 localPivot = body->getCenterOfMassTransform().inverse() * pickPos;
btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*body, localPivot);
m_dynamicsWorld->addConstraint(p2p, true);
m_pickedConstraint = p2p;
btScalar mousePickClamping = 30.f;
p2p->m_setting.m_impulseClamp = mousePickClamping;
//very weak constraint for picking
p2p->m_setting.m_tau = 0.001f;
}
} else
{
btMultiBodyLinkCollider* multiCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(rayCallback.m_collisionObject);
if (multiCol && multiCol->m_multiBody)
{
m_prevCanSleep = multiCol->m_multiBody->getCanSleep();
multiCol->m_multiBody->setCanSleep(false);
btVector3 pivotInA = multiCol->m_multiBody->worldPosToLocal(multiCol->m_link, pickPos);
btMultiBodyPoint2Point* p2p = new btMultiBodyPoint2Point(multiCol->m_multiBody,multiCol->m_link,0,pivotInA,pickPos);
//if you add too much energy to the system, causing high angular velocities, simulation 'explodes'
//see also http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=4&t=949
//so we try to avoid it by clamping the maximum impulse (force) that the mouse pick can apply
//it is not satisfying, hopefully we find a better solution (higher order integrator, using joint friction using a zero-velocity target motor with limited force etc?)
btScalar scaling=1;
p2p->setMaxAppliedImpulse(2*scaling);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*) m_dynamicsWorld;
world->addMultiBodyConstraint(p2p);
m_pickingMultiBodyPoint2Point =p2p;
}
}
// pickObject(pickPos, rayCallback.m_collisionObject);
m_oldPickingPos = rayToWorld;
m_hitPos = pickPos;
m_oldPickingDist = (pickPos - rayFromWorld).length();
// printf("hit !\n");
//add p2p
}
return false;
}
virtual bool movePickedBody(const btVector3& rayFromWorld, const btVector3& rayToWorld)
{
if (m_pickedBody && m_pickedConstraint)
{
btPoint2PointConstraint* pickCon = static_cast<btPoint2PointConstraint*>(m_pickedConstraint);
if (pickCon)
{
//keep it at the same picking distance
btVector3 dir = rayToWorld-rayFromWorld;
dir.normalize();
dir *= m_oldPickingDist;
btVector3 newPivotB = rayFromWorld + dir;
pickCon->setPivotB(newPivotB);
}
}
if (m_pickingMultiBodyPoint2Point)
{
//keep it at the same picking distance
btVector3 dir = rayToWorld-rayFromWorld;
dir.normalize();
dir *= m_oldPickingDist;
btVector3 newPivotB = rayFromWorld + dir;
m_pickingMultiBodyPoint2Point->setPivotInB(newPivotB);
}
return false;
}
virtual void removePickingConstraint()
{
if (m_pickedConstraint)
{
m_dynamicsWorld->removeConstraint(m_pickedConstraint);
delete m_pickedConstraint;
m_pickedConstraint = 0;
m_pickedBody = 0;
}
if (m_pickingMultiBodyPoint2Point)
{
m_pickingMultiBodyPoint2Point->getMultiBodyA()->setCanSleep(m_prevCanSleep);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*) m_dynamicsWorld;
world->removeMultiBodyConstraint(m_pickingMultiBodyPoint2Point);
delete m_pickingMultiBodyPoint2Point;
m_pickingMultiBodyPoint2Point = 0;
}
}
btBoxShape* createBoxShape(const btVector3& halfExtents)
{
btBoxShape* box = new btBoxShape(halfExtents);
return box;
}
btRigidBody* createRigidBody(float mass, const btTransform& startTransform, btCollisionShape* shape, const btVector4& color = btVector4(1, 0, 0, 1))
{
btAssert((!shape || shape->getShapeType() != INVALID_SHAPE_PROXYTYPE));
//rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f);
btVector3 localInertia(0, 0, 0);
if (isDynamic)
shape->calculateLocalInertia(mass, localInertia);
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
#define USE_MOTIONSTATE 1
#ifdef USE_MOTIONSTATE
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo cInfo(mass, myMotionState, shape, localInertia);
btRigidBody* body = new btRigidBody(cInfo);
//body->setContactProcessingThreshold(m_defaultContactProcessingThreshold);
#else
btRigidBody* body = new btRigidBody(mass, 0, shape, localInertia);
body->setWorldTransform(startTransform);
#endif//
body->setUserIndex(-1);
m_dynamicsWorld->addRigidBody(body);
return body;
}
};
#endif //COMMON_MULTI_BODY_SETUP_H

View File

@@ -3,6 +3,7 @@
#define COMMON_PHYSICS_SETUP_H
class btRigidBody;
class btCollisionObject;
class btBoxShape;
class btTransform;
class btCollisionShape;
@@ -18,6 +19,10 @@ struct GraphicsPhysicsBridge
virtual void createRigidBodyGraphicsObject(btRigidBody* body,const btVector3& color)
{
}
virtual void createCollisionObjectGraphicsObject(btCollisionObject* obj,const btVector3& color)
{
}
virtual void createCollisionShapeGraphicsObject(btCollisionShape* collisionShape)
{
}

View File

@@ -443,7 +443,7 @@ void DemoApplication::keyboardCallback(unsigned char key, int x, int y)
m_debugMode |= btIDebugDraw::DBG_ProfileTimings;
break;
case '=':
case '\\':
{
int maxSerializeBufferSize = 1024*1024*5;
btDefaultSerializer* serializer = new btDefaultSerializer(maxSerializeBufferSize);

View File

@@ -462,7 +462,7 @@ void GL_ShapeDrawer::drawOpenGL(btScalar* m, const btCollisionShape* shape, cons
{
const int s=x>>4;
const GLubyte b=180;
GLubyte c=b+((s+t&1)&1)*(255-b);
GLubyte c=b+((s+(t&1))&1)*(255-b);
pi[0]=pi[1]=pi[2]=pi[3]=c;pi+=3;
}
}
@@ -518,7 +518,7 @@ void GL_ShapeDrawer::drawOpenGL(btScalar* m, const btCollisionShape* shape, cons
glColor3f(color.x(),color.y(), color.z());
bool useWireframeFallback = true;
//bool useWireframeFallback = true;
if (!(debugMode & btIDebugDraw::DBG_DrawWireframe))
{
@@ -535,7 +535,7 @@ void GL_ShapeDrawer::drawOpenGL(btScalar* m, const btCollisionShape* shape, cons
const btSphereShape* sphereShape = static_cast<const btSphereShape*>(shape);
float radius = sphereShape->getMargin();//radius doesn't include the margin, so draw with margin
drawSphere(radius,10,10);
useWireframeFallback = false;
//useWireframeFallback = false;
break;
}
@@ -586,7 +586,7 @@ void GL_ShapeDrawer::drawOpenGL(btScalar* m, const btCollisionShape* shape, cons
glEnd();
#endif
useWireframeFallback = false;
//useWireframeFallback = false;
break;
}
@@ -617,7 +617,7 @@ void GL_ShapeDrawer::drawOpenGL(btScalar* m, const btCollisionShape* shape, cons
glTranslatef(0.0, 0.0, -0.5*height);
glutSolidCone(radius,height,10,10);
useWireframeFallback = false;
//useWireframeFallback = false;
break;
}

View File

@@ -17,6 +17,11 @@ subject to the following restrictions:
#include "DemoApplication.h"
#if !defined(_WIN32) && !defined(__APPLE__)
//assume linux workaround
//#include <pthread.h>
#endif
//glut is C code, this global gDemoApplication links glut to the C++ demo
static DemoApplication* gDemoApplication = 0;
@@ -77,6 +82,14 @@ int glutmain(int argc, char **argv,int width,int height,const char* title,DemoAp
gDemoApplication = demoApp;
#if !defined(_WIN32) && !defined(__APPLE__)
//Access pthreads as a workaround for a bug in Linux/Ubuntu
//See https://bugs.launchpad.net/ubuntu/+source/nvidia-graphics-drivers-319/+bug/1248642
// int i=pthread_getconcurrency();
// printf("pthread_getconcurrency()=%d\n",i);
#endif
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
glutInitWindowPosition(width/2, height/2);

View File

@@ -14,8 +14,48 @@ void SerializeSetup::initPhysics(GraphicsPhysicsBridge& gfxBridge)
{
this->createEmptyDynamicsWorld();
gfxBridge.createPhysicsDebugDrawer(m_dynamicsWorld);
m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe);
m_dynamicsWorld->getDebugDrawer()->setDebugMode(btIDebugDraw::DBG_DrawWireframe+btIDebugDraw::DBG_DrawContactPoints);
btBulletWorldImporter* importer = new btBulletWorldImporter(m_dynamicsWorld);
const char* filename = "testFile.bullet";
importer->loadFile(filename);
const char* someFileName="spider.bullet";
const char* prefix[]={"./","./data/","../data/","../../data/","../../../data/","../../../../data/"};
int numPrefixes = sizeof(prefix)/sizeof(const char*);
char relativeFileName[1024];
FILE* f=0;
bool fileFound = false;
int result = 0;
for (int i=0;!f && i<numPrefixes;i++)
{
sprintf(relativeFileName,"%s%s",prefix[i],someFileName);
f = fopen(relativeFileName,"rb");
if (f)
{
fileFound = true;
break;
}
}
if (f)
{
fclose(f);
}
importer->loadFile(relativeFileName);
//for now, guess the up axis from gravity
if (m_dynamicsWorld->getGravity()[1] == 0.f)
{
gfxBridge.setUpAxis(2);
} else
{
gfxBridge.setUpAxis(1);
}
}
void SerializeSetup::stepSimulation(float deltaTime)
{
CommonRigidBodySetup::stepSimulation(deltaTime);
}

View File

@@ -9,6 +9,7 @@ public:
virtual ~SerializeSetup();
virtual void initPhysics(GraphicsPhysicsBridge& gfxBridge);
virtual void stepSimulation(float deltaTime);
};
#endif //SERIALIZE_SETUP_H

View File

@@ -34,7 +34,7 @@ function createDemos( demos, incdirs, linknames)
linkoptions { "-framework Carbon -framework OpenGL -framework AGL -framework Glut" }
configuration {"not Windows", "not MacOSX"}
links {"GL","GLU","glut"}
links {"GL","GLU","glut","pthread"}
configuration{}

View File

@@ -14,10 +14,18 @@
#include "../bullet2/LuaDemo/LuaPhysicsSetup.h"
#include "../bullet2/ChainDemo/ChainDemo.h"
#include "../../Demos/CcdPhysicsDemo/CcdPhysicsSetup.h"
#include "../../Demos/ConstraintDemo/ConstraintPhysicsSetup.h"
#include "../bullet2/ConstraintDemo/ConstraintPhysicsSetup.h"
#include "../ImportURDFDemo/ImportURDFSetup.h"
#include "../ImportObjDemo/ImportObjSetup.h"
#include "../ImportSTLDemo/ImportSTLSetup.h"
#include "../../Demos/SerializeDemo/SerializeSetup.h"
#include "../bullet2/MultiBodyDemo/TestJointTorqueSetup.h"
static BulletDemoInterface* TestJointTorqueCreateFunc(SimpleOpenGL3App* app)
{
CommonPhysicsSetup* physicsSetup = new TestJointTorqueSetup();
return new BasicDemo(app, physicsSetup);
}
static BulletDemoInterface* LuaDemoCreateFunc(SimpleOpenGL3App* app)
{
@@ -36,7 +44,11 @@ static BulletDemoInterface* MyKinematicObjectCreateFunc(SimpleOpenGL3App* app)
CommonPhysicsSetup* physicsSetup = new KinematicObjectSetup();
return new BasicDemo(app, physicsSetup);
}
static BulletDemoInterface* MySerializeCreateFunc(SimpleOpenGL3App* app)
{
CommonPhysicsSetup* physicsSetup = new SerializeSetup();
return new BasicDemo(app, physicsSetup);
}
static BulletDemoInterface* MyConstraintCreateFunc(SimpleOpenGL3App* app)
{
CommonPhysicsSetup* physicsSetup = new ConstraintPhysicsSetup();
@@ -82,6 +94,7 @@ static BulletDemoEntry allDemos[]=
{0,"File Formats", 0},
//@todo(erwincoumans) { 1, "bullet", MyImportSTLCreateFunc},
{ 1, ".bullet",MySerializeCreateFunc},
{ 1, "Wavefront Obj", MyImportObjCreateFunc},
{ 1, "URDF", MyImportUrdfCreateFunc },
{ 1, "STL", MyImportSTLCreateFunc},
@@ -102,6 +115,8 @@ static BulletDemoEntry allDemos[]=
{1,"MultiBody1",FeatherstoneDemo1::MyCreateFunc},
// {"MultiBody2",FeatherstoneDemo2::MyCreateFunc},
{1,"MultiDofDemo",MultiDofDemo::MyCreateFunc},
{1,"TestJointTorque",TestJointTorqueCreateFunc},
};
@@ -124,10 +139,15 @@ static int loadCurrentDemoEntry(const char* startFileName)
FILE* f = fopen(startFileName,"r");
if (f)
{
fscanf(f,"%d",&currentEntry);
int result;
result = fscanf(f,"%d",&currentEntry);
if (result)
{
return currentEntry;
}
fclose(f);
}
return currentEntry;
return 0;
};
#endif//BULLET_DEMO_ENTRIES_H

View File

@@ -6,7 +6,6 @@ INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/btgui/lua-5.2.3/src
)
SET(App_AllBullet2Demos_SRCS
main.cpp
BulletDemoInterface.h
@@ -26,8 +25,16 @@ SET(App_AllBullet2Demos_SRCS
../../Demos/BasicDemo/BasicDemoPhysicsSetup.h
../../Demos/CcdPhysicsDemo/CcdPhysicsSetup.cpp
../../Demos/CcdPhysicsDemo/CcdPhysicsSetup.h
../../Demos/ConstraintDemo/ConstraintPhysicsSetup.cpp
../../Demos/ConstraintDemo/ConstraintPhysicsSetup.h
../../Demos/SerializeDemo/SerializeSetup.cpp
../../Extras/Serialize/BulletFileLoader/bChunk.cpp
../../Extras/Serialize/BulletFileLoader/bDNA.cpp
../../Extras/Serialize/BulletFileLoader/bFile.cpp
../../Extras/Serialize/BulletFileLoader/btBulletFile.cpp
../../Extras/Serialize/BulletWorldImporter/btBulletWorldImporter.cpp
../../Extras/Serialize/BulletWorldImporter/btWorldImporter.cpp
../bullet2/MultiBodyDemo/TestJointTorqueSetup.cpp
../bullet2/ConstraintDemo/ConstraintPhysicsSetup.cpp
../bullet2/ConstraintDemo/ConstraintPhysicsSetup.h
../bullet2/FeatherstoneMultiBodyDemo/BulletMultiBodyDemos.cpp
../bullet2/FeatherstoneMultiBodyDemo/BulletMultiBodyDemos.h
../bullet2/FeatherstoneMultiBodyDemo/MultiDofDemo.cpp
@@ -93,7 +100,13 @@ ELSE(WIN32)
MESSAGE(${COCOA})
link_libraries(${COCOA})
ELSE(APPLE)
LINK_LIBRARIES( pthread GLEW)
ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1")
ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/btgui/OpenGLWindow/GlewWindows
)
LINK_LIBRARIES( pthread dl)
ENDIF(APPLE)
ENDIF(WIN32)

View File

@@ -14,7 +14,7 @@ GraphingTexture::~GraphingTexture()
destroy();
}
bool GraphingTexture::destroy()
void GraphingTexture::destroy()
{
//TODO(erwincoumans) release memory etc...
m_width = 0;
@@ -58,21 +58,18 @@ bool GraphingTexture::create(int texWidth, int texHeight)
glGenTextures(1,(GLuint*)&m_textureId);
uploadImageData();
return true;
}
void GraphingTexture::uploadImageData()
{
glBindTexture(GL_TEXTURE_2D,m_textureId);
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width,m_height,0,GL_RGBA,GL_UNSIGNED_BYTE,&m_imageData[0]);
glGenerateMipmap(GL_TEXTURE_2D);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}

View File

@@ -14,7 +14,7 @@ struct GraphingTexture
virtual ~GraphingTexture();
bool create(int texWidth, int texHeight);
bool destroy();
void destroy();
void setPixel(int x, int y, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha)
{

View File

@@ -124,7 +124,7 @@ void GwenParameterInterface::registerSliderFloatParameter(SliderParams& params)
pSlider->onValueChanged.Add( handler, &MySliderEventHandler<btScalar>::SliderMoved );
handler->SliderMoved(pSlider);
float v = pSlider->GetValue();
// float v = pSlider->GetValue();
m_gwenInternalData->m_curYposition+=22;
}

View File

@@ -1,3 +1,4 @@
#include "GwenProfileWindow.h"
#include "../GpuDemos/gwenUserInterface.h"
#include "../GpuDemos/gwenInternalData.h"
#include "LinearMath/btQuickprof.h"
@@ -27,7 +28,7 @@ protected:
void SliderMoved(Gwen::Controls::Base* pControl )
{
Gwen::Controls::Slider* pSlider = (Gwen::Controls::Slider*)pControl;
// Gwen::Controls::Slider* pSlider = (Gwen::Controls::Slider*)pControl;
//this->m_app->scaleYoungModulus(pSlider->GetValue());
// printf("Slider Value: %.2f", pSlider->GetValue() );
}
@@ -35,8 +36,8 @@ protected:
void OnCheckChangedStiffnessWarping (Gwen::Controls::Base* pControl)
{
Gwen::Controls::CheckBox* labeled = (Gwen::Controls::CheckBox* )pControl;
bool checked = labeled->IsChecked();
// Gwen::Controls::CheckBox* labeled = (Gwen::Controls::CheckBox* )pControl;
// bool checked = labeled->IsChecked();
//m_app->m_stiffness_warp_on = checked;
}
public:
@@ -148,13 +149,13 @@ public:
void UpdateText(CProfileIterator* profileIterator, bool idle)
{
static bool update=true;
// static bool update=true;
m_ctrl->SetBounds(0,0,this->GetInnerBounds().w,this->GetInnerBounds().h);
// if (!update)
// return;
update=false;
// update=false;
static int test = 1;
@@ -170,18 +171,18 @@ public:
{
//recompute profiling data, and store profile strings
char blockTime[128];
// char blockTime[128];
double totalTime = 0;
// double totalTime = 0;
int frames_since_reset = CProfileManager::Get_Frame_Count_Since_Reset();
// int frames_since_reset = CProfileManager::Get_Frame_Count_Since_Reset();
profileIterator->First();
double parent_time = profileIterator->Is_Root() ? time_since_reset : profileIterator->Get_Current_Parent_Total_Time();
Gwen::Controls::TreeNode* curParent = m_node;
// Gwen::Controls::TreeNode* curParent = m_node;
double accumulated_time = dumpRecursive(profileIterator,m_node);

View File

@@ -1,8 +1,7 @@
#ifndef GWEN_PROFILE_WINDOW_H
#define GWEN_PROFILE_WINDOW_H
struct MyProfileWindow* setupProfileWindow(struct GwenInternalData* data);
class MyProfileWindow* setupProfileWindow(struct GwenInternalData* data);
void processProfileData(MyProfileWindow* window, bool idle);
void profileWindowSetVisible(MyProfileWindow* window, bool visible);
void destroyProfileWindow(MyProfileWindow* window);

View File

@@ -78,7 +78,7 @@ public:
}
};
struct MyGraphWindow* setupTextureWindow(const MyGraphInput& input)
MyGraphWindow* setupTextureWindow(const MyGraphInput& input)
{
MyGraphWindow* graphWindow = new MyGraphWindow(input);
MyMenuItems2* menuItems = new MyMenuItems2(graphWindow);

View File

@@ -25,7 +25,7 @@ struct MyGraphInput
{
}
};
struct MyGraphWindow* setupTextureWindow(const MyGraphInput& input);
class MyGraphWindow* setupTextureWindow(const MyGraphInput& input);
void destroyTextureWindow(MyGraphWindow* window);

View File

@@ -24,9 +24,11 @@ static b3AlignedObjectArray<const char*> allNames;
bool drawGUI=true;
extern bool useShadowMap;
static bool wireframe=false;
static bool pauseSimulation=false;
static bool pauseSimulation=false;//true;
int midiBaseIndex = 176;
//#include <float.h>
//unsigned int fp_control_state = _controlfp(_EM_INEXACT, _MCW_EM);
#ifdef B3_USE_MIDI
#include "../../btgui/MidiTest/RtMidi.h"
@@ -179,6 +181,32 @@ static void MyMouseButtonCallback(int button, int state, float x, float y)
#include <string.h>
void openURDFDemo(const char* filename)
{
if (sCurrentDemo)
{
sCurrentDemo->exitPhysics();
app->m_instancingRenderer->removeAllInstances();
delete sCurrentDemo;
sCurrentDemo=0;
}
app->m_parameterInterface->removeAllParameters();
ImportUrdfDemo* physicsSetup = new ImportUrdfDemo();
physicsSetup->setFileName(filename);
sCurrentDemo = new BasicDemo(app, physicsSetup);
if (sCurrentDemo)
{
sCurrentDemo->initPhysics();
}
}
void selectDemo(int demoIndex)
{
sCurrentDemoIndex = demoIndex;
@@ -238,13 +266,13 @@ struct MyMenuItemHander :public Gwen::Event::Handler
void onButtonA(Gwen::Controls::Base* pControl)
{
const Gwen::String& name = pControl->GetName();
//const Gwen::String& name = pControl->GetName();
Gwen::Controls::TreeNode* node = (Gwen::Controls::TreeNode*)pControl;
Gwen::Controls::Label* l = node->GetButton();
// Gwen::Controls::Label* l = node->GetButton();
Gwen::UnicodeString la = node->GetButton()->GetText();// node->GetButton()->GetName();// GetText();
Gwen::String laa = Gwen::Utility::UnicodeToString(la);
const char* ha = laa.c_str();
// const char* ha = laa.c_str();
//printf("selected %s\n", ha);
//int dep = but->IsDepressed();
@@ -257,7 +285,7 @@ struct MyMenuItemHander :public Gwen::Event::Handler
Gwen::Controls::Label* label = (Gwen::Controls::Label*) pControl;
Gwen::UnicodeString la = label->GetText();// node->GetButton()->GetName();// GetText();
Gwen::String laa = Gwen::Utility::UnicodeToString(la);
const char* ha = laa.c_str();
//const char* ha = laa.c_str();
selectDemo(sCurrentHightlighted);
@@ -265,10 +293,10 @@ struct MyMenuItemHander :public Gwen::Event::Handler
}
void onButtonC(Gwen::Controls::Base* pControl)
{
Gwen::Controls::Label* label = (Gwen::Controls::Label*) pControl;
Gwen::UnicodeString la = label->GetText();// node->GetButton()->GetName();// GetText();
Gwen::String laa = Gwen::Utility::UnicodeToString(la);
const char* ha = laa.c_str();
// Gwen::Controls::Label* label = (Gwen::Controls::Label*) pControl;
// Gwen::UnicodeString la = label->GetText();// node->GetButton()->GetName();// GetText();
// Gwen::String laa = Gwen::Utility::UnicodeToString(la);
// const char* ha = laa.c_str();
// printf("onButtonC ! %s\n", ha);
@@ -314,7 +342,8 @@ struct GL3TexLoader : public MyTextureLoader
virtual void LoadTexture( Gwen::Texture* pTexture )
{
const char* n = pTexture->name.Get().c_str();
Gwen::String namestr = pTexture->name.Get();
const char* n = namestr.c_str();
GLint* texIdPtr = m_hashMap[n];
if (texIdPtr)
{
@@ -326,6 +355,18 @@ struct GL3TexLoader : public MyTextureLoader
}
};
void fileOpenCallback()
{
char filename[1024];
int len = app->m_window->fileOpenDialog(filename,1024);
if (len)
{
//todo(erwincoumans) check if it is actually URDF
//printf("file open:%s\n", filename);
openURDFDemo(filename);
}
}
extern float shadowMapWorldSize;
int main(int argc, char* argv[])
@@ -334,7 +375,7 @@ int main(int argc, char* argv[])
b3Clock clock;
float dt = 1./120.f;
//float dt = 1./120.f;
int width = 1024;
int height=768;
@@ -348,8 +389,7 @@ int main(int argc, char* argv[])
app->m_window->setKeyboardCallback(MyKeyboardCallback);
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
sth_stash* fontstash=app->getFontStash();
gui = new GwenUserInterface;
@@ -376,7 +416,8 @@ int main(int argc, char* argv[])
gt->create(256,256);
int texId = gt->getTextureId();
myTexLoader->m_hashMap.insert("graph1", texId);
MyGraphWindow* gw = setupTextureWindow(input);
//MyGraphWindow* gw =
setupTextureWindow(input);
}
if (1)
{
@@ -403,7 +444,8 @@ int main(int argc, char* argv[])
int texId = gt->getTextureId();
input.m_xPos = width-input.m_width;
myTexLoader->m_hashMap.insert("graph2", texId);
MyGraphWindow* gw = setupTextureWindow(input);
//MyGraphWindow* gw =
setupTextureWindow(input);
}
//destroyTextureWindow(gw);
@@ -414,8 +456,8 @@ int main(int argc, char* argv[])
int numDemos = sizeof(allDemos)/sizeof(BulletDemoEntry);
char nodeText[1024];
int curDemo = 0;
//char nodeText[1024];
//int curDemo = 0;
int selectedDemo = loadCurrentDemoEntry(startFileName);
Gwen::Controls::TreeNode* curNode = tree;
MyMenuItemHander* handler2 = new MyMenuItemHander(-1);
@@ -472,12 +514,12 @@ int main(int argc, char* argv[])
*/
unsigned long int prevTimeInMicroseconds = clock.getTimeMicroseconds();
gui->registerFileOpenCallback(fileOpenCallback);
do
{
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
app->m_instancingRenderer->init();
DrawGridData dg;
dg.upAxis = app->getUpAxis();

View File

@@ -44,14 +44,23 @@
"../bullet2/BasicDemo/Bullet2RigidBodyDemo.h",
"../bullet2/LuaDemo/LuaPhysicsSetup.cpp",
"../bullet2/LuaDemo/LuaPhysicsSetup.h",
"../bullet2/MultiBodyDemo/TestJointTorqueSetup.cpp",
"../bullet2/MultiBodyDemo/TestJointTorqueSetup.h",
-- "../DifferentialGearDemo/DifferentialGearSetup.cpp",
-- "../DifferentialGearDemo/DifferentialGearSetup.h",
"../../Demos/BasicDemo/BasicDemoPhysicsSetup.cpp",
"../../Demos/BasicDemo/BasicDemoPhysicsSetup.h",
"../../Demos/CcdPhysicsDemo/CcdPhysicsSetup.cpp",
"../../Demos/CcdPhysicsDemo/CcdPhysicsSetup.h",
"../../Demos/ConstraintDemo/ConstraintPhysicsSetup.cpp",
"../../Demos/ConstraintDemo/ConstraintPhysicsSetup.h",
"../../Demos/SerializeDemo/SerializeSetup.cpp",
"../../Extras/Serialize/BulletFileLoader/bChunk.cpp",
"../../Extras/Serialize/BulletFileLoader/bDNA.cpp",
"../../Extras/Serialize/BulletFileLoader/bFile.cpp",
"../../Extras/Serialize/BulletFileLoader/btBulletFile.cpp",
"../../Extras/Serialize/BulletWorldImporter/btBulletWorldImporter.cpp",
"../../Extras/Serialize/BulletWorldImporter/btWorldImporter.cpp",
"../bullet2/ConstraintDemo/ConstraintPhysicsSetup.cpp",
"../bullet2/ConstraintDemo/ConstraintPhysicsSetup.h",
"../ImportURDFDemo/ImportURDFSetup.cpp",
"../ImportObjDemo/ImportObjSetup.cpp",
"../ImportSTLDemo/ImportSTLSetup.cpp",

View File

@@ -144,7 +144,7 @@ int main(int argc, char* argv[])
}
if (majorGlVersion>=3 && wci.m_openglVersion>=3)
{
float retinaScale = 1.f;
// float retinaScale = 1.f;
#ifndef __APPLE__
#ifndef _WIN32
@@ -154,14 +154,15 @@ int main(int argc, char* argv[])
glewInit();
#endif
//we ned to call glGetError twice, because of some Ubuntu/Intel/OpenGL issue
//we need to call glGetError twice, because of some Ubuntu/Intel/OpenGL issue
GLuint err = glGetError();
err = glGetError();
btAssert(err==GL_NO_ERROR);
glGetError();
glGetError();
btAssert(glGetError()==GL_NO_ERROR);
retinaScale = window->getRetinaScale();
//retinaScale = window->getRetinaScale();
//primRenderer = new GLPrimitiveRenderer(sWidth,sHeight);
//sth_stash* font = initFont(primRenderer );

View File

@@ -1,5 +1,5 @@
if (OPENGL_FOUND)
if (BUILD_BULLET3_DEMOS)
if (BUILD_OPENGL3_DEMOS)
SUBDIRS( AllBullet2Demos GpuDemos SimpleOpenGL3 )
endif(BUILD_BULLET3_DEMOS)
endif(BUILD_OPENGL3_DEMOS)
endif(OPENGL_FOUND)

View File

@@ -50,7 +50,16 @@ ELSE(WIN32)
MESSAGE(${COCOA})
link_libraries(${COCOA})
ELSE(APPLE)
LINK_LIBRARIES( GLEW X11 pthread dl)
SET(App_Bullet3_OpenCL_Demos_SRCS ${App_Bullet3_OpenCL_Demos_SRCS} ${App_Bullet3_OpenCL_Demos_Common_SRCS} ../../btgui/OpenGLWindow/GlewWindows/glew.c)
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/btgui/OpenGLWindow/GlewWindows
)
ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1")
ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
LINK_LIBRARIES( X11 pthread dl)
ENDIF(APPLE)
ENDIF(WIN32)

View File

@@ -5,7 +5,7 @@
#include "Bullet3OpenCL/Initialize/b3OpenCLUtils.h"
#define MSTRINGIFY(A) #A
static char* particleKernelsString =
static const char* particleKernelsString =
#include "ParticleKernels.cl"
#define INTEROPKERNEL_SRC_PATH "demo/gpudemo/ParticleKernels.cl"
@@ -256,7 +256,7 @@ void ParticleDemo::setupScene(const ConstructionInfo& ci)
int id = m_instancingRenderer->registerGraphicsInstance(shapeId,position,quaternion,color,scaling);
void* userPtr = (void*)userIndex;
int collidableIndex = userIndex;
b3Vector3 aabbMin,aabbMax;
b3Vector3 particleRadius=b3MakeVector3(rad,rad,rad);

View File

@@ -40,6 +40,7 @@ struct GwenInternalData
Gwen::Controls::TabButton* m_explorerPage;
Gwen::Controls::TreeControl* m_explorerTreeCtrl;
Gwen::Controls::MenuItem* m_viewMenu;
class MyMenuItems* m_menuItems;
int m_curYposition;

View File

@@ -44,13 +44,23 @@ class MyMenuItems : public Gwen::Controls::Base
{
public:
MyMenuItems() :Gwen::Controls::Base(0)
b3FileOpenCallback m_fileOpenCallback;
MyMenuItems() :Gwen::Controls::Base(0),m_fileOpenCallback(0)
{
}
void myQuitApp( Gwen::Controls::Base* pControl )
{
exit(0);
}
void fileOpen( Gwen::Controls::Base* pControl )
{
if (m_fileOpenCallback)
{
(*m_fileOpenCallback)();
}
}
};
struct MyTestMenuBar : public Gwen::Controls::MenuStrip
@@ -58,16 +68,19 @@ struct MyTestMenuBar : public Gwen::Controls::MenuStrip
Gwen::Controls::MenuItem* m_fileMenu;
Gwen::Controls::MenuItem* m_viewMenu;
MyMenuItems* m_menuItems;
MyTestMenuBar(Gwen::Controls::Base* pParent)
:Gwen::Controls::MenuStrip(pParent)
{
// Gwen::Controls::MenuStrip* menu = new Gwen::Controls::MenuStrip( pParent );
{
MyMenuItems* menuItems = new MyMenuItems;
m_menuItems = new MyMenuItems;
m_fileMenu = AddItem( L"File" );
m_fileMenu->GetMenu()->AddItem(L"Quit",menuItems,(Gwen::Event::Handler::Function)&MyMenuItems::myQuitApp);
m_fileMenu->GetMenu()->AddItem(L"Open",m_menuItems,(Gwen::Event::Handler::Function)&MyMenuItems::fileOpen);
m_fileMenu->GetMenu()->AddItem(L"Quit",m_menuItems,(Gwen::Event::Handler::Function)&MyMenuItems::myQuitApp);
m_viewMenu = AddItem( L"View" );
}
@@ -120,7 +133,7 @@ struct MyButtonHander :public Gwen::Event::Handler
void onButtonA( Gwen::Controls::Base* pControl )
{
Gwen::Controls::Button* but = (Gwen::Controls::Button*) pControl;
int dep = but->IsDepressed();
// int dep = but->IsDepressed();
int tog = but->GetToggleState();
if (m_data->m_toggleButtonCallback)
(*m_data->m_toggleButtonCallback)(m_buttonId,tog);
@@ -142,6 +155,11 @@ void GwenUserInterface::setStatusBarMessage(const char* message, bool isLeft)
}
}
void GwenUserInterface::registerFileOpenCallback(b3FileOpenCallback callback)
{
m_data->m_menuItems->m_fileOpenCallback = callback;
}
void GwenUserInterface::init(int width, int height,struct sth_stash* stash,float retinaScale)
{
m_data->m_curYposition = 20;
@@ -157,6 +175,10 @@ void GwenUserInterface::init(int width, int height,struct sth_stash* stash,float
MyTestMenuBar* menubar = new MyTestMenuBar(m_data->pCanvas);
m_data->m_viewMenu = menubar->m_viewMenu;
m_data->m_menuItems = menubar->m_menuItems;
Gwen::Controls::StatusBar* bar = new Gwen::Controls::StatusBar(m_data->pCanvas);
m_data->m_rightStatusBar = new Gwen::Controls::Label( bar );
m_data->m_rightStatusBar->SetWidth(width/2);

View File

@@ -5,7 +5,7 @@ struct GwenInternalData;
typedef void (*b3ComboBoxCallback) (int combobox, const char* item);
typedef void (*b3ToggleButtonCallback)(int button, int state);
typedef void (*b3FileOpenCallback)();
class GwenUserInterface
@@ -40,6 +40,8 @@ class GwenUserInterface
void setStatusBarMessage(const char* message, bool isLeft=true);
void registerFileOpenCallback(b3FileOpenCallback callback);
GwenInternalData* getInternalData()
{
return m_data;

View File

@@ -55,8 +55,8 @@ bool dump_timings = false;
int maxFrameCount = 102;
extern char OpenSansData[];
extern char* gPairBenchFileName;
extern float shadowMapWidth;
extern float shadowMapHeight;
extern int shadowMapWidth;
extern int shadowMapHeight;
extern bool gDebugLauncherCL;
extern bool gAllowCpuOpenCL;
extern bool gUseLargeBatches;
@@ -94,7 +94,8 @@ static int loadCurrentDemoEntry(const char* startFileName)
FILE* f = fopen(startFileName,"r");
if (f)
{
fscanf(f,"%d",&currentEntry);
int bytesScanned;
bytesScanned = fscanf(f,"%d",&currentEntry);
fclose(f);
}
return currentEntry;
@@ -534,7 +535,7 @@ FILE* defaultOutput = stdout;
void myprintf(const char* msg)
{
fprintf(defaultOutput,msg);
fprintf(defaultOutput,"%s",msg);
}
@@ -820,7 +821,7 @@ int main(int argc, char* argv[])
for (int i=0;i<nummsg;i++)
{
char txt[512];
sprintf(txt,msg[i]);
sprintf(txt,"%s",msg[i]);
//sth_draw_text(stash, droidRegular,i, 10, dy-spacing, txt, &dx,g_OpenGLWidth,g_OpenGLHeight);
sth_draw_text(stash, droidRegular,fontSize, 10, spacing, txt, &dx,g_OpenGLWidth,g_OpenGLHeight);
spacing+=fontSize;

View File

@@ -569,7 +569,7 @@ int b3BulletDataExtractor::createSphereShape( float radius, const Bullet3Seriali
int b3BulletDataExtractor::createPlaneShape( const Bullet3SerializeBullet2::b3Vector3FloatData& planeNormal, float planeConstant, const Bullet3SerializeBullet2::b3Vector3FloatData& localScaling)
{
printf("createPlaneShape with normal %f,%f,%f and planeConstant\n",planeNormal.m_floats[0], planeNormal.m_floats[1],planeNormal.m_floats[2],planeConstant);
printf("createPlaneShape with normal %f,%f,%f and planeConstant %f\n",planeNormal.m_floats[0], planeNormal.m_floats[1],planeNormal.m_floats[2],planeConstant);
return -1;
}

View File

@@ -218,7 +218,7 @@ void ConcaveScene::setupScene(const ConstructionInfo& ci)
//char* fileName = "teddy.obj";//"plane.obj";
// char* fileName = "sponza_closed.obj";//"plane.obj";
//char* fileName = "leoTest1.obj";
char* fileName = "samurai_monastry.obj";
const char* fileName = "samurai_monastry.obj";
// char* fileName = "teddy2_VHACD_CHs.obj";
b3Vector3 shift1=b3MakeVector3(0,0,0);//0,230,80);//150,-100,-120);
@@ -377,7 +377,7 @@ void ConcaveCompoundScene::setupScene(const ConstructionInfo& ci)
void ConcaveCompound2Scene::createDynamicObjects(const ConstructionInfo& ci)
{
char* fileName = "teddy2_VHACD_CHs.obj";
const char* fileName = "teddy2_VHACD_CHs.obj";
//char* fileName = "cube_offset.obj";

View File

@@ -28,7 +28,7 @@ static GLInstanceGraphicsShape* gCreateGraphicsShapeFromWavefrontObj(std::vector
// int numIndices = 0;
b3AlignedObjectArray<int>* indicesPtr = new b3AlignedObjectArray<int>;
for (int s=0;s<shapes.size();s++)
for (int s=0;s<(int)shapes.size();s++)
{
tinyobj::shape_t& shape = shapes[s];
int faceCount = shape.mesh.indices.size();
@@ -151,7 +151,7 @@ void ImportObjDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
btVector3 shift(0,0,0);
btVector3 scaling(1,1,1);
int index=10;
// int index=10;
{
@@ -172,7 +172,8 @@ void ImportObjDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
int shapeId = m_app->m_instancingRenderer->registerShape(&gfxShape->m_vertices->at(0).xyzw[0], gfxShape->m_numvertices, &gfxShape->m_indices->at(0), gfxShape->m_numIndices);
int id = m_app->m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
//int id =
m_app->m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
/*

View File

@@ -4,6 +4,7 @@
#include "OpenGLWindow/GLInstanceGraphicsShape.h"
#include "btBulletDynamicsCommon.h"
#include "OpenGLWindow/SimpleOpenGL3App.h"
#include "LoadMeshFromSTL.h"
ImportSTLDemo::ImportSTLDemo(SimpleOpenGL3App* app)
:m_app(app)
@@ -16,97 +17,6 @@ ImportSTLDemo::~ImportSTLDemo()
}
struct MySTLTriangle
{
float normal[3];
float vertex0[3];
float vertex1[3];
float vertex2[3];
};
GLInstanceGraphicsShape* LoadMeshFromSTL(const char* relativeFileName)
{
GLInstanceGraphicsShape* shape = 0;
FILE* file = fopen(relativeFileName,"rb");
if (file)
{
int size=0;
if (fseek(file, 0, SEEK_END) || (size = ftell(file)) == EOF || fseek(file, 0, SEEK_SET))
{
printf("Error: Cannot access file to determine size of %s\n", relativeFileName);
} else
{
if (size)
{
printf("Open STL file of %d bytes\n",size);
char* memoryBuffer = new char[size+1];
int actualBytesRead = fread(memoryBuffer,1,size,file);
if (actualBytesRead!=size)
{
printf("Error reading from file %s",relativeFileName);
} else
{
int numTriangles = *(int*)&memoryBuffer[80];
if (numTriangles)
{
shape = new GLInstanceGraphicsShape;
// b3AlignedObjectArray<GLInstanceVertex>* m_vertices;
// int m_numvertices;
// b3AlignedObjectArray<int>* m_indices;
// int m_numIndices;
// float m_scaling[4];
shape->m_scaling[0] = 1;
shape->m_scaling[1] = 1;
shape->m_scaling[2] = 1;
shape->m_scaling[3] = 1;
int index = 0;
shape->m_indices = new b3AlignedObjectArray<int>();
shape->m_vertices = new b3AlignedObjectArray<GLInstanceVertex>();
for (int i=0;i<numTriangles;i++)
{
char* curPtr = &memoryBuffer[84+i*50];
MySTLTriangle* tri = (MySTLTriangle*) curPtr;
GLInstanceVertex v0,v1,v2;
if (i==numTriangles-2)
{
printf("!\n");
}
v0.uv[0] = v1.uv[0] = v2.uv[0] = 0.5;
v0.uv[1] = v1.uv[1] = v2.uv[1] = 0.5;
for (int v=0;v<3;v++)
{
v0.xyzw[v] = tri->vertex0[v];
v1.xyzw[v] = tri->vertex1[v];
v2.xyzw[v] = tri->vertex2[v];
v0.normal[v] = v1.normal[v] = v2.normal[v] = tri->normal[v];
}
v0.xyzw[3] = v1.xyzw[3] = v2.xyzw[3] = 0.f;
shape->m_vertices->push_back(v0);
shape->m_vertices->push_back(v1);
shape->m_vertices->push_back(v2);
shape->m_indices->push_back(index++);
shape->m_indices->push_back(index++);
shape->m_indices->push_back(index++);
}
}
}
delete[] memoryBuffer;
}
}
fclose(file);
}
shape->m_numIndices = shape->m_indices->size();
shape->m_numvertices = shape->m_vertices->size();
return shape;
}
void ImportSTLDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
@@ -143,7 +53,7 @@ void ImportSTLDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
btVector3 shift(0,0,0);
btVector3 scaling(10,10,10);
int index=10;
// int index=10;
{
@@ -161,7 +71,8 @@ void ImportSTLDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
int shapeId = m_app->m_instancingRenderer->registerShape(&gfxShape->m_vertices->at(0).xyzw[0], gfxShape->m_numvertices, &gfxShape->m_indices->at(0), gfxShape->m_numIndices);
int id = m_app->m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
// int id =
m_app->m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling);
/*

View File

@@ -0,0 +1,101 @@
#ifndef LOAD_MESH_FROM_STL_H
#define LOAD_MESH_FROM_STL_H
#include "OpenGLWindow/GLInstanceGraphicsShape.h"
#include <stdio.h> //fopen
#include "Bullet3Common/b3AlignedObjectArray.h"
struct MySTLTriangle
{
float normal[3];
float vertex0[3];
float vertex1[3];
float vertex2[3];
};
static GLInstanceGraphicsShape* LoadMeshFromSTL(const char* relativeFileName)
{
GLInstanceGraphicsShape* shape = 0;
FILE* file = fopen(relativeFileName,"rb");
if (file)
{
int size=0;
if (fseek(file, 0, SEEK_END) || (size = ftell(file)) == EOF || fseek(file, 0, SEEK_SET))
{
printf("Error: Cannot access file to determine size of %s\n", relativeFileName);
} else
{
if (size)
{
printf("Open STL file of %d bytes\n",size);
char* memoryBuffer = new char[size+1];
int actualBytesRead = fread(memoryBuffer,1,size,file);
if (actualBytesRead!=size)
{
printf("Error reading from file %s",relativeFileName);
} else
{
int numTriangles = *(int*)&memoryBuffer[80];
if (numTriangles)
{
shape = new GLInstanceGraphicsShape;
// b3AlignedObjectArray<GLInstanceVertex>* m_vertices;
// int m_numvertices;
// b3AlignedObjectArray<int>* m_indices;
// int m_numIndices;
// float m_scaling[4];
shape->m_scaling[0] = 1;
shape->m_scaling[1] = 1;
shape->m_scaling[2] = 1;
shape->m_scaling[3] = 1;
int index = 0;
shape->m_indices = new b3AlignedObjectArray<int>();
shape->m_vertices = new b3AlignedObjectArray<GLInstanceVertex>();
for (int i=0;i<numTriangles;i++)
{
char* curPtr = &memoryBuffer[84+i*50];
MySTLTriangle* tri = (MySTLTriangle*) curPtr;
GLInstanceVertex v0,v1,v2;
if (i==numTriangles-2)
{
printf("!\n");
}
v0.uv[0] = v1.uv[0] = v2.uv[0] = 0.5;
v0.uv[1] = v1.uv[1] = v2.uv[1] = 0.5;
for (int v=0;v<3;v++)
{
v0.xyzw[v] = tri->vertex0[v];
v1.xyzw[v] = tri->vertex1[v];
v2.xyzw[v] = tri->vertex2[v];
v0.normal[v] = v1.normal[v] = v2.normal[v] = tri->normal[v];
}
v0.xyzw[3] = v1.xyzw[3] = v2.xyzw[3] = 0.f;
shape->m_vertices->push_back(v0);
shape->m_vertices->push_back(v1);
shape->m_vertices->push_back(v2);
shape->m_indices->push_back(index++);
shape->m_indices->push_back(index++);
shape->m_indices->push_back(index++);
}
}
}
delete[] memoryBuffer;
}
}
fclose(file);
}
shape->m_numIndices = shape->m_indices->size();
shape->m_numvertices = shape->m_vertices->size();
return shape;
}
#endif //LOAD_MESH_FROM_STL_H

View File

@@ -1,6 +1,9 @@
#include "ImportURDFSetup.h"
#include "BulletDynamics/ConstraintSolver/btGeneric6DofSpring2Constraint.h"
#include "Bullet3Common/b3FileUtils.h"
#include "../ImportSTLDemo/LoadMeshFromSTL.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
static int bodyCollisionFilterGroup=btBroadphaseProxy::CharacterFilter;
static int bodyCollisionFilterMask=btBroadphaseProxy::AllFilter&(~btBroadphaseProxy::CharacterFilter);
@@ -9,7 +12,7 @@ static bool enableConstraints = true;//false;
ImportUrdfDemo::ImportUrdfDemo()
{
sprintf(m_fileName,"r2d2.urdf");
}
ImportUrdfDemo::~ImportUrdfDemo()
@@ -18,7 +21,10 @@ ImportUrdfDemo::~ImportUrdfDemo()
}
void ImportUrdfDemo::setFileName(const char* urdfFileName)
{
memcpy(m_fileName,urdfFileName,strlen(urdfFileName)+1);
}
#include "urdf/urdfdom/urdf_parser/include/urdf_parser/urdf_parser.h"
@@ -59,6 +65,8 @@ void printTree(my_shared_ptr<const Link> link,int level = 0)
struct URDF_LinkInformation
{
const Link* m_thisLink;
int m_linkIndex;
int m_parentIndex;
btTransform m_localInertialFrame;
btTransform m_localVisualFrame;
@@ -80,62 +88,23 @@ struct URDF2BulletMappings
{
btHashMap<btHashPtr /*to Link*/, URDF_LinkInformation*> m_link2rigidbody;
btHashMap<btHashPtr /*to Joint*/, btTypedConstraint*> m_joint2Constraint;
btAlignedObjectArray<btTransform> m_linkLocalInertiaTransforms;//Body transform is in center of mass, aligned with Principal Moment Of Inertia;
btAlignedObjectArray<btScalar> m_linkMasses;
btAlignedObjectArray<btVector3> m_linkLocalDiagonalInertiaTensors;
btAlignedObjectArray<btTransform> m_jointTransforms;//for root, it is identity
btAlignedObjectArray<int> m_parentIndices;//for root, it is identity
btAlignedObjectArray<btVector3> m_jointAxisArray;
btAlignedObjectArray<btTransform> m_jointOffsetInParent;
btAlignedObjectArray<btTransform> m_jointOffsetInChild;
btAlignedObjectArray<int> m_jointTypeArray;
};
void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhysicsBridge& gfxBridge, const btTransform& parentTransformInWorldSpace, btDiscreteDynamicsWorld* world, URDF2BulletMappings& mappings)
btCollisionShape* convertVisualToCollisionShape(const Visual* visual, const char* pathPrefix)
{
btCollisionShape* shape = 0;
btTransform linkTransformInWorldSpace;
linkTransformInWorldSpace.setIdentity();
btScalar mass = 1;
btTransform inertialFrame;
inertialFrame.setIdentity();
const Link* parentLink = (*link).getParent();
URDF_LinkInformation* pp = 0;
{
URDF_LinkInformation** ppRigidBody = mappings.m_link2rigidbody.find(parentLink);
if (ppRigidBody)
{
pp = (*ppRigidBody);
btRigidBody* parentRigidBody = pp->m_bulletRigidBody;
btTransform tr = parentRigidBody->getWorldTransform();
printf("rigidbody origin (COM) of link(%s) parent(%s): %f,%f,%f\n",(*link).name.c_str(), parentLink->name.c_str(), tr.getOrigin().x(), tr.getOrigin().y(), tr.getOrigin().z());
}
}
if ((*link).inertial)
{
mass = (*link).inertial->mass;
inertialFrame.setOrigin(btVector3((*link).inertial->origin.position.x,(*link).inertial->origin.position.y,(*link).inertial->origin.position.z));
inertialFrame.setRotation(btQuaternion((*link).inertial->origin.rotation.x,(*link).inertial->origin.rotation.y,(*link).inertial->origin.rotation.z,(*link).inertial->origin.rotation.w));
}
btTransform parent2joint;
if ((*link).parent_joint)
{
btTransform p2j;
const urdf::Vector3 pos = (*link).parent_joint->parent_to_joint_origin_transform.position;
const urdf::Rotation orn = (*link).parent_joint->parent_to_joint_origin_transform.rotation;
parent2joint.setOrigin(btVector3(pos.x,pos.y,pos.z));
parent2joint.setRotation(btQuaternion(orn.x,orn.y,orn.z,orn.w));
linkTransformInWorldSpace =parentTransformInWorldSpace*parent2joint;
} else
{
linkTransformInWorldSpace = parentTransformInWorldSpace;
}
{
printf("converting link %s",link->name.c_str());
for (int v=0;v<link->visual_array.size();v++)
{
const Visual* visual = link->visual_array[v].get();
switch (visual->geometry->type)
{
case Geometry::CYLINDER:
@@ -171,21 +140,74 @@ void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhy
btVector3 extents(box->dim.x,box->dim.y,box->dim.z);
btBoxShape* boxShape = new btBoxShape(extents*0.5f);
shape = boxShape;
shape ->setMargin(0.001);
break;
}
case Geometry::SPHERE:
{
printf("processing a sphere\n");
urdf::Sphere* sphere = (urdf::Sphere*)visual->geometry.get();
btScalar radius = sphere->radius*0.8;
btScalar radius = sphere->radius;
btSphereShape* sphereShape = new btSphereShape(radius);
shape = sphereShape;
shape ->setMargin(0.001);
break;
break;
}
case Geometry::MESH:
{
if (visual->name.length())
{
printf("visual->name=%s\n",visual->name.c_str());
}
if (visual->geometry)
{
const urdf::Mesh* mesh = (const urdf::Mesh*) visual->geometry.get();
if (mesh->filename.length())
{
const char* filename = mesh->filename.c_str();
printf("mesh->filename=%s\n",filename);
char fullPath[1024];
sprintf(fullPath,"%s%s",pathPrefix,filename);
FILE* f = fopen(fullPath,"rb");
if (f)
{
fclose(f);
GLInstanceGraphicsShape* glmesh = LoadMeshFromSTL(fullPath);
if (glmesh && (glmesh->m_numvertices>0))
{
printf("extracted %d verticed from STL file %s\n", glmesh->m_numvertices,fullPath);
//int shapeId = m_glApp->m_instancingRenderer->registerShape(&gvertices[0].pos[0],gvertices.size(),&indices[0],indices.size());
//convex->setUserIndex(shapeId);
btAlignedObjectArray<btVector3> convertedVerts;
convertedVerts.reserve(glmesh->m_numvertices);
for (int i=0;i<glmesh->m_numvertices;i++)
{
convertedVerts.push_back(btVector3(glmesh->m_vertices->at(i).xyzw[0],glmesh->m_vertices->at(i).xyzw[1],glmesh->m_vertices->at(i).xyzw[2]));
}
//btConvexHullShape* cylZShape = new btConvexHullShape(&glmesh->m_vertices->at(0).xyzw[0], glmesh->m_numvertices, sizeof(GLInstanceVertex));
btConvexHullShape* cylZShape = new btConvexHullShape(&convertedVerts[0].getX(), convertedVerts.size(), sizeof(btVector3));
//cylZShape->initializePolyhedralFeatures();
//btVector3 halfExtents(cyl->radius,cyl->radius,cyl->length/2.);
//btCylinderShapeZ* cylZShape = new btCylinderShapeZ(halfExtents);
cylZShape->setMargin(0.001);
shape = cylZShape;
} else
{
printf("issue extracting mesh from STL file %s\n", fullPath);
}
} else
{
printf("mesh geometry not found %s\n",fullPath);
}
}
}
break;
}
default:
@@ -193,8 +215,313 @@ void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhy
printf("Error: unknown visual geometry type\n");
}
}
return shape;
}
btMultiBody* URDF2BulletMultiBody(my_shared_ptr<const Link> link, GraphicsPhysicsBridge& gfxBridge, const btTransform& parentTransformInWorldSpace, btMultiBodyDynamicsWorld* world, URDF2BulletMappings& mappings, const char* pathPrefix, btMultiBody* mb, int totalNumJoints)
{
btScalar mass = 0.f;
btTransform localInertialTransform; localInertialTransform.setIdentity();
btVector3 localInertiaDiagonal(0,0,0);
{
if ((*link).inertial)
{
mass = (*link).inertial->mass;
btMatrix3x3 inertiaMat;
inertiaMat.setIdentity();
inertiaMat.setValue(
(*link).inertial->ixx,(*link).inertial->ixy,(*link).inertial->ixz,
(*link).inertial->ixy,(*link).inertial->iyy,(*link).inertial->iyz,
(*link).inertial->ixz,(*link).inertial->iyz,(*link).inertial->izz);
btScalar threshold = 0.00001f;
int maxSteps=20;
btMatrix3x3 inertia2PrincipalAxis;
inertiaMat.diagonalize(inertia2PrincipalAxis,threshold,maxSteps);
localInertiaDiagonal.setValue(inertiaMat[0][0],inertiaMat[1][1],inertiaMat[2][2]);
btVector3 inertiaLocalCOM((*link).inertial->origin.position.x,(*link).inertial->origin.position.y,(*link).inertial->origin.position.z);
localInertialTransform.setOrigin(inertiaLocalCOM);
btQuaternion inertiaOrn((*link).inertial->origin.rotation.x,(*link).inertial->origin.rotation.y,(*link).inertial->origin.rotation.z,(*link).inertial->origin.rotation.w);
btMatrix3x3 inertiaOrnMat(inertiaOrn);
if (mass > 0 && (localInertiaDiagonal[0]==0.f || localInertiaDiagonal[1] == 0.f
|| localInertiaDiagonal[2] == 0.f))
{
b3Warning("Error: inertia should not be zero if mass is positive\n");
localInertiaDiagonal.setMax(btVector3(0.1,0.1,0.1));
localInertialTransform.setIdentity();//.setBasis(inertiaOrnMat);
}
else
{
localInertialTransform.setBasis(inertiaOrnMat*inertia2PrincipalAxis);
}
}
}
btTransform linkTransformInWorldSpace;
int parentIndex = -1;
const Link* parentLink = (*link).getParent();
if (parentLink)
{
parentIndex = parentLink->m_link_index;
btAssert(parentIndex>=0);
}
int linkIndex = mappings.m_linkMasses.size();
btTransform parent2joint;
if ((*link).parent_joint)
{
const urdf::Vector3 pos = (*link).parent_joint->parent_to_joint_origin_transform.position;
const urdf::Rotation orn = (*link).parent_joint->parent_to_joint_origin_transform.rotation;
parent2joint.setOrigin(btVector3(pos.x,pos.y,pos.z));
parent2joint.setRotation(btQuaternion(orn.x,orn.y,orn.z,orn.w));
linkTransformInWorldSpace =parentTransformInWorldSpace*parent2joint;
} else
{
linkTransformInWorldSpace = parentTransformInWorldSpace;
btAssert(mb==0);
bool multiDof = true;
bool canSleep = false;
bool isFixedBase = (mass==0);//todo: figure out when base is fixed
mb = new btMultiBody(totalNumJoints,mass, localInertiaDiagonal, isFixedBase, canSleep, multiDof);
}
btAssert(mb);
(*link).m_link_index = linkIndex;
//compute this links center of mass transform, aligned with the principal axis of inertia
{
//btTransform rigidBodyFrameInWorldSpace =linkTransformInWorldSpace*inertialFrame;
mappings.m_linkMasses.push_back(mass);
mappings.m_linkLocalDiagonalInertiaTensors.push_back(localInertiaDiagonal);
mappings.m_linkLocalInertiaTransforms.push_back(localInertialTransform);
if ((*link).parent_joint)
{
btTransform offsetInA,offsetInB;
offsetInA.setIdentity();
//offsetInA = mappings.m_linkLocalInertiaTransforms[parentIndex].inverse()*parent2joint;
offsetInA = parent2joint;
offsetInB.setIdentity();
//offsetInB = localInertialTransform.inverse();
const Joint* pj = (*link).parent_joint.get();
//btVector3 jointAxis(0,0,1);//pj->axis.x,pj->axis.y,pj->axis.z);
btVector3 jointAxis(pj->axis.x,pj->axis.y,pj->axis.z);
mappings.m_jointAxisArray.push_back(jointAxis);
mappings.m_jointOffsetInParent.push_back(offsetInA);
mappings.m_jointOffsetInChild.push_back(offsetInB);
mappings.m_jointTypeArray.push_back(pj->type);
switch (pj->type)
{
case Joint::FIXED:
{
printf("Fixed joint\n");
mb->setupFixed(linkIndex-1,mass,localInertiaDiagonal,parentIndex-1,offsetInA.getRotation(),offsetInA.getOrigin(),offsetInB.getOrigin());
break;
}
case Joint::CONTINUOUS:
case Joint::REVOLUTE:
{
printf("Revolute joint\n");
mb->setupRevolute(linkIndex-1,mass,localInertiaDiagonal,parentIndex-1,offsetInA.getRotation(),jointAxis,offsetInA.getOrigin(),offsetInB.getOrigin(),true);
mb->finalizeMultiDof();
//mb->setJointVel(linkIndex-1,1);
break;
}
case Joint::PRISMATIC:
{
mb->setupPrismatic(linkIndex-1,mass,localInertiaDiagonal,parentIndex-1,offsetInA.getRotation(),jointAxis,offsetInB.getOrigin(),true);
printf("Prismatic joint\n");
break;
}
default:
{
printf("Unknown joint\n");
btAssert(0);
}
};
} else
{
mappings.m_jointAxisArray.push_back(btVector3(0,0,0));
btTransform ident;
ident.setIdentity();
mappings.m_jointOffsetInParent.push_back(ident);
mappings.m_jointOffsetInChild.push_back(ident);
mappings.m_jointTypeArray.push_back(-1);
}
}
//btCompoundShape* compoundShape = new btCompoundShape();
btCollisionShape* shape = 0;
for (int v=0;v<(int)link->visual_array.size();v++)
{
const Visual* visual = link->visual_array[v].get();
shape = convertVisualToCollisionShape(visual,pathPrefix);
if (shape)//childShape)
{
gfxBridge.createCollisionShapeGraphicsObject(shape);//childShape);
btVector3 color(0,0,1);
if (visual->material.get())
{
color.setValue(visual->material->color.r,visual->material->color.g,visual->material->color.b);//,visual->material->color.a);
}
btVector3 localInertia(0,0,0);
if (mass)
{
shape->calculateLocalInertia(mass,localInertia);
}
//btRigidBody::btRigidBodyConstructionInfo rbci(mass,0,shape,localInertia);
btVector3 visual_pos(visual->origin.position.x,visual->origin.position.y,visual->origin.position.z);
btQuaternion visual_orn(visual->origin.rotation.x,visual->origin.rotation.y,visual->origin.rotation.z,visual->origin.rotation.w);
btTransform visual_frame;
visual_frame.setOrigin(visual_pos);
visual_frame.setRotation(visual_orn);
btTransform childTransform;
childTransform.setIdentity();//TODO(erwincoumans): compute relative visual/inertial transform
// compoundShape->addChildShape(childTransform,childShape);
}
}
if (shape)//compoundShape->getNumChildShapes()>0)
{
btMultiBodyLinkCollider* col= new btMultiBodyLinkCollider(mb, linkIndex-1);
col->setCollisionShape(shape);
btTransform tr;
tr.setIdentity();
tr = linkTransformInWorldSpace;
//if we don't set the initial pose of the btCollisionObject, the simulator will do this
//when syncing the btMultiBody link transforms to the btMultiBodyLinkCollider
//tr.setOrigin(local_origin[0]);
//tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3]));
col->setWorldTransform(tr);
bool isDynamic = true;
short collisionFilterGroup = isDynamic? short(btBroadphaseProxy::DefaultFilter) : short(btBroadphaseProxy::StaticFilter);
short collisionFilterMask = isDynamic? short(btBroadphaseProxy::AllFilter) : short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
world->addCollisionObject(col,collisionFilterGroup,collisionFilterMask);
btVector3 color(0.0,0.0,0.5);
gfxBridge.createCollisionObjectGraphicsObject(col,color);
btScalar friction = 0.5f;
col->setFriction(friction);
if (parentIndex>=0)
{
mb->getLink(linkIndex-1).m_collider=col;
} else
{
mb->setBaseCollider(col);
}
}
for (std::vector<my_shared_ptr<Link> >::const_iterator child = link->child_links.begin(); child != link->child_links.end(); child++)
{
if (*child)
{
URDF2BulletMultiBody(*child,gfxBridge, linkTransformInWorldSpace, world,mappings,pathPrefix,mb,totalNumJoints);
}
else
{
std::cout << "root link: " << link->name << " has a null child!" << *child << std::endl;
}
}
return mb;
}
void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhysicsBridge& gfxBridge, const btTransform& parentTransformInWorldSpace, btDiscreteDynamicsWorld* world, URDF2BulletMappings& mappings, const char* pathPrefix)
{
btCollisionShape* shape = 0;
btTransform linkTransformInWorldSpace;
linkTransformInWorldSpace.setIdentity();
btScalar mass = 1;
btTransform inertialFrame;
inertialFrame.setIdentity();
const Link* parentLink = (*link).getParent();
URDF_LinkInformation* pp = 0;
{
URDF_LinkInformation** ppRigidBody = mappings.m_link2rigidbody.find(parentLink);
if (ppRigidBody)
{
pp = (*ppRigidBody);
btRigidBody* parentRigidBody = pp->m_bulletRigidBody;
btTransform tr = parentRigidBody->getWorldTransform();
printf("rigidbody origin (COM) of link(%s) parent(%s): %f,%f,%f\n",(*link).name.c_str(), parentLink->name.c_str(), tr.getOrigin().x(), tr.getOrigin().y(), tr.getOrigin().z());
}
}
if ((*link).inertial)
{
mass = (*link).inertial->mass;
inertialFrame.setOrigin(btVector3((*link).inertial->origin.position.x,(*link).inertial->origin.position.y,(*link).inertial->origin.position.z));
inertialFrame.setRotation(btQuaternion((*link).inertial->origin.rotation.x,(*link).inertial->origin.rotation.y,(*link).inertial->origin.rotation.z,(*link).inertial->origin.rotation.w));
}
btTransform parent2joint;
parent2joint.setIdentity();
if ((*link).parent_joint)
{
const urdf::Vector3 pos = (*link).parent_joint->parent_to_joint_origin_transform.position;
const urdf::Rotation orn = (*link).parent_joint->parent_to_joint_origin_transform.rotation;
parent2joint.setOrigin(btVector3(pos.x,pos.y,pos.z));
parent2joint.setRotation(btQuaternion(orn.x,orn.y,orn.z,orn.w));
linkTransformInWorldSpace =parentTransformInWorldSpace*parent2joint;
} else
{
linkTransformInWorldSpace = parentTransformInWorldSpace;
}
{
printf("converting visuals of link %s",link->name.c_str());
for (int v=0;v<(int)link->visual_array.size();v++)
{
const Visual* visual = link->visual_array[v].get();
shape = convertVisualToCollisionShape(visual,pathPrefix);
if (shape)
{
@@ -241,25 +568,16 @@ void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhy
//create a joint if necessary
if ((*link).parent_joint)
{
btAssert(pp);
btRigidBody* parentBody =pp->m_bulletRigidBody;
const Joint* pj = (*link).parent_joint.get();
btTransform offsetInA,offsetInB;
btTransform p2j; p2j.setIdentity();
btVector3 p2jPos; p2jPos.setValue(pj->parent_to_joint_origin_transform.position.x,
pj->parent_to_joint_origin_transform.position.y,
pj->parent_to_joint_origin_transform.position.z);
btQuaternion p2jOrn;p2jOrn.setValue(pj->parent_to_joint_origin_transform.rotation.x,
pj->parent_to_joint_origin_transform.rotation.y,
pj->parent_to_joint_origin_transform.rotation.z,
pj->parent_to_joint_origin_transform.rotation.w);
p2j.setOrigin(p2jPos);
p2j.setRotation(p2jOrn);
offsetInA.setIdentity();
offsetInA = pp->m_localVisualFrame.inverse()*p2j;
offsetInA = pp->m_localVisualFrame.inverse()*parent2joint;
offsetInB.setIdentity();
offsetInB = visual_frame.inverse();
@@ -331,7 +649,7 @@ void URDFvisual2BulletCollisionShape(my_shared_ptr<const Link> link, GraphicsPhy
{
if (*child)
{
URDFvisual2BulletCollisionShape(*child,gfxBridge, linkTransformInWorldSpace, world,mappings);
URDFvisual2BulletCollisionShape(*child,gfxBridge, linkTransformInWorldSpace, world,mappings,pathPrefix);
}
else
@@ -353,9 +671,9 @@ void ImportUrdfDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
this->createEmptyDynamicsWorld();
gfxBridge.createPhysicsDebugDrawer(m_dynamicsWorld);
m_dynamicsWorld->getDebugDrawer()->setDebugMode(
//btIDebugDraw::DBG_DrawConstraints
btIDebugDraw::DBG_DrawConstraints
+btIDebugDraw::DBG_DrawContactPoints
//+btIDebugDraw::DBG_DrawAabb
+btIDebugDraw::DBG_DrawAabb
);//+btIDebugDraw::DBG_DrawConstraintLimits);
@@ -364,21 +682,31 @@ void ImportUrdfDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
gravity[upAxis]=-9.8;
m_dynamicsWorld->setGravity(gravity);
int argc=0;
char* filename="somefile.urdf";
//int argc=0;
char relativeFileName[1024];
b3FileUtils fu;
printf("m_fileName=%s\n", m_fileName);
bool fileFound = fu.findFile(m_fileName, relativeFileName, 1024);
std::string xml_string;
char pathPrefix[1024];
pathPrefix[0] = 0;
if (argc < 2){
std::cerr << "No URDF file name provided, using a dummy test URDF" << std::endl;
if (!fileFound){
std::cerr << "URDF file not found, using a dummy test URDF" << std::endl;
xml_string = std::string(urdf_char);
} else
{
int maxPathLen = 1024;
fu.extractPath(relativeFileName,pathPrefix,maxPathLen);
std::fstream xml_file(filename, std::fstream::in);
std::fstream xml_file(relativeFileName, std::fstream::in);
while ( xml_file.good() )
{
std::string line;
@@ -408,9 +736,45 @@ void ImportUrdfDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
btTransform worldTrans;
worldTrans.setIdentity();
int numJoints = (*robot).m_numJoints;
if (1)
{
URDF2BulletMappings mappings;
URDFvisual2BulletCollisionShape(root_link, gfxBridge, worldTrans,m_dynamicsWorld,mappings);
URDFvisual2BulletCollisionShape(root_link, gfxBridge, worldTrans,m_dynamicsWorld,mappings,pathPrefix);
}
//the btMultiBody support is work-in-progress :-)
if (0)
{
URDF2BulletMappings mappings;
btMultiBody* mb = URDF2BulletMultiBody(root_link, gfxBridge, worldTrans,m_dynamicsWorld,mappings,pathPrefix, 0,numJoints);
mb->setHasSelfCollision(false);
mb->finalizeMultiDof();
m_dynamicsWorld->addMultiBody(mb);
//m_dynamicsWorld->integrateTransforms(0.f);
}
printf("numJoints/DOFS = %d\n", numJoints);
if (0)
{
btVector3 halfExtents(1,1,1);
btBoxShape* box = new btBoxShape(halfExtents);
box->initializePolyhedralFeatures();
gfxBridge.createCollisionShapeGraphicsObject(box);
btTransform start; start.setIdentity();
btVector3 origin(0,0,0);
origin[upAxis]=5;
start.setOrigin(origin);
btRigidBody* body = createRigidBody(1,start,box);
btVector3 color(0.5,0.5,0.5);
gfxBridge.createRigidBodyGraphicsObject(body,color);
}
{
@@ -422,12 +786,23 @@ void ImportUrdfDemo::initPhysics(GraphicsPhysicsBridge& gfxBridge)
gfxBridge.createCollisionShapeGraphicsObject(box);
btTransform start; start.setIdentity();
btVector3 groundOrigin(0,0,0);
groundOrigin[upAxis]=-1.5;
groundOrigin[upAxis]=-2.5;
start.setOrigin(groundOrigin);
btRigidBody* body = createRigidBody(0,start,box);
//m_dynamicsWorld->removeRigidBody(body);
// m_dynamicsWorld->addRigidBody(body,2,1);
btVector3 color(0.5,0.5,0.5);
gfxBridge.createRigidBodyGraphicsObject(body,color);
}
}
void ImportUrdfDemo::stepSimulation(float deltaTime)
{
if (m_dynamicsWorld)
{
//the maximal coordinates/iterative MLCP solver requires a smallish timestep to converge
m_dynamicsWorld->stepSimulation(deltaTime,10,1./240.);
}
}

View File

@@ -2,15 +2,20 @@
#define IMPORT_URDF_SETUP_H
#include "../../Demos/CommonRigidBodySetup.h"
#include "../../Demos/CommonMultiBodySetup.h"
class ImportUrdfDemo : public CommonRigidBodySetup
class ImportUrdfDemo : public CommonMultiBodySetup
{
char m_fileName[1024];
public:
ImportUrdfDemo();
virtual ~ImportUrdfDemo();
virtual void initPhysics(GraphicsPhysicsBridge& gfxBridge);
virtual void stepSimulation(float deltaTime);
void setFileName(const char* urdfFileName);
};
#endif //IMPORT_URDF_SETUP_H

View File

@@ -27,7 +27,15 @@ ELSE(WIN32)
MESSAGE(${COCOA})
link_libraries(${COCOA})
ELSE(APPLE)
LINK_LIBRARIES( GLEW X11 pthread dl Xext)
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/btgui/OpenGLWindow/GlewWindows
)
ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1")
ADD_DEFINITIONS("-DGLEW_STATIC")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
LINK_LIBRARIES( X11 pthread dl Xext)
ENDIF(APPLE)
ENDIF(WIN32)

View File

@@ -11,15 +11,13 @@ int main(int argc, char* argv[])
{
b3CommandLineArgs myArgs(argc,argv);
float dt = 1./120.f;
SimpleOpenGL3App* app = new SimpleOpenGL3App("SimpleOpenGL3App",1024,768);
app->m_instancingRenderer->setCameraDistance(13);
app->m_instancingRenderer->setCameraPitch(0);
app->m_instancingRenderer->setCameraTargetPosition(b3MakeVector3(0,0,0));
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
myArgs.GetCmdLineArgument("mp4_file",gVideoFileName);
if (gVideoFileName)
@@ -40,8 +38,7 @@ int main(int argc, char* argv[])
app->dumpNextFrameToPng(fileName);
}
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
app->m_instancingRenderer->init();
app->m_instancingRenderer->updateCamera();

View File

@@ -21,6 +21,10 @@ struct MyGraphicsPhysicsBridge : public GraphicsPhysicsBridge
{
}
virtual void createRigidBodyGraphicsObject(btRigidBody* body, const btVector3& color)
{
createCollisionObjectGraphicsObject(body,color);
}
virtual void createCollisionObjectGraphicsObject(btCollisionObject* body, const btVector3& color)
{
btCollisionShape* shape = body->getCollisionShape();
btTransform startTransform = body->getWorldTransform();
@@ -32,6 +36,10 @@ struct MyGraphicsPhysicsBridge : public GraphicsPhysicsBridge
}
virtual void createCollisionShapeGraphicsObject(btCollisionShape* collisionShape)
{
//already has a graphics object?
if (collisionShape->getUserIndex()>=0)
return;
//todo: support all collision shape types
switch (collisionShape->getShapeType())
{

View File

@@ -1,7 +1,7 @@
#ifndef CONSTAINT_PHYSICS_SETUP_H
#define CONSTAINT_PHYSICS_SETUP_H
#include "../CommonRigidBodySetup.h"
#include "../../../Demos/CommonRigidBodySetup.h"
struct ConstraintPhysicsSetup : public CommonRigidBodySetup
{

View File

@@ -169,7 +169,7 @@ bool Bullet2MultiBodyDemo::mouseMoveCallback(float x,float y)
//keep it at the same picking distance
btVector3 newRayTo = getRayTo(x,y);
btVector3 rayFrom;
btVector3 oldPivotInB = pickCon->getPivotInB();
// btVector3 oldPivotInB = pickCon->getPivotInB();
btVector3 newPivotB;
m_glApp->m_instancingRenderer->getCameraPosition(rayFrom);
btVector3 dir = newRayTo-rayFrom;
@@ -186,7 +186,7 @@ bool Bullet2MultiBodyDemo::mouseMoveCallback(float x,float y)
btVector3 newRayTo = getRayTo(x,y);
btVector3 rayFrom;
btVector3 oldPivotInB = m_pickingMultiBodyPoint2Point->getPivotInB();
// btVector3 oldPivotInB = m_pickingMultiBodyPoint2Point->getPivotInB();
btVector3 newPivotB;
btVector3 camPos;
m_glApp->m_instancingRenderer->getCameraPosition(camPos);
@@ -438,7 +438,7 @@ btMultiBody* FeatherstoneDemo1::createFeatherstoneMultiBody(class btMultiBodyDyn
btVector4 halfExtents(7.5,0.45,4.5,1);
{
float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
// float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
float quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()};
@@ -484,7 +484,7 @@ btMultiBody* FeatherstoneDemo1::createFeatherstoneMultiBody(class btMultiBodyDyn
{
btVector3 posr = local_origin[i+1];
float pos[4]={posr.x(),posr.y(),posr.z(),1};
//float pos[4]={posr.x(),posr.y(),posr.z(),1};
float quat[4]={-world_to_local[i+1].x(),-world_to_local[i+1].y(),-world_to_local[i+1].z(),world_to_local[i+1].w()};
@@ -531,8 +531,8 @@ void FeatherstoneDemo1::createGround()
{
//create ground
int cubeShapeId = m_glApp->registerCubeShape();
float pos[]={0,0,0};
float orn[]={0,0,0,1};
//float pos[]={0,0,0};
//float orn[]={0,0,0,1};
{
@@ -575,7 +575,8 @@ void FeatherstoneDemo1::initPhysics()
settings.m_isFixedBase = false;
settings.m_basePosition.setValue(0,10,0);
settings.m_numLinks = 10;
btMultiBody* mb = createFeatherstoneMultiBody(m_dynamicsWorld,settings);
//btMultiBody* mb =
createFeatherstoneMultiBody(m_dynamicsWorld,settings);
m_glApp->m_instancingRenderer->writeTransforms();
@@ -727,7 +728,7 @@ class RagDoll2
hull->buildHull(0.01);
{
int strideInBytes = 9*sizeof(float);
// int strideInBytes = 9*sizeof(float);
int numVertices = hull->numVertices();
int numIndices =hull->numIndices();
@@ -988,7 +989,7 @@ public:
virtual ~RagDoll2 ()
{
int i;
//int i;
/*
// Remove all constraints
for ( i = 0; i < JOINT_COUNT; ++i)
@@ -1027,8 +1028,8 @@ void FeatherstoneDemo2::initPhysics()
settings.m_usePrismatic = true;
btMultiBody* mb = createFeatherstoneMultiBody(m_dynamicsWorld,settings);
*/
btVector3 offset(0,2,0);
RagDoll2* doll = new RagDoll2(m_dynamicsWorld,offset,m_glApp);
// btVector3 offset(0,2,0);
//RagDoll2* doll = new RagDoll2(m_dynamicsWorld,offset,m_glApp);
m_glApp->m_instancingRenderer->writeTransforms();

View File

@@ -307,7 +307,7 @@ void MultiDofDemo::addColliders_testMultiDof(btMultiBody *pMultiBody, btMultiBod
{
float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
// float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
float quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()};
@@ -348,7 +348,7 @@ void MultiDofDemo::addColliders_testMultiDof(btMultiBody *pMultiBody, btMultiBod
{
btVector3 posr = local_origin[i+1];
float pos[4]={posr.x(),posr.y(),posr.z(),1};
// float pos[4]={posr.x(),posr.y(),posr.z(),1};
float quat[4]={-world_to_local[i+1].x(),-world_to_local[i+1].y(),-world_to_local[i+1].z(),world_to_local[i+1].w()};

View File

@@ -14,7 +14,7 @@ extern "C" {
}
char* sLuaFileName = "init_physics.lua";
const char* sLuaFileName = "init_physics.lua";
static const float scaling=0.35f;
static LuaPhysicsSetup* sLuaDemo = 0;

View File

@@ -0,0 +1,251 @@
//test addJointTorque
#include "TestJointTorqueSetup.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
TestJointTorqueSetup::TestJointTorqueSetup()
{
}
TestJointTorqueSetup::~TestJointTorqueSetup()
{
}
void TestJointTorqueSetup::initPhysics(GraphicsPhysicsBridge& gfxBridge)
{
int upAxis = 2;
btVector4 colors[4] =
{
btVector4(1,0,0,1),
btVector4(0,1,0,1),
btVector4(0,1,1,1),
btVector4(1,1,0,1),
};
int curColor = 0;
gfxBridge.setUpAxis(upAxis);
this->createEmptyDynamicsWorld();
gfxBridge.createPhysicsDebugDrawer(m_dynamicsWorld);
m_dynamicsWorld->getDebugDrawer()->setDebugMode(
//btIDebugDraw::DBG_DrawConstraints
+btIDebugDraw::DBG_DrawWireframe
+btIDebugDraw::DBG_DrawContactPoints
+btIDebugDraw::DBG_DrawAabb
);//+btIDebugDraw::DBG_DrawConstraintLimits);
//create a static ground object
if (0)
{
btVector3 groundHalfExtents(20,20,20);
groundHalfExtents[upAxis]=1.f;
btBoxShape* box = new btBoxShape(groundHalfExtents);
box->initializePolyhedralFeatures();
gfxBridge.createCollisionShapeGraphicsObject(box);
btTransform start; start.setIdentity();
btVector3 groundOrigin(0,0,0);
groundOrigin[upAxis]=-1.5;
start.setOrigin(groundOrigin);
btRigidBody* body = createRigidBody(0,start,box);
btVector4 color = colors[curColor];
curColor++;
curColor&=3;
gfxBridge.createRigidBodyGraphicsObject(body,color);
}
{
bool floating = false;
bool damping = true;
bool gyro = true;
int numLinks = 5;
bool spherical = false; //set it ot false -to use 1DoF hinges instead of 3DoF sphericals
bool canSleep = false;
bool selfCollide = false;
btVector3 linkHalfExtents(0.05, 0.37, 0.1);
btVector3 baseHalfExtents(0.05, 0.37, 0.1);
btVector3 basePosition = btVector3(-0.4f, 3.f, 0.f);
//mbC->forceMultiDof(); //if !spherical, you can comment this line to check the 1DoF algorithm
//init the base
btVector3 baseInertiaDiag(0.f, 0.f, 0.f);
float baseMass = 1.f;
if(baseMass)
{
btCollisionShape *pTempBox = new btBoxShape(btVector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
pTempBox->calculateLocalInertia(baseMass, baseInertiaDiag);
delete pTempBox;
}
bool isMultiDof = false;
btMultiBody *pMultiBody = new btMultiBody(numLinks, baseMass, baseInertiaDiag, !floating, canSleep, isMultiDof);
m_multiBody = pMultiBody;
btQuaternion baseOriQuat(0.f, 0.f, 0.f, 1.f);
pMultiBody->setBasePos(basePosition);
pMultiBody->setWorldToBaseRot(baseOriQuat);
btVector3 vel(0, 0, 0);
// pMultiBody->setBaseVel(vel);
//init the links
btVector3 hingeJointAxis(1, 0, 0);
float linkMass = 1.f;
btVector3 linkInertiaDiag(0.f, 0.f, 0.f);
btCollisionShape *pTempBox = new btBoxShape(btVector3(linkHalfExtents[0], linkHalfExtents[1], linkHalfExtents[2]));
pTempBox->calculateLocalInertia(linkMass, linkInertiaDiag);
delete pTempBox;
//y-axis assumed up
btVector3 parentComToCurrentCom(0, -linkHalfExtents[1] * 2.f, 0); //par body's COM to cur body's COM offset
btVector3 currentPivotToCurrentCom(0, -linkHalfExtents[1], 0); //cur body's COM to cur body's PIV offset
btVector3 parentComToCurrentPivot = parentComToCurrentCom - currentPivotToCurrentCom; //par body's COM to cur body's PIV offset
//////
btScalar q0 = 0.f * SIMD_PI/ 180.f;
btQuaternion quat0(btVector3(0, 1, 0).normalized(), q0);
quat0.normalize();
/////
for(int i = 0; i < numLinks; ++i)
{
if(!spherical)
pMultiBody->setupRevolute(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), hingeJointAxis, parentComToCurrentPivot, currentPivotToCurrentCom, false);
else
//pMultiBody->setupPlanar(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f)/*quat0*/, btVector3(1, 0, 0), parentComToCurrentPivot*2, false);
pMultiBody->setupSpherical(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), parentComToCurrentPivot, currentPivotToCurrentCom, false);
}
//pMultiBody->finalizeMultiDof();
btMultiBodyDynamicsWorld* world = m_dynamicsWorld;
///
world->addMultiBody(pMultiBody);
btMultiBody* mbC = pMultiBody;
mbC->setCanSleep(canSleep);
mbC->setHasSelfCollision(selfCollide);
mbC->setUseGyroTerm(gyro);
//
if(!damping)
{
mbC->setLinearDamping(0.f);
mbC->setAngularDamping(0.f);
}else
{ mbC->setLinearDamping(0.1f);
mbC->setAngularDamping(0.9f);
}
//
btVector3 gravity(0,0,0);
//gravity[upAxis] = -9.81;
m_dynamicsWorld->setGravity(gravity);
//////////////////////////////////////////////
if(numLinks > 0)
{
btScalar q0 = 45.f * SIMD_PI/ 180.f;
if(!spherical)
if(mbC->isMultiDof())
mbC->setJointPosMultiDof(0, &q0);
else
mbC->setJointPos(0, q0);
else
{
btQuaternion quat0(btVector3(1, 1, 0).normalized(), q0);
quat0.normalize();
mbC->setJointPosMultiDof(0, quat0);
}
}
///
btAlignedObjectArray<btQuaternion> world_to_local;
world_to_local.resize(pMultiBody->getNumLinks() + 1);
btAlignedObjectArray<btVector3> local_origin;
local_origin.resize(pMultiBody->getNumLinks() + 1);
world_to_local[0] = pMultiBody->getWorldToBaseRot();
local_origin[0] = pMultiBody->getBasePos();
double friction = 1;
{
// float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
float quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()};
if (1)
{
btCollisionShape* box = new btBoxShape(baseHalfExtents);
gfxBridge.createCollisionShapeGraphicsObject(box);
btMultiBodyLinkCollider* col= new btMultiBodyLinkCollider(pMultiBody, -1);
col->setCollisionShape(box);
btTransform tr;
tr.setIdentity();
//if we don't set the initial pose of the btCollisionObject, the simulator will do this
//when syncing the btMultiBody link transforms to the btMultiBodyLinkCollider
tr.setOrigin(local_origin[0]);
tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3]));
col->setWorldTransform(tr);
world->addCollisionObject(col, 2,1+2);
btVector3 color(0.0,0.0,0.5);
gfxBridge.createCollisionObjectGraphicsObject(col,color);
col->setFriction(friction);
pMultiBody->setBaseCollider(col);
}
}
for (int i=0; i < pMultiBody->getNumLinks(); ++i)
{
const int parent = pMultiBody->getParent(i);
world_to_local[i+1] = pMultiBody->getParentToLocalRot(i) * world_to_local[parent+1];
local_origin[i+1] = local_origin[parent+1] + (quatRotate(world_to_local[i+1].inverse() , pMultiBody->getRVector(i)));
}
for (int i=0; i < pMultiBody->getNumLinks(); ++i)
{
btVector3 posr = local_origin[i+1];
// float pos[4]={posr.x(),posr.y(),posr.z(),1};
float quat[4]={-world_to_local[i+1].x(),-world_to_local[i+1].y(),-world_to_local[i+1].z(),world_to_local[i+1].w()};
btCollisionShape* box = new btBoxShape(linkHalfExtents);
gfxBridge.createCollisionShapeGraphicsObject(box);
btMultiBodyLinkCollider* col = new btMultiBodyLinkCollider(pMultiBody, i);
col->setCollisionShape(box);
btTransform tr;
tr.setIdentity();
tr.setOrigin(posr);
tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3]));
col->setWorldTransform(tr);
col->setFriction(friction);
world->addCollisionObject(col,2,1+2);
btVector4 color = colors[curColor];
curColor++;
curColor&=3;
gfxBridge.createCollisionObjectGraphicsObject(col,color);
pMultiBody->getLink(i).m_collider=col;
}
}
}
void TestJointTorqueSetup::stepSimulation(float deltaTime)
{
m_multiBody->addJointTorque(0, 10.0);
m_dynamicsWorld->stepSimulation(deltaTime);
}

View File

@@ -0,0 +1,21 @@
#ifndef TEST_JOINT_TORQUE_SETUP_H
#define TEST_JOINT_TORQUE_SETUP_H
#include "../../../Demos/CommonMultiBodySetup.h"
struct TestJointTorqueSetup : public CommonMultiBodySetup
{
btMultiBody* m_multiBody;
public:
TestJointTorqueSetup();
virtual ~TestJointTorqueSetup();
virtual void initPhysics(GraphicsPhysicsBridge& gfxBridge);
virtual void stepSimulation(float deltaTime);
};
#endif //TEST_JOINT_TORQUE_SETUP_H

View File

@@ -197,10 +197,46 @@ btCollisionShape* btWorldImporter::convertCollisionShape( btCollisionShapeData*
}
break;
}
//The btCapsuleShape* API has issue passing the margin/scaling/halfextents unmodified through the API
//so deal with this
case CAPSULE_SHAPE_PROXYTYPE:
{
btCapsuleShapeData* capData = (btCapsuleShapeData*)shapeData;
switch (capData->m_upAxis)
{
case 0:
{
shape = createCapsuleShapeX(1,1);
break;
}
case 1:
{
shape = createCapsuleShapeY(1,1);
break;
}
case 2:
{
shape = createCapsuleShapeZ(1,1);
break;
}
default:
{
printf("error: wrong up axis for btCapsuleShape\n");
}
};
if (shape)
{
btCapsuleShape* cap = (btCapsuleShape*) shape;
cap->deSerializeFloat(capData);
}
break;
}
case CYLINDER_SHAPE_PROXYTYPE:
case CONE_SHAPE_PROXYTYPE:
case CAPSULE_SHAPE_PROXYTYPE:
case BOX_SHAPE_PROXYTYPE:
case SPHERE_SHAPE_PROXYTYPE:
case MULTI_SPHERE_SHAPE_PROXYTYPE:
@@ -227,36 +263,7 @@ btCollisionShape* btWorldImporter::convertCollisionShape( btCollisionShapeData*
shape = createSphereShape(implicitShapeDimensions.getX());
break;
}
case CAPSULE_SHAPE_PROXYTYPE:
{
btCapsuleShapeData* capData = (btCapsuleShapeData*)shapeData;
switch (capData->m_upAxis)
{
case 0:
{
shape = createCapsuleShapeX(implicitShapeDimensions.getY()+bsd->m_collisionMargin*2,2*implicitShapeDimensions.getX());
break;
}
case 1:
{
shape = createCapsuleShapeY(implicitShapeDimensions.getX()+bsd->m_collisionMargin*2,2*implicitShapeDimensions.getY());
break;
}
case 2:
{
shape = createCapsuleShapeZ(implicitShapeDimensions.getX()+bsd->m_collisionMargin*2,2*implicitShapeDimensions.getZ());
break;
}
default:
{
printf("error: wrong up axis for btCapsuleShape\n");
}
bsd->m_collisionMargin = 0.f;
};
break;
}
case CYLINDER_SHAPE_PROXYTYPE:
{
btCylinderShapeData* cylData = (btCylinderShapeData*) shapeData;

View File

@@ -1,3 +1,5 @@
[![Travis Build Status](https://api.travis-ci.org/bulletphysics/bullet3.png?branch=master)](https://travis-ci.org/bulletphysics/bullet3)
[![Appveyor Build status](https://ci.appveyor.com/api/projects/status/6sly9uxajr6xsstq)](https://ci.appveyor.com/project/erwincoumans/bullet3)
Bullet 3.x GPU rigid body pipeline using OpenCL.

9
appveyor.yml Normal file
View File

@@ -0,0 +1,9 @@
build:
project: build3/vs2010/0_Bullet3Solution.sln
before_build:
- echo %CD%
- ps: cd build3
- echo %CD%
- premake4 vs2010
- ps: cd ..

View File

@@ -112,7 +112,7 @@ void CrossSplitter::Layout( Skin::Base* /*skin*/ )
else
{
//This should probably use Fill docking instead
m_Sections[m_iZoomedSection]->SetBounds( 0, 0, Width(), Height() );
m_Sections[(int)m_iZoomedSection]->SetBounds( 0, 0, Width(), Height() );
}
}

View File

@@ -23,7 +23,7 @@ void Resizer::OnMouseMoved( int x, int y, int /*deltaX*/, int /*deltaY*/ )
if ( !m_pTarget ) return;
if ( !m_bDepressed ) return;
Gwen::Rect oldBounds = m_pTarget->GetBounds();
// Gwen::Rect oldBounds = m_pTarget->GetBounds();
Gwen::Rect pBounds = m_pTarget->GetBounds();
Gwen::Point pntMin = m_pTarget->GetMinimumSize();

View File

@@ -134,8 +134,14 @@ void ScrollControl::UpdateScrollBars()
m_InnerPanel->SetSize( Utility::Max(Width(), childrenWidth), Utility::Max(Height(), childrenHeight));
float wPercent = (float)Width() / (float)(childrenWidth + (m_VerticalScrollBar->Hidden() ? 0 : m_VerticalScrollBar->Width()));
float hPercent = (float)Height() / (float)(childrenHeight + (m_HorizontalScrollBar->Hidden() ? 0 : m_HorizontalScrollBar->Height()));
float hg = (float)(childrenWidth + (m_VerticalScrollBar->Hidden() ? 0 : m_VerticalScrollBar->Width()));
if (hg==0.f)
hg = 0.00001f;
float wPercent = (float)Width() / hg;
hg = (float)(childrenHeight + (m_HorizontalScrollBar->Hidden() ? 0 : m_HorizontalScrollBar->Height()));
if (hg==0.f)
hg = 0.00001f;
float hPercent = (float)Height() / hg;
if ( m_bCanScrollV )
SetVScrollRequired( hPercent >= 1 );

View File

@@ -101,12 +101,12 @@ bool TreeControl::OnKeyUp( bool bDown )
if (bDown)
{
ForceUpdateScrollBars();
int maxIndex = 0;
// int maxIndex = 0;
int newIndex = 0;
int maxItem=0;
int curItem=-1;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX,&maxItem,&curItem);
maxIndex = maxItem;
// maxIndex = maxItem;
int targetItem = curItem;
if (curItem>0)
{
@@ -121,15 +121,17 @@ bool TreeControl::OnKeyUp( bool bDown )
iterate(ITERATE_ACTION_DESELECT_INDEX,&maxItem,&deselectIndex);
}
curItem = newIndex;
float amount = float(newIndex)/float(maxIndex);
// float amount = float(newIndex)/float(maxIndex);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
float minCoordViewableWindow = curAmount*contSize;
float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
// float minCoordViewableWindow = curAmount*contSize;
//float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem*16.f;
float maxCoordSelectedItem = (curItem+1)*16.f;
// float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize!=viewSize)
{
{
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
@@ -148,6 +150,7 @@ bool TreeControl::OnKeyUp( bool bDown )
}
}
}
}
return true;
}
@@ -157,12 +160,12 @@ bool TreeControl::OnKeyDown( bool bDown )
if (bDown)
{
ForceUpdateScrollBars();
int maxIndex = 0;
// int maxIndex = 0;
int newIndex = 0;
int maxItem=0;
int curItem=-1;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX,&maxItem,&curItem);
maxIndex = maxItem;
// maxIndex = maxItem;
int targetItem = curItem;
if (curItem>=0)
{
@@ -177,15 +180,17 @@ bool TreeControl::OnKeyDown( bool bDown )
iterate(ITERATE_ACTION_DESELECT_INDEX,&maxItem,&deselectIndex);
}
curItem= newIndex;
float amount = (int)float(newIndex)/float(maxIndex);
// float amount = (int)float(newIndex)/float(maxIndex);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
float minCoordViewableWindow = curAmount*contSize;
float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
// float minCoordViewableWindow = curAmount*contSize;
//float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem*16.f;
float maxCoordSelectedItem = (curItem+1)*16.f;
//float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize!=viewSize)
{
{
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
@@ -204,6 +209,7 @@ bool TreeControl::OnKeyDown( bool bDown )
}
}
}
}
return true;
}
extern int avoidUpdate;
@@ -219,15 +225,17 @@ bool TreeControl::OnKeyRight( bool bDown )
int maxItem=0;
int curItem=0;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX,&maxItem,&curItem);
float amount = float(curItem)/float(maxItem);
// float amount = float(curItem)/float(maxItem);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
float minCoordViewableWindow = curAmount*contSize;
float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
// float minCoordViewableWindow = curAmount*contSize;
// float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem*16.f;
float maxCoordSelectedItem = (curItem+1)*16.f;
// float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize!=viewSize)
{
{
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
@@ -244,6 +252,7 @@ bool TreeControl::OnKeyRight( bool bDown )
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount,true);
}
}
}
Invalidate();
}
return true;
@@ -262,18 +271,19 @@ bool TreeControl::OnKeyLeft( bool bDown )
int maxItems=0;
int curItem=0;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX,&maxItems,&curItem);
float amount = float(curItem)/float(maxItems);
// float amount = float(curItem)/float(maxItems);
// m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(amount,true);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
float minCoordViewableWindow = curAmount*contSize;
float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
// float minCoordViewableWindow = curAmount*contSize;
// float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem*16.f;
float maxCoordSelectedItem = (curItem+1)*16.f;
// float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize!=viewSize)
{
{
float newAmount = float(minCoordSelectedItem)/(contSize-viewSize);
if (newAmount<curAmount)
@@ -291,6 +301,7 @@ bool TreeControl::OnKeyLeft( bool bDown )
}
Invalidate();
}
}
//viewSize/contSize
printf("!\n");

View File

@@ -73,7 +73,7 @@ void TreeNode::Render( Skin::Base* skin )
TreeNode* TreeNode::AddNode( const UnicodeString& strLabel )
{
int sz = sizeof(TreeNode);
// int sz = sizeof(TreeNode);
TreeNode* node = new TreeNode( this );
node->SetText( strLabel );
node->Dock( Pos::Top );
@@ -231,7 +231,7 @@ void TreeNode::iterate(int action, int* curIndex, int* targetIndex)
Gwen::String name = Gwen::Utility::UnicodeToString(m_Title->GetText());
int actualIndex = curIndex? *curIndex : -1;
// int actualIndex = curIndex? *curIndex : -1;
//printf("iterated over item %d with name = %s\n", actualIndex, name.c_str());
if (action==ITERATE_ACTION_SELECT)

View File

@@ -164,7 +164,7 @@ namespace Gwen
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
GLenum format = GL_RGB;
//GLenum format = GL_RGB;
unsigned char* texdata = new unsigned char[256*256*4];
for (int i=0;i<256*256;i++)
{
@@ -316,11 +316,11 @@ namespace Gwen
Gwen::String converted_string = Gwen::Utility::UnicodeToString( text );
float yOffset=0.0f;
for ( int i=0; i<text.length(); i++ )
for ( int i=0; i<(int)text.length(); i++ )
{
wchar_t chr = text[i];
// wchar_t chr = text[i];
char ch = converted_string[i];
float curSpacing = sGwenDebugFontSpacing[ch] * m_fLetterSpacing * fSize * m_fFontScale[0];
float curSpacing = sGwenDebugFontSpacing[(int)ch] * m_fLetterSpacing * fSize * m_fFontScale[0];
Gwen::Rect r( pos.x + yOffset, pos.y-fSize*0.2f, (fSize * m_fFontScale[0]), fSize * m_fFontScale[1] );
if ( m_pFontTexture )
@@ -390,10 +390,10 @@ namespace Gwen
Gwen::String converted_string = Gwen::Utility::UnicodeToString( text );
float spacing = 0.0f;
for ( int i=0; i<text.length(); i++ )
for ( int i=0; i<(int)text.length(); i++ )
{
char ch = converted_string[i];
spacing += sGwenDebugFontSpacing[ch];
spacing += sGwenDebugFontSpacing[(int)ch];
}
p.x = spacing*m_fLetterSpacing*fSize * m_fFontScale[0];

View File

@@ -78,7 +78,7 @@ namespace Gwen
m_Render->DrawLinedRect( control->GetRenderBounds() );
}
Gwen::Rect rect = control->GetRenderBounds();
// Gwen::Rect rect = control->GetRenderBounds();
if ( bChecked )
{
m_Render->SetDrawColor( Color( 0, 0, 0, 255) );
@@ -490,7 +490,7 @@ namespace Gwen
virtual void DrawSlider( Gwen::Controls::Base* control, bool bIsHorizontal, int numNotches, int barSize)
{
Gwen::Rect rect = control->GetRenderBounds();
Gwen::Rect notchRect = rect;
// Gwen::Rect notchRect = rect;
if ( bIsHorizontal )
{

View File

@@ -219,7 +219,7 @@ int sth_add_font(struct sth_stash* stash, const char* path)
FILE* fp = 0;
int datasize;
unsigned char* data = NULL;
int idx;
int idx=0;
// Read in the font data.
fp = fopen(path, "rb");
@@ -229,11 +229,16 @@ int sth_add_font(struct sth_stash* stash, const char* path)
fseek(fp,0,SEEK_SET);
data = (unsigned char*)malloc(datasize);
if (data == NULL) goto error;
fread(data, 1, datasize, fp);
int bytesRead;
bytesRead = fread(data, 1, datasize, fp);
if (bytesRead)
{
idx = sth_add_font_from_memory(stash, data);
}
fclose(fp);
fp = 0;
idx = sth_add_font_from_memory(stash, data);
// Modify type of the loaded font.
if (idx)
stash->fonts->type = TTFONT_FILE;

View File

@@ -37,8 +37,7 @@ InternalOpenGL2RenderCallbacks::~InternalOpenGL2RenderCallbacks()
void InternalOpenGL2RenderCallbacks::display2()
{
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
// glViewport(0,0,10,10);
//const float timeScale = 0.008f;
@@ -48,39 +47,31 @@ void InternalOpenGL2RenderCallbacks::display2()
glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer);
glBindVertexArray(s_vertexArrayObject);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
// glBindTexture(GL_TEXTURE_2D,m_texturehandle);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
vec2 p( 0.f,0.f);//?b?0.5f * sinf(timeValue), 0.5f * cosf(timeValue) );
glUniform2fv(data->m_positionUniform, 1, (const GLfloat *)&p);
err = glGetError();
assert(err==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(data->m_positionAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(data->m_colourAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(data->m_textureAttribute);
glVertexAttribPointer(data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)0);
glVertexAttribPointer(data->m_colourAttribute , 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)sizeof(vec4));
glVertexAttribPointer(data->m_textureAttribute , 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)(sizeof(vec4)+sizeof(vec4)));
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
/*
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer);
@@ -101,10 +92,7 @@ void InternalOpenGL2RenderCallbacks::display2()
void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_glyph* glyph, int textureWidth, int textureHeight)
{
GLint err;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
if (glyph)
@@ -114,13 +102,11 @@ void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_gly
glBindTexture(GL_TEXTURE_2D, *gltexture);
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 0, GL_RED, GL_UNSIGNED_BYTE, texture->m_texels);
GLenum err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
} else
{
@@ -132,8 +118,7 @@ void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_gly
//create new texture
glGenTextures(1, texId);
GLenum err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
@@ -143,8 +128,7 @@ void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_gly
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 0, GL_RED, GL_UNSIGNED_BYTE, texture->m_texels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
////////////////////////////
//create the other data
@@ -155,8 +139,7 @@ void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_gly
glGenBuffers(1, &s_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, VERT_COUNT * sizeof(Vertex), texture->newverts, GL_DYNAMIC_DRAW);
GLuint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
for (int i=0;i<INDEX_COUNT;i++)
{
@@ -167,8 +150,7 @@ void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_gly
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s_indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,INDEX_COUNT*sizeof(int), s_indexData,GL_STATIC_DRAW);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}
} else
{
@@ -196,13 +178,10 @@ void InternalOpenGL2RenderCallbacks::render(sth_texture* texture)
GLuint* texId = (GLuint*) texture->m_userData;
GLint err;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindTexture(GL_TEXTURE_2D, *texId);
bool useFiltering = false;
@@ -215,25 +194,21 @@ void InternalOpenGL2RenderCallbacks::render(sth_texture* texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer);
glBindVertexArray(s_vertexArrayObject);
glBufferData(GL_ARRAY_BUFFER, texture->nverts * sizeof(Vertex), &texture->newverts[0].position.p[0], GL_DYNAMIC_DRAW);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s_indexBuffer);
//glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
int indexCount = texture->nverts;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindVertexArray(0);

View File

@@ -32,7 +32,14 @@ ENDIF(APPLE)
#no Linux detection?
IF(NOT WIN32 AND NOT APPLE)
SET(OpenGLWindow_SRCS ${OpenGLWindowLinux_CPP} ${OpenGLWindowCommon_CPP} )
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/btgui/OpenGLWindow/GlewWindows
)
ADD_DEFINITIONS(-DGLEW_STATIC)
ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
SET(OpenGLWindow_SRCS ${OpenGLWindowLinux_CPP} ${BULLET_PHYSICS_SOURCE_DIR}/btgui/OpenGLWindow/GlewWindows/glew.c ${OpenGLWindowCommon_CPP} )
ENDIF()

View File

@@ -16,8 +16,8 @@ subject to the following restrictions:
///todo: make this configurable in the gui
bool useShadowMap=true;//false;//true;
float shadowMapWidth=8192;
float shadowMapHeight=8192;
int shadowMapWidth=8192;
int shadowMapHeight=8192;
float shadowMapWorldSize=100;
float WHEEL_MULTIPLIER=0.01f;
float MOUSE_MOVE_MULTIPLIER = 0.4f;

View File

@@ -131,8 +131,8 @@ void GLPrimitiveRenderer::loadBufferData()
glGenBuffers(1, &m_data->m_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_data->m_vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(Vertex), vertexData, GL_DYNAMIC_DRAW);
GLuint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
@@ -142,16 +142,14 @@ void GLPrimitiveRenderer::loadBufferData()
glEnableVertexAttribArray(m_data->m_positionAttribute);
glEnableVertexAttribArray(m_data->m_colourAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_textureAttribute);
glVertexAttribPointer(m_data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)0);
glVertexAttribPointer(m_data->m_colourAttribute , 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)sizeof(vec4));
glVertexAttribPointer(m_data->m_textureAttribute , 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)(sizeof(vec4)+sizeof(vec4)));
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
@@ -191,8 +189,7 @@ void GLPrimitiveRenderer::loadBufferData()
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256,256,0,GL_RGB,GL_UNSIGNED_BYTE,image);
glGenerateMipmap(GL_TEXTURE_2D);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
delete[] image;
@@ -217,36 +214,25 @@ void GLPrimitiveRenderer::drawLine()
void GLPrimitiveRenderer::drawRect(float x0, float y0, float x1, float y1, float color[4])
{
GLint err;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindTexture(GL_TEXTURE_2D,m_data->m_texturehandle);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
drawTexturedRect(x0,y0,x1,y1,color,0,0,1,1);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}
void GLPrimitiveRenderer::drawTexturedRect(float x0, float y0, float x1, float y1, float color[4], float u0,float v0, float u1, float v1, int useRGBA)
{
GLint err;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glUseProgram(m_data->m_shaderProg);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, m_data->m_vertexBuffer);
glBindVertexArray(m_data->m_vertexArrayObject);
@@ -263,10 +249,10 @@ void GLPrimitiveRenderer::drawTexturedRect(float x0, float y0, float x1, float y
}
Vertex vertexData[4] = {
{ vec4(-1.+2.*x0/float(m_screenWidth), 1.-2.*y0/float(m_screenHeight), 0, 0 ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u0,v0)},
{ vec4(-1.+2.*x0/float(m_screenWidth), 1.-2.*y1/float(m_screenHeight), 0, 1 ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u0,v1)},
{ vec4( -1.+2.*x1/float(m_screenWidth), 1.-2.*y1/float(m_screenHeight), 1, 1 ), vec4(color[0], color[1], color[2], color[3]) ,vec2(u1,v1)},
{ vec4( -1.+2.*x1/float(m_screenWidth), 1.-2.*y0/float(m_screenHeight), 1, 0 ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u1,v0)}
{ vec4(-1.f+2.f*x0/float(m_screenWidth), 1.f-2.f*y0/float(m_screenHeight), 0.f, 0.f ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u0,v0)},
{ vec4(-1.f+2.f*x0/float(m_screenWidth), 1.f-2.f*y1/float(m_screenHeight), 0.f, 1.f ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u0,v1)},
{ vec4( -1.f+2.f*x1/float(m_screenWidth), 1.f-2.f*y1/float(m_screenHeight), 1.f, 1.f ), vec4(color[0], color[1], color[2], color[3]) ,vec2(u1,v1)},
{ vec4( -1.f+2.f*x1/float(m_screenWidth), 1.f-2.f*y0/float(m_screenHeight), 1.f, 0.f ), vec4( color[0], color[1], color[2], color[3] ) ,vec2(u1,v0)}
};
glBufferSubData(GL_ARRAY_BUFFER, 0,4 * sizeof(Vertex), vertexData);
@@ -276,8 +262,7 @@ void GLPrimitiveRenderer::drawTexturedRect(float x0, float y0, float x1, float y
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
vec2 p( 0.f,0.f);//?b?0.5f * sinf(timeValue), 0.5f * cosf(timeValue) );
if (useRGBA)
@@ -290,60 +275,47 @@ void GLPrimitiveRenderer::drawTexturedRect(float x0, float y0, float x1, float y
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_positionAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_colourAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_textureAttribute);
glVertexAttribPointer(m_data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)0);
glVertexAttribPointer(m_data->m_colourAttribute , 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)sizeof(vec4));
glVertexAttribPointer(m_data->m_textureAttribute , 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)(sizeof(vec4)+sizeof(vec4)));
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_data->m_indexBuffer);
//glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
int indexCount = 6;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindVertexArray(0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
//glDisableVertexAttribArray(m_data->m_textureAttribute);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glUseProgram(0);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}

View File

@@ -119,55 +119,37 @@ public:
{
m_yOffset=0;
glEnable(GL_BLEND);
GLint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glDisable(GL_DEPTH_TEST);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
//glColor4ub(255,0,0,255);
err = glGetError();
assert(err==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
// saveOpenGLState(width,height);//m_glutScreenWidth,m_glutScreenHeight);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
err = glGetError();
assert(err==GL_NO_ERROR);
glEnable(GL_BLEND);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}
virtual void End()
{
@@ -375,10 +357,7 @@ public:
glBindTexture(GL_TEXTURE_2D,texHandle);
// glDisable(GL_DEPTH_TEST);
GLint err;
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
/* bool useFiltering = true;
@@ -406,8 +385,8 @@ public:
m_primitiveRenderer->drawTexturedRect(rect.x, rect.y+m_yOffset, rect.x+rect.w, rect.y+rect.h+m_yOffset, color,0+add,0,1+add,1,true);
err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
}

View File

@@ -18,8 +18,7 @@ void gltLoadShaderSrc(const char *szShaderSrc, GLuint shader)
GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
{
GLuint err = glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
// Temporary Shader objects
GLuint hVertexShader;
@@ -36,7 +35,7 @@ GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
// Compile them
glCompileShader(hVertexShader);
err = glGetError();
assert(glGetError()==GL_NO_ERROR);
glGetShaderiv(hVertexShader, GL_COMPILE_STATUS, &testVal);
if(testVal == GL_FALSE)
@@ -51,10 +50,10 @@ GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
return (GLuint)NULL;
}
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
glCompileShader(hFragmentShader);
err = glGetError();
assert(glGetError()==GL_NO_ERROR);
glGetShaderiv(hFragmentShader, GL_COMPILE_STATUS, &testVal);
if(testVal == GL_FALSE)
@@ -69,7 +68,7 @@ GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
return (GLuint)NULL;
}
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
// Check for errors

View File

@@ -81,7 +81,7 @@ public:
virtual void setWindowTitle(const char* title);
int fileOpenDialog(char* filename, int maxNameLength);
};

View File

@@ -989,8 +989,48 @@ void MacOpenGLWindow::setRequestExit()
m_internalData->m_exitRequested = true;
}
#include <string.h>
int MacOpenGLWindow::fileOpenDialog(char* filename, int maxNameLength)
{
//save/restore the OpenGL context, NSOpenPanel can mess it up
//http://stackoverflow.com/questions/13987148/nsopenpanel-breaks-my-sdl-opengl-app
NSOpenGLContext *foo = [NSOpenGLContext currentContext];
// get the url of a .txt file
NSOpenPanel * zOpenPanel = [NSOpenPanel openPanel];
NSArray * zAryOfExtensions = [NSArray arrayWithObject:@"urdf"];
[zOpenPanel setAllowedFileTypes:zAryOfExtensions];
NSInteger zIntResult = [zOpenPanel runModal];
[foo makeCurrentContext];
if (zIntResult == NSFileHandlingPanelCancelButton) {
NSLog(@"readUsingOpenPanel cancelled");
return 0;
}
NSURL *zUrl = [zOpenPanel URL];
if (zUrl)
{
//without the file://
NSString *myString = [zUrl absoluteString];
int slen = [myString length];
if (slen < maxNameLength)
{
const char *cfilename=[myString UTF8String];
//expect file:// at start of URL
const char* p = strstr(cfilename, "file://");
if (p==cfilename)
{
int actualLen = strlen(cfilename)-7;
memcpy(filename, cfilename+7,actualLen);
filename[actualLen]=0;
return actualLen;
}
}
}
return 0;
}

View File

@@ -430,19 +430,17 @@ static void writeTextureToFile(int textureWidth, int textureHeight, const char*
{
int numComponents = 4;
//glPixelStorei(GL_PACK_ALIGNMENT,1);
GLuint err=glGetError();
assert(err==GL_NO_ERROR);
b3Assert(glGetError()==GL_NO_ERROR);
//glReadBuffer(GL_BACK);//COLOR_ATTACHMENT0);
err=glGetError();
assert(err==GL_NO_ERROR);
float* orgPixels = (float*)malloc(textureWidth*textureHeight*numComponents*4);
glReadPixels(0,0,textureWidth, textureHeight, GL_RGBA, GL_FLOAT, orgPixels);
//it is useful to have the actual float values for debugging purposes
//convert float->char
char* pixels = (char*)malloc(textureWidth*textureHeight*numComponents);
err=glGetError();
assert(err==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
for (int j=0;j<textureHeight;j++)
{

View File

@@ -137,6 +137,40 @@ void Win32OpenGLWindow::endRendering()
}
int Win32OpenGLWindow::fileOpenDialog(char* fileName, int maxFileNameLength)
{
//wchar_t wideChars[1024];
OPENFILENAME ofn ;
ZeroMemory( &ofn , sizeof( ofn));
ofn.lStructSize = sizeof ( ofn );
ofn.hwndOwner = NULL ;
#ifdef UNICODE
WCHAR bla[1024];
ofn.lpstrFile = bla;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = 1023;
ofn.lpstrFilter = L"URDF\0*.urdf\0";
#else
ofn.lpstrFile = fileName;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = 1023;
//ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.lpstrFilter = "URDF\0*.urdf\0";
#endif
ofn.nFilterIndex =1;
ofn.lpstrFileTitle = NULL ;
ofn.nMaxFileTitle = 0 ;
ofn.lpstrInitialDir=NULL ;
ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST ;
GetOpenFileName( &ofn );
return strlen(fileName);
//return 0;
}

View File

@@ -51,6 +51,8 @@ public:
virtual void endRendering();
virtual float getRetinaScale() const {return 1.f;}
virtual int fileOpenDialog(char* fileName, int maxFileNameLength);
};

View File

@@ -29,7 +29,34 @@
#include <pthread.h>
GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
GLint att[] = { GLX_RGBA,
GLX_DEPTH_SIZE, 24,
GLX_RED_SIZE , 8,
GLX_GREEN_SIZE , 8,
GLX_BLUE_SIZE , 8,
GLX_ALPHA_SIZE , 8,
GLX_STENCIL_SIZE , 8,
GLX_DOUBLEBUFFER,
None };
/*
static int att[] =
{
GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None
GLX_X_RENDERABLE , True,
GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT,
GLX_RENDER_TYPE , GLX_RGBA_BIT,
GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR,
GLX_RED_SIZE , 8,
GLX_GREEN_SIZE , 8,
GLX_BLUE_SIZE , 8,
GLX_ALPHA_SIZE , 8,
GLX_DEPTH_SIZE , 24,
GLX_STENCIL_SIZE , 8,
GLX_DOUBLEBUFFER , True,
None
};
*/
static bool forceOpenGL3 = true;
@@ -37,6 +64,7 @@ static bool forceOpenGL3 = true;
#ifdef DYNAMIC_LOAD_X11_FUNCTIONS
///our X11 function typedefs
typedef int (*PFNXFREE)(void*);
typedef XErrorHandler (* PFNXSETERRORHANDLER) (XErrorHandler);
typedef int (* PFNXSYNC) (Display* a,Bool b);
@@ -47,9 +75,13 @@ typedef int (*PFNXMAPWINDOW) (Display*, Window);
typedef int (*PFNXSTORENAME) (Display* a,Window b,_Xconst char* c);
typedef int (*PFNXCLOSEDISPLAY) (Display* a);
typedef int (*PFNXDESTROYWINDOW) (Display* a,Window b);
typedef int (*PFNXRAISEWINDOW) (Display* a, Window b);
#if NeedWidePrototypes
typedef KeySym* (*PFNXGETKEYBOARDMAPPING) (Display*,unsigned int,int,int*);
typedef KeySym (*PFNXKEYCODETOKEYSYM) (Display* a,unsigned int b,int c);
#else
typedef KeySym* (*PFNXGETKEYBOARDMAPPING) (Display*,KeyCode,int,int*);
typedef KeySym (*PFNXKEYCODETOKEYSYM) (Display* a,KeyCode b,int c);
#endif
typedef void (*PFNXCONVERTCASE) (KeySym /* sym */,KeySym * /* lower */,KeySym * /* upper */);
@@ -63,6 +95,7 @@ typedef Status (*PFNXGETWINDOWATTRIBUTES) (Display* a,Window b,XWindowAttributes
#define X11_LIBRARY "libX11.so.6"
#define MyXSync m_data->m_x11_XSync
#define MyXGetKeyboardMapping m_data->m_x11_XGetKeyboardMapping
#define MyXSetErrorHandler m_data->m_x11_XSetErrorHandler
#define MyXOpenDisplay m_data->m_x11_XOpenDisplay
#define MyXCreateColormap m_data->m_x11_XCreateColormap
@@ -70,6 +103,7 @@ typedef Status (*PFNXGETWINDOWATTRIBUTES) (Display* a,Window b,XWindowAttributes
#define MyXMapWindow m_data->m_x11_XMapWindow
#define MyXStoreName m_data->m_x11_XStoreName
#define MyXDestroyWindow m_data->m_x11_XDestroyWindow
#define MyXRaiseWindow m_data->m_x11_XRaiseWindow
#define MyXCloseDisplay m_data->m_x11_XCloseDisplay
#define MyXKeycodeToKeysym m_data->m_x11_XKeycodeToKeysym
#define MyXConvertCase m_data->m_x11_XConvertCase
@@ -87,6 +121,7 @@ typedef Status (*PFNXGETWINDOWATTRIBUTES) (Display* a,Window b,XWindowAttributes
#else
#define MyXSync XSync
#define MyXGetKeyboardMapping XGetKeyboardMapping
#define MyXSetErrorHandler XSetErrorHandler
#define MyXOpenDisplay XOpenDisplay
#define MyXCreateColormap XCreateColormap
@@ -94,6 +129,7 @@ typedef Status (*PFNXGETWINDOWATTRIBUTES) (Display* a,Window b,XWindowAttributes
#define MyXMapWindow XMapWindow
#define MyXStoreName XStoreName
#define MyXDestroyWindow XDestroyWindow
#define MyXRaiseWindow XRaiseWindow
#define MyXCloseDisplay XCloseDisplay
#define MyXKeycodeToKeysym XKeycodeToKeysym
#define MyXConvertCase XConvertCase
@@ -136,7 +172,9 @@ struct InternalData2
PFNXSTORENAME m_x11_XStoreName;
PFNXCLOSEDISPLAY m_x11_XCloseDisplay;
PFNXDESTROYWINDOW m_x11_XDestroyWindow;
PFNXRAISEWINDOW m_x11_XRaiseWindow;
PFNXKEYCODETOKEYSYM m_x11_XKeycodeToKeysym;
PFNXGETKEYBOARDMAPPING m_x11_XGetKeyboardMapping;
PFNXCONVERTCASE m_x11_XConvertCase;
PFNXPENDING m_x11_XPending;
PFNXNEXTEVENT m_x11_XNextEvent;
@@ -190,13 +228,15 @@ struct InternalData2
if (missingFunc) { printf("Error: missing func XMapWindow in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XStoreName = (PFNXSTORENAME) dlsym(m_x11_library,"XStoreName"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XStoreName in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XCloseDisplay = (PFNXCLOSEDISPLAY) dlsym(m_x11_library,"XCloseDisplay"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XCloseDisplay in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XDestroyWindow = (PFNXDESTROYWINDOW) dlsym(m_x11_library,"XDestroyWindow"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XMapWindow in %s, exiting!\n", X11_LIBRARY); exit(0);}
if (missingFunc) { printf("Error: missing func XDestroyWindow in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XRaiseWindow = (PFNXRAISEWINDOW) dlsym(m_x11_library,"XRaiseWindow"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XRaiseWindow in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XGetKeyboardMapping = (PFNXGETKEYBOARDMAPPING) dlsym(m_x11_library,"XGetKeyboardMapping"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XGetKeyboardMapping in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XKeycodeToKeysym = (PFNXKEYCODETOKEYSYM) dlsym(m_x11_library,"XKeycodeToKeysym"))==NULL) | missingFunc;
if (missingFunc) { printf("Error: missing func XKeycodeToKeysym in %s, exiting!\n", X11_LIBRARY); exit(0);}
missingFunc = ((m_x11_XConvertCase = (PFNXCONVERTCASE) dlsym(m_x11_library,"XConvertCase"))==NULL) | missingFunc;
@@ -612,9 +652,21 @@ void X11OpenGLWindow::closeWindow()
int X11OpenGLWindow::getAsciiCodeFromVirtualKeycode(int keycode)
{
int result = 0;
KeySym key, key_lc, key_uc;
key = MyXKeycodeToKeysym( m_data->m_dpy, keycode, 0 );
int keysyms_per_keycode_return;
KeySym *keysym = MyXGetKeyboardMapping(m_data->m_dpy,
keycode,
1,
&keysyms_per_keycode_return);
key = keysym[0];
//key = MyXKeycodeToKeysym( m_data->m_dpy, keycode, 0 );
switch( key )
{
case XK_Escape: return B3G_ESCAPE;
@@ -660,9 +712,12 @@ int X11OpenGLWindow::getAsciiCodeFromVirtualKeycode(int keycode)
{
return (int) key;
}
return -1;
result = -1;
}
return 0;
MyXFree(keysym);
return result;
}
void X11OpenGLWindow::pumpMessage()
@@ -913,4 +968,29 @@ b3KeyboardCallback X11OpenGLWindow::getKeyboardCallback()
{
return m_data->m_keyboardCallback;
}
#include <stdio.h>
int X11OpenGLWindow::fileOpenDialog(char* filename, int maxNameLength)
{
int len = 0;
FILE * output = popen("zenity --file-selection --file-filter=\"*.urdf\" --file-filter=\"*.*\"","r");
if (output)
{
while( fgets(filename, maxNameLength-1, output) != NULL )
{
len=strlen(filename);
if (len>0)
{
filename[len-1]=0;
printf("file open (length=%d) = %s\n", len,filename);
}
}
pclose(output);
} else
{
printf("Error: fileOpenDialog no popen output, perhaps install zenity?\n");
}
MyXRaiseWindow(m_data->m_dpy, m_data->m_win);
return len;
}

View File

@@ -59,6 +59,7 @@ public:
virtual void setWindowTitle(const char* title);
int fileOpenDialog(char* filename, int maxNameLength);
};

View File

@@ -110,6 +110,8 @@ class b3gWindowInterface
virtual float getRetinaScale() const =0;
virtual int fileOpenDialog(char* fileName, int maxFileNameLength) = 0;
};
#endif //B3G_WINDOW_INTERFACE_H

View File

@@ -5,9 +5,15 @@
--flags {}
defines { "LUA_COMPAT_ALL"}
if os.is("Linux") then
defines {"LUA_USE_LINUX"}
end
if os.is("MacOSX") then
defines {"LUA_USE_MACOSX"}
end
targetdir "../../lib"
includedirs {
"src"

View File

@@ -115,6 +115,7 @@ static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
#if defined(LUA_USE_DLOPEN)
/*
** {========================================================================
** This is an implementation of loadlib based on the dlfcn interface.

View File

@@ -42,8 +42,8 @@
#if defined(LUA_USE_LINUX)
#define LUA_USE_POSIX
#define LUA_USE_DLOPEN /* needs an extra library: -ldl */
#define LUA_USE_READLINE /* needs some extra libraries */
//#define LUA_USE_DLOPEN /* needs an extra library: -ldl */
//#define LUA_USE_READLINE /* needs some extra libraries */
#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */
#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
#define LUA_USE_LONGLONG /* assume support for long long */
@@ -51,8 +51,8 @@
#if defined(LUA_USE_MACOSX)
#define LUA_USE_POSIX
#define LUA_USE_DLOPEN /* does not need -ldl */
#define LUA_USE_READLINE /* needs an extra library: -lreadline */
//#define LUA_USE_DLOPEN /* does not need -ldl */
//#define LUA_USE_READLINE /* needs an extra library: -lreadline */
#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */
#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
#define LUA_USE_LONGLONG /* assume support for long long */

View File

@@ -26,6 +26,8 @@
http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong
Encryption is not supported.
*/
#define NOCRYPT
#define NOUNCRYPT
#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))

View File

@@ -116,6 +116,7 @@ my_shared_ptr<ModelInterface> parseURDF(const std::string &xml_string)
{
my_shared_ptr<Link> link;
link.reset(new Link);
model->m_numLinks++;
try {
parseLink(*link, link_xml);
@@ -176,6 +177,7 @@ my_shared_ptr<ModelInterface> parseURDF(const std::string &xml_string)
{
my_shared_ptr<Joint> joint;
joint.reset(new Joint);
model->m_numJoints++;
if (parseJoint(*joint, joint_xml))
{

View File

@@ -223,6 +223,8 @@ public:
std::vector<my_shared_ptr<Joint> > child_joints;
std::vector<my_shared_ptr<Link> > child_links;
mutable int m_link_index;
const Link* getParent() const
{return parent_link_;}
@@ -242,6 +244,8 @@ public:
this->child_links.clear();
this->collision_array.clear();
this->visual_array.clear();
this->m_link_index=-1;
this->parent_link_ = NULL;
};
private:

View File

@@ -41,7 +41,7 @@
#include <map>
//#include <boost/function.hpp>
#include <urdf/urdfdom_headers/urdf_model/include/urdf_model/link.h>
#include <stdio.h> //printf
#include <urdf/urdfdom_headers/urdf_exception/include/urdf_exception/exception.h>
namespace urdf {
@@ -82,6 +82,8 @@ public:
void clear()
{
m_numLinks=0;
m_numJoints = 0;
name_.clear();
this->links_.clear();
this->joints_.clear();
@@ -132,6 +134,7 @@ public:
this->getLink(child_link_name, child_link);
if (!child_link)
{
printf("Error: child link [%s] of joint [%s] not found\n", child_link_name.c_str(),joint->first.c_str() );
assert(0);
// throw ParseError("child link [" + child_link_name + "] of joint [" + joint->first + "] not found");
}
@@ -206,6 +209,8 @@ public:
/// \brief The root is always a link (the parent of the tree describing the robot)
my_shared_ptr<Link> root_link_;
int m_numLinks;//includes parent
int m_numJoints;
};

View File

@@ -1,3 +1,4 @@
function findOpenGL()
configuration{}
if os.is("Linux") then
@@ -7,6 +8,22 @@
return true
end
function findOpenGL3()
configuration{}
if os.is("MacOSX") then
local osversion = os.getversion()
--Mac OSX 10.9 and above supports OpenGL 3, below doesn't, so ...
if osversion.majorversion > 10 or (osversion.majorversion == 10 and osversion.minorversion >=9) then
return findOpenGL()
else
return false
end
else
return findOpenGL()
end
end
function initOpenGL()
configuration {}
configuration {"Windows"}

View File

@@ -1,6 +1,12 @@
solution "0_Bullet3Solution"
local osversion = os.getversion()
print(string.format(" %d.%d.%d (%s)",
osversion.majorversion, osversion.minorversion, osversion.revision,
osversion.description))
-- Multithreaded compiling
if _ACTION == "vs2010" or _ACTION=="vs2008" then
buildoptions { "/MP" }
@@ -35,8 +41,8 @@
newoption
{
trigger = "bullet2gpu",
description = "Enable Bullet 2.x GPU using b3GpuDynamicsWorld bridge to Bullet 3.x"
trigger = "bullet2demos",
description = "Compile the Bullet 2 demos (Demo/Extra folder)"
}
newoption
@@ -113,13 +119,12 @@
include "../test/TestBullet3OpenCL"
end
if findOpenGL() then
if findOpenGL3() then
include "../Demos3/AllBullet2Demos"
include "../Demos3/GpuDemos"
include"../Demos3/BasicDemoConsole"
include"../Demos3/BasicDemoCustomOpenGL2"
include "../btgui/OpenGLTrueTypeFont"
-- include "../Demos3/CpuDemos"
-- include "../Demos3/Wavefront"
@@ -137,6 +142,7 @@ if findOpenGL() then
include "../btgui/GwenOpenGLTest"
end
-- include "../demo/gpudemo"
if _OPTIONS["midi"] then
include "../btgui/MidiTest"
@@ -169,7 +175,7 @@ end
-- include "../demo/gpu_initialize"
-- include "../opencl/lds_bank_conflict"
-- include "../opencl/reduce"
include "../btgui/OpenGLTrueTypeFont"
-- include "../btgui/OpenGLTrueTypeFont"
-- include "../btgui/OpenGLWindow"
-- include "../demo/ObjLoader"
-- include "../test/b3DynamicBvhBroadphase"
@@ -180,7 +186,10 @@ end
include "../test/enet/client"
end
if _OPTIONS["bullet2gpu"] then
if _OPTIONS["bullet2demos"] then
include "../Extras"
if findOpenGL() then
include "../Demos"
end
end

414
data/r2d2.urdf Normal file
View File

@@ -0,0 +1,414 @@
<?xml version="1.0"?>
<robot name="physics">
<link name="base_link">
<visual>
<geometry>
<cylinder length="0.6" radius="0.2"/>
</geometry>
<material name="blue">
<color rgba="0 0 .8 1"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length="0.6" radius="0.2"/>
</geometry>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<link name="right_leg">
<visual>
<geometry>
<box size="0.6 .2 .1"/>
</geometry>
<origin rpy="0 1.57075 0" xyz="0 0 -0.3"/>
<material name="white">
<color rgba="1 1 1 1"/>
</material>
</visual>
<collision>
<geometry>
<box size="0.6 .2 .1"/>
</geometry>
<origin rpy="0 1.57075 0" xyz="0 0 -0.3"/>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="base_to_right_leg" type="fixed">
<parent link="base_link"/>
<child link="right_leg"/>
<origin xyz="0.22 0 .25"/>
</joint>
<link name="right_base">
<visual>
<geometry>
<box size=".1 0.4 .1"/>
</geometry>
<material name="white"/>
</visual>
<collision>
<geometry>
<box size=".1 0.4 .1"/>
</geometry>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_base_joint" type="fixed">
<parent link="right_leg"/>
<child link="right_base"/>
<origin xyz="0 0 -0.6"/>
</joint>
<link name="right_front_wheel">
<visual>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
<material name="black">
<color rgba="0 0 0 1"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
</collision>
<inertial>
<mass value="1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_front_wheel_joint" type="continuous">
<axis xyz="0 0 1"/>
<parent link="right_base"/>
<child link="right_front_wheel"/>
<origin rpy="0 1.57075 0" xyz="0 0.133333333333 -0.085"/>
<limit effort="100" velocity="100"/>
<joint_properties damping="0.0" friction="0.0"/>
</joint>
<link name="right_back_wheel">
<visual>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
<material name="black"/>
</visual>
<collision>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
</collision>
<inertial>
<mass value="1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_back_wheel_joint" type="continuous">
<axis xyz="0 0 1"/>
<parent link="right_base"/>
<child link="right_back_wheel"/>
<origin rpy="0 1.57075 0" xyz="0 -0.133333333333 -0.085"/>
<limit effort="100" velocity="100"/>
<joint_properties damping="0.0" friction="0.0"/>
</joint>
<link name="left_leg">
<visual>
<geometry>
<box size="0.6 .2 .1"/>
</geometry>
<origin rpy="0 1.57075 0" xyz="0 0 -0.3"/>
<material name="white"/>
</visual>
<collision>
<geometry>
<box size="0.6 .2 .1"/>
</geometry>
<origin rpy="0 1.57075 0" xyz="0 0 -0.3"/>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="base_to_left_leg" type="fixed">
<parent link="base_link"/>
<child link="left_leg"/>
<origin xyz="-0.22 0 .25"/>
</joint>
<link name="left_base">
<visual>
<geometry>
<box size=".1 0.4 .1"/>
</geometry>
<material name="white"/>
</visual>
<collision>
<geometry>
<box size=".1 0.4 .1"/>
</geometry>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_base_joint" type="fixed">
<parent link="left_leg"/>
<child link="left_base"/>
<origin xyz="0 0 -0.6"/>
</joint>
<link name="left_front_wheel">
<visual>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
<material name="black"/>
</visual>
<collision>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
</collision>
<inertial>
<mass value="1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_front_wheel_joint" type="continuous">
<axis xyz="0 0 1"/>
<parent link="left_base"/>
<child link="left_front_wheel"/>
<origin rpy="0 1.57075 0" xyz="0 0.133333333333 -0.085"/>
<limit effort="100" velocity="100"/>
<joint_properties damping="0.0" friction="0.0"/>
</joint>
<link name="left_back_wheel">
<visual>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
<material name="black"/>
</visual>
<collision>
<geometry>
<cylinder length=".1" radius="0.035"/>
</geometry>
</collision>
<inertial>
<mass value="1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_back_wheel_joint" type="continuous">
<axis xyz="0 0 1"/>
<parent link="left_base"/>
<child link="left_back_wheel"/>
<origin rpy="0 1.57075 0" xyz="0 -0.133333333333 -0.085"/>
<limit effort="100" velocity="100"/>
<joint_properties damping="0.0" friction="0.0"/>
</joint>
<joint name="gripper_extension" type="prismatic">
<parent link="base_link"/>
<child link="gripper_pole"/>
<limit effort="1000.0" lower="-0.38" upper="0" velocity="0.5"/>
<origin rpy="0 0 1.57075" xyz="0 0.19 .2"/>
</joint>
<link name="gripper_pole">
<visual>
<geometry>
<cylinder length="0.2" radius=".01"/>
</geometry>
<origin rpy="0 1.57075 0 " xyz="0.1 0 0"/>
<material name="Gray">
<color rgba=".7 .7 .7 1"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length="0.2" radius=".01"/>
</geometry>
<origin rpy="0 1.57075 0 " xyz="0.1 0 0"/>
</collision>
<inertial>
<mass value="0.05"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_gripper_joint" type="revolute">
<axis xyz="0 0 1"/>
<limit effort="1000.0" lower="0.0" upper="0.548" velocity="0.5"/>
<origin rpy="0 0 0" xyz="0.2 0.01 0"/>
<parent link="gripper_pole"/>
<child link="left_gripper"/>
</joint>
<link name="left_gripper">
<visual>
<origin rpy="0.0 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="l_finger.stl"/>
</geometry>
</visual>
<collision>
<geometry>
<mesh filename="l_finger.stl"/>
</geometry>
<origin rpy="0.0 0 0" xyz="0 0 0"/>
</collision>
<inertial>
<mass value="0.05"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_tip_joint" type="fixed">
<parent link="left_gripper"/>
<child link="left_tip"/>
</joint>
<link name="left_tip">
<visual>
<origin rpy="0.0 0 0" xyz="0.09137 0.00495 0"/>
<geometry>
<mesh filename="l_finger_tip.stl"/>
</geometry>
</visual>
<collision>
<geometry>
<mesh filename="l_finger_tip.stl"/>
</geometry>
<origin rpy="0.0 0 0" xyz="0.09137 0.00495 0"/>
</collision>
<inertial>
<mass value="0.05"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_gripper_joint" type="revolute">
<axis xyz="0 0 -1"/>
<limit effort="1000.0" lower="0.0" upper="0.548" velocity="0.5"/>
<origin rpy="0 0 0" xyz="0.2 -0.01 0"/>
<parent link="gripper_pole"/>
<child link="right_gripper"/>
</joint>
<link name="right_gripper">
<visual>
<origin rpy="-3.1415 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="l_finger.stl"/>
</geometry>
</visual>
<collision>
<geometry>
<mesh filename="l_finger.stl"/>
</geometry>
<origin rpy="-3.1415 0 0" xyz="0 0 0"/>
</collision>
<inertial>
<mass value="0.05"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_tip_joint" type="fixed">
<parent link="right_gripper"/>
<child link="right_tip"/>
</joint>
<link name="right_tip">
<visual>
<origin rpy="-3.1415 0 0" xyz="0.09137 0.00495 0"/>
<geometry>
<mesh filename="l_finger_tip.stl"/>
</geometry>
</visual>
<collision>
<geometry>
<mesh filename="l_finger_tip.stl"/>
</geometry>
<origin rpy="-3.1415 0 0" xyz="0.09137 0.00495 0"/>
</collision>
<inertial>
<mass value="0.05"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<link name="head">
<visual>
<geometry>
<sphere radius="0.2"/>
</geometry>
<material name="white"/>
</visual>
<collision>
<geometry>
<sphere radius="0.2"/>
</geometry>
</collision>
<inertial>
<mass value="10"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="head_swivel" type="continuous">
<parent link="base_link"/>
<child link="head"/>
<axis xyz="0 0 1"/>
<origin xyz="0 0 0.3"/>
</joint>
<link name="box">
<visual>
<geometry>
<box size=".08 .08 .08"/>
</geometry>
<material name="blue"/>
</visual>
<collision>
<geometry>
<box size=".08 .08 .08"/>
</geometry>
</collision>
<inertial>
<mass value="1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="tobox" type="fixed">
<parent link="head"/>
<child link="box"/>
<origin xyz="0 0.1414 0.1414"/>
</joint>
</robot>

BIN
data/spider.bullet Normal file

Binary file not shown.

View File

@@ -0,0 +1,116 @@
#ifndef B3_FILE_UTILS_H
#define B3_FILE_UTILS_H
#include <stdio.h>
#include "b3Scalar.h"
#include <stddef.h>//ptrdiff_h
struct b3FileUtils
{
b3FileUtils()
{
}
virtual ~b3FileUtils()
{
}
bool findFile(const char* orgFileName, char* relativeFileName, int maxRelativeFileNameMaxLen)
{
FILE* f=0;
f = fopen(orgFileName,"rb");
if (f)
{
//printf("original file found: [%s]\n", orgFileName);
sprintf(relativeFileName,"%s", orgFileName);
fclose(f);
return true;
}
//printf("Trying various directories, relative to current working directory\n");
const char* prefix[]={"./","./data/","../data/","../../data/","../../../data/","../../../../data/"};
int numPrefixes = sizeof(prefix)/sizeof(const char*);
f=0;
bool fileFound = false;
int result = 0;
for (int i=0;!f && i<numPrefixes;i++)
{
#ifdef _WIN32
sprintf_s(relativeFileName,maxRelativeFileNameMaxLen,"%s%s",prefix[i],orgFileName);
#else
sprintf(relativeFileName,"%s%s",prefix[i],orgFileName);
#endif
f = fopen(relativeFileName,"rb");
if (f)
{
fileFound = true;
break;
}
}
if (f)
{
fclose(f);
}
return fileFound;
}
static const char* strip2(const char* name, const char* pattern)
{
size_t const patlen = strlen(pattern);
size_t patcnt = 0;
const char * oriptr;
const char * patloc;
// find how many times the pattern occurs in the original string
for (oriptr = name; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
{
patcnt++;
}
return oriptr;
}
void extractPath(const char* fileName, char* path, int maxPathLength)
{
const char* stripped = strip2(fileName, "/");
stripped = strip2(stripped, "\\");
ptrdiff_t len = stripped-fileName;
b3Assert((len+1)<maxPathLength);
if (len && ((len+1)<maxPathLength))
{
for (int i=0;i<len;i++)
{
path[i] = fileName[i];
}
path[len]=0;
} else
{
b3Assert(maxPathLength>0);
if (maxPathLength>0)
{
path[0] = 0;
}
}
}
/*static const char* strip2(const char* name, const char* pattern)
{
size_t const patlen = strlen(pattern);
size_t patcnt = 0;
const char * oriptr;
const char * patloc;
// find how many times the pattern occurs in the original string
for (oriptr = name; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
{
patcnt++;
}
return oriptr;
}
*/
};
#endif //B3_FILE_UTILS_H

View File

@@ -277,7 +277,8 @@ void b3GpuGridBroadphase::calculateOverlappingPairs(int maxPairs)
b3AlignedObjectArray<b3Int4> pairsCpu;
m_gpuPairs.copyToHost(pairsCpu);
printf("m_gpuPairs.size()=%d\n",m_gpuPairs.size());
int sz = m_gpuPairs.size();
printf("m_gpuPairs.size()=%d\n",sz);
for (int i=0;i<m_gpuPairs.size();i++)
{
printf("pair %d = %d,%d\n",i,pairsCpu[i].x,pairsCpu[i].y);

View File

@@ -782,7 +782,8 @@ cl_program b3OpenCLUtils_compileCLProgramFromString(cl_context clContext, cl_dev
binarySize = ftell( file );
rewind( file );
binary = (char*)malloc(sizeof(char)*binarySize);
fread( binary, sizeof(char), binarySize, file );
int bytesRead;
bytesRead = fread( binary, sizeof(char), binarySize, file );
fclose( file );
m_cpProgram = clCreateProgramWithBinary( clContext, 1,&device, &binarySize, (const unsigned char**)&binary, 0, &status );

View File

@@ -74,7 +74,8 @@ bFile::bFile(const char *filename, const char headerString[7])
fseek(fp, 0L, SEEK_SET);
mFileBuffer = (char*)malloc(mFileLen+1);
fread(mFileBuffer, mFileLen, 1, fp);
int bytesRead;
bytesRead = fread(mFileBuffer, mFileLen, 1, fp);
fclose(fp);
@@ -1268,7 +1269,7 @@ int bFile::resolvePointersStructRecursive(char *strcPtr, int dna_nr, int verbose
}
//skip the *
printf("<%s type=\"pointer\"> ",&memName[1]);
printf("%d ", array[a]);
printf("%p ", array[a]);
printf("</%s>\n",&memName[1]);
}
@@ -1286,7 +1287,7 @@ int bFile::resolvePointersStructRecursive(char *strcPtr, int dna_nr, int verbose
printf(" ");
}
printf("<%s type=\"pointer\"> ",&memName[1]);
printf("%d ", ptr);
printf("%p ", ptr);
printf("</%s>\n",&memName[1]);
}
ptr = findLibPointer(ptr);
@@ -1467,7 +1468,7 @@ void bFile::resolvePointers(int verboseMode)
char* oldType = fileDna->getType(oldStruct[0]);
if (verboseMode & FD_VERBOSE_EXPORT_XML)
printf(" <%s pointer=%d>\n",oldType,dataChunk.oldPtr);
printf(" <%s pointer=%p>\n",oldType,dataChunk.oldPtr);
resolvePointersChunk(dataChunk, verboseMode);

View File

@@ -39,7 +39,8 @@ static DBVT_INLINE btDbvtVolume merge( const btDbvtVolume& a,
{
#if (DBVT_MERGE_IMPL==DBVT_IMPL_SSE)
ATTRIBUTE_ALIGNED16( char locals[sizeof(btDbvtAabbMm)]);
btDbvtVolume& res=*(btDbvtVolume*)locals;
btDbvtVolume* ptr = (btDbvtVolume*) locals;
btDbvtVolume& res=*ptr;
#else
btDbvtVolume res;
#endif
@@ -250,7 +251,8 @@ static btDbvtVolume bounds( const tNodeArray& leaves)
{
#if DBVT_MERGE_IMPL==DBVT_IMPL_SSE
ATTRIBUTE_ALIGNED16(char locals[sizeof(btDbvtVolume)]);
btDbvtVolume& volume=*(btDbvtVolume*)locals;
btDbvtVolume* ptr = (btDbvtVolume*) locals;
btDbvtVolume& volume=*ptr;
volume=leaves[0]->volume;
#else
btDbvtVolume volume=leaves[0]->volume;

View File

@@ -31,8 +31,8 @@ btCollisionObject::btCollisionObject()
m_activationState1(1),
m_deactivationTime(btScalar(0.)),
m_friction(btScalar(0.5)),
m_rollingFriction(0.0f),
m_restitution(btScalar(0.)),
m_rollingFriction(0.0f),
m_internalType(CO_COLLISION_OBJECT),
m_userObjectPointer(0),
m_userIndex(-1),

View File

@@ -292,7 +292,7 @@ void btCollisionWorld::rayTestSingleInternal(const btTransform& rayFromTrans,con
btGjkConvexCast gjkConvexCaster(castShape,convexShape,&simplexSolver);
//btContinuousConvexCollision convexCaster(castShape,convexShape,&simplexSolver,0);
bool condition = true;
btConvexCast* convexCasterPtr = 0;
//use kF_UseSubSimplexConvexCastRaytest by default
if (resultCallback.m_flags & btTriangleRaycastCallback::kF_UseGjkConvexCastRaytest)
@@ -1245,7 +1245,10 @@ public:
void btCollisionWorld::debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color)
{
// Draw a small simplex at the center of the object
if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawFrames)
{
getDebugDrawer()->drawTransform(worldTransform,1);
}
if (shape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE)
{

View File

@@ -123,7 +123,7 @@ public:
//backup
btTransform orgTrans = m_compoundColObjWrap->getWorldTransform();
btTransform orgInterpolationTrans = m_compoundColObjWrap->getWorldTransform();
const btTransform& childTrans = compoundShape->getChildTransform(index);
btTransform newChildWorldTrans = orgTrans*childTrans ;
@@ -294,7 +294,7 @@ void btCompoundCollisionAlgorithm::processCollision (const btCollisionObjectWrap
btManifoldArray manifoldArray;
const btCollisionShape* childShape = 0;
btTransform orgTrans;
btTransform orgInterpolationTrans;
btTransform newChildWorldTrans;
btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
@@ -305,7 +305,7 @@ void btCompoundCollisionAlgorithm::processCollision (const btCollisionObjectWrap
childShape = compoundShape->getChildShape(i);
//if not longer overlapping, remove the algorithm
orgTrans = colObjWrap->getWorldTransform();
orgInterpolationTrans = colObjWrap->getWorldTransform();
const btTransform& childTrans = compoundShape->getChildTransform(i);
newChildWorldTrans = orgTrans*childTrans ;

View File

@@ -112,10 +112,9 @@ struct btCompoundCompoundLeafCallback : btDbvt::ICollide
btManifoldResult* resultOut,
btHashedSimplePairCache* childAlgorithmsCache,
btPersistentManifold* sharedManifold)
:m_compound0ColObjWrap(compound1ObjWrap),m_compound1ColObjWrap(compound0ObjWrap),m_dispatcher(dispatcher),m_dispatchInfo(dispatchInfo),m_resultOut(resultOut),
:m_numOverlapPairs(0),m_compound0ColObjWrap(compound1ObjWrap),m_compound1ColObjWrap(compound0ObjWrap),m_dispatcher(dispatcher),m_dispatchInfo(dispatchInfo),m_resultOut(resultOut),
m_childCollisionAlgorithmCache(childAlgorithmsCache),
m_sharedManifold(sharedManifold),
m_numOverlapPairs(0)
m_sharedManifold(sharedManifold)
{
}

View File

@@ -88,20 +88,19 @@ partId, int triangleIndex)
//just for debugging purposes
//printf("triangle %d",m_triangleCount++);
const btCollisionObject* ob = const_cast<btCollisionObject*>(m_triBodyWrap->getCollisionObject());
btCollisionAlgorithmConstructionInfo ci;
ci.m_dispatcher1 = m_dispatcher;
//const btCollisionObject* ob = static_cast<btCollisionObject*>(m_triBodyWrap->getCollisionObject());
#if 0
///debug drawing of the overlapping triangles
if (m_dispatchInfoPtr && m_dispatchInfoPtr->m_debugDraw && (m_dispatchInfoPtr->m_debugDraw->getDebugMode() &btIDebugDraw::DBG_DrawWireframe ))
{
const btCollisionObject* ob = const_cast<btCollisionObject*>(m_triBodyWrap->getCollisionObject());
btVector3 color(1,1,0);
btTransform& tr = ob->getWorldTransform();
m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[0]),tr(triangle[1]),color);

View File

@@ -105,8 +105,7 @@ btDefaultCollisionConfiguration::btDefaultCollisionConfiguration(const btDefault
int maxSize = sizeof(btConvexConvexAlgorithm);
int maxSize2 = sizeof(btConvexConcaveCollisionAlgorithm);
int maxSize3 = sizeof(btCompoundCollisionAlgorithm);
int sl = sizeof(btConvexSeparatingDistanceUtil);
sl = sizeof(btGjkPairDetector);
int collisionAlgorithmMaxElementSize = btMax(maxSize,constructionInfo.m_customCollisionAlgorithmMaxElementSize);
collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize2);
collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize3);

View File

@@ -114,7 +114,6 @@ struct btConnectivityProcessor : public btTriangleCallback
if(numshared >= 3)
return;
}
switch (numshared)
{
case 0:
@@ -203,6 +202,7 @@ struct btConnectivityProcessor : public btTriangleCallback
ang4 = 0.f;
} else
{
calculatedEdge.normalize();
btVector3 calculatedNormalA = calculatedEdge.cross(edgeCrossA);
calculatedNormalA.normalize();
@@ -213,7 +213,7 @@ struct btConnectivityProcessor : public btTriangleCallback
isConvex = (dotA<0.);
correctedAngle = isConvex ? ang4 : -ang4;
btQuaternion orn2 = btQuaternion(btVector3(calculatedEdge.x(), calculatedEdge.y(), calculatedEdge.z()),-correctedAngle);
btQuaternion orn2(calculatedEdge,-correctedAngle);
calculatedNormalB = btMatrix3x3(orn2)*normalA;
@@ -301,6 +301,11 @@ struct btConnectivityProcessor : public btTriangleCallback
break;
}
default:
{
// printf("warning: duplicate triangle\n");
}
}
}
};

View File

@@ -117,6 +117,7 @@ public:
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const;
SIMD_FORCE_INLINE void deSerializeFloat(struct btCapsuleShapeData* dataBuffer);
};
@@ -181,4 +182,13 @@ SIMD_FORCE_INLINE const char* btCapsuleShape::serialize(void* dataBuffer, btSeri
return "btCapsuleShapeData";
}
SIMD_FORCE_INLINE void btCapsuleShape::deSerializeFloat(btCapsuleShapeData* dataBuffer)
{
m_implicitShapeDimensions.deSerializeFloat(dataBuffer->m_convexInternalShapeData.m_implicitShapeDimensions);
m_collisionMargin = dataBuffer->m_convexInternalShapeData.m_collisionMargin;
m_localScaling.deSerializeFloat(dataBuffer->m_convexInternalShapeData.m_localScaling);
//it is best to already pre-allocate the matching btCapsuleShape*(X/Z) version to match m_upAxis
m_upAxis = dataBuffer->m_upAxis;
}
#endif //BT_CAPSULE_SHAPE_H

View File

@@ -28,18 +28,14 @@ ATTRIBUTE_ALIGNED16(class) btCollisionShape
{
protected:
int m_shapeType;
union
{
void* m_userPointer;
int m_userIndex;
};
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btCollisionShape() : m_shapeType (INVALID_SHAPE_PROXYTYPE), m_userPointer(0)
btCollisionShape() : m_shapeType (INVALID_SHAPE_PROXYTYPE), m_userPointer(0), m_userIndex(-1)
{
}
@@ -135,7 +131,6 @@ public:
{
return m_userPointer;
}
void setUserIndex(int index)
{
m_userIndex = index;
@@ -146,6 +141,7 @@ public:
return m_userIndex;
}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)

View File

@@ -77,8 +77,8 @@ void btCompoundShape::addChildShape(const btTransform& localTransform,btCollisio
if (m_dynamicAabbTree)
{
const btDbvtVolume bounds=btDbvtVolume::FromMM(localAabbMin,localAabbMax);
int index = m_children.size();
child.m_node = m_dynamicAabbTree->insert(bounds,(void*)index);
size_t index = m_children.size();
child.m_node = m_dynamicAabbTree->insert(bounds,reinterpret_cast<void*>(index) );
}
m_children.push_back(child);
@@ -312,7 +312,8 @@ void btCompoundShape::createAabbTreeFromChildren()
child.m_childShape->getAabb(child.m_transform,localAabbMin,localAabbMax);
const btDbvtVolume bounds=btDbvtVolume::FromMM(localAabbMin,localAabbMax);
child.m_node = m_dynamicAabbTree->insert(bounds,(void*)index);
size_t index2 = index;
child.m_node = m_dynamicAabbTree->insert(bounds, reinterpret_cast<void*>(index2) );
}
}
}

View File

@@ -313,7 +313,7 @@ bool btPolyhedralContactClipping::findSeparatingAxis( const btConvexPolyhedron&
int edgeB=-1;
btVector3 worldEdgeA;
btVector3 worldEdgeB;
btVector3 witnessPointA,witnessPointB;
btVector3 witnessPointA(0,0,0),witnessPointB(0,0,0);
int curEdgeEdge = 0;

View File

@@ -21,7 +21,6 @@ subject to the following restrictions:
struct btBroadphaseProxy;
class btConvexShape;
class btTriangleRaycastCallback: public btTriangleCallback
{
public:

View File

@@ -65,10 +65,10 @@ bool btSubsimplexConvexCast::calcTimeOfImpact(
btVector3 n;
n.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
bool hasResult = false;
btVector3 c;
btScalar lastLambda = lambda;
btScalar dist2 = v.length2();
@@ -109,9 +109,9 @@ bool btSubsimplexConvexCast::calcTimeOfImpact(
//m_simplexSolver->reset();
//check next line
w = supVertexA-supVertexB;
lastLambda = lambda;
n = v;
hasResult = true;
}
}
///Just like regular GJK only add the vertex if it isn't already (close) to current vertex, it would lead to divisions by zero and NaN etc.
@@ -121,7 +121,7 @@ bool btSubsimplexConvexCast::calcTimeOfImpact(
if (m_simplexSolver->closest(v))
{
dist2 = v.length2();
hasResult = true;
//todo: check this normal for validity
//n=v;
//printf("V=%f , %f, %f\n",v[0],v[1],v[2]);

Some files were not shown because too many files have changed in this diff Show More