コード例 #1
0
//---------------------------------------------------
void CCharacterVersionAdapter::adaptToVersion2(CCharacter &character) const
{
	/****************************************************************/
	/* reset all bricks and actions, set charcateristics to their 
	/* starting values and recompute scores
	/****************************************************************/

	static const NLMISC::CSheetId sheet("skills.skill_tree");
	static const CStaticSkillsTree * skillsTree = CSheets::getSkillsTreeForm( sheet );

	character._SpType[EGSPD::CSPType::Fight] = 10 * skillsTree->getPlayerSkillPointsUnderSkill(&character._Skills, SKILLS::SF);
	character._SpType[EGSPD::CSPType::Magic] = 10 * skillsTree->getPlayerSkillPointsUnderSkill(&character._Skills, SKILLS::SM);
	character._SpType[EGSPD::CSPType::Craft] = 10 * skillsTree->getPlayerSkillPointsUnderSkill(&character._Skills, SKILLS::SC);
	character._SpType[EGSPD::CSPType::Harvest] = 10 * skillsTree->getPlayerSkillPointsUnderSkill(&character._Skills, SKILLS::SH);

	character._Skills._Sp = 0;
	
	// clear all memories... 
	character._MemorizedPhrases.forgetAll();

	// clear bricks and phrases
	character._KnownPhrases.clear();
	character._BoughtPhrases.clear();
	character._KnownBricks.clear();

	for( uint i = 0; i < CHARACTERISTICS::NUM_CHARACTERISTICS; ++i )
	{
		// at level 1 for formula dependency with regenerate value
		character._PhysCharacs._PhysicalCharacteristics[ i ].Base = 10; 
	
		character._PhysCharacs._PhysicalCharacteristics[ i ].Max = character._PhysCharacs._PhysicalCharacteristics[ i ].Base + character._PhysCharacs._PhysicalCharacteristics[ i ].Modifier;
		character._PhysCharacs._PhysicalCharacteristics[ i ].Current = character._PhysCharacs._PhysicalCharacteristics[ i ].Max;
	}
	// Compute Scores
	// !!! DOT NOT change modifiers as they are changed by equipement !!!
	for(uint i = 0; i < SCORES::NUM_SCORES; ++i )
	{
		switch( i )
		{
		case SCORES::hit_points:
			character._PhysScores._PhysicalScores[ i ].Base = character._PhysCharacs._PhysicalCharacteristics[ CHARACTERISTICS::constitution ].Base * 10;
			break;
		case SCORES::sap:
			character._PhysScores._PhysicalScores[ i ].Base = character._PhysCharacs._PhysicalCharacteristics[ CHARACTERISTICS::intelligence ].Base * 10;
			break;
		case SCORES::stamina:
			character._PhysScores._PhysicalScores[ i ].Base = character._PhysCharacs._PhysicalCharacteristics[ CHARACTERISTICS::strength ].Base * 10;
			break;
		case SCORES::focus:
			character._PhysScores._PhysicalScores[ i ].Base = character._PhysCharacs._PhysicalCharacteristics[ CHARACTERISTICS::dexterity ].Base * 10;
			break;
		default:;
		}
		character.updateRegen();
		character._PhysScores._PhysicalScores[ i ].Max = character._PhysScores._PhysicalScores[ i ].Base + character._PhysScores._PhysicalScores[ i ].Modifier;
		character._PhysScores._PhysicalScores[ i ].Current = character._PhysScores._PhysicalScores[ i ].Max;
		character._PhysScores._PhysicalScores[ i ].CurrentRegenerate = character._PhysScores._PhysicalScores[ i ].BaseRegenerateAction + character._PhysScores._PhysicalScores[ i ].RegenerateModifier;
	}

	character.addCreationBricks();
}
コード例 #2
0
LTBOOL CAISenseSeeEnemy::Update(HOBJECT hStimulus, LTFLOAT fTimeDelta)
{
	if ( !IsCharacter(hStimulus) ) return LTFALSE;

	if ( m_pAI->GetCharacterClass() == NEUTRAL )
	{
		// If we're innocent, we only consider someone an enemy if they have a gun

        CCharacter* pCharacter = (CCharacter*)g_pLTServer->HandleToObject(hStimulus);
		if ( !pCharacter->HasDangerousWeapon() )
		{
            return LTFALSE;
		}
	}

	// Instead of looking right at the center of the target, we at a grid of points.
	// The grid is a plane with normal equal to the forward vector of the object,
	// in the center of the object, clipped to the objects dims. We scan the grid
	// at a given resolution and simply advance our scan col/row every frame. Note
	// that the grid is aligned with the objects rotation, not the bounding boxes,
	// since all the bounding boxes are axis aligned.

	int nXRange = m_rngGridX.GetMax() - m_rngGridX.GetMin();
	int nYRange = m_rngGridY.GetMax() - m_rngGridY.GetMin();

    LTVector vDims;
    g_pLTServer->GetObjectDims(hStimulus, &vDims);

    LTFLOAT fX = vDims.x * ((LTFLOAT)m_nGridX/(LTFLOAT)nXRange);
    LTFLOAT fY = vDims.y * ((LTFLOAT)m_nGridY/(LTFLOAT)nYRange);

    LTVector vPosition;
    g_pLTServer->GetObjectPos(hStimulus, &vPosition);

    LTRotation rRot;
    g_pLTServer->GetObjectRotation(hStimulus, &rRot);

    LTVector vUp, vRight, vForward;
    g_pLTServer->GetRotationVectors(&rRot, &vUp, &vRight, &vForward);

	vPosition += vRight*fX;
	vPosition += vUp*fY;

	// Update the point

    LTFLOAT fDistanceSqr;
    LTBOOL bVisible;

	if ( m_pAI->CanSeeThrough() )
	{
        bVisible = m_pAI->IsObjectPositionVisibleFromEye(CAI::SeeThroughFilterFn, CAI::SeeThroughPolyFilterFn, hStimulus, vPosition, (m_fDistanceSqr), LTTRUE, &fDistanceSqr);
	}
	else
	{
        bVisible = m_pAI->IsObjectPositionVisibleFromEye(CAI::DefaultFilterFn, NULL, hStimulus, vPosition, (m_fDistanceSqr), LTTRUE, &fDistanceSqr);
	}

	if ( bVisible )
	{
		if ( fDistanceSqr > g_pAIButeMgr->GetSenses()->fInstantSeeDistanceSqr )
		{
			LTFLOAT fRateModifier = (1.0f - fDistanceSqr/m_fDistanceSqr);
			IncreaseStimulation(fTimeDelta, (fRateModifier));
		}
		else
		{
			IncreaseStimulation(fTimeDelta, 99999999.0f);
		}
	}

	// Update our grid col/row values

	if ( ++m_nGridX > m_rngGridX.GetMax() )
	{
		m_nGridX = m_rngGridX.GetMin();

		if ( ++m_nGridY > m_rngGridY.GetMax() )
		{
			m_nGridY = m_rngGridY.GetMin();
		}
	}

	return bVisible;
}
コード例 #3
0
ファイル: ctf.cpp プロジェクト: Rush/teeworlds
void CGameControllerCTF::Tick()
{
	IGameController::Tick();

	DoTeamScoreWincheck();
	
	for(int fi = 0; fi < 2; fi++)
	{
		CFlag *F = m_apFlags[fi];
		
		if(!F)
			continue;
		
		// flag hits death-tile, reset it
		if(GameServer()->Collision()->GetCollisionAt(F->m_Pos.x, F->m_Pos.y)&CCollision::COLFLAG_DEATH)
		{
			GameServer()->CreateSoundGlobal(SOUND_CTF_RETURN);
			F->Reset();
			continue;
		}
		
		//
		if(F->m_pCarryingCharacter)
		{
			// update flag position
			F->m_Pos = F->m_pCarryingCharacter->m_Pos;
			
			if(m_apFlags[fi^1] && m_apFlags[fi^1]->m_AtStand)
			{
				if(distance(F->m_Pos, m_apFlags[fi^1]->m_Pos) < CFlag::ms_PhysSize + CCharacter::ms_PhysSize)
				{
					// CAPTURE! \o/
					m_aTeamscore[fi^1] += 100;
					F->m_pCarryingCharacter->GetPlayer()->m_Score += 5;

					char aBuf[512];
					str_format(aBuf, sizeof(aBuf), "flag_capture player='%d:%s'",
						F->m_pCarryingCharacter->GetPlayer()->GetCID(),
						Server()->ClientName(F->m_pCarryingCharacter->GetPlayer()->GetCID()));
					GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf);

					float CaptureTime = (Server()->Tick() - F->m_GrabTick)/(float)Server()->TickSpeed();
					if(CaptureTime <= 60)
					{
						str_format(aBuf, sizeof(aBuf), "The %s flag was captured by '%s' (%d.%s%d seconds)", fi ? "blue" : "red", Server()->ClientName(F->m_pCarryingCharacter->GetPlayer()->GetCID()), (int)CaptureTime%60, ((int)(CaptureTime*100)%100)<10?"0":"", (int)(CaptureTime*100)%100);
					}
					else
					{
						str_format(aBuf, sizeof(aBuf), "The %s flag was captured by '%s'", fi ? "blue" : "red", Server()->ClientName(F->m_pCarryingCharacter->GetPlayer()->GetCID()));
					}
					GameServer()->SendChat(-1, -2, aBuf);
					for(int i = 0; i < 2; i++)
						m_apFlags[i]->Reset();
					
					GameServer()->CreateSoundGlobal(SOUND_CTF_CAPTURE);
				}
			}
		}
		else
		{
			CCharacter *apCloseCCharacters[MAX_CLIENTS];
			int Num = GameServer()->m_World.FindEntities(F->m_Pos, CFlag::ms_PhysSize, (CEntity**)apCloseCCharacters, MAX_CLIENTS, NETOBJTYPE_CHARACTER);
			for(int i = 0; i < Num; i++)
			{
				if(!apCloseCCharacters[i]->IsAlive() || apCloseCCharacters[i]->GetPlayer()->GetTeam() == -1 || GameServer()->Collision()->IntersectLine(F->m_Pos, apCloseCCharacters[i]->m_Pos, NULL, NULL))
					continue;
				
				if(apCloseCCharacters[i]->GetPlayer()->GetTeam() == F->m_Team)
				{
					// return the flag
					if(!F->m_AtStand)
					{
						CCharacter *pChr = apCloseCCharacters[i];
						pChr->GetPlayer()->m_Score += 1;

						char aBuf[256];
						str_format(aBuf, sizeof(aBuf), "flag_return player='%d:%s'",
							pChr->GetPlayer()->GetCID(),
							Server()->ClientName(pChr->GetPlayer()->GetCID()));
						GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf);

						GameServer()->CreateSoundGlobal(SOUND_CTF_RETURN);
						F->Reset();
					}
				}
				else
				{
					// take the flag
					if(F->m_AtStand)
					{
						m_aTeamscore[fi^1]++;
						F->m_GrabTick = Server()->Tick();
					}
					
					F->m_AtStand = 0;
					F->m_pCarryingCharacter = apCloseCCharacters[i];
					F->m_pCarryingCharacter->GetPlayer()->m_Score += 1;

					char aBuf[256];
					str_format(aBuf, sizeof(aBuf), "flag_grab player='%d:%s'",
						F->m_pCarryingCharacter->GetPlayer()->GetCID(),
						Server()->ClientName(F->m_pCarryingCharacter->GetPlayer()->GetCID()));
					GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf);
					
					for(int c = 0; c < MAX_CLIENTS; c++)
					{
						if(!GameServer()->m_apPlayers[c])
							continue;
							
						if(GameServer()->m_apPlayers[c]->GetTeam() == fi)
							GameServer()->CreateSoundGlobal(SOUND_CTF_GRAB_EN, GameServer()->m_apPlayers[c]->GetCID());
						else
							GameServer()->CreateSoundGlobal(SOUND_CTF_GRAB_PL, GameServer()->m_apPlayers[c]->GetCID());
					}
					break;
				}
			}
			
			if(!F->m_pCarryingCharacter && !F->m_AtStand)
			{
				if(Server()->Tick() > F->m_DropTick + Server()->TickSpeed()*30)
				{
					GameServer()->CreateSoundGlobal(SOUND_CTF_RETURN);
					F->Reset();
				}
				else
				{
					F->m_Vel.y += GameServer()->m_World.m_Core.m_Tuning.m_Gravity;
					GameServer()->Collision()->MoveBox(&F->m_Pos, &F->m_Vel, vec2(F->ms_PhysSize, F->ms_PhysSize), 0.5f);
				}
			}
		}
	}
}
コード例 #4
0
//-----------------------------------------------
// CFaberPhrase apply
//-----------------------------------------------
void CFaberPhrase::apply()
{
	H_AUTO(CFaberPhrase_apply);
	
	CCharacter * c = dynamic_cast< CCharacter * > ( CEntityBaseManager::getEntityBasePtr( _ActorRowId ) );
	if( c == 0 )
	{
		nlwarning("<CFaberPhrase::apply> Player character not found but his crafting action still running!!!");
		stop();
		return;
	}

	// apply wearing equipment penalty on Recommended skill
	_Recommended -= (uint32)(_Recommended * c->wearMalus() * WearMalusCraftFactor);

	const CStaticBrick * plan = CSheets::getSBrickForm( c->getCraftPlan() );
	if( plan == 0 )
	{
		nlwarning("<CFaberPhrase::apply> Can't found static form of craft plan %s", c->getCraftPlan().toString().c_str() );
		PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "UNKNOWN_CRAFT_PLAN");
		stop();
		return;
	}
	_RootFaberPlan = plan;

	// TODO check compatibility of Rms with plan
	// temporary only check number of Mp match with plan

	sint32 nbMp = (sint32)_Mps.size();

	uint32 nbMpNeedeInPlan = 0;
	uint32 neededMp = (uint32)_RootFaberPlan->Faber->NeededMps.size();
	for( uint mp = 0; mp < neededMp; ++mp )
	{
		//for each type of Mp needed
		nbMpNeedeInPlan += _RootFaberPlan->Faber->NeededMps[ mp ].Quantity;
	}

	if( nbMpNeedeInPlan != _Mps.size() )
	{
		nlwarning("<CFaberPhrase::apply> Craft plan %s need %d Raw Material and client send %d Raw Material", c->getCraftPlan().toString().c_str(), _RootFaberPlan->Faber->NeededMps.size(), _Mps.size() );
		PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "RAW_MATERIAL_MISSING");
		stop();
		return;
	}

	nbMp = (sint32)_MpsFormula.size();
	
	uint32 nbMpForumulaNeedeInPlan = 0;
	neededMp = (uint32)_RootFaberPlan->Faber->NeededMpsFormula.size();
	for( uint mp = 0; mp < neededMp; ++mp )
	{
		//for each type of Mp needed
		nbMpForumulaNeedeInPlan += _RootFaberPlan->Faber->NeededMpsFormula[ mp ].Quantity;
	}
	
	if( nbMpForumulaNeedeInPlan != _MpsFormula.size() )
	{
		nlwarning("<CFaberPhrase::apply> Craft plan %s need %d Raw Material Formula and client send %d Raw Material Formula", c->getCraftPlan().toString().c_str(), _RootFaberPlan->Faber->NeededMpsFormula.size(), _MpsFormula.size() );
		PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "RAW_MATERIAL_MISSING");
		stop();
		return;
	}

	// Check skill on faber plan
	if( _RootFaberPlan->getSkill(0) == SKILLS::unknown )
	{
		nlwarning("<CFaberPhrase::apply> Craft plan %s contains an invalid skill", c->getCraftPlan().toString().c_str() );
		PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "INVALID_CRAFT_PLAN");
		stop();
		return;
	}

	_CraftedItemStaticForm = CSheets::getForm( plan->Faber->CraftedItem );
	if( _CraftedItemStaticForm == 0 )
	{
		nlwarning("<CFaberPhrase::apply> Can't found static form of crafted item %s", plan->Faber->CraftedItem.toString().c_str() );
		PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "UNKNOWN_CRAFTED_ITEM");
		stop();
		return;
	}

	// build the craft action
	_FaberAction = IFaberActionFactory::buildAction( _ActorRowId, this, _CraftedItemStaticForm->Type );
	if ( !_FaberAction )
	{
		nlwarning( "<CFaberPhrase build> could not build action for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() );
		stop();
		return;
	}
	
	neededMp = _RootFaberPlan->Faber->NeededMps.size();
    EGSPD::CPeople::TPeople civRestriction = _RootFaberPlan->CivRestriction;
	uint32 usedMp=0;
	vector< const CStaticItem * > usedMps = _Mps;

	for( uint mp = 0; mp < neededMp; ++mp )
	{
		nlinfo("MP #%d\n", mp);
		//for each type of Mp needed
		for( uint k = 0; k < _RootFaberPlan->Faber->NeededMps[ mp ].Quantity; ++k )
		{
		   nlinfo(" usedmps : %d", usedMps.size());
		   bool found_mp = false;
		   for(uint u_mp = 0; u_mp < usedMps.size(); ++u_mp)
		   {
			   // for each Mp of one type (we have Quantity by type)
			   uint32 NumMpParameters = (uint32)usedMps[u_mp]->Mp->MpFaberParameters.size();
				
			   // for each Faber parameters in Mp
			   for( uint j = 0; j < NumMpParameters; ++j )
			   {
					// check if Mp Type match with Faber waiting Type
					if( _RootFaberPlan->Faber->NeededMps[mp].MpType == usedMps[u_mp]->Mp->MpFaberParameters[j].MpFaberType )
					{
						found_mp = true;
						usedMp++;
						break;
					}
			   }

			   if (found_mp)
			   {

				   // Bypass if : Plan is common
					if ( civRestriction != EGSPD::CPeople::Common )
					{
						   switch (usedMps[u_mp]->Mp->Ecosystem)
						   {
							   // I can't found some thing to do this ugly translation.
							   case ECOSYSTEM::desert:
								   if (civRestriction != EGSPD::CPeople::Fyros)
								   {
			   							nlwarning( "<CFaberPhrase build> bad civilisation mp for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() );
										stop();
										return;
								   }
								   break;
							   case ECOSYSTEM::forest:
								   if (civRestriction != EGSPD::CPeople::Matis)
								   {
			   							nlwarning( "<CFaberPhrase build> bad civilisation mp for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() );
										stop();
										return;
								   }
								   break;
							   case ECOSYSTEM::lacustre:
								   if (civRestriction != EGSPD::CPeople::Tryker)
								   {
			   							nlwarning( "<CFaberPhrase build> bad civilisation mp for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() );
										stop();
										return;
								   }
								   break;
							   case ECOSYSTEM::jungle:
								   if (civRestriction != EGSPD::CPeople::Zorai)
								   {
			   							nlwarning( "<CFaberPhrase build> bad civilisation mp for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() );
										stop();
										return;
								   }
								   break;
						   }
					}
				   usedMps.erase(usedMps.begin()+u_mp);
				   break;
			   }
		   }

		   if (!found_mp)
		   {
				nlinfo("NOT FOUND : wanted %d\n", _RootFaberPlan->Faber->NeededMps[ mp ].MpType);
		   }
		}
	}
	if (!usedMps.empty())
	{
		nlinfo("final usedmps : %d", usedMps.size());
		nlwarning( "<CFaberPhrase build> could not build action for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() );
		stop();
		return;
	}

	if (usedMp != nbMpNeedeInPlan)
	{
		nlwarning( "<CFaberPhrase build> could not build action for plan brick %s", _RootFaberPlan->SheetId.toString().c_str() );
		stop();
		return;
	}

	// spend energies
	SCharacteristicsAndScores &focus = c->getScores()._PhysicalScores[SCORES::focus];
	if ( focus.Current != 0)
	{
		focus.Current = focus.Current - _FocusCost;
		if (focus.Current < 0)
			focus.Current = 0;
	}

	// apply action of the sentence
	_FaberAction->apply(this);
	_CraftedItem = 0;
}//CFaberPhrase apply
コード例 #5
0
void CCharacter::FireWeapon()
{
	if(m_ReloadTimer != 0)
		return;

	DoWeaponSwitch();
	vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY));

	bool FullAuto = false;
	if(m_ActiveWeapon == WEAPON_GRENADE || m_ActiveWeapon == WEAPON_SHOTGUN || m_ActiveWeapon == WEAPON_RIFLE)
		FullAuto = true;


	// check if we gonna m_Fire
	bool WillFire = false;
	if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses)
		WillFire = true;
	if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_ActiveWeapon].m_Ammo)
		WillFire = true;
	if(!WillFire)
		return;
	modFireAction mfa;
	for(std::set<mod *>::iterator i = modLoaderGetter::modloader_main->modList.begin(); i != modLoaderGetter::modloader_main->modList.end(); i++){
		modFireAction mfa2 = (*i)->onFire(m_ActiveWeapon, this);
		if(!mfa2.doAmmoDecrease){
			mfa.doAmmoDecrease = false;
		}
		if(mfa2.AmmoDecreaseValue != 1){
			mfa.AmmoDecreaseValue = mfa2.AmmoDecreaseValue;
		}
		if(mfa2.breakShoot){
			mfa.breakShoot = true;
		}
	}
	if(mfa.breakShoot) return;
	// check for ammo
	if(!m_aWeapons[m_ActiveWeapon].m_Ammo)
	{
		// 125ms is a magical limit of how fast a human can click
		m_ReloadTimer = 125 * Server()->TickSpeed() / 1000;
		if(m_LastNoAmmoSound+Server()->TickSpeed() <= Server()->Tick())
		{
			GameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO);
			m_LastNoAmmoSound = Server()->Tick();
		}
		return;
	}

	vec2 ProjStartPos = m_Pos+Direction*m_ProximityRadius*0.75f;

	switch(m_ActiveWeapon)
	{
		case WEAPON_HAMMER:
		{
			// reset objects Hit
			m_NumObjectsHit = 0;
			GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE);

			CCharacter *apEnts[MAX_CLIENTS];
			int Hits = 0;
			int Num = GameServer()->m_World.FindEntities(ProjStartPos, m_ProximityRadius*0.5f, (CEntity**)apEnts,
														MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER);

			for (int i = 0; i < Num; ++i)
			{
				CCharacter *pTarget = apEnts[i];

				if ((pTarget == this) || GameServer()->Collision()->IntersectLine(ProjStartPos, pTarget->m_Pos, NULL, NULL))
					continue;

				// set his velocity to fast upward (for now)
				if(length(pTarget->m_Pos-ProjStartPos) > 0.0f)
					GameServer()->CreateHammerHit(pTarget->m_Pos-normalize(pTarget->m_Pos-ProjStartPos)*m_ProximityRadius*0.5f);
				else
					GameServer()->CreateHammerHit(ProjStartPos);

				vec2 Dir;
				if (length(pTarget->m_Pos - m_Pos) > 0.0f)
					Dir = normalize(pTarget->m_Pos - m_Pos);
				else
					Dir = vec2(0.f, -1.f);

				pTarget->TakeDamage(vec2(0.f, -1.f) + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage,
					m_pPlayer->GetCID(), m_ActiveWeapon);
				Hits++;
			}

			// if we Hit anything, we have to wait for the reload
			if(Hits)
				m_ReloadTimer = Server()->TickSpeed()/3;

		} break;

		case WEAPON_GUN:
		{
			CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GUN,
				m_pPlayer->GetCID(),
				ProjStartPos,
				Direction,
				(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime),
				1, 0, 0, -1, WEAPON_GUN);

			// pack the Projectile and send it to the client Directly
			CNetObj_Projectile p;
			pProj->FillInfo(&p);

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(1);
			for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
				Msg.AddInt(((int *)&p)[i]);

			Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE);
		} break;

		case WEAPON_SHOTGUN:
		{
			int ShotSpread = 2;

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(ShotSpread*2+1);

			for(int i = -ShotSpread; i <= ShotSpread; ++i)
			{
				float Spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f};
				float a = GetAngle(Direction);
				a += Spreading[i+2];
				float v = 1-(absolute(i)/(float)ShotSpread);
				float Speed = mix((float)GameServer()->Tuning()->m_ShotgunSpeeddiff, 1.0f, v);
				CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_SHOTGUN,
					m_pPlayer->GetCID(),
					ProjStartPos,
					vec2(cosf(a), sinf(a))*Speed,
					(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_ShotgunLifetime),
					1, 0, 0, -1, WEAPON_SHOTGUN);

				// pack the Projectile and send it to the client Directly
				CNetObj_Projectile p;
				pProj->FillInfo(&p);

				for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
					Msg.AddInt(((int *)&p)[i]);
			}

			Server()->SendMsg(&Msg, 0,m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE);
		} break;

		case WEAPON_GRENADE:
		{
			CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GRENADE,
				m_pPlayer->GetCID(),
				ProjStartPos,
				Direction,
				(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime),
				1, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE);

			// pack the Projectile and send it to the client Directly
			CNetObj_Projectile p;
			pProj->FillInfo(&p);

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(1);
			for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
				Msg.AddInt(((int *)&p)[i]);
			Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE);
		} break;

		case WEAPON_RIFLE:
		{
			new CLaser(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID());
			GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE);
		} break;

		case WEAPON_NINJA:
		{
			// reset Hit objects
			m_NumObjectsHit = 0;

			m_Ninja.m_ActivationDir = Direction;
			m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * Server()->TickSpeed() / 1000;
			m_Ninja.m_OldVelAmount = length(m_Core.m_Vel);

			GameServer()->CreateSound(m_Pos, SOUND_NINJA_FIRE);
		} break;

	}

	m_AttackTick = Server()->Tick();

	if(mfa.doAmmoDecrease && m_aWeapons[m_ActiveWeapon].m_Ammo - mfa.AmmoDecreaseValue >= 0) // -1 == unlimited
		m_aWeapons[m_ActiveWeapon].m_Ammo -= mfa.AmmoDecreaseValue;

	if(!m_ReloadTimer)
		m_ReloadTimer = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay * Server()->TickSpeed() / 1000;
}
コード例 #6
0
void CGameControllerMOD::Tick()
{
	IGameController::Tick();
	
	//Check session
	{
		CPlayerIterator<PLAYERITER_ALL> Iter(GameServer()->m_apPlayers);
		while(Iter.Next())
		{
			//Update session
			IServer::CClientSession* pSession = Server()->GetClientSession(Iter.ClientID());
			if(pSession)
			{
				if(!Server()->GetClientMemory(Iter.ClientID(), CLIENTMEMORY_SESSION_PROCESSED))
				{
					//The client already participated to this round,
					//and he exit the game as infected.
					//To avoid cheating, we assign to him the same class again.
					if(
						m_InfectedStarted &&
						pSession->m_RoundId == m_RoundId &&
						pSession->m_Class > END_HUMANCLASS
					)
					{
						Iter.Player()->SetClass(pSession->m_Class);
					}
					
					Server()->SetClientMemory(Iter.ClientID(), CLIENTMEMORY_SESSION_PROCESSED, true);
				}
				
				pSession->m_Class = Iter.Player()->GetClass();
				pSession->m_RoundId = GameServer()->m_pController->GetRoundId();
			}
		}
	}
	
	UpdatePlayerCounter();
	
	m_InfectedStarted = false;
	
	//If the game can start ...
	if(m_GameOverTick == -1 && m_HumanCounter + m_InfectedCounter >= 2)
	{
		//If the infection started
		if(IsInfectionStarted())
		{
			bool StartInfectionTrigger = (m_RoundStartTick + Server()->TickSpeed()*10 == Server()->Tick());
			
			GameServer()->EnableTargetToKill();
			
			if(m_pHeroFlag)
				m_pHeroFlag->Show();
			
			m_InfectedStarted = true;
	
			CPlayerIterator<PLAYERITER_INGAME> Iter(GameServer()->m_apPlayers);
			while(Iter.Next())
			{
				if(Iter.Player()->GetClass() == PLAYERCLASS_NONE)
				{
					if(StartInfectionTrigger)
					{
						Iter.Player()->SetClass(ChooseHumanClass(Iter.Player()));
						if(Iter.Player()->GetCharacter())
							Iter.Player()->GetCharacter()->IncreaseArmor(10);
					}
					else
						Iter.Player()->StartInfection();
				}
			}
			
			int NumNeededInfection = m_NumFirstInfected;
			
			while(m_InfectedCounter < NumNeededInfection)
			{
				float InfectionProb = 1.0/static_cast<float>(m_HumanCounter);
				float random = frandom();
				
				//Fair infection
				bool FairInfectionFound = false;
				
				Iter.Reset();
				while(Iter.Next())
				{
					if(Iter.Player()->IsInfected()) continue;
					
					if(!Server()->IsClientInfectedBefore(Iter.ClientID()))
					{
						Server()->InfecteClient(Iter.ClientID());
						Iter.Player()->StartInfection();
						m_InfectedCounter++;
						m_HumanCounter--;
						
						GameServer()->SendChatTarget_Localization(-1, CHATCATEGORY_INFECTION, _("{str:VictimName} has been infected"),
							"VictimName", Server()->ClientName(Iter.ClientID()),
							NULL
						);
						FairInfectionFound = true;
						break;
					}
				}
				
				//Unfair infection
				if(!FairInfectionFound)
				{
					Iter.Reset();
					while(Iter.Next())
					{
						if(Iter.Player()->IsInfected()) continue;
						
						if(random < InfectionProb)
						{
							Server()->InfecteClient(Iter.ClientID());
							Iter.Player()->StartInfection();
							m_InfectedCounter++;
							m_HumanCounter--;
							
							GameServer()->SendChatTarget_Localization(-1, CHATCATEGORY_INFECTION, _("{str:VictimName} has been infected"), "VictimName", Server()->ClientName(Iter.ClientID()), NULL);
							
							break;
						}
						else
						{
							random -= InfectionProb;
						}
					}
				}
			}
		}
		else
		{
			if(m_pHeroFlag)
				m_pHeroFlag->Show();
			
			GameServer()->DisableTargetToKill();
			
			CPlayerIterator<PLAYERITER_SPECTATORS> IterSpec(GameServer()->m_apPlayers);
			while(IterSpec.Next())
			{
				IterSpec.Player()->SetClass(PLAYERCLASS_NONE);
			}
		}
		
		//Win check
		if(m_InfectedStarted && m_HumanCounter == 0 && m_InfectedCounter > 1)
		{			
			int Seconds = (Server()->Tick()-m_RoundStartTick)/((float)Server()->TickSpeed());
			
			GameServer()->SendChatTarget_Localization(-1, CHATCATEGORY_INFECTED, _("Infected won the round in {sec:RoundDuration}"), "RoundDuration", &Seconds, NULL);
			
			EndRound();
		}
		
		//Start the final explosion if the time is over
		if(m_InfectedStarted && !m_ExplosionStarted && g_Config.m_SvTimelimit > 0 && (Server()->Tick()-m_RoundStartTick) >= g_Config.m_SvTimelimit*Server()->TickSpeed()*60)
		{
			for(CCharacter *p = (CCharacter*) GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER); p; p = (CCharacter *)p->TypeNext())
			{
				if(p->IsInfected())
				{
					GameServer()->SendEmoticon(p->GetPlayer()->GetCID(), EMOTICON_GHOST);
				}
				else
				{
					GameServer()->SendEmoticon(p->GetPlayer()->GetCID(), EMOTICON_EYES);
				}
			}
			m_ExplosionStarted = true;
		}
		
		//Do the final explosion
		if(m_ExplosionStarted)
		{		
			bool NewExplosion = false;
			
			for(int j=0; j<m_MapHeight; j++)
			{
				for(int i=0; i<m_MapWidth; i++)
				{
					if((m_GrowingMap[j*m_MapWidth+i] & 1) && (
						(i > 0 && m_GrowingMap[j*m_MapWidth+i-1] & 2) ||
						(i < m_MapWidth-1 && m_GrowingMap[j*m_MapWidth+i+1] & 2) ||
						(j > 0 && m_GrowingMap[(j-1)*m_MapWidth+i] & 2) ||
						(j < m_MapHeight-1 && m_GrowingMap[(j+1)*m_MapWidth+i] & 2)
					))
					{
						NewExplosion = true;
						m_GrowingMap[j*m_MapWidth+i] |= 8;
						m_GrowingMap[j*m_MapWidth+i] &= ~1;
						if(rand()%10 == 0)
						{
							vec2 TilePos = vec2(16.0f, 16.0f) + vec2(i*32.0f, j*32.0f);
							GameServer()->CreateExplosion(TilePos, -1, WEAPON_GAME, true);
							GameServer()->CreateSound(TilePos, SOUND_GRENADE_EXPLODE);
						}
					}
				}
			}
			
			for(int j=0; j<m_MapHeight; j++)
			{
				for(int i=0; i<m_MapWidth; i++)
				{
					if(m_GrowingMap[j*m_MapWidth+i] & 8)
					{
						m_GrowingMap[j*m_MapWidth+i] &= ~8;
						m_GrowingMap[j*m_MapWidth+i] |= 2;
					}
				}
			}
			
			for(CCharacter *p = (CCharacter*) GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER); p; p = (CCharacter *)p->TypeNext())
			{
				if(!p->IsInfected())
					continue;
				
				int tileX = static_cast<int>(round(p->m_Pos.x))/32;
				int tileY = static_cast<int>(round(p->m_Pos.y))/32;
				
				if(tileX < 0) tileX = 0;
				if(tileX >= m_MapWidth) tileX = m_MapWidth-1;
				if(tileY < 0) tileY = 0;
				if(tileY >= m_MapHeight) tileY = m_MapHeight-1;
				
				if(m_GrowingMap[tileY*m_MapWidth+tileX] & 2 && p->GetPlayer())
				{
					p->Die(p->GetPlayer()->GetCID(), WEAPON_GAME);
				}
			}
		
			//If no more explosions, game over, decide who win
			if(!NewExplosion)
			{
				if(m_HumanCounter)
				{
					GameServer()->SendChatTarget_Localization_P(-1, CHATCATEGORY_HUMANS, m_HumanCounter, _P("One human won the round", "{int:NumHumans} humans won the round"), "NumHumans", &m_HumanCounter, NULL);
					
					CPlayerIterator<PLAYERITER_INGAME> Iter(GameServer()->m_apPlayers);
					while(Iter.Next())
					{
						if(!Iter.Player()->IsInfected())
						{
							//TAG_SCORE
							Server()->RoundStatistics()->OnScoreEvent(Iter.ClientID(), SCOREEVENT_HUMAN_SURVIVE, Iter.Player()->GetClass());
							Server()->RoundStatistics()->SetPlayerAsWinner(Iter.ClientID());
							GameServer()->SendScoreSound(Iter.ClientID());
							Iter.Player()->m_WinAsHuman++;
							
							GameServer()->SendChatTarget_Localization(Iter.ClientID(), CHATCATEGORY_SCORE, _("You have survived, +5 points"), NULL);
						}
					}
				}
				else
				{
					int Seconds = g_Config.m_SvTimelimit*60;
					GameServer()->SendChatTarget_Localization(-1, CHATCATEGORY_INFECTED, _("Infected won the round in {sec:RoundDuration}"), "RoundDuration", &Seconds, NULL);
				}
				
				EndRound();
			}
		}
	}
	else
	{
		GameServer()->DisableTargetToKill();
		
		if(m_pHeroFlag)
			m_pHeroFlag->Show();
		
		m_RoundStartTick = Server()->Tick();
	}
}
コード例 #7
0
void CAIActionReactToDanger::ActivateAction( CAI* pAI, CAIWorldState& wsWorldStateGoal )
{
	super::ActivateAction( pAI, wsWorldStateGoal );

	// Bail if we are not aware of danger.

	CAIWMFact factQuery;
	factQuery.SetFactType( kFact_Danger );
	CAIWMFact* pFact = pAI->GetAIWorkingMemory()->FindWMFact( factQuery );
	if( !pFact )
	{
		return;
	}

	// Set animate state.

	pAI->SetState( kState_Animate );

	// Set flinch animation.

	CAnimationProps	animProps;
	animProps.Set( kAPG_Posture, kAP_POS_Crouch );
	animProps.Set( kAPG_Weapon, pAI->GetAIBlackBoard()->GetBBPrimaryWeaponProp() );
	animProps.Set( kAPG_WeaponPosition, kAP_WPOS_Up );
	animProps.Set( kAPG_Activity, kAP_ATVT_Distress );
	animProps.Set( kAPG_Action, kAP_ACT_Idle );

	CAIStateAnimate* pStateAnimate = (CAIStateAnimate*)( pAI->GetState() );
	pStateAnimate->SetAnimation( animProps, !LOOP );

	// Do NOT play a threat sound if threatened by a Turret.
	// Instead, allow turret targeting to play something appropriate.

	if( IsPlayer( pFact->GetSourceObject() ) )
	{
		CPlayerObj* pPlayer = (CPlayerObj*)g_pLTServer->HandleToObject( pFact->GetSourceObject() );
		if( pPlayer && pPlayer->GetTurret() )
		{
			return;
		}
	}

	// Play threat sound.

	// "Fire!"

	if( IsAINode( pFact->GetSourceObject() ) )
	{
		EnumAISoundType eAISound = kAIS_Danger;
		AINode* pNode = (AINode*)g_pLTServer->HandleToObject( pFact->GetSourceObject() );
		if( pNode && pNode->GetType() == kNode_Stimulus )
		{
			AINodeStimulus* pNodeStim = (AINodeStimulus*)pNode;
			if( pNodeStim )
			{
				eAISound = pNodeStim->GetAISoundType();
			}
		}
		g_pAISoundMgr->RequestAISound( pAI->m_hObject, eAISound, kAISndCat_Event, NULL, 0.f );
	}

	// "Watch out grenade!"
	// "Shit!"

	else if( IsKindOf( pFact->GetSourceObject(), "CProjectile" ) )
	{
		// Don't say anything if ally threw grenade.

		CProjectile* pProjectile = (CProjectile*)g_pLTServer->HandleToObject( pFact->GetSourceObject() );
		if( pProjectile && IsCharacter( pProjectile->GetFiredFrom() ) )
		{
			CCharacter *pChar = (CCharacter*)g_pLTServer->HandleToObject( pProjectile->GetFiredFrom() );
			if( pChar && kCharStance_Like != g_pCharacterDB->GetStance( pAI->GetAlignment(), pChar->GetAlignment() ) )
			{
				ENUM_AI_SQUAD_ID eSquad = g_pAICoordinator->GetSquadID( pAI->m_hObject );
				CAISquad* pSquad = g_pAICoordinator->FindSquad( eSquad );
				if( pSquad && pSquad->GetNumSquadMembers() > 1 )
				{
					g_pAISoundMgr->RequestAISound( pAI->m_hObject, kAIS_GrenadeThreat, kAISndCat_Event, NULL, 0.f );
				}
				else {
					g_pAISoundMgr->RequestAISound( pAI->m_hObject, kAIS_GrenadeThreatAlone, kAISndCat_Event, NULL, 0.f );
				}
			}
		}
	}

	// "Shit"

	else 
	{
		g_pAISoundMgr->RequestAISound( pAI->m_hObject, kAIS_GrenadeThreatAlone, kAISndCat_Event, NULL, 0.f );
	}



	// Search for the source of the danger.

	LTVector vDangerPos = pFact->GetPos();
	SearchForDangerOrigin( pAI, vDangerPos );
}
コード例 #8
0
ファイル: AIBrain.cpp プロジェクト: Arc0re/lithtech
void CAIBrain::GetDodgeStatus(DodgeStatus* peDodgeStatus, Direction* peDirection, DodgeAction* peDodgeAction, uint32* pdwNode)
{
	if ( !GetAI()->HasTarget() || !GetAI()->HasLastVolume() ) 
	{
		*peDodgeStatus = m_eDodgeStatusLast = eDodgeStatusOk;
		return;
	}

	if ( g_pLTServer->GetTime() >= m_fDodgeStatusCheckTimeVector )
	{
		m_fDodgeStatusCheckTimeVector = g_pLTServer->GetTime() + LOWER_BY_DIFFICULTY(m_pBrain->fDodgeVectorCheckTime);

		if ( GetRandom(0.0f, 1.0f) <= RAISE_BY_DIFFICULTY(m_pBrain->fDodgeVectorCheckChance) )
		{
			if ( GetAI()->GetTarget()->IsVisiblePartially() )
			{
				CCharacter* pCharacter = (CCharacter*)g_pLTServer->HandleToObject(GetAI()->GetTarget()->GetObject());
				if ( pCharacter->HasDangerousWeapon() )
				{
					LTRotation rRot;
					LTVector vNull, vForward;
					g_pLTServer->GetObjectRotation(GetAI()->GetTarget()->GetObject(), &rRot);
					g_pMathLT->GetRotationVectors(rRot, vNull, vNull, vForward);

					LTVector vDir;
					vDir = GetAI()->GetPosition() - GetAI()->GetTarget()->GetPosition();
					vDir.y = 0;
					vDir.Norm();

					// TODO: bute this

					const static LTFLOAT fThreshhold = 0.95f;

					if ( (vDir.Dot(vForward) > fThreshhold) && (GetAI()->GetForwardVector().Dot(vForward) < -fThreshhold) )
					{
						LTFLOAT fCheckDistance;

						LTFLOAT fRandom = GetRandom(0.0f, 1.0f);

						if ( fRandom > m_pBrain->fDodgeVectorCoverChance )
						{
							if ( fRandom > (m_pBrain->fDodgeVectorCoverChance + m_pBrain->fDodgeVectorRollChance) )
							{
								*peDodgeAction = eDodgeActionShuffle;
								fCheckDistance = 109.0f;
							}
							else
							{
								*peDodgeAction = eDodgeActionRoll;
								fCheckDistance = 140.0f;
							}

							// MAKE SURE WE WON'T DODGE OUT OF THE VOLUME 
							if ( GetAI()->GetLastVolume()->Inside2d(GetAI()->GetPosition()+GetAI()->GetRightVector()*fCheckDistance, GetAI()->GetRadius()) )
							{
								*peDirection = eDirectionRight;
								*peDodgeStatus = m_eDodgeStatusLast = eDodgeStatusVector;
								return;
							}
							else if ( GetAI()->GetLastVolume()->Inside2d(GetAI()->GetPosition()-GetAI()->GetRightVector()*fCheckDistance, GetAI()->GetRadius()) )
							{
								*peDirection = eDirectionLeft;
								*peDodgeStatus = m_eDodgeStatusLast = eDodgeStatusVector;
								return;
							}
							else
							{
								*peDodgeStatus = m_eDodgeStatusLast = eDodgeStatusOk;
								return;
							}
						}
						else
						{
							CAINode* pNode = g_pAINodeMgr->FindNearestCoverFromThreat(GetAI()->GetPosition(), GetAI()->GetTarget()->GetObject());

							if ( pNode )
							{
								*peDodgeAction = eDodgeActionCover;
								*peDodgeStatus = m_eDodgeStatusLast = eDodgeStatusVector;
								*pdwNode = pNode->GetID();
							}
							else
							{
								*peDodgeStatus = m_eDodgeStatusLast = eDodgeStatusOk;
							}
							return;
						}
					}
				}
			}
		}
	}

	if ( g_pLTServer->GetTime() >= m_fDodgeStatusCheckTimeProjectile )
	{
		m_fDodgeStatusCheckTimeProjectile = g_pLTServer->GetTime() + RAISE_BY_DIFFICULTY(m_pBrain->fDodgeProjectileCheckTime);

		if ( GetRandom(0.0f, 1.0f) <= RAISE_BY_DIFFICULTY(m_pBrain->fDodgeProjectileCheckChance) )
		{
			CGrenade* pGrenade;
			if ( FindGrenadeDangerPosition(GetAI()->GetPosition(), 40000.0f, &m_vDodgeProjectilePosition, &pGrenade) )
			{
				FREE_HSTRING(m_hstrDodgeProjectileName);
				// $STRING
				m_hstrDodgeProjectileName = g_pLTServer->CreateString(g_pLTServer->GetObjectName(pGrenade->m_hObject));

				*peDodgeStatus = m_eDodgeStatusLast = eDodgeStatusProjectile;
				*peDodgeAction = eDodgeActionFlee;

				return;
			}
		}
	}

	*peDodgeStatus = m_eDodgeStatusLast = eDodgeStatusOk;
	return;
}
コード例 #9
0
void CLobbyServerPlayer::ProcessGetCharacters(const PacketData& packetData)
{
	CLog::GetInstance().LogMessage(LOG_NAME, "GetCharacters");

	if(m_dbConnection.IsEmpty())
	{
		CLog::GetInstance().LogMessage(LOG_NAME, "No database connection available. Bailing.");
		m_disconnect = true;
		return;
	}

	PacketData outgoingPacket(std::begin(g_characterListPacket), std::end(g_characterListPacket));

	CCharacter character;

	try
	{
		auto query = string_format("SELECT * FROM ffxiv_characters WHERE userId = %d", m_userId);
		auto result = m_dbConnection.Query(query.c_str());
		if(result.GetRowCount() != 0)
		{
			character = CCharacter(result);
		}
	}
	catch(const std::exception& exception)
	{
		CLog::GetInstance().LogError(LOG_NAME, "Failed to fetch characters for user (id = %d): %s", m_userId, exception.what());
		m_disconnect = true;
		return;
	}

	PacketData characterData(std::begin(g_characterData), std::end(g_characterData));
	
	characterData[0x21] = CCharacter::GetModelFromTribe(character.tribe);
	characterData[0x9F] = character.tribe;
	characterData[0xC7] = character.guardian;
	characterData[0xC8] = character.birthMonth;
	characterData[0xC9] = character.birthDay;
	characterData[0xE8] = character.allegiance;

	*reinterpret_cast<uint32*>(&characterData[0x25]) = character.size;				//size

	*reinterpret_cast<uint32*>(&characterData[0x29]) = character.GetColorInfo();	//hairColor + skinColor
	*reinterpret_cast<uint32*>(&characterData[0x2D]) = character.GetFaceInfo();		//face Stuff?
	*reinterpret_cast<uint32*>(&characterData[0x31]) = character.hairStyle << 10;	//hair model
	*reinterpret_cast<uint32*>(&characterData[0x35]) = character.voice;				//voice
	*reinterpret_cast<uint32*>(&characterData[0x39]) = character.weapon1;			//weapon1
	*reinterpret_cast<uint32*>(&characterData[0x3D]) = character.weapon2;			//weapon2
	*reinterpret_cast<uint32*>(&characterData[0x55]) = character.headGear;			//headGear
	*reinterpret_cast<uint32*>(&characterData[0x59]) = character.bodyGear;			//bodyGear
	*reinterpret_cast<uint32*>(&characterData[0x5D]) = character.legsGear;			//legsGear
	*reinterpret_cast<uint32*>(&characterData[0x61]) = character.handsGear;			//handsGear
	*reinterpret_cast<uint32*>(&characterData[0x65]) = character.feetGear;			//feetGear
	*reinterpret_cast<uint32*>(&characterData[0x69]) = character.waistGear;			//waistGear
//	*reinterpret_cast<uint32*>(&characterData[0x6D]) = 0;							//???
	*reinterpret_cast<uint32*>(&characterData[0x71]) = character.rightEarGear;		//rightEarGear
	*reinterpret_cast<uint32*>(&characterData[0x75]) = character.leftEarGear;		//leftEarGear
//	*reinterpret_cast<uint32*>(&characterData[0x79]) = 0;							//???
//	*reinterpret_cast<uint32*>(&characterData[0x7D]) = 0;							//???
	*reinterpret_cast<uint32*>(&characterData[0x81]) = character.rightFingerGear;	//rightFingerGear
	*reinterpret_cast<uint32*>(&characterData[0x85]) = character.leftFingerGear;	//leftFingerGear

	auto encodedCharacterData = Framework::ToBase64(characterData.data(), characterData.size());
	std::replace(std::begin(encodedCharacterData), std::end(encodedCharacterData), '+', '-');
	std::replace(std::begin(encodedCharacterData), std::end(encodedCharacterData), '/', '_');

	static const uint32 characterInfoBase = 0x860;

	if(character.active)
	{
		for(unsigned int i = 0; i < encodedCharacterData.size(); i++)
		{
			outgoingPacket[characterInfoBase + 0x40 + i] = encodedCharacterData[i];
		}

		*reinterpret_cast<uint32*>(&outgoingPacket[characterInfoBase + 0x00]) = 0x0158E7FC;
		*reinterpret_cast<uint32*>(&outgoingPacket[characterInfoBase + 0x04]) = character.id;
		*reinterpret_cast<uint32*>(&outgoingPacket[characterInfoBase + 0x0C]) = 0x000000F4;

		//Insert character name
		for(unsigned int i = 0; i < character.name.size(); i++)
		{
			outgoingPacket[characterInfoBase + 0x10 + i] = character.name[i];
		}
		outgoingPacket[characterInfoBase + 0x10 + character.name.size()] = 0;
	}

	CPacketUtils::EncryptPacket(outgoingPacket);
	QueuePacket(outgoingPacket);
}
コード例 #10
0
void CProjectile::Tick()
{
	float Pt = (Server()->Tick()-m_StartTick-1)/(float)Server()->TickSpeed();
	float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed();
	vec2 PrevPos = GetPos(Pt);
	vec2 CurPos = GetPos(Ct);
	vec2 ColPos;
	vec2 NewPos;
	int Collide = GameServer()->Collision()->IntersectLine(PrevPos, CurPos, &ColPos, &NewPos, false);
	CCharacter *pOwnerChar = 0;



	if(m_Owner >= 0)
		pOwnerChar = GameServer()->GetPlayerChar(m_Owner);

	CCharacter *pTargetChr = GameServer()->m_World.IntersectCharacter(PrevPos, ColPos, m_Freeze ? 1.0f : 6.0f, ColPos, pOwnerChar);

	if(m_LifeSpan > -1)
		m_LifeSpan--;

	int TeamMask = -1;
	bool isWeaponCollide = false;
	if
	(
			pOwnerChar &&
			pTargetChr &&
			pOwnerChar->IsAlive() &&
			pTargetChr->IsAlive() &&
			!pTargetChr->CanCollide(m_Owner)
			)
	{
			isWeaponCollide = true;
			//TeamMask = OwnerChar->Teams()->TeamMask( OwnerChar->Team());
	}
	if (pOwnerChar && pOwnerChar->IsAlive())
	{
			TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner);
	}
	if( ((pTargetChr && (pOwnerChar ? !(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || m_Owner == -1 || pTargetChr == pOwnerChar)) || Collide || GameLayerClipped(CurPos)) && !isWeaponCollide)
	{
		if(m_Explosive/*??*/ && (!pTargetChr || (pTargetChr && !m_Freeze)))
		{
			GameServer()->CreateExplosion(ColPos, m_Owner, m_Weapon, m_Owner == -1, (!pTargetChr ? -1 : pTargetChr->Team()),
			(m_Owner != -1)? TeamMask : -1);
			GameServer()->CreateSound(ColPos, m_SoundImpact,
			(m_Owner != -1)? TeamMask : -1);
		}
		else if(pTargetChr && m_Freeze && ((m_Layer == LAYER_SWITCH && GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[pTargetChr->Team()]) || m_Layer != LAYER_SWITCH))
			pTargetChr->Freeze();
		if(Collide && m_Bouncing != 0)
		{
			m_StartTick = Server()->Tick();
			m_Pos = NewPos+(-(m_Direction*4));
			if (m_Bouncing == 1)
				m_Direction.x = -m_Direction.x;
			else if(m_Bouncing == 2)
				m_Direction.y =- m_Direction.y;
			if (fabs(m_Direction.x) < 1e-6)
				m_Direction.x = 0;
			if (fabs(m_Direction.y) < 1e-6)
				m_Direction.y = 0;
			m_Pos += m_Direction;
		}
		else if (m_Weapon == WEAPON_GUN)
		{
			GameServer()->CreateDamageInd(CurPos, -atan2(m_Direction.x, m_Direction.y), 10, (m_Owner != -1)? TeamMask : -1);
			GameServer()->m_World.DestroyEntity(this);
		}
		else
			if (!m_Freeze)
				GameServer()->m_World.DestroyEntity(this);
	}
	if(m_LifeSpan == -1)
	{
		GameServer()->m_World.DestroyEntity(this);
	}
}
コード例 #11
0
ファイル: pickup.cpp プロジェクト: eeeee/ddnet
void CPickup::Tick()
{
	Move();
	/*// wait for respawn
	if(m_SpawnTick > 0)
	{
		if(Server()->Tick() > m_SpawnTick)
		{
			// respawn
			m_SpawnTick = -1;

			if(m_Type == POWERUP_WEAPON)
				GameServer()->CreateSound(m_Pos, SOUND_WEAPON_SPAWN);
		}
		else
			return;
	}*/
	// Check if a player intersected us
	CCharacter *apEnts[MAX_CLIENTS];
	int Num = GameWorld()->FindEntities(m_Pos, 20.0f, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER);
	for(int i = 0; i < Num; ++i) {
		CCharacter * pChr = apEnts[i];
		if(pChr && pChr->IsAlive())
		{
			if(m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[pChr->Team()]) continue;
			bool sound = false;
			// player picked us up, is someone was hooking us, let them go
			switch (m_Type)
			{
				case POWERUP_HEALTH:
					if(pChr->Freeze()) GameServer()->CreateSound(m_Pos, SOUND_PICKUP_HEALTH, pChr->Teams()->TeamMask(pChr->Team()));
					break;

				case POWERUP_ARMOR:
					if(pChr->Team() == TEAM_SUPER) continue;
					for(int i = WEAPON_SHOTGUN; i < NUM_WEAPONS; i++)
					{
						if(pChr->GetWeaponGot(i))
						{
							if(!(pChr->m_FreezeTime && i == WEAPON_NINJA))
							{
								pChr->SetWeaponGot(i, false);
								pChr->SetWeaponAmmo(i, 0);
								sound = true;
							}
						}
					}
					pChr->SetNinjaActivationDir(vec2(0,0));
					pChr->SetNinjaActivationTick(-500);
					pChr->SetNinjaCurrentMoveTime(0);
					if (sound)
					{
						pChr->SetLastWeapon(WEAPON_GUN);
						GameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR, pChr->Teams()->TeamMask(pChr->Team()));
					}
					if(!pChr->m_FreezeTime && pChr->GetActiveWeapon() >= WEAPON_SHOTGUN)
						pChr->SetActiveWeapon(WEAPON_HAMMER);
					break;

				case POWERUP_WEAPON:

					if (m_Subtype >= 0 && m_Subtype < NUM_WEAPONS && (!pChr->GetWeaponGot(m_Subtype) || (pChr->GetWeaponAmmo(m_Subtype) != -1 && !pChr->m_FreezeTime)))
					{
						pChr->GiveWeapon(m_Subtype);

						//RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;

						if (m_Subtype == WEAPON_GRENADE)
							GameServer()->CreateSound(m_Pos, SOUND_PICKUP_GRENADE, pChr->Teams()->TeamMask(pChr->Team()));
						else if (m_Subtype == WEAPON_SHOTGUN)
							GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN, pChr->Teams()->TeamMask(pChr->Team()));
						else if (m_Subtype == WEAPON_RIFLE)
							GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN, pChr->Teams()->TeamMask(pChr->Team()));

						if (pChr->GetPlayer())
							GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), m_Subtype);

					}
					break;

			case POWERUP_NINJA:
				{
					// activate ninja on target player
					pChr->GiveNinja();
					//RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;

					/*// loop through all players, setting their emotes
					CCharacter *pC = static_cast<CCharacter *>(GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER));
					for(; pC; pC = (CCharacter *)pC->TypeNext())
					{
						if (pC != pChr)
							pC->SetEmote(EMOTE_SURPRISE, Server()->Tick() + Server()->TickSpeed());
					}*/
					break;
				}
				default:
					break;
			};

			/*if(RespawnTime >= 0)
			{
				char aBuf[256];
				str_format(aBuf, sizeof(aBuf), "pickup player='%d:%s' item=%d/%d",
					pChr->GetPlayer()->GetCID(), Server()->ClientName(pChr->GetPlayer()->GetCID()), m_Type, m_Subtype);
				GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf);
				m_SpawnTick = Server()->Tick() + Server()->TickSpeed() * RespawnTime;
			}*/
		}
	}
}
コード例 #12
0
void CCharacter::FireWeapon()
{
	if(m_ReloadTimer != 0)
		return;

	DoWeaponSwitch();
	vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY));

	bool FullAuto = false;
	if(m_ActiveWeapon == WEAPON_GRENADE || m_ActiveWeapon == WEAPON_SHOTGUN || m_ActiveWeapon == WEAPON_RIFLE || (m_ActiveWeapon == WEAPON_HAMMER && g_Config.m_SvSuperHammer))
		FullAuto = true;


	// check if we gonna fire
	bool WillFire = false;
	if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses)
		WillFire = true;

	if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_ActiveWeapon].m_Ammo)
		WillFire = true;

	if (!g_Config.m_SvNinja && m_ActiveWeapon == WEAPON_NINJA)
		WillFire = false;

	if(!WillFire)
		return;

	// check for ammo
	if(!m_aWeapons[m_ActiveWeapon].m_Ammo)
	{
		// 125ms is a magical limit of how fast a human can click
		m_ReloadTimer = 125 * Server()->TickSpeed() / 1000;
		GameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO);
		return;
	}

	vec2 ProjStartPos = m_Pos+Direction*m_ProximityRadius*0.75f;

	switch(m_ActiveWeapon)
	{
		case WEAPON_HAMMER:
		{
			// reset objects Hit
			m_NumObjectsHit = 0;
			GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE);

			CCharacter *apEnts[MAX_CLIENTS];
			int Hits = 0;
			int Num = GameServer()->m_World.FindEntities(ProjStartPos, m_ProximityRadius*0.5f, (CEntity**)apEnts,
														MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER);

			for (int i = 0; i < Num; ++i)
			{
				CCharacter *pTarget = apEnts[i];

				if ((pTarget == this) || GameServer()->Collision()->IntersectLine(ProjStartPos, pTarget->m_Pos, NULL, NULL))
					continue;

				// set his velocity to fast upward (for now)
				if(length(pTarget->m_Pos-ProjStartPos) > 0.0f)
					GameServer()->CreateHammerHit(pTarget->m_Pos-normalize(pTarget->m_Pos-ProjStartPos)*m_ProximityRadius*0.5f);
				else
					GameServer()->CreateHammerHit(ProjStartPos);

				vec2 Dir;
				if (length(pTarget->m_Pos - m_Pos) > 0.0f)
					Dir = normalize(pTarget->m_Pos - m_Pos);
				else
					Dir = vec2(0.f, -1.f);

				bool MeltHit = GameServer()->m_pController->IsTeamplay() && pTarget->GetPlayer()->GetTeam() == GetPlayer()->GetTeam() && pTarget->GetFreezeTicks() > 0;

				vec2 Force = (vec2(0.f, -1.f) + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f);
				if (!MeltHit)
				{
					Force.x *= g_Config.m_SvHammerScaleX*0.01f;
					Force.y *= g_Config.m_SvHammerScaleY*0.01f;
				}
				else
				{
					Force.x *= g_Config.m_SvMeltHammerScaleX*0.01f;
					Force.y *= g_Config.m_SvMeltHammerScaleY*0.01f;
				}

				pTarget->TakeDamage(Force, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, m_pPlayer->GetCID(), m_ActiveWeapon);
				Hits++;

				pTarget->m_HammeredBy = GetPlayer()->GetCID();

				if (MeltHit)
				{
					pTarget->Freeze(pTarget->GetFreezeTicks() - g_Config.m_SvHammerMelt * Server()->TickSpeed());
					if (pTarget->GetFreezeTicks() <= 0)
					{
						pTarget->m_MoltenBy = m_pPlayer->GetCID();
						pTarget->m_MoltenAt = -1; // we don't want the unfreezability to take effect when being molten by hammer
					}
				}
					
			}

			// if we Hit anything, we have to wait for the reload
			if(Hits)
				m_ReloadTimer = Server()->TickSpeed()/3;

		} break;

		case WEAPON_GUN:
		{
			CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GUN,
				m_pPlayer->GetCID(),
				ProjStartPos,
				Direction,
				(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime),
				1, 0, 0, -1, WEAPON_GUN);

			// pack the Projectile and send it to the client Directly
			CNetObj_Projectile p;
			pProj->FillInfo(&p);

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(1);
			for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
				Msg.AddInt(((int *)&p)[i]);

			Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE);
		} break;

		case WEAPON_SHOTGUN:
		{
			int ShotSpread = 2;

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(ShotSpread*2+1);

			for(int i = -ShotSpread; i <= ShotSpread; ++i)
			{
				float Spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f};
				float a = GetAngle(Direction);
				a += Spreading[i+2];
				float v = 1-(absolute(i)/(float)ShotSpread);
				float Speed = mix((float)GameServer()->Tuning()->m_ShotgunSpeeddiff, 1.0f, v);
				CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_SHOTGUN,
					m_pPlayer->GetCID(),
					ProjStartPos,
					vec2(cosf(a), sinf(a))*Speed,
					(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_ShotgunLifetime),
					1, 0, 0, -1, WEAPON_SHOTGUN);

				// pack the Projectile and send it to the client Directly
				CNetObj_Projectile p;
				pProj->FillInfo(&p);

				for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
					Msg.AddInt(((int *)&p)[i]);
			}

			Server()->SendMsg(&Msg, 0,m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE);
		} break;

		case WEAPON_GRENADE:
		{
			CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GRENADE,
				m_pPlayer->GetCID(),
				ProjStartPos,
				Direction,
				(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime),
				1, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE);

			// pack the Projectile and send it to the client Directly
			CNetObj_Projectile p;
			pProj->FillInfo(&p);

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(1);
			for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
				Msg.AddInt(((int *)&p)[i]);
			Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE);
		} break;

		case WEAPON_RIFLE:
		{
			new CLaser(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID());
			GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE);
		} break;

		case WEAPON_NINJA:
		{
			// reset Hit objects
			m_NumObjectsHit = 0;

			m_Ninja.m_ActivationDir = Direction;
			m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * Server()->TickSpeed() / 1000;
			m_Ninja.m_OldVelAmount = length(m_Core.m_Vel);

			GameServer()->CreateSound(m_Pos, SOUND_NINJA_FIRE);
		} break;

	}

	m_AttackTick = Server()->Tick();

	if (!g_Config.m_SvUnlimitedAmmo && m_aWeapons[m_ActiveWeapon].m_Ammo > 0)
		m_aWeapons[m_ActiveWeapon].m_Ammo--;

	if(!m_ReloadTimer)
		m_ReloadTimer = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay * Server()->TickSpeed() / 1000;
}
コード例 #13
0
//---------------------------------------------------
void CCharacterVersionAdapter::adaptToVersion11(CCharacter &character) const
{
	// delete all missions
	std::map<uint32,EGSPD::CMissionPD *>::iterator it;
	while (true)
	{
		it = character._Missions->getMissionsBegin();
		if (it == character._Missions->getMissionsEnd())
			break;
		character._Missions->deleteFromMissions( (*it).first );
	}
	
	// get the region where the user is
	CRegion * region = dynamic_cast<CRegion*> (	CZoneManager::getInstance().getPlaceFromId( character.getCurrentRegion() ) );
	if ( !region )
	{
		nlwarning("<adaptToVersion11> user%s is on invalid region %u",character.getId().toString().c_str(), character.getCurrentRegion()  );
		return;
	}
	
	vector<TAIAlias> bots;
	TAIAlias mission = CAIAliasTranslator::Invalid;
	// if the user is in newbie land, give him the appropriate newbie mission
	if ( region->isNewbieRegion() )
	{
		switch( character.getRace() )
		{
		case EGSPD::CPeople::Fyros :
			mission = CAIAliasTranslator::getInstance()->getMissionUniqueIdFromName( "FYROS_NEWB_WELCOME_KAEMON_1" );
			CAIAliasTranslator::getInstance()->getNPCAliasesFromName("welcomer_kaemon_1", bots);
			break;
		case EGSPD::CPeople::Matis :
			mission = CAIAliasTranslator::getInstance()->getMissionUniqueIdFromName( "MATIS_NEWB_WELCOME_BOREA_1" );
			CAIAliasTranslator::getInstance()->getNPCAliasesFromName("welcomer_borea_1", bots);
			break;
		case EGSPD::CPeople::Tryker :
			mission = CAIAliasTranslator::getInstance()->getMissionUniqueIdFromName( "TRYKER_NEWB_WELCOME_BARKDELL_1" );
			CAIAliasTranslator::getInstance()->getNPCAliasesFromName("welcomer_barkdell_1", bots);
			break;
		case EGSPD::CPeople::Zorai :
			mission = CAIAliasTranslator::getInstance()->getMissionUniqueIdFromName( "ZORAI_NEWB_WELCOME_SHENG_WO_1" );
			CAIAliasTranslator::getInstance()->getNPCAliasesFromName("welcomer_sheng_wo_1", bots);
			break;	
		}
	}
	// other give him a rite intro mission
	else
	{
		switch( character.getRace() )
		{
		case EGSPD::CPeople::Fyros :
			mission = CAIAliasTranslator::getInstance()->getMissionUniqueIdFromName( "FYROS_ENCYCLO_TUTORIAL" );
			CAIAliasTranslator::getInstance()->getNPCAliasesFromName("pyr_barman", bots);
			break;
		case EGSPD::CPeople::Matis :
			mission = CAIAliasTranslator::getInstance()->getMissionUniqueIdFromName( "MATIS_ENCYCLO_TUTORIAL" );
			CAIAliasTranslator::getInstance()->getNPCAliasesFromName("yrkanis_barman", bots);
			break;
		case EGSPD::CPeople::Tryker :
			mission = CAIAliasTranslator::getInstance()->getMissionUniqueIdFromName( "TRYKER_ENCYCLO_TUTORIAL" );
			CAIAliasTranslator::getInstance()->getNPCAliasesFromName("fairhaven_barman_1", bots);
			break;
		case EGSPD::CPeople::Zorai :
			mission = CAIAliasTranslator::getInstance()->getMissionUniqueIdFromName( "ZORAI_ENCYCLO_TUTORIAL" );
			CAIAliasTranslator::getInstance()->getNPCAliasesFromName("zora_barman", bots);
			break;	
		}
	}
	if ( mission == CAIAliasTranslator::Invalid || bots.empty() )
	{
		nlwarning("<adaptToVersion11> %s cant have newbie/rite mission set. race is '%s' bot vector size is %u mission is %u newbie mission is %u",
			character.getId().toString().c_str(),
			EGSPD::CPeople::toString( character.getRace() ).c_str(),
			bots.size(),
			mission,
			region->isNewbieRegion());
		return;
	}

	nlassert(!bots.empty());
	character.setWelcomeMissionDesc(mission, bots[0]);
}
コード例 #14
0
//---------------------------------------------------
void CCharacterVersionAdapter::adaptToVersion7(CCharacter &character) const
{
	static map<uint,string> maleSheets;
	static map<uint,string> femaleSheets;
	if ( maleSheets.empty() )
		initCharacterAdapterToVersion7( maleSheets, femaleSheets );


	map<uint,string>::iterator it;
	if ( character.getGender() == GSGENDER::female )
	{		
		it = femaleSheets.find( character._HairType );
		if ( it == femaleSheets.end() )
		{
			nlwarning( "<adaptToVersion7> invalid hair type %u in char %s (female)",character._HairType, character.getId().toString().c_str() );
			return;
		}
	}
	else
	{		
		it = maleSheets.find( character._HairType );
		if ( it == maleSheets.end() )
		{
			nlwarning( "<adaptToVersion7> invalid hair type %u in char %s (male)",character._HairType, character.getId().toString().c_str() );
			return;
		}
	}
	CSheetId sheet( (*it).second );
	if ( sheet == CSheetId::Unknown )
	{
		nlwarning( "<adaptToVersion7> char %s, sheet '%s' is invalid",character.getId().toString().c_str(), (*it).second.c_str() );
		return;
	}
	uint idx = CVisualSlotManager::getInstance()->sheet2Index( sheet,SLOTTYPE::HEAD_SLOT );
	if ( idx == 0 )
	{
		nlwarning( "<adaptToVersion7> char %s, sheet '%s' has no valid slot index",character.getId().toString().c_str(), (*it).second.c_str() );
		return;
	}
	character._HairType = idx;
	
		/*
		 Below is the association between former visual slot id / old sheet / new shhet

	male

		1 : fy_cheveux_long01.sitem : fy_hom_hair_style03.sitem
		2 : fy_cheveux_medium01.sitem : fy_hom_hair_style02.sitem
		3 : fy_cheveux_shave01.sitem : fy_hom_hair_basic01.sitem
		4 : fy_cheveux_short01.sitem : fy_hom_hair_basic02.sitem
		30 : fy_cheveux_medium02.sitem : fy_hom_hair_style01.sitem
		31 : fy_cheveux_medium03.sitem : fy_hom_hair_artistic01.sitem
		32 : fy_cheveux_short02.sitem : fy_hom_hair_basic03.sitem

		16 : tr_cheveux_long01.sitem : tr_hom_hair_artistic01.sitem
		17 : tr_cheveux_medium01.sitem : tr_hom_hair_basic03.sitem
		18 : tr_cheveux_shave01.sitem : tr_hom_hair_basic01.sitem
		19 : tr_cheveux_short01.sitem : tr_hom_hair_style01.sitem
		36 : tr_cheveux_medium02.sitem : tr_hom_hair_style02.sitem
		37 : tr_cheveux_short02.sitem : tr_hom_hair_basic02.sitem
		38 : tr_cheveux_short03.sitem : tr_hom_hair_artistic02.sitem
		
		
		10 : ma_cheveux_long01.sitem : ma_hom_hair_style04.sitem
		11 : ma_cheveux_medium01.sitem : ma_hom_hair_basic02.sitem
		12 : ma_cheveux_shave01.sitem : ma_hom_hair_basic01.sitem
		13 : ma_cheveux_shave_01.sitem : ma_hom_hair_basic01.sitem
		14 : ma_cheveux_short01.sitem : ma_hom_hair_style01.sitem
		33 : ma_cheveux_long02.sitem : ma_hom_hair_artistic01.sitem
		34 : ma_cheveux_medium02.sitem : ma_hom_hair_style02.sitem
		35 : ma_cheveux_short02.sitem : ma_hom_hair_style03.sitem
		
		
		
		21 : zo_cheveux_long01.sitem : zo_hom_hair_basic02.sitem
		22 : zo_cheveux_medium01.sitem : zo_hom_hair_style01.sitem
		23 : zo_cheveux_shave01.sitem : zo_hom_hair_basic01.sitem
		24 : zo_cheveux_short01.sitem : zo_hom_hair_basic03.sitem
		39 : zo_cheveux_long02.sitem : zo_hom_hair_basic04.sitem
		40 : zo_cheveux_medium02.sitem : zo_hom_hair_style02.sitem
		41 : zo_cheveux_medium03.sitem : zo_hom_hair_style03.sitem






  female


		1 : fy_cheveux_long01.sitem : fy_hof_hair_style03.sitem
		2 : fy_cheveux_medium01.sitem : fy_hof_hair_basic02.sitem
		3 : fy_cheveux_shave01.sitem : fy_hof_hair_basic01.sitem
		4 : fy_cheveux_short01.sitem : fy_hof_hair_style01.sitem
		30 : fy_cheveux_medium02.sitem : fy_hof_hair_style02.sitem
		31 : fy_cheveux_medium03.sitem : fy_hof_hair_artistic01.sitem
		32 : fy_cheveux_short02.sitem : fy_hof_hair_basic03.sitem
		
		16 : tr_cheveux_long01.sitem : tr_hof_hair_style01.sitem  
		17 : tr_cheveux_medium01.sitem : tr_hof_hair_style02.sitem  
		18 : tr_cheveux_shave01.sitem : tr_hof_hair_basic01.sitem
		19 : tr_cheveux_short01.sitem : tr_hof_hair_artistic03.sitem
		36 : tr_cheveux_medium02.sitem : tr_hof_hair_artistic04.sitem
		37 : tr_cheveux_short02.sitem : tr_hof_hair_artistic01.sitem
		38 : tr_cheveux_short03.sitem : tr_hof_hair_artistic02.sitem
		  
			
		10 : ma_cheveux_long01.sitem : ma_hof_hair_style01.sitem
		11 : ma_cheveux_medium01.sitem : ma_hof_hair_artistic_01.sitem
		12 : ma_cheveux_shave01.sitem : ma_hof_hair_basic_01.sitem
		13 : ma_cheveux_shave_01.sitem : ma_hof_hair_basic_01.sitem
		14 : ma_cheveux_short01.sitem : ma_hof_hair_basic_02.sitem
		33 : ma_cheveux_long02.sitem : ma_hof_hair_style02.sitem
		34 : ma_cheveux_medium02.sitem : ma_hof_hair_artistic_02.sitem
		35 : ma_cheveux_short02.sitem : ma_hof_hair_style03.sitem
			  
				
				  
		21 : zo_cheveux_long01.sitem : zo_hof_hair_style_04.sitem
		22 : zo_cheveux_medium01.sitem : zo_hof_hair_style_02.sitem
		23 : zo_cheveux_shave01.sitem : zo_hof_hair_basic_01.sitem
		24 : zo_cheveux_short01.sitem : zo_hof_hair_basic_02.sitem
		39 : zo_cheveux_long02.sitem : zo_hof_hair_basic_03.sitem
		40 : zo_cheveux_medium02.sitem : zo_hof_hair_style_01.sitem
		41 : zo_cheveux_medium03.sitem : zo_hof_hair_style_03.sitem

  */
		
}
コード例 #15
0
ファイル: Scene.cpp プロジェクト: Taka03/Camerun
//=============================================================================
//初期化
//=============================================================================
//[input]
//	pScene:設定するシーン
//=============================================================================
bool CScene::Init( CScene *pScene )
{
	if( m_IsFirstBoot )
	{
		/*マウスの取得*/
		pScene->m_pMouse = m_pApp->GetCore()->GetMouse();
		
		//-----------------------------------------------------------------
		// シーン
		//-----------------------------------------------------------------
		m_pSceneMgr[S_MAIN]->SetRenderSize( m_pApp->GetScreenWidth(), m_pApp->GetScreenHeight() );
		m_pSceneMgr[S_SUB]->SetRenderSize( m_pApp->GetScreenWidth(), m_pApp->GetScreenHeight() );
		
		for( int i = 0;i < S_MAX;++i )
		{
			m_pSceneMgr[i]->CreateDevice( m_pApp->GetRenderer() );
		}
		
		m_pSceneMgr[S_MAIN]->SetInitParameter( false );
		m_pSceneMgr[S_SUB]->SetInitParameter( true );
		
		//-----------------------------------------------------------------
		//オブジェクトの追加
		//-----------------------------------------------------------------
		//std::ifstream ifs("aa.csv");
		
		//char Temp[256];
		//char Temp2[256];
		//
		//string strDataName;
		//string strObjectName;
		

		//ifs >> Temp >> Temp2;
		//
		//strDataName = Temp;
		//strObjectName = Temp2;
		
		//m_pGameObj->AppendObject( new CField(strDataName), strObjectName, true );
		
		Selene::File::IResourceFile *pResFile = NULL;
		
		
		#if defined(DEBUG_CHAT)
		
		#else
		
		m_p3DObj->AppendObject( new CField("map.stm"), "Field", true );
		//m_pGameObj->AppendObject( new CField("Kaidan.stm"), "Field", true );
		//ifs >> Temp >> Temp2 ;
		//
		//strDataName = Temp;
		//strObjectName = Temp2;
		
		m_pApp->GetFileMgr()->SetCurrentPath( "CSV" );
		
		
		pResFile = m_pApp->GetFileMgr()->FileOpen("Ameus.csv");
		
		m_p3DObj->AppendObject( new CPlayer("Camerun.smf" , Math::Vector3D( 0, 7, -73) ) , "Player", true ); 
		m_p3DObj->AppendObject( new CTrain("train1.smf", Math::Vector3D(0.0f, 0.0f, -73.0f) ), "Train", true );
		m_p3DObj->AppendObject( new CEnemyAmeus("ameus.smf", Math::Vector3D(-141.0f , 1.0f, -238.0f), pResFile->GetNamePointer() ), "Ameus", true );
		
		SAFE_RELEASE( pResFile );
		
		for( int i = 0;i < BIRD_MAX;++i )
		{
			char Temp[20] = "";
			
			sprintf( Temp, "bird%d.csv", i+1 );
			
			pResFile = m_pApp->GetFileMgr()->FileOpen(Temp);
			
			sprintf(Temp, "Bird%d", i+1 );
			
			m_p3DObj->AppendObject( new CEnemyBird("bird.smf", Math::Vector3D(0.0f, 120.0, -45.0f), pResFile->GetNamePointer() ), Temp, true );
			
			SAFE_RELEASE( pResFile );
		}
		
		for( int i = 0;i < MOUSE_MAX;++i )
		{
			char Temp[20] = "";
			
			sprintf( Temp, "mouse%d.csv", i+1 );
			
			pResFile = m_pApp->GetFileMgr()->FileOpen(Temp);
			
			sprintf(Temp, "Mouse%d", i+1 );
			
			m_p3DObj->AppendObject( new CEnemyMouse("mouse.smf", Math::Vector3D(0.0f, 0.0f, -40.0f), pResFile->GetNamePointer() ), Temp, true );
			
			SAFE_RELEASE( pResFile );
		}
		
		pResFile = m_pApp->GetFileMgr()->FileOpen("manta.csv");
		
		#if defined( TEST_RELEASE )	
			m_p3DObj->AppendObject( new CEnemyManta("manta.smf", Math::Vector3D(0.0f, 0.0f, -40.0f), pResFile->GetNamePointer() ), "Manta", true );
		#else
			m_p3DObj->AppendObject( new CEnemyManta("manta.smf", Math::Vector3D(0.0f, 80.0f, -40.0f), pResFile->GetNamePointer() ), "Manta", true );
		#endif
		
		SAFE_RELEASE( pResFile );
		
		pResFile = m_pApp->GetFileMgr()->FileOpen("rabbit.csv");
		
		m_p3DObj->AppendObject( new CEnemyRabbit("rabbit.smf", Math::Vector3D(0.0f, 0.0f, -40.0f), pResFile->GetNamePointer() ), "Rabbit", true );
		
		SAFE_RELEASE( pResFile );
		
		m_p3DObj->AppendObject( new CCamObject("camera.smf"), "CamObj", false );
		
		m_p3DObj->AppendObject( new CCharacter("statue_dove.smf", Math::Vector3D( -188, 3.6f, -361) ), "FountObj", true );
		m_p3DObj->AppendObject( new CCharacter("flag.smf", Math::Vector3D( -188, 3.6f, -361) ), "Flag", true );
		
		//m_p3DObj->AppendObject( new CFlagObject("flag.smf"), "Flag", false );
		
		//m_p3DObj->AppendObject( new CCharacter("statue_dove.smf", Math::Vector3D( -188, 4.4f, -361) ), "FountObj2", true );
		//m_p3DObj->AppendObject( new CCharacter("statue_dove.smf", Math::Vector3D( -188, 4.4f, -361) ), "FountObj3", true );
		
		
		m_p3DObj->AppendObject( new CCharacter("arrow.smf", Math::Vector3D( 0, 0, 0 ) ), "Arrow", true );
		//m_p3DObj->AppendObject( new CSprite3D("title.png", Math::Vector3D( 0, 0, -100 ) ), "BillBoard", true );
		m_p3DObj->AppendObject( new CCharacter("target.smf", Math::Vector3D( 0, 0, -100 ) ), "Target", true );
		m_p3DObj->AppendObject( new CCharacter("star.smf", Math::Vector3D( 0, 0, -100 ) ), "Star", false ) ;
		m_p3DObj->AppendObject( new CCharacter("flying_island.smf", Math::Vector3D( 162, 180, -212 ) ), "IsLand", true ) ;
		
		
		m_p3DObj->AppendObject( new CSprite3D("flgemo.dds", Math::Vector3D( 0, 0, -10 ) ), "FlagBalloon", true );
		m_p3DObj->AppendObject( new CParticle("smoke.dds", Math::Vector3D(0, 0, 10) ), "RunEffect0", false );
		m_p3DObj->AppendObject( new CParticle("smoke.dds", Math::Vector3D(0, 0, 10) ), "RunEffect1", false );
		m_p3DObj->AppendObject( new CParticle("smoke.dds", Math::Vector3D(0, 0, 10) ), "RunEffect2", false );
		m_p3DObj->AppendObject( new CParticle("smoke.dds", Math::Vector3D(0, 0, 10) ), "RunEffect3", false );
		m_p3DObj->AppendObject( new CFlash("flash2.png", Math::Vector3D( 0, 0, 0 ) ), "Emission0", false );
		m_p3DObj->AppendObject( new CFlash("flash2.png", Math::Vector3D( 0, 0, 0 ) ), "Emission1", false );
		m_p3DObj->AppendObject( new CFlash("flash2.png", Math::Vector3D( 0, 0, 0 ) ), "Emission2", false );
		m_p3DObj->AppendObject( new CFlash("flash2.png", Math::Vector3D( 0, 0, 0 ) ), "Emission3", false );
		m_p3DObj->AppendObject( new CFlash("flash2.png", Math::Vector3D( 0, 0, 0 ) ), "Emission4", false );
		m_p3DObj->AppendObject( new CFlash("flash2.png", Math::Vector3D( 0, 0, 0 ) ), "Emission5", false );
		
		
		m_p3DObj->AppendObject( new CSprite3D("emo.dds", Math::Vector3D( 0, 0, 0 ) ), "Emotion", false );
	
		
		m_pSoundObj->AppendObject( new CSoundEffect("shutter.WAV"), "Shutter", true );
		m_pSoundObj->AppendObject( new CSoundEffect("flag.WAV"), "Flag", true );
		m_pSoundObj->AppendObject( new CSoundEffect("run.WAV"), "Run", true );
		m_pSoundObj->AppendObject( new CSoundEffect("train.WAV"), "STrain", true );
		m_pSoundObj->AppendObject( new CSoundEffect("change.WAV"), "Change", true );
		m_pSoundObj->AppendObject( new CSoundEffect("enter.WAV"), "Enter", true );
		m_pSoundObj->AppendObject( new CSoundEffect("collision.WAV"), "Collision", true );
		m_pSoundObj->AppendObject( new CSoundEffect("mouse.WAV"), "Mouse", true );
		m_pSoundObj->AppendObject( new CSoundEffect("flagrecall.WAV"), "RecallFlag", true );
		m_pSoundObj->AppendObject( new CSoundEffect("flagsetfail.WAV"), "SetFlagFail", true );
		m_pSoundObj->AppendObject( new CSoundEffect("missionclear.WAV"), "MissionClear", true );
		m_pSoundObj->AppendObject( new CSoundEffect("missionfail.WAV"), "MissionFail", true );
		m_pSoundObj->AppendObject( new CSoundEffect("bird.WAV"), "Bird", true );
		m_pSoundObj->AppendObject( new CSoundEffect("select.WAV"), "Select", true );
		m_pSoundObj->AppendObject( new CSoundEffect("DrumRoll.WAV"), "DrumRoll", true );
		m_pSoundObj->AppendObject( new CSoundEffect("decide.WAV"), "Decide", true );
		
		
		
		
		//while( !ifs.eof() )
		//{	
		//	ifs >> Temp >> Temp2;
		//	
		//	strDataName = Temp;
		//	strObjectName = Temp2;
		//	
		//	m_pSoundObj->AppendObject( new CSoundEffect(strDataName), strObjectName, true );
		//	
		//}
		
		#endif
		
		m_pSoundObj->AppendObject( new CBGM("BGM.ogg"), "TitleBGM", true );
		m_pSoundObj->AppendObject( new CBGM("Rolling Railing Hiking!.ogg"), "GameBGM", true );
		m_pSoundObj->AppendObject( new CBGM("TitleBGM.ogg"), "ChatBGM", true );
		
		m_pSoundObj->AppendObject( new CBGM("BGM.ogg"), "ResultBGM", true );
		
		
		m_pGameObj->AppendObject( new CCamera(), "CamMain", true );
		m_pGameObj->AppendObject( new CCamera(), "CamSub", true );
		
		m_pGameObj->AppendObject( new CFontSprite("font.sff", Math::Vector2D( 200, 400 ) ), "TitleFont", true );
		m_pGameObj->AppendObject( new CFontSprite("font2.sff", Math::Vector2D( 200, 400 ) ), "CommonFont", true );
		m_pGameObj->AppendObject( new CFontSprite("MissionFont.sff", Math::Vector2D( 430, 13) ), "MissionFont", true );
		m_pGameObj->AppendObject( new CFontSprite("MenuFont.sff", Math::Vector2D( 220, 100 ) ), "MenuFont", true );
		m_pGameObj->AppendObject( new CFontSprite("ChatFont.sff", Math::Vector2D( 110, 465 ) ), "ChatFont", true );
		m_pGameObj->AppendObject( new CFontSprite("NumFont.sff", Math::Vector2D( 110, 465 ) ), "NumFont", true );
		m_pGameObj->AppendObject( new CFontSprite("MiContFont.sff", Math::Vector2D( 110, 465 ) ), "ContentFont", true );
		m_pGameObj->AppendObject( new CFontSprite("MiContFont2.sff", Math::Vector2D( 110, 465 ) ), "ContentFont2", true );
		m_pGameObj->AppendObject( new CFontSprite("ExplainFont.sff", Math::Vector2D( 110, 465 ) ), "ExplainFont", true );
		
		
		
		
		//m_pGameObj->AppendObject( new Draw2DObject("Build_1.bmp", Math::Vector2D(100, 200) ), "Film", true );
		#if defined( DEBUG_MAP_EDIT ) 
		
		#elif defined( DEBUG_MAP_SEE )
		
		#else
			m_p2DObj->AppendObject( new CSprite("title.png", Math::Vector2D( 0, 0 ) ), "Title", false );
			m_p2DObj->AppendObject( new CSprite("background.png", Math::Vector2D( 0, 0 ) ), "MissionSelect", false );
			m_p2DObj->AppendObject( new CSprite("chat.png", Math::Vector2D( 0, 0 ) ), "Chat", false );
			m_p2DObj->AppendObject( new CSprite("Result.png", Math::Vector2D( 0, 0 ) ), "Result", false );
			m_p2DObj->AppendObject( new CSprite("back.png", Math::Vector2D( 0, 0 ) ), "CalcScore", false );
			m_p2DObj->AppendObject( new CSprite("clear.dds", Math::Vector2D( 0, 0 ) ), "GameClear", false );
			m_p2DObj->AppendObject( new CSprite("failure.dds", Math::Vector2D( 0, 0 ) ), "GameFailure", false );
			
		#endif
		
		const char *pMiniCharaName[] =
		{
			"Mini_Mouse1",	
			"Mini_Mouse2",
			"Mini_Mouse3",
			"Mini_Bird1",
			"Mini_Bird2",
			"Mini_Bird3",
			"Mini_Bird4",
			"Mini_Bird5",
			"Mini_Bird6",
			
		};
		
		m_p2DObj->AppendObject( new CMiniMap("minimap3.png", Math::Vector2D( 0, 0) ), "MiniMap", true );
		m_p2DObj->AppendObject( new CSprite("came.dds", Math::Vector2D( 200, 200) ), "Mini_Player", true );
		m_p2DObj->AppendObject( new CSprite("mini_flag.dds", Math::Vector2D( 0, 0 ) ), "Mini_Camera", false );
		
		for( int i = 0;i < MINI_CHARA_MAX;++i )
		{
			m_p2DObj->AppendObject( new CSprite("mini_camera.png", Math::Vector2D( 0, 0 ) ), pMiniCharaName[i], false );
		}
			
		m_p2DObj->AppendObject( new CSprite("mini_target.dds", Math::Vector2D( 0, 0 ) ), "Mini_Target", false );
		
		
		m_p2DObj->AppendObject( new CSprite("pauseback.png", Math::Vector2D( 0, 0 ) ), "Pause", false );
		m_p2DObj->AppendObject( new CSprite("menu.dds", Math::Vector2D( 0, 0 ) ), "Menu", true );
		m_p2DObj->AppendObject( new CSprite("char.dds", Math::Vector2D( 170, 7 ) ), "CharaIcon", true );
		m_p2DObj->AppendObject( new CSprite("flag.dds", Math::Vector2D( 170, 7 ) ), "FlagIcon", true );
		m_p2DObj->AppendObject( new CSprite("film.dds", Math::Vector2D( 220, 7 ) ), "Film", true );
		m_p2DObj->AppendObject( new CSprite("bar.dds", Math::Vector2D( 310, 5 ) ), "Bar", true );
		m_p2DObj->AppendObject( new CSprite("systemmenu.dds", Math::Vector2D( 100, 200 ) ), "PopMenu", true );
		m_p2DObj->AppendObject( new CSprite("high.dds", Math::Vector2D( 590, 90 ) ), "HighScore", false );
		m_p2DObj->AppendObject( new CSprite("pointa.dds", Math::Vector2D( 645, 470 ) ), "Pointa", true );
		m_p2DObj->AppendObject( new CSprite("Cloud.tga", Math::Vector2D( 0, 0 ) ), "Cloud", true );
		
		#if defined( DEBUG_MAP_EDIT )
		
		#elif defined( DEBUG_MAP_SEE )
		
		#else
		
  			m_p2DObj->AppendObject( new CSprite("mission1.dds", Math::Vector2D( 270, 208 ) ), "MissionFont1", true );
			m_p2DObj->AppendObject( new CSprite("mission2.dds", Math::Vector2D( 115, 298 ) ), "MissionFont2", true );
			m_p2DObj->AppendObject( new CSprite("mission3.dds", Math::Vector2D( 452, 128 ) ), "MissionFont3", true );
			m_p2DObj->AppendObject( new CSprite("mission4.dds", Math::Vector2D( 65, 138 ) ), "MissionFont4", true );
			m_p2DObj->AppendObject( new CSprite("mission5.dds", Math::Vector2D( 426, 318 ) ), "MissionFont5", true );
			m_p2DObj->AppendObject( new CSprite("pin.dds", Math::Vector2D( 383, 142 ) ), "Pin", true );
			
			//m_p2DObj->AppendObject( new CSprite("pin2.dds", Math::Vector2D( 665, 490 ) ), "Pin2", true );
			m_p2DObj->AppendObject( new CSprite("train.png", Math::Vector2D( 280, 150) ), "Picture1", true );
			m_p2DObj->AppendObject( new CSprite("ameus.png", Math::Vector2D( 125, 240) ), "Picture2", true );
			m_p2DObj->AppendObject( new CSprite("oashisu.png", Math::Vector2D( 480, 70) ), "Picture3", true );
			m_p2DObj->AppendObject( new CSprite("funsui.png", Math::Vector2D( 75, 80 ) ), "Picture4", true );
			m_p2DObj->AppendObject( new CSprite("manta.png", Math::Vector2D( 440, 260 ) ), "Picture5", true );
			m_p2DObj->AppendObject( new CSprite("note.dds", Math::Vector2D( 322, 200 ) ), "Note", false );
			
			
		#endif
		
			m_p2DObj->AppendObject( new CSprite("ready.dds", Math::Vector2D( 159, 245 ) ), "Ready", true );
			m_p2DObj->AppendObject( new CSprite("go.dds", Math::Vector2D( 300, 238 ) ), "Go", true );
			m_p2DObj->AppendObject( new CSprite("nofilm.dds", Math::Vector2D( 300, 238 ) ), "NoFilm", false );
		
		
		m_p3DObj->AppendObject( new CDebugLine(), "DebugLine", true );
		
		//ifs.close();
		
		#if defined( DEBUG_MAP_EDIT ) 
		
		#elif defined( DEBUG_MAP_SEE )
		
		
		#elif defined( DEBUG_CHAT )
		
		#else
			CSprite *pPin = dynamic_cast<CSprite *>( pScene->Get2DObject()->FindObjectFromName("Pin") );
			
			pPin->SetDivnum( Math::Point2DI(2, 1) );
			
			CSprite3D *pEmotion = dynamic_cast<CSprite3D *>( pScene->Get3DObject()->FindObjectFromName("Emotion") );
			
			pEmotion->SetDivnum( Math::Point2DI( 4, 1 ) );
			
			CSprite3D *pFlagBal = dynamic_cast<CSprite3D *>( pScene->Get3DObject()->FindObjectFromName("FlagBalloon") );
			
			pFlagBal->SetDivnum( Math::Point2DI( 2, 1 ) );
			
		#endif
		
		
		
			//CSprite *pPin = dynamic_cast<CSprite *>( pScene->Get2DObject()->FindObjectFromName("Pin") );
			//
			//pPin->SetDivnum( Math::Point2DI(2, 1) );
			//
			//CSprite3D *pEmotion = dynamic_cast<CSprite3D *>( pScene->Get3DObject()->FindObjectFromName("Emotion") );
			//
			//pEmotion->SetDivnum( Math::Point2DI( 4, 1 ) );
			//
			//CSprite3D *pFlagBal = dynamic_cast<CSprite3D *>( pScene->Get3DObject()->FindObjectFromName("FlagBalloon") );
			//
			//pFlagBal->SetDivnum( Math::Point2DI( 2, 1 ) );
		
		
		
		//---------------------------------------------------------------------------
		//カメラ
		//---------------------------------------------------------------------------
		CCamera *objCamMain	= dynamic_cast<CCamera *>( m_pGameObj->FindObjectFromName("CamMain") );
		CCamera *objCamSub  = dynamic_cast<CCamera *>( m_pGameObj->FindObjectFromName("CamSub") );
		
		/*カメラデバイスのセット*/
		objCamMain->SetCamera( m_pSceneMgr[S_MAIN]->GetSceneMgr() );
		objCamSub->SetCamera( m_pSceneMgr[S_SUB]->GetSceneMgr() );
		
		/*プロジェクションのセット*/
		objCamMain->SetProjection( 1.0f, 1000.0f, 45, m_pSceneMgr[S_MAIN]->GetRenderWidth(), m_pSceneMgr[S_MAIN]->GetRenderHeight() );
		
		objCamSub->SetProjection( 1.0f, 1000.0f, 45, m_pSceneMgr[S_SUB]->GetRenderWidth(), m_pSceneMgr[S_SUB]->GetRenderHeight() );
		
		
		//---------------------------------------------------------------------------
		//物理エンジン初期化
		//---------------------------------------------------------------------------
		//pDynamicsWorld = Dynamics::CreateWorld( m_pSceneMgr[S_MAIN]->GetSceneMgr() );
		//
		///*ワールドにおける重力を設定*/
		//pDynamicsWorld->SetGravity( Math::Vector3D( 0, -GRAVITY, 0 ) );
		//
		///*剛体モデルの生成*/
		//m_p3DObj->CreateRigidModel( pDynamicsWorld );
		
		
		//---------------------------------------------------------------------------
		//モデル
		//---------------------------------------------------------------------------
		
		#if defined( DEBUG_CHAT )
		
		#else
			// ルートディレクトリに対して読み込むカレントディレクトリ設定
			m_pApp->GetFileMgr()->SetCurrentPath( "Model" );
			
			CField *objField = dynamic_cast<CField *>( m_p3DObj->FindObjectFromName("Field") );
			
			CDebugLine *pDebugLine = dynamic_cast<CDebugLine *>( m_p3DObj->FindObjectFromName("DebugLine") );

			/*読み込み*/
			m_p3DObj->Load( m_pApp->GetRenderer() );
			
			
			m_pApp->GetFileMgr()->SetCurrentPath("Shader");
			
			CPlayer *objPlayer = dynamic_cast<CPlayer *>( pScene->Get3DObject()->FindObjectFromName("Player") );
			
			pDebugLine->CreateLine( m_pApp->GetRenderer() );
			
			
			
			//objPlayer->LoadShader( m_pGame->GetRenderer(), "UserShader.fx" );
			pDebugLine->CreateActor( m_pSceneMgr[S_MAIN]->GetSceneMgr() );
					
		#endif
	
		#if defined( DEBUG ) | (_DEBUG )
		
			objField->SetCollisionLine( pDebugLine->GetLine() );
		
		
		#elif defined( DEBUG_CHAT )
		
		
		#endif
		
		//pDebugLine->CreateActor( m_pSceneMgr[S_SUB]->GetSceneMgr() );

		#if defined( DEBUG_CHAT )
		
		#else
			/*アクターの生成*/
			for( int numScreen = 0;numScreen < S_MAX;++numScreen )
			{	
				m_p3DObj->CreateActor( numScreen, m_pSceneMgr[numScreen]->GetSceneMgr() );
				
				objField->CreateActor( numScreen, m_pSceneMgr[numScreen]->GetSceneMgr() );
			}
			
		#endif
		
		//---------------------------------------------------------------------------
		//サウンド
		//---------------------------------------------------------------------------
		m_pApp->GetFileMgr()->SetCurrentPath("Sound");
		
		/*サウンドの読み込み*/
		m_pSoundObj->LoadSound( m_pApp->GetCore() );
		
		//---------------------------------------------------------------------------
		//テクスチャ
		//---------------------------------------------------------------------------
		m_pApp->GetFileMgr()->SetCurrentPath("Texture");
		
		/*テクスチャの読み込み*/
		m_p2DObj->Load( m_pApp->GetRenderer() );
		
		CSprite *SkySpr = dynamic_cast<CSprite *>( pScene->Get2DObject()->FindObjectFromName("Cloud") );
		
		for( int scenenum = 0;scenenum < S_MAX;++scenenum )
		{
			m_pSceneMgr[scenenum]->CreateSkyDoom( SkySpr->GetTexture(), m_pApp->GetRenderer() );
		}
		
		pScene->Get2DObject()->RemoveObject( SkySpr );
			
		//---------------------------------------------------------------------------
		//フォント
		//---------------------------------------------------------------------------
		m_pApp->GetFileMgr()->SetCurrentPath("Font");
		
		CFontSprite *pFontSpr = dynamic_cast<CFontSprite *>( m_pGameObj->FindObjectFromName("TitleFont") );
		CFontSprite *pCommonFont = dynamic_cast<CFontSprite *>( m_pGameObj->FindObjectFromName("CommonFont") );
		CFontSprite *pMissionFont = dynamic_cast<CFontSprite *>( m_pGameObj->FindObjectFromName("MissionFont") );
		CFontSprite *pMenuFont = dynamic_cast<CFontSprite *>( m_pGameObj->FindObjectFromName("MenuFont") );
		CFontSprite *pChatFont = dynamic_cast<CFontSprite *>( m_pGameObj->FindObjectFromName("ChatFont") );
		CFontSprite *pNumFont = dynamic_cast<CFontSprite *>( m_pGameObj->FindObjectFromName("NumFont") );
		CFontSprite *pMiContFont = dynamic_cast<CFontSprite *>( m_pGameObj->FindObjectFromName("ContentFont") );
		CFontSprite *pMiContFont2 = dynamic_cast<CFontSprite *>( m_pGameObj->FindObjectFromName("ContentFont2") );
		CFontSprite *pExpFont = dynamic_cast<CFontSprite *>( m_pGameObj->FindObjectFromName("ExplainFont") );
		
		pFontSpr->Load( m_pApp->GetRenderer() );
		pCommonFont->Load( m_pApp->GetRenderer() );
		pMissionFont->Load( m_pApp->GetRenderer() );
		pMenuFont->Load( m_pApp->GetRenderer() );
		pChatFont->Load( m_pApp->GetRenderer() );
		pNumFont->Load( m_pApp->GetRenderer() );
		pMiContFont->Load( m_pApp->GetRenderer() );
		pMiContFont2->Load( m_pApp->GetRenderer() );
		pExpFont->Load( m_pApp->GetRenderer() );
		
		//---------------------------------------------------------------------------
		//テキスト読み込み
		//---------------------------------------------------------------------------
		pResFile = 	m_pApp->GetFileMgr()->FileOpen("Text.txt");
		
		Sint32 FileSize = pResFile->GetFileSize();
		
		char *pTextBuff = new char[FileSize + 1];
		
		pResFile->Read( pTextBuff, FileSize );
		
		pTextBuff[FileSize] = '\0';
		
		pResFile->Release();
		
		pFontSpr->SetDrawString("PUSH START");
		
		CSprite *objPopMenu	= dynamic_cast<CSprite *>( m_p2DObj->FindObjectFromName("PopMenu") );
		
		m_pGameObj->AppendObject( new CMenu( pMenuFont, objPopMenu ), "PopMenu", true );
		
		//---------------------------------------------------------------------------
		//ミッションの追加
		//---------------------------------------------------------------------------
		m_pApp->GetFileMgr()->SetCurrentPath("CSV");
		
		pResFile = m_pApp->GetFileMgr()->FileOpen("mission.csv");
		
		std::ifstream ifsMission( pResFile->GetNamePointer() );
		
		SAFE_RELEASE( pResFile );
		
		char MissionTemp[256];
		
		ifsMission.getline( MissionTemp, 256 );
		
		m_pApp->GetFileMgr()->SetCurrentPath("Font");
		
		
		//ifs.open("mission.csv");
		
		while( !ifsMission.eof() )
		{
			char Temp[20];
			
			static int count = 0;
			
			MissionData datMission;
			char TempMissionName[256];
			char TempTargetName[256];
			char TempChat[1024];
			
			
			sprintf( Temp, "Mission%d.txt", count+1);
			
			pResFile = 	m_pApp->GetFileMgr()->FileOpen(Temp);
			
			ifstream ifs( pResFile->GetNamePointer() );
			
			SAFE_RELEASE(pResFile);
			
			#if defined (DEBUG) | (_DEBUG)
				//ofstream out( Temp, ios::out );
				//
				////while( *pTextBuff != '\0')
				////{
				////	if( *pTextBuff != '\n' )
				////	{
				////		out << pTextBuff;
				////	}
				////	
				////	pTextBuff += 1;
				////	
				////	
				////}
				//
				//
				//out.close();
			
			#endif
			
			while( !ifs.eof() )
			{	
				ifs >> TempChat;
				datMission.m_vecChat.push_back( TempChat );
			}
			
			ifs.close();
			
			
			sprintf( Temp, "MissionContent%d.txt", count+1 );
			
			pResFile = 	m_pApp->GetFileMgr()->FileOpen(Temp);
			
			ifstream ifsContent( pResFile->GetNamePointer() );
			
			char TempMiCont[256] = "";
			
			//ifsContent.read( TempMiCont, pResFile->GetFileSize() );
			
			SAFE_RELEASE( pResFile );
			
			while( !ifsContent.eof() )
			{
				ifsContent >> TempMiCont;
				datMission.m_vecMissionContent.push_back( TempMiCont );
			}
			
			ifsContent.close();
			
			ifsMission >> TempMissionName >> TempTargetName >> datMission.m_ClearPoint >> datMission.m_FilmNum 
			>> datMission.m_LimitTime.Min >> datMission.m_LimitTime.Sec >> datMission.m_TimeBorder.Min >> datMission.m_TimeBorder.Sec
			>> datMission.m_TargetPosMin >> datMission.m_TargetPosMax >> datMission.m_DistanceMin >> datMission.m_DistanceMax ;
			
			datMission.m_MissionName = TempMissionName;
			datMission.m_TargetName = TempTargetName;
			
			CCharacter *objFlag	  = dynamic_cast<CCharacter *>( pScene->Get3DObject()->FindObjectFromName("Flag") );
			
			float Scale = 4.0f;
			objFlag->SetScale( Math::Vector3D( Scale, Scale, Scale ) );
			
			sprintf( Temp, "MissionFont%d", count+1 );
			
			datMission.m_pFontSpr = dynamic_cast<CSprite *>( m_p2DObj->FindObjectFromName(Temp) );		
			
			sprintf( Temp, "Picture%d", count+1 );
			
			datMission.m_pPhotoSpr = dynamic_cast<CSprite *>( m_p2DObj->FindObjectFromName(Temp) );	
			
			m_pMissionMgr->AppendMission( count, new CMission( dynamic_cast<CDraw3DObject *>( m_p3DObj->FindObjectFromName( datMission.m_TargetName ) ), datMission ) );
			
			count++;
		}
			
		ifsMission.close();
			
		#if defined( DEBUG_MAP_EDIT )
		
		#elif defined( DEBUG_MAP_SEE)
		
		#else
			
		#endif
		
		//-----------------------------------------------------------------
		// 変更しないステート
		//-----------------------------------------------------------------
		m_pApp->SetTextureFilter();
		
		m_IsFirstBoot = false;
	}
	
	
	return true;
	
}
コード例 #16
0
ファイル: plasma.cpp プロジェクト: PJK136/teeworlds-wDM
bool CPlasma::HitCharacter(vec2 From, vec2 To)
{
	vec2 At;
	vec2 TempPos;

	float ClosestLen = -1;

	CCharacter *pOwnerChar = GameServer()->GetPlayerChar(m_Owner);
	CCharacter *pHit = GameServer()->m_World.IntersectCharacter(From, To, 0.0f, TempPos, pOwnerChar);
	if (pHit)
	{
		ClosestLen = distance(From, TempPos);
		At = TempPos;
	}

	CTurret *pHitTurret = (CTurret*) GameServer()->m_World.IntersectEntity(From, To, 0.0f, TempPos, CGameWorld::ENTTYPE_TURRET);
	if (pHitTurret && pHitTurret->GetOwner() != m_Owner && (ClosestLen > distance(From, TempPos) || ClosestLen == -1))
	{
		ClosestLen = distance(From, TempPos);
		At = TempPos;
		pHit = 0;
	}
	else if (pHitTurret)
		pHitTurret = 0;

	CExplodeWall *pHitExplodeWall = 0;

	{
		CExplodeWall *p = (CExplodeWall *)GameWorld()->FindFirst(CGameWorld::ENTTYPE_EXPLODEWALL);
		for(; p; p = (CExplodeWall *)p->TypeNext())
		{
			// Store the values for fast access and easy
			// equations-to-code conversion
			float x1 = From.x, x2 = To.x, x3 = p->m_From.x, x4 = p->m_Pos.x;
			float y1 = From.y, y2 = To.y, y3 = p->m_From.y, y4 = p->m_Pos.y;

			float d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
			// If d is zero, there is no intersection
			if (d == 0)
				continue;

			// Get the x and y
			float pre = (x1*y2 - y1*x2), post = (x3*y4 - y3*x4);
			float x = ( pre * (x3 - x4) - (x1 - x2) * post ) / d;
			float y = ( pre * (y3 - y4) - (y1 - y2) * post ) / d;

			// Check if the x and y coordinates are within both lines
			if ( x < min(x1, x2) || x > max(x1, x2) || x < min(x3, x4) || x > max(x3, x4) )
				continue;
			if ( y < min(y1, y2) || y > max(y1, y2) || y < min(y3, y4) || y > max(y3, y4) )
				continue;

			if ( ClosestLen > distance(From, vec2(x, y)) || ClosestLen == -1 )
			{
				ClosestLen = distance(From, vec2(x, y));
				At.x = x;
				At.y = y;
				pHit = 0;
				pHitTurret = 0;
				pHitExplodeWall = p;
			}
		}
	}

	if(!pHit && !pHitTurret && !pHitExplodeWall)
		return false;

	m_Pos = At;
	m_Energy = -1;

	if ( pHit && (!GameServer()->m_pEventsGame->IsActualEvent(WALLSHOT) || m_Bounces > 0 || GameServer()->m_pEventsGame->IsActualEvent(BULLET_PIERCING)) )
		pHit->TakeDamage(vec2(0.f, 0.f), GameServer()->Tuning()->m_LaserDamage, m_Owner, WEAPON_RIFLE, false);
	else if ( pHitTurret && (!GameServer()->m_pEventsGame->IsActualEvent(WALLSHOT) || m_Bounces > 0 || GameServer()->m_pEventsGame->IsActualEvent(BULLET_PIERCING)) )
		pHitTurret->TakeDamage(GameServer()->Tuning()->m_LaserDamage, m_Owner, WEAPON_RIFLE, false);
	else if ( pHitExplodeWall && (!GameServer()->m_pEventsGame->IsActualEvent(WALLSHOT) || m_Bounces > 0 || GameServer()->m_pEventsGame->IsActualEvent(BULLET_PIERCING)) )
		pHitExplodeWall->TakeDamage(GameServer()->Tuning()->m_LaserDamage, m_Owner, WEAPON_RIFLE, false);

	return true;
}
コード例 #17
0
ファイル: AIWeaponAbstract.cpp プロジェクト: Arc0re/lithtech
bool CAIWeaponAbstract::GetShootPosition( CAI* pAI, AimContext& Context,LTVector& outvShootPos )
{
	ASSERT(pAI);

	// Cineractive firing.

	if( m_eFiringState == kAIFiringState_CineFiring )
	{
		LTVector vDir = pAI->GetWeaponForward( m_pWeapon );
		vDir.Normalize();
		outvShootPos = pAI->GetPosition() + ( vDir * 5000.f );
		return true;
	}

	// If perfect accuracy is enabled, we are done.

	if( pAI->GetAIBlackBoard()->GetBBPerfectAccuracy() )
	{
		HOBJECT hTarget = pAI->GetAIBlackBoard()->GetBBTargetObject();
		g_pLTServer->GetObjectPos( hTarget, &outvShootPos );
		return true;
	}

	// Initially aim for the target's visible position.
	// If the target is not visible at all, use his actual position.
	// This is a failsafe for AI shooting at the origin if they have
	// not yet seen the target ever.

	LTVector vVisiblePosition = pAI->GetTarget()->GetVisiblePosition();
	if( !pAI->GetAIBlackBoard()->GetBBTargetVisibleFromWeapon() )
	{
		vVisiblePosition = pAI->GetAIBlackBoard()->GetBBTargetPosition();
	}
	outvShootPos = vVisiblePosition;

	// If Target is within the FullAccuracy radius, we are done.

	if( pAI->GetTarget()->GetTargetDistSqr() < pAI->GetFullAccuracyRadiusSqr() )
	{
		return true;
	}

	// The following code forces the AI to intenionally miss every x
	// number of shots, depending on their accuracy. This gives players
	// the excitement of getting shot at without killing them too fast.

	// For example, if accuracy = 0.5 there will be a guaranteed sequence
	// of HIT, MISS, HIT, MISS, ...
	// If accuracy = 0.25, then HIT, MISS, MISS, MISS, HIT, MISS, MISS, MISS, etc.
	// If accuracy = 0.75, then HIT, HIT, HIT, MISS, HIT, HIT, HIT, MISS, etc.

	// Calculate the ratio of hits to misses based on the current 
	// accuracy.  This needs to be recalculated for every shot, 
	// because accuracy may change at any time.

	float fAccuracy = m_flWeaponContextInaccuracyScalar * pAI->GetAccuracy();
	if( fAccuracy <= 0.f )
	{
		Context.m_cMisses = 1;
		Context.m_cHits = 0;
	}
	else if( fAccuracy >= 1.f )
	{
		Context.m_cMisses = 0;
		Context.m_cHits = 1;
	}
	else if( fAccuracy < 0.5f )
	{
		Context.m_cMisses = (uint32)( ( ( 1.f - fAccuracy ) / fAccuracy ) + 0.5f );
		Context.m_cHits = 1;
	}
	else 
	{
		Context.m_cMisses = 1;
		Context.m_cHits = (uint32)( ( fAccuracy / ( 1.f - fAccuracy ) ) + 0.5f );
	}

	// If we have met or exceeded the required number of misses, 
	// reset the counters.

	if( Context.m_iMiss >= Context.m_cMisses )
	{
		Context.m_iHit = 0;
		Context.m_iMiss = 0;
	}

	//
	// First take care of hits, then take care of misses.
	//

	// Hit.

	if( Context.m_iHit < Context.m_cHits )
	{
		++Context.m_iHit;

		// Blind fire.

		if( pAI->GetAIBlackBoard()->GetBBBlindFire() )
		{
			GetBlindFirePosition( pAI, outvShootPos, !FIRE_MISS );
			return false;
		}

		// Suppression fire at last known pos.

		if( pAI->GetAIBlackBoard()->GetBBSuppressionFire() )
		{
			HOBJECT hTarget = pAI->GetAIBlackBoard()->GetBBTargetObject();

			CAIWMFact factQuery;
			factQuery.SetFactType( kFact_Character );
			factQuery.SetTargetObject( hTarget );
			CAIWMFact* pFact = pAI->GetAIWorkingMemory()->FindWMFact( factQuery );
			if( pFact )
			{
				outvShootPos = pFact->GetPos();
			}
		}

		// Default fire.

		// If target has started moving or change directions recently,
		// factor in some inaccuracy.

		float fInnaccuracy = LTMAX( 0.f, pAI->GetTarget()->GetCurMovementInaccuracy() );
		if( fInnaccuracy > 0.f )
		{
			LTVector vShootOffset = LTVector(	GetRandom( -fInnaccuracy, fInnaccuracy ),
				GetRandom( -fInnaccuracy * 0.5f, fInnaccuracy * 0.5f ),
				GetRandom( -fInnaccuracy, fInnaccuracy ) );
			vShootOffset.Normalize();

			outvShootPos += vShootOffset * 100.0f;
		}
		
		return true;
	}

	// Miss.

	else 
	{
		++Context.m_iMiss;

		// Blind fire.

		if( pAI->GetAIBlackBoard()->GetBBBlindFire() )
		{
			GetBlindFirePosition( pAI, outvShootPos, FIRE_MISS );
			return false;
		}

		// Default fire.

		HOBJECT hTarget = pAI->GetAIBlackBoard()->GetBBTargetObject();
		if( !IsCharacter( hTarget ) )
		{
			return false;
		}

		CCharacter* pChar = (CCharacter*)g_pLTServer->HandleToObject( hTarget );
		if( !pChar )
		{
			return false;
		}

		// Intentionally shoot a little short of the target.

		LTVector vPos = pAI->GetAIBlackBoard()->GetBBTargetPosition();;

		// Suppression fire at last known pos.

		if( pAI->GetAIBlackBoard()->GetBBSuppressionFire() )
		{
			CAIWMFact factQuery;
			factQuery.SetFactType( kFact_Character );
			factQuery.SetTargetObject( hTarget );
			CAIWMFact* pFact = pAI->GetAIWorkingMemory()->FindWMFact( factQuery );
			if( pFact )
			{
				vPos = pFact->GetPos();
			}
		}

		float fDist = sqrt( pAI->GetTarget()->GetTargetDistSqr() );

		float fRadius = pChar->GetRadius();

		float fRand = GetRandom( 0.f, 1.f );
		fDist -= ( fRadius * 2.f ) + ( fRand * pAI->GetAccuracyMissPerturb() );

		// Calculate a position to the right or left of the target.

		LTVector vDir = vPos - pAI->GetPosition();
		if( vDir != LTVector::GetIdentity() )
		{
			vDir.Normalize();
		}

		vPos = pAI->GetPosition() + ( vDir * fDist );

		LTVector vRight = vDir.Cross( LTVector( 0.f, 1.f, 0.f ) );

		fRand = GetRandom( 0.f, 1.f );
		float fPerturb = ( ( pAI->GetAccuracyMissPerturb() * 2.f ) * fRand ) - pAI->GetAccuracyMissPerturb();
		vRight *= fPerturb;

		// Apply the offset to miss the target.

		outvShootPos = vPos + vRight;

		// Force bullets to land in front of the target, on the floor.

		if( m_pAIWeaponRecord->bForceMissToFloor )
		{
			float fFloor = pAI->GetAIBlackBoard()->GetBBTargetPosition().y;
			fFloor -= pAI->GetAIBlackBoard()->GetBBTargetDims().y;
			outvShootPos.y = fFloor;
		}

		return false;
	}

	return false;
}
コード例 #18
0
ファイル: ddracechat.cpp プロジェクト: ftk/XXLDDRace
void CGameContext::ConRescue(IConsole::IResult *pResult, void *pUserData)
{
	CGameContext *pSelf = (CGameContext *)pUserData;
	CCharacter* pChr = pSelf->m_apPlayers[pResult->m_ClientID]->GetCharacter();

	if(!g_Config.m_SvRescue)
	{
		pSelf->SendChatTarget(pResult->m_ClientID, "Rescue is not activated.");
		return;
	}

	if(!pChr)
	{
		pSelf->SendChatTarget(pResult->m_ClientID, "You are not alive!");
		return;
	}
	
	
	if(pChr->m_DeepFreeze)
	{
		pSelf->SendChatTarget(pResult->m_ClientID, "You are deepfreezed, undeepfreeze first!");
		return;
	}
	if(!pChr->IsAlive())
	{
		pSelf->SendChatTarget(pResult->m_ClientID, "You are not alive!");
		return;
	}
	// unfreeze if pressed second time
	if(pChr->m_RescueFlags & RESCUEFLAG_CAN_UNFREEZE)
	{
		pChr->m_RescueFlags &= ~RESCUEFLAG_CAN_UNFREEZE;
		if(pChr->m_FreezeTime && pChr->m_TileIndex != TILE_FREEZE && pChr->m_TileFIndex != TILE_FREEZE && pChr->Core()->m_Pos == pChr->m_RescuePos)
		{
			pChr->UnFreeze();
			return;
		}
	}
	if(pChr->m_FreezeTime == 0)
		return;
    
	if(pChr->m_LastRescue) // sv_rescue_delay
		return;

	if(pChr->m_RescueOverride)
	{
		pSelf->SendChatTarget(pResult->m_ClientID, "Rescue is disabled by the map.");
		return;
	}

	if(pChr->m_RescuePos == vec2(0,0))
	{
		pSelf->SendChatTarget(pResult->m_ClientID, "No position saved!");
		return;
	}


	// reset players' hook
	for(int i = 0; i < MAX_CLIENTS; i++)
	{
		if(pSelf->m_apPlayers[i])
		{
			CCharacter* pChr2 = pSelf->m_apPlayers[i]->GetCharacter();
			//who hooks me?
			if(pChr2 && pChr2->Core()->m_HookedPlayer == pResult->m_ClientID)
			{
				//Release hook
				pChr2->Core()->m_HookedPlayer = -1;
				pChr2->Core()->m_HookState = HOOK_RETRACTED;
				pChr2->Core()->m_HookPos = pChr2->Core()->m_Pos;
			}
		}
	}
	if(g_Config.m_SvRescueEffects)
	{
		//Blood effect
		pChr->GameServer()->CreateDeath(pChr->m_Pos, pResult->m_ClientID);
		//Spawn effect
		pChr->GameServer()->CreatePlayerSpawn(pChr->m_RescuePos);
	}
	//Teleport player
	pChr->Core()->m_Pos = pChr->m_PrevPos = pChr->m_Pos = pChr->m_RescuePos;
	pChr->Core()->m_Vel = vec2(0.f, 0.f); // reset momentum

	if(pChr->m_RescueFlags)
	{
		// disarm player
		if(pChr->m_RescueFlags & RESCUEFLAG_DISARM)
		{
			bool disarmed = false;
			for(int i = WEAPON_SHOTGUN; i < NUM_WEAPONS; i++)
			{
				if(pChr->GetWeaponGot(i) && i != WEAPON_NINJA)
				{
					pChr->SetWeaponGot(i, false);
					pChr->SetWeaponAmmo(i, 0);
					disarmed = true;
				}
			}
			if(disarmed)
				pChr->GameServer()->SendChatTarget(pResult->m_ClientID, "You have been disarmed");
		}
		// solo fix
		if(pChr->m_RescueFlags & RESCUEFLAG_SOLOOUT)
		{
			pChr->GameServer()->SendChatTarget(pResult->m_ClientID, "You are now in a solo part");
			pChr->m_Solo = true;
		}
		else if(pChr->m_RescueFlags & RESCUEFLAG_SOLOIN)
		{
			pChr->GameServer()->SendChatTarget(pResult->m_ClientID, "You are now out of the solo part");
			pChr->m_Solo = false;
		}
		// hit fix
		if(pChr->m_RescueFlags & RESCUEFLAG_NOHIT)
		{
			pChr->GameServer()->SendChatTarget(pResult->m_ClientID, "You can hit others");
			pChr->m_Hit = CCharacter::HIT_ALL;
		}
		else if(pChr->m_RescueFlags & RESCUEFLAG_HIT)
		{
			pChr->GameServer()->SendChatTarget(pResult->m_ClientID, "You can't hit others");
			pChr->m_Hit = CCharacter::DISABLE_HIT_GRENADE|CCharacter::DISABLE_HIT_HAMMER|
				CCharacter::DISABLE_HIT_RIFLE|CCharacter::DISABLE_HIT_SHOTGUN;
		}
		// endless hook fix
		if(pChr->m_RescueFlags & RESCUEFLAG_NOEHOOK && !pChr->m_EndlessHook)
		{
			pChr->GameServer()->SendChatTarget(pResult->m_ClientID, "Endless hook has been activated");
			pChr->m_EndlessHook = true;
		}
		else if(pChr->m_RescueFlags & RESCUEFLAG_EHOOK && pChr->m_EndlessHook)
		{
			pChr->GameServer()->SendChatTarget(pResult->m_ClientID, "Endless hook has been deactivated");
			pChr->m_EndlessHook = false;
		}
		pChr->m_RescueFlags = RESCUEFLAG_NONE;
	}
	//"save" last rescue time
	pChr->m_LastRescue = ((float)g_Config.m_SvRescueDelay / 1000) * pSelf->Server()->TickSpeed();
	pChr->m_RescueFlags |= RESCUEFLAG_CAN_UNFREEZE;
}
コード例 #19
0
int CGameControllerMOD::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon)
{
	// do scoreing
	if(!pKiller || Weapon == WEAPON_GAME)
		return 0;
		
	if(pKiller->IsInfected())
	{
		CPlayer* pVictimPlayer = pVictim->GetPlayer();
		if(pVictimPlayer)
		{
			if(!pVictim->IsInfected())
			{
				GameServer()->SendChatTarget_Localization(pKiller->GetCID(), CHATCATEGORY_SCORE, _("You have infected {str:VictimName}, +3 points"), "VictimName", Server()->ClientName(pVictimPlayer->GetCID()), NULL);
				Server()->RoundStatistics()->OnScoreEvent(pKiller->GetCID(), SCOREEVENT_INFECTION, pKiller->GetClass());
				GameServer()->SendScoreSound(pKiller->GetCID());
				
				//Search for hook
				for(CCharacter *pHook = (CCharacter*) GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER); pHook; pHook = (CCharacter *)pHook->TypeNext())
				{
					if(
						pHook->GetPlayer() &&
						pHook->m_Core.m_HookedPlayer == pVictim->GetPlayer()->GetCID() &&
						pHook->GetPlayer()->GetCID() != pKiller->GetCID()
					)
					{
						Server()->RoundStatistics()->OnScoreEvent(pHook->GetPlayer()->GetCID(), SCOREEVENT_HELP_HOOK_INFECTION, pHook->GetClass());
						GameServer()->SendScoreSound(pHook->GetPlayer()->GetCID());
					}
				}
			}
		}
	}
	else
	{
		if(pKiller == pVictim->GetPlayer())
		{
			Server()->RoundStatistics()->OnScoreEvent(pKiller->GetCID(), SCOREEVENT_HUMAN_SUICIDE, pKiller->GetClass());
		}
		if(pVictim->GetClass() == PLAYERCLASS_WITCH)
		{
			GameServer()->SendChatTarget_Localization(pKiller->GetCID(), CHATCATEGORY_SCORE, _("You have killed a witch, +5 points"), NULL);
			Server()->RoundStatistics()->OnScoreEvent(pKiller->GetCID(), SCOREEVENT_KILL_WITCH, pKiller->GetClass());
			GameServer()->SendScoreSound(pKiller->GetCID());
		}
		else if(pKiller->GetClass() == PLAYERCLASS_NINJA && pVictim->GetPlayer()->GetCID() == GameServer()->GetTargetToKill())
		{
			GameServer()->SendChatTarget_Localization(pKiller->GetCID(), CHATCATEGORY_SCORE, _("You have eliminated your target, +3 points"), NULL);
			Server()->RoundStatistics()->OnScoreEvent(pKiller->GetCID(), SCOREEVENT_KILL_TARGET, pKiller->GetClass());
			GameServer()->SendScoreSound(pKiller->GetCID());
			GameServer()->TargetKilled();
		}
		else if(pVictim->IsInfected())
		{
			Server()->RoundStatistics()->OnScoreEvent(pKiller->GetCID(), SCOREEVENT_KILL_INFECTED, pKiller->GetClass());
			GameServer()->SendScoreSound(pKiller->GetCID());
		}
	}
		
	//Add bonus point for ninja
	if(pVictim->IsInfected() && pVictim->IsFrozen() && pVictim->m_LastFreezer >= 0 && pVictim->m_LastFreezer != pKiller->GetCID())
	{
		CPlayer* pFreezer = GameServer()->m_apPlayers[pVictim->m_LastFreezer];
		if(pFreezer)
		{
			Server()->RoundStatistics()->OnScoreEvent(pFreezer->GetCID(), SCOREEVENT_HELP_FREEZE, pFreezer->GetClass());
			GameServer()->SendScoreSound(pFreezer->GetCID());
		}
	}
	
	if(Weapon == WEAPON_SELF)
		pVictim->GetPlayer()->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()*3.0f;
		
	return 0;
}
コード例 #20
0
bool ServerPhysicsCollisionMgr::StartAIStimulusResponse( CollisionResponse& collisionResponse )
{
	// Get the aistimulus record struct.
	HATTRIBUTE hStruct = DATABASE_CATEGORY( CollisionProperty ).GETSTRUCTSTRUCT( Responses, 
		collisionResponse.GetResponses(), collisionResponse.GetResponsesIndex( ), AIStimulusRecord );
	if( !hStruct )
		return false;

	uint32 nIndexFound;
	uint32 nImpulseFound;
	if( !FindImpulseInTable( collisionResponse.GetImpulse( ), hStruct, AIStimulusRecordImpulseAccessCB, nIndexFound, nImpulseFound ))
		return false;

	// Determine the stimulus type.
	HRECORD hStimulus = DATABASE_CATEGORY( CollisionProperty ).GETSTRUCTATTRIB( AIStimulusRecord, hStruct, nIndexFound, Stimulus );
	if( !hStimulus )
		return false;
	const char* pszStimulus = g_pLTDatabase->GetRecordName( hStimulus );
	if( !pszStimulus || !pszStimulus[0] )
		return false;

	// Bail if stimulus does not exist.
	EnumAIStimulusType eStimulus = (EnumAIStimulusType)g_pAIDB->String2BitFlag( pszStimulus, kStim_Count, s_aszStimulusTypes );
	if( eStimulus == kStim_InvalidType )
		return false;

	// Use the generic object alignment set in GDBEdit under AI/Constants.
	EnumCharacterAlignment eAlignment = g_pCharacterDB->String2Alignment(g_pAIDB->GetAIConstantsRecord()->strObjectAlignmentName.c_str());

	// Interpolate the radius of the stimulus.
	float fRadius = FindStimulusRadius( collisionResponse );

	// Bail if either character has sound disabled.
	// This is a hack to prevent AI from generating stimuli.
	// (e.g. at the begining of the FEAR Docks level, where
	// we have a scripted execution scene, and do not want the
	// AI to start investigating when a body hits the ground).
	HOBJECT hActor = collisionResponse.GetCollisionActor()->GetObject();
	HOBJECT hOtherActor = collisionResponse.GetCollisionActor()->GetOtherCollisionActor()->GetObject();

	if( IsCharacter( hActor ) )
	{
		CCharacter* pChar = (CCharacter*)g_pLTServer->HandleToObject( hActor );
		if( pChar && pChar->GetSoundOuterRadius() == 0.f )
		{
			return false;
		}
	}
	if( IsCharacter( hOtherActor ) )
	{
		CCharacter* pChar = (CCharacter*)g_pLTServer->HandleToObject( hOtherActor );
		if( pChar && pChar->GetSoundOuterRadius() == 0.f )
		{
			return false;
		}
	}

	// Register the stimulus.
	StimulusRecordCreateStruct scs( eStimulus, eAlignment, collisionResponse.GetCollisionPoint( ), hActor );
	scs.m_hStimulusTarget = hOtherActor;
	scs.m_flRadiusScalar = fRadius;
	g_pAIStimulusMgr->RegisterStimulus( scs );

#ifndef _FINAL
	uint32 nStatsLevel;
	bool bServer;
	HRECORD hCollisionPropertyFilter = NULL;
	CollisionStatsLevel( nStatsLevel, bServer, hCollisionPropertyFilter );
	if( nStatsLevel > 0 &&
		( !hCollisionPropertyFilter || hCollisionPropertyFilter == collisionResponse.GetCollisionProperty()))
	{
		g_pLTBase->CPrint( "S:  AIStimulus(%s)", pszStimulus );
	}
#endif // _FINAL

	return true;
}
コード例 #21
0
//-----------------------------------------------
// CFaberPhrase validate
//-----------------------------------------------
bool CFaberPhrase::validate()
{
	H_AUTO(CFaberPhrase_validate);
	
	if ( !CraftSystemEnabled )
		return false;
	
	CCharacter * c = (CCharacter *) CEntityBaseManager::getEntityBasePtr( _ActorRowId );
	if( c == 0 )
	{
		nlwarning("<CFaberPhrase::validate> Player character not found but his crafting action still running!!!");
		return false;
	}

	// test entity can use action
	if (c->canEntityUseAction() == false)
	{
		return false;
	}

	// check right hand item is a crafting tool 
	CGameItemPtr rightHandItem = c->getRightHandItem();
	if (rightHandItem == NULL || rightHandItem->getStaticForm() == NULL || rightHandItem->getStaticForm()->Family != ITEMFAMILY::CRAFTING_TOOL)
	{
		PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CRAFT_NEED_CRAFTING_TOOL");
		return false;
	}

	// check tool is not worned
	if( rightHandItem->getItemWornState() == ITEM_WORN_STATE::Worned )
	{
		PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CRAFT_NEED_CRAFTING_TOOL");
		return false;
	}

	// entities cant craft if in combat
	/* commented as test of right hand item is now made... 
	TDataSetRow entityRowId = CPhraseManager::getInstance().getEntityEngagedMeleeBy( _ActorRowId );
	if (TheDataset.isAccessible(entityRowId))
	{
		PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CANT_CRAFT_ENGAGED_IN_MELEE");
		return false;
	}
	*/
	
	const sint32 focus = c->getScores()._PhysicalScores[ SCORES::focus ].Current;
	if ( focus < _FocusCost  )
	{
		PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CANT_CRAFT_NOT_ENOUGHT_FOCUS");
		c->unlockFaberRms();
		return false;
	}

	const sint32 hp = c->currentHp();
	if (hp <= 0	||	c->isDead())
	{
		PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CANT_CRAFT_WHEN_DEAD");
		c->unlockFaberRms();
		return false;
	}

	/// todo alain : test if on mount

	// store vector of pointer on raw material item
	if( state() == Evaluated )
	{
		if( c->lockFaberRms() )
		{
			_Mps.clear();
			_MpsFormula.clear();
			if( c->getFillFaberRms( _Mps, _MpsFormula, _LowerRmQuality ) == false ) //TODO check exec step
			{
				c->unlockFaberRms();
				PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CANT_FOUND_RM");
				return false;
			}
		}
		else
		{
			c->unlockFaberRms();
			PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, "CANT_LOCK_RM");
			return false;
		}
	}

	return true;
}// CFaberPhrase validate
コード例 #22
0
ファイル: battle.cpp プロジェクト: osROSE/osprose
void CCharacter::DoAttack( )
{
    //if(Status->Sleep <= 0xff)
    //{
    //    ClearBattle( Battle );
    //    return; // can't take any action while we are asleep can we?
    //}
    //Log(MSG_INFO,"skill type %i selected. Chartype = %i",Battle->atktype, CharType);
    if(Battle->iscasting == 1) 
    {
        CCharacter* Enemy = GetCharTarget( );
        if(Enemy == NULL)
        {
            ClearBattle( Battle );
            return;
        }
        //Log(MSG_DEBUG,"Iscasting detected as true. Reset to false.");
        if(CanAttack())
        {
            //if(IsPlayer())
            //{
            //    Log(MSG_DEBUG,"Should reach here once on normal attack. iscasting state = %i",Battle->iscasting);
            //}
            ClearBattle( Battle );
            StartAction(Enemy, NORMAL_ATTACK, 0);
        }
        else
        {
            return;
        }
        return;
    }
    if(!CanAttack())
    {
        return;
    }
    if(IsSummon())
    {
        CCharacter* Enemy = GetCharTarget( );
        if(Enemy == NULL || (Battle->atktype != SKILL_AOE && Battle->atktype != BUFF_AOE))
        {
            //Log(MSG_DEBUG,"No Enemy found");
            ClearBattle( Battle );
            return;
        }
        if(this == Enemy) //summoned monster is attacking itself. It has been observed to happen
        {
            //Log(MSG_INFO,"Clearing Battle for this summon");
            ClearBattle( Battle );
            return;
        }
        if(Enemy->IsSummon())
        {
            CMonster* thisMonster = reinterpret_cast<CMonster*>(this);
            if(thisMonster == NULL)
            {
                ClearBattle( Battle );
                return;           
            }
            CMonster* otherMonster = reinterpret_cast<CMonster*>(Enemy);
            if(otherMonster == NULL)
            {
                ClearBattle( Battle );
                return;           
            }
            if(thisMonster->owner == otherMonster->owner)
            {
                //Log(MSG_INFO,"Clearing Battle for this summon");
                ClearBattle( Battle );
                return;                    
            }                
        }
    }
    CMap* map = GServer->MapList.Index[Position->Map];
    //Log(MSG_INFO,"DoAttack Battle Attack type = %i",Battle->atktype);
    switch(Battle->atktype)
    {
        case NORMAL_ATTACK://normal attack
        {
            //if(!Status->CanAttack)
            //    return; //can't attack right now.
            CCharacter* Enemy = GetCharTarget( );
            if(Enemy == NULL)
            {
                ClearBattle( Battle );
                return;
            }
            if(Enemy == this)
            {
                //Log(MSG_INFO,"WTF?? I AM trying to attack myself");
                ClearBattle( Battle );
            }
            if(IsTargetReached( Enemy ))
            {
                //if(IsMonster())
                //    Log(MSG_INFO,"Monster is trying to hit the player");
                NormalAttack( Enemy );
                if (Enemy->IsMonster()) // do monster AI script when monster is attacked.
                {
                    CMonster* monster = GServer->GetMonsterByID(Enemy->clientid, Enemy->Position->Map);
                    if(monster == NULL)return;
                    //monster->DoAi(monster->thisnpc->AI, 3);
                    monster->DoAi(monster->monAI, 3);
                }
            }
        }
        break;
        case SKILL_ATTACK://skill attack
        {
            CCharacter* Enemy = GetCharTarget( );
            if(Enemy == NULL)
            {
                ClearBattle( Battle );
                return;
            }
            CSkills* skill = GServer->GetSkillByID( Battle->skillid );
            if(skill == NULL)
            {
                //ClearBattle( Battle );
                return;
            }
            if(IsTargetReached( Enemy, skill )) 
            {
                SkillAttack( Enemy, skill );
                if (Enemy->IsMonster())
                {
                    CMonster* monster = GServer->GetMonsterByID(Enemy->clientid, Enemy->Position->Map);
                    if(monster == NULL)return;
                    monster->DoAi(monster->monAI, 3);
                }
            }
        }
        break;
        case SKILL_BUFF://buffs
        {


            CCharacter* Enemy = GetCharTarget( );
            if(Enemy == NULL)
            {
                //Log(MSG_DEBUG,"this target is NULL");
                ClearBattle( Battle );
                return;
            }
            CSkills* skill = GServer->GetSkillByID( Battle->skillid );
            if(skill == NULL)
            {
                //Log(MSG_DEBUG,"this skill is NULL");
                return;
            }

            if(IsTargetReached( Enemy, skill ))
            {
                //Log(MSG_DEBUG,"Skill successfully cast");
                BuffSkill( Enemy, skill );
            }
        }
        break;
        case SKILL_AOE:
        //case SKILL_SELF: //this is impossible. it can never be set
        case AOE_TARGET:
        {


            //Log(MSG_DEBUG,"Called skill type %i",Battle->atktype);
            CCharacter* Enemy = NULL;
            CSkills* skill = GServer->GetSkillByID( Battle->skillid );
            if(skill == NULL)
            {
                ClearBattle( Battle );
                return;
            }
            if(Battle->atktype == AOE_TARGET)
            {
                float distance = GServer->distance( Position->current, Position->destiny );
                if(distance <= skill->range)
                {
                    Position->destiny = Position->current;
                    AoeSkill( skill, Enemy );
                }
            }
            else
            {
                Position->skilltargetpos = Position->current;
                AoeSkill( skill, NULL );
            }
        }
        break;
        case BUFF_SELF:
        {

            //    return; // can't cast skills right now
            CSkills* skill = GServer->GetSkillByID( Battle->skillid );
            if(skill == NULL)
            {
                //ClearBattle( Battle );
                return;
            }
            BuffSkill( this, skill );
        }
        break;
        case BUFF_AOE:
        {
            //Log(MSG_INFO,"BUFF AOE selected");
            CSkills* skill = GServer->GetSkillByID( Battle->skillid );
            if(skill == NULL)
            {
                //ClearBattle( Battle );

                return;
            }
            AoeBuff( skill );
        }
        break;
        default:
            return;
        break;
    }
}
コード例 #23
0
ファイル: chars_segment.cpp プロジェクト: felixqin/EasyPR
bool slideChineseWindow(Mat& image, Rect mr, Mat& newRoi, Color plateType, float slideLengthRatio, bool useAdapThreshold) {
  std::vector<CCharacter> charCandidateVec;
  
  Rect maxrect = mr;
  Point tlPoint = mr.tl();

  bool isChinese = true;
  int slideLength = int(slideLengthRatio * maxrect.width);
  int slideStep = 1;
  int fromX = 0;
  fromX = tlPoint.x;
  
  for (int slideX = -slideLength; slideX < slideLength; slideX += slideStep) {
    float x_slide = 0;

    x_slide = float(fromX + slideX);

    float y_slide = (float)tlPoint.y;
    Point2f p_slide(x_slide, y_slide);

    //cv::circle(image, p_slide, 2, Scalar(255), 1);

    int chineseWidth = int(maxrect.width);
    int chineseHeight = int(maxrect.height);

    Rect rect(Point2f(x_slide, y_slide), Size(chineseWidth, chineseHeight));

    if (rect.tl().x < 0 || rect.tl().y < 0 || rect.br().x >= image.cols || rect.br().y >= image.rows)
      continue;

    Mat auxRoi = image(rect);

    Mat roiOstu, roiAdap;
    if (1) {
      if (BLUE == plateType) {
        threshold(auxRoi, roiOstu, 0, 255, CV_THRESH_BINARY + CV_THRESH_OTSU);
      }
      else if (YELLOW == plateType) {
        threshold(auxRoi, roiOstu, 0, 255, CV_THRESH_BINARY_INV + CV_THRESH_OTSU);
      }
      else if (WHITE == plateType) {
        threshold(auxRoi, roiOstu, 0, 255, CV_THRESH_BINARY_INV + CV_THRESH_OTSU);
      }
      else {
        threshold(auxRoi, roiOstu, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);
      }
      roiOstu = preprocessChar(roiOstu, kChineseSize);

      CCharacter charCandidateOstu;
      charCandidateOstu.setCharacterPos(rect);
      charCandidateOstu.setCharacterMat(roiOstu);
      charCandidateOstu.setIsChinese(isChinese);
      charCandidateVec.push_back(charCandidateOstu);
    }
    if (useAdapThreshold) {
      if (BLUE == plateType) {
        adaptiveThreshold(auxRoi, roiAdap, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, 0);
      }
      else if (YELLOW == plateType) {
        adaptiveThreshold(auxRoi, roiAdap, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV, 3, 0);
      }
      else if (WHITE == plateType) {
        adaptiveThreshold(auxRoi, roiAdap, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV, 3, 0);
      }
      else {
        adaptiveThreshold(auxRoi, roiAdap, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, 0);
      }
      roiAdap = preprocessChar(roiAdap, kChineseSize);

      CCharacter charCandidateAdap;
      charCandidateAdap.setCharacterPos(rect);
      charCandidateAdap.setCharacterMat(roiAdap);
      charCandidateAdap.setIsChinese(isChinese);
      charCandidateVec.push_back(charCandidateAdap);
    }

  }

  CharsIdentify::instance()->classifyChinese(charCandidateVec);

  double overlapThresh = 0.1;
  NMStoCharacter(charCandidateVec, overlapThresh);

  if (charCandidateVec.size() >= 1) {
    std::sort(charCandidateVec.begin(), charCandidateVec.end(),
      [](const CCharacter& r1, const CCharacter& r2) {
      return r1.getCharacterScore() > r2.getCharacterScore();
    });

    newRoi = charCandidateVec.at(0).getCharacterMat();
    return true;
  }

  return false;

}
コード例 #24
0
ファイル: building.cpp プロジェクト: TsFreddie/New-Nodes
void CBuilding::Tick()
{
	// handle death-tiles and leaving gamelayer
	if(GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/2.f, m_Pos.y-m_ProximityRadius/2.f)&CCollision::COLFLAG_DEATH ||
		GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/2.f, m_Pos.y+m_ProximityRadius/2.f)&CCollision::COLFLAG_DEATH ||
		GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/2.f, m_Pos.y-m_ProximityRadius/2.f)&CCollision::COLFLAG_DEATH ||
		GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/2.f, m_Pos.y+m_ProximityRadius/2.f)&CCollision::COLFLAG_DEATH ||
		GameLayerClipped(m_Pos))
	{
		Die(-1, WEAPON_WORLD);
		return;
	}
	
	if(!IsGrounded()) {
		Die(-1, WEAPON_WORLD);
		return;
	}
	
	
	
	if(Server()->Tick() % 5 == 0 && m_Decon) {
		if( ((CGameControllerNODES*)GameServer()->m_pController)->Spawns[m_Team] <= 0)
		{
			m_Decon = false;
		} else {
			TakeDamage(vec2(0,0), 1, -1, WEAPON_SELF);
		}
	}
		
	if(m_Decay > 0)
		m_Decay--;
		
	if(m_AnimDecay > 0)
		m_AnimDecay--;
		
	if(m_SpawnanimDecay > 0)
		m_SpawnanimDecay--;

	m_Power = Powered();

	if(!m_Power && (m_Type == B_REPEATER || m_Type == B_TELEPORT))
		m_Anim = 0;
	
	if(!m_Power)
		m_Hit = 0;
		
	
		
	if(!m_Power && m_Type == B_TELEPORT)
		m_Anim = 0;

	if(!m_Alive || (!m_Power && m_Type != B_SHIELD))
		return;

	if(Server()->Tick() % 100 == 0 && m_Health < m_Maxhealth/4) {
		GameServer()->CreateExplosion(pos, -1, -1, true);
		
	}	
	
	switch(m_Type) {
		case B_REACTOR: {
			if(m_AnimDecay == 0) {
				m_Anim++;
				if(m_Anim > 3) {
					m_Anim = 0;
					m_AnimDecay = 100;
				} else
					m_AnimDecay = 10;
			}
		} break;
		
		case B_REPEATER: {
			if(!m_Power) {
				m_Anim = 0;
			} else {
				if(m_AnimDecay == 0) {
					m_Anim++;
					if(m_Anim > 1) {
						m_Anim = 0;
						m_AnimDecay = 100;
					} else
						m_AnimDecay = 10;
				}
			}
		} break;
		
		case B_SPAWN: {
			m_Anim = m_Anim & 0xF;
			if(m_AnimDecay == 0) {
				m_Anim++;
				if(m_Anim > 6)
					m_Anim = 0;
				m_AnimDecay = 35;
			}
			if(m_Spawnanim > 0 && m_SpawnanimDecay == 0) {
				m_Spawnanim--;
				m_SpawnanimDecay = 4;
			}
			m_Anim = (m_Spawnanim << 4) | m_Anim;
		} break;
		case B_AMMO1: case B_AMMO2: case B_AMMO3: {
			CCharacter *c = GetNearest(ms_PhysSize, m_Team);
			if(c) {
				if(m_Anim < 3 && m_AnimDecay == 0) {
					m_Anim++;
					m_AnimDecay = 4;
				}
				if(m_Decay == 0 && m_Anim == 3) {
					m_Decay = 50;
					int weapon = -1;
					if(m_Type == B_AMMO1)
						weapon = WEAPON_SHOTGUN;
					else if(m_Type == B_AMMO2) 
						weapon = WEAPON_GRENADE;
					else if(m_Type == B_AMMO3)
						weapon = WEAPON_RIFLE;
					if(!c->m_Weapons[weapon].m_Got) {
						c->m_Weapons[weapon].m_Got = 1;	
						c->m_ActiveWeapon = weapon;
						GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN);
					} else {
						GameServer()->CreateSound(m_Pos, SOUND_PICKUP_GRENADE);
					}
					c->m_Weapons[weapon].m_Ammo = 10;
				}
			}
			else {
				if(m_Anim > 0 && m_AnimDecay == 0) {
					m_Anim--;
					m_AnimDecay = 4;
				}
			}
		} break;
		
		case B_TURRET1: {
			vec2 realpos = vec2(m_Pos.x, m_Pos.y-74);
			vec2 tmppos = m_Pos;
			m_Pos = realpos;
			CCharacter *c = GetNearest(700, m_Team^1);
			m_Pos = tmppos;
			if(c) {
				m_Angle = GetAngle(normalize(c->m_Pos - realpos));
				if(m_Decay == 0) {
					m_Decay = 12;
						float a = m_Angle;
						a+=frandom()*0.20f -0.10f;
						CProjectile *pProj = new CProjectile(WEAPON_GUN,
							-1,
							realpos,
							vec2(cosf(a), sinf(a)),
							(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime),
							1, 0, 0, -1, WEAPON_GUN, false);
					GameServer()->CreateSound(realpos, SOUND_GUN_FIRE);
				}
			}
		} break;
		
		case B_TURRET2: {
			vec2 realpos = vec2(m_Pos.x, m_Pos.y-66);
			vec2 tmppos = m_Pos;
			m_Pos = realpos;
			CCharacter *c = GetNearest(500, m_Team^1);
			m_Pos = tmppos;
			if(c) {
				m_Angle = GetAngle(normalize(c->m_Pos-realpos));
				if(m_Decay == 0) {
					m_Decay = 30;
					int shotspread = 2;
					
					for(int i = -shotspread; i <= shotspread; i++)
					{
						float spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f};
						float a = m_Angle;
						a += spreading[i+2];
						float v = 1-(abs(i)/(float)shotspread);
						float speed = mix((float)tuning.shotgun_speeddiff, 1.0f, v);
						CProjectile *pProj = new CProjectile(WEAPON_SHOTGUN,
							-2, 
							realpos,
							vec2(cosf(a), sinf(a))*speed,
							(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_ShotgunLifetime),
							1, 0, 0, -1, WEAPON_SHOTGUN, false);
					}
					game.create_sound(realpos, SOUND_SHOTGUN_FIRE);
				}
			}
		} break;
		
		case B_HEALTH: case B_ARMOR: {
			CCharacter *c = GetNearest(ms_PhysSize, m_Team);
			if(c) {
				if(m_Decay == 0) { //wait for open first
					if(m_AnimDecay == 0 && m_Decay == 0 && m_Anim < 4) {
						m_AnimDecay = 3;
						m_Anim++;
					}
					else if(m_AnimDecay == 0) {
						if(m_Type == B_HEALTH && c->m_Health < 10) {
							m_Decay = 150;
							c->IncreaseHealth(3);
							GameServer()->CreateSound(m_Pos, SOUND_PICKUP_HEALTH);
							c->m_Ill = false;
						} else if(m_Type == B_HEALTH) {
							c->m_Ill = false;
						} else if(m_Type == B_ARMOR && c->m_Armor < 10) {
							m_Decay = 150;
							c->IncreaseArmor(3);
							GameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR);
						}
					}
				}
			}
			else { 
				if(m_AnimDecay == 0 && m_Decay == 0 && m_Anim > 0) {
					m_AnimDecay = 3;
					m_Anim--;
				}
			}
		} break;
		
		case B_SHIELD: {
			if(Server()->Tick() % 50 == 0 && m_Power) {
				if(m_Armor < 30)
					m_Armor++;				
				//game.create_damageind(pos, 3.141592, armor > 0 ? (int)(10.0f*armor/30) : 0);
			}
			
			if(Server()->Tick() % 5 == 0) {
				if(m_Hit > 0)
					m_Hit--;
				if(m_Power && m_Armor > 0) {
					CProjectile *pProj[128];
					int num = GameServer()->m_World.FindEntities(m_Pos, 250.0f, (CEntity**)pProj, 128, CGameWorld::ENTTYPE_PROJECTILE);
					for(int i = 0; i < num && m_Armor > 0; i++) {
						if(pProj[i]->m_Bounce)
							continue;
						if((pProj[i]->m_Owner >= 0) && GameServer()->m_apPlayers[pProj[i]->m_Owner] && GameServer()->m_apPlayers[pProj[i]->m_Owner]->m_Team == m_Team)
							continue;
						if(pProj[i]->m_Owner < 0)
							continue;
						
						pProj[i]->m_Initpos = pProj[i]->m_Pos;
						pProj[i]->m_StartTick = Server()->Tick();
						pProj[i]->m_Direction = normalize(pProj[i]->m_Pos-m_Pos);
						pProj[i]->m_Bounce = 1;
						m_Hit = 3;
						
						//game.create_shieldhit(m_Pos, 0);
						
						m_Armor = clamp(m_Armor-(pProj[i]->m_Weapon == WEAPON_GRENADE ? 4 : 2), 0, 30);
						if(m_Armor == 0) {
							m_Armor = -4;
						}
					}
				}
			}
			m_Anim = (m_Armor > 0 ? (int)(9.0f*m_Armor/30.0f) : 0) | (m_Hit << 4);
		} break;
		
		//NODESTODO: COUNTINUE!
		case B_TELEPORT: {
			if(m_Decay == 0) {
				//find other teleport... D=
				CBuilding *other = 0;
				for(int i = 0; i < ((CGameControllerNODES*)GameServer()->m_pController)->BuildingsCount[m_Team]; i++) {
					CBuilding *b = ((CGameControllerNODES*)GameServer()->m_pController)->Buildings[m_Team][i];
					if( b != this && b->m_Type == B_TELEPORT && b->m_Alive && b->m_Power) {
						other = b;
					}
				}
				if(other) {
					bool is_enemy = false;
					CCharacter *c = GetNearest(ms_PhysSize-4.0f, m_Team); 
					if(!c && m_Anim == 8) {//once opened, port enemies as well
						c = GetNearest(ms_PhysSize-4.0f, m_Team^1);
						is_enemy = true;
					}
					if(c) {
						if(m_Anim < 8 && m_AnimDecay == 0 && !is_enemy) {
							m_Anim++;
							m_AnimDecay = 2;
							other->m_Anim = m_Anim;
							other->m_AnimDecay = m_AnimDecay+1;
							other->m_Decay =m_AnimDecay+1;
						}
						else if(anim == 8 && m_AnimDecay == 0) {
							if(!c->m_pPlayer->m_Ported) {
								//dbg_msg("nodes", "yay");
								float ill_prob = min((distance(other->m_Pos, m_Pos))/8000.0f * 0.2f, 0.2f);
								for(int i = 0; i < MAX_CLIENTS; i++) {
									if(game.players[i] && game.players[i]->get_character() && (game.players[i]->get_character()->core.hooked_player == c->player->client_id || c->core.hooked_player == game.players[i]->client_id)) {
										CCharacter *hc = game.players[i]->get_character();
										hc->m_Pos = vec2(other->m_Pos.x, other->m_Pos.y-1);
										hc->core.m_Pos = vec2(other->m_Pos.x, other->m_Pos.y-1);
										hc->player->ported = true;
										hc->core.hook_state = -1;
										hc->core.hooked_player = -1;
										if(frandom() <= ill_prob) {
											if(!hc->ill) {
												hc->ill = true;
												hc->infecter = -1;
											}
										}
									}
								}
								//dbg_msg("nodes", "porting %d from (%d,%d) to (%d,%d)", c->player->client_id, (int)pos.x, (int)pos.y, (int)other->pos.x, (int)other->pos.y);
								c->pos = vec2(other->pos.x, other->pos.y-1);
								c->core.pos = vec2(other->pos.x, other->pos.y-1);
								c->player->ported = true;
								c->core.hook_state = -1;
								c->core.hooked_player = -1;
								if(frandom() <= ill_prob) {
									if(!c->ill) {
										c->ill = true;
										c->infecter = -1;
									}
								}
								decay = 50;
								other->decay = 50;
								anim = 1;
								other->anim = 1;
								game.create_playerspawn(other->pos);
								game.create_sound(pos, SOUND_TELEPORT);
								game.create_death(pos, c->player->client_id);
								game.create_sound(other->pos, SOUND_TELEPORT);
							} else {
								anim = 0;
							}
						}
					}
					else {
						if(anim > 0 && anim_decay == 0) {
							anim++;
							if(anim == 9)
								anim = 0;
							anim_decay = 2;
							other->anim = anim;
							other->anim_decay = anim_decay+1;
							other->decay =anim_decay+1;
						}
					}
				}
			} else {
				if(anim_decay == 0 && anim > 0) {
					anim_decay = 2;
					anim++;
					if(anim == 9)
						anim = 0;
				}
			}
		} break;
	}

	return;
}
コード例 #25
0
ファイル: harvest_source.cpp プロジェクト: sythaeryn/pndrpg
/*
 * Update the source state with an extraction (see doc in .h).
 */
