Bullet + Ogre (Falling sphere)

Post Reply
kumbwol
Posts: 1
Joined: Thu Aug 07, 2014 11:20 am

Bullet + Ogre (Falling sphere)

Post by kumbwol »

Hello!

I made an application, in C++, VS11, with OGRE. Yet it just make a flat field, at (0,0,0), and makes a sphere at (0,50,0).
Heres the code:

//Base.h

Code: Select all

#ifndef __BASE_H_
#define __BASE_H_

#include <OgreCamera.h>
#include <OgreEntity.h>
#include <OgreLogManager.h>
#include <OgreRoot.h>
#include <OgreString.h>
#include <OgreViewport.h>
#include <OgreSceneManager.h>
#include <OgreRenderWindow.h>
#include <OgreConfigFile.h>

#include <OISEvents.h>
#include <OISInputManager.h>
#include <OISKeyboard.h>
#include <OISMouse.h>

#include <SdkTrays.h>
#include <SdkCameraMan.h>

class Base : public Ogre::FrameListener, public Ogre::WindowEventListener, public OIS::KeyListener, public OIS::MouseListener, OgreBites::SdkTrayListener {
protected:
	/*******************************************************************************
	*** Változók *******************************************************************
	*******************************************************************************/
	Ogre::Root*					mRoot;
    Ogre::Camera*				mCamera;
    Ogre::SceneManager*			mSceneMgr;
    Ogre::RenderWindow*			mWindow;
    Ogre::String				mResourcesCfg;
    Ogre::String				mPluginsCfg;

	Ogre::OverlaySystem*		mOverlaySystem;

    OgreBites::SdkTrayManager*	mTrayMgr;
    OgreBites::SdkCameraMan*	mCameraMan;

	OgreBites::InputContext		mInputContext;
	
	bool mCursorWasVisible;
    bool mShutDown;

    OIS::InputManager*			mInputManager;
    OIS::Mouse*					mMouse;
    OIS::Keyboard*				mKeyboard;

	/*******************************************************************************
	*** Függvények *****************************************************************
	*******************************************************************************/
	virtual bool setup();
    virtual bool configure(void);
    virtual void chooseSceneManager(void);
    virtual void createCamera(void);
    virtual void createFrameListener(void);
    virtual void createScene(void) = 0; // Override me!
    virtual void destroyScene(void);
    virtual void createViewports(void);
    virtual void setupResources(void);
    virtual void createResourceListener(void);
    virtual void loadResources(void);

    virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt);

    virtual bool keyPressed( const OIS::KeyEvent &arg );
    virtual bool keyReleased( const OIS::KeyEvent &arg );

    virtual bool mouseMoved( const OIS::MouseEvent &arg );
    virtual bool mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id );
    virtual bool mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id );

    virtual void windowResized(Ogre::RenderWindow* rw);
    virtual void windowClosed(Ogre::RenderWindow* rw);

public:
    Base(void);
    virtual ~Base(void);

	virtual void init(void);
};

#endif
//Sphere.h

Code: Select all

#include <OgreAxisAlignedBox.h>

// A gömb osztálya
class Sphere : public Base {
public:
	Sphere();
	virtual ~Sphere();

protected:
	virtual void createScene(void);
	virtual void createSphere(const std::string& strName, const float r, const int nRings = 16, const int nSegments = 16);
};

#endif
//Application.cpp

Code: Select all

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include "Sphere.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {
	Sphere sphere;
	sphere.init();

	return 0;
}
//Base.cpp

Code: Select all

#include "Base.h"

Base::Base(void) :	mRoot(0), mCamera(0), mSceneMgr(0), mWindow(0), mResourcesCfg(Ogre::StringUtil::BLANK), mPluginsCfg(Ogre::StringUtil::BLANK), mTrayMgr(0), mCameraMan(0),
					mCursorWasVisible(false), mShutDown(false), mInputManager(0), mMouse(0), mKeyboard(0), mOverlaySystem(0) {
}

