Bullet - objects falling through

Started by
4 comments, last by xexuxjy 9 years, 8 months ago

I have created pulsing bars, similar to music equalizers. Now, I set them no gravity and controll them with setLinearVecolity. It behaves correctly and I see same result as if I set position directly.

Problem is, that if I want to have those bars collided with some other geometry, it is no working correctly. I am throwing balls on top of those bars. They bounce and are pushed by bars, but after some time, bars and balls go through each other and stuck inside each other. I must admit, that there ciould be some big changes in applied velocity from frame to frame, including negative one to move bars in oposite dirrection.

Note:

I have also tried controll bars with applyCentralForce, but it behaves weird. For example: First iteration works, I got correct position. In second one, there is 0 difference in height, so no force should be applied. I set force to be 0. But in the next iteration, even with no force applied in previous one, position of object has changed. There is no gravity and no other external force. There are no other objects in scene as well (I disabled falling balls).

Any ideas ?

Thank you

Advertisement

How are you setting up the objects, Can you post any code? have you got any other structures (planes, boxes,etc.) which are stopping the balls falling in front and behind of the boxes? Are you limiting the balls/boxes to 2d movement only (setLinearFactor) or is it all in 3d?

Objects are set using Bounding sphere and bounding box, both from Bullet library. I dont have any other structures, basicly all image is 2D (I have limited angularFactor to be only in 1 axis and linearFactor accordingly).

Some init code (using Bullet not directly, but through my engine - mapping of those values is than done 1:1 to Bullet)

Bars:


MyModels::WorldSettings barSets = MyModels::WorldSettings::defaultWorldSettings();
barSets.mass = 10.0f;
barSets.restitution = 1.0f;
barSets.friction = 0.1f;
barSets.angularFactor = MyMath::Vector3(0, 0, 0);
barSets.linearFactor = MyMath::Vector3(0, 1, 0);

Balls:


MyModels::WorldSettings itemSets = MyModels::WorldSettings::defaultWorldSettings();
itemSets.mass = 0.0f;
itemSets.restitution = 0.5f;
itemSets.friction = 0.1f;
itemSets.angularFactor = MyMath::Vector3(0, 0, 1);
itemSets.linearFactor = MyMath::Vector3(1, 1, 0);

I have also tried to use CCD, that improve stability a little, but problem still persist.

Bars CCD:


for (int i = 0; i < this->bars.size(); i++)
{
    this->bars[i]->GetWorldInfo()->GetBulletBody()->forceActivationState(DISABLE_DEACTIVATION);
    this->bars[i]->GetWorldInfo()->GetBulletBody()->setGravity(btVector3(0, 0, 0));

    this->bars[i]->GetWorldInfo()->GetBulletBody()->setCcdMotionThreshold(this->baseBarHeight);
    this->bars[i]->GetWorldInfo()->GetBulletBody()->setCcdSweptSphereRadius(0.8f * this->baseBarHeight);     
}

Balls CCD:


ball->GetWorldInfo()->GetBulletBody()->setCcdMotionThreshold(radius);
ball->GetWorldInfo()->GetBulletBody()->setCcdSweptSphereRadius(0.8f * radius);

You can see my problem in video:

(around 0:18)

Movement of vertical bars is controlled with this code


dist = distance I need the bar to change its position in a single frame
float g = (2 * dist) / (times.dTime); //dTime = 1/60
bars[i]->GetBulletBody()->setLinearVelocity(btVector3(0, 0, 0));
bars[i]->GetBulletBody()->setGravity(btVector3(0, speedUpFactor * g, 0));

Falling balls have only gravity applied on them.

Really can't see anything particularly odd with that. Only thing i can think of is collisions being missed as a bar / bars are moving too much in one frame, but your changes for ccd should prevent that. You've set the mass of the balls to 0, is that correct? I'll see if I can generate a similar bug on my home install.

You've set the mass of the balls to 0, is that correct?

Eh.. that is a bug in rewriting code to post, there should be 10.0

The bars are moving fast, there could be collision miss. But thats way I used CCD.

