void PhysicsSystem::addActor (const Ptr& ptr)
 {
     std::string mesh = MWWorld::Class::get(ptr).getModel(ptr);
     Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
     //TODO:optimize this. Searching the std::map isn't very efficient i think.
     mEngine->addCharacter(node->getName(), mesh, node->getPosition(), node->getScale().x, node->getOrientation());
 }
Exemple #2
0
Ogre::SceneNode * WheelAnimalSceneObj::getBaseCenter()
{
	if(_sn == NULL)
	{
		_sn =  Orz::OgreGraphicsManager::getSingleton().getSceneManager()->getRootSceneNode()->createChildSceneNode(getCenterPoint());
		//_sn->yaw(Ogre::Radian(Ogre::Math::PI));
		for(int i=0 ; i<(BASE_ALL-BASE_0); ++i)
		{
			Ogre::SceneNode * base = getBase(i);
			Ogre::Node * parent = base->getParent();
			Ogre::Vector3 p = base->getPosition();
			if(parent)
			{
				parent->removeChild(base);
			}
			base->translate(-getCenterPoint());
			_sn->addChild(base);
			Ogre::SceneManager * sm = OgreGraphicsManager::getSingleton().getSceneManager();
			Ogre::Entity * ent = sm->createEntity("ring"+Ogre::StringConverter::toString(i), "zp_dwdzgh.mesh");
			Ogre::SceneNode * node = base->createChildSceneNode("ring"+Ogre::StringConverter::toString(i),Ogre::Vector3(0.f, 10.f, 0.f));
			node->setScale(0.6f,0.6f,0.6f);
			node->attachObject(ent);
			Orz::OgreGraphicsManager::getSingleton().getSceneManager()->getSceneNode("ring"+Ogre::StringConverter::toString(i))->setVisible(false);
		}
	}
	return _sn;
}
bool TutorialApplication::mouseMoved(const OIS::MouseEvent& me) 
{ 
	// Move the camera around an origin point if the user is holding the right mouse button
	if(me.state.buttonDown(OIS::MB_Right))
	{
		int relativeX = me.state.X.rel;
		int relativeY = me.state.Y.rel;
		int relativeZ = me.state.Z.rel;

		Ogre::SceneNode* positionNode = mSceneMgr->getSceneNode("CAMERA_POSITION");
		Ogre::Vector3 pos = positionNode->getPosition();

		Ogre::Vector3 origin = Ogre::Vector3(0,0,0);
		Ogre::Vector3 scale = origin - pos;
		scale.normalise();
		
		
		//if(pos.z > 50.0f)
		//{
			positionNode->setPosition(pos+(scale*relativeZ));
		//}

		//currentDegree += ;

		if(currentDegree > maxDegree){ currentDegree = maxDegree; }
		if(currentDegree < minDegree){ currentDegree = minDegree; }

		Ogre::SceneNode* rotationNode = mSceneMgr->getSceneNode("CAMERA_ROTATION");
		rotationNode->rotate(Ogre::Quaternion(Ogre::Degree(relativeX*0.1f), Ogre::Vector3(0,1,0)) , Ogre::Node::TransformSpace::TS_WORLD);
		rotationNode->rotate(Ogre::Quaternion(Ogre::Degree(relativeY*0.1f), Ogre::Vector3(1,0,0)) , Ogre::Node::TransformSpace::TS_LOCAL);
	}
	return true; 
}
Exemple #4
0
void Cube::save(Ogre::String file)
{
  if (rndCounter == 0)
  {
    std::ofstream output(file.c_str());

    // Write cube size
    output << size << std::endl;

    for (int i = 0; i < size; ++i)
      for (int j = 0; j < size; ++j)
        for (int k = 0; k < size; ++k)
        {
          CubeElement *e = data[i][j][k];
          Ogre::Entity *ent = static_cast<Ogre::Entity*>(e->node->getAttachedObject(0));
          Ogre::SceneNode *node = e->node;
          // Write name, indexes and position
          output << node->getName() << "\n"
                 << "\t" << i << " " << j << " " << k << "\n" // index in data array
                 << "\t" << node->getPosition().x << " " << node->getPosition().y << " " << node->getPosition().z << "\n"; // position
          // Write orientation
          Ogre::Vector3 orient_axis;
          Ogre::Degree orient_angle;
          node->getOrientation().ToAngleAxis(orient_angle, orient_axis);
          output << "\t" << orient_axis.x << " " << orient_axis.y << " " << orient_axis.z << " " // orientation axis
                 << orient_angle.valueDegrees() << "\n"; // orientation angle
          output << "\t" << ent->getSubEntity(0)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(1)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(2)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(3)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(4)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(5)->getMaterialName() << "\n";
          // Write pivot info
          output << "\t" << e->isPivot << "\n";
          if (e->isPivot)
          {
            // pivot indexes
            output << "\t" << e->pivotArrays[0] << " " << e->pivotArrayIndexes[0] << "\n"
                   << "\t" << e->pivotArrays[1] << " " << e->pivotArrayIndexes[1] << "\n";
          }
          // flush
          output << std::endl;
        }

    output.close();
  }
}
Exemple #5
0
     void PhysicsSystem::insertObjectPhysics(const MWWorld::Ptr& ptr, const std::string model){

           Ogre::SceneNode* node = ptr.getRefData().getBaseNode();

           // unused
		   //Ogre::Vector3 objPos = node->getPosition();

         addObject (node->getName(), model, node->getOrientation(),
            node->getScale().x, node->getPosition());
     }
