예제 #1
0
void			Player::_handleCamera()
{
  Ogre::Camera *cam = indie::GameManager::getCamera();

  cam->setPosition(gameObject->getPosition().x,
		   cam->getPosition().y,
		   gameObject->getPosition().z + 300);
}
예제 #2
0
void camera_get_position(CameraHandle handle, coiVector3* result)
{
    Ogre::Camera* camera = static_cast<Ogre::Camera*>(handle);
    const Ogre::Vector3& pos = camera->getPosition();
    result->x = pos.x;
    result->y = pos.y;
    result->z = pos.z;
}
예제 #3
0
void DotSceneLoader::processCamera(rapidxml::xml_node<>* XMLNode,
		Ogre::SceneNode *pParent) {
	// Process attributes
	Ogre::String name = getAttrib(XMLNode, "name");
	Ogre::String id = getAttrib(XMLNode, "id");
// Ogre::Real fov = getAttribReal(XMLNode, "fov", 45);
// Ogre::Real aspectRatio = getAttribReal(XMLNode, "aspectRatio", 1.3333);
	Ogre::String projectionType = getAttrib(XMLNode, "projectionType",
			"perspective");

	// Create the camera
	Ogre::Camera *pCamera = mSceneMgr->createCamera(name);

	// Set the projection type
	if (projectionType == "perspective")
		pCamera->setProjectionType(Ogre::PT_PERSPECTIVE);
	else if (projectionType == "orthographic")
		pCamera->setProjectionType(Ogre::PT_ORTHOGRAPHIC);

	rapidxml::xml_node<>* pElement;

	// Process clipping (?)
	pElement = XMLNode->first_node("clipping");
	if (pElement) {
		Ogre::Real nearDist = getAttribReal(pElement, "near");
		if (nearDist > 0)
		  pCamera->setNearClipDistance(nearDist);

		Ogre::Real farDist = getAttribReal(pElement, "far");
		pCamera->setFarClipDistance(farDist);
	}

	// Process position (?)
	pElement = XMLNode->first_node("position");
	if (pElement)
		pCamera->setPosition(parseVector3(pElement));

	// Process rotation (?)
	pElement = XMLNode->first_node("rotation");
	if (pElement)
		pCamera->setOrientation(parseQuaternion(pElement));

	// construct a scenenode is no parent
	if (!pParent) {
		Ogre::SceneNode* pNode = mAttachNode->createChildSceneNode(name);
		pNode->setPosition(pCamera->getPosition());
		pNode->setOrientation(pCamera->getOrientation());
		pNode->scale(1, 1, 1);
	}
}
예제 #4
0
void World::EnableFreeCamera( bool bEnable )
{
	assert(m_pRenderSystem->m_pMainCamera && m_cameraMan);

	if(!bEnable)
	{
		Ogre::Camera* cam = m_pRenderSystem->m_pMainCamera;
		const Ogre::Vector3 pos = cam->getPosition();
		cam->setPosition(0, 24, 0);
		cam->lookAt(0, 0, 8);
	}

	m_bFreeCamMode = bEnable;
}
예제 #5
0
//---------------------------------------------------------------------------------------------
void TEditorMapLogic::SaveSettingCamera()
{
  Ogre::Camera* pCamera = TModuleLogic::Get()->GetC()->pGraphicEngine->GetGE()->GetCamera();
  const Ogre::Vector3& pos = pCamera->getPosition();
  const Ogre::Quaternion& dir = pCamera->getOrientation();

  GetSettings()->BeginGroup( "SettingCamera" );

  GetSettings()->WriteEntry( "pos_x", pos.x );
  GetSettings()->WriteEntry( "pos_y", pos.y );
  GetSettings()->WriteEntry( "pos_z", pos.z );

  GetSettings()->WriteEntry( "dir_x", dir.x );
  GetSettings()->WriteEntry( "dir_y", dir.y );
  GetSettings()->WriteEntry( "dir_z", dir.z );
  GetSettings()->WriteEntry( "dir_w", dir.w );
}
void OgrePlanarReflectionMaterial::updateReflectionCamera(const Ogre::MovablePlane& plane)
{
    Ogre::Camera* sofaCamera = mSceneMgr->getCamera("sofaCamera");
    assert(sofaCamera);

    //mCamera->setNearClipDistance(sofaCamera->getNearClipDistance());
    mCamera->setFarClipDistance(sofaCamera->getFarClipDistance());
    mCamera->setAspectRatio(sofaCamera->getViewport()->getActualWidth() /
            sofaCamera->getViewport()->getActualHeight());
    mCamera->setFOVy(sofaCamera->getFOVy());
    mCamera->setOrientation(sofaCamera->getOrientation());
    mCamera->setPosition(sofaCamera->getPosition());

    mCamera->enableReflection(&plane);
    mCamera->enableCustomNearClipPlane(&plane);

}
예제 #7
0
// 检测是否要透明
void CEngineInterface::CheckObjectTransparent()
{
	if(!m_pFairySystem)
		return ;

	CObjectManager* objMng = CObjectManager::GetMe();
	fVector3 fvPos;
	
	if( objMng->GetMySelf()->GetRenderInterface() )
	{
		objMng->GetMySelf()->GetRenderInterface()->Actor_GetLocator( GetCharaLocatorName(LOCATOR_CHAR_ATTACK), fvPos );		// 取人物绑定点的位置, 判断起来比较合理	"人物身体受击点"
	}

	Axis_Trans(tGfxSystem::AX_GAME, fvPos, tGfxSystem::AX_GFX, fvPos);

	Ogre::Camera* pOgreCamera = m_pFairySystem->getCamera();
	Ogre::Vector3 origin = pOgreCamera->getPosition();

	// 屏掉下边这句了by czg 200911-30
	m_pFairySystem->makeObjectTransparent(origin, Ogre::Vector3(fvPos.x, fvPos.y, fvPos.z), 0.8, 1, NULL);
}
예제 #8
0
    // Move the player relative to her own position and
    // orientation. After the call, the new position is returned.
    void moveRel(float &relX, float &relY, float &relZ)
    {
        using namespace Ogre;

        // Move camera relative to its own direction
        camera->moveRelative(Vector3(relX,0,relZ));

        // Up/down movement is always done relative the world axis.
        camera->move(Vector3(0,relY,0));

        // Get new camera position, converting back to MW coords.
        Vector3 pos = camera->getPosition();
        relX = pos[0];
        relY = -pos[2];
        relZ = pos[1];

        // TODO: Collision detection must be used to find the REAL new
        // position.

        // Set the position
        setPos(relX, relY, relZ);
    }