Base::~Base(void) {
	if (mTrayMgr)
		delete mTrayMgr;

    if (mCameraMan)
		delete mCameraMan;

	if (mOverlaySystem)
		delete mOverlaySystem;

    Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this);
    windowClosed(mWindow);
    delete mRoot;
}

bool Base::configure(void) {
	if(mRoot->showConfigDialog()) {
        mWindow = mRoot->initialise(true, "Application");
        return true;
    }
    else {
        return false;
    }
}

void Base::chooseSceneManager(void) {
    mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);
    mOverlaySystem = new Ogre::OverlaySystem();
    mSceneMgr->addRenderQueueListener(mOverlaySystem);
}

void Base::createCamera(void) {
    mCamera = mSceneMgr->createCamera("PlayerCam");
    mCamera->setPosition(Ogre::Vector3(0,0,80));
    mCamera->lookAt(Ogre::Vector3(0,0,-300));
    mCamera->setNearClipDistance(5);

    mCameraMan = new OgreBites::SdkCameraMan(mCamera);
}

void Base::createFrameListener(void) {
    Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
    OIS::ParamList pl;
    size_t windowHnd = 0;
    std::ostringstream windowHndStr;

    mWindow->getCustomAttribute("WINDOW", &windowHnd);
    windowHndStr << windowHnd;
    pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));

    mInputManager = OIS::InputManager::createInputSystem( pl );

    mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true ));
    mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true ));

	mInputContext.mKeyboard = mKeyboard;
    mInputContext.mMouse = mMouse;

    mMouse->setEventCallback(this);
    mKeyboard->setEventCallback(this);

    windowResized(mWindow);

    Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);

	mTrayMgr = new OgreBites::SdkTrayManager("InterfaceName", mWindow, mInputContext, this);
    mTrayMgr->hideCursor();

    Ogre::StringVector items;
    items.push_back("cam.pX");
    items.push_back("cam.pY");
    items.push_back("cam.pZ");
    items.push_back("");
    items.push_back("cam.oW");
    items.push_back("cam.oX");
    items.push_back("cam.oY");
    items.push_back("cam.oZ");
    items.push_back("");
    items.push_back("Filtering");
    items.push_back("Poly Mode");

    mRoot->addFrameListener(this);
}

void Base::destroyScene(void) {

}

void Base::createViewports(void) {
    Ogre::Viewport* vp = mWindow->addViewport(mCamera);
    vp->setBackgroundColour(Ogre::ColourValue(0,0,0));

    mCamera->setAspectRatio(Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
}

void Base::setupResources(void) {
    Ogre::ConfigFile cf;
    cf.load(mResourcesCfg);

    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();

    Ogre::String secName, typeName, archName;
    while (seci.hasMoreElements()) {
        secName = seci.peekNextKey();
        Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
        Ogre::ConfigFile::SettingsMultiMap::iterator i;
        for (i = settings->begin(); i != settings->end(); ++i) {
            typeName = i->first;
            archName = i->second;
            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
        }
    }
}

void Base::createResourceListener(void) {

}

void Base::loadResources(void) {
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
}

void Base::init(void) {
#ifdef _DEBUG
    mResourcesCfg = "resources_d.cfg";
    mPluginsCfg = "plugins_d.cfg";
#else
    mResourcesCfg = "resources.cfg";
    mPluginsCfg = "plugins.cfg";
#endif

    if (!setup())
        return;

    mRoot->startRendering();
    destroyScene();
}

bool Base::setup(void) {
    mRoot = new Ogre::Root(mPluginsCfg);

    setupResources();

    bool carryOn = configure();

    if (!carryOn)
		return false;

    chooseSceneManager();
    createCamera();
    createViewports();

    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

    createResourceListener();
    loadResources();

    createScene();

    createFrameListener();

    return true;
};

bool Base::frameRenderingQueued(const Ogre::FrameEvent& evt) {
    if(mWindow->isClosed())
        return false;

    if(mShutDown)
        return false;

	mInputContext.capture();

    mTrayMgr->frameRenderingQueued(evt);

    if (!mTrayMgr->isDialogVisible()) {
        mCameraMan->frameRenderingQueued(evt);
    }

    return true;
}

bool Base::keyPressed( const OIS::KeyEvent &arg ) {
    if (mTrayMgr->isDialogVisible())
		return true;
	
	if (arg.key == OIS::KC_ESCAPE) {
        mShutDown = true;
    }

    mCameraMan->injectKeyDown(arg);
    return true;
}

bool Base::keyReleased( const OIS::KeyEvent &arg ) {
    mCameraMan->injectKeyUp(arg);
    return true;
}

bool Base::mouseMoved( const OIS::MouseEvent &arg ) {
    if (mTrayMgr->injectMouseMove(arg))
		return true;

    mCameraMan->injectMouseMove(arg);
    return true;
}

bool Base::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id ) {
    if (mTrayMgr->injectMouseDown(arg, id))
		return true;

    mCameraMan->injectMouseDown(arg, id);
    return true;
}