So far, I am solving this problem manually. I check if ball is in collision with bar. If so and if it is stucked inside bar, I push the ball with big force to move it from collidable state. It is working in a way, but result is not as nice, as it should be if balls are just bouncing from bars like most of the time in video.

Something like the below seemed to work..... apologies as I don't seem to be able to attach the .h/.cpp files

 


BasicDemo.h

/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, 
including commercial applications, and to alter it and redistribute it freely, 
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BASIC_DEMO_H
#define BASIC_DEMO_H

#ifdef _WINDOWS
#include "Win32DemoApplication.h"
#define PlatformDemoApplication Win32DemoApplication
#else
#include "GlutDemoApplication.h"
#define PlatformDemoApplication GlutDemoApplication
#endif

#include "LinearMath/btAlignedObjectArray.h"

class btBroadphaseInterface;
class btCollisionShape;
class btOverlappingPairCache;
class btCollisionDispatcher;
class btConstraintSolver;
struct btCollisionAlgorithmCreateFunc;
class btDefaultCollisionConfiguration;

///BasicDemo is good starting point for learning the code base and porting.

class BasicDemo : public PlatformDemoApplication
{

	//keep the collision shapes, for deletion/cleanup
	btAlignedObjectArray<btCollisionShape*>	m_collisionShapes;

	btBroadphaseInterface*	m_broadphase;

	btCollisionDispatcher*	m_dispatcher;

	btConstraintSolver*	m_solver;

	btDefaultCollisionConfiguration* m_collisionConfiguration;


	btAlignedObjectArray<class BarInfo*>	m_bars;
	btAlignedObjectArray<class btRigidBody*> m_balls;

	public:

	BasicDemo()
	{
	}
	virtual ~BasicDemo()
	{
		exitPhysics();
	}
	void	initPhysics();

	void	exitPhysics();

	void updateBars();

	btRigidBody* buildBall(float radius,const btTransform& t);
	btRigidBody* buildBar(const btVector3& halfExtents, const btTransform& t);

	virtual void clientMoveAndDisplay();

	virtual void displayCallback();
	virtual void	clientResetScene();
	
	static DemoApplication* Create()
	{
		BasicDemo* demo = new BasicDemo;
		demo->myinit();
		demo->initPhysics();
		return demo;
	}

	
};

class BarInfo
{
public :
	btVector3 direction;
	btScalar currentElapsed;
	btScalar lifeTime = 2.0;
	btRigidBody* body;
	btVector3 startPosition;
	btScalar maxRange;

	BarInfo(btRigidBody* theBody);
	void chooseNewDirection();

	void update(btScalar elapsed);
	

};

#endif //BASIC_DEMO_H


 

BasicDemo.cpp


/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, 
including commercial applications, and to alter it and redistribute it freely, 
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/


///create 125 (5x5x5) dynamic object
#define ARRAY_SIZE_X 5
#define ARRAY_SIZE_Y 5
#define ARRAY_SIZE_Z 5

//maximum number of objects (and allow user to shoot additional boxes)
#define MAX_PROXIES (ARRAY_SIZE_X*ARRAY_SIZE_Y*ARRAY_SIZE_Z + 1024)

///scaling of the objects (0.1 = 20 centimeter boxes )
#define SCALING 1.
#define START_POS_X -5
#define START_POS_Y -5
#define START_POS_Z -3

#include "BasicDemo.h"
#include "GlutStuff.h"
///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files.
#include "btBulletDynamicsCommon.h"

#include <stdio.h> //printf debugging
#include "GLDebugDrawer.h"
#include "LinearMath/btAabbUtil2.h"

static GLDebugDrawer gDebugDraw;

///The MyOverlapCallback is used to show how to collect object that overlap with a given bounding box defined by aabbMin and aabbMax. 
///See m_dynamicsWorld->getBroadphase()->aabbTest.
struct	MyOverlapCallback : public btBroadphaseAabbCallback
{
	btVector3 m_queryAabbMin;
	btVector3 m_queryAabbMax;
	