예제 #9
0
void C_Input::Translate(Ogre::SceneManager *sceneMgr, const Ogre::FrameEvent& evt)
{
	/*

	Ogre::Vector3 transVector = Ogre::Vector3::ZERO;//vector to hold transition to translate to

	//Prep animations
	//Stealth walk
	a_ninjaStealth = sceneMgr->getEntity("Ninja")->getAnimationState("Stealth");
	a_ninjaStealth->setLoop(true);
	a_ninjaStealth->setEnabled(false);
	//Walk ---todo: add this
	a_ninjaWalk = sceneMgr->getEntity("Ninja")->getAnimationState("Walk");
	a_ninjaWalk->setLoop(true);
	a_ninjaWalk->setEnabled(false);
	//Idle1
	a_ninjaIdle1 = sceneMgr->getEntity("Ninja")->getAnimationState("Idle1");
	a_ninjaIdle1->setLoop(true);
	a_ninjaIdle1->setEnabled(false);
	//Attack1
	a_ninjaAttack1 = sceneMgr->getEntity("Ninja")->getAnimationState("Attack1");
	a_ninjaAttack1->setLoop(true);
	a_ninjaAttack1->setEnabled(false);

	if(left){
		m_xMagnitude += m_xVel;
		if(m_xMagnitude > MOVE_SPEED)
			m_xMagnitude = MOVE_SPEED;
		
		m_directionFacing = LEFT;
		m_keepTurning = true;

		//Stealth
		//if(!a_ninjaStealth->getEnabled()){//if not already walking
		if(m_xMagnitude < MOVE_SPEED){
			a_ninjaStealth->setEnabled(true);//walk
			a_ninjaStealth->addTime(evt.timeSinceLastFrame);
		}
		else{
			a_ninjaStealth->setEnabled(false);
			a_ninjaWalk->setEnabled(true);
			a_ninjaWalk->addTime(evt.timeSinceLastFrame);
			m_xMagnitude = 350;
		}
		transVector.x -= m_xMagnitude;
	}

	if(right){
		transVector.x += MOVE_SPEED;
		m_directionFacing = RIGHT;
		m_keepTurning = true;

		//Stealth	
		if(!a_ninjaStealth->getEnabled()){//if not already walking
			a_ninjaStealth->setEnabled(true);//walk
			a_ninjaStealth->addTime(evt.timeSinceLastFrame);

			//TODO scribble here
			m_xMagnitude = 0;
		}
	}
	/*
	if(up)
		transVector.y += MOVE_SPEED;

	if(down)
		transVector.y -= MOVE_SPEED;
	*/


/*
	//IF NOT LEFT OR RIGHT IDLE OR TURNING
	if(!left && !right){
		a_ninjaStealth->setEnabled(false);
		a_ninjaWalk->setEnabled(false);
		a_ninjaIdle1->setEnabled(true);
		
		a_ninjaIdle1->addTime(evt.timeSinceLastFrame);
		
	}
	else
		a_ninjaIdle1->setEnabled(false);
	



	//const Ogre::FrameEvent evt; TODO: how to setup timer???
	//TODO: DONT LEAVE TRANSLATION UPDATE HERE!!
	sceneMgr->getSceneNode("Ninja1")->translate(transVector * evt.timeSinceLastFrame, Ogre::Node::TS_WORLD);
	
	
	//sceneMgr->getSceneNode("Ninja1")->yaw(Ogre::Degree(m_degreeFacing));
	if(m_directionFacing == RIGHT && m_angleFacing < 90  && m_keepTurning == true){
		float turnSpeed = 240 * evt.timeSinceLastFrame;
		sceneMgr->getSceneNode("Ninja1")->yaw(Ogre::Degree(turnSpeed));
		m_angleFacing += turnSpeed;
		if(m_angleFacing > 90)
			m_keepTurning = false;
	}

	if(m_directionFacing == LEFT && m_angleFacing > -90 && m_keepTurning == true){
		float turnSpeed = -240 * evt.timeSinceLastFrame;
		sceneMgr->getSceneNode("Ninja1")->yaw(Ogre::Degree(turnSpeed));
		m_angleFacing += turnSpeed;
		if(m_angleFacing < -90)
			m_keepTurning = false;
	}

	if(space){
		//make a function that sets everything to false
		a_ninjaWalk->setEnabled(false);
		a_ninjaStealth->setEnabled(false);
		a_ninjaIdle1->setEnabled(false);
		a_ninjaAttack1->setEnabled(true);
		a_ninjaAttack1->addTime(evt.timeSinceLastFrame);
	}
	
	
	//This will test collision for a falling ninja
	if(key_a)
		sceneMgr->getSceneNode("Ninja1")->setPosition(0, 300,-100);

	


	

	//REAL INPUTS HERE todo: clean up above but save for reference
	//GUI STUFF
#if(GUI_ON)
	if(key_grave)
		CEGUI::System::getSingleton().getGUISheet()->show();//shows GUI. User must click close to exit
#endif


	*/

	float speed = 30;
	Ogre::Vector3 movement = Ogre::Vector3::ZERO;

	if(up)
		movement.z = -speed;

	if(down)
		movement.z = speed;

	if(left)
		movement.x = -speed;

	if(right)
		movement.x = speed;

	if(mouseWheelUp)
		movement.y = speed;

	if(mouseWheelDown)
		movement.y = -speed;

	

	Ogre::Camera* cam = sceneMgr->getCamera("PlayerCam");
	cam->setPosition(cam->getPosition() + movement);



	//reset mouse wheel movement (CEGUI IS lame about it)
	mouseWheelDown = false;
	mouseWheelUp = false;
}
예제 #10
0
void DotSceneLoader::processCamera(rapidxml::xml_node<>* XMLNode, Ogre::SceneNode *pParent)
{
	// Process attributes
	Ogre::String name = getAttrib(XMLNode, "name");
	Ogre::String id = getAttrib(XMLNode, "id");
	Ogre::Real fov = getAttribReal(XMLNode, "fov", 45);
	Ogre::Real aspectRatio = getAttribReal(XMLNode, "aspectRatio", 1.3333);
	Ogre::String projectionType = getAttrib(XMLNode, "projectionType", "perspective");

	// Create the camera
	Ogre::Camera *pCamera = mSceneMgr->createCamera(name);

	//TODO: make a flag or attribute indicating whether or not the camera should be attached to any parent node.
	//if(pParent)
	//    pParent->attachObject(pCamera);

	// Set the field-of-view
	//! @todo Is this always in degrees?
	//pCamera->setFOVy(Ogre::Degree(fov));

	// Set the aspect ratio
	//pCamera->setAspectRatio(aspectRatio);

	// Set the projection type
	if (projectionType == "perspective")
		pCamera->setProjectionType(Ogre::PT_PERSPECTIVE);
	else if (projectionType == "orthographic")
		pCamera->setProjectionType(Ogre::PT_ORTHOGRAPHIC);

	rapidxml::xml_node<>* pElement;

	// Process clipping (?)
	pElement = XMLNode->first_node("clipping");
	if (pElement)
	{
		Ogre::Real nearDist = getAttribReal(pElement, "near");
		pCamera->setNearClipDistance(nearDist);

		Ogre::Real farDist = getAttribReal(pElement, "far");
		pCamera->setFarClipDistance(farDist);
	}

	// Process position (?)
	pElement = XMLNode->first_node("position");
	if (pElement)
		pCamera->setPosition(parseVector3(pElement));

	// Process rotation (?)
	pElement = XMLNode->first_node("rotation");
	if (pElement)
		pCamera->setOrientation(parseQuaternion(pElement));

	// Process normal (?)
	pElement = XMLNode->first_node("normal");
	if (pElement)
		;//!< @todo What to do with this element?

	// Process lookTarget (?)
	pElement = XMLNode->first_node("lookTarget");
	if (pElement)
		;//!< @todo Implement the camera look target

	// Process trackTarget (?)
	pElement = XMLNode->first_node("trackTarget");
	if (pElement)
		;//!< @todo Implement the camera track target

	// Process userDataReference (?)
	pElement = XMLNode->first_node("userDataReference");
	if (pElement)
		;//!< @todo Implement the camera user data reference

	// construct a scenenode is no parent
	if (!pParent)
	{
		Ogre::SceneNode* pNode = mAttachNode->createChildSceneNode(name);
		pNode->setPosition(pCamera->getPosition());
		pNode->setOrientation(pCamera->getOrientation());
		pNode->scale(1, 1, 1);
	}
}
예제 #11
0
void ActorSceneCanvas::OnMouseMove(wxMouseEvent& e)
{

	ShowPos(e.GetX(), e.GetY());

    if (!GetSceneManipulator())
        return;

    if (m_pCameraManip)
    {
        wxASSERT(mDragButton != wxMOUSE_BTN_NONE);
        m_pCameraManip->onMotion(e.GetX(), e.GetY());
    }

	if (mDragStarted  && e.LeftIsDown())
	{
		mDragCurrent =Ogre::Vector2(e.GetX(), e.GetY()) ;
		mDragDelta = mDragCurrent - mDragOrigin;
		mDragOrigin = mDragCurrent;

		if (Fairy::CDataManipulator::GetDataManipulator() && mCanManipulateAxis)
		{	
			Ogre::Camera* camera = GetSceneManipulator()->getCamera();
			assert (camera);
			Ogre::Vector3 oldPos = camera->getPosition();
			Fairy::LogicModel* pModel = GetDataManipulator()->m_pObjTemplate;
			if (pModel)
			{
				Ogre::Vector3 objPos = pModel->getPosition();
				Ogre::Real distance = oldPos.distance(objPos);
				Ogre::Real factor = distance*0.1/150.0;

				Ogre::Vector3 pos=Fairy::CDataManipulator::m_baseNode->getPosition();
				Ogre::Vector3 fdeltaxi = Ogre::Vector3::ZERO;
				Ogre::Quaternion qRot = Fairy::CDataManipulator::m_baseNode->getOrientation();
				//david-<<
				 if(mXax)
					 fdeltaxi = /*qRot**/(mDragDelta.x*0.1*Ogre::Vector3::UNIT_X);
				 if(mYax)
					 fdeltaxi = /*qRot**/(mDragDelta.x*0.1*Ogre::Vector3::UNIT_Y);
				 if(mZax)
					 fdeltaxi = /*qRot**/(mDragDelta.x*0.1*Ogre::Vector3::UNIT_Z);
				 //david->>

				Fairy::CDataManipulator::GetDataManipulator()->_updateCurLocatorTrans(fdeltaxi,Ogre::Quaternion::IDENTITY,true);
			}			
		}	
	}

	if(mDragRightStarted &&  e.RightIsDown())
	{
	
		mDragCurrent =Ogre::Vector2(e.GetX(), e.GetY()) ;
		mDragDelta = mDragCurrent - mDragOrigin;
		mDragOrigin = mDragCurrent;

// 		Ogre::Radian x = Ogre::Degree(mDragDelta.val[0]);
// 		Ogre::Radian y = Ogre::Degree(mDragDelta.val[1]);
// 		Fairy::CDataManipulator::m_axex->yaw(y);
// 		Fairy::CDataManipulator::m_axex->pitch(x);

		if ( Fairy::CDataManipulator::GetDataManipulator() &&(mXax || mYax || mZax) && mCanManipulateAxis)
		{			
			Ogre::Vector3 fBaseAxis = Ogre::Vector3::ZERO;
			Ogre::Quaternion fBaseRot = Fairy::CDataManipulator::m_baseNode->getOrientation();

			if(mXax)
				fBaseAxis =/* fBaseRot**/Ogre::Vector3::UNIT_X;
			if(mYax)
				fBaseAxis =/* fBaseRot**/Ogre::Vector3::UNIT_Y;
			if(mZax)
				fBaseAxis =/* fBaseRot**/Ogre::Vector3::UNIT_Z;

			//david-<<
			Ogre::Radian angle = Ogre::Degree(mDragDelta.y);
			//david->>

			Ogre::Quaternion rot(angle, fBaseAxis);			

			if(mRotFirst)
			{
				Fairy::CDataManipulator::GetDataManipulator()->_updateCurLocatorTrans(Ogre::Vector3::ZERO, rot, false);	
			}
			else
			{
				Fairy::CDataManipulator::GetDataManipulator()->_updateCurLocatorRot(rot);	
			}				
		}
	}



    if (GetActiveAction())
    {
        //GetActiveAction()->onMotion(e.GetX(), e.GetY());
		if (e.ControlDown())
		{
			GetActiveAction()->setParameter("FUNC_KEY", "CTRL");
		}
		
		if(e.AltDown())
		{
			GetActiveAction()->setParameter("FUNC_KEY", "ATL");
		}
		
		if(e.ShiftDown())
		{
			GetActiveAction()->setParameter("FUNC_KEY", "SHIFT");
		}

	}
	else
	{
        //GetSceneManipulator()->getHitIndicator("IntersectPoint")->setHitPoint(e.GetX(), e.GetY());
	}
    // 显示标准模型
    //if ( GetSceneManipulator()->getShowStandardModel() )
    //    GetSceneManipulator()->getHitIndicator("StandardModelIndicator")->setHitPoint(0.5,0.5);
    //else
    //    GetSceneManipulator()->getHitIndicator("StandardModelIndicator")->hide();

    m_CurrentMousePos.x = e.GetX();
    m_CurrentMousePos.y = e.GetY();

	Ogre::Vector3 position;
	bool hit = GetSceneManipulator()->getTerrainIntersects(m_CurrentMousePos.x, m_CurrentMousePos.y, position);

	std::pair<int, int> gridCoord = GetSceneManipulator()->getTerrainData()->getGrid(position.x, position.z);

	if (hit)
	{
		mParentFrame->SetStatusText("World Coordinate : " + Ogre::StringConverter::toString((int)(position.x)) +
			"  " + Ogre::StringConverter::toString((int)(position.y)) + "  "
			 + Ogre::StringConverter::toString((int)(position.z)), 0);
		mParentFrame->SetStatusText("Grid Coordinate : " + Ogre::StringConverter::toString(gridCoord.first) + " " +
			Ogre::StringConverter::toString(gridCoord.second), 1);
	}

}
예제 #12
0
void ActorSceneCanvas::OnKeyDown(wxKeyEvent& e)
{
	switch(e.GetKeyCode())
	{
	case 'w':
	case 'W':
		{
			Ogre::Camera* camera = GetSceneManipulator()->getCamera();
			assert (camera);

			Ogre::Vector3 oldPos = camera->getPosition();

			Ogre::Vector3 offsetPos = camera->getDirection() * GetSceneManipulator()->getMoveSpeed();

			Ogre::Vector3 newPos = oldPos;
            newPos.x += offsetPos.x;
            newPos.z += offsetPos.z;

			GetSceneManipulator()->setCameraPosition(newPos);
			e.Skip(false);
		}
		break;
	case 's':
	case 'S':
		{
			Ogre::Camera* camera = GetSceneManipulator()->getCamera();
			assert (camera);

			Ogre::Vector3 oldPos = camera->getPosition();

			Ogre::Vector3 offsetPos = camera->getDirection() * -(GetSceneManipulator()->getMoveSpeed());

			Ogre::Vector3 newPos = oldPos;
            newPos.x += offsetPos.x;
            newPos.z += offsetPos.z;

			GetSceneManipulator()->setCameraPosition(newPos);
			e.Skip(false);
		}
		break;
	case 'a':
	case 'A':
		{
			Ogre::Camera* camera = GetSceneManipulator()->getCamera();
			assert (camera);

			Ogre::Radian yawAngle( GetSceneManipulator()->getRotateSpeed() / 360.0f );

			camera->yaw(yawAngle);
			e.Skip(false);
		}
		break;
	case 'd':
	case 'D':
		{
			Ogre::Camera* camera = GetSceneManipulator()->getCamera();
			assert (camera);

			Ogre::Radian yawAngle( -(GetSceneManipulator()->getRotateSpeed() / 360.0f) );

			camera->yaw(yawAngle);
			e.Skip(false);
		}
		break;
	case 'h':
	case 'H':
		{
			mHideAxis = !mHideAxis;
			Fairy::CDataManipulator::m_baseNode->setVisible(!mHideAxis);
			Fairy::CDataManipulator::mAxisNode_x->setVisible(!mHideAxis);
			Fairy::CDataManipulator::mAxisNode_y->setVisible(!mHideAxis);
			Fairy::CDataManipulator::mAxisNode_z->setVisible(!mHideAxis);
		}
		break;
 	case 'b':
	case 'B':
		{
			GetDataManipulator()->switchBoundingBox(true);
		}
		break;
	case 't':
	case 'T':
		{
			GetSceneManipulator()->setTerrainVisible(!GetSceneManipulator()->getTerrainVisible());
		}
		break;
	case 'g':
	case 'G':
		{
			GetSceneManipulator()->setGridVisible(!GetSceneManipulator()->getGridVisible());
		}
		break;
	case 'r':
	case 'R':
		{
			mRotFirst = !mRotFirst;
		}
		break;
	//case 'C':
 //	case 'c':
 //		{
	//		Fairy::LogicModelManager::getSingleton().showModelBoundingBox(!Fairy::LogicModelManager::getSingleton().isShowBoundingBox()); 			
 //		}
 //		break;
// 
// 	case 'y':
// 	case 'Y':
// 		{
// 			mYax = !mYax;
// 			mXax = mZax = false;
// 		}
// 		break;
// 
// 	case 'z':
// 	case 'Z':
// 		{
// 			mZax = !mZax;
// 			mXax = mYax = false;
// 		}
		//break;
	//case 'z':
	//case 'Z':
 //       {
	//		GetSceneManipulator()->setActiveAction("ManipObjectAction");
 //           GetSceneManipulator()->setUseAxis(!GetSceneManipulator()->getUseAxis());
 //       }
 //       e.Skip(false);
 //       break;
	}
}
예제 #13
0
bool SoundEditDialog::frameStarted(const Ogre::FrameEvent& evt)
{
    if (!mPlaySound)
        return true;

    if (/*mPlaySoundInGame*/0)
    {
        Ogre::Camera* camera = mSceneManipulator->getCamera();
        const Ogre::Vector3& camPos = camera->getPosition();

        Fairy::TerrainData* terrainData = mSceneManipulator->getTerrainData();

        std::pair<int, int> camGrid = terrainData->getGrid(camPos.x, camPos.z);

        for (size_t i=0; i<mSoundItems.size(); ++i)
        {
            SoundItem* workingItem = mSoundItems[i];

            if (workingItem->mRepeatTime != 0)
            {
                FLOAT deltaTime = evt.timeSinceLastFrame * 1000;

                // 如果当前的播放次数已达到重复播放次数,就累加时间,直到达到下次播放的时间,就播放
                if (workingItem->mCurrentRepeatTime == workingItem->mRepeatTime)
                {
                    workingItem->mCurrentPlayIntervalTime += (INT)deltaTime;

                    if (workingItem->mCurrentPlayIntervalTime >= workingItem->mNextRepeatTime)
                    {
                        workingItem->mCurrentRepeatTime = 0;
                        workingItem->mCurrentPlayIntervalTime = 0;

                        SoundNames::iterator it = mSoundNames.find(workingItem->mSoundID);

                        if (it != mSoundNames.end())
                        {
                            workingItem->mSoundHandle = _PlaySound(it->second, workingItem->mSoundHandle, false);
                        }

                        ++workingItem->mCurrentRepeatTime;
                    }
                }
                else
                {
                    // 累加重复播放之间的间隔时间
                    workingItem->mCurrentRepeatIntervalTime += (INT)deltaTime;

                    if (workingItem->mCurrentRepeatIntervalTime >= workingItem->mRepeatIntervalTime)
                    {
                        workingItem->mCurrentRepeatIntervalTime = 0;

                        SoundNames::iterator it = mSoundNames.find(workingItem->mSoundID);

                        if (it != mSoundNames.end())
                        {
                            workingItem->mSoundHandle = _PlaySound(it->second, workingItem->mSoundHandle, false);
                        }

                        ++workingItem->mCurrentRepeatTime;
                    }
                }
            }
            else
            {
                if (workingItem->mSoundHandle == -1)
                {
                    SoundNames::iterator it = mSoundNames.find(workingItem->mSoundID);

                    if (it != mSoundNames.end())
                    {
                        workingItem->mSoundHandle = _PlaySound(it->second, workingItem->mSoundHandle, false);
                    }

                    workingItem->mSoundHandle = _PlaySound(it->second, workingItem->mSoundHandle, true);
                }
            }

            if (workingItem->mRadius > 0)
            {
                float dis = Ogre::Math::Sqrt( (camGrid.first - workingItem->mXPos) * (camGrid.first - workingItem->mXPos) +
                    (camGrid.second - workingItem->mZPos) * (camGrid.second - workingItem->mZPos) );

                float volume = 0;

                if(dis <= workingItem->mRadius) 
                    volume = 1.0f-(dis/workingItem->mRadius);

                _SetSoundVolume(workingItem->mSoundHandle, volume);
            }
        }
    }
    else
    {
        if (mPlaySound && mCurrentSoundItem && mCurrentSoundItem->mRepeatTime != 0)
        {
            FLOAT deltaTime = evt.timeSinceLastFrame * 1000;

            // 如果当前的播放次数已达到重复播放次数,就累加时间,直到达到下次播放的时间,就播放
            if (mCurrentRepeatTime == mCurrentSoundItem->mRepeatTime)
            {
                mCurrentPlayIntervalTime += (INT)deltaTime;

                if (mCurrentPlayIntervalTime >= mCurrentSoundItem->mNextRepeatTime)
                {
                    mCurrentRepeatTime = 0;
                    mCurrentPlayIntervalTime = 0;

                    SoundNames::iterator it = mSoundNames.find(mCurrentSoundItem->mSoundID);

                    if (it != mSoundNames.end())
                    {
                        mCurrentSoundHandle = _PlaySound(it->second, mCurrentSoundHandle, false);
                    }

                    ++mCurrentRepeatTime;
                }
            }
            else
            {
                // 累加重复播放之间的间隔时间
                mCurrentRepeatIntervalTime += (INT)deltaTime;

                if (mCurrentRepeatIntervalTime >= mCurrentSoundItem->mRepeatIntervalTime)
                {
                    mCurrentRepeatIntervalTime = 0;

                    SoundNames::iterator it = mSoundNames.find(mCurrentSoundItem->mSoundID);

                    if (it != mSoundNames.end())
                    {
                        mCurrentSoundHandle = _PlaySound(it->second, mCurrentSoundHandle, false);
                    }

                    ++mCurrentRepeatTime;
                }
            }
        }
    }

    return true;
}
예제 #14
0
//!
//! Clones an Ogre::MovableObject.
//!
//! Is needed because OGRE does not provide clone functions for cameras and
//! lights.
//!
//! \param movableObject The object to clone.
//! \param name The name to use for the object.
//! \param sceneManager The scene manager to use for creating the object.
//! \return The cloned object.
//!
Ogre::MovableObject * OgreTools::cloneMovableObject ( Ogre::MovableObject *movableObject, const QString &name, Ogre::SceneManager *sceneManager /* =  0 */ )
{
    // make sure the given object is valid
    if (!movableObject) {
        Log::error("The given movable object is invalid.", "OgreTools::cloneMovableObject");
        return 0;
    }

    // make sure a valid scene manager is available
    if (!sceneManager)
        sceneManager = movableObject->_getManager();
    if (!sceneManager) {
        Log::error("No valid scene manager available.", "OgreTools::cloneMovableObject");
        return 0;
    }

    Ogre::MovableObject *result = 0;
    Ogre::String typeName = movableObject->getMovableType();
    if (typeName == "Entity") {
        // clone entity
        Ogre::Entity *entity = dynamic_cast<Ogre::Entity *>(movableObject);
        //movableObjectCopy = entity->clone(name.toStdString());
        Ogre::Entity *entityCopy = sceneManager->createEntity(name.toStdString(), entity->getMesh()->getName());
        Ogre::AnimationStateSet *animationStateSet = entity->getAllAnimationStates();
        Ogre::AnimationStateSet *animationStateSetCopy  = entityCopy->getAllAnimationStates();
        // set the same blend mode on entity copy
        if (entity && entityCopy) {
            if (entity->hasSkeleton() && entityCopy->hasSkeleton()) {
                Ogre::Skeleton *skeleton = entity->getSkeleton();
                Ogre::Skeleton *skeletonCopy = entityCopy->getSkeleton();
                skeletonCopy->setBlendMode(skeleton->getBlendMode());
            }
        }
        // copy all animation states
        if (animationStateSet && animationStateSetCopy) {
            Ogre::AnimationStateIterator animationStateIter = animationStateSet->getAnimationStateIterator();
            Ogre::AnimationStateIterator animationStateCopyIter = animationStateSetCopy->getAnimationStateIterator();
            while (animationStateIter.hasMoreElements()) {
                if (!animationStateCopyIter.hasMoreElements())
                    break;
                Ogre::AnimationState *animationState = animationStateIter.getNext();
                Ogre::AnimationState *animationStateCopy = animationStateCopyIter.getNext();
                animationStateCopy->setLoop(animationState->getLoop());
                //bool enabled = animationState->getEnabled();
                //animationStateCopy->setEnabled(animationState->getEnabled());
                animationStateCopy->setEnabled(true);
                animationStateCopy->setTimePosition(animationState->getTimePosition());
            }
        }

        // create a new container for the cloned entity
        OgreContainer *entityCopyContainer = new OgreContainer(entityCopy);
        entityCopy->setUserAny(Ogre::Any(entityCopyContainer));
        if (!entity->getUserAny().isEmpty()) {
            OgreContainer *entityContainer = Ogre::any_cast<OgreContainer *>(entity->getUserAny());
			if (entityContainer) {
                QObject::connect(entityContainer, SIGNAL(animationStateUpdated(const QString &, double)), entityCopyContainer, SLOT(updateAnimationState(const QString &, double)));
				QObject::connect(entityContainer, SIGNAL(boneTransformUpdated(const QString &, double, double, double, double, double, double)), entityCopyContainer, SLOT(updateBoneTransform(const QString &, double, double, double, double, double, double)));
			}
        }
        result = dynamic_cast<Ogre::MovableObject *>(entityCopy);
    } else if (typeName == "Light") {
        // clone light
        Ogre::Light *light = dynamic_cast<Ogre::Light *>(movableObject);
        Ogre::Light *lightCopy = sceneManager->createLight(name.toStdString());
        lightCopy->setType(light->getType());
        lightCopy->setDiffuseColour(light->getDiffuseColour());
        lightCopy->setSpecularColour(light->getSpecularColour());
        lightCopy->setAttenuation(light->getAttenuationRange(), light->getAttenuationConstant(), light->getAttenuationLinear(), light->getAttenuationQuadric());
        lightCopy->setPosition(light->getPosition());
        lightCopy->setDirection(light->getDirection());
        if (lightCopy->getType() == Ogre::Light::LT_SPOTLIGHT)
            lightCopy->setSpotlightRange(light->getSpotlightInnerAngle(), light->getSpotlightOuterAngle(), light->getSpotlightFalloff());
        lightCopy->setPowerScale(light->getPowerScale());
        lightCopy->setCastShadows(light->getCastShadows());

        // create a new container for the cloned light
        OgreContainer *lightCopyContainer = new OgreContainer(lightCopy);
        lightCopy->setUserAny(Ogre::Any(lightCopyContainer));
        if (!light->getUserAny().isEmpty()) {
            OgreContainer *lightContainer = Ogre::any_cast<OgreContainer *>(light->getUserAny());
            if (lightContainer)
                QObject::connect(lightContainer, SIGNAL(sceneNodeUpdated()), lightCopyContainer, SLOT(updateLight()));
        }
        result = dynamic_cast<Ogre::MovableObject *>(lightCopy);
    } else if (typeName == "Camera") {
        // clone camera
        Ogre::Camera *camera = dynamic_cast<Ogre::Camera *>(movableObject);
        Ogre::Camera *cameraCopy = sceneManager->createCamera(name.toStdString());
        //cameraCopy->setCustomParameter(0, camera->getCustomParameter(0));
        cameraCopy->setAspectRatio(camera->getAspectRatio());
        cameraCopy->setAutoAspectRatio(camera->getAutoAspectRatio());
        //cameraCopy->setAutoTracking(...);
        cameraCopy->setCastShadows(camera->getCastsShadows());
        //cameraCopy->setCullingFrustum(camera->getCullingFrustum());
        //cameraCopy->setCustomParameter(...);
        //cameraCopy->setCustomProjectionMatrix(..);
        //cameraCopy->setCustomViewMatrix(..);
        //cameraCopy->setDebugDisplayEnabled(...);
        //cameraCopy->setDefaultQueryFlags(...);
        //cameraCopy->setDefaultVisibilityFlags(...);
        cameraCopy->setDirection(camera->getDirection());
        //cameraCopy->setFixedYawAxis(...);
        cameraCopy->setFocalLength(camera->getFocalLength());
        cameraCopy->setFOVy(camera->getFOVy());

        //Ogre::Real left;
        //Ogre::Real right;
        //Ogre::Real top;
        //Ogre::Real bottom;
        //camera->getFrustumExtents(left, right, top, bottom);
        //cameraCopy->setFrustumExtents(left, right, top, bottom);
        //cameraCopy->setFrustumOffset(camera->getFrustumOffset());
        //cameraCopy->setListener(camera->getListener());
        cameraCopy->setLodBias(camera->getLodBias());
        //cameraCopy->setLodCamera(camera->getLodCamera());
        cameraCopy->setNearClipDistance(camera->getNearClipDistance());
        cameraCopy->setFarClipDistance(camera->getFarClipDistance());
        cameraCopy->setOrientation(camera->getOrientation());
        //cameraCopy->setOrthoWindow(...);
        //cameraCopy->setOrthoWindowHeight(...);
        //cameraCopy->setOrthoWindowWidth(...);
        cameraCopy->setPolygonMode(camera->getPolygonMode());
        cameraCopy->setPolygonModeOverrideable(camera->getPolygonModeOverrideable());
        cameraCopy->setPosition(camera->getPosition());
        cameraCopy->setProjectionType(camera->getProjectionType());
        cameraCopy->setQueryFlags(camera->getQueryFlags());
        cameraCopy->setRenderingDistance(camera->getRenderingDistance());
        cameraCopy->setRenderQueueGroup(camera->getRenderQueueGroup());
        //cameraCopy->setRenderSystemData(camera->getRenderSystemData());
        cameraCopy->setUseIdentityProjection(camera->getUseIdentityProjection());
        cameraCopy->setUseIdentityView(camera->getUseIdentityView());
        //cameraCopy->setUserAny(camera->getUserAny());
        cameraCopy->setUseRenderingDistance(camera->getUseRenderingDistance());
        //cameraCopy->setUserObject(camera->getUserObject());
        cameraCopy->setVisibilityFlags(camera->getVisibilityFlags());
        cameraCopy->setVisible(camera->getVisible());
        //cameraCopy->setWindow(...);

        if (!movableObject->getUserAny().isEmpty()) {
            CameraInfo *sourceCameraInfo = Ogre::any_cast<CameraInfo *>(movableObject->getUserAny());
            if (sourceCameraInfo) {
                CameraInfo *targetCameraInfo = new CameraInfo();
                targetCameraInfo->width = sourceCameraInfo->width;
                targetCameraInfo->height = sourceCameraInfo->height;
                dynamic_cast<Ogre::MovableObject *>(cameraCopy)->setUserAny(Ogre::Any(targetCameraInfo));
            }
        }

        //// Setup connections for instances
        //SceneNode *targetSceneNode = new SceneNode(cameraCopy);
        //((Ogre::MovableObject *)cameraCopy)->setUserAny(Ogre::Any(targetSceneNode));
        //if (!((Ogre::MovableObject *)camera)->getUserAny().isEmpty()) {
        //    SceneNode *sourceSceneNode = Ogre::any_cast<SceneNode *>(((Ogre::MovableObject *)camera)->getUserAny());
        //    if (sourceSceneNode) {
        //        QObject::connect(sourceSceneNode, SIGNAL(sceneNodeUpdated()), targetSceneNode, SLOT(updateSceneNode()));
        //    }
        //}

        result = dynamic_cast<Ogre::MovableObject *>(cameraCopy);
    }

    if (!result)
        Log::error(QString("Could not clone movable object \"%1\" of type \"%2\".").arg(movableObject->getName().c_str()).arg(typeName.c_str()), "OgreTools::cloneMovableObject");

    return result;
}
예제 #15
0
	bool frameStarted(const Ogre::FrameEvent& evt){
		if(vidas==0)
			return false;
		_key->capture();
		_mouse->capture();
		
		float movSpeed = 500.0f;


		if (_key->isKeyDown(OIS::KC_ESCAPE))
			return false;

		Ogre::Vector3 t(0,0,0);

		if (_key->isKeyDown(OIS::KC_W))
			if (freemoving)
				t += Ogre::Vector3(0,0,-10);
			else
				nave->moverAdelante();
		if (_key->isKeyDown(OIS::KC_S))
			if (freemoving)
				t += Ogre::Vector3(0,0,10);
			else
				nave->moverAtras();

		if (_key->isKeyDown(OIS::KC_A))
			if (freemoving)
				t += Ogre::Vector3(-10,0,0);
			else
				nave->moverIzquierda();

		if (_key->isKeyDown(OIS::KC_D))
			if (freemoving)
				t += Ogre::Vector3(10,0,0);
			else
				nave->moverDerecha();
		if (_key->isKeyDown(OIS::KC_UP))
			nave->moverArriba();

		if (_key->isKeyDown(OIS::KC_DOWN))
			nave->moverAbajo();

		if (!_key->isKeyDown(OIS::KC_A) && !_key->isKeyDown(OIS::KC_D))
			nave->reset();

		if(_key->isKeyDown(OIS::KC_I))
			std::cout<<"CAMARA:"<<_cam->getPosition()<<std::endl
					 <<"NAVE:"<<nave->nodoNave->getPosition()<<std::endl;

		_cam->moveRelative(t*evt.timeSinceLastFrame*movSpeed);
		if (freemoving){
			float rotX = _mouse->getMouseState().X.rel * evt.timeSinceLastFrame* -1;
			float rotY = _mouse->getMouseState().Y.rel * evt.timeSinceLastFrame * -1;
		
			_cam->yaw(Ogre::Radian(rotX));
			_cam->pitch(Ogre::Radian(rotY));
		}
		for (int i = 0; i < num_monedas; i++)
		{
			moneda[i]->animState->addTime(evt.timeSinceLastFrame);
		}

		for (int i = 0; i < num_obstaculo; i++)
		{
			obstaculo[i]->animState->addTime(evt.timeSinceLastFrame);
		}

		for (int i = 0; i < num_monedas; i++)
		{
			if (moneda[i]->visible && nave->getBox().intersects(moneda[i]->getBox())){
				moneda[i]->visible = false;
				moneda[i]->nodoMoneda->setVisible(false);
				puntaje+=100;
				mostrarPuntaje();
			}
		}
		
		for (int i = 0; i < num_aros; i++)
		{
			Ogre::AxisAlignedBox boxNave = nave->getBox();
			Ogre::Vector3 centro = nave->getCenter();
			if (aro[i]->visible &&
				nave->getBox().intersects(aro[i]->getBox()) && 
				aro[i]->adentro(boxNave, centro))
			{
				aro[i]->visible = false;
				aro[i]->nodoAro->setVisible(false);
				puntaje+=200;
				mostrarPuntaje();
			}
		}
		
		for (int i = 0; i < num_obstaculo; i++)
		{
			if (obstaculo[i]->visible && nave->getBox().intersects(obstaculo[i]->getBox())){
				obstaculo[i]->visible = false;
				obstaculo[i]->nodoObstaculo->setVisible(false);
				vidas-=1;
				mostrarPuntaje();
			}
		}
		
		nave->animStateDer->addTime(evt.timeSinceLastFrame);
		nave->animStateIzq->addTime(evt.timeSinceLastFrame);
		return true;
	}