void CHarvestSource::extractMaterial( float *reqPosProps, float *absPosProps, float qualityCeilingFactor, float qualitySlowFactor, float *results, float successFactor, uint8 lifeAbsorberRatio, const TDataSetRow& extractingEntityRow, CHarvestSource::TRealTimeProp& propDrop )
{
	H_AUTO(CHarvestSource_extractMaterial);

	CCharacter* player = PlayerManager.getChar( extractingEntityRow );
	
	++_NbExtractions; // it's 1 at the first call, so that the initial value is used
	float nbe = (float)_NbExtractions;

	if ( (successFactor < 0.1f) || ForceDropProp )
	{
		if ( _NbExtractions < 6 )
			propDrop = Q; // don't drop A at the beginning (wait to reach 1 (cumulated) would be better)
		else
			propDrop = (TRealTimeProp)(RandomGenerator.rand(1)+1);
		nldebug( "Prop drop %u", propDrop );
	}

	// Aperture: converges towards the requested value, except when a drop occurs (0 at this step)
//	if ( reqPosProps[A] > 0 )
	{
		float obtainedQuantity = (propDrop == A) ? 0.0f : (results[A]*ForageQuantitySlowFactor.get() + reqPosProps[A]) / (ForageQuantitySlowFactor.get()+1);

		// Apply possible aperture bonus
		if ( _BonusForAPct != 0 )
		{
			obtainedQuantity += obtainedQuantity * (float)((uint)_BonusForAPct) * 0.01f;
		}
		
		// Extract material
		if ( _ForageSite )
			obtainedQuantity = _ForageSite->consume( obtainedQuantity ); // consume (and limit) in forage site & deposit
		if ( obtainedQuantity > _N ) // should not occur because _N uses the deposit quantity
			obtainedQuantity = _N;
		_N -= obtainedQuantity;
		_A = (_A*nbe + obtainedQuantity) / (nbe + 1.0f); // average per source
		_DepositForK->incKamiAnger( obtainedQuantity, _Foragers );
		if ( (obtainedQuantity == 0) && (results[A] != 0) && (! (propDrop == A)) )
			PHRASE_UTILITIES::sendDynamicSystemMessage( _Foragers[0], "FORAGE_DEPOSIT_IS_EMPTY" );
		results[A] = obtainedQuantity;
		
		// add spire effect ( quantity )
		if ( player )
		{
			const CSEffect* pEffect = player->lookForActiveEffect( EFFECT_FAMILIES::TotemHarvestQty );
			if ( pEffect != NULL )
			{
				results[A] *= ( 1.0f + pEffect->getParamValue() / 100.0f );
			}
		}
		// add item special effect
		if ( player )
		{
			std::vector<SItemSpecialEffect> effects = player->lookForSpecialItemEffects(ITEM_SPECIAL_EFFECT::ISE_FORAGE_ADD_RM);
			std::vector<SItemSpecialEffect>::const_iterator it, itEnd;
			double addedQty = 0.;
			for (it=effects.begin(), itEnd=effects.end(); it!=itEnd; ++it)
			{
				float rnd = RandomGenerator.frand();
				if (rnd<it->EffectArgFloat[0])
				{
					addedQty += it->EffectArgFloat[1];
					PHRASE_UTILITIES::sendItemSpecialEffectProcMessage(ITEM_SPECIAL_EFFECT::ISE_FORAGE_ADD_RM, player, NULL, (sint32)(it->EffectArgFloat[1]*100.));
				}
			}
			results[A] *= 1.0f + (float)addedQty;
		}
	}
//	else
//	{
//		results[A] = 0;
//	}

	// Speed: always the requested speed (otherwise, looks like a bug for the player when it's the speed of the action)
	results[S] = reqPosProps[S];
	_S = (_S*nbe + results[S]) / (nbe + 1.0f); // average per source

	// Quality: converges towards the requested value, except when a drop occurs (0 at this step)
	float usedReqQ = (propDrop == Q) ? 0.0f : reqPosProps[Q] * qualityCeilingFactor;
	float resQ = (results[Q]*qualitySlowFactor + usedReqQ) / (qualitySlowFactor+1);
	float maxQOfSource = (float)_MaxQuality;
	if ( resQ > maxQOfSource )
	{
		resQ = maxQOfSource;
		//if ( results[Q] < (float)_MaxQuality )
		//	nldebug( "Quality limited by source to %hu", _MaxQuality ); // TODO: tell the player(s)
	}
	if ( (resQ < _Q) || (resQ < reqPosProps[Q]) || (! ForageQualityCeilingClamp.get()) )
	{
		// Set Q only if not increasing and exceeding requested quality
		results[Q] = resQ;
	}
	else
	{
		// Clamp Q to the max required by the player
		results[Q] = reqPosProps[Q];
	}
	float prevQ = _Q;
	_Q = results[Q]; // now there is only one extractor => the Q of the source is the resulting Q
	if ( ((prevQ < reqPosProps[Q]) && (_Q == reqPosProps[Q])) || ((prevQ < maxQOfSource) && (_Q == maxQOfSource)) )
	{
		setNewImpactScheme(); // we just reached the max quality
	}

	// Calc impact of the new average values

	// Previously, the impact depended on the level of the extraction:
	// float quantityBaseImpact = _A * _S * ForageQuantityImpactFactor.get();
	// float qualityBaseImpact = (_Q - oldQ) * ForageQualityImpactFactor.get();
	//
	// Now it's constant (=max), but the amount of damage depends on the level of the extraction:
	float quantityBaseImpact = MaxAS * ForageQuantityImpactFactor.get();
	float qualityBaseImpact = MaxDeltaQ * ForageQualityImpactFactor.get();
	uint impactScheme = _IImpactMappingScheme;
	if ( impactScheme >= SpecialNewbieImpactSchemeD)
	{
		// Lower impacts for newbies
		impactScheme -= SpecialNewbieImpactSchemeD;
		quantityBaseImpact *= 0.5f;
		qualityBaseImpact *= 0.5f;
	}
	if ( ForceAbsorption.get() != 0 )
	{
		absPosProps[A] = ForceAbsorption.get();
		absPosProps[Q] = ForceAbsorption.get();
		absPosProps[S] = ForceAbsorption.get();
	}
	for ( uint i=D; i!=NbRTProps; ++i )
	{
		if (i==E && _SafeSource)
			break;
		uint impactType = ImpactSchemes[impactScheme][i-NbPosRTProps];
		float impact;
		switch ( impactType )
		{
		case 0 : impact = quantityBaseImpact * (1.0f - absPosProps[A]); break;
		case 1 : impact = qualityBaseImpact * (1.0f - absPosProps[Q]); break;
		default: impact = (quantityBaseImpact + qualityBaseImpact) / 2.0f * (1.0f - absPosProps[S]); break; // bound on the average of both, absorption of S
		}

		impact += RandomGenerator.frandPlusMinus( impact ); // result impact from 0 to impact*2
		
		// add spire effect ( aggressivity )
		if ( player )
		{
			const CSEffect* pEffect = player->lookForActiveEffect( EFFECT_FAMILIES::TotemHarvestAgg );
			if ( pEffect != NULL )
			{
				impact *= ( 1.0f - pEffect->getParamValue() / 100.0f );
			}
		}

		if ( impact < 0 ) impact = 0; // impact can't be negative
		if ( (i==D) && (lifeAbsorberRatio != 0) )
		{
			// Damage the life absorber, instead of impacting D
			CEntityBase *entity = CEntityBaseManager::getEntityBasePtr( extractingEntityRow ); // getEntityBasePtr() tests TheDataset.isAccessible( extractingEntity )
			if ( entity )
			{
				float impactOnHP = ((float)lifeAbsorberRatio) * impact * 0.01f;
				impact -= impactOnHP;
				float dmgRatio = impactOnHP * ForageHPRatioPerSourceLifeImpact.get();
				sint32 dmg = (sint32)((float)entity->maxHp() * dmgRatio);
				if ( dmg != 0 )
					CHarvestSource::hitEntity( RYZOMID::forageSource, entity, dmg, dmg, true );
			}
		}
		if ( (_TargetRTProps[i-D] < CommonRiskThreshold*0.90f) && (_TargetRTProps[i-D] + impact > CommonRiskThreshold) )
		{
			// Avoid a brutal unnatural end, make a step just before reaching threshold
			impactRTProp( (TTargetRTProp)(i-D), CommonRiskThreshold - 2.0f );
		}
		else
		{
			// Normal impact
			impactRTProp( (TTargetRTProp)(i-D), _TargetRTProps[i-D] + impact );
		}
	}
}
コード例 #26
0
//-----------------------------------------------
// CSLinkEffect update
//-----------------------------------------------
bool CSLinkEffect::update(CTimerEvent * event, bool)
{
	CEntityBase * target = CEntityBaseManager::getEntityBasePtr( _TargetRowId );
	if ( !target )
	{
		nlwarning("<CSLinkEffect update> Invalid target %u",_TargetRowId.getIndex() );
		_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
		return true;
	}

	// -> effect is removed when target receive the invulnerability power
	// if target is now protected, cancel the effect
/*	const CSEffect *effect = target->lookForActiveEffect(EFFECT_FAMILIES::PowerInvulnerability);
	if (effect)
	{
		_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
		return true;
	}
*/

	// if link exists pay price and test distance
	if (_LinkExists)
	{
		bool endEffect = false;

		CEntityBase * caster = CEntityBaseManager::getEntityBasePtr( _CreatorRowId );
		if ( !caster )
		{
			nlwarning("<CSLinkEffectDot update> Invalid caster %u",_CreatorRowId.getIndex() );
			_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
			return true;
		}

		// test range
		if ( ! PHRASE_UTILITIES::testRange(*caster, *target, _MaxDistance) )
		{
			endEffect = true;
		}

		// if caster if a player get used focus item
		CCharacter *player = NULL;
		if (caster->getId().getType() == RYZOMID::player)
		{
			CCharacter *player = dynamic_cast<CCharacter *> (caster);
			if (player)
			{
				_Focus.init(player->getRightHandItem());
			}
		}

		// price is modified by focus item if any
		sint32 price = _CostPerUpdate;
		if (_Focus.isMagicFocus())
		{
			price = sint32( price / (1.0f + _Focus.getPowerFactor(_Skill, _SpellPower) ) );
		}

		// pay price
		SCharacteristicsAndScores & score = caster->getScores()._PhysicalScores[_EnergyCost];
		if ( score.Current != 0)
		{
			if ( score.Current >  price )
			{
				score.Current = score.Current - price;	
			}
			else
				endEffect = true;
		}
		else
			endEffect = true;

		// degrade items
		if (player != NULL)
		{
			if (_Focus.wearItem())
				player->wearRightHandItem();

			player->wearArmor();
			player->wearShield();
			player->wearJewels();
		}

		// set next update timer
		if (!endEffect)
		{
			//_UpdateTimer.setRemaining( NLMISC::TGameCycle( _UpdatePeriod / CTickEventHandler::getGameTimeStep() ), event );
			_UpdateTimer.setRemaining( CSLinkEffect::getUpdatePeriod(_Family), event );
		}
		else
		{
			// break link
			caster->removeLink( this, 1.0f );
		}
	}
	// no more link
	else
	{
		//
	}

	return false;
} // CSLinkEffect::update //
コード例 #27
0
LTBOOL CAISenseHearEnemyWeaponImpact::Update(HOBJECT hStimulus, LTFLOAT fTimeDelta)
{
	if ( !IsCharacter(hStimulus) ) return LTFALSE;

    CCharacter* pChar = (CCharacter*)g_pLTServer->HandleToObject(hStimulus);

	CharFireInfo info;
	pChar->GetLastFireInfo(info);

	// Make sure this is a recent firing of the weapon...

    if (info.fTime + 1.0 < g_pLTServer->GetTime() || info.nWeaponId == WMGR_INVALID_ID) return LTFALSE;

	AMMO* pAmmo = g_pWeaponMgr->GetAmmo(info.nAmmoId);
    if (!pAmmo || !pAmmo->pImpactFX) return LTFALSE;

	// Get the Distance that the impact noise carries

    LTFLOAT fWeaponImpactNoiseDistance = (LTFLOAT) pAmmo->pImpactFX->nAISoundRadius;

	// Scale based on surface types

	SURFACE* pSurf = g_pSurfaceMgr->GetSurface(info.eSurface);
	_ASSERT(pSurf);
	if ( pSurf && !pAmmo->pImpactFX->bAIIgnoreSurface )
	{
		fWeaponImpactNoiseDistance *= pSurf->fImpactNoiseModifier;
	}

	// Get the distance from the impact

    LTFLOAT fDistance = VEC_DIST(info.vImpactPos, m_pAI->GetPosition());

	// Are we close enough to hear? (or did it hit us?)

	if ( (fDistance < (m_fDistance + fWeaponImpactNoiseDistance)) || (info.hObject == GetAI()->GetObject()) )
	{
		React();

		// Record the Timestamp

		m_fTimestamp = info.fTime;

        return LTTRUE;
	}
	else
	{
		// If it hit a character (forget if we like him or not), and we can see that character, react.

		if ( info.hObject && IsCharacter(info.hObject) && (fDistance < (500.0f)) )
		{
			LTVector vPosition;
			g_pLTServer->GetObjectPos(info.hObject, &vPosition);

			LTBOOL bVisible = LTFALSE;

			if ( m_pAI->CanSeeThrough() )
			{
				bVisible = m_pAI->IsObjectPositionVisibleFromEye(CAI::SeeThroughFilterFn, CAI::SeeThroughPolyFilterFn, info.hObject, vPosition, (250000.0f), LTTRUE);
			}
			else
			{
				bVisible = m_pAI->IsObjectPositionVisibleFromEye(CAI::DefaultFilterFn, NULL, info.hObject, vPosition, (250000.0f), LTTRUE);
			}
			
			if ( bVisible )
			{
				React();

				// Record the Timestamp

				m_fTimestamp = info.fTime;

				return LTTRUE;
			}
		}
	}

    return LTFALSE;
}
コード例 #28
0
//-----------------------------------------------
// CSLinkEffectOffensive updateOffensive
//-----------------------------------------------
bool CSLinkEffectOffensive::updateOffensive(CTimerEvent * event, bool sendReportForXP)
{
	if ( CSLinkEffect::update(event,true) )
		return true;

	CEntityBase * target = CEntityBaseManager::getEntityBasePtr( _TargetRowId );
	if ( !target )
	{
		nlwarning("<CSLinkEffectDot update> Invalid target %u",_TargetRowId.getIndex() );
		_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
		return true;
	}

	// if target is now protected, cancel the effect
	CSEffect *effect = target->lookForActiveEffect(EFFECT_FAMILIES::PowerAntiMagicShield);
	if (effect)
	{
		_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
		return true;
	}

	// test target is still valid for a link (can happen in PVP or duel)
	string errorCode;
	if ( !PHRASE_UTILITIES::validateSpellTarget(_CreatorRowId, _TargetRowId, ACTNATURE::OFFENSIVE_MAGIC, errorCode, true ) )
	{
		_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
		return true;
	}

	if (_LinkExists)
	{
		CEntityBase * caster = CEntityBaseManager::getEntityBasePtr( _CreatorRowId );
		if ( !caster )
		{
			nlwarning("<CSLinkEffectDot update> Invalid caster %u",_CreatorRowId.getIndex() );
			_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
			return true;
		}
	
		// test resistance
		if ( !_FirstResist && !EntitiesNoResist)
		{
			uint32 resistValue = 0;
			if (_Family == EFFECT_FAMILIES::Dot)
			{
				CSLinkEffectDot *dot = dynamic_cast<CSLinkEffectDot*> (this);
				if (dot)
				{
					resistValue = target->getMagicResistance(dot->getDamageType());
				}
			}
			else
			{
				resistValue = target->getMagicResistance(_Family);
			}

			sint skillValue = 0;
			if ( caster->getId().getType() == RYZOMID::player )
			{
				CCharacter * pC = (CCharacter *) caster;
				skillValue = pC->getSkillValue( _Skill );
			}
			else
			{
				const CStaticCreatures * form = caster->getForm();
				if ( !form )
				{
					nlwarning( "<MAGIC>invalid creature form %s in entity %s", caster->getType().toString().c_str(), caster->getId().toString().c_str() );
					_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
					return true;
				}	
				skillValue = form->getAttackLevel();
			}

			const CSEffect* debuff = caster->lookForActiveEffect( EFFECT_FAMILIES::DebuffSkillMagic );
			if ( debuff )
				skillValue -= debuff->getParamValue();
			const CSEffect * outPostBuff = caster->lookForActiveEffect( EFFECT_FAMILIES::OutpostMagic );
			if ( outPostBuff )
				skillValue += outPostBuff->getParamValue();

			// cap skill values with brick power
			if ( (sint32)_Power < skillValue )
				skillValue = (sint32)_Power;
			
			if ( caster->getId().getType() == RYZOMID::player )
			{
				CCharacter * pC = dynamic_cast<CCharacter *>( caster );
				if( pC )
				{
					// boost magic skill for low level chars
					sint sb = (sint)MagicSkillStartValue.get();
					skillValue = max( sb, skillValue );

					// add magic boost from consumable
					skillValue += pC->magicSuccessModifier();
				}
			}

			// test resistance
			const uint8 roll = (uint8)RandomGenerator.rand( 99 );
			_ResistFactor = CStaticSuccessTable::getSuccessFactor(SUCCESS_TABLE_TYPE::MagicResistLink, skillValue - resistValue, roll);

			// increase target resistance
			if (_ResistFactor > 0.0f)
			{
				if (_Family == EFFECT_FAMILIES::Dot)
				{
					CSLinkEffectDot *dot = dynamic_cast<CSLinkEffectDot*> (this);
					if (dot)
					{
						target->incResistModifier(dot->getDamageType(), _ResistFactor);
					}
				}
				else
				{
					target->incResistModifier(_Family,_ResistFactor);
				}
			}

			// delta level for XP gain 
			// opponent must be a creature or an npc to gain xp
			_Report.DeltaLvl = skillValue - resistValue;
			if (target->getId().getType() != RYZOMID::player && caster->getId().getType() == RYZOMID::player)
			{
				CCreature *creature = dynamic_cast<CCreature*> (target);
				if (!creature)
				{
					nlwarning("Entity %s type is creature but dynamic_cast in CCreature * returns NULL ?!", target->getId().toString().c_str());
					_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
					return true;
				}
				CCharacter * pC = dynamic_cast<CCharacter*> (caster);
				if (!pC)
				{
					nlwarning("Entity %s type is player but dynamic_cast in CCharacter * returns NULL ?!", caster->getId().toString().c_str());
					_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
					return true;
				}

				const CStaticCreatures* form = creature->getForm();
				if (form)
					_Report.DeltaLvl =  pC->getSkillValue(_Skill) - form->getXPLevel();
				else
					sendReportForXP = false;
			}
			else
				sendReportForXP = false;
		}
		else
		{
			_FirstResist = false;
			_ResistFactor = 1.0f;
		}
		
		bool end = true;
		// resist if factor <= 0
		if ( _ResistFactor > 0.0f  )
		{
			end = false;
			if ( _ResistFactor > 1.0f )
			{
				_ResistFactor = 1.0f;
			}

			// send report for XP			
			_Report.factor = _ResistFactor;

			if (sendReportForXP)
			{
				PROGRESSIONPVE::CCharacterProgressionPVE::getInstance()->actionReport( _Report );
				PROGRESSIONPVP::CCharacterProgressionPVP::getInstance()->reportAction(_Report);
			}
		}
		else
		{
			PHRASE_UTILITIES::sendSpellResistMessages( _CreatorRowId, _TargetRowId);
		}

		//////////////////////////////////////////////////////////////////////////
		// TEMPORARY : SEND AGGRO MESSAGE FOR EVERY UPDATE OF OFFENSIVE LINKS
		//////////////////////////////////////////////////////////////////////////	
		CAiEventReport report;
		report.Originator = _CreatorRowId;
		report.Target = _TargetRowId;
		report.Type = ACTNATURE::OFFENSIVE_MAGIC;		
		report.AggroAdd = -0.01f;
		CPhraseManager::getInstance().addAiEventReport(report);
		//////////////////////////////////////////////////////////////////////////
				
		if (end)
		{
			_EndTimer.setRemaining(1, new CEndEffectTimerEvent(this));
			return true;
		}
	}
	else
	{
		// no link -> no possible resist ?
	}

	return false;
} // CSLinkEffectOffensive::updateOffensive //
コード例 #29
0
//-----------------------------------------------
// CTimedActionPhrase build
//-----------------------------------------------
bool CTimedActionPhrase::build( const TDataSetRow & actorRowId, const std::vector< const CStaticBrick* >& bricks, bool buildToExecute )
{
    _ActorRowId = actorRowId;

    for (uint i = 0 ; i < bricks.size() ; ++i)
    {
        const CStaticBrick *brick = bricks[i];
        nlassert(brick != NULL);

        if (i==0)
            _RootSheetId = brick->SheetId;

        // process params
        for ( uint j = 0 ; j < brick->Params.size() ; ++j)
        {
            TBrickParam::IId	*param = brick->Params[j];
            if (!param) continue;

            switch(param->id())
            {
            case TBrickParam::TA_TELEPORT:
            {
                _TimedAction = new CTPTimedAction();
                if (_TimedAction == NULL)
                {
                    nlwarning("Error allocating new CTPTimedAction object");
                    return false;
                }
                _ExecutionDuration = DelayBeforeItemTP;
                _ActionType = CLIENT_ACTION_TYPE::Teleport;
            }
            break;

            case TBrickParam::TA_DISCONNECT:
            {
                _TimedAction = new CDisconnectTimedAction();
                if (_TimedAction == NULL)
                {
                    nlwarning("Error allocating new CTPTimedAction object");
                    return false;
                }

                _ExecutionDuration = TimeBeforeDisconnection;
                if (IsRingShard)
                {
                    // Find out how much time to wait depending on the role of the character
                    CCharacter* player = PlayerManager.getChar(_ActorRowId);
                    if (player)
                    {
                        // In Ring edition and animation mode, take a short cut when Far Teleporting
                        R2::TUserRole role = player->sessionUserRole();
                        if ((role == R2::TUserRole::ur_editor) || (role == R2::TUserRole::ur_animator))
                            _ExecutionDuration = 1;
                    }
                }
                _ActionType = CLIENT_ACTION_TYPE::Disconnect;
            }
            break;

            case TBrickParam::TA_MOUNT:
            {
                _TimedAction = new CMountTimedAction();
                if (_TimedAction == NULL)
                {
                    nlwarning("Error allocating new CTPTimedAction object");
                    return false;
                }
                _ExecutionDuration = MountDuration;
                _ActionType = CLIENT_ACTION_TYPE::Mount;
            }
            break;

            case TBrickParam::TA_UNMOUNT:
            {
                _TimedAction = new CUnmountTimedAction();
                if (_TimedAction == NULL)
                {
                    nlwarning("Error allocating new CTPTimedAction object");
                    return false;
                }
                _ExecutionDuration = UnmountDuration;
                _ActionType = CLIENT_ACTION_TYPE::Unmount;
            }
            break;

            case TBrickParam::TA_CONSUME:
            {
                _TimedAction = new CConsumeItemTimedAction();
                if (_TimedAction == NULL)
                {
                    nlwarning("Error allocating new CConsumeItemTimedAction object");
                    return false;
                }
                // get item to consume to init consumption time
                CCharacter *player = PlayerManager.getChar(actorRowId);
                if (player)
                {
                    CGameItemPtr item =player->getConsumedItem();
                    if (item != NULL)
                    {
                        const CStaticItem *form = item->getStaticForm();
                        if (form && form->ConsumableItem)
                        {
                            _ExecutionDuration = TGameCycle(form->ConsumableItem->ConsumptionTime / CTickEventHandler::getGameTimeStep());
                        }
                    }
                }
                _ActionType = CLIENT_ACTION_TYPE::ConsumeItem;
            }
            break;

            default:
                ;
            };
        }
    }

    return true;
}// CTimedActionPhrase build
コード例 #30
0
ファイル: building_unit_test.cpp プロジェクト: AzyxWare/ryzom
//----------------------------------------------------------------------------
void CBuildingTest::checkCharIntegrity(uint charIndex)
{
	nlassert( charIndex < TestCharacters.size() );
	
	if ( !TestCharacters[charIndex].InBuilding )
		return;

	sint32 cellId = TestCharacters[charIndex].CellId;
	if ( cellId > -2 || (cellId & 1) )
	{
		nlwarning("*** BuildingUnitTest *** INTEGRITY FAILURE for character %u: invalid cell id (%d)", charIndex, cellId);
		DEBUG_STOP;
		return;
	}

	CCharacter * c = PlayerManager.getChar( TestCharacters[charIndex].EId );
	nlassert( c );
	CMirrorPropValueRO<TYPE_CELL> mirrorCell( TheDataset, c->getEntityRowId(), DSPropertyCELL );
	if (mirrorCell != cellId)
	{
		nlwarning("*** BuildingUnitTest *** INTEGRITY FAILURE for character %u: cell does not match with mirror: %d != %d",
			charIndex, cellId, (sint32)mirrorCell
			);
		DEBUG_STOP;
		return;
	}

	const IRoomInstance * room = CBuildingManager::getInstance()->getRoomInstanceFromCell( cellId );
	if ( !room )
	{
		nlwarning("*** BuildingUnitTest *** INTEGRITY FAILURE for character %u: cannot find room (null)", charIndex);
		DEBUG_STOP;
		return;
	}

	if ( !room->getBuilding() )
	{
		nlwarning("*** BuildingUnitTest *** INTEGRITY FAILURE for character %u: cannot find building (null)", charIndex);
		DEBUG_STOP;
		return;
	}

	if ( TestCharacters[charIndex].BuildingName != room->getBuilding()->getName() )
	{
		nlwarning("*** BuildingUnitTest *** INTEGRITY FAILURE for character %u: building does not match: %s != %s",
			charIndex, TestCharacters[charIndex].BuildingName.c_str(), room->getBuilding()->getName().c_str()
			);
		DEBUG_STOP;
		return;
	}

	if ( TestCharacters[charIndex].RoomIndex != room->getRoomIndex() )
	{
		CBuildingManager * bm = CBuildingManager::getInstance();
		nlassert( bm );

		nlwarning("*** BuildingUnitTest *** INTEGRITY FAILURE for character %u: room index does not match: %hu != %hu",
			charIndex, TestCharacters[charIndex].RoomIndex, room->getRoomIndex()
			);
		DEBUG_STOP;
		return;
	}
}