	int m_numOverlap;
	MyOverlapCallback(const btVector3& aabbMin, const btVector3& aabbMax ) : m_queryAabbMin(aabbMin),m_queryAabbMax(aabbMax),m_numOverlap(0)	{}
	virtual bool	process(const btBroadphaseProxy* proxy)
	{
		btVector3 proxyAabbMin,proxyAabbMax;
		btCollisionObject* colObj0 = (btCollisionObject*)proxy->m_clientObject;
		colObj0->getCollisionShape()->getAabb(colObj0->getWorldTransform(),proxyAabbMin,proxyAabbMax);
		if (TestAabbAgainstAabb2(proxyAabbMin,proxyAabbMax,m_queryAabbMin,m_queryAabbMax))
		{
			m_numOverlap++;
		}
		return true;
	}
};

void BasicDemo::clientMoveAndDisplay()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

	//simple dynamics world doesn't handle fixed-time-stepping
	float ms = getDeltaTimeMicroseconds();
	
	///step the simulation
	if (m_dynamicsWorld)
	{
		updateBars();

		m_dynamicsWorld->stepSimulation(ms / 1000000.f);
		//optional but useful: debug drawing
		m_dynamicsWorld->debugDrawWorld();

		//btVector3 aabbMin(1,1,1);
		//btVector3 aabbMax(2,2,2);

		//MyOverlapCallback aabbOverlap(aabbMin,aabbMax);
		//m_dynamicsWorld->getBroadphase()->aabbTest(aabbMin,aabbMax,aabbOverlap);
		//
		//if (aabbOverlap.m_numOverlap)
		//	printf("#aabb overlap = %d\n", aabbOverlap.m_numOverlap);
	}
		
	renderme(); 

	glFlush();

	swapBuffers();

}



void BasicDemo::displayCallback(void) {

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

	renderme();

	//optional but useful: debug drawing to detect problems
	if (m_dynamicsWorld)
		m_dynamicsWorld->debugDrawWorld();

	glFlush();
	swapBuffers();
}





void	BasicDemo::initPhysics()
{
	setTexturing(true);
	setShadows(true);

	setCameraDistance(btScalar(SCALING*50.));

	///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();

	///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
	btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver;
	m_solver = sol;

	m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
	m_dynamicsWorld->setDebugDrawer(&gDebugDraw);
	
	m_dynamicsWorld->setGravity(btVector3(0,-10,0));

	btVector3 barHalfExtents(1.5, 5, 1.5);
	int numBars = 10;
	float pad = 0.1;
	btTransform t;

	btScalar startX = -1.0;
	btScalar lastX = startX;

	btStaticPlaneShape* leftWall = new btStaticPlaneShape(btVector3(1, 0, 0), 0);


	for (int i = 0; i < numBars; ++i)
	{
		t = btTransform::getIdentity();
		btVector3 origin(lastX, 0, 0);
		t.setOrigin(origin);
		btRigidBody* bar = buildBar(barHalfExtents,t);
		m_bars.push_back(new BarInfo(bar));
		m_dynamicsWorld->addRigidBody(bar);
		bar->setGravity(btVector3(0, 0, 0));
		lastX += ((barHalfExtents.x() * 2.0) + pad*2.0);

	}
	btStaticPlaneShape* rightWall = new btStaticPlaneShape(btVector3(-1, 0, 0), 0);

	t = btTransform::getIdentity();
	btVector3 origin(startX-pad, 0, 0);
	t.setOrigin(origin);
	localCreateRigidBody(0.0, t, leftWall);

	t = btTransform::getIdentity();
	origin=btVector3(lastX-barHalfExtents.x(), 0, 0);
	t.setOrigin(origin);
	localCreateRigidBody(0.0, t, rightWall);


	btScalar range = (lastX-startX);
	btScalar startY = 10.0;


	int numBalls = 100;
	btScalar ballRadius = 0.4;
	for (int i = 0; i < numBalls; ++i)
	{

		t = btTransform::getIdentity();
		double x = startX + static_cast <double> (rand()) / (static_cast <double> (RAND_MAX / range));


		btVector3 origin(x,startY,0);
		t.setOrigin(origin);
		btRigidBody* ball = buildBall(ballRadius,t);
		m_balls.push_back(ball);

		m_dynamicsWorld->addRigidBody(ball);
	}



}
void	BasicDemo::clientResetScene()
{
	exitPhysics();
	initPhysics();
}
	