예제 #16
0
//-------------------------------------------------------------------------------------
void SampleApp::createScene(void)
{
	mImpulse = btVector3(0,0,0);
    mLoader = new DotSceneLoader();
	mLoader->parseDotScene(mSceneFile, "General", mSceneMgr,0,"",Globals::phyWorld);

    // Get rid of the initial camera
    mSceneMgr->destroyCamera(mCamera);

	//ENTITY DECLARATIONS

	Ogre::SceneNode* headNode;
	Ogre::Entity* head;
	head = mSceneMgr->createEntity("Ex1.mesh");
	headNode = mSceneMgr->createSceneNode();
	mSceneMgr->getRootSceneNode()->addChild(headNode);
	headNode->attachObject(head);
	//headNode->scale(0.1,0.1,0.1);
	//headNode->setPosition(0,25,0);

	//Create shape.
	BtOgre::StaticMeshToShapeConverter converter(head);
	mCharacterShape = converter.createBox(); // Declare this btCollisionShape * pointer in SampleApp.h  

	//Calculate inertia tensor.
	btScalar mass = 5;
	btVector3 inertia;
	mCharacterShape -> calculateLocalInertia(mass, inertia);

	//Create BtOgre MotionState (connects Ogre and Bullet).
	BtOgre::RigidBodyState *characterState = new BtOgre::RigidBodyState(headNode);
	
	//Create the Body.
	mCharacterBody = new btRigidBody(mass, characterState, mCharacterShape, inertia);
	mCharacterBody ->setActivationState(DISABLE_DEACTIVATION);
	//mCharacterBody->setCollisionFlags(mCharacterBody->getCollisionFlags() | btCollisionObject::CF_STATIC_OBJECT);
	// Get bullet debug lines to show using F3
	Globals::dbgdraw = new BtOgre::DebugDrawer(mSceneMgr -> getRootSceneNode(), Globals::phyWorld);
	Globals::phyWorld->setDebugDrawer(Globals::dbgdraw);
	Globals::phyWorld->addRigidBody(mCharacterBody);

	//END OF ENTITY DECLARATIONS

    // Loop through all cameras and grab their name and set their debug representation
    Ogre::SceneManager::CameraIterator cameras = mSceneMgr->getCameraIterator();
    while (cameras.hasMoreElements())
    {
        Ogre::Camera* camera = cameras.getNext();
        mCamNames.push_back(camera->getName());
        Ogre::Entity* debugEnt = mSceneMgr->createEntity(camera->getName() + Ogre::String("_debug"), "scbCamera.mesh");

        try{
            Ogre::SceneNode* sNode = mSceneMgr->getSceneNode(camera->getName());
            sNode->attachObject(debugEnt);
            sNode->scale(0.5, 0.5, 0.5);
        }catch (...){
            Ogre::SceneNode* pNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(camera->getName());
            pNode->setPosition(camera->getPosition());
            pNode->setOrientation(camera->getOrientation());

            pNode->attachObject(debugEnt);
            pNode->scale(0.5, 0.5, 0.5);
        }
    }
    // Grab the first available camera, for now
    Ogre::String cameraName = mCamNames[0];
    try
    {
        mActiveCamera = mSceneMgr->getCamera(cameraName);
        mWindow->getViewport(0)->setCamera(mActiveCamera);
        mCameraMan->setCamera(mActiveCamera);
        mSceneMgr->getEntity(mActiveCamera->getName() + Ogre::String("_debug"))->setVisible(false);

        //for(unsigned int ij = 0;ij < mLoader->mPGHandles.size();ij++)
        //{
        //    mLoader->mPGHandles[ij]->setCamera(mActiveCamera);
        //}
        
    }
    catch (Ogre::Exception& e)
    {
        Ogre::LogManager::getSingleton().logMessage("SampleApp::createScene : setting the active camera to (\"" +
            cameraName + ") failed: " + e.getFullDescription());
    }
}
void CSaveSceneView::SceneNodeExplore(Ogre::SceneNode *SceneNode)
{
	Ogre::Entity *Entity = NULL;
	Ogre::Camera *Camera = NULL;
	Ogre::Light *Light = NULL;
	Ogre::ParticleSystem *ParticleSystem = NULL;
	Ogre::ManualObject *ManualObject = NULL;
	Ogre::BillboardSet *BillboardSet = NULL;

	xmlTextWriterStartElement(m_XmlWriter, BAD_CAST "SceneNode");
	
	Ogre::String SceneNodeName = SceneNode->getName();

	xmlTextWriterWriteAttribute(m_XmlWriter, 
										BAD_CAST "SceneNodeName",
										BAD_CAST SceneNodeName.c_str());

	Ogre::SceneNode::ObjectIterator obji = SceneNode->getAttachedObjectIterator();

	while (obji.hasMoreElements())
	{
		Ogre::MovableObject* mobj = obji.getNext();
	
		Ogre::String Type = mobj->getMovableType();
	
		if (Type == "Entity")
		{
			Entity = (Ogre::Entity *)(mobj);
			Ogre::String EntityName = Entity->getName();
			xmlTextWriterStartElement(m_XmlWriter, BAD_CAST "Entity");
			xmlTextWriterWriteAttribute(m_XmlWriter, 
										BAD_CAST "EntityName",
										BAD_CAST EntityName.c_str());

			Ogre::MeshPtr Mesh = Entity->getMesh();
			Ogre::String MeshName = Mesh->getName();
			xmlTextWriterWriteAttribute(m_XmlWriter, 
										BAD_CAST "MeshName",
										BAD_CAST MeshName.c_str());
			xmlTextWriterEndElement(m_XmlWriter); 
		}
		
		if (Type == "Camera")
		{
			Camera = (Ogre::Camera *)(mobj);
			Ogre::String CameraName = Camera->getName();
			xmlTextWriterStartElement(m_XmlWriter, BAD_CAST "Camera");
			
			xmlTextWriterWriteAttribute(m_XmlWriter, 
										BAD_CAST "CameraName",
										BAD_CAST CameraName.c_str());
			
			Ogre::Vector3 CameraPosition = Camera->getPosition();
			
			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "XPosition",
										"%f",CameraPosition.x);
			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "YPosition",
										"%f",CameraPosition.y);
			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "ZPosition",
										"%f",CameraPosition.z);

			Ogre::Vector3 CameraDirection = Camera->getDirection();

			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "XDirection",
										"%f",CameraDirection.x);
			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "YDirection",
										"%f",CameraDirection.y);
			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "ZDirection",
										"%f",CameraDirection.z);

			xmlTextWriterEndElement(m_XmlWriter); 
		}

		if (Type == "Light")
		{
			Light = (Ogre::Light *)(mobj);
		}

		if (Type == "ParticleSystem")
		{
			ParticleSystem = (Ogre::ParticleSystem *)(mobj);
		}

		if (Type == "ManualObject")
		{
			ManualObject = (Ogre::ManualObject *)(mobj);
		}

		if (Type == "BillboardSet")
		{
			BillboardSet = (Ogre::BillboardSet *)(mobj);
		}

	}

	Ogre::Node::ChildNodeIterator nodei = SceneNode->getChildIterator();

	while (nodei.hasMoreElements())
	{
		Ogre::SceneNode* node = (Ogre::SceneNode*)(nodei.getNext());
			// Add this subnode and its children...
		SceneNodeExplore(node);
	}

	xmlTextWriterEndElement(m_XmlWriter); //end SceneNode
}
//=============================================================================
void UpdateStats(Widget* _widget)
{
    ParamsPanel* _panel = dynamic_cast<ParamsPanel*>(_widget);
    assert(_panel);

    // param names
    const Ogre::StringVector& params = _panel->getAllParamNames();
    if (params.empty())
    {
        Ogre::String ParamNames[] = {"Camera Pos","Last FPS","Average FPS","Best FPS","Worst FPS","Triangles","Batches","ProcessMemory"};
        //stat
	    Ogre::StringVector stats(ParamNames, ParamNames + sizeof(ParamNames)/sizeof(Ogre::String));

        _panel->setPanelWidth(250);
        _panel->setAllParamNames(stats);
        _panel->setPanelAlignment(Ogre::GHA_RIGHT, Ogre::GVA_BOTTOM);
    } // End if
    
    // param values
    if (_panel->getOverlayElement()->isVisible())    
	{		
        Ogre::StringVector values;

        Ogre::SceneManager* pSceneMgr = Ogre::Root::getSingletonPtr()->getSceneManager("DefaultSceneManager");
        assert(pSceneMgr);
        Ogre::Camera* pCamera = pSceneMgr->getCamera("DefaultCamera");
        assert(pCamera);
        const Ogre::Vector3& vPosition = pCamera->getPosition();

        char buf[64];
        sprintf_s(buf, sizeof(buf), "%.2f, %.2f, %.2f", vPosition.x, vPosition.y, vPosition.z);
        values.push_back(buf);

        Ogre::RenderWindow* _pRenderWindow = (Ogre::RenderWindow*)Ogre::Root::getSingletonPtr()->getRenderTarget("Ogre Render Window");
        assert(_pRenderWindow);    
        const Ogre::RenderTarget::FrameStats& stats = _pRenderWindow->getStatistics();

        // fps info
		std::ostringstream oss;
        Ogre::String str;

        float fps[] = {stats.lastFPS, stats.avgFPS, stats.bestFPS, stats.worstFPS};
        int size = sizeof(fps)/sizeof(float);
        for (int j = 0 ; j < size ; ++j)
        {
            oss.str("");
            oss << std::fixed << std::setprecision(1) << fps[j];
            str = oss.str();
		    for (int i = str.length() - 5; i > 0; i -= 3) { str.insert(i, 1, ','); }
		    values.push_back(str);
        } // End for
        
        // triangle info
		str = Ogre::StringConverter::toString(stats.triangleCount);
		for (int i = str.length() - 3; i > 0; i -= 3) { str.insert(i, 1, ','); }
		values.push_back(str);

		str = Ogre::StringConverter::toString(stats.batchCount);
		for (int i = str.length() - 3; i > 0; i -= 3) { str.insert(i, 1, ','); }
		values.push_back(str);

/*
 * calculate total triangle count for all render targets
 *
        size_t uiTotalTriangleCount = 0, uiTotalBatchCount = 0;
        Ogre::RenderSystem* _pRenderSystem = Ogre::Root::getSingletonPtr()->getRenderSystem();
        assert(_pRenderSystem);
        Ogre::RenderSystem::RenderTargetIterator it = _pRenderSystem->getRenderTargetIterator();
	    while(it.hasMoreElements())
	    {
            uiTotalTriangleCount += it.current()->second->getTriangleCount();
		    uiTotalBatchCount += it.current()->second->getBatchCount();

            it.getNext();
	    } // End while
*/
        // memory info
        oss.str("");
		oss << std::fixed << std::setprecision(3) << CalculateProcessMemory()/(1024.0f*1024.0f);
        str = oss.str();
 		values.push_back(str);

		_panel->setAllParamValues(values);
	}
}
예제 #19
0
void EC_OgreEnvironment::UpdateVisualEffects(f64 frametime)
{
    if (renderer_.expired())
        return;
    RendererPtr renderer = renderer_.lock();
    Ogre::Camera *camera = renderer->GetCurrentCamera();
    Ogre::Viewport *viewport = renderer->GetViewport();
    Ogre::SceneManager *sceneManager = renderer->GetSceneManager();
        
#ifdef CAELUM
    // Set sunlight attenuation using diffuse multiplier.
    // Seems to be working ok, but feel free to fix if you find better logic and/or values.
    Ogre::ColourValue diffuseMultiplier(sunColorMultiplier_, sunColorMultiplier_, sunColorMultiplier_, 1);
    caelumSystem_->getSun()->setDiffuseMultiplier(diffuseMultiplier);

    Ogre::Light* sun = caelumSystem_->getSun()->getMainLight();
    Ogre::Light* moon = caelumSystem_->getMoon()->getMainLight();

    float sunDirZaxis = caelumSystem_->getSun()->getMainLight()->getDirection().z;
    if (sunDirZaxis > 0)
    {
        sunColorMultiplier_ -= 0.005f;
        if (sunColorMultiplier_ <= 0.05f)
            sunColorMultiplier_ = 0.05f;
    }
    else if(sunDirZaxis < 0)
    {
        sunColorMultiplier_ += 0.010f;
        if (sunColorMultiplier_ >= MAX_SUNLIGHT_MULTIPLIER)
            sunColorMultiplier_ = MAX_SUNLIGHT_MULTIPLIER;
    }
    
    if ( !fog_color_override_)
        fogColor_ = caelumSystem_->getGroundFog()->getColour();
#endif

#ifdef CAELUM
    // Update Caelum system.
    caelumSystem_->notifyCameraChanged(camera);
    caelumSystem_->updateSubcomponents(frametime);

    // Disable specular from the sun & moon for now, because it easily leads to too strong results
    sun->setSpecularColour(0.0f, 0.0f, 0.0f);
    moon->setSpecularColour(0.0f, 0.0f, 0.0f);
#endif

#ifdef HYDRAX
    
    // Update Hydrax system.
    hydraxSystem_->update(frametime);
    sunPos = camera->getPosition();
    sunPos -= caelumSystem_->getSun()->getLightDirection() * 80000;
    hydraxSystem_->setSunPosition(sunPos);


#endif

    Ogre::Entity* water = 0;
    
    cameraFarClip_ = renderer->GetViewDistance();
    
    if ( sceneManager->hasEntity("WaterEntity") )
        water = sceneManager->getEntity("WaterEntity");
              
    if (!water)
    {
        // No water entity, set fog value.
        Real fogStart = fogStart_;
        Real fogEnd = fogEnd_;
        ClampFog(fogStart, fogEnd, cameraFarClip_);
        
        sceneManager->setFog(Ogre::FOG_LINEAR, fogColor_, 0.001, fogStart, fogEnd);
        viewport->setBackgroundColour(fogColor_);
        camera->setFarClipDistance(cameraFarClip_);
    }
    else 
    {
        if(camera->getDerivedPosition().z >= water->getParentNode()->getPosition().z)
        {        
            // We're above the water.
            Real fogStart = fogStart_;
            Real fogEnd = fogEnd_;
            ClampFog(fogStart, fogEnd, cameraFarClip_);
        
#ifdef CAELUM
            caelumSystem_->forceSubcomponentVisibilityFlags(caelumComponents_);
#endif
            sceneManager->setFog(Ogre::FOG_LINEAR, fogColor_, 0.001, fogStart, fogEnd);
            viewport->setBackgroundColour(fogColor_);
            camera->setFarClipDistance(cameraFarClip_);
            cameraUnderWater_ = false;
        }
        else
        {
            // We're below the water.
            Real fogStart = waterFogStart_;
            Real fogEnd = waterFogEnd_;
            Real farClip = waterFogEnd_ + 10.f;
            if (farClip > cameraFarClip_)
                farClip = cameraFarClip_;            
            ClampFog(fogStart, fogEnd, farClip);            
#ifdef CAELUM
            // Hide the Caelum subsystems.
            caelumSystem_->forceSubcomponentVisibilityFlags(Caelum::CaelumSystem::CAELUM_COMPONENTS_NONE);
#endif
            sceneManager->setFog(Ogre::FOG_LINEAR, fogColor_ * waterFogColor_, 0.001, fogStart, fogEnd);
            viewport->setBackgroundColour(fogColor_ * waterFogColor_);
            camera->setFarClipDistance(farClip);
            cameraUnderWater_ = true;
        }
    }

#ifdef CAELUM 
    // If sun color and direction are controlled by user then their value are needed to override here. 
    // internally caelum calculates new values for those so they are needed to set again in each update loop.

    if ( override_flags_.testFlag(None) )
        return;

    if ( override_flags_.testFlag(AmbientLight))
    {   
        // Override ambient light.
        sceneManager->setAmbientLight(userAmbientLight_);
    }

    if ( override_flags_.testFlag(SunDirection) )
    {
        // Override sun direction.
        if ( sun != 0 )
            sun->setDirection(userSunDirection_);
    }

    if ( override_flags_.testFlag(SunColor) )
    {
        // Override sun color. 
        if ( sun != 0 )
            sun->setDiffuseColour(userSunColor_);
    }
#endif 

}