void CharacterController::setupBody(SceneManager* sceneMgr) {
	// create main model
	mBodyNode = sceneMgr->getRootSceneNode()->createChildSceneNode(Vector3::UNIT_Y * CHAR_HEIGHT);
	mBodyEnt = sceneMgr->createEntity("SinbadBody", "Sinbad.mesh");
	mBodyEnt->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE);
	mBodyNode->attachObject(mBodyEnt);
	mMove = true;

	// scale to fit
	mBodyNode->scale(CHAR_SCALE_X, CHAR_SCALE_Y, CHAR_SCALE_Z);

	mKeyDirection = Vector3::ZERO;
	mVerticalVelocity = 0;

	// Get the two halves of the idle animation
	Ogre::AnimationState* baseAnim = mBodyEnt->getAnimationState("IdleBase");
	Ogre::AnimationState* topAnim = mBodyEnt->getAnimationState("IdleTop");

	// Enable both of them and set them to loop.
	baseAnim->setLoop(true);
	topAnim->setLoop(true);
	baseAnim->setEnabled(true);
	topAnim->setEnabled(true);

	mBodyNode->setVisible(false, true);
}
示例#2
0
//-------------------------------------------------------------------------------------
void DeltaControl::createScene(void) {

    mSceneMgr->setSkyBox(true, "StormySkyBox");

    mControlCenter = new ControlCenter(mSceneMgr);

    /* *********************************************************
     * ENTITIES
     * *********************************************************/

//	Telephone* phone = new Telephone(mSceneMgr, "phone1");
//	phone->init();

    // Create entity from mesh and attach it to a scene node.
    Ogre::SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode();
    Ogre::Entity* ent = mSceneMgr->createEntity("Sinbad", "Sinbad.mesh");
    node->attachObject(ent);
    node->setPosition(0,50,0);
    node->scale(10,10,10);

    // Set animation blend mode to additive / cumulative.
    ent->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE);

    // Get the two halves of the idle animation
    Ogre::AnimationState* baseAnim = ent->getAnimationState("IdleBase");
    Ogre::AnimationState* topAnim = ent->getAnimationState("IdleTop");

    // Enable both of them and set them to loop.
    baseAnim->setLoop(true);
    topAnim->setLoop(true);
    baseAnim->setEnabled(true);
    topAnim->setEnabled(true);

}
    bool EC_OgreAnimationController::EnableAnimation(const std::string& name, bool looped, Real fadein, bool high_priority)
    {
        Ogre::Entity* entity = GetEntity();
        Ogre::AnimationState* animstate = GetAnimationState(entity, name);
        if (!animstate) 
            return false;

        animstate->setLoop(looped);

        // See if we already have this animation
        AnimationMap::iterator i = animations_.find(name);
        if (i != animations_.end())
        {
            i->second.phase_ = PHASE_FADEIN;
            i->second.num_repeats_ = (looped ? 0: 1);
            i->second.fade_period_ = fadein;
            i->second.high_priority_ = high_priority;
            return true;
        }
        
        // Start new animation from zero weight & speed factor 1, also reset time position
        animstate->setTimePosition(0.0f);
        
        Animation newanim;
        newanim.phase_ = PHASE_FADEIN;
        newanim.num_repeats_ = (looped ? 0: 1); // if looped, repeat 0 times (loop indefinetly) otherwise repeat one time.
        newanim.fade_period_ = fadein;
        newanim.high_priority_ = high_priority;

        animations_[name] = newanim;

        return true;
    }
示例#4
0
NifOgre::EntityList NpcAnimation::insertBoundedPart(const std::string &mesh, int group, const std::string &bonename)
{
    NifOgre::EntityList entities = NifOgre::Loader::createEntities(mEntityList.mSkelBase, bonename,
                                                                   mInsert, mesh);
    std::vector<Ogre::Entity*> &parts = entities.mEntities;
    for(size_t i = 0;i < parts.size();i++)
    {
        parts[i]->getUserObjectBindings().setUserAny(Ogre::Any(group));
        if (mVisibilityFlags != 0)
            parts[i]->setVisibilityFlags(mVisibilityFlags);

        for(unsigned int j=0; j < parts[i]->getNumSubEntities(); ++j)
        {
            Ogre::SubEntity* subEnt = parts[i]->getSubEntity(j);
            subEnt->setRenderQueueGroup(subEnt->getMaterial()->isTransparent() ? RQG_Alpha : RQG_Main);
        }
    }
    if(entities.mSkelBase)
    {
        Ogre::AnimationStateSet *aset = entities.mSkelBase->getAllAnimationStates();
        Ogre::AnimationStateIterator asiter = aset->getAnimationStateIterator();
        while(asiter.hasMoreElements())
        {
            Ogre::AnimationState *state = asiter.getNext();
            state->setEnabled(false);
            state->setLoop(false);
        }
        Ogre::SkeletonInstance *skelinst = entities.mSkelBase->getSkeleton();
        Ogre::Skeleton::BoneIterator boneiter = skelinst->getBoneIterator();
        while(boneiter.hasMoreElements())
            boneiter.getNext()->setManuallyControlled(true);
    }
    return entities;
}
示例#5
0
void
PlayersManager::createPlayer(zappy::Player *player)
{
  Ogre::Entity *ent;
  Ogre::SceneNode *node;
  Ogre::AnimationState *anim;
  std::string id(NumberToString<unsigned int>(player->getId()));
  OPlayer *toAdd;

  ent = this->mSceneMgr->createEntity("Player" + id, "robot.mesh");
  node = this->mSceneMgr->getRootSceneNode()->
    createChildSceneNode(PLAYERNODENAME + id,
                         Ogre::Vector3(player->getX() * Constants::SquareSize,
                                       0,
                                       player->getY() * Constants::SquareSize));
  ent->setQueryFlags(Constants::PLAYER_MASK);
  anim = ent->getAnimationState("Idle");
  anim->setLoop(true);
  anim->setEnabled(true);
  node->attachObject(ent);
  player->setRendered(true);
  toAdd = new OPlayer(ent, node);
  toAdd->setSpell(this->mSceneMgr->createParticleSystem("Aureola" + id, "Examples/Aureola"));
  toAdd->setBroad(this->mSceneMgr->createParticleSystem("Purple" + id, "Examples/PurpleFountain"));
  this->mOPlayers.push_back(toAdd);
}
示例#6
0
	ProfessorController(Root* root)
	{
		mProfessorNode = root->getSceneManager("main")->getSceneNode("Professor");
		mProfessorEntity = root->getSceneManager("main")->getEntity("Professor");

		mWalkSpeed = 80.0f;
		mDirection = Vector3::ZERO;
		mAnimationState = mProfessorEntity->getAnimationState("Walk");
		mAnimationState->setEnabled(true);
		mAnimationState->setLoop(true);
	}