bool Base::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id ) {
    if (mTrayMgr->injectMouseUp(arg, id))
		return true;

    mCameraMan->injectMouseUp(arg, id);
    return true;
}

void Base::windowResized(Ogre::RenderWindow* rw) {
    unsigned int width, height, depth;
    int left, top;
    rw->getMetrics(width, height, depth, left, top);

    const OIS::MouseState &ms = mMouse->getMouseState();
    ms.width = width;
    ms.height = height;
}

void Base::windowClosed(Ogre::RenderWindow* rw) {
    if( rw == mWindow ) {
        if( mInputManager ) {
            mInputManager->destroyInputObject( mMouse );
            mInputManager->destroyInputObject( mKeyboard );

            OIS::InputManager::destroyInputSystem(mInputManager);
            mInputManager = 0;
        }
    }
}
//Sphere.cpp

Code: Select all

#include "Sphere.h"

Sphere::Sphere() {
}

Sphere::~Sphere() {

}

void Sphere::createSphere(const std::string& strName, const float r, const int nRings, const int nSegments) {
	Ogre::ManualObject* manual = mSceneMgr->createManualObject(strName);
	manual->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST);
 
	float fDeltaRingAngle = (Ogre::Math::PI / nRings);
	float fDeltaSegAngle = (2 * Ogre::Math::PI / nSegments);
	unsigned short wVerticeIndex = 0 ;
 
	for (int ring = 0; ring <= nRings; ring++) {
		float r0 = r * sinf (ring * fDeltaRingAngle);
		float y0 = r * cosf (ring * fDeltaRingAngle);
 
		for (int seg = 0; seg <= nSegments; seg++) {
			float x0 = r0 * sinf(seg * fDeltaSegAngle);
			float z0 = r0 * cosf(seg * fDeltaSegAngle);
 
			manual->position( x0, y0, z0);
			manual->normal(Ogre::Vector3(x0, y0, z0).normalisedCopy());
			manual->textureCoord((float) seg / (float) nSegments, (float) ring / (float) nRings);
 
			if (ring != nRings) {
				manual->index(wVerticeIndex + nSegments + 1);
				manual->index(wVerticeIndex);               
				manual->index(wVerticeIndex + nSegments);
				manual->index(wVerticeIndex + nSegments + 1);
				manual->index(wVerticeIndex + 1);
				manual->index(wVerticeIndex);

				wVerticeIndex ++;
			}
		};
	}

	manual->end();
	Ogre::MeshPtr mesh = manual->convertToMesh(strName);
	mesh->_setBounds(Ogre::AxisAlignedBox(Ogre::Vector3(-r, -r, -r), Ogre::Vector3(r, r, r) ), false);
 
	mesh->_setBoundingSphereRadius(r);

	unsigned short src, dest;
	if (!mesh->suggestTangentVectorBuildParams(Ogre::VES_TANGENT, src, dest)) {
		mesh->buildTangentVectors(Ogre::VES_TANGENT, src, dest);
	}
}