// Manage physics from this loop
// Please don't alter the Ogre scene manager directly. Instead use the designated methods (setPositionX, setPositionY, setPositionZ, setRoll, setPitch, setYaw, animate)
void loop(Ogre::SceneManager* smgr){
	int dir = 1;
	int timeStep = 10;
	while(true){
		// If the message array has any elements, the render loop is applying changes from physics loop
		// If so, abort this timestep
		if((*::message).size() == 1){
			continue;
		}
		Sleep(timeStep);
		Ogre::SceneManager::MovableObjectIterator iterator = smgr->getMovableObjectIterator("Entity");
		while(iterator.hasMoreElements()){
			// If the message array has any elements, the render loop is applying changes from physics loop
			// If so, abort this timestep
			if((*::message).size() == 1){
				continue;
			}
			Ogre::Entity* entity = static_cast<Ogre::Entity*>(iterator.getNext());

			// <>< <>< Make the cute fishy swim <>< <><
			// This only moves fish
			if(entity->hasAnimationState("swim")){
			
				Ogre::SceneNode* sceneNode = entity->getParentSceneNode();

				// Update position
				Ogre::Vector3 pos = sceneNode->getPosition();
				if(pos.x > 120){
					dir = -1;
					setYaw(entity, 180);
				}
				if(pos.x < -120){
					dir = 1;
					setYaw(entity, 180);
				}
				setPositionX(entity, sceneNode->getPosition().x + dir);
				animate(entity, "swim");
			}

		}
	}
}
AnimatPosition::AnimatPosition(Ogre::String sNodeName, Ogre::Vector3 newPos, float durationSeconds) {
	this->SceneNodeName = sNodeName;
	this->AnimatType = AnimatTypePosition;

	Ogre::SceneNode* node = LG::RendererOgre::Instance()->m_sceneMgr->getSceneNode(this->SceneNodeName);
	m_originalPosition = node->getPosition();
	m_targetPosition = newPos;
	m_durationSeconds = durationSeconds;
	m_distanceVector = m_targetPosition - m_originalPosition;
	m_progress = 0.0f;
};
Exemple #8
0
void Board::show(Ogre::SceneNode* const node)
{
    // corner node of a level
    Ogre::SceneNode* levNode = 0;
    Ogre::SceneNode* rowNode = 0;
    Ogre::SceneNode* colNode = 0;

    // index of the square in the vector of squares
    unsigned int i = 0;

    for(unsigned int level = 0; level < m_model->getLevels(); ++level)
    {
        levNode = (levNode == 0) ? node : levNode->createChildSceneNode();

        for(unsigned int row = 0; row < m_model->getRows(); ++row)
        {
            rowNode = (rowNode == 0 || row == 0) ? levNode : rowNode->createChildSceneNode();

            for(unsigned int col = 0; col < m_model->getCols(); ++col, ++i)
            {
                colNode = (col == 0) ? rowNode : colNode->createChildSceneNode();
                Ogre::Vector3 squareOrigin = colNode->getPosition();
                Color squareColor = ((row + col + level) % 2 == 0) ? COLOR_WHITE : COLOR_BLACK;
                m_squares[i] = new Square(colNode, squareColor);

                // correctly position the node
                if(level > 0 && row == 0 && col == 0)
                    // raise the square
                    squareOrigin.y += LEVEL_MARGIN;
                else if(row > 0 && col == 0)
                    // add a row to the board
                    squareOrigin.z -= m_squares[i]->getEntity()->getBoundingBox().getSize().z;
                else
                    // add a cell to a column of the board
                    squareOrigin.x += m_squares[i]->getEntity()->getBoundingBox().getSize().x;

                // update the node's position accordingly
                colNode->setPosition(squareOrigin);
            }
        }
    }

    // finally we center the entire board over the x and z axis
    // take a single square for reference
    Square* refSquare = m_squares[0];
    Ogre::Vector3 boardOrigin = node->getPosition();
    boardOrigin.x -= (refSquare->getEntity()->getBoundingBox().getSize().x * m_model->getCols()) / 2.0;
    boardOrigin.z += (refSquare->getEntity()->getBoundingBox().getSize().z * m_model->getRows()) / 2.0;
    node->setPosition(boardOrigin);
}
Exemple #9
0
void TranslationAnm::Fly()
{
    Ogre::SceneNode* node = m_pGameObj->getNode();
    Ogre::Vector3 pos = node->getPosition();
    if(m_pAnmState->getEnabled())
        return;
    Ogre::TransformKeyFrame* k_t0_0=m_pAnmTrack->getNodeKeyFrame(ANM_KEYFRAME_0);
    k_t0_0->setRotation(node->getOrientation());

    Ogre::TransformKeyFrame* k_t0_2=m_pAnmTrack->getNodeKeyFrame(ANM_KEYFRAME_1);
    k_t0_2->setRotation(node->getOrientation());

    m_pAnmState->setTimePosition(0);
    m_pAnmState->setEnabled(true);
}
Exemple #10
0
float3x4 EC_Mesh::LocalToParent() const
{
    if (!entity_)
    {
        LogError("EC_Mesh::LocalToParent failed! No entity exists in this mesh!");
        return float3x4::identity;
    }

    Ogre::SceneNode *node = entity_->getParentSceneNode();
    if (!node)
    {
        LogError("EC_Mesh::LocalToParent failed! Ogre::Entity is not attached to a Ogre::SceneNode!");
        return float3x4::identity;
    }

    return float3x4::FromTRS(node->getPosition(), node->getOrientation(), node->getScale());
}
Exemple #11
0
float3x4 EC_Mesh::LocalToParent() const
{
    if (!entity_)
    {
        LogError(QString("EC_Mesh::LocalToParent failed! No entity exists in mesh \"%1\" (entity: \"%2\")!").arg(meshRef.Get().ref).arg(ParentEntity() ? ParentEntity()->Name() : "(EC_Mesh with no parent entity)"));
        return float3x4::identity;
    }

    Ogre::SceneNode *node = entity_->getParentSceneNode();
    if (!node)
    {
        LogError(QString("EC_Mesh::LocalToParent failed! Ogre::Entity is not attached to a Ogre::SceneNode! Mesh \"%1\" (entity: \"%2\")!").arg(meshRef.Get().ref).arg(ParentEntity() ? ParentEntity()->Name() : "(EC_Mesh with no parent entity)"));
        return float3x4::identity;
    }

    return float3x4::FromTRS(node->getPosition(), node->getOrientation(), node->getScale());
}
Exemple #12
0
//-------------------------------------------------------------------------------------
bool
PlayersManager::moving(zappy::Player *p, int i)
{
  OPlayer *OPlayer = this->mOPlayers.at(i);
  this->speed = Constants::SquareSize /
    ((Constants::timeUnit / static_cast<Ogre::Real>(time)));

  Ogre::SceneNode *node = OPlayer->getSceneNode();
  Ogre::Vector3 &direction = OPlayer->getDirection();
  Ogre::Real &distance = OPlayer->getDistance();
  Ogre::Real move = this->speed * this->tslf;
  Ogre::Vector3 destination(p->getX() * Constants::SquareSize, 0, p->getY() * Constants::SquareSize);
  Ogre::AnimationState *anim = OPlayer->getEntity()->
    getAnimationState(distance <= 0.0f ? "Idle" : "Walk");

  anim->setLoop(true);
  anim->setEnabled(true);
  if (direction == Ogre::Vector3::ZERO)
    {
      Ogre::Vector3 src = node->getOrientation() * Ogre::Vector3::UNIT_X;
      direction = destination - node->getPosition();
      distance = direction.normalise();
      if ((1.0f + src.dotProduct(direction)) < 0.0001f)
        node->yaw(Ogre::Degree(180));
      else
        node->rotate(src.getRotationTo(direction));
      if (distance > Constants::SquareSize)
        distance = 0.0f;
    }
  else
    {
      distance -= move;
      if (distance <= 0.0f)
        {
          node->setPosition(destination);
          direction = Ogre::Vector3::ZERO;
        }
      else
        node->translate(direction * move);
    }
  if (OPlayer->stateHasChanged())
    OPlayer->detachAnim();
  anim->addTime(this->tslf);
  return true;
}
Exemple #13
0
void Player::reset() {
	Ogre::String floorTileName = "N" + Ogre::StringConverter::toString(4-position[1]) + Ogre::StringConverter::toString(position[0]);
	Ogre::SceneNode* floorTile = mSceneMgr->getSceneNode(floorTileName);
	Ogre::Vector3 floorTilePos = floorTile->getPosition();
	floorTilePos.y = 0;
	floorTile->setPosition(floorTilePos);
	mPlayerNode->setPosition(Ogre::Vector3(-400, 0, 400));

	rotated = false;
	position[0] = 0;
	position[1] = 0;
	mRotating = false;
	mRotatingLeft = false;
	walking = false;
	dying = false;
	dyingProgress = 1.0;
	nextKey = 0;
}
Exemple #14
0
//-------------------------------------------------------------------------------------
bool
PlayersManager::dying(zappy::Player *p, int i)
{
  OPlayer *OPlayer = this->mOPlayers.at(i);

  if (OPlayer->stateHasChanged())
    OPlayer->detachAnim();
  Ogre::Vector3 position(p->getX() * Constants::SquareSize, 0, p->getY() * Constants::SquareSize);
  Ogre::AnimationState *anim = OPlayer->getEntity()->
    getAnimationState("Die");
  Ogre::SceneNode *node = OPlayer->getSceneNode();
  if (position != node->getPosition())
      node->setPosition(position);
  anim->setEnabled(true);
  anim->setLoop(false);
  anim->addTime(this->tslf);
  return true;
}
Exemple #15
0
entityx::Entity Factory::createProjectile(entityx::ptr<EntityManager> where, Ogre::Vector3 pos, Ogre::Quaternion ori, Ogre::Real velocity, std::string materialName)
{
    Ogre::Entity *projMesh;
    Ogre::SceneManager *sceneMgr = RenderManager::getPtr()->getSceneManager();

    projMesh = sceneMgr->createEntity("ProjectileMesh.mesh");
    projMesh->setMaterialName(materialName);

    Entity proj = where->create();

    Ogre::SceneNode *projNode = sceneMgr->getRootSceneNode()->createChildSceneNode();
    projNode->attachObject(projMesh);

    Ogre::Light *light = sceneMgr->createLight();
    if(materialName == "RedLaser")
        light->setDiffuseColour(Ogre::ColourValue(.8, .2, .2));
    else
        light->setDiffuseColour(Ogre::ColourValue(.2, .2, .8));

    light->setType(Ogre::Light::LT_POINT);
    projNode->attachObject(light);



    projNode->setPosition(pos);
    projNode->setOrientation(ori);

    //projNode->translate(0, 0, -2, Ogre::SceneNode::TS_LOCAL);

    proj.assign<Position>(projNode->getPosition());
    proj.assign<Orientation>(ori);

    proj.assign<Velocity>(0, 0, velocity);
    proj.component<Velocity>()->direction.z = -1;
    proj.assign<Renderable>(projNode);
    proj.assign<AngularVelocity>(0, 0, 10);
    proj.assign<Name>("proiettile");
    proj.assign<LightComponent>(light);
    return proj;
}
 void PhysicsSystem::moveObject (const Ptr& ptr)
 {
     Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
     std::string handle = node->getName();
     Ogre::Vector3 position = node->getPosition();
     if (OEngine::Physic::RigidBody* body = mEngine->getRigidBody(handle))
     {
         // TODO very dirty hack to avoid crash during setup -> needs cleaning up to allow
         // start positions others than 0, 0, 0
         
         
         if(dynamic_cast<btBoxShape*>(body->getCollisionShape()) == NULL){
             btTransform tr = body->getWorldTransform();
             tr.setOrigin(btVector3(position.x,position.y,position.z));
             body->setWorldTransform(tr);
         }
         else{
             //For objects that contain a box shape.  
             //Do any such objects exist?  Perhaps animated objects?
             mEngine->boxAdjustExternal(handleToMesh[handle], body, node->getScale().x, position, node->getOrientation());
         }
     }
     if (OEngine::Physic::PhysicActor* act = mEngine->getCharacter(handle))
     {
         // TODO very dirty hack to avoid crash during setup -> needs cleaning up to allow
         // start positions others than 0, 0, 0
         if (handle == "player")
         {
             playerphysics->ps.origin = position;
         }
         else
         {
             act->setPosition(position);
         }
     }
 }
 void PhysicsSystem::addObject (const Ptr& ptr)
 {
     std::string mesh = MWWorld::Class::get(ptr).getModel(ptr);
     Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
     handleToMesh[node->getName()] = mesh;
     OEngine::Physic::RigidBody* body = mEngine->createAndAdjustRigidBody(mesh, node->getName(), node->getScale().x, node->getPosition(), node->getOrientation());
     mEngine->addRigidBody(body);
 }