示例#7
0
bool CAnimatedEntity::setAnimation(const std::string &anim, bool loop, int rewind, float fadeTime)
{
    if(!_entity->getAllAnimationStates()->hasAnimationState(anim))
        return false;
    //comprobamos si la animación ya estaba ejecutandose
    auto runningAnim = _runningAnimations.find(anim);

    if(runningAnim != _runningAnimations.end()) {
        if(runningAnim->second.state == FADE_OUT) {
            runningAnim->second.state = FADE_IN;

            //comprobamos que la animación no estaba justo para
            //ser sacada
            if(!_deletedAnims.empty()) {

                auto delAnim = _deletedAnims.begin();
                auto delEnd = _deletedAnims.end();

                for(; delAnim!=delEnd; delAnim++) {
                    if ((*delAnim) == runningAnim->second.animation->getAnimationName()) {
                        _deletedAnims.erase(delAnim);
                        runningAnim->second.animation->setEnabled(true);
                        break;
                    }
                }

            }

        }
        runningAnim->second.direction = rewind;
        return true;
    }

    //cogemos la animacion y la preparamos para ejecutarla
    Ogre::AnimationState* animstate = _entity->getAnimationState(anim);
    animstate->setEnabled(true);
    animstate->setLoop(loop);
    animstate->setWeight(0);

    //seteamos la animación nueva para que haga fade-in, teniendo
    //en cuenta el tiempo de fade que se le ha pasado
    Animation animation;
    animation.animation = animstate;
    animation.state = FADE_IN;
    animation.fadeTime = fadeTime;
    animation.direction = rewind;
    //metemos la animacion en la lista de animaciones ejecutandose
    TAnim newAnim (anim,animation);
    _runningAnimations.insert(newAnim);

    return true;

} // setAnimation
void AssetLoader::createCamera(Ogre::SceneManager* sceneMgr, const aiScene* scene, Ogre::String camName)
{
	for (size_t n = 0; n < scene->mNumCameras; n++)
	{
		// カメラを作成
		Ogre::Camera* cam = sceneMgr->createCamera(scene->mCameras[n]->mName.data);
		std::cout << "Create Camra " << cam->getName() << " " << scene->mCameras[n]->mHorizontalFOV << std::endl;
		cam->setFOVy(Ogre::Radian(scene->mCameras[n]->mHorizontalFOV));
		
		// 視点アニメーション用ノード
		Ogre::SceneNode* camNode = sceneMgr->getRootSceneNode()->createChildSceneNode(cam->getName()+"CamNode");
		camNode->attachObject(cam);

		// アニメーションを走査
		for (size_t na = 0; na < scene->mNumAnimations; na++) {
			aiAnimation* aiani = scene->mAnimations[na];
			for (size_t nc = 0; nc < aiani->mNumChannels; nc++) {
				// カメラと同じ名前のチャネルを取得する
				if (Ogre::String(scene->mCameras[n]->mName.data) == cam->getName()) {
					
					//アニメーションを付けるトラックを作成しておく
					Ogre::Animation* ogani = sceneMgr->createAnimation(cam->getName()+"Animation", aiani->mDuration);
					std::cout << "Animation : " << ogani->getName() << std::endl; 
					Ogre::NodeAnimationTrack* track = ogani->createNodeTrack(0, camNode);
					ogani->setInterpolationMode(Ogre::Animation::IM_LINEAR);

					// アニメーションチャネルからキーフレームアニメーションを取得
					aiNodeAnim* chan = aiani->mChannels[n];
					for (size_t np = 0; np < chan->mNumPositionKeys; np++) {						
						aiVectorKey* vk = &(chan->mPositionKeys[np]);
						Ogre::TransformKeyFrame* key = track->createNodeKeyFrame(vk->mTime);
						key->setTranslate(Ogre::Vector3(vk->mValue[0], vk->mValue[1], vk->mValue[2]));

						aiQuatKey* qk = &(chan->mRotationKeys[np]);
						key->setRotation(Ogre::Quaternion(qk->mValue.w, qk->mValue.x, qk->mValue.y, qk->mValue.z));
					}

					// 管理するアニメーションの名前を付けておく
					Ogre::AnimationState* aniState = sceneMgr->createAnimationState(ogani->getName());
					aniState->setEnabled(true);
					aniState->setLoop(true);
					aniState->setTimePosition(0.0);

					//ループを抜ける
					na = scene->mNumAnimations;
					break;
				}
			}
		}
	}
}
示例#9
0
	bool frameStarted(const FrameEvent &evt)
	{
		// Fill Here --------------------------------------------------------------
		if (Vector3::ZERO == mDirection)
		{
			if (nextLocation())
			{
				mAnimationState = mProfessorEntity->getAnimationState("Walk");
				mAnimationState->setLoop(true);
				mAnimationState->setEnabled(true);
			}
		}
		else // Vector3::ZERO != mDirection
		{
			Real move = mWalkSpeed * evt.timeSinceLastFrame;
			mDistance -= move;
			if (mDistance <= 0.f)
			{ // 목표 지점에 다 왔으면
				mProfessorNode->setPosition(mDestination);
				mDestination = Vector3::ZERO;
				if (!nextLocation())
				{
					mAnimationState->setEnabled(false);
					mAnimationState = mProfessorEntity->getAnimationState("Idle");
					mAnimationState->setLoop(true);
					mAnimationState->setEnabled(true);
				}
			}
			else 
			{
				mProfessorNode->translate(mDirection * move);
			}
		}
		// -------------------------------------------------------------------------
		mAnimationState->addTime(evt.timeSinceLastFrame);

		return true;
	}