void Sphere::createScene(void) {
	Ogre::MovablePlane* mPlane;
    Ogre::Entity* mPlaneEnt;
    Ogre::SceneNode* mPlaneNode;
    Ogre::Rectangle2D* mMiniScreen;

    mSceneMgr->setAmbientLight(Ogre::ColourValue(0.2f, 0.2f, 0.2f));
 
	Ogre::Light* light = mSceneMgr->createLight("MainLight");
	light->setPosition(20, 80, 50);
 
	mCamera->setPosition(60, 200, 70);
	mCamera->lookAt(0,0,0);
 
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("PlaneMat", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	Ogre::TextureUnitState* tuisTexture = mat->getTechnique(0)->getPass(0)->createTextureUnitState("grass_1024.jpg");
 
	mPlane = new Ogre::MovablePlane("Plane");
	mPlane->d = 0;
	mPlane->normal = Ogre::Vector3::UNIT_Y;

	createSphere("mySphereMesh", 10, 64, 64);

	Ogre::Entity* sphereEntity = mSceneMgr->createEntity("mySphereEntity", "mySphereMesh");
 
    Ogre::SceneNode* sphereNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
	sphereEntity->setMaterialName("HeatVision");
	sphereNode->setPosition(0.0f, 50.0f, 0.0f);
    sphereNode->attachObject(sphereEntity);
	sphereNode->_update(true, false);
 
	Ogre::MeshManager::getSingleton().createPlane("PlaneMesh", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, *mPlane, 120, 120, 1, 1, true, 1, 1, 1, Ogre::Vector3::UNIT_Z);
	mPlaneEnt = mSceneMgr->createEntity("PlaneEntity", "PlaneMesh");
	mPlaneEnt->setMaterialName("PlaneMat");
 
	mPlaneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
	mPlaneNode->attachObject(mPlaneEnt);
}

------------------------------------------------------------------------------

If run this 5 part, and you setup ogre 1.9 well, it must work in VS 11.

And my question is, how can i make the sphere falling with bullet?

Already calculated the falling in this application, with bullet:

Code: Select all

#include "stdafx.h"
#include <iostream>

#include <btBulletDynamicsCommon.h>

int main (void)
{

        btBroadphaseInterface* broadphase = new btDbvtBroadphase();

        btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
        btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);

        btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;

        btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);

        dynamicsWorld->setGravity(btVector3(0, -10, 0));


        btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1);

        btCollisionShape* fallShape = new btSphereShape(1);


        btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0)));
        btRigidBody::btRigidBodyConstructionInfo
                groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));
        btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
        dynamicsWorld->addRigidBody(groundRigidBody);


        btDefaultMotionState* fallMotionState =
                new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 50, 0)));
        btScalar mass = 1;
        btVector3 fallInertia(0, 0, 0);
        fallShape->calculateLocalInertia(mass, fallInertia);
        btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
        btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
        dynamicsWorld->addRigidBody(fallRigidBody);


        for (int i = 0; i < 300; i++) {
                dynamicsWorld->stepSimulation(1 / 60.f, 10);

                btTransform trans;
                fallRigidBody->getMotionState()->getWorldTransform(trans);

                std::cout << "sphere height: " << trans.getOrigin().getY() << std::endl;
        }

        dynamicsWorld->removeRigidBody(fallRigidBody);
        delete fallRigidBody->getMotionState();
        delete fallRigidBody;

        dynamicsWorld->removeRigidBody(groundRigidBody);
        delete groundRigidBody->getMotionState();
        delete groundRigidBody;


        delete fallShape;

        delete groundShape;


        delete dynamicsWorld;
        delete solver;
        delete collisionConfiguration;
        delete dispatcher;
        delete broadphase;

        return 0;
}

------------------------------------------------

Please tell me how to "combine" this 2 programs, to make the sphere falling :roll:
Post Reply