Exemple #18
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
#else
int main (int argc, char *argv[]) {
#endif

	Ogre::Root *ogre;
	Ogre::RenderWindow *window;
	Ogre::SceneManager *sceneMgr;
	Ogre::SceneManager *guiSceneMgr;
	Ogre::Camera *camera;
	Ogre::Camera *guiCamera;

	// fire up an Ogre rendering window. Clearing the first two (of three) params will let us 
	// specify plugins and resources in code instead of via text file
	ogre = new Ogre::Root("", "");

#if defined(_DEBUG)
	ogre->loadPlugin("RenderSystem_GL_d");
#else
	ogre->loadPlugin("RenderSystem_GL");
#endif

	Ogre::RenderSystemList *renderSystems = NULL;
	Ogre::RenderSystemList::iterator r_it;

	renderSystems = ogre->getAvailableRenderers();
	r_it = renderSystems->begin();
	ogre->setRenderSystem(*r_it);
	ogre->initialise(false);

	// load common plugins
#if defined(_DEBUG)
	//ogre->loadPlugin("Plugin_CgProgramManager_d");		
	ogre->loadPlugin("Plugin_OctreeSceneManager_d");
#else
	//ogre->loadPlugin("Plugin_CgProgramManager");		
	ogre->loadPlugin("Plugin_OctreeSceneManager");
#endif
	// load the basic resource location(s)
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resource", "FileSystem", "General");
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resource/gui.zip", "Zip", "GUI");
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("meshes", "FileSystem", "Meshes");
#if defined(WIN32)
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("c:\\windows\\fonts", "FileSystem", "GUI");
#endif

	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("General");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("GUI");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Meshes");

	// setup main window; hardcode some defaults for the sake of presentation
	Ogre::NameValuePairList opts;
	opts["resolution"] = "1024x768";
	opts["fullscreen"] = "false";
	opts["vsync"] = "false";

	// create a rendering window with the title "CDK"
	window = ogre->createRenderWindow("Bouwgame Client v0.1", 1024, 768, false, &opts);

	// since this is basically a CEGUI app, we can use the ST_GENERIC scene manager for now; in a later article 
	// we'll see how to change this
	sceneMgr = ogre->createSceneManager(Ogre::ST_GENERIC);
	guiSceneMgr = ogre->createSceneManager(Ogre::ST_GENERIC);

	guiCamera = guiSceneMgr->createCamera("GUICamera");
	guiCamera->setNearClipDistance(5);
	camera = sceneMgr->createCamera("camera");
	camera->setNearClipDistance(5);
    Ogre::Viewport* vp = window->addViewport(guiCamera);
    vp->setBackgroundColour(Ogre::ColourValue(0.2f,0.2f,0.8f));

	/* ambient light */
	sceneMgr->setAmbientLight(Ogre::ColourValue(0.8, 0.8, 0.8));
	sceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);

	/* meshes */
	Ogre::Entity* ent = sceneMgr->createEntity( "BouwPlaatsEntity", "world.mesh" );
	Ogre::SceneNode* node = sceneMgr->getRootSceneNode()->createChildSceneNode("BouwNode", Ogre::Vector3(0, 0, 0));
    node->attachObject(ent);
	//node->setScale(Ogre::Vector3(0.7,0.7,0.7));

	ent = sceneMgr->createEntity("plaats", "bouwplaats_step_00.mesh");
	Ogre::Vector3 size = ent->getBoundingBox().getSize();
	Ogre::LogManager::getSingletonPtr()->getDefaultLog()->logMessage(Ogre::String("Bouwplaats size: ") + Ogre::StringConverter::toString(size));
	size = ent->getBoundingBox().getMaximum();
	Ogre::LogManager::getSingletonPtr()->getDefaultLog()->logMessage(Ogre::String("Bouwplaats max: ") + Ogre::StringConverter::toString(size));
	size = ent->getBoundingBox().getMinimum();
	Ogre::LogManager::getSingletonPtr()->getDefaultLog()->logMessage(Ogre::String("Bouwplaats min: ") + Ogre::StringConverter::toString(size));

    Ogre::Entity* ent1 = sceneMgr->createEntity( "KeetEntity", "keet.mesh" );
	Ogre::SceneNode* scenenode = sceneMgr->getRootSceneNode()->createChildSceneNode("KeetNode", Ogre::Vector3(0, 0, 0));
    scenenode->attachObject(ent1);

	
	Ogre::Entity* ent2 = sceneMgr->createEntity( "HekjeEntity", "hekje.mesh" );
	Ogre::SceneNode* scenenode2 = sceneMgr->getRootSceneNode()->createChildSceneNode("HekjeNode", Ogre::Vector3(0, -100, 0));
    scenenode2->attachObject(ent2);
	scenenode2->setScale(Ogre::Vector3(400,0,100));

	// most examples get the viewport size to calculate this; for now, we'll just 
	// set it to 4:3 the easy way
	camera->setAspectRatio((Ogre::Real)1.333333);
	camera->setPosition(Ogre::Vector3(40,100,10));
	guiCamera->setPosition(0, 0, 300);
	guiCamera->lookAt(node->getPosition());

	// this next bit is for the sake of the input handler
	unsigned long hWnd;
	window->getCustomAttribute("WINDOW", &hWnd);

	
	// set up the input handlers
	Simulation *sim = new Simulation();
	InputHandler *handler = new InputHandler(sim, hWnd, camera);
	DataManager *dataManager = new DataManager();
	GameAI* gameAI = new GameAI(dataManager);

	//Create Network
	Network * net = new Network(dataManager);
	//net->start();

	sim->requestStateChange(GUI);
	gui = new GuiManager();

	// networkshit
	while(!net->isConnected())
	{
		Sleep(1000);
	}
	net->Send(GETGROUPS, "", "", NULL);
	net->Send(LOGIN, "gast", "gast", 1);

	gui->setSimulation(sim);
	gui->init("", ogre, guiSceneMgr, window);
	gui->activate("main");
	handler->setWindowExtents(1024,768);
	
	SimulationState cState;
	Ogre::WindowEventUtilities::addWindowEventListener(window, handler);

	DWORD tFrameStart = 0x0; //in miliseconds
	signed long tFrameX = 0x0;
	float tDelta2 = 0.0f; //in seconds
	float m_fps = 60.0f;
	tFrameStart = GetTickCount();

	float tDelta;

	//testAI->calculateNextPath(40,10);

	while ((cState = sim->getCurrentState()) != SHUTDOWN) {

		tFrameX = GetTickCount() - tFrameStart;
		tDelta2 = (float)tFrameX / 1000.0f;
		if (tDelta2 > 3600) // tDelta > 1 hour
			tDelta2 = 1.0f / m_fps; //< System tick count has highly likely overflowed, so get approximation
		tFrameStart = GetTickCount();
		m_fps = (int)(1.0f / tDelta2);

		tDelta = tDelta2;

		handler->capture();
		handler->update(tDelta);
		gui->update(tDelta);

		//if (sim->getCurrentState() == SIMULATION || sim->getCurrentState() == SIMULATION_MOUSELOOK)
//			testAI->update(tDelta);

		// run the message pump (Eihort)
		Ogre::WindowEventUtilities::messagePump();

		ogre->renderOneFrame();

		if (sim->getCurrentState() != cState) {
			handler->StateSwitched(cState, sim->getCurrentState());
			switch (sim->getCurrentState()) {
				case GUI:
					window->getViewport(0)->setCamera(guiCamera);
					break;
				case SIMULATION:
					window->getViewport(0)->setCamera(camera);
					break;
			}
		}

	}

	// clean up after ourselves
	//delete testAI;
	delete sim;
	delete ogre;
	delete handler;
	delete gameAI;
	delete dataManager;

	return 0;
}
// BETWEEN FRAME OPERATION
void VisCalcFrustDist::calculateEntityVisibility(Ogre::Node* regionNode, Ogre::Node* node, bool recurse) {
	if (recurse && node->numChildren() > 0) {
		// if node has more children nodes, visit them recursivily
		Ogre::SceneNode::ChildNodeIterator nodeChildIterator = node->getChildIterator();
		while (nodeChildIterator.hasMoreElements()) {
			Ogre::Node* nodeChild = nodeChildIterator.getNext();
			// 'false' causes it to not visit sub-children which are included in parent and pos relative to parent
			calculateEntityVisibility(regionNode, nodeChild, false);
			visChildren++;
		}
	}
	visNodes++;
	// children taken care of... check fo attached objects to this node
	Ogre::SceneNode* snode = (Ogre::SceneNode*)node;
	// the camera needs to be made relative to the region
	// Ogre::Vector3 relCameraPos = LG::RendererOgre::Instance()->m_camera->getPosition() - regionNode->getPosition();
	// float snodeDistance = LG::RendererOgre::Instance()->m_camera->getPosition().distance(snode->_getWorldAABB().getCenter());
	// float snodeDistance = relCameraPos.distance(snode->getPosition());
	float snodeDistance = LG::RendererOgre::Instance()->m_camera->getDistanceFromCamera(regionNode, snode->getPosition());
	Ogre::SceneNode::ObjectIterator snodeObjectIterator = snode->getAttachedObjectIterator();
	while (snodeObjectIterator.hasMoreElements()) {
		Ogre::MovableObject* snodeObject = snodeObjectIterator.getNext();
		if (snodeObject->getMovableType() == "Entity") {
			visEntities++;
			Ogre::Entity* snodeEntity = (Ogre::Entity*)snodeObject;
			// check it's visibility if it's not world geometry (terrain and ocean)
			if ((snodeEntity->getQueryFlags() & Ogre::SceneManager::WORLD_GEOMETRY_TYPE_MASK) == 0) {
				// computation if it should be visible
				// Note: this call is overridden by derived classes that do fancier visibility rules
				bool shouldBeVisible = this->CalculateVisibilityImpl(LG::RendererOgre::Instance()->m_camera, snodeEntity, snodeDistance);
				if (snodeEntity->isVisible()) {
					// we currently think this object is visible. make sure it should stay that way
					if (shouldBeVisible) {
						// it should stay visible
						visVisToVis++;
					}
					else {
						// not visible any more... make invisible nad unload it`
						/*
						Ogre::Vector3 cPos = LG::RendererOgre::Instance()->m_camera->getPosition();
						Ogre::Vector3 rPos = regionNode->getPosition();
						Ogre::Vector3 sPos = snode->getPosition();
						LG::Log("VisToInVis: cPos=<%f,%f,%f>, rPos=<%f,%f,%f>, sPos(%s)=<%f,%f,%f>, d=%f", 
								cPos.x, cPos.y, cPos.z, 
								rPos.x, rPos.y, rPos.z, 
								snode->getName().c_str(),
								sPos.x, sPos.y, sPos.z, 
								snodeDistance);
								*/
						snodeEntity->setVisible(false);
						snode->needUpdate(true);
						visVisToInvis++;
						if (!snodeEntity->getMesh().isNull()) {
							queueMeshUnload(snodeEntity->getMesh());
						}
					}
				}
				else {
					// the entity currently thinks it's not visible.
					// check to see if it should be visible by checking a fake bounding box
					if (shouldBeVisible) {
						// it should become visible again
						if (!snodeEntity->getMesh().isNull()) {
							// queueMeshLoad(snodeEntity, snodeEntity->getMesh());
							LG::OLMeshTracker::Instance()->MakeLoaded(snodeEntity->getMesh()->getName(),
									Ogre::String(""), Ogre::String("visible"), snodeEntity);
						}
						// snodeEntity->setVisible(true);	// must happen after mesh loaded
						visInvisToVis++;
					}
					else {
						visInvisToInvis++;
					}
				}
			}
		}
	}
}
Exemple #20
0
bool BaseApplication::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
    if(mWindow->isClosed())
        return false;

    //run save code then shut down

    if(mShutDown)
    {
        if(mStats->isLoggedIn())
        {
            mStats->save();
        }
        return false;
    }
    // Need to capture/update each device
    mKeyboard->capture();
    mMouse->capture();
    if(!mMusic)
    {
        Mix_PauseMusic();
        Mix_Volume(-1, 0);
        if(bgm)
        {
             Mix_ResumeMusic();
        }
        if(soundeffect)
        {
             Mix_Volume(-1, 110);
        }
    }
    else if(mMusic)
    {
        Mix_ResumeMusic();
        Mix_Volume(-1, 110);
        if(!bgm)
        {
             Mix_PauseMusic();
        }
        if(!soundeffect)
        {
             Mix_Volume(-1, 0);
        }
    }
    if(mGameStart && !mInMenu)
    {
        if(player->levelFinished)
        {
            if(mStats->isLoggedIn())
            {
                mStats->update(mDifficulty, mLevel, mDeathCounter, mStopwatch->elapsedTime(), true);
            }
            calcNextLevel();
            deleteMap();
            createObjects();
            mLevelName->setCaption(gameMap->getName());
            mStopwatch->reset();
            mDeathCounter = 0;
            mNumDeaths->setCaption(patch::to_string(mDeathCounter) + " deaths");
            //SAVE AND LOAD
        }

        mPlayerHp->setProgress((player->health)/100.0);
        mPlayerHp->setCaption("current HP is " + patch::to_string(player->health) + "/100");
        mTime->setCaption(patch::to_string(int(mStopwatch->elapsedTime() / 100.0 ) / 10.0) + " seconds");
        Ogre::SceneNode* tem = mSceneMgr->getSceneNode("playerNode");    
        Ogre::Vector3 position = tem->getPosition();
        mCamera->setPosition(position.x , 300, position.z+200);
        if(gameMap->isPlayerAlive())
        {
            if(wisDown)
                gameMap->move(0);
            else if(disDown)
                gameMap->move(1);
            else if(sisDown)
                gameMap->move(2);
            else if(aisDown)
                gameMap->move(3);
            if(!mStopwatch->isRunning() && (sisDown || wisDown || disDown || aisDown))
            {
                mStopwatch->start();
            }
        }
        else
        {
            setupDeathMenu();  
            mTrayMgr->showCursor();
            mCanRespawn = true;
        }
        gameMap->simulate(evt.timeSinceLastFrame);  
        // mSimulator->stepSimulation(evt.timeSinceLastFrame, music2);
    }
    else if (!mGameStart) //should be the loadinglevel
    {
        if(!levelLoaded)
        {
            mDifficulty = 0;
            mLevel = 0;
            mOldDifficulty =0;
            createObjects();       
            levelLoaded = true;   
            Ogre::SceneNode* tem = mSceneMgr->getSceneNode("playerNode");    
            Ogre::Vector3 position = tem->getPosition();
            mCamera->setPosition(position.x , 300, position.z+300);        
        }
        else
        {
            gameMap->simulate(evt.timeSinceLastFrame);
        }
    }

    mTrayMgr->frameRenderingQueued(evt);

    if (!mTrayMgr->isDialogVisible())
    {
        mCameraMan->frameRenderingQueued(evt);   // If dialog isn't up, then update the camera
        if (mDetailsPanel->isVisible())          // If details panel is visible, then update its contents
        {
            mDetailsPanel->setParamValue(0, Ogre::StringConverter::toString(mCamera->getDerivedPosition().x));
            mDetailsPanel->setParamValue(1, Ogre::StringConverter::toString(mCamera->getDerivedPosition().y));
            mDetailsPanel->setParamValue(2, Ogre::StringConverter::toString(mCamera->getDerivedPosition().z));
            mDetailsPanel->setParamValue(4, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().w));
            mDetailsPanel->setParamValue(5, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().x));
            mDetailsPanel->setParamValue(6, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().y));
            mDetailsPanel->setParamValue(7, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().z));
        }
    }

    return true;
}
Exemple #21
0
Entity Factory::createTank(entityx::ptr<entityx::EntityManager> entityMgr, std::string prefix,Ogre::Real velocity,Ogre::Real angularVelocity ,Ogre::Vector3 overHating,int health,bool ai)
{
    DotSceneLoader loader;
    Ogre::SceneManager* sceneMgr = RenderManager::getPtr()->getSceneManager();

    loader.parseDotScene("tank.scene", "General", sceneMgr, 0, prefix);

    Ogre::SceneNode* ctl = sceneMgr->getSceneNode(prefix + "TankControl");
    Ogre::SceneNode* body = sceneMgr->getSceneNode(prefix + "TankBody");
    Ogre::SceneNode* turret = sceneMgr->getSceneNode(prefix + "TankTurret");
    Ogre::SceneNode* cannon = sceneMgr->getSceneNode(prefix +"TankCannon");

    Entity tankEmptyControl = entityMgr->create();
    Entity tankTurret = entityMgr->create();
    Entity tankBody = entityMgr->create();
    Entity tankCannon = entityMgr->create();

    tankEmptyControl.assign<Position>(ctl->getPosition());
    tankEmptyControl.assign<Orientation>(ctl->getOrientation());
    tankEmptyControl.assign<Velocity>(0, 0, velocity);
    tankEmptyControl.assign<AngularVelocity>(0, angularVelocity, 0);
    tankEmptyControl.assign<Renderable>(ctl);
    tankEmptyControl.assign<OverHeating>(overHating.x,overHating.y,overHating.z);
    tankEmptyControl.assign<Destroyable>(health,health);
    tankEmptyControl.assign<Collidable>();
    tankEmptyControl.assign<Name>(prefix);
    if(ai){
        tankEmptyControl.assign<AI>();
        Ogre::Entity *model = static_cast<Ogre::Entity*>(body->getAttachedObject(0));
        model->getSubEntity(1)->setMaterialName("Red");

        model = static_cast<Ogre::Entity*>(turret->getAttachedObject(0));
        model->getSubEntity(1)->setMaterialName("Red");

        model = static_cast<Ogre::Entity*>(cannon->getAttachedObject(0));
        model->getSubEntity(1)->setMaterialName("Red");

    }

    ptr<Children> child = tankEmptyControl.assign<Children>();
    child->children["body"] = tankBody;
    child->children["turret"] = tankTurret;
    //child->children.push_back(tankBody);
    //child->children.push_back(tankTurret);

    tankTurret.assign<Position>(turret->getPosition());
    tankTurret.assign<Orientation>(turret->getOrientation());
    tankTurret.assign<Renderable>(turret);
    child = tankTurret.assign<Children>();
    child->children["cannon"] = tankCannon;

    tankBody.assign<Position>(body->getPosition());
    tankBody.assign<Orientation>(body->getOrientation());
    tankBody.assign<Renderable>(body);

    tankCannon.assign<Position>(cannon->getPosition());
    tankCannon.assign<Renderable>(cannon);
    tankCannon.assign<Orientation>(cannon->getOrientation());


    ctl->scale(.35, .55, .35);
    return tankEmptyControl;
}
Exemple #22
0
void EC_Clone::Create()
{
    if (renderer_.expired())
        return;

    Ogre::SceneManager *scene = renderer_.lock()->GetSceneManager();
    assert(scene);
    if (!scene)
        return;

    Scene::Entity *entity = GetParentEntity();
    assert(entity);
    if (!entity)
        return;

    EC_Placeable *placeable = entity->GetComponent<EC_Placeable>().get();
    assert(placeable);
    if (!placeable)
        return;

    Ogre::SceneManager *sceneMgr = renderer_.lock()->GetSceneManager();
    assert(sceneMgr);
    if (!sceneMgr)
        return;

    Ogre::Entity *originalEntity  = 0;
    Ogre::SceneNode *originalNode = 0;

    // Check out if this entity has EC_Mesh or EC_OgreCustomObject.
    if (entity->GetComponent(EC_Mesh::TypeNameStatic()))
    {
        EC_Mesh *ec_mesh= entity->GetComponent<EC_Mesh>().get();
        assert(ec_mesh);

        originalEntity = ec_mesh->GetEntity();
        //originalNode = placeable->GetSceneNode();
        originalNode = ec_mesh->GetAdjustmentSceneNode();

        sceneNode_ = sceneMgr->createSceneNode();
        sceneNode_->setPosition(originalNode->getPosition());
        originalNode->addChild(sceneNode_);
    }
    else if(entity->GetComponent(EC_OgreCustomObject::TypeNameStatic()))
    {
        EC_OgreCustomObject *ec_custom = entity->GetComponent<EC_OgreCustomObject>().get();
        assert(ec_custom);
        if (!ec_custom->IsCommitted())
        {
            LogError("Mesh entity have not been created for the target primitive. Cannot create EC_Clone.");
            return;
        }

        originalEntity = ec_custom->GetEntity();
        originalNode = placeable->GetSceneNode();

        sceneNode_ = sceneMgr->createSceneNode();
        sceneNode_->setPosition(originalNode->getPosition());
        originalNode->addChild(sceneNode_);
    }
    else
    {
        LogError("This entity doesn't have either EC_Mesh or EC_OgreCustomObject present. Cannot create EC_Clone.");
        return;
    }

    assert(originalEntity);
    if (!originalEntity)
        return;

    assert(sceneNode_);
    if (!sceneNode_)
        return;

    // Clone the Ogre entity.
    cloneName_ = renderer_.lock()->GetUniqueObjectName("EC_Clone_ent");
    entityClone_ = originalEntity->clone(cloneName_);
    assert(entityClone_);

    // Disable casting of shadows for the clone.
    entityClone_->setCastShadows(false);

    ///\todo If original entity has skeleton, (try to) link it to the clone.
/*
    if (originalEntity->hasSkeleton())
    {
        Ogre::SkeletonInstance *skel = originalEntity->getSkeleton();
        // If sharing a skeleton, force the attachment mesh to use the same skeleton
        // This is theoretically quite a scary operation, for there is possibility for things to go wrong
        Ogre::SkeletonPtr entity_skel = originalEntity->getMesh()->getSkeleton();
        if (entity_skel.isNull())
        {
            LogError("Cannot share skeleton for attachment, not found");
        }
        else
        {
            try
            {
                entityClone_->getMesh()->_notifySkeleton(entity_skel);
            }
            catch (Ogre::Exception &e)
            {
                LogError("Could not set shared skeleton for attachment: " + std::string(e.what()));
            }
        }
    }
*/

    const std::string &material_name = "Clone";
    try
    {
        entityClone_->setMaterialName(material_name);
    }
    catch (Ogre::Exception &e)
    {
        LogError("Could not set material \"" + std::string(material_name) + "\": " + std::string(e.what()));
        return;
    }

    sceneNode_->attachObject(entityClone_);
}
//-------------------------------------------------------------------------------------
void Practical4::createScene(void)
{
    // Create the ground with grass on it
 	Ogre::Plane plane;
    plane.normal = Ogre::Vector3::UNIT_Y;
	// horizontal plane with normal up in y-direction
   	plane.d = 0;//Plane passes through the origin i.e. plane at y = 0
    Ogre::MeshManager::getSingleton().createPlane("floor", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, 4500,4500,10,10,true,1,10,10,Ogre::Vector3::UNIT_Z);
   	Ogre::Entity* pPlaneEnt = mSceneMgr->createEntity("plane", "floor");
    pPlaneEnt->setMaterialName("Examples/GrassFloor");
   	pPlaneEnt->setCastShadows(false);
	Ogre::SceneNode* floorNode = mSceneMgr->createSceneNode("floor1");
	mSceneMgr->getRootSceneNode()->addChild(floorNode);
	floorNode->attachObject(pPlaneEnt);


    // Set ambient light
    mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));

    // Create a light
    Ogre::Light* l = mSceneMgr->createLight("MainLight");
    l->setPosition(20,80,50);


	// Now to draw a ball on the ground at the origin
	// First create a ball Entity from an Ogre model
	Ogre::Entity* ball = mSceneMgr->createEntity("sphere1","geosphere8000.mesh");
	ball->setMaterialName("Examples/Hilite/Yellow");
	double ballModelRadius = 200; // Radius of actual model in //"geosphere8000.mesh"
	double ballScale = 0.02;//To multiply radius by this factor
	double ballRadius;  // To store actual radius used here

	// Create a new sceneNode and attach it to the rootSceneNode 
	//as a child of the scene manager
	Ogre::SceneNode* ballNode = mSceneMgr->createSceneNode("sphere1");
	mSceneMgr->getRootSceneNode()->addChild(ballNode);
	ballNode->attachObject(ball);

	// Amend the properties of the ball to suit your purposes
	ball->setCastShadows(true);
	ballNode->scale(ballScale, ballScale, ballScale);
	ballRadius = ballScale*ballModelRadius; // Actual radius 
	ballNode->setPosition(Ogre::Vector3(0,ballRadius,0)); // position //the ball on top of the ground
	// Create an instance of the PhysicsObject class
	m_sphereObject = new PhysicsObject();
	// Now initialise all of it’s properties to match the //graphics model of the sphere as in ballNode
	m_sphereObject->initialise(ballNode,ballRadius,ballNode->getPosition(),Ogre::Vector3(0,30,0), 10.0f, 10.0f);


	//Ogre::Entity *cube = mSceneMgr->createEntity("cube", "cube.mesh");
	//// Choose a material texture for the cube
	//cube->setMaterialName("Examples/RustySteel");
	//// Create a new sceneNode for the cube, attach it to the rootSceneNode 
	////as a child of the scene manager
	//Ogre::SceneNode *cubeNode = mSceneMgr->createSceneNode("cubeNode");
	//mSceneMgr->getRootSceneNode( )->addChild(cubeNode);
	//cubeNode->attachObject( cube );
	//cube->setCastShadows(true);
	//float cubeModelLength = 100;  // The cube actual model size
	//float cubeLength = 2;  // The cube size that we want
	//// Change size of graphics drawing of cube to that of cubeLength
	//double cubeScale = cubeLength/cubeModelLength;
	//cubeNode->scale(cubeScale, cubeScale, cubeScale);
	//	
	//// Position the cube to sit exactly on the ground
	//cubeNode-> setPosition(Ogre::Vector3(0, cubeLength/2,0));


}
Exemple #24
0
	void preViewportUpdate(const Ogre::RenderTargetViewportEvent & evt)
	{
		const Ogre::Vector3& cameraPos = evt.source->getCamera()->getDerivedPosition();
		mWaterNode->setPosition(cameraPos.x - std::fmod(cameraPos.x, mXTextureSize), mWaterNode->getPosition().y, cameraPos.z - std::fmod(cameraPos.z, mZTextureSize));

	}