示例#10
0
CreatureAnimation::CreatureAnimation(const MWWorld::Ptr& ptr): Animation()
{
    mInsert = ptr.getRefData().getBaseNode();
    MWWorld::LiveCellRef<ESM::Creature> *ref = ptr.get<ESM::Creature>();

    assert (ref->mBase != NULL);
    if(!ref->mBase->mModel.empty())
    {
        std::string mesh = "meshes\\" + ref->mBase->mModel;

        mEntityList = NifOgre::NIFLoader::createEntities(mInsert, &mTextKeys, mesh);
        for(size_t i = 0; i < mEntityList.mEntities.size(); i++)
        {
            Ogre::Entity *ent = mEntityList.mEntities[i];
            ent->setVisibilityFlags(RV_Actors);

            bool transparent = false;
            for (unsigned int j=0; j < ent->getNumSubEntities() && !transparent; ++j)
            {
                Ogre::MaterialPtr mat = ent->getSubEntity(j)->getMaterial();
                Ogre::Material::TechniqueIterator techIt = mat->getTechniqueIterator();
                while (techIt.hasMoreElements() && !transparent)
                {
                    Ogre::Technique* tech = techIt.getNext();
                    Ogre::Technique::PassIterator passIt = tech->getPassIterator();
                    while (passIt.hasMoreElements() && !transparent)
                    {
                        Ogre::Pass* pass = passIt.getNext();

                        if (pass->getDepthWriteEnabled() == false)
                            transparent = true;
                    }
                }
            }
            ent->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);
        }

        if(mEntityList.mSkelBase)
        {
            Ogre::AnimationStateSet *aset = mEntityList.mSkelBase->getAllAnimationStates();
            Ogre::AnimationStateIterator as = aset->getAnimationStateIterator();
            while(as.hasMoreElements())
            {
                Ogre::AnimationState *state = as.getNext();
                state->setEnabled(true);
                state->setLoop(false);
            }
        }
    }
}
示例#11
0
  bool frameStarted(const FrameEvent &evt)
  {
    if (mDirection == Vector3::ZERO) 
    {
      if (nextLocation()) 
      {
        mAnimationState = mProfessorEntity->getAnimationState("Walk");
        mAnimationState->setLoop(true);
        mAnimationState->setEnabled(true);
      }
    } 
    else 
    {
      Real move = mWalkSpeed * evt.timeSinceLastFrame; // 이동량 계산
      mDistance -= move; // 남은 거리 계산
      if (mDistance <= 0.0f) 
      { // 목표 지점에 다 왔으면…
        mProfessorNode->setPosition( mDestination ); // 목표 지점에 캐릭터를 위치
        mDirection = Vector3::ZERO; // 정지 상태로 들어간다.
        if (! nextLocation( ) ) 
        {
          mAnimationState->setEnabled(false);
          mAnimationState = mProfessorEntity->getAnimationState( "Idle" );
          mAnimationState->setLoop( true );
          mAnimationState->setEnabled( true );
        }
      } 
      else 
      {
        mProfessorNode->translate( mDirection * move );
      }
    }

    mAnimationState->addTime(evt.timeSinceLastFrame);

    return true;
  }