void	BasicDemo::exitPhysics()
{

	//cleanup in the reverse order of creation/initialization

	//remove the rigidbodies from the dynamics world and delete them
	int 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;



}

btRigidBody* BasicDemo::buildBar(const btVector3& halfExtents,const btTransform& t)
{
	btCollisionShape* shape = new btBoxShape(halfExtents);
	btVector3 localInertia(0, 0, 0);
	float mass = 100.0;
	shape->calculateLocalInertia(mass, localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(t);

	btRigidBody::btRigidBodyConstructionInfo cInfo(mass, myMotionState, shape, localInertia);

	btRigidBody* body = new btRigidBody(cInfo);
	body->setGravity(btVector3(0, 0, 0));
	body->setLinearFactor(btVector3(1, 1, 0));
	body->setAngularFactor(btVector3(0, 0, 0));
	body->setActivationState(DISABLE_DEACTIVATION);
	return body;
}

btRigidBody* BasicDemo::buildBall(float radius, const btTransform& t)
{
	btCollisionShape* shape = new btSphereShape(radius);
	btVector3 localInertia(0, 0, 0);
	float mass = 1.0f;
	shape->calculateLocalInertia(mass, localInertia);

	btDefaultMotionState* myMotionState = new btDefaultMotionState(t);


	btRigidBody::btRigidBodyConstructionInfo cInfo(mass, myMotionState, shape, localInertia);

	btRigidBody* body = new btRigidBody(cInfo);
	
	body->setLinearFactor(btVector3(1, 1, 0));
	return body;
}


void BasicDemo::updateBars()
{
	float maxFrameDistance = 1.5;
	float dTime = 1.0 / 60.0;
	int numBars = m_bars.size();
		
	float speedUpFactor = 1;


	for (int i = 0; i<numBars; ++i)
	{
		m_bars[i]->update(dTime);
	}
	
}



BarInfo::BarInfo(btRigidBody* theBody) : currentElapsed(0.0), lifeTime(2.0), body(theBody)
{
	direction.setZero();
	float dist = (rand() % 2 == 1 ? 1 : -1);
	direction[1] = dist;
	// random warmup
	
	double x = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX / lifeTime));

	currentElapsed = x;
	startPosition = theBody->getWorldTransform().getOrigin();
	maxRange = 2.0;

	chooseNewDirection();

}

void BarInfo::update(btScalar elapsed)
{
	float maxFrameDistance = 10.0;

	currentElapsed += elapsed;

	btScalar dist = abs(body->getWorldTransform().getOrigin().y() - startPosition.y());

	if (dist > maxRange)
	{
		// gone too far. reverse direction for now and reset timer
		direction[1] *= -1.0;
		currentElapsed = 0;

		//body->setGravity(btVector3(0, 0, 0));
	}
	//else
	{
		if (currentElapsed > lifeTime)
		{
			chooseNewDirection();
		}

	}

	body->setLinearVelocity(direction);
	body->setAngularVelocity(btVector3(0.0,0.0,0.0));


	//float g = (2 * dist) / (dTime); //dTime = 1/60
	//m_bars->setLinearVelocity(btVector3(0, 0, 0));
	//m_bars->setGravity(btVector3(0, speedUpFactor * g, 0));


}

void BarInfo::chooseNewDirection()
{
	float maxFrameDistance = 10.0;

	float distDirection = (rand() % 2 == 1 ? 1 : -1);

	double x = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX / maxFrameDistance));
	direction[1] = x * distDirection;
	currentElapsed = 0;
}

 

This topic is closed to new replies.

Advertisement