void CActor::g_SetAnimation( u32 mstate_rl )
{


	if (!g_Alive()) {
		if (m_current_legs||m_current_torso){
			SActorState*				ST = 0;
			if (mstate_rl&mcCrouch)		ST = &m_anims->m_crouch;
			else						ST = &m_anims->m_normal;
			mstate_real					= 0;
			m_current_legs.invalidate	();
			m_current_torso.invalidate	();

			//smart_cast<IKinematicsAnimated*>(Visual())->PlayCycle(m_anims->m_dead_stop);
		}

		return;
	}
	STorsoWpn::eMovingState	moving_idx 		= STorsoWpn::eIdle;
	SActorState*					ST 		= 0;
	SAnimState*						AS 		= 0;
	
	if		(mstate_rl&mcCrouch)	
		ST 		= &m_anims->m_crouch;
	else if	(mstate_rl&mcClimb)		
		ST 		= &m_anims->m_climb;
	else							
		ST 		= &m_anims->m_normal;

	bool bAccelerated = isActorAccelerated(mstate_rl, IsZoomAimingMode());
	if ( bAccelerated )
	{
		AS							= &ST->m_run;
	}else{
		AS							= &ST->m_walk;
	}
	if(mstate_rl&mcAnyMove)
	{
		if( bAccelerated )
			moving_idx				= STorsoWpn::eRun;
		else
			moving_idx				= STorsoWpn::eWalk;
	}
	// анимации
	MotionID 						M_legs;
	MotionID 						M_torso;
	MotionID 						M_head;

	//если мы просто стоим на месте
	bool is_standing = false;

	// Legs
	if		(mstate_rl&mcLanding)	M_legs	= ST->landing[0];
	else if (mstate_rl&mcLanding2)	M_legs	= ST->landing[1];
	else if ((mstate_rl&mcTurn)&&
			!(mstate_rl&mcClimb))	M_legs	= ST->legs_turn;
	else if (mstate_rl&mcFall)		M_legs	= ST->jump_idle;
	else if (mstate_rl&mcJump)		M_legs	= ST->jump_begin;
	else if (mstate_rl&mcFwd)		M_legs	= AS->legs_fwd;
	else if (mstate_rl&mcBack)		M_legs	= AS->legs_back;
	else if (mstate_rl&mcLStrafe)	M_legs	= AS->legs_ls;
	else if (mstate_rl&mcRStrafe)	M_legs	= AS->legs_rs;
	else is_standing = true;

	if(mstate_rl&mcSprint)
	{
		g_SetSprintAnimation			(mstate_rl,M_head,M_torso,M_legs);
		moving_idx						= STorsoWpn::eSprint;
	}

	if (this == Level().CurrentViewEntity())
	{	
		if ((mstate_rl&mcSprint) != (mstate_old&mcSprint))
		{
			g_player_hud->OnMovementChanged(mcSprint);
		}else
		if ((mstate_rl&mcAnyMove) != (mstate_old&mcAnyMove))
		{
			g_player_hud->OnMovementChanged(mcAnyMove);
		}
	};

	//-----------------------------------------------------------------------
	// Torso
	if(mstate_rl&mcClimb)
	{
		if		(mstate_rl&mcFwd)		M_torso	= AS->legs_fwd;
		else if (mstate_rl&mcBack)		M_torso	= AS->legs_back;
		else if (mstate_rl&mcLStrafe)	M_torso	= AS->legs_ls;
		else if (mstate_rl&mcRStrafe)	M_torso	= AS->legs_rs;
	}
	
	if(!M_torso)
	{
		CInventoryItem* _i = inventory().ActiveItem();
		CHudItem		*H = smart_cast<CHudItem*>(_i);
		CWeapon			*W = smart_cast<CWeapon*>(_i);
		CMissile		*M = smart_cast<CMissile*>(_i);
		CArtefact		*A = smart_cast<CArtefact*>(_i);
					
		if (H) {
			VERIFY(H->animation_slot() <= _total_anim_slots_);
			STorsoWpn* TW			= &ST->m_torso[H->animation_slot() - 1];
			if (!b_DropActivated&&!fis_zero(f_DropPower))
			{
				M_torso					= TW->drop;
				if (!M_torso)	
				{
					Msg("! drop animation for %s", *(H->object().cName()));
					M_torso = ST->m_torso_idle;
				};
				m_bAnimTorsoPlayed		= TRUE;
			}
			else
			{
				if (!m_bAnimTorsoPlayed) 
				{
					if (W) 
					{
						bool K	=inventory().GetActiveSlot() == KNIFE_SLOT;
						bool R3 = W->IsTriStateReload();
						
						if(K)
						{
							switch (W->GetState())
							{
							case CWeapon::eIdle:		M_torso	= TW->moving[moving_idx];		break;
							
							case CWeapon::eFire:	
								if(is_standing)
														M_torso = M_legs = M_head = TW->all_attack_0;
								else
														M_torso	= TW->attack_zoom;
								break;

							case CWeapon::eFire2:
								if(is_standing)
														M_torso = M_legs = M_head = TW->all_attack_1;
								else
														M_torso	= TW->fire_idle;
								break;

							case CWeapon::eReload:		M_torso	= TW->reload;					break;
							case CWeapon::eShowing:		M_torso	= TW->draw;						break;
							case CWeapon::eHiding:		M_torso	= TW->holster;					break;
							default				 :  	M_torso	= TW->moving[moving_idx];		break;
							}
						}
						else
						{
							switch (W->GetState())
							{
							case CWeapon::eIdle:		M_torso	= W->IsZoomed()?TW->zoom:TW->moving[moving_idx];	break;
							case CWeapon::eFire:		M_torso	= W->IsZoomed()?TW->attack_zoom:TW->attack;				break;
							case CWeapon::eFire2:		M_torso	= W->IsZoomed()?TW->attack_zoom:TW->attack;				break;
							case CWeapon::eReload:	
								if(!R3)
									M_torso	= TW->reload;
								else
								{
									CWeapon::EWeaponSubStates sub_st = W->GetReloadState();
									switch (sub_st)
									{
										case CWeapon::eSubstateReloadBegin:			M_torso	= TW->reload;	break;
										case CWeapon::eSubstateReloadInProcess:		M_torso	= TW->reload_1; break;
										case CWeapon::eSubstateReloadEnd:			M_torso	= TW->reload_2; break;
										default:									M_torso	= TW->reload;	break;
									}
								}break;

							case CWeapon::eShowing:	M_torso	= TW->draw;					break;
							case CWeapon::eHiding:	M_torso	= TW->holster;				break;
							default				 :  M_torso	= TW->moving[moving_idx];	break;
							}
						}
					}
					else if (M) 
					{
						if(is_standing)
						{
							switch (M->GetState())
							{
							case CMissile::eShowing		:		M_torso	= TW->draw;			break;
							case CMissile::eHiding		:		M_torso	= TW->holster;		break;
							case CMissile::eIdle		:		M_torso	= TW->moving[moving_idx];		break;
							case CMissile::eThrowStart	:		M_torso = M_legs = M_head = TW->all_attack_0;	break;
							case CMissile::eReady		:		M_torso = M_legs = M_head = TW->all_attack_1;	break;
							case CMissile::eThrow		:		M_torso = M_legs = M_head = TW->all_attack_2;	break;
							case CMissile::eThrowEnd	:		M_torso = M_legs = M_head = TW->all_attack_2;	break;
							default						:		M_torso	= TW->draw;			break; 
							}
						}
						else
						{
							switch (M->GetState())
							{
							case CMissile::eShowing		:		M_torso	= TW->draw;						break;
							case CMissile::eHiding		:		M_torso	= TW->holster;					break;
							case CMissile::eIdle		:		M_torso	= TW->moving[moving_idx];		break;
							case CMissile::eThrowStart	:		M_torso	= TW->attack_zoom;				break;
							case CMissile::eReady		:		M_torso	= TW->fire_idle;				break;
							case CMissile::eThrow		:		M_torso	= TW->fire_end;					break;
							case CMissile::eThrowEnd	:		M_torso	= TW->fire_end;					break;
							default						:		M_torso	= TW->draw;						break; 
							}
						}
					}
					else if (A)
					{
							switch(A->GetState())
							{
								case CArtefact::eIdle		: M_torso	= TW->moving[moving_idx];	break; 
								case CArtefact::eShowing	: M_torso	= TW->draw;					break; 
								case CArtefact::eHiding		: M_torso	= TW->holster;				break; 
								case CArtefact::eActivating : M_torso	= TW->zoom;					break; 
								default						: M_torso	= TW->moving[moving_idx];
							}
					
					}
				}
			}
		}
	}
	MotionID		mid = smart_cast<IKinematicsAnimated*>(Visual())->ID_Cycle("norm_idle_0");

	if (!M_legs)
	{
		if((mstate_rl&mcCrouch)&&!isActorAccelerated(mstate_rl, IsZoomAimingMode()))//!(mstate_rl&mcAccel))
		{
			M_legs=smart_cast<IKinematicsAnimated*>(Visual())->ID_Cycle("cr_idle_1");
		}
		else 
			M_legs	= ST->legs_idle;
	}
	if (!M_head)					
		M_head	= ST->m_head_idle;

	if (!M_torso)
	{
		if (m_bAnimTorsoPlayed)		
			M_torso	= m_current_torso;
		else						
			M_torso = ST->m_torso_idle;
	}
	
	// есть анимация для всего - запустим / иначе запустим анимацию по частям
	if (m_current_torso!=M_torso)
	{
		if (m_bAnimTorsoPlayed)		
			m_current_torso_blend = smart_cast<IKinematicsAnimated*>(Visual())->PlayCycle(M_torso,TRUE,AnimTorsoPlayCallBack,this);
		else						
			m_current_torso_blend = smart_cast<IKinematicsAnimated*>(Visual())->PlayCycle(M_torso);

		m_current_torso=M_torso;
	}
	
	if(m_current_head!=M_head)
	{
		if(M_head)
			smart_cast<IKinematicsAnimated*>(Visual())->PlayCycle(M_head);

		m_current_head=M_head;
	}

	if (m_current_legs!=M_legs)
	{
		float pos					= 0.f;
		VERIFY						(!m_current_legs_blend || !fis_zero(m_current_legs_blend->timeTotal));
		if ((mstate_real&mcAnyMove)&&(mstate_old&mcAnyMove)&&m_current_legs_blend)
			pos						= fmod(m_current_legs_blend->timeCurrent,m_current_legs_blend->timeTotal)/m_current_legs_blend->timeTotal;


		IKinematicsAnimated* ka		= smart_cast<IKinematicsAnimated*>(Visual());
		m_current_legs_blend		= PlayMotionByParts(ka, M_legs, TRUE, legs_play_callback, this);
//		m_current_legs_blend		= smart_cast<IKinematicsAnimated*>(Visual())->PlayCycle(M_legs,TRUE,legs_play_callback,this);


		if ((!(mstate_old&mcAnyMove))&&(mstate_real&mcAnyMove))
		{
			pos						= 0.5f;//0.5f*Random.randI(2);
		}
		if (m_current_legs_blend)
			m_current_legs_blend->timeCurrent = m_current_legs_blend->timeTotal*pos;

		m_current_legs				= M_legs;

		CStepManager::on_animation_start(M_legs, m_current_legs_blend);
	}



#ifdef DEBUG
	if(bDebug && g_ShowAnimationInfo)
	{
		UI().Font().pFontStat->OutSetI	(0,0);
		UI().Font().pFontStat->OutNext("[%s]",mov_state[moving_idx]);
		IKinematicsAnimated* KA = smart_cast<IKinematicsAnimated*>(Visual());
		if(M_torso)
			UI().Font().pFontStat->OutNext("torso [%s]",KA->LL_MotionDefName_dbg(M_torso).first);
		if(M_head)
			UI().Font().pFontStat->OutNext("head [%s]",KA->LL_MotionDefName_dbg(M_head).first);
		if(M_legs)
			UI().Font().pFontStat->OutNext("legs [%s]",KA->LL_MotionDefName_dbg(M_legs).first);
	}
#endif

#ifdef DEBUG
	if ((Level().CurrentControlEntity() == this) && g_ShowAnimationInfo) {
		string128 buf;
		xr_strcpy(buf,"");
		if (isActorAccelerated(mstate_rl, IsZoomAimingMode()))		xr_strcat(buf,"Accel ");
		if (mstate_rl&mcCrouch)		xr_strcat(buf,"Crouch ");
		if (mstate_rl&mcFwd)		xr_strcat(buf,"Fwd ");
		if (mstate_rl&mcBack)		xr_strcat(buf,"Back ");
		if (mstate_rl&mcLStrafe)	xr_strcat(buf,"LStrafe ");
		if (mstate_rl&mcRStrafe)	xr_strcat(buf,"RStrafe ");
		if (mstate_rl&mcJump)		xr_strcat(buf,"Jump ");
		if (mstate_rl&mcFall)		xr_strcat(buf,"Fall ");
		if (mstate_rl&mcTurn)		xr_strcat(buf,"Turn ");
		if (mstate_rl&mcLanding)	xr_strcat(buf,"Landing ");
		if (mstate_rl&mcLLookout)	xr_strcat(buf,"LLookout ");
		if (mstate_rl&mcRLookout)	xr_strcat(buf,"RLookout ");
		if (m_bJumpKeyPressed)		xr_strcat(buf,"+Jumping ");
		UI().Font().pFontStat->OutNext	("MSTATE:     [%s]",buf);
/*
		switch (m_PhysicMovementControl->Environment())
		{
		case CPHMovementControl::peOnGround:	xr_strcpy(buf,"ground");			break;
		case CPHMovementControl::peInAir:		xr_strcpy(buf,"air");				break;
		case CPHMovementControl::peAtWall:		xr_strcpy(buf,"wall");				break;
		}
		UI().Font().pFontStat->OutNext	(buf);
		UI().Font().pFontStat->OutNext	("Accel     [%3.2f, %3.2f, %3.2f]",VPUSH(NET_SavedAccel));
		UI().Font().pFontStat->OutNext	("V         [%3.2f, %3.2f, %3.2f]",VPUSH(m_PhysicMovementControl->GetVelocity()));
		UI().Font().pFontStat->OutNext	("vertex ID   %d",ai_location().level_vertex_id());
		
		Game().m_WeaponUsageStatistic->Draw();
		*/
	};
#endif

	if (!m_current_torso_blend)
		return;

	IKinematicsAnimated		*skeleton_animated = smart_cast<IKinematicsAnimated*>(Visual());

	CMotionDef				*motion0 = skeleton_animated->LL_GetMotionDef(m_current_torso);
	VERIFY					(motion0);
	if (!(motion0->flags & esmSyncPart))
		return;

	if (!m_current_legs_blend)
		return;

	CMotionDef				*motion1 = skeleton_animated->LL_GetMotionDef(m_current_legs);
	VERIFY					(motion1);
	if (!(motion1->flags & esmSyncPart))
		return;


	m_current_torso_blend->timeCurrent	= m_current_legs_blend->timeCurrent/m_current_legs_blend->timeTotal*m_current_torso_blend->timeTotal;
}
Beispiel #2
0
void CActor::OnEvent(NET_Packet& P, u16 type)
{
	inherited::OnEvent			(P,type);
	CInventoryOwner::OnEvent	(P,type);

	u16 id;
	switch (type)
	{
	case GE_TRADE_BUY:
	case GE_OWNERSHIP_TAKE:
		{
			P.r_u16					(id);
			CObject* Obj			= Level().Objects.net_Find	(id);

//			R_ASSERT2( Obj, make_string("GE_OWNERSHIP_TAKE: Object not found. object_id = [%d]", id).c_str() );
			VERIFY2  ( Obj, make_string("GE_OWNERSHIP_TAKE: Object not found. object_id = [%d]", id).c_str() );
			if ( !Obj ) {
				Msg                 ( "! GE_OWNERSHIP_TAKE: Object not found. object_id = [%d]", id );
				break;
			}
		
			CGameObject* _GO		= smart_cast<CGameObject*>(Obj);
			if (!IsGameTypeSingle() && !g_Alive())
			{
				Msg("! WARNING: dead player [%d][%s] can't take items [%d][%s]",
					ID(), Name(), _GO->ID(), _GO->cNameSect().c_str());
				break;
			}
			
			if( inventory().CanTakeItem(smart_cast<CInventoryItem*>(_GO)) )
			{
				Obj->H_SetParent		(smart_cast<CObject*>(this));
				
#ifdef MP_LOGGING
				string64 act;
				xr_strcpy( act, (type == GE_TRADE_BUY)? "buys" : "takes" );
				Msg("--- Actor [%d][%s]  %s  [%d][%s]", ID(), Name(), act, _GO->ID(), _GO->cNameSect().c_str());
#endif // MP_LOGGING
				
				inventory().Take	(_GO, false, true);
			
				SelectBestWeapon(Obj);
			}
			else
			{
				if (IsGameTypeSingle())
				{
					NET_Packet		P;
					u_EventGen		(P,GE_OWNERSHIP_REJECT,ID());
					P.w_u16			(u16(Obj->ID()));
					u_EventSend		(P);
				} else
				{
					Msg("! ERROR: Actor [%d][%s]  tries to drop on take [%d][%s]", ID(), Name(), _GO->ID(), _GO->cNameSect().c_str());
				}
			}
		}
		break;
	case GE_TRADE_SELL:
	case GE_OWNERSHIP_REJECT:
		{
			P.r_u16							(id);
			CObject* Obj					= Level().Objects.net_Find	(id);

//			R_ASSERT2( Obj, make_string("GE_OWNERSHIP_REJECT: Object not found, id = %d", id).c_str() );
			VERIFY2  ( Obj, make_string("GE_OWNERSHIP_REJECT: Object not found, id = %d", id).c_str() );
			if ( !Obj ) {
				Msg                 ( "! GE_OWNERSHIP_REJECT: Object not found, id = %d", id );
				break;
			}

			bool just_before_destroy		= !P.r_eof() && P.r_u8();
			bool dont_create_shell			= (type==GE_TRADE_SELL) || just_before_destroy;
			Obj->SetTmpPreDestroy			(just_before_destroy);
			
			CGameObject * GO = smart_cast<CGameObject*>(Obj);
			
#ifdef MP_LOGGING
			string64 act;
			xr_strcpy( act, (type == GE_TRADE_SELL)? "sells" : "rejects" );
			Msg("--- Actor [%d][%s]  %s  [%d][%s]", ID(), Name(), act, GO->ID(), GO->cNameSect().c_str());
#endif // MP_LOGGING
			
			VERIFY( GO->H_Parent() );
			if ( !GO->H_Parent() )
			{
				Msg("! ERROR: Actor [%d][%s] tries to reject item [%d][%s] that has no parent", 
					ID(), Name(), GO->ID(), GO->cNameSect().c_str());
				break;
			}
			
			VERIFY2( GO->H_Parent()->ID() == ID(), 
				make_string("actor [%d][%s] tries to drop not own object [%d][%s]",
					ID(), Name(), GO->ID(), GO->cNameSect().c_str() ).c_str() );

			if ( GO->H_Parent()->ID() != ID() )
			{
				CActor* real_parent = smart_cast<CActor*>(GO->H_Parent());
				Msg("! ERROR: Actor [%d][%s] tries to drop not own item [%d][%s], his parent is [%d][%s]",
					ID(), Name(), GO->ID(), GO->cNameSect().c_str(), real_parent->ID(), real_parent->Name());
				break;
			}

			if (!Obj->getDestroy() && inventory().DropItem(GO, just_before_destroy, dont_create_shell)) 
			{
				//O->H_SetParent(0,just_before_destroy);//moved to DropItem
				//feel_touch_deny(O,2000);
				Level().m_feel_deny.feel_touch_deny(Obj, 1000);

				// [12.11.07] Alexander Maniluk: extended GE_OWNERSHIP_REJECT packet for drop item to selected position
				Fvector dropPosition;
				if (!P.r_eof())
				{
					P.r_vec3(dropPosition);
					GO->MoveTo(dropPosition);
					//Other variant :)
					/*NET_Packet MovePacket;
					MovePacket.w_begin(M_MOVE_ARTEFACTS);
					MovePacket.w_u8(1);
					MovePacket.w_u16(id);
					MovePacket.w_vec3(dropPosition);
					u_EventSend(MovePacket);*/
				}
			}

			if (!just_before_destroy)
				SelectBestWeapon(Obj);

		}
		break;
	case GE_INV_ACTION:
		{
			u16 cmd;
			P.r_u16		(cmd);
			u32 flags;
			P.r_u32		(flags);
			s32 ZoomRndSeed = P.r_s32();
			s32 ShotRndSeed = P.r_s32();
			if (!IsGameTypeSingle() && !g_Alive())
			{
//				Msg("! WARNING: dead player tries to rize inventory action");
				break;
			}
									
			if (flags & CMD_START)
			{
				if (cmd == kWPN_ZOOM)
					SetZoomRndSeed(ZoomRndSeed);
				if (cmd == kWPN_FIRE)
					SetShotRndSeed(ShotRndSeed);
				IR_OnKeyboardPress(cmd);
			}
			else
				IR_OnKeyboardRelease(cmd);
		}
		break;
	case GEG_PLAYER_ITEM2SLOT:
	case GEG_PLAYER_ITEM2BELT:
	case GEG_PLAYER_ITEM2RUCK:
	case GEG_PLAYER_ITEM_EAT:
	case GEG_PLAYER_ACTIVATEARTEFACT:
{
			P.r_u16		(id);
			CObject* Obj	= Level().Objects.net_Find	(id);

//			R_ASSERT2( Obj, make_string("GEG_PLAYER_ITEM_EAT(use): Object not found. object_id = [%d]", id).c_str() );
			VERIFY2  ( Obj, make_string("GEG_PLAYER_ITEM_EAT(use): Object not found. object_id = [%d]", id).c_str() );
			if ( !Obj ) {
//				Msg                 ( "! GEG_PLAYER_ITEM_EAT(use): Object not found. object_id = [%d]", id );
				break;
			}

//			R_ASSERT2( !Obj->getDestroy(), make_string("GEG_PLAYER_ITEM_EAT(use): Object is destroying. object_id = [%d]", id).c_str() );
			VERIFY2  ( !Obj->getDestroy(), make_string("GEG_PLAYER_ITEM_EAT(use): Object is destroying. object_id = [%d]", id).c_str() );
			if ( Obj->getDestroy() ) {
//				Msg                                ( "! GEG_PLAYER_ITEM_EAT(use): Object is destroying. object_id = [%d]", id );
				break;
			}

			if (!IsGameTypeSingle() && !g_Alive())
			{
				Msg("! WARNING: dead player [%d][%s] can't use items [%d][%s]",
					ID(), Name(), Obj->ID(), Obj->cNameSect().c_str());
				break;
			}

			if ( type == GEG_PLAYER_ACTIVATEARTEFACT )
			{
				CArtefact* pArtefact = smart_cast<CArtefact*>(Obj);
	//			R_ASSERT2( pArtefact, make_string("GEG_PLAYER_ACTIVATEARTEFACT: Artefact not found. artefact_id = [%d]", id).c_str() );
				VERIFY2  ( pArtefact, make_string("GEG_PLAYER_ACTIVATEARTEFACT: Artefact not found. artefact_id = [%d]", id).c_str() );
				if ( !pArtefact ) {
					Msg                       ( "! GEG_PLAYER_ACTIVATEARTEFACT: Artefact not found. artefact_id = [%d]", id );
					break;//1
				}
				
				pArtefact->ActivateArtefact	();
				break;//1
			}
			
			PIItem iitem = smart_cast<CInventoryItem*>(Obj);
			R_ASSERT( iitem );

			switch (type)
			{
			case GEG_PLAYER_ITEM2SLOT:
			{
				u16 slot_id = P.r_u16();
				inventory().Slot(slot_id, iitem ); 
			}break;//2
			case GEG_PLAYER_ITEM2BELT:	 
				inventory().Belt( iitem ); 
				break;//2
			case GEG_PLAYER_ITEM2RUCK:	 
				inventory().Ruck( iitem ); 
				break;//2
			case GEG_PLAYER_ITEM_EAT:	 
				inventory().Eat( iitem ); 
				break;//2
			}//switch

		}break;//1
	case GEG_PLAYER_ACTIVATE_SLOT:
		{
			u16							slot_id;
			P.r_u16						(slot_id);

			inventory().Activate		(slot_id);
								  
		}break;

	case GEG_PLAYER_DISABLE_SPRINT:
		{
			s8 cmd				= P.r_s8();
			m_block_sprint_counter = m_block_sprint_counter+cmd;
			Msg("m_block_sprint_counter=%d",m_block_sprint_counter);
			if(m_block_sprint_counter>0)
			{
				mstate_wishful	&=~mcSprint;
			}
		}break;

	case GEG_PLAYER_WEAPON_HIDE_STATE:
		{
			u16 State		= P.r_u16();
			BOOL	Set		= !!P.r_u8();
			inventory().SetSlotsBlocked	(State, !!Set);
		}break;
	case GE_MOVE_ACTOR:
		{
			Fvector NewPos, NewRot;
			P.r_vec3(NewPos);
			P.r_vec3(NewRot);
			
			MoveActor(NewPos, NewRot);
		}break;
	case GE_ACTOR_MAX_POWER:
		{
			conditions().MaxPower();
			conditions().ClearWounds();
			ClearBloodWounds();
		}break;
	case GE_ACTOR_MAX_HEALTH:
		{
			SetfHealth(GetMaxHealth());
		}break;
	case GEG_PLAYER_ATTACH_HOLDER:
		{
			u16 id = P.r_u16();
			CObject* O	= Level().Objects.net_Find	(id);
			if (!O){
				Msg("! Error: No object to attach holder [%d]", id);
				break;
			}
			VERIFY(m_holder==NULL);
			CHolderCustom*	holder = smart_cast<CHolderCustom*>(O);
			if(!holder->Engaged())	use_Holder		(holder);

		}break;
	case GEG_PLAYER_DETACH_HOLDER:
		{
			if			(!m_holder)	break;
			u16 id			= P.r_u16();
			CGameObject*	GO	= smart_cast<CGameObject*>(m_holder);
			VERIFY			(id==GO->ID());
			use_Holder		(NULL);
		}break;
	case GEG_PLAYER_PLAY_HEADSHOT_PARTICLE:
		{
			OnPlayHeadShotParticle(P);
		}break;
	case GE_ACTOR_JUMPING:
		{
			/*
			Fvector dir;
			P.r_dir(dir);
			float jump = P.r_float();
			NET_SavedAccel = dir;
			extern float NET_Jump;
			NET_Jump = jump;
			m_bInInterpolation = false;
			mstate_real |= mcJump;
			*/
		}break;
	}
}
bool CAI_Stalker::bfAssignObject(CScriptEntityAction *tpEntityAction)
{
	CScriptObjectAction	&l_tObjectAction	= tpEntityAction->m_tObjectAction;
	CInventoryItem	*l_tpInventoryItem	= smart_cast<CInventoryItem*>(l_tObjectAction.m_tpObject);

	if (!inherited::bfAssignObject(tpEntityAction) || !l_tObjectAction.m_tpObject || !l_tpInventoryItem) {
		if (!inventory().ActiveItem()) {
			CObjectHandler::set_goal	(eObjectActionIdle);
		}
		else {
			CObjectHandler::set_goal	(eObjectActionIdle,inventory().ActiveItem());
		}

		return	((l_tObjectAction.m_bCompleted = (CObjectHandler::goal_reached())) == false);
	}

	if (!l_tpInventoryItem->object().H_Parent())
		return			(true);

	CWeapon				*l_tpWeapon				= smart_cast<CWeapon*>(inventory().ActiveItem());
	CWeaponMagazined	*l_tpWeaponMagazined	= smart_cast<CWeaponMagazined*>(inventory().ActiveItem());

	if (l_tpWeaponMagazined)
		l_tpWeaponMagazined->SetQueueSize		(l_tObjectAction.m_dwQueueSize);

	switch (l_tObjectAction.m_tGoalType) {
		case eObjectActionIdle : {
			if (!l_tpWeapon)
				return	((l_tObjectAction.m_bCompleted = true) == false);
			CObjectHandler::set_goal	(eObjectActionIdle,l_tpInventoryItem);
//			inventory().Action	(kWPN_FIRE,	CMD_STOP);
			return	((l_tObjectAction.m_bCompleted = (CObjectHandler::goal_reached())) == false);
			break;
		}
		case eObjectActionFire1 : {
			CObjectHandler::set_goal	(eObjectActionFire1,l_tpInventoryItem);
//			if (!l_tpWeapon)
//				return	((l_tObjectAction.m_bCompleted = true) == false);
			if (inventory().ActiveItem() && l_tpWeapon) {
				if (l_tpWeapon->GetAmmoElapsed()) {
//					if (l_tpWeapon->GetAmmoMagSize() > 1)
//						l_tpWeaponMagazined->SetQueueSize(l_tObjectAction.m_dwQueueSize);
//					else
//						l_tpWeaponMagazined->SetQueueSize(1);
//					inventory().Action(kWPN_FIRE,	CMD_START);
				}
				else {
//					inventory().Action(kWPN_FIRE,	CMD_STOP);
					if (l_tpWeapon->GetSuitableAmmoTotal()) {
//						CObjectHandler::set_goal	(eObjectActionFire1,l_tObjectAction.m_tpObject);
//						inventory().Action(kWPN_RELOAD, CMD_START);
					}
					else
						l_tObjectAction.m_bCompleted = true;
				}
			}
			break;
		}
		case eObjectActionFire2 : {
			CObjectHandler::set_goal	(eObjectActionFire2,l_tpInventoryItem);
//			if (!l_tpWeapon)
//				return	((l_tObjectAction.m_bCompleted = true) == false);
			if (inventory().ActiveItem()) {
				if (l_tpWeapon->GetAmmoElapsed()) {
//					if (l_tpWeapon->GetAmmoMagSize() > 1)
//						l_tpWeaponMagazined->SetQueueSize(l_tObjectAction.m_dwQueueSize);
//					else
//						l_tpWeaponMagazined->SetQueueSize(1);
//					inventory().Action(kWPN_FIRE,	CMD_START);
				}
				else {
//					inventory().Action(kWPN_FIRE,	CMD_STOP);
					if (l_tpWeapon->GetSuitableAmmoTotal()) {
//						CObjectHandler::set_goal	(eObjectActionFire1,l_tObjectAction.m_tpObject);
//						inventory().Action(kWPN_RELOAD, CMD_START);
					}
					else
						l_tObjectAction.m_bCompleted = true;
				}
			}
			break;
		}
		case eObjectActionReload2 :
		case eObjectActionReload1 : {
			if (!l_tpWeapon)
				return	((l_tObjectAction.m_bCompleted = true) == false);
			CObjectHandler::set_goal	(eObjectActionReload1,l_tpInventoryItem);
			if (inventory().ActiveItem()->object().ID() == l_tObjectAction.m_tpObject->ID()) {
//				inventory().Action(kWPN_FIRE,	CMD_STOP);
				if (CWeapon::eReload != l_tpWeapon->GetState()) {
//					inventory().Action(kWPN_RELOAD,	CMD_START);
				}
				else
					l_tObjectAction.m_bCompleted = true;
			}
			else
				ai().script_engine().script_log(ScriptStorage::eLuaMessageTypeError,"cannot reload active item because it is not selected!");

//			if (inventory().ActiveItem()) {
//				inventory().Action(kWPN_FIRE,	CMD_STOP);
//				if (CWeapon::eReload != l_tpWeapon->STATE)
//					inventory().Action(kWPN_RELOAD,	CMD_START);
//				else
//					l_tObjectAction.m_bCompleted = true;
//			}
//			else
//				ai().script_engine().script_log(ScriptStorage::eLuaMessageTypeError,"cannot reload active item because it is not selected!");
			break;
		}
		case eObjectActionActivate : {
			CTorch			*torch = smart_cast<CTorch*>(l_tObjectAction.m_tpObject);
			if (torch) {
				torch->Switch(true);
				break;
			}
			CObjectHandler::set_goal	(eObjectActionIdle,l_tpInventoryItem);
//				inventory().Slot(l_tpInventoryItem);
//				inventory().Activate(l_tpInventoryItem->GetSlot());
//			if (inventory().ActiveItem() && (inventory().ActiveItem()->ID() == l_tpInventoryItem->ID()))
//				if (l_tpWeapon && (CWeapon::eIdle == l_tpWeapon->STATE))
//				l_tObjectAction.m_bCompleted = true;
			return	((l_tObjectAction.m_bCompleted = (CObjectHandler::goal_reached())) == false);

			break;
		}
		case eObjectActionDeactivate : {
			CTorch			*torch = smart_cast<CTorch*>(l_tObjectAction.m_tpObject);
			if (torch) {
				torch->Switch(false);
				break;
			}
//				inventory().Activate(u32(-1));
			CObjectHandler::set_goal	(eObjectActionIdle);
			return	((l_tObjectAction.m_bCompleted = (CObjectHandler::goal_reached())) == false);
			break;
		}
		case eObjectActionUse : {
			CObjectHandler::set_goal	(eObjectActionUse);
			return	((l_tObjectAction.m_bCompleted = (CObjectHandler::goal_reached())) == false);
			break;
		}
		case eObjectActionTake : {
			if (inventory().GetItemFromInventory(*l_tObjectAction.m_tpObject->cName())) {
				ai().script_engine().script_log(ScriptStorage::eLuaMessageTypeError,"item is already in the inventory!");
				return	((l_tObjectAction.m_bCompleted = true) == false);
			}
			feel_touch_new(l_tObjectAction.m_tpObject);
			l_tObjectAction.m_bCompleted = true;
			break;
		}
		case eObjectActionDrop : {
			if (!inventory().GetItemFromInventory(*l_tObjectAction.m_tpObject->cName())) {
				ai().script_engine().script_log(ScriptStorage::eLuaMessageTypeError,"item is not in the inventory!");
				return	((l_tObjectAction.m_bCompleted = true) == false);
			}
			DropItemSendMessage(l_tObjectAction.m_tpObject);
			break;
		}
		default : NODEFAULT;
	}

	return	(true);
}
CWeapon	*CAI_Stalker::GetCurrentWeapon() const
{
	return			(smart_cast<CWeapon*>(inventory().ActiveItem()));
}
Beispiel #5
0
CInventoryItem* CInventoryOwner::GetCurrentOutfit() const
{
    return inventory().m_slots[OUTFIT_SLOT].m_pIItem;
}
Beispiel #6
0
void CActor::IR_OnKeyboardPress(int cmd)
{
	if (m_blocked_actions.find((EGameActions)cmd) != m_blocked_actions.end() ) return; // Real Wolf. 14.10.2014

	if (Remote())		return;

//	if (conditions().IsSleeping())	return;
	if (IsTalking())	return;
	if (m_input_external_handler && !m_input_external_handler->authorized(cmd))	return;
	
	switch (cmd)
	{
	case kWPN_FIRE:
		{
			mstate_wishful &=~mcSprint;
			//-----------------------------
			if (OnServer())
			{
				NET_Packet P;
				P.w_begin(M_PLAYER_FIRE); 
				P.w_u16(ID());
				u_EventSend(P);
			}
		}break;
	default:
		{
		}break;
	}

	if (!g_Alive()) return;

	if(m_holder && kUSE != cmd)
	{
		m_holder->OnKeyboardPress			(cmd);
		if(m_holder->allowWeapon() && inventory().Action(cmd, CMD_START))		return;
		return;
	}else
		if(inventory().Action(cmd, CMD_START))					return;

	switch(cmd){
	case kJUMP:		
		{
			mstate_wishful |= mcJump;
			{
//				NET_Packet	P;
//				u_EventGen(P, GE_ACTOR_JUMPING, ID());
//				u_EventSend(P);
			}
		}break;
	case kCROUCH_TOGGLE:
		{
			g_bAutoClearCrouch = !g_bAutoClearCrouch;
			if (!g_bAutoClearCrouch)
				mstate_wishful |= mcCrouch;

		}break;
	case kSPRINT_TOGGLE:	
		{
			if (mstate_wishful & mcSprint)
				mstate_wishful &=~mcSprint;
			else
				mstate_wishful |= mcSprint;					
		}break;
	case kCAM_1:	cam_Set			(eacFirstEye);				break;
	case kCAM_2:	cam_Set			(eacLookAt);				break;
	case kCAM_3:	cam_Set			(eacFreeLook);				break;
	case kNIGHT_VISION:
		{
			const xr_vector<CAttachableItem*>& all = CAttachmentOwner::attached_objects();
			xr_vector<CAttachableItem*>::const_iterator it = all.begin();
			xr_vector<CAttachableItem*>::const_iterator it_e = all.end();
			for(;it!=it_e;++it){
				CTorch* torch = smart_cast<CTorch*>(*it);
				if (torch){		
					torch->SwitchNightVision();
					break;
				}
			}
		}break;
	case kTORCH:{ 
		const xr_vector<CAttachableItem*>& all = CAttachmentOwner::attached_objects();
		xr_vector<CAttachableItem*>::const_iterator it = all.begin();
		xr_vector<CAttachableItem*>::const_iterator it_e = all.end();
		for(;it!=it_e;++it){
				CTorch* torch = smart_cast<CTorch*>(*it);
				if (torch){		
					torch->Switch();
					break;
				}
		}
		}break;
	case kWPN_1:	
	case kWPN_2:	
	case kWPN_3:	
	case kWPN_4:	
	case kWPN_5:	
	case kWPN_6:	
	case kWPN_RELOAD:
		//Weapons->ActivateWeaponID	(cmd-kWPN_1);			
		break;
	case kUSE:
		ActorUse();
		break;
	case kDROP:
		b_DropActivated			= TRUE;
		f_DropPower				= 0;
		break;
	case kNEXT_SLOT:
		{
			OnNextWeaponSlot();
		}break;
	case kPREV_SLOT:
		{
			OnPrevWeaponSlot();
		}break;

	case kUSE_BANDAGE:
	case kUSE_MEDKIT:
		{
			if(IsGameTypeSingle())
			{
				PIItem itm = inventory().item((cmd==kUSE_BANDAGE)?  CLSID_IITEM_BANDAGE:CLSID_IITEM_MEDKIT );	
				if(itm)
				{
					inventory().Eat				(itm);
					SDrawStaticStruct* _s		= HUD().GetUI()->UIGame()->AddCustomStatic("item_used", true);
					_s->m_endTime				= Device.fTimeGlobal+3.0f;// 3sec
					string1024					str;
					strconcat					(sizeof(str),str,*CStringTable().translate("st_item_used"),": ", itm->Name());
					_s->wnd()->SetText			(str);
				}
			}
		}break;
#ifdef INV_NEW_SLOTS_SYSTEM
	case kUSE_SLOT_QUICK_ACCESS_0:
	case kUSE_SLOT_QUICK_ACCESS_1:
	case kUSE_SLOT_QUICK_ACCESS_2:
	case kUSE_SLOT_QUICK_ACCESS_3:
		{
			if(IsGameTypeSingle())
			{
				PIItem itm = 0;
				switch (cmd){
				case kUSE_SLOT_QUICK_ACCESS_0:
					
					itm = inventory().m_slots[SLOT_QUICK_ACCESS_0].m_pIItem;
					break;
				case kUSE_SLOT_QUICK_ACCESS_1:	
					itm = inventory().m_slots[SLOT_QUICK_ACCESS_1].m_pIItem;
					break;
				case kUSE_SLOT_QUICK_ACCESS_2:
					itm = inventory().m_slots[SLOT_QUICK_ACCESS_2].m_pIItem;
					break;
				case kUSE_SLOT_QUICK_ACCESS_3:
					itm = inventory().m_slots[SLOT_QUICK_ACCESS_3].m_pIItem;
					break;					
				}

				if (itm){
					CMedkit*			pMedkit				= smart_cast<CMedkit*>			(itm);
					CAntirad*			pAntirad			= smart_cast<CAntirad*>			(itm);
					CEatableItem*		pEatableItem		= smart_cast<CEatableItem*>		(itm);
					CBottleItem*		pBottleItem			= smart_cast<CBottleItem*>		(itm);				
					string1024					str;
					
					if(pMedkit || pAntirad || pEatableItem || pBottleItem){
						PIItem iitm = inventory().Same(itm,true);
						if(iitm){
							inventory().Eat(iitm);
							strconcat(sizeof(str),str,*CStringTable().translate("st_item_used"),": ", iitm->Name());
						}else{
							inventory().Eat(itm);
							strconcat(sizeof(str),str,*CStringTable().translate("st_item_used"),": ", itm->Name());
						}
						
						SDrawStaticStruct* _s		= HUD().GetUI()->UIGame()->AddCustomStatic("item_used", true);
						_s->m_endTime				= Device.fTimeGlobal+3.0f;// 3sec
						_s->wnd()->SetText			(str);
					}
				}
			}
		}break;
#endif		
		
	}
}
float CActor::MaxCarryWeight () const
{
	float res = inventory().GetMaxWeight();
	res      += get_additional_weight();
	return res;
}
Beispiel #8
0
bool Troll::getMenuSel(const char *szMenu, int *iSel, int nSel) {
    Common::Event event;
    int y;

    drawMenu(szMenu, *iSel);

    while (!_vm->shouldQuit()) {
        while (_vm->_system->getEventManager()->pollEvent(event)) {
            switch (event.type) {
            case Common::EVENT_RTL:
            case Common::EVENT_QUIT:
                return 0;
            case Common::EVENT_MOUSEMOVE:
                y = event.mouse.y / 8;

                if (y >= 22)
                    if (nSel > y - 22)
                        *iSel = y - 22;

                drawMenu(szMenu, *iSel);
                break;
            case Common::EVENT_LBUTTONUP:
                return true;
            case Common::EVENT_KEYDOWN:
                switch (event.kbd.keycode) {
                case Common::KEYCODE_t:
                case Common::KEYCODE_f:
                    inventory();

                    return false;
                case Common::KEYCODE_DOWN:
                case Common::KEYCODE_SPACE:
                    *iSel += 1;

                    if (*iSel == nSel)
                        *iSel = IDI_TRO_SEL_OPTION_1;

                    drawMenu(szMenu, *iSel);
                    break;
                case Common::KEYCODE_UP:
                    *iSel -= 1;

                    if (*iSel == IDI_TRO_SEL_OPTION_1 - 1)
                        *iSel = nSel - 1;

                    drawMenu(szMenu, *iSel);
                    break;
                case Common::KEYCODE_RETURN:
                case Common::KEYCODE_KP_ENTER:
                    return true;
                case Common::KEYCODE_s:
                    if (event.kbd.hasFlags(Common::KBD_CTRL)) {
                        if (_soundOn) {
                            playTune(2, 1);
                            _soundOn = !_soundOn;
                        } else {
                            _soundOn = !_soundOn;
                            playTune(3, 1);
                        }
                    }
                default:
                    break;
                }
                break;
            default:
                break;
            }
        }
        _vm->_system->updateScreen();
        _vm->_system->delayMillis(10);
    }

    return true;
}
void PlayerInst::use_item(GameState* gs, const GameAction& action) {
	if (!effective_stats().allowed_actions.can_use_items) {
		return;
	}
	itemslot_t slot = action.use_id;
	ItemSlot& itemslot = inventory().get(slot);
	Item& item = itemslot.item;
	ItemEntry& type = itemslot.item_entry();

	lua_State* L = gs->luastate();

	if (item.amount > 0) {
		if (item.is_equipment()) {
			if (itemslot.is_equipped()) {
				inventory().deequip(slot);
			} else {
				if (item.is_projectile()) {
					// Best-effort to equip, may not be possible:
					projectile_smart_equip(inventory(), slot);
				} else if (item.is_weapon()) {
					const Projectile& p = equipment().projectile();
					if (!p.empty()) {
						if (!p.projectile_entry().is_standalone()) {
							inventory().deequip_type(
									EquipmentEntry::AMMO);
						}
					}
					equipment().equip(slot);
					// Try and equip a projectile
					WeaponEntry& wentry = item.weapon_entry();
					if (wentry.uses_projectile) {
						const Projectile& p = equipment().projectile();
						if (p.empty()) {
							projectile_smart_equip(inventory(),
									wentry.weapon_class);
						}
					}
				} else {
					equipment().equip(slot);
				}

				if (item.is_weapon() || item.is_projectile()) {
					last_chosen_weaponclass =
							weapon().weapon_entry().weapon_class;
				}
			}
		} else if (equipment().valid_to_use(item)
				&& item_check_lua_prereq(L, type, this)) {
			item_do_lua_action(L, type, this,
					Pos(action.action_x, action.action_y), item.amount);
			if (is_local_player() && !type.inventory_use_message().empty()) {
				gs->game_chat().add_message(type.inventory_use_message(),
						Colour(100, 100, 255));
			}
			if (item.is_projectile())
				itemslot.clear();
			else
				item.remove_copies(1);
			reset_rest_cooldown();
		}
	}
}
Beispiel #10
0
void CActor::g_cl_CheckControls(u32 mstate_wf, Fvector &vControlAccel, float &Jump, float dt)
{
	float					cam_eff_factor = 0.0f;
	mstate_old				= mstate_real;
	vControlAccel.set		(0,0,0);

	if (!(mstate_real&mcFall) && (character_physics_support()->movement()->Environment()==CPHMovementControl::peInAir)) 
	{
		m_fFallTime				-=	dt;
		if (m_fFallTime<=0.f)
		{
			m_fFallTime			=	s_fFallTime;
			mstate_real			|=	mcFall;
			mstate_real			&=~	mcJump;
		}
	}

	if(!CanMove()) 
	{
		if(mstate_wf&mcAnyMove) 
		{
			StopAnyMove();
			mstate_wf &= ~mcAnyMove;
			mstate_wf &= ~mcJump;
		}
	}
	// update player accel
	if (mstate_wf&mcFwd)		vControlAccel.z +=  1;
	if (mstate_wf&mcBack)		vControlAccel.z += -1;
	if (mstate_wf&mcLStrafe)	vControlAccel.x += -1;
	if (mstate_wf&mcRStrafe)	vControlAccel.x +=  1;

	CPHMovementControl::EEnvironment curr_env = character_physics_support()->movement()->Environment();
	if(curr_env==CPHMovementControl::peOnGround || curr_env==CPHMovementControl::peAtWall)
	{
		// crouch
		if ((0==(mstate_real&mcCrouch))&&(mstate_wf&mcCrouch))
		{
			if(mstate_real&mcClimb)
			{
				mstate_wf&=~mcCrouch;
			}
			else
			{
				character_physics_support()->movement()->EnableCharacter();
				bool Crouched = false;
				if(isActorAccelerated(mstate_wf, IsZoomAimingMode()))
					Crouched = character_physics_support()->movement()->ActivateBoxDynamic(1);
				else
					Crouched = character_physics_support()->movement()->ActivateBoxDynamic(2);
				
				if(Crouched) 
					mstate_real			|=	mcCrouch;
			}
		}
		// jump
		m_fJumpTime				-=	dt;

		if( CanJump() && (mstate_wf&mcJump) )
		{
			mstate_real			|=	mcJump;
			m_bJumpKeyPressed	=	TRUE;
			Jump				= m_fJumpSpeed;
			m_fJumpTime			= s_fJumpTime;


			//уменьшить силу игрока из-за выполненого прыжка
			if (!GodMode())
				conditions().ConditionJump(inventory().TotalWeight() / MaxCarryWeight());
		}

		// mask input into "real" state
		u32 move	= mcAnyMove|mcAccel;

		if(mstate_real&mcCrouch)
		{
			if (!isActorAccelerated(mstate_real, IsZoomAimingMode()) && isActorAccelerated(mstate_wf, IsZoomAimingMode()))
			{
				character_physics_support()->movement()->EnableCharacter();
				if(!character_physics_support()->movement()->ActivateBoxDynamic(1))move	&=~mcAccel;
			}

			if (isActorAccelerated(mstate_real, IsZoomAimingMode()) && !isActorAccelerated(mstate_wf, IsZoomAimingMode()))
			{
				character_physics_support()->movement()->EnableCharacter();
				if(character_physics_support()->movement()->ActivateBoxDynamic(2))mstate_real	&=~mcAccel;
			}
		}

		if ((mstate_wf&mcSprint) && !CanSprint())
			mstate_wf				&= ~mcSprint;

		mstate_real &= (~move);
		mstate_real |= (mstate_wf & move);

		if(mstate_wf&mcSprint)
			mstate_real|=mcSprint;
		else
			mstate_real&=~mcSprint;
		if(!(mstate_real&(mcFwd|mcLStrafe|mcRStrafe))||mstate_real&(mcCrouch|mcClimb)|| !isActorAccelerated(mstate_wf, IsZoomAimingMode()))
		{
			mstate_real&=~mcSprint;
			mstate_wishful&=~mcSprint;
		}
				
		// check player move state
		if(mstate_real&mcAnyMove)
		{
			BOOL	bAccelerated		= isActorAccelerated(mstate_real, IsZoomAimingMode())&&CanAccelerate();

			// correct "mstate_real" if opposite keys pressed
			if (_abs(vControlAccel.z)<EPS)	mstate_real &= ~(mcFwd+mcBack		);
			if (_abs(vControlAccel.x)<EPS)	mstate_real &= ~(mcLStrafe+mcRStrafe);

			// normalize and analyze crouch and run
			float	scale			= vControlAccel.magnitude();
			if(scale>EPS)	
			{
				scale	=	m_fWalkAccel/scale;
				if (bAccelerated)
					if (mstate_real&mcBack)
						scale *= m_fRunBackFactor;
					else
						scale *= m_fRunFactor;
				else
					if (mstate_real&mcBack)
						scale *= m_fWalkBackFactor;



				if (mstate_real&mcCrouch)	scale *= m_fCrouchFactor;
				if (mstate_real&mcClimb)	scale *= m_fClimbFactor;
				if (mstate_real&mcSprint)	scale *= m_fSprintFactor;

				if (mstate_real&(mcLStrafe|mcRStrafe) && !(mstate_real&mcCrouch))
				{
					if (bAccelerated)
						scale *= m_fRun_StrafeFactor;
					else
						scale *= m_fWalk_StrafeFactor;
				}

				vControlAccel.mul			(scale);
				cam_eff_factor				= scale;
			}//scale>EPS
		}//(mstate_real&mcAnyMove)
	}//peOnGround || peAtWall

	if(IsGameTypeSingle() && cam_eff_factor>EPS)
	{
	LPCSTR state_anm				= NULL;

	if(mstate_real&mcSprint && !(mstate_old&mcSprint) )
		state_anm					= "sprint";
	else
	if(mstate_real&mcLStrafe && !(mstate_old&mcLStrafe) )
		state_anm					= "strafe_left";
	else
	if(mstate_real&mcRStrafe && !(mstate_old&mcRStrafe) )
		state_anm					= "strafe_right";
	else
	if(mstate_real&mcFwd && !(mstate_old&mcFwd) )
		state_anm					= "move_fwd";
	else
	if(mstate_real&mcBack && !(mstate_old&mcBack) )
		state_anm					= "move_back";

		if(state_anm)
		{ //play moving cam effect
			CActor*	control_entity		= static_cast_checked<CActor*>(Level().CurrentControlEntity());
			R_ASSERT2					(control_entity, "current control entity is NULL");
			CEffectorCam* ec			= control_entity->Cameras().GetCamEffector(eCEActorMoving);
			if(NULL==ec)
			{
				string_path			eff_name;
				xr_sprintf			(eff_name, sizeof(eff_name), "%s.anm", state_anm);
				string_path			ce_path;
				string_path			anm_name;
				strconcat			(sizeof(anm_name), anm_name, "camera_effects\\actor_move\\", eff_name);
				if (FS.exist( ce_path, "$game_anims$", anm_name))
				{
					CAnimatorCamLerpEffectorConst* e		= xr_new<CAnimatorCamLerpEffectorConst>();
					float max_scale				= 70.0f;
					float factor				= cam_eff_factor/max_scale;
					e->SetFactor				(factor);
					e->SetType					(eCEActorMoving);
					e->SetHudAffect				(false);
					e->SetCyclic				(false);
					e->Start					(anm_name);
					control_entity->Cameras().AddCamEffector(e);
				}
			}
		}
	}
	//transform local dir to world dir
	Fmatrix				mOrient;
	mOrient.rotateY		(-r_model_yaw);
	mOrient.transform_dir(vControlAccel);
}
void PlayerInst::enqueue_io_equipment_actions(GameState* gs,
		bool do_stopaction) {
	GameView& view = gs->view();
	bool mouse_within = gs->mouse_x() < gs->view().width;
	int rmx = view.x + gs->mouse_x(), rmy = view.y + gs->mouse_y();

	int level = gs->get_level()->id();
	int frame = gs->frame();
	bool item_used = false;
	IOController& io = gs->io_controller();

	Pos p(gs->mouse_x() + view.x, gs->mouse_y() + view.y);
	obj_id target = this->current_target;
	GameInst* targetted = gs->get_instance(target);
	if (targetted)
		p = Pos(targetted->x, targetted->y);

// We may have already used an item eg due to auto-use of items
	bool used_item = false;

//Item use
	for (int i = 0; i < 9 && !used_item; i++) {
		if (io.query_event(IOEvent(IOEvent::USE_ITEM_N, i))) {
			if (inventory().get(i).amount() > 0) {
				item_used = true;
				queued_actions.push_back(
						GameAction(id, GameAction::USE_ITEM, frame, level, i,
								p.x, p.y));
			}
		}
	}
	if (!used_item && gs->game_settings().autouse_health_potions
			&& core_stats().hp < AUTOUSE_HEALTH_POTION_THRESHOLD) {
		int item_slot = inventory().find_slot(
				get_item_by_name("Health Potion"));
		if (item_slot > -1) {
			queued_actions.push_back(
					game_action(gs, this, GameAction::USE_ITEM, item_slot));
			used_item = true;
		}
	}

//Item pickup
	GameInst* inst = NULL;
	if (cooldowns().can_pickup()
			&& gs->object_radius_test(this, &inst, 1, &item_colfilter)) {
		ItemInst* iteminst = (ItemInst*)inst;
		Item& item = iteminst->item_type();

		bool was_dropper = iteminst->last_held_by() == id;
		bool dropper_autopickup = iteminst->autopickup_held();

		bool autopickup = (item.is_normal_item() && !was_dropper
				&& !dropper_autopickup) || (was_dropper && dropper_autopickup);

		bool wieldable_projectile = projectile_should_autowield(equipment(),
				item, this->last_chosen_weaponclass);

		bool pickup_io = gs->key_down_state(SDLK_LSHIFT)
				|| gs->key_down_state(SDLK_RSHIFT);

		if (do_stopaction || wieldable_projectile || pickup_io || autopickup)
			queued_actions.push_back(
					GameAction(id, GameAction::PICKUP_ITEM, frame, level,
							iteminst->id));
	}
}
void
load_city (char *cname)
{
    unsigned long q;
    int i, x, y, z, n, p, ver;
    int num_pbars, pbar_data_size;
    int pbar_tmp;
    int dummy;
    FILE *ofile;
    char s[256];
    if ((ofile = fopen_read_gzipped (cname)) == NULL) {
	printf ("Can't open <%s> (gzipped)", cname);
	do_error ("Can't open it!");
    }
    fscanf (ofile, "%d", &ver);
    if (ver < MIN_LOAD_VERSION) {
	ok_dial_box ("too-old.mes", BAD, 0L);
	fclose_read_gzipped (ofile);
	return;
    }

    init_pbars();
    num_pbars = NUM_PBARS;
    pbar_data_size = PBAR_DATA_SIZE;

    init_inventory();
    
    print_time_for_year();
    q = (unsigned long) sizeof (Map_Point_Info);
    prog_box (_("Loading scene"), 0);

    for (x = 0; x < WORLD_SIDE_LEN; x++) {
	for (y = 0; y < WORLD_SIDE_LEN; y++) {
	    for (z = 0; z < sizeof(int); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).population) + z) = n;
	    }
	    for (z = 0; z < sizeof(int); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).flags) + z) = n;
	    }
	    for (z = 0; z < sizeof(unsigned short); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).coal_reserve) + z) = n;
	    }
	    for (z = 0; z < sizeof(unsigned short); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).ore_reserve) + z) = n;
	    }
	    for (z = 0; z < sizeof(int); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).int_1) + z) = n;
	    }
	    for (z = 0; z < sizeof(int); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).int_2) + z) = n;
	    }
	    for (z = 0; z < sizeof(int); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).int_3) + z) = n;
	    }
	    for (z = 0; z < sizeof(int); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).int_4) + z) = n;
	    }
	    for (z = 0; z < sizeof(int); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).int_5) + z) = n;
	    }
	    for (z = 0; z < sizeof(int); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).int_6) + z) = n;
	    }
	    for (z = 0; z < sizeof(int); z++) {
		fscanf (ofile, "%d", &n);
		*(((unsigned char *) &MP_INFO(x,y).int_7) + z) = n;
	    }
	    fscanf (ofile, "%d", &n);
	    MP_POL(x,y) = (unsigned short) n;
	    fscanf (ofile, "%d", &n);
	    MP_TYPE(x,y) = (short) n;

	    if (get_group_of_type(MP_TYPE(x,y)) == GROUP_MARKET)
		inventory(x,y);
	}
	if (((93 * x) / WORLD_SIDE_LEN) % 3 == 0)
	    prog_box ("", (93 * x) / WORLD_SIDE_LEN);
    }
    check_endian ();
    set_map_groups ();

    fscanf (ofile, "%d", &main_screen_originx);
    fscanf (ofile, "%d", &main_screen_originy);
    if (main_screen_originx > WORLD_SIDE_LEN - scr.main_win.w / 16 - 1)
	main_screen_originx = WORLD_SIDE_LEN - scr.main_win.w / 16 - 1;

    if (main_screen_originy > WORLD_SIDE_LEN - scr.main_win.h / 16 - 1)
	main_screen_originy = WORLD_SIDE_LEN - scr.main_win.h / 16 - 1;

    fscanf (ofile, "%d", &total_time);
    if (ver <= MM_MS_C_VER)
	i = OLD_MAX_NUMOF_SUBSTATIONS;
    else
	i = MAX_NUMOF_SUBSTATIONS;
    for (x = 0; x < i; x++)
    {
	fscanf (ofile, "%d", &substationx[x]);
	fscanf (ofile, "%d", &substationy[x]);
    }
    prog_box ("", 92);
    fscanf (ofile, "%d", &numof_substations);
    if (ver <= MM_MS_C_VER)
	i = OLD_MAX_NUMOF_MARKETS;
    else
	i = MAX_NUMOF_MARKETS;
    for (x = 0; x < i; x++)
    {
	fscanf (ofile, "%d", &marketx[x]);
	fscanf (ofile, "%d", &markety[x]);
    }
    prog_box ("", 94);
    fscanf (ofile, "%d", &numof_markets);
    fscanf (ofile, "%d", &people_pool);
    fscanf (ofile, "%d", &total_money);
    fscanf (ofile, "%d", &income_tax_rate);
    fscanf (ofile, "%d", &coal_tax_rate);
    fscanf (ofile, "%d", &dole_rate);
    fscanf (ofile, "%d", &transport_cost_rate);
    fscanf (ofile, "%d", &goods_tax_rate);
    fscanf (ofile, "%d", &export_tax);
    fscanf (ofile, "%d", &export_tax_rate);
    fscanf (ofile, "%d", &import_cost);
    fscanf (ofile, "%d", &import_cost_rate);
    fscanf (ofile, "%d", &tech_level);
    if (tech_level > MODERN_WINDMILL_TECH)
	modern_windmill_flag = 1;
    fscanf (ofile, "%d", &tpopulation);
    fscanf (ofile, "%d", &tstarving_population);
    fscanf (ofile, "%d", &tunemployed_population);
    fscanf (ofile, "%d", &x);  /* waste_goods obsolete */
    fscanf (ofile, "%d", &power_made);
    fscanf (ofile, "%d", &power_used);
    fscanf (ofile, "%d", &coal_made);
    fscanf (ofile, "%d", &coal_used);
    fscanf (ofile, "%d", &goods_made);
    fscanf (ofile, "%d", &goods_used);
    fscanf (ofile, "%d", &ore_made);
    fscanf (ofile, "%d", &ore_used);
    fscanf (ofile, "%d", &dummy); /* &diff_old_population */

    /* Update variables calculated from those above */
    housed_population = tpopulation / NUMOF_DAYS_IN_MONTH;

    prog_box ("", 96);
    /* Get size of monthgraph array */
    if (ver <= MG_C_VER) {
	i = 120;
    } else {
	fscanf (ofile, "%d", &i);
    }
    for (x = 0; x < i; x++) {
	/* If more entries in file than will fit on screen, 
	   then we need to skip past them. */
	if (x >= monthgraph_size) {
	    fscanf (ofile, "%d", &dummy); /* &monthgraph_pop[x] */
	    fscanf (ofile, "%d", &dummy); /* &monthgraph_starve[x] */
	    fscanf (ofile, "%d", &dummy); /* &monthgraph_nojobs[x] */
	    fscanf (ofile, "%d", &dummy); /* &monthgraph_ppool[x] */
	} else {
	    fscanf (ofile, "%d", &monthgraph_pop[x]);
	    fscanf (ofile, "%d", &monthgraph_starve[x]);
	    fscanf (ofile, "%d", &monthgraph_nojobs[x]);
	    fscanf (ofile, "%d", &monthgraph_ppool[x]);
	}
	/* If our save file is old, skip past obsolete diffgraph entries */
	if (ver <= MG_C_VER) {
	    fscanf (ofile, "%d", &dummy); /* &diffgraph_power[x] */
	    fscanf (ofile, "%d", &dummy); /* &diffgraph_coal[x] */
	    fscanf (ofile, "%d", &dummy); /* &diffgraph_goods[x] */
	    fscanf (ofile, "%d", &dummy); /* &diffgraph_ore[x] */
	    fscanf (ofile, "%d", &dummy); /* &diffgraph_population[x] */
	}
    }
    /* If screen bigger than number of entries in file, pad with zeroes */
    while (x < monthgraph_size) {
	monthgraph_pop[x] = 0;
	monthgraph_starve[x] = 0;
	monthgraph_nojobs[x] = 0;
	monthgraph_ppool[x] = 0;
	x++;
    }
    prog_box ("", 98);
    fscanf (ofile, "%d", &rockets_launched);
    fscanf (ofile, "%d", &rockets_launched_success);
    fscanf (ofile, "%d", &coal_survey_done);
    
    for (x = 0; x < pbar_data_size; x++) {
	for (p = 0; p < num_pbars; p++) {
	    fscanf (ofile, "%d", &(pbar_tmp));
	    update_pbar(p,pbar_tmp,1);
/*	    fscanf (ofile, "%d", &(pbars[p].data[x])); */
	}
    }

    for (p = 0; p < num_pbars; p++)
	pbars[p].data_size = pbar_data_size;

    prog_box ("", 99);

    for (p = 0; p < num_pbars; p++) {
	fscanf (ofile, "%d", &(pbars[p].oldtot));
	fscanf (ofile, "%d", &(pbars[p].diff));
    }


    fscanf (ofile, "%d", &cheat_flag);
    fscanf (ofile, "%d", &total_pollution_deaths);
    fscanf (ofile, "%f", &pollution_deaths_history);
    fscanf (ofile, "%d", &total_starve_deaths);
    fscanf (ofile, "%f", &starve_deaths_history);
    fscanf (ofile, "%d", &total_unemployed_years);
    fscanf (ofile, "%f", &unemployed_history);
    fscanf (ofile, "%d", &max_pop_ever);
    fscanf (ofile, "%d", &total_evacuated);
    fscanf (ofile, "%d", &total_births);
    for (x = 0; x < NUMOF_MODULES; x++)
	fscanf (ofile, "%d", &(module_help_flag[x]));
    fscanf (ofile, "%d", &x);	/* just dummy reads */
    fscanf (ofile, "%d", &x);	/* for backwards compatibility. */

    /* 10 dummy strings, for missed out things, have been put in save. */
    /* Input from this point uses them. */
    /* XXX: WCK: Huh? Missed out things? */

    fscanf (ofile, "%128s", given_scene);
    if (strncmp (given_scene, "dummy", 5) == 0 || strlen (given_scene) < 3)
	given_scene[0] = 0;
    fscanf (ofile, "%128s", s);
    if (strncmp (given_scene, "dummy", 5) != 0)
	sscanf (s, "%d", &highest_tech_level);
    else
	highest_tech_level = 0;
    fgets (s, 80, ofile);		/* this is the CR */

    fgets (s, 80, ofile);
    if (sscanf (s, "sust %d %d %d %d %d %d %d %d %d %d"
		,&sust_dig_ore_coal_count, &sust_port_count
		,&sust_old_money_count, &sust_old_population_count
		,&sust_old_tech_count, &sust_fire_count
		,&sust_old_money, &sust_old_population, &sust_old_tech
		,&sustain_flag) == 10)
    {
	sust_dig_ore_coal_tip_flag = sust_port_flag = 1;
	/* GCS FIX: Check after loading file if screen is drawn OK */
	/* draw_sustainable_window (); */
    }
    else
	sustain_flag = sust_dig_ore_coal_count = sust_port_count
		= sust_old_money_count = sust_old_population_count
		= sust_old_tech_count = sust_fire_count
		= sust_old_money = sust_old_population = sust_old_tech = 0;
    fclose_read_gzipped (ofile);

    numof_shanties = count_groups (GROUP_SHANTY);
    numof_communes = count_groups (GROUP_COMMUNE);
    prog_box ("", 100);

    /* set up the university intake. */
    x = count_groups (GROUP_UNIVERSITY);
    if (x > 0) {
	university_intake_rate
		= (count_groups (GROUP_SCHOOL) * 20) / x;
	if (university_intake_rate > 100)
	    university_intake_rate = 100;
    }
    else
	university_intake_rate = 50;
    for (x = 0; x < WORLD_SIDE_LEN; x++)
    {
	for (y = 0; y < WORLD_SIDE_LEN; y++)
	{
	    update_tech_dep (x, y);
	}
    }

    selected_module_type = CST_TRACK_LR;
    selected_module_cost = GROUP_TRACK_COST;
    old_selected_module = sbut[7];
    highlight_module_button (sbut[7]);	/* 7 is track.  Watch out though! */

    print_total_money ();
    reset_animation_times ();
    map_power_grid (); /* WCK:  Is this safe to do here? */
}
Beispiel #13
0
void CActor::g_cl_CheckControls(u32 mstate_wf, Fvector &vControlAccel, float &Jump, float dt)
{
	mstate_old = mstate_real;
	vControlAccel.set	(0,0,0);

	if (!(mstate_real&mcFall) && (character_physics_support()->movement()->Environment()==CPHMovementControl::peInAir)) 
	{
		m_fFallTime				-=	dt;
		if (m_fFallTime<=0.f){
			m_fFallTime			=	s_fFallTime;
			mstate_real			|=	mcFall;
			mstate_real			&=~	mcJump;
		}
	}

	if(!CanMove()) 
	{
		if(mstate_wf&mcAnyMove) 
		{
			StopAnyMove();
			mstate_wf &= ~mcAnyMove;
			mstate_wf &= ~mcJump;
		}
			//character_physics_support()->movement()->EnableCharacter();
		//return;
	}

	// update player accel
	if (mstate_wf&mcFwd)		vControlAccel.z +=  1;
	if (mstate_wf&mcBack)		vControlAccel.z += -1;
	if (mstate_wf&mcLStrafe)	vControlAccel.x += -1;
	if (mstate_wf&mcRStrafe)	vControlAccel.x +=  1;

	if (character_physics_support()->movement()->Environment()==CPHMovementControl::peOnGround || character_physics_support()->movement()->Environment()==CPHMovementControl::peAtWall )
	{
		// crouch
		if ((0==(mstate_real&mcCrouch))&&(mstate_wf&mcCrouch))
		{
			if(mstate_real&mcClimb)
			{
				mstate_wf&=~mcCrouch;
			}
			else
			{
				character_physics_support()->movement()->EnableCharacter();
				bool Crouched = false;
				if (isActorAccelerated(mstate_wf, IsZoomAimingMode()))
					Crouched = character_physics_support()->movement()->ActivateBoxDynamic(1);
				else
					Crouched = character_physics_support()->movement()->ActivateBoxDynamic(2);
				if (Crouched) mstate_real			|=	mcCrouch;
			}
		}
		// jump
		m_fJumpTime				-=	dt;

		if ( CanJump() && (mstate_wf&mcJump) )
		{
			mstate_real			|=	mcJump;
			m_bJumpKeyPressed	=	TRUE;
			Jump				= m_fJumpSpeed;
			m_fJumpTime			= s_fJumpTime;


			//уменьшить силу игрока из-за выполненого прыжка
			if (!GodMode())
				conditions().ConditionJump(inventory().TotalWeight() / MaxCarryWeight());
		}

		/*
		if(m_bJumpKeyPressed)
		Jump				= m_fJumpSpeed;
		*/


		// mask input into "real" state
		u32 move	= mcAnyMove|mcAccel;

		if (((mstate_real&mcCrouch)))
		{
			if (!isActorAccelerated(mstate_real, IsZoomAimingMode()) && isActorAccelerated(mstate_wf, IsZoomAimingMode()))
			{
				character_physics_support()->movement()->EnableCharacter();
				if(!character_physics_support()->movement()->ActivateBoxDynamic(1))move	&=~mcAccel;
			}

			if (isActorAccelerated(mstate_real, IsZoomAimingMode()) && !isActorAccelerated(mstate_wf, IsZoomAimingMode()))
			{
				character_physics_support()->movement()->EnableCharacter();
				if(character_physics_support()->movement()->ActivateBoxDynamic(2))mstate_real	&=~mcAccel;
			}
		}

		if ((mstate_wf&mcSprint) && !CanSprint())
		{
			mstate_wf				&= ~mcSprint;
		}

		mstate_real &= (~move);
		mstate_real |= (mstate_wf & move);

		if(mstate_wf&mcSprint)
			mstate_real|=mcSprint;
		else
			mstate_real&=~mcSprint;
		if(!(mstate_real&(mcFwd|mcLStrafe|mcRStrafe))||mstate_real&(mcCrouch|mcClimb)|| !isActorAccelerated(mstate_wf, IsZoomAimingMode()))
		{
			mstate_real&=~mcSprint;
			mstate_wishful&=~mcSprint;
		}
				
		// check player move state
		if (mstate_real&mcAnyMove)
		{
			BOOL	bAccelerated		= isActorAccelerated(mstate_real, IsZoomAimingMode())&&CanAccelerate();



			// correct "mstate_real" if opposite keys pressed
			if (_abs(vControlAccel.z)<EPS)	mstate_real &= ~(mcFwd+mcBack		);
			if (_abs(vControlAccel.x)<EPS)	mstate_real &= ~(mcLStrafe+mcRStrafe);

			// normalize and analyze crouch and run
			float	scale				= vControlAccel.magnitude();
			if (scale>EPS)	{
				scale	=	m_fWalkAccel/scale;
				if (bAccelerated)
					if (mstate_real&mcBack)
						scale *= m_fRunBackFactor;
					else
						scale *= m_fRunFactor;
				else
					if (mstate_real&mcBack)
						scale *= m_fWalkBackFactor;



				if (mstate_real&mcCrouch)	scale *= m_fCrouchFactor;
				if (mstate_real&mcClimb)	scale *= m_fClimbFactor;
				if (mstate_real&mcSprint)	scale *= m_fSprintFactor;

				if (mstate_real&(mcLStrafe|mcRStrafe) && !(mstate_real&mcCrouch))
				{
					if (bAccelerated)
						scale *= m_fRun_StrafeFactor;
					else
						scale *= m_fWalk_StrafeFactor;
				}

				vControlAccel.mul			(scale);
			}else{
				//				mstate_real	&= ~mcAnyMove;
			}
		}		
	}else{
		//		mstate_real			&=~ mcAnyMove;
	}

	//-------------------------------------------------------------------------------	
	

	//transform local dir to world dir
	Fmatrix				mOrient;
	mOrient.rotateY		(-r_model_yaw);
	mOrient.transform_dir(vControlAccel);
	//XFORM().transform_dir(vControlAccel);

	/*
	if(mstate_real&mcClimb&&mstate_real&mcAnyMove&&
	inventory().ActiveItem()&&inventory().ActiveItem()->HandDependence()==hd2Hand)
	{
		//inventory().ActiveItem()->Deactivate();
		inventory().Activate(NO_ACTIVE_SLOT);
	}
*/
}
Beispiel #14
0
inventory inventory::operator+ (const inventory &rhs)
{
 return inventory(*this) += rhs;
}
Beispiel #15
0
/* The main game loop */
void play(void) {
	int playing = 1;
	int x, y, vpx, vpy;
	
	/* A messy way to do the map, works for now */
	map_t *map = map_new(50, 50);
	generate_cave(map);
	map_fov_build(map);
	
	/* Set up the offscreen consoles */
	map_layer = TCOD_console_new(ui_viewport_width, ui_viewport_height);
	psion_layer = TCOD_console_new(ui_viewport_width, ui_viewport_height);
	TCOD_console_set_key_color(psion_layer, C_KEY);
	bgcolor(psion_layer, C_KEY);
	
	/* Set up the player */
	init_player();
	rename_player("Gu the Cabeboy");
	blink_player(map);
	
	/* Initialize the inventory */
	
	
	/* Enter the main game loop! */
	while (playing) {
	
		/* Prepare the screen for drawing */
		clear(NULL);
		
		/* Calculate the position of the viewport */
		vpx = player->x - ui_viewport_width/2 > 0 ?
			  player->x - ui_viewport_width/2 : 0;
		vpy = player->y - ui_viewport_height/2 > 0 ?
			  player->y - ui_viewport_height/2 : 0;
		if ((vpx + ui_viewport_width) > map->width) {
			vpx = map->width - ui_viewport_width;
		}
		if ((vpy + ui_viewport_height) > map->height) {
			vpy = map->height - ui_viewport_height;
		}
		if (ui_viewport_width > map->width) {
			vpx = 0;
		}
		if (ui_viewport_height > map->height) {
			vpy = 0;
		}
			
		/* Calculate the field of view */
		map_fov_do(map, player->x, player->y);
		
		/* Only display the part of the map inside the viewport */
		for (y = 0; y < ui_viewport_height; y++) {
			for (x = 0; x < ui_viewport_width; x++) {
				if (((vpy+y) < map->height) && ((vpx+x) < map->width)) {
					tile_t *tile = tile_at(map, vpx+x, vpy+y);
					if (TCOD_map_is_in_fov(map->fov, vpx+x, vpy+y)) {
						fgcolor(map_layer, tile->fg_lit);
					}
					else {
						fgcolor(map_layer, tile->fg_dark);
					}
					putch(map_layer, x, y, tile->glyph);
				}
			}
		}
		
		TCOD_console_blit(map_layer, 0, 0, ui_viewport_width,
		                  ui_viewport_height, NULL, ui_viewport_x,
		                  ui_viewport_y, 255);
		
		/* Draw the player and status */
		fgcolor(NULL, C_WHITE);
		putch(NULL, ui_viewport_x+player->x-vpx, ui_viewport_y+player->y-vpy, '@');
		fgcolor(NULL, C_MSG);
		putstr(NULL, 1, 23, player->name);
		
		/* Redraw the screen */
		update();
		
		/* Handle keypress */
		TCOD_key_t k = getkey();
		if (k.c == 0) {
			switch (k.vk) {
				/* Move around */
				case TCODK_KP7: /* up left */
					attempt_move(map, player->x-1, player->y-1);
					break;
					
				case TCODK_KP8: /* up */
				case TCODK_UP:
					attempt_move(map, player->x, player->y-1);
					break;
					
				case TCODK_KP9: /* up right */
					attempt_move(map, player->x+1, player->y-1);
					break;
					
				case TCODK_KP1: /* down left */
					attempt_move(map, player->x-1, player->y+1);
					break;
				
				case TCODK_KP2: /* down */
				case TCODK_DOWN:
					attempt_move(map, player->x, player->y+1);
					break;
					
				case TCODK_KP3: /* down right */
					attempt_move(map, player->x+1, player->y+1);
					break;
				
				case TCODK_KP4: /* left */
				case TCODK_LEFT:
					attempt_move(map, player->x-1, player->y);
					break;
				
				case TCODK_KP6: /* right */
				case TCODK_RIGHT:
					attempt_move(map, player->x+1, player->y);
					break;
				
				/* View character summary */
				case TCODK_TAB:
					character();
					break;
				
				default:
					printf("%d %d\n", TCODK_TAB, k.vk);
					break;
			}
		}
		else {
			switch (k.c) {
				
				/* Quit the game */
				case 'Q':
					playing = quit();
					break;
				
				/* Open up the inventory */
				case 'i':
					inventory();
					break;
				
				/* View character summary */
				case 'c':
					character();
					break;
					
				/* Use scan ability */
				case 's':
					psion_scan(map);
					break;
				
				default:
					break;
			}
		}
	}
	
	/* Clean up, the game is over */
	map_destroy(map);
}
Beispiel #16
0
inventory inventory::operator+ (const std::list<item> &rhs)
{
 return inventory(*this) += rhs;
}
Beispiel #17
0
void process_keys() {
	if (game.cooldown <= 0) {
		scanKeys();
		u32 keys = keysHeld();
		u32 down = keysDown();
		touchPosition touch = touchReadXY();

		if (down & KEY_START) {
			new_game();
			return;
		}

		if (down & KEY_SELECT) {
			test_map();

			torch.buf.scroll.x = game.player.x - 16;
			torch.buf.scroll.y = game.player.y - 12;
			torch.buf.bounded(torch.buf.scroll.x, torch.buf.scroll.y);
			torch.dirty_screen();
			torch.reset_luminance();

			return;
		}

		if (down & KEY_X) {
			inventory(); return;
		}
		if (down & KEY_L) {
			overview(); return;
		}

		if (down & KEY_TOUCH && touch.px != 0 && touch.py != 0) {
			if (!(keys & KEY_R) && game.player.projectile) {
				game.player.chuck(torch.buf.scroll.x + touch.px/8,
													torch.buf.scroll.y + touch.py/8);
			}
			return;
		}

		if (down & KEY_R) {
			printf("Saving... ");
			fflush(stdout);
			game.save("blah.adrift");
			printf("done\n");
			printf("Loading... ");
			fflush(stdout);
			game.load("blah.adrift");
			printf("done\n");
		}

		if (keys & KEY_Y) {
			if (get_items()) return;
		}

		DIRECTION dir = 0;
		if (keys & KEY_RIGHT)
			dir |= D_EAST;
		else if (keys & KEY_LEFT)
			dir |= D_WEST;
		if (keys & KEY_DOWN)
			dir |= D_SOUTH;
		else if (keys & KEY_UP)
			dir |= D_NORTH;

		if (dir) {
			game.player.moveDir(dir, keys & KEY_B);
			return;
		}

		if (down & KEY_A) {
			seek_and_destroy();
			if (!game.player.target) {
				// no monsters in range
				for (int x = game.player.x-1; x <= game.player.x+1; x++) {
					for (int y = game.player.y-1; y <= game.player.y+1; y++) {
						Object *o = game.map.at(x,y)->objects.head();
						if (!o) continue;
						if (o->type == VENDING_MACHINE) {
							if (game.player.x == x+D_DX[o->orientation] && game.player.y == y+D_DY[o->orientation]) {
								iprintf("You kick the vending machine. ");
								if (o->quantity > 0 && rand4() < 5) {
									if (rand4() & 1) {
										iprintf("Clunk! A can rolls out.\n");
										addObject(game.player.x, game.player.y, CAN_OF_STEWED_BEEF);
									} else {
										iprintf("Clunk! A bottle rolls out.\n");
										addObject(game.player.x, game.player.y, BOTTLE_OF_WATER);
									}
									o->quantity--;
								} else {
									iprintf("Nothing happens.\n");
								}
								game.cooldown += 5;
							}
						}
					}
				}
			} else return;
		}
		if (keys & KEY_A) {
			seek_and_destroy(); return;
		}

	} else if (game.cooldown > 0)
		game.cooldown--;
}