示例#12
0
//-------------------------------------------------------------------------------------
bool
PlayersManager::taking(zappy::Player *p, int i)
{
  OPlayer *OPlayer;

  OPlayer = this->mOPlayers.at(i);
  Ogre::AnimationState *anim = OPlayer->getEntity()->
    getAnimationState("Slump");
  anim->setEnabled(true);
  anim->setLoop(true);
  anim->addTime(this->tslf);
  if (OPlayer->stateHasChanged())
    OPlayer->detachAnim();
  return true;
}
示例#13
0
void Pacman::arrancaMuerte(Ogre::Real deltaT)
{
  stop();
  Ogre::AnimationState *anim;
  Ogre::Entity* pacmanEnt = static_cast<Ogre::Entity*>( node->getAttachedObject(PACMAN_NODE));
  anim = pacmanEnt->getAnimationState(PACMAN_EAT_ANIM);
  anim->setEnabled(false);
  anim = pacmanEnt->getAnimationState(PACMAN_DIES);
  anim->addTime(deltaT);
  anim->setEnabled(true);
  anim->setLoop(false);
  anim->setTimePosition(0.0);
  estoyMuriendo = true;

}
示例#14
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;
}
示例#15
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;
}
示例#16
0
  void createScene()
  {
    // Create the Entity
    Ogre::Entity* robot = mSceneMgr->createEntity("Robot", "robot.mesh");
    // Attach robot to scene graph
    Ogre::SceneNode* RobotNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("Robot");
    //RobotNode->setPosition((Ogre::Real)-0.3, (Ogre::Real)0.2, (Ogre::Real)0);
    RobotNode->attachObject(robot);
    RobotNode->scale((Ogre::Real)0.001,(Ogre::Real)0.001,(Ogre::Real)0.001);
    RobotNode->pitch(Ogre::Degree(180));
    RobotNode->yaw(Ogre::Degree(-90));

    // The animation
    // Set the good animation
    mAnimationState = robot->getAnimationState( "Idle" );
    // Start over when finished
    mAnimationState->setLoop( true );
    // Animation enabled
    mAnimationState->setEnabled( true );
  }
void MeshPersonVisual::setAnimationState(const std::string& nameOfAnimationState) {
    Ogre::AnimationStateSet *animationStates = entity_->getAllAnimationStates();
    if(animationStates != NULL)
    {
      Ogre::AnimationStateIterator animationsIterator = animationStates->getAnimationStateIterator();
      while (animationsIterator.hasMoreElements())
      {
        Ogre::AnimationState *animationState = animationsIterator.getNext();
        if(animationState->getAnimationName() == nameOfAnimationState || nameOfAnimationState.empty()) {
          animationState->setLoop(true);
          animationState->setEnabled(true);
          m_animationState = animationState;
          return;
        }    
      }

      // Not found. Set first animation state then.
      ROS_WARN_STREAM_ONCE("Person mesh animation state " << nameOfAnimationState << " does not exist in mesh!");
      setAnimationState("");
    }
}
示例#18
0
void Actor::setAnimationEnabled(const QString& name, bool enabled)
{
    assert(mNode);

    if(mNode->numAttachedObjects() == 0)
    {
        qWarning() << "Can't enable animation [" << name
                   << "] on actor [" << getName() << "]"
                   << " because it doesn't have any attached objects.";
        return;
    }

    Ogre::Entity* entity = dynamic_cast<Ogre::Entity*>(mNode->getAttachedObject(0));

    if(!entity)
    {
        qWarning() << "Can't enable animation [" << name
                   << "] on actor [" << getName() << "]"
                   << " because its attachment isn't an entity.";
        return;
    }

    Ogre::AnimationStateSet* set = entity->getAllAnimationStates();
    if(!set->hasAnimationState(name.toStdString()))
    {
        qWarning() << "Tried to set the state of an animation named "
                   << name << " on actor "
                   << QString::fromStdString(mNode->getName())
                   << " that doesn't exist. The animation states remain unchanged.";
        return;
    }

    Ogre::AnimationState* state = set->getAnimationState(name.toStdString());

    state->setEnabled(enabled);
    state->setLoop(true);
}
	void AnimationTask::receiveAnimationTaskMessage(const Poco::AutoPtr<AnimationTaskMessage>& message)
	{
		AnimationMapEntry entry;
		AnimationMapIterator iter;
		AnimationMapValueEntry valueEntry;
		Ogre::AnimationState *animation;
		memUInt animationAddress;
		FunctorBase *pFunctor;

		if (message.get() == NULL)
		{
			LOG(EngineLog::LM_WARNING, "AnimationTask::receiveAnimationTaskMessage(): message is NULL.");

			return;
		}

		Poco::ScopedRWLock lock(mRWLockActiveAnimations, true);

		animation = message->getAnimation();
		animationAddress = reinterpret_cast<memUInt>(animation);
		if (animation != NULL)
		{
			iter = activeAnimations.find(animationAddress); 
		}

		switch (message->getMessageType())
		{
			case AnimationTaskMessage::AM_ENABLE:
				// If the playCounter flag is true, increment the playCounter if the animation is active, other just start 
				// playing the animation if the counter is one.
				if ((message->isPlayCounter()) && (iter != activeAnimations.end()))
				{
					valueEntry = iter->second;
					valueEntry.second++;
				}
				else
				{
					// Set the loop, restart and enabled values for the animation
					animation->setLoop(message->isLoop());
					if (message->isRestart())
					{
						animation->setTimePosition(0.0f);
					}
					animation->setEnabled(true);

					valueEntry.first = animation;
					valueEntry.second = 1;
				}

				// Add this animations start and stop callbacks to the callback maps
				pFunctor = message->getStartCallback();
				if (pFunctor != NULL)
				{
					Poco::ScopedRWLock lock(mRWLockCallbacks, true);
					mStartCallbacks[animationAddress] = pFunctor;
				}
				pFunctor = message->getStopCallback();
				if (pFunctor != NULL)
				{
					Poco::ScopedRWLock lock(mRWLockCallbacks, true);
					mStopCallbacks[animationAddress] = pFunctor;
				}

				// Add it to the list of active animations
				activeAnimations[animationAddress] = valueEntry;

				// Add it to the set of starting animations
				mStartingAnimations.insert(animationAddress);
				break;

			case AnimationTaskMessage::AM_DISABLE:
				if (iter != activeAnimations.end())
				{
					// If the playCounter flag is true, decrement the playCounter if the animation is active, otherwise just stop 
					// playing the animation if the counter <= 0.
					if (message->isPlayCounter())
					{
						valueEntry = iter->second;
						valueEntry.second--;
						if (valueEntry.second == 0)
						{
							// Mark animation as disabled and remove it from the list
							// of active animations
							animation->setEnabled(false);
							activeAnimations.erase(animationAddress);
							// Remove any callbacks associated with this animation
							{
								Poco::ScopedRWLock lock(mRWLockCallbacks, true);
								mStartCallbacks.erase(animationAddress);
								mStopCallbacks.erase(animationAddress);
							}
						}
						else
						{
							activeAnimations[animationAddress] = valueEntry;
						}
					}
					else
					{
						// Mark animation as disabled and remove it from the list
						// of active transformations
						animation->setEnabled(false);
						activeAnimations.erase(animationAddress);
						// Remove any callbacks associated with this animation
						{
							Poco::ScopedRWLock lock(mRWLockCallbacks, true);
							mStartCallbacks.erase(animationAddress);
							mStopCallbacks.erase(animationAddress);
						}
					}
				}
				break;
			case AnimationTaskMessage::AM_DISABLE_ALL:
				{
					// Remove all active animations and their callbacks
					Poco::ScopedRWLock(mRWLockCallbacks, true);
					for (iter = activeAnimations.begin(); iter != activeAnimations.end(); ++iter)
					{
						animationAddress = iter->first;
						mStartCallbacks.erase(animationAddress);
						mStopCallbacks.erase(animationAddress);
					}
					activeAnimations.clear();
					mStartingAnimations.clear();
				}
				break;
		}
	}
