summaryrefslogtreecommitdiff
path: root/game/server/tf/tf_autobalance.cpp
blob: e6b7b0fbc437930b9cc85e7dda8c27617c91472c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: 
//
// $NoKeywords: $
//=============================================================================
#include "cbase.h"

#include "tf_autobalance.h"
#include "tf_gamerules.h"
#include "tf_matchmaking_shared.h"
#include "team.h"
#include "minigames/tf_duel.h"
#include "player_resource.h"
#include "tf_player_resource.h"

// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>

extern ConVar mp_developer;
extern ConVar mp_teams_unbalance_limit;
extern ConVar tf_arena_use_queue;
extern ConVar mp_autoteambalance;
extern ConVar tf_autobalance_query_lifetime;
extern ConVar tf_autobalance_xp_bonus;

ConVar tf_autobalance_detected_delay( "tf_autobalance_detected_delay", "30", FCVAR_NONE );

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
CTFAutobalance::CTFAutobalance()
{
	Reset();
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
CTFAutobalance::~CTFAutobalance()
{
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFAutobalance::Reset()
{
	m_iCurrentState = AB_STATE_INACTIVE;
	m_iLightestTeam = m_iHeaviestTeam = TEAM_INVALID;
	m_nNeeded = 0;
	m_flBalanceTeamsTime = -1.f;

	if ( m_vecPlayersAsked.Count() > 0 )
	{
		// if we're resetting and we have people we haven't heard from yet, tell them to close their notification
		FOR_EACH_VEC( m_vecPlayersAsked, i )
		{
			if ( m_vecPlayersAsked[i].hPlayer.Get() && ( m_vecPlayersAsked[i].eState == AB_VOLUNTEER_STATE_ASKED ) )
			{
				CSingleUserRecipientFilter filter( m_vecPlayersAsked[i].hPlayer.Get() );
				filter.MakeReliable();
				UserMessageBegin( filter, "AutoBalanceVolunteer_Cancel" );
				MessageEnd();
			}
		}

		m_vecPlayersAsked.Purge();
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFAutobalance::Shutdown()
{
	Reset();
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFAutobalance::LevelShutdownPostEntity()
{
	Reset();
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
bool CTFAutobalance::ShouldBeActive() const
{
	if ( !TFGameRules() )
		return false;

	if ( TFGameRules()->IsInTraining() || TFGameRules()->IsInItemTestingMode() )
		return false;

	if ( TFGameRules()->IsInArenaMode() && tf_arena_use_queue.GetBool() )
		return false;

#if defined( _DEBUG ) || defined( STAGING_ONLY )
	if ( mp_developer.GetBool() )
		return false;
#endif // _DEBUG || STAGING_ONLY

	if ( mp_teams_unbalance_limit.GetInt() <= 0 )
		return false;

	const IMatchGroupDescription *pMatchDesc = GetMatchGroupDescription( TFGameRules()->GetCurrentMatchGroup() );
	if ( pMatchDesc )
	{
		return pMatchDesc->m_params.m_bUseAutoBalance;
	}

	// outside of managed matches, we don't normally do any balancing for tournament mode
	if ( TFGameRules()->IsInTournamentMode() )
		return false;

	return ( mp_autoteambalance.GetInt() == 2 );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
bool CTFAutobalance::AreTeamsUnbalanced()
{
	if ( !TFGameRules() )
		return false;

	// don't bother switching teams if the round isn't running
	if ( TFGameRules()->State_Get() != GR_STATE_RND_RUNNING )
		return false;

	if ( mp_teams_unbalance_limit.GetInt() <= 0 )
		return false;

	if ( TFGameRules()->ArePlayersInHell() )
		return false;

	int nDiffBetweenTeams = 0;
	m_iLightestTeam = m_iHeaviestTeam = TEAM_INVALID;
	m_nNeeded = 0;

	CMatchInfo *pMatch = GTFGCClientSystem()->GetLiveMatch();
	if ( pMatch )
	{
		int nNumTeamRed = pMatch->GetNumActiveMatchPlayersForTeam( TFGameRules()->GetGCTeamForGameTeam( TF_TEAM_RED ) );
		int nNumTeamBlue = pMatch->GetNumActiveMatchPlayersForTeam( TFGameRules()->GetGCTeamForGameTeam( TF_TEAM_BLUE ) );

		m_iLightestTeam = ( nNumTeamRed > nNumTeamBlue ) ? TF_TEAM_BLUE : TF_TEAM_RED;
		m_iHeaviestTeam = ( nNumTeamRed > nNumTeamBlue ) ? TF_TEAM_RED : TF_TEAM_BLUE;

		nDiffBetweenTeams = abs( nNumTeamRed - nNumTeamBlue );
	}
	else
	{
		int iMostPlayers = 0;
		int iLeastPlayers = MAX_PLAYERS + 1;
		int i = FIRST_GAME_TEAM;

		for ( CTeam *pTeam = GetGlobalTeam( i ); pTeam != NULL; pTeam = GetGlobalTeam( ++i ) )
		{
			int iNumPlayers = pTeam->GetNumPlayers();

			if ( iNumPlayers < iLeastPlayers )
			{
				iLeastPlayers = iNumPlayers;
				m_iLightestTeam = i;
			}

			if ( iNumPlayers > iMostPlayers )
			{
				iMostPlayers = iNumPlayers;
				m_iHeaviestTeam = i;
			}
		}

		nDiffBetweenTeams = ( iMostPlayers - iLeastPlayers );
	}

	if ( nDiffBetweenTeams > mp_teams_unbalance_limit.GetInt() ) 
	{
		m_nNeeded = ( nDiffBetweenTeams / 2 );
		return true;
	}

	return false;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFAutobalance::MonitorTeams()
{
	if ( AreTeamsUnbalanced() )
	{
		if ( m_flBalanceTeamsTime < 0.f )
		{
			// trigger a small waiting period to see if the GC sends us someone before we need to balance the teams 
			m_flBalanceTeamsTime = gpGlobals->curtime + tf_autobalance_detected_delay.GetInt();
		}
		else if ( m_flBalanceTeamsTime < gpGlobals->curtime )
		{
			if ( IsOkayToBalancePlayers() )
			{
				UTIL_ClientPrintAll( HUD_PRINTTALK, "#TF_Autobalance_Start", ( m_iHeaviestTeam == TF_TEAM_RED ) ? "#TF_RedTeam_Name" : "#TF_BlueTeam_Name" );
				m_iCurrentState = AB_STATE_FIND_VOLUNTEERS;
			}
		}
	}
	else
	{
		m_flBalanceTeamsTime = -1.f;
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
bool CTFAutobalance::HaveAlreadyAskedPlayer( CTFPlayer *pTFPlayer ) const
{
	FOR_EACH_VEC( m_vecPlayersAsked, i )
	{
		if ( m_vecPlayersAsked[i].hPlayer == pTFPlayer )
			return true;
	}

	return false;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
int CTFAutobalance::GetTeamAutoBalanceScore( int nTeam ) const
{
	CMatchInfo *pMatch = GTFGCClientSystem()->GetLiveMatch();
	if ( pMatch && TFGameRules() )
	{
		return pMatch->GetTotalSkillRatingForTeam( TFGameRules()->GetGCTeamForGameTeam( nTeam ) );
	}

	int nTotalScore = 0;
	CTFPlayerResource *pTFPlayerResource = dynamic_cast<CTFPlayerResource *>( g_pPlayerResource );
	if ( pTFPlayerResource )
	{
		CTeam *pTeam = GetGlobalTeam( nTeam );
		if ( pTeam )
		{
			for ( int i = 0; i < pTeam->GetNumPlayers(); i++ )
			{
				CTFPlayer *pTFPlayer = ToTFPlayer( pTeam->GetPlayer( i ) );
				if ( pTFPlayer )
				{
					nTotalScore += pTFPlayerResource->GetTotalScore( pTFPlayer->entindex() );
				}
			}
		}
	}

	return nTotalScore;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
int CTFAutobalance::GetPlayerAutoBalanceScore( CTFPlayer *pTFPlayer ) const
{
	if ( !pTFPlayer )
		return 0;

	CMatchInfo *pMatch = GTFGCClientSystem()->GetLiveMatch();
	if ( pMatch )
	{
		CSteamID steamID;
		pTFPlayer->GetSteamID( &steamID );

		if ( steamID.IsValid() )
		{
			const CMatchInfo::PlayerMatchData_t* pPlayerMatchData = pMatch->GetMatchDataForPlayer( steamID );
			if ( pPlayerMatchData )
			{
				FixmeMMRatingBackendSwapping(); // Make sure this makes sense with arbitrary skill rating values --
												// e.g. maybe we want a smarter glicko-weighting thing.
				return (int)pPlayerMatchData->unMMSkillRating;
			}
		}
	}

	int nTotalScore = 0;
	CTFPlayerResource *pTFPlayerResource = dynamic_cast<CTFPlayerResource *>( g_pPlayerResource );
	if ( pTFPlayerResource )
	{
		nTotalScore = pTFPlayerResource->GetTotalScore( pTFPlayer->entindex() );
	}

	return nTotalScore;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
CTFPlayer *CTFAutobalance::FindPlayerToAsk()
{
	CTFPlayer *pRetVal = NULL;

	CUtlVector< CTFPlayer* > vecCandiates;
	CTeam *pTeam = GetGlobalTeam( m_iHeaviestTeam );
	if ( pTeam )
	{
		// loop through and get a list of possible candidates
		for ( int i = 0; i < pTeam->GetNumPlayers(); i++ )
		{
			CTFPlayer *pTFPlayer = ToTFPlayer( pTeam->GetPlayer( i ) );
			if ( pTFPlayer && !HaveAlreadyAskedPlayer( pTFPlayer ) && pTFPlayer->CanBeAutobalanced() )
			{
				vecCandiates.AddToTail( pTFPlayer );
			}
		}
	}

	// no need to go any further if there's only one candidate
	if ( vecCandiates.Count() == 1 )
	{
		pRetVal = vecCandiates[0];
	}
	else if ( vecCandiates.Count() > 1 )
	{
		int nTotalDiff = abs( GetTeamAutoBalanceScore( m_iHeaviestTeam ) - GetTeamAutoBalanceScore( m_iLightestTeam ) );
		int nAverageNeeded = ( nTotalDiff / 2 ) / m_nNeeded;

		// now look a player on the heaviest team with skillrating closest to that average
		int nClosest = INT_MAX;
		FOR_EACH_VEC( vecCandiates, iIndex )
		{
			int nDiff = abs( nAverageNeeded - GetPlayerAutoBalanceScore( vecCandiates[iIndex] ) );
			if ( nDiff < nClosest )
			{
				nClosest = nDiff;
				pRetVal = vecCandiates[iIndex];
			}
		}
	}

	return pRetVal;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFAutobalance::FindVolunteers()
{
	// keep track of the state of things, this will also update our counts if more players drop from the server
	if ( !AreTeamsUnbalanced() || !IsOkayToBalancePlayers() )
	{
		Reset();
		return;
	}

	int nPendingReplies = 0;
	int nRepliedNo = 0;

	FOR_EACH_VEC( m_vecPlayersAsked, i )
	{
		// if the player is valid
		if ( m_vecPlayersAsked[i].hPlayer.Get() )
		{
			switch ( m_vecPlayersAsked[i].eState )
			{
			case AB_VOLUNTEER_STATE_ASKED:
				if ( m_vecPlayersAsked[i].flQueryExpireTime < gpGlobals->curtime )
				{
					// they've timed out the request period without replying
					m_vecPlayersAsked[i].eState = AB_VOLUNTEER_STATE_NO;
					nRepliedNo++;
				}
				else
				{
					nPendingReplies++;
				}
				break;
			case AB_VOLUNTEER_STATE_NO:
				nRepliedNo++;
				break;
			default:
				break;
			}
		}
	}

	int nNumToAsk = ( m_nNeeded * 2 );

	// do we need to ask for more volunteers?
	if ( nPendingReplies < nNumToAsk )
	{
		int nNumNeeded = nNumToAsk - nPendingReplies;
		int nNumAsked = 0;

		while ( nNumAsked < nNumNeeded )
		{
			CTFPlayer *pTFPlayer = FindPlayerToAsk();
			if ( pTFPlayer )
			{
				int iIndex = m_vecPlayersAsked.AddToTail();
				m_vecPlayersAsked[iIndex].hPlayer = pTFPlayer;
				m_vecPlayersAsked[iIndex].eState = AB_VOLUNTEER_STATE_ASKED;
				m_vecPlayersAsked[iIndex].flQueryExpireTime = gpGlobals->curtime + tf_autobalance_query_lifetime.GetInt() + 3; // add 3 seconds to allow for travel time to/from the client

				CSingleUserRecipientFilter filter( pTFPlayer );
				filter.MakeReliable();
				UserMessageBegin( filter, "AutoBalanceVolunteer" );
				MessageEnd();

				nNumAsked++;
				nPendingReplies++;
			}
			else
			{
				// we couldn't find anyone else to ask
				if ( nPendingReplies <= 0 )
				{
					// we're not waiting on anyone else to reply....so we should just reset
					Reset();
				}

				return;
			}
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFAutobalance::FrameUpdatePostEntityThink()
{
	bool bActive = ShouldBeActive();
	if ( !bActive )
	{
		Reset();
		return;
	}

	switch ( m_iCurrentState )
	{
	case AB_STATE_INACTIVE:
		// we should be active if we've made it this far
		m_iCurrentState = AB_STATE_MONITOR;
		break;
	case AB_STATE_MONITOR:
		MonitorTeams();
		break;
	case AB_STATE_FIND_VOLUNTEERS:
		FindVolunteers();
		break;
	default:
		break;
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
bool CTFAutobalance::IsOkayToBalancePlayers()
{
	if ( GTFGCClientSystem()->GetLiveMatch() && !GTFGCClientSystem()->CanChangeMatchPlayerTeams() ) 
		return false;

	return true;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFAutobalance::ReplyReceived( CTFPlayer *pTFPlayer, bool bResponse )
{
	if ( m_iCurrentState != AB_STATE_FIND_VOLUNTEERS )
		return;

	if ( !AreTeamsUnbalanced() || !IsOkayToBalancePlayers() )
	{
		Reset();
		return;
	}

	FOR_EACH_VEC( m_vecPlayersAsked, i )
	{
		// is this a player we asked?
		if ( m_vecPlayersAsked[i].hPlayer == pTFPlayer )
		{
			m_vecPlayersAsked[i].eState = bResponse ? AB_VOLUNTEER_STATE_YES : AB_VOLUNTEER_STATE_NO;
			if ( bResponse  && pTFPlayer->CanBeAutobalanced() )
			{
				pTFPlayer->ChangeTeam( m_iLightestTeam, false, false, true );
				pTFPlayer->ForceRespawn();
				pTFPlayer->SetLastAutobalanceTime( gpGlobals->curtime );

				CMatchInfo *pMatch = GTFGCClientSystem()->GetLiveMatch();
				if ( pMatch )
				{
					CSteamID steamID;
					pTFPlayer->GetSteamID( &steamID );

					// We're going to give the switching player a bonus pool of XP. This should encourage
					// them to keep playing to earn what's in the pool, rather than just quit after getting
					// a big payout
					if ( !pMatch->BSentResult() )
					{
						pMatch->GiveXPBonus( steamID, CMsgTFXPSource_XPSourceType_SOURCE_AUTOBALANCE_BONUS, 1, tf_autobalance_xp_bonus.GetInt() );
					}

					GTFGCClientSystem()->ChangeMatchPlayerTeam( steamID, TFGameRules()->GetGCTeamForGameTeam( m_iLightestTeam ) );
				}
			}
		}
	}
}

CTFAutobalance gTFAutobalance;
CTFAutobalance *TFAutoBalance(){ return &gTFAutobalance; }