//-------------------------------------------------------------------------------------
void RollerCoaster::mouseMoveEvent( QMouseEvent *event )
{
	lastPos=event->pos();
	//bLMouseDown = true;



	float RatioX = float (lastPos.x())/mCamera->getViewport()->getActualWidth();
	float RatioY = float (lastPos.y())/mCamera->getViewport()->getActualWidth();
	if(bLMouseDown){
	using namespace Ogre;
	Ray mouseRay=mCamera->getCameraToViewportRay(RatioX,RatioY);
	std::pair<bool, Real>point =mouseRay.intersects(mPlane);
	if(point.first)
	{
		Vector3 pos= mouseRay.getPoint(point.second);
		SceneNode *tempSn = mSceneMgr->getRootSceneNode()->createChildSceneNode();
		Entity *tempEn = mSceneMgr->createEntity("ogrehead.mesh");
		tempSn->attachObject(tempEn);
		tempSn->setPosition(pos);
		tempSn->setScale(0.1,0.1,0.1);
	}


	}
	if( bLMouseDown )
	{
		mCurrentObjName = objControl->mouseDragged(
			lastPos,
			event->pos(),
			mCamera->getViewport()->getActualWidth(), 
			mCamera->getViewport()->getActualHeight()
		);

		if( !mCurrentObjName.empty() )
		{
			Ogre::SceneNode *currObj = mSceneMgr->getSceneNode(mCurrentObjName);
			if (currObj)
			{
				bReplan = true;

				mTrack->mMove(currObj->getName(), currObj->getPosition());
				mTrack->mRotate(currObj->getName(), currObj->getOrientation().yAxis());
			}
		}
	}
	//==== 當按下滑鼠右鍵 ====//
	if( event->buttons().testFlag(Qt::RightButton) && lastPos != invalidMousePoint )
	{
		if( currCamType != eWorld ) return;

		mCamWorldNode = mCamera->getParentSceneNode();

		Ogre::Degree rotX(0);
		Ogre::Degree rotY(0);
		int dx = event->pos().x()-lastPos.x();
		int dy = event->pos().y()-lastPos.y();
		rotX += Ogre::Degree(-dx * 0.0025f * ROT_SCALE);		// Rotate camera horizontaly
		rotY += Ogre::Degree(-dy * 0.0025f * ROT_SCALE);		// Rotate camera vertical

		mCamWorldNode->yaw	( rotX, Ogre::Node::TS_WORLD );
		mCamWorldNode->pitch( rotY, Ogre::Node::TS_LOCAL );

		objControl->update();
	}

	lastPos = event->pos();
}
Exemple #26
0
 Vector3d getOgrePosition() const {
     return fromOgre(mSceneNode->getPosition(), getScene()->getOffset());
 }