示例#20
0
 void mesh_anim_play ( void *state, bool loop ) {
     Ogre::AnimationState *s = static_cast<Ogre::AnimationState *> ( state );
     s->setLoop ( loop );
     s->setEnabled ( true );
 }
示例#21
0
	void DemoGameLogic::initialise(void)
	{
		//qApp->setStyleSheet(qApp->settings()->value("UI/StyleFile").toString());
		
		mDemoLog = mApplication->createLog("Demo");

		mApplication->showLogManager();

		mDemoLog->logMessage("A demonstration debug message", LL_DEBUG);
		mDemoLog->logMessage("A demonstration info message", LL_INFO);
		mDemoLog->logMessage("A demonstration warning message", LL_WARNING);
		mDemoLog->logMessage("A demonstration error message", LL_ERROR);

		//Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

		// Create the generic scene manager
		mSceneManager = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC, "GenericSceneManager");

		//Set up scene
		loadScene("media/scenes/test.scene");

		//mApplication->ogreRenderWindow()->addViewport(mCamera)->setBackgroundColour(Ogre::ColourValue::Black);

		mSceneManager->setAmbientLight( Ogre::ColourValue( 1, 1, 1 ) );

		//Create the MainMenu
		mMainMenu = new MainMenu(qApp, qApp->mainWidget());

		//Create widget to choose between models
		//mChooseMeshWidget = new ChooseMeshWidget(mJaiquaEntity, mRobotEntity, qApp->mainWidget());
		//mChooseMeshWidget->setWindowOpacity(qApp->settings()->value("System/DefaultWindowOpacity", 1.0).toDouble());
		//mChooseMeshWidget->move(qApp->mainWidget()->geometry().left() + qApp->mainWidget()->geometry().width() - mChooseMeshWidget->frameGeometry().width() - 10, qApp->mainWidget()->geometry().top() + 10);
		//mChooseMeshWidget->show();

		mTime = new QTime;
		mTime->start();

		mIsFirstFrame = true;

		mCameraSpeed = 10.0;

		

		for (Ogre::SceneManager::MovableObjectIterator moi = mSceneManager->getMovableObjectIterator("Entity"); moi.hasMoreElements(); moi.moveNext())
		{
			Ogre::Entity *entity = static_cast<Ogre::Entity*>(moi.peekNextValue());

			Ogre::AnimationStateSet* animationStateSet = entity->getAllAnimationStates();		
			if(animationStateSet && animationStateSet->hasAnimationState("Walk"))
			{
				Ogre::AnimationState* walkAnimationState = animationStateSet->getAnimationState("Walk");
				walkAnimationState->setLoop(true);
				walkAnimationState->setEnabled(true);
			}
		}

		mApplication->showFPSCounter();
		
		mStyleSettingsWidget = new StyleSettingsWidget;
		mApplication->addSettingsWidget("Style", mStyleSettingsWidget);
	}
示例#22
0
bool
PlayState::frameStarted
(const Ogre::FrameEvent& evt)
{
   std::cout << "frameStarted PLAY" << std::endl;

  Ogre::Vector3 vt(0,0,0);     Ogre::Real tSpeed = 20.0;  
  _deltaT = evt.timeSinceLastFrame;

  _world->stepSimulation(_deltaT); // Actualizar simulacion Bullet
  _timeLastObject -= _deltaT;

  _camera->moveRelative(vt * _deltaT * tSpeed);
  if (_camera->getPosition().length() < 10.0) {
    _camera->moveRelative(-vt * _deltaT * tSpeed);
  }

  _camera->yaw(Degree(CAM_ROTATION_SPEED * _deltaT * _mouseRotation.x)); //, Node::TS_PARENT
  _camera->pitch(Degree(CAM_ROTATION_SPEED * _deltaT * _mouseRotation.y)); //, Node::TS_LOCAL
  _mouseRotation = Vector2::ZERO;

  //CONTROLAR LA DIRECCION DE LA CAMARA DEL PROYECTIL
  _projectileCamera->lookAt(_camera->getDerivedDirection());
  
  if(_trackedBody){
    _projectileCamera->setPosition(_trackedBody->getCenterOfMassPosition());
    Ogre::Vector3 trackedBodyPosition = _trackedBody->getCenterOfMassPosition();
    Ogre::Vector3 projectileLookAt(trackedBodyPosition.x - _camera->getPosition().x, trackedBodyPosition.y - _camera->getPosition().y, trackedBodyPosition.z - _camera->getPosition().z);
    //_projectileCamera->lookAt(_camera->getDerivedDirection());
    _projectileCamera->lookAt(trackedBodyPosition + projectileLookAt);
  }
   std::cout << "CAMERAS" << std::endl;
  if(_shootKeyDown){
    _keyDownTime = _keyDownTime + _deltaT;
  }
 
  if(_keyDownTime * THROW_FORCE > 100){
    _forcePercent = 100;
  }  
  else{
    _forcePercent = _keyDownTime * THROW_FORCE;
  }

  //_points++;
  _sPF->updatePower(_forcePercent);
  _sPF->updatePoints(_points);
  //std::cout<<_sPF->getSheet()->getChild("PowerWindow")->getUpdateMode() <<std::endl;
  //_sPF->getSheet()->getChild("PowerWindow")->update(_deltaT);
  //CEGUI::System::getSingleton().injectTimePulse(_deltaT);
  //DetectCollisionPig();
   std::cout << "points power" << std::endl;
  _physicsController->detectCollision();  //Este es el bueno. Hay que cambiarlo para que compruebe colisiones sobre todo
   std::cout << "pisis" << std::endl;
  _movementController->moveAll();
  std::cout << "collision moveall" << std::endl;
  if(_finalGame){
      pushState(FinalState::getSingletonPtr());
  }
  lifeWolf();
 std::cout << "wolf" << std::endl;
  if (_lanzaranimationPig){
    for (int i = 0; i < 3; ++i){
      std::ostringstream os;
      os << "pigA" <<i; 
      Ogre::AnimationState* animStatePig = _sceneMgr->getEntity(os.str())-> getAnimationState("SaltoR");
      animStatePig->setTimePosition(0.0);
      animStatePig->setEnabled(true);
      animStatePig->setLoop(true);
      _vector_anims_pig -> push_back(animStatePig);
    }
    _lanzaranimationPig = false;
  }
  

  for (int i = 0; i < 3; ++i){
      Ogre::AnimationState* animStatePig = _vector_anims_pig->at(i);
      if (animStatePig != NULL){
        if (animStatePig->hasEnded()){
          animStatePig->setTimePosition(0.0);
          animStatePig->setEnabled(false);
        }else{
          animStatePig->addTime(_deltaT);
        }
      }
  }
   std::cout << "animation" << std::endl;
  //RecorreVectorTAOAnadirMovimientoConstante();
  //std::cout << "Hasta aqui todo bien 1" << std::endl;

  return true;
  
}
示例#23
0
/* Function used to load an AnimationState to a sceneNode.
 * Params:
 * 	@scnManager		the SceneManager
 * 	@node			The SceneNode to load the AnimationStates
 * 	@elem			The TiXmlElement where is the animation
 * Returns:
 * 	anim			On success
 * 	0				On error
 */