//---------------------------------------------------------------------------------------
bool DigitalForensicsVisualisation::visualise(const CEGUI::EventArgs &e)
{
	try
	{
		mSceneMgr->getRootSceneNode()->removeAndDestroyChild("FilesNode");
		mSceneMgr->destroyAllMovableObjects(); //does not destroy movable texts, they are needed to be destroyed manually
		mSceneMgr->destroyAllManualObjects();
		cubeCount = pyramidCount = cylinderCount = 0;

		for (unsigned long int i = 0; i < textArrIndex; ++i)
		{
			textArr[textArrIndex]->~MovableText();
			
			textArr[textArrIndex] = NULL;
		}

		textArrIndex = 0;
	}
	catch(std::exception& e)
	{
		//do nothing
		OutputDebugString("DID NOTHING\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nnREALLYDIDNOTHING\nn");
	}

	beginProgress();

	const float radius = 1000;
	const float thickness = radius - 45;
	

	try
	{

		MYSQL_RES *res_set; /* Create a pointer to recieve the return value.*/
		MYSQL_ROW row;  /* Assign variable for rows. */
 
		OutputDebugString(buildQuery().c_str());
		res_set = mysqlExecute(buildQuery().c_str());
		unsigned long long int numrows = mysql_num_rows(res_set); /* Create the count to print all rows */
 

		float distFromCentre = radius - thickness;
		unsigned long long int itemIndex = 0;
		char containerName[50]; //for container
		char fileName[50]; //for fileName
		char fontName[50]; //for fontName

		filesNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("FilesNode");
		filesNode->setPosition (0, -300, -500);

		srand(time(NULL));

		

		for (float y = radius - thickness; y <= radius; y += Ogre::Math::PI * 6)
		{

			//progress_bar->setProgress(progress_bar->getProgress() + ( 1/ (Ogre::Math::PI / (thickness * thickness))));

			for (float theta = 0; theta <= Ogre::Math::PI * 1.8; theta += Ogre::Math::PI / (distFromCentre / 6)) 
			{
				if ((row = mysql_fetch_row(res_set)) == NULL)
					goto exit;

			
				try
				{	

					app.e.name = row[0];
					app.e.directory = row[1];
					app.e.size = std::stoull(row[2]); //for unsigned long long
					
					app.e.setExtension();
					std::string ext = app.e.extension;
			
					for (unsigned int i = 0; i < ext.length(); ++i)
					{
						ext[i] = std::toupper(ext[i]);
					}

					app.e.extension = ext;

					app.e.write_permission = std::stoi(row[4]);
					app.e.access_permission = std::stoi(row[5]);
					app.e.creation_time = row[6];
					app.e.access_time = row[7];
					app.e.modification_time = row[8];
					app.e.c = std::stoi(row[9]);
					app.e.a = std::stoi(row[10]);
					app.e.m = std::stoi(row[11]);
			
				}
				catch(std::exception& e)
				{	
					OutputDebugString(e.what());
					OutputDebugString("SIZEEXCEPTIONNN\nn\n\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\n\nn\nn\nn\nn\nnn\nn\nSIZEEXCEPTIONNN\nn\n");
					app.e.creation_time = app.e.modification_time = app.e.access_time = app.e.name = "exception occured";
				
				}

				sprintf(containerName,"container_%d",itemIndex);
				sprintf(fontName,"font_%d", itemIndex);
				sprintf(fileName, "file_%d", itemIndex++);

				Ogre::SceneNode* container = filesNode->createChildSceneNode(containerName);
				Ogre::SceneNode* fsn = container->createChildSceneNode(fileName);
				Ogre::SceneNode* fontNode = container->createChildSceneNode(fontName);
				Ogre::SceneNode* textureNode;
				bool isTexture = app.e.isTextureFile();
				if (isTexture)
				{
					try
					{
					
						char textureName[50];
						sprintf(textureName,"texture_%d",itemIndex-1);
						std::stringstream ss;
						ss << app.e.directory << "/" << app.e.name;
						//loads and adds the image to the resources/////
						
						Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName("MyMaterial2");
						Ogre::MaterialPtr matClone = material->clone(textureName);
						loadImageFile(textureName,ss.str());
						matClone->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName(textureName);
						
						textureNode = container->createChildSceneNode(textureName);
						textureNode->attachObject(rectangle(textureName));
						textureNode->setPosition(y * cos(theta), 0, y * sin(theta));
						textureNode->scale(.09,((float) app.e.size / 20000000 + 0.1),.09);
					}
					catch(std::exception e)
					{
						
						OutputDebugStringA("\nm\nm\nm\nm\nm\nm\nm\nm");
						OutputDebugStringA(e.what());
					};


					


				}

				ColorMap cm(app.e.extension);
			

				if (colorTree.search(cm) == NULL)
					colorTree.insert(cm);
				else
					cm = colorTree.search(cm)->data;
				

		

			
				
				if ((app.e.write_permission == 1) && (app.e.access_permission == 1))
					fsn ->attachObject(cube(true, cm));
				else if ((app.e.write_permission == 1) && (app.e.access_permission == 0))
					fsn->attachObject(cube(false, cm));
				else if ((app.e.write_permission == 0) && (app.e.access_permission == 1))
				{
					fsn -> attachObject(pyramid(cm));
					fsn -> scale (1.3, 1.3, 1.3);
				}
				else
				{
					fsn->attachObject(cylinder(cm));
					fsn->pitch((Ogre::Radian) Ogre::Math::PI);
					if (isTexture)
						textureNode->scale(.8,1,.8);
					
				}
				std::stringstream ss;
				ss << "file name: " << app.e.name << "\n\nlast access time: " << app.e.access_time << "\nmodification time: " 
					<< app.e.modification_time << "\ncreation time: " << app.e.creation_time;
				std::string s = ss.str();
			
				textArr[textArrIndex] = new Ogre::MovableText("tayyar", (s));
				textArr[textArrIndex] ->setTextAlignment(Ogre::MovableText::H_CENTER, Ogre::MovableText::V_CENTER); // Center horizontally and display above the node	
				textArr[textArrIndex] ->setColor(Ogre::ColourValue(1,1,1,.65));

				fontNode->attachObject(textArr[textArrIndex++]);

				fsn->setPosition(y * cos(theta), 0, y * sin(theta));
				fontNode->setPosition(fsn->getPosition().x + 6, fsn->getPosition().y, fsn->getPosition().z + 3.75);
			

				fsn->scale(.09,((float) app.e.size / 20000000 + 0.1),.09);

		

				OutputDebugString(fileName);
				OutputDebugString("\n");
			
			}

			distFromCentre += Ogre::Math::PI * 6;
		
		}

	
	}
	catch(std::exception& e)
	{
		OutputDebugString(e.what());
		OutputDebugString("EXCEPTIONNN\nn\n\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\n\nn\nn\nn\nn\nnn\nn\nEXCEPTIONNN\nn\n");
					
	}
	
	exit:
	endProgress();
	return true;
}
Exemple #28
0
void PhysicsWorld::detectCollisions(void) 
{
    int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();

    int ballContacts = 0;


    for(int i = 0; i < numManifolds; ++i) 
    {
        btPersistentManifold* contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
        btCollisionObject* objectA = const_cast<btCollisionObject*>
          ((btCollisionObject*)contactManifold->getBody0());
        btCollisionObject* objectB = const_cast<btCollisionObject*>
          ((btCollisionObject*)contactManifold->getBody1());

        void* userPointerA = objectA->getUserPointer();
        void* userPointerB = objectB->getUserPointer();

        Ogre::SceneNode* snA;
        Ogre::SceneNode* snB;

        if(userPointerA) snA = static_cast<Ogre::SceneNode*>(userPointerA);
        if(userPointerB) snB = static_cast<Ogre::SceneNode*>(userPointerB);
        
        int numContacts = contactManifold->getNumContacts();

        if(snA && snA->getName() == "ball") {
            ballContacts += numContacts;
        }

        for(int j = 0; j < numContacts; ++j) 
        {
            btManifoldPoint& pt = contactManifold->getContactPoint(j);

            //std::cout << pt.getDistance() << "\n";
            if(pt.getDistance() <= 1.0f) 
            {
                const btVector3& ptA = pt.getPositionWorldOnA();
                const btVector3& ptB = pt.getPositionWorldOnB();
                const btVector3& normalOnB = pt.m_normalWorldOnB;

                //std::cout << collisionIgnoreTimer << std::endl;
                //std::cout << "collision detected!" << std::endl;    

                if(!collisionIgnore) 
                {   
                    if(userPointerA)
                    {
                        if(snA->getName() == "ball") {
                            collisionIgnore = true;
                        }
                        //std::cout << "A is " << snA->getName() << std::endl;
                        if(userPointerB)
                        {
                            //std::cout << "B is " << snB->getName() << std::endl;
                            
                            if (snA->getName() == "floor" ||
                                snB->getName() == "floor" )
                            {
                                // Floor collision
                                physSound->playSound(2);

                                if(!multiplayer) 
                                {
                                    physScore->resetScore();
                                }
                                else 
                                {
                                    if(snA->getName() == "ball") {
                                        if(snA->getPosition().y > 100.0f) 
                                        {
                                            std::cout << "Player 1 gets a point!\n";
                                            physScore->addScore(1,1);
                                        } 
                                        else 
                                        {
                                            std::cout << "Player 2 gets a point!\n";
                                            physScore->addScore(1,2);
                                        }
                                    } 
                                    else 
                                    {
                                        if(snA->getPosition().y > 100.0f) 
                                        {
                                            std::cout << "Player 1 gets a point!\n";
                                            physScore->addScore(1,1);
                                        } 
                                        else 
                                        {
                                            std::cout << "Player 2 gets a point!\n";
                                            physScore->addScore(1,2);
                                        }
                                    }
                                }
                            }
                            else if (
                                snA->getName() == "paddle" ||
                                snB->getName() == "paddle" )
                            {
                                // Paddle collision
                                physSound->playSound(1);
                                
                                if(!multiplayer) 
                                    physScore->addScore(1);  

                                lastPaddleHit = 1;  
                            }      
                            else if (
                                snA->getName() == "paddle2" ||
                                snB->getName() == "paddle2" )
                            {
                                // Paddle collision
                                physSound->playSound(1);
                                
                                lastPaddleHit = 2;
                            } 
                        }
                        else 
                        {
                            // Wall collision
                            physSound->playSound(0);
                            
                            if(!multiplayer) 
                                physScore->addScore(3);
                        }
                    }
                    //std::cout << "Player 1: " << physScore->getScore(1) << std::endl;
                    //std::cout << "Player 2: " << physScore->getScore(2)  << std::endl;
                }
            }
        }
    }

    if(ballContacts == 0) {
        collisionIgnore = false;
    }
}
Exemple #29
0
 void PhysicsSystem::insertActorPhysics(const MWWorld::Ptr& ptr, const std::string model){
       Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
        // std::cout << "Adding node with name" << node->getName();
     addActor (node->getName(), model, node->getPosition());
 }
 void PhysicsSystem::rotateObject (const Ptr& ptr)
 {
     Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
     std::string handle = node->getName();
     Ogre::Quaternion rotation = node->getOrientation();
     if (OEngine::Physic::PhysicActor* act = mEngine->getCharacter(handle))
     {
         //Needs to be changed
         act->setRotation(rotation);
     }
     if (OEngine::Physic::RigidBody* body = mEngine->getRigidBody(handle))
     {
         if(dynamic_cast<btBoxShape*>(body->getCollisionShape()) == NULL)
             body->getWorldTransform().setRotation(btQuaternion(rotation.x, rotation.y, rotation.z, rotation.w));
         else
             mEngine->boxAdjustExternal(handleToMesh[handle], body, node->getScale().x, node->getPosition(), rotation);
     }
 }