bool Util::getAnimation(Ogre::SceneManager *scnManager,
		Ogre::SceneNode *node,
		TiXmlElement *elem,
		std::list<Ogre::AnimationState *> &animList)
{
	ASSERT(scnManager);
	ASSERT(node);
	ASSERT(elem);

	if(Ogre::String(elem->Value()) != "animations") {
		debug("Invalid animation xml: %s \n", elem->Value());
		return false;
	}
	animList.clear();

	TiXmlElement *pElement = elem->FirstChildElement("animation");
	if(!pElement){
		debug("No animations found\n");
		return false;
	}
	while(pElement){
		TiXmlElement *actualElement = pElement;
		Ogre::String nombreanimacion = actualElement->Attribute("name");
		Ogre::String activada = actualElement->Attribute("enable");
		Ogre::String loop = actualElement->Attribute("loop");
		Ogre::String modointerpolacion = actualElement->Attribute("interpolationMode");
		Ogre::String modointerpolacionrotacion = actualElement->Attribute("rotationInterpolationMode");
		Ogre::Real longitud= Ogre::StringConverter::parseReal(actualElement->Attribute("length"));

		Ogre::SceneManager *sceneMgr = scnManager;
		Ogre::Animation *animrueda = sceneMgr->createAnimation(nombreanimacion,longitud);

		if (modointerpolacion == "spline") {
			animrueda->setInterpolationMode(Ogre::Animation::IM_SPLINE);
		} else //linear
		{
			animrueda->setInterpolationMode(Ogre::Animation::IM_LINEAR);
		}

		if (modointerpolacionrotacion == "spherical") {
			animrueda->setRotationInterpolationMode(Ogre::Animation::RIM_SPHERICAL);
		} else //linear
		{
			animrueda->setRotationInterpolationMode(Ogre::Animation::RIM_LINEAR);
		}

		Ogre::NodeAnimationTrack *track = animrueda->createNodeTrack(
				animrueda->getNumNodeTracks() + 1, node);

		actualElement = actualElement->FirstChildElement();
		do {
			Ogre::Real tiempo = Ogre::StringConverter::parseReal(
					actualElement->Attribute("time"));
			Ogre::TransformKeyFrame *kf = track->createNodeKeyFrame(tiempo);

			kf->setTranslate(
					parseVector3(actualElement->FirstChildElement("translation")));
			kf->setRotation(
					parseQuaternion(
							actualElement->FirstChildElement("rotation")));
			kf->setScale(
					parseVector3(
							actualElement->FirstChildElement("scale")));

		} while (actualElement = actualElement->NextSiblingElement());

		// Create the animation and put it in the list
		Ogre::AnimationState *as = scnManager->createAnimationState(nombreanimacion);
		as->setEnabled(false);
		as->setLoop(false);
		ASSERT(as);
		animList.push_back(as);
		pElement = pElement->NextSiblingElement("animation");
	}


	return true;
}
示例#24
0
NpcAnimation::NpcAnimation(const MWWorld::Ptr& ptr, Ogre::SceneNode* node, MWWorld::InventoryStore& _inv, int visibilityFlags)
    : Animation(), mStateID(-1), mInv(_inv), timeToChange(0), mVisibilityFlags(visibilityFlags),
    robe(mInv.end()), helmet(mInv.end()), shirt(mInv.end()),
    cuirass(mInv.end()), greaves(mInv.end()),
    leftpauldron(mInv.end()), rightpauldron(mInv.end()),
    boots(mInv.end()),
    leftglove(mInv.end()), rightglove(mInv.end()), skirtiter(mInv.end()),
    pants(mInv.end())
{
    MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();

    for (int init = 0; init < 27; init++)
    {
        mPartslots[init] = -1;  //each slot is empty
        mPartPriorities[init] = 0;
    }

    const ESMS::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
    const ESM::Race *race = store.races.find(ref->base->mRace);

    std::string hairID = ref->base->mHair;
    std::string headID = ref->base->mHead;
    headModel = "meshes\\" + store.bodyParts.find(headID)->mModel;
    hairModel = "meshes\\" + store.bodyParts.find(hairID)->mModel;
    npcName = ref->base->mName;

    isFemale = !!(ref->base->mFlags&ESM::NPC::Female);
    isBeast = !!(race->mData.mFlags&ESM::Race::Beast);

    bodyRaceID = "b_n_"+ref->base->mRace;
    std::transform(bodyRaceID.begin(), bodyRaceID.end(), bodyRaceID.begin(), ::tolower);


    mInsert = node;
    assert(mInsert);

    std::string smodel = (!isBeast ? "meshes\\base_anim.nif" : "meshes\\base_animkna.nif");

    mEntityList = NifOgre::NIFLoader::createEntities(mInsert, &mTextKeys, smodel);
    for(size_t i = 0;i < mEntityList.mEntities.size();i++)
    {
        Ogre::Entity *base = mEntityList.mEntities[i];

        base->getUserObjectBindings ().setUserAny (Ogre::Any(-1));

        base->setVisibilityFlags(mVisibilityFlags);
        bool transparent = false;
        for(unsigned int j=0;j < base->getNumSubEntities();++j)
        {
            Ogre::MaterialPtr mat = base->getSubEntity(j)->getMaterial();
            Ogre::Material::TechniqueIterator techIt = mat->getTechniqueIterator();
            while (techIt.hasMoreElements())
            {
                Ogre::Technique* tech = techIt.getNext();
                Ogre::Technique::PassIterator passIt = tech->getPassIterator();
                while (passIt.hasMoreElements())
                {
                    Ogre::Pass* pass = passIt.getNext();
                    if (pass->getDepthWriteEnabled() == false)
                        transparent = true;
                }
            }
        }
        base->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);
    }

    if(mEntityList.mSkelBase)
    {
        Ogre::AnimationStateSet *aset = mEntityList.mSkelBase->getAllAnimationStates();
        Ogre::AnimationStateIterator as = aset->getAnimationStateIterator();
        while(as.hasMoreElements())
        {
            Ogre::AnimationState *state = as.getNext();
            state->setEnabled(true);
            state->setLoop(false);
        }
    }

    float scale = race->mData.mHeight.mMale;
    if (isFemale) {
        scale = race->mData.mHeight.mFemale;
    }
    mInsert->scale(scale, scale, scale);

    updateParts();
}
示例#25
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;
}
void OgreCharacterController::animate(Ogre::Real elapsedTime, OGRE_ANIMATION_STATE state)
{
  Ogre::Entity * ent = getEntity();
  Ogre::AnimationState * animTop = 0;
  Ogre::AnimationState * animBase = 0;

  if(animTimer > 0) {
    if(lastTop != 0)
      lastTop->addTime(elapsedTime);
    if(lastBase != 0)
      lastBase->addTime(elapsedTime);
    animTimer -= elapsedTime;
    return;
  }
  
  switch(state)
  {
  case IDLE:
    animTop  = ent->getAnimationState("IdleTop");
    animBase = ent->getAnimationState("IdleBase");
    break;
  case RUN:
    animTop = ent->getAnimationState("RunTop");
    animBase = ent->getAnimationState("RunBase");
    break;
  case DRAWSWORDS:
    drawSwords(animTop, ent);
    animBase = lastBase;
    break;
  case SLICE:
    animTop = lastTop;
    if(swordsOut)
      slice(animTop, ent);
    animBase = lastBase;
    break;
  }

  // Disable last set of animations
  if(animTop != lastTop) {
    if(lastTop != 0)
      lastTop->setEnabled(false);
  }

  if(animBase != lastBase) {
    if(lastBase != 0)
      lastBase->setEnabled(false);
  }

  // Enable next set
  if(animTop) {
    animTop->setEnabled(true);
    animTop->setLoop(true);
    animTop->addTime(elapsedTime);
  }

  if(animBase) {
    animBase->setEnabled(true);
    animBase->setLoop(true);
    animBase->addTime(elapsedTime);
  }

  // Book keeping
  lastTop = animTop;
  lastBase = animBase;
}
示例#27
0
void Animation::setObjectRoot(const std::string &model, bool baseonly)
{
    OgreAssert(mAnimSources.empty(), "Setting object root while animation sources are set!");

    mSkelBase = NULL;
    mObjectRoot.setNull();

    if(model.empty())
        return;

    std::string mdlname = Misc::StringUtils::lowerCase(model);
    std::string::size_type p = mdlname.rfind('\\');
    if(p == std::string::npos)
        p = mdlname.rfind('/');
    if(p != std::string::npos)
        mdlname.insert(mdlname.begin()+p+1, 'x');
    else
        mdlname.insert(mdlname.begin(), 'x');
    if(!Ogre::ResourceGroupManager::getSingleton().resourceExistsInAnyGroup(mdlname))
    {
        mdlname = model;
        Misc::StringUtils::toLower(mdlname);
    }

    mObjectRoot = (!baseonly ? NifOgre::Loader::createObjects(mInsert, mdlname) :
                               NifOgre::Loader::createObjectBase(mInsert, mdlname));
    if(mObjectRoot->mSkelBase)
    {
        mSkelBase = mObjectRoot->mSkelBase;

        Ogre::AnimationStateSet *aset = mObjectRoot->mSkelBase->getAllAnimationStates();
        Ogre::AnimationStateIterator asiter = aset->getAnimationStateIterator();
        while(asiter.hasMoreElements())
        {
            Ogre::AnimationState *state = asiter.getNext();
            state->setEnabled(false);
            state->setLoop(false);
        }

        // Set the bones as manually controlled since we're applying the
        // transformations manually
        Ogre::SkeletonInstance *skelinst = mObjectRoot->mSkelBase->getSkeleton();
        Ogre::Skeleton::BoneIterator boneiter = skelinst->getBoneIterator();
        while(boneiter.hasMoreElements())
            boneiter.getNext()->setManuallyControlled(true);

        // Reattach any objects that have been attached to this one
        ObjectAttachMap::iterator iter = mAttachedObjects.begin();
        while(iter != mAttachedObjects.end())
        {
            if(!skelinst->hasBone(iter->second))
                mAttachedObjects.erase(iter++);
            else
            {
                mSkelBase->attachObjectToBone(iter->second, iter->first);
                ++iter;
            }
        }
    }
    else
        mAttachedObjects.clear();

    for(size_t i = 0;i < mObjectRoot->mControllers.size();i++)
    {
        if(mObjectRoot->mControllers[i].getSource().isNull())
            mObjectRoot->mControllers[i].setSource(mAnimationTimePtr[0]);
    }
}