]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/teamplay.qc
Merge branch 'master' into Lyberta/TeamplayOverhaul
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / teamplay.qc
1 #include "teamplay.qh"
2
3 #include "client.qh"
4 #include "race.qh"
5 #include "scores.qh"
6 #include "scores_rules.qh"
7
8 #include "bot/api.qh"
9
10 #include "command/vote.qh"
11
12 #include "mutators/_mod.qh"
13
14 #include "../common/deathtypes/all.qh"
15 #include "../common/gamemodes/_mod.qh"
16 #include "../common/teams.qh"
17
18 /// \brief Describes a state of team balance entity.
19 enum
20 {
21         TEAM_BALANCE_UNINITIALIZED, ///< The team balance has not been initialized.
22         /// \brief TeamBalance_CheckAllowedTeams has been called.
23         TEAM_BALANCE_TEAMS_CHECKED,
24         /// \brief TeamBalance_GetTeamCounts has been called.
25         TEAM_BALANCE_TEAM_COUNTS_FILLED
26 };
27
28 /// \brief Indicates that the player is not allowed to join a team.
29 const int TEAM_NOT_ALLOWED = -1;
30
31 .int m_team_balance_state; ///< Holds the state of the team balance entity.
32 .entity m_team_balance_team[NUM_TEAMS]; ///< ???
33
34 .float m_team_score; ///< The score of the team.
35 .int m_num_players; ///< Number of players (both humans and bots) in a team.
36 .int m_num_bots; ///< Number of bots in a team.
37 .int m_num_players_alive; ///< Number of alive players in a team.
38 .int m_num_control_points; ///< Number of control points owned by a team.
39 .entity m_lowest_human; ///< Human with the lowest score in a team.
40 .entity m_lowest_bot; ///< Bot with the lowest score in a team.
41
42 entity g_team_entities[NUM_TEAMS]; ///< Holds global team entities.
43
44 STATIC_INIT(g_team_entities)
45 {
46         for (int i = 0; i < NUM_TEAMS; ++i)
47         {
48                 g_team_entities[i] = spawn();
49         }
50 }
51
52 entity Team_GetTeamFromIndex(int index)
53 {
54         if (!Team_IsValidIndex(index))
55         {
56                 LOG_FATALF("Team_GetTeamFromIndex: Index is invalid: %f", index);
57         }
58         return g_team_entities[index - 1];
59 }
60
61 entity Team_GetTeam(int team_num)
62 {
63         if (!Team_IsValidTeam(team_num))
64         {
65                 LOG_FATALF("Team_GetTeam: Value is invalid: %f", team_num);
66         }
67         return g_team_entities[Team_TeamToIndex(team_num) - 1];
68 }
69
70 float Team_GetTeamScore(entity team_)
71 {
72         return team_.m_team_score;
73 }
74
75 void Team_SetTeamScore(entity team_, float score)
76 {
77         team_.m_team_score = score;
78 }
79
80 int Team_GetNumberOfAlivePlayers(entity team_)
81 {
82         return team_.m_num_players_alive;
83 }
84
85 void Team_SetNumberOfAlivePlayers(entity team_, int number)
86 {
87         team_.m_num_players_alive = number;
88 }
89
90 int Team_GetNumberOfAliveTeams()
91 {
92         int result = 0;
93         for (int i = 0; i < NUM_TEAMS; ++i)
94         {
95                 if (g_team_entities[i].m_num_players_alive > 0)
96                 {
97                         ++result;
98                 }
99         }
100         return result;
101 }
102
103 int Team_GetNumberOfControlPoints(entity team_)
104 {
105         return team_.m_num_control_points;
106 }
107
108 void Team_SetNumberOfControlPoints(entity team_, int number)
109 {
110         team_.m_num_control_points = number;
111 }
112
113 int Team_GetNumberOfTeamsWithControlPoints()
114 {
115         int result = 0;
116         for (int i = 0; i < NUM_TEAMS; ++i)
117         {
118                 if (g_team_entities[i].m_num_control_points > 0)
119                 {
120                         ++result;
121                 }
122         }
123         return result;
124 }
125
126 void setcolor(entity this, int clr)
127 {
128 #if 0
129         this.clientcolors = clr;
130         this.team = (clr & 15) + 1;
131 #else
132         builtin_setcolor(this, clr);
133 #endif
134 }
135
136 bool Entity_HasValidTeam(entity this)
137 {
138         return Team_IsValidTeam(this.team);
139 }
140
141 int Entity_GetTeamIndex(entity this)
142 {
143         return Team_TeamToIndex(this.team);
144 }
145
146 entity Entity_GetTeam(entity this)
147 {
148         int index = Entity_GetTeamIndex(this);
149         if (!Team_IsValidIndex(index))
150         {
151                 return NULL;
152         }
153         return Team_GetTeamFromIndex(index);
154 }
155
156 void SetPlayerColors(entity player, float _color)
157 {
158         float pants = _color & 0x0F;
159         float shirt = _color & 0xF0;
160         if (teamplay)
161         {
162                 setcolor(player, 16 * pants + pants);
163         }
164         else
165         {
166                 setcolor(player, shirt + pants);
167         }
168 }
169
170 bool Player_SetTeamIndex(entity player, int index)
171 {
172         int new_team = Team_IndexToTeam(index);
173         if (player.team == new_team)
174         {
175                 // This is important when players join the game and one of their color
176                 // matches the team color while other doesn't. For example [BOT]Lion.
177                 SetPlayerColors(player, new_team - 1);
178                 return true;
179         }
180         int old_index = Team_TeamToIndex(player.team);
181         if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, old_index, index) == true)
182         {
183                 // Mutator has blocked team change.
184                 return false;
185         }
186         SetPlayerColors(player, new_team - 1);
187         MUTATOR_CALLHOOK(Player_ChangedTeam, player, old_index, index);
188         return true;
189 }
190
191 bool SetPlayerTeam(entity player, int destination_team_index,
192         int source_team_index, bool no_print)
193 {
194         if (!Player_SetTeamIndex(player, destination_team_index))
195         {
196                 return false;
197         }
198         LogTeamchange(player.playerid, player.team, TEAM_CHANGE_MANUAL);
199         if (no_print)
200         {
201                 return true;
202         }
203         bprint(playername(player, false), "^7 has changed from ",
204                 Team_IndexToColoredFullName(source_team_index), "^7 to ",
205                 Team_IndexToColoredFullName(destination_team_index), "\n");
206         return true;
207 }
208
209 bool MoveToTeam(entity client, int team_index, int type)
210 {
211         int lockteams_backup = lockteams;  // backup any team lock
212         lockteams = 0;  // disable locked teams
213         PlayerScore_Clear(client);
214         if (!Player_SetTeamIndex(client, team_index))
215         {
216                 lockteams = lockteams_backup;  // restore the team lock
217                 return false;
218         }
219         KillPlayerForTeamChange(client);
220         lockteams = lockteams_backup;  // restore the team lock
221         LogTeamchange(client.playerid, client.team, type);
222         return true;
223 }
224
225 void KillPlayerForTeamChange(entity player)
226 {
227         if (IS_DEAD(player))
228         {
229                 return;
230         }
231         if (MUTATOR_CALLHOOK(Player_ChangeTeamKill, player) == true)
232         {
233                 return;
234         }
235         Damage(player, player, player, 100000, DEATH_TEAMCHANGE.m_id, DMG_NOWEP,
236                 player.origin, '0 0 0');
237 }
238
239 void LogTeamchange(float player_id, float team_number, int type)
240 {
241         if(!autocvar_sv_eventlog)
242                 return;
243
244         if(player_id < 1)
245                 return;
246
247         GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
248 }
249
250 entity TeamBalance_CheckAllowedTeams(entity for_whom)
251 {
252         entity balance = spawn();
253         for (int i = 0; i < NUM_TEAMS; ++i)
254         {
255                 entity team_ = balance.m_team_balance_team[i] = spawn();
256                 team_.m_team_score = g_team_entities[i].m_team_score;
257                 team_.m_num_players = TEAM_NOT_ALLOWED;
258                 team_.m_num_bots = 0;
259                 team_.m_lowest_human = NULL;
260                 team_.m_lowest_bot = NULL;
261         }
262         
263         int teams_mask = 0;     
264         string teament_name = string_null;
265         bool mutator_returnvalue = MUTATOR_CALLHOOK(TeamBalance_CheckAllowedTeams,
266                 teams_mask, teament_name, for_whom);
267         teams_mask = M_ARGV(0, float);
268         teament_name = M_ARGV(1, string);
269         if (mutator_returnvalue)
270         {
271                 for (int i = 0; i < NUM_TEAMS; ++i)
272                 {
273                         if (teams_mask & BIT(i))
274                         {
275                                 balance.m_team_balance_team[i].m_num_players = 0;
276                         }
277                 }
278         }
279
280         if (teament_name)
281         {
282                 entity head = find(NULL, classname, teament_name);
283                 while (head)
284                 {
285                         if (Team_IsValidTeam(head.team))
286                         {
287                                 TeamBalance_GetTeam(balance, head.team).m_num_players = 0;
288                         }
289                         head = find(head, classname, teament_name);
290                 }
291         }
292
293         // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
294         if (AvailableTeams() == 2)
295         if (autocvar_bot_vs_human && for_whom)
296         {
297                 if (autocvar_bot_vs_human > 0)
298                 {
299                         // find last team available
300                         if (IS_BOT_CLIENT(for_whom))
301                         {
302                                 if (TeamBalance_IsTeamAllowedInternal(balance, 4))
303                                 {
304                                         TeamBalance_BanTeamsExcept(balance, 4);
305                                 }
306                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
307                                 {
308                                         TeamBalance_BanTeamsExcept(balance, 3);
309                                 }
310                                 else
311                                 {
312                                         TeamBalance_BanTeamsExcept(balance, 2);
313                                 }
314                                 // no further cases, we know at least 2 teams exist
315                         }
316                         else
317                         {
318                                 if (TeamBalance_IsTeamAllowedInternal(balance, 1))
319                                 {
320                                         TeamBalance_BanTeamsExcept(balance, 1);
321                                 }
322                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
323                                 {
324                                         TeamBalance_BanTeamsExcept(balance, 2);
325                                 }
326                                 else
327                                 {
328                                         TeamBalance_BanTeamsExcept(balance, 3);
329                                 }
330                                 // no further cases, bots have one of the teams
331                         }
332                 }
333                 else
334                 {
335                         // find first team available
336                         if (IS_BOT_CLIENT(for_whom))
337                         {
338                                 if (TeamBalance_IsTeamAllowedInternal(balance, 1))
339                                 {
340                                         TeamBalance_BanTeamsExcept(balance, 1);
341                                 }
342                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
343                                 {
344                                         TeamBalance_BanTeamsExcept(balance, 2);
345                                 }
346                                 else
347                                 {
348                                         TeamBalance_BanTeamsExcept(balance, 3);
349                                 }
350                                 // no further cases, we know at least 2 teams exist
351                         }
352                         else
353                         {
354                                 if (TeamBalance_IsTeamAllowedInternal(balance, 4))
355                                 {
356                                         TeamBalance_BanTeamsExcept(balance, 4);
357                                 }
358                                 else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
359                                 {
360                                         TeamBalance_BanTeamsExcept(balance, 3);
361                                 }
362                                 else
363                                 {
364                                         TeamBalance_BanTeamsExcept(balance, 2);
365                                 }
366                                 // no further cases, bots have one of the teams
367                         }
368                 }
369         }
370
371         if (!for_whom)
372         {
373                 balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
374                 return balance;
375         }
376
377         // if player has a forced team, ONLY allow that one
378         for (int i = 1; i <= NUM_TEAMS; ++i)
379         {
380                 if (for_whom.team_forced == Team_IndexToTeam(i) &&
381                         TeamBalance_IsTeamAllowedInternal(balance, i))
382                 {
383                         TeamBalance_BanTeamsExcept(balance, i);
384                 }
385                 break;
386         }
387         balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
388         return balance;
389 }
390
391 void TeamBalance_Destroy(entity balance)
392 {
393         if (balance == NULL)
394         {
395                 return;
396         }
397         for (int i = 0; i < NUM_TEAMS; ++i)
398         {
399                 remove(balance.(m_team_balance_team[i]));
400         }
401         remove(balance);
402 }
403
404 int TeamBalance_GetAllowedTeams(entity balance)
405 {
406         if (balance == NULL)
407         {
408                 LOG_FATAL("TeamBalance_GetAllowedTeams: Team balance entity is NULL.");
409         }
410         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
411         {
412                 LOG_FATAL("TeamBalance_GetAllowedTeams: "
413                         "Team balance entity is not initialized.");
414         }
415         int result = 0;
416         for (int i = 1; i <= NUM_TEAMS; ++i)
417         {
418                 if (TeamBalance_IsTeamAllowedInternal(balance, i))
419                 {
420                         result |= Team_IndexToBit(i);
421                 }
422         }
423         return result;
424 }
425
426 bool TeamBalance_IsTeamAllowed(entity balance, int index)
427 {
428         if (balance == NULL)
429         {
430                 LOG_FATAL("TeamBalance_IsTeamAllowed: Team balance entity is NULL.");
431         }
432         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
433         {
434                 LOG_FATAL("TeamBalance_IsTeamAllowed: "
435                         "Team balance entity is not initialized.");
436         }
437         if (!Team_IsValidIndex(index))
438         {
439                 LOG_FATALF("TeamBalance_IsTeamAllowed: Team index is invalid: %f",
440                         index);
441         }
442         return TeamBalance_IsTeamAllowedInternal(balance, index);
443 }
444
445 void TeamBalance_GetTeamCounts(entity balance, entity ignore)
446 {
447         if (balance == NULL)
448         {
449                 LOG_FATAL("TeamBalance_GetTeamCounts: Team balance entity is NULL.");
450         }
451         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
452         {
453                 LOG_FATAL("TeamBalance_GetTeamCounts: "
454                         "Team balance entity is not initialized.");
455         }
456         if (MUTATOR_CALLHOOK(TeamBalance_GetTeamCounts) == true)
457         {
458                 // Mutator has overriden the configuration.
459                 for (int i = 1; i <= NUM_TEAMS; ++i)
460                 {
461                         entity team_ = TeamBalance_GetTeamFromIndex(balance, i);
462                         if (TeamBalanceTeam_IsAllowed(team_))
463                         {
464                                 MUTATOR_CALLHOOK(TeamBalance_GetTeamCount, i, ignore,
465                                         team_.m_num_players, team_.m_num_bots, team_.m_lowest_human,
466                                         team_.m_lowest_bot);
467                                 team_.m_num_players = M_ARGV(2, float);
468                                 team_.m_num_bots = M_ARGV(3, float);
469                                 team_.m_lowest_human = M_ARGV(4, entity);
470                                 team_.m_lowest_bot = M_ARGV(5, entity);
471                         }
472                 }
473         }
474         else
475         {
476                 // Manually count all players.
477                 FOREACH_CLIENT(true,
478                 {
479                         if (it == ignore)
480                         {
481                                 continue;
482                         }
483                         int team_num;
484                         if (IS_PLAYER(it) || it.caplayer)
485                         {
486                                 team_num = it.team;
487                         }
488                         else if (it.team_forced > 0)
489                         {
490                                 team_num = it.team_forced; // reserve the spot
491                         }
492                         else
493                         {
494                                 continue;
495                         }
496                         if (!Team_IsValidTeam(team_num))
497                         {
498                                 continue;
499                         }
500                         entity team_ = TeamBalance_GetTeam(balance, team_num);
501                         if (!TeamBalanceTeam_IsAllowed(team_))
502                         {
503                                 continue;
504                         }
505                         ++team_.m_num_players;
506                         if (IS_BOT_CLIENT(it))
507                         {
508                                 ++team_.m_num_bots;
509                         }
510                         float temp_score = PlayerScore_Get(it, SP_SCORE);
511                         if (!IS_BOT_CLIENT(it))
512                         {
513                                 if (team_.m_lowest_human == NULL)
514                                 {
515                                         team_.m_lowest_human = it;
516                                         continue;
517                                 }
518                                 if (temp_score < PlayerScore_Get(team_.m_lowest_human,
519                                         SP_SCORE))
520                                 {
521                                         team_.m_lowest_human = it;
522                                 }
523                                 continue;
524                         }
525                         if (team_.m_lowest_bot == NULL)
526                         {
527                                 team_.m_lowest_bot = it;
528                                 continue;
529                         }
530                         if (temp_score < PlayerScore_Get(team_.m_lowest_bot, SP_SCORE))
531                         {
532                                 team_.m_lowest_bot = it;
533                         }
534                 });
535         }
536
537         // if the player who has a forced team has not joined yet, reserve the spot
538         if (autocvar_g_campaign)
539         {
540                 if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
541                 {
542                         entity team_ = TeamBalance_GetTeamFromIndex(balance,
543                                 autocvar_g_campaign_forceteam);
544                         if (team_.m_num_players == team_.m_num_bots)
545                         {
546                                 ++team_.m_num_players;
547                         }
548                 }
549         }
550         balance.m_team_balance_state = TEAM_BALANCE_TEAM_COUNTS_FILLED;
551 }
552
553 int TeamBalance_GetNumberOfPlayers(entity balance, int index)
554 {
555         if (balance == NULL)
556         {
557                 LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
558                         "Team balance entity is NULL.");
559         }
560         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
561         {
562                 LOG_FATAL("TeamBalance_GetNumberOfPlayers: "
563                         "TeamBalance_GetTeamCounts has not been called.");
564         }
565         if (!Team_IsValidIndex(index))
566         {
567                 LOG_FATALF("TeamBalance_GetNumberOfPlayers: Team index is invalid: %f",
568                         index);
569         }
570         return balance.m_team_balance_team[index - 1].m_num_players;
571 }
572
573 int TeamBalance_FindBestTeam(entity balance, entity player, bool ignore_player)
574 {
575         if (balance == NULL)
576         {
577                 LOG_FATAL("TeamBalance_FindBestTeam: Team balance entity is NULL.");
578         }
579         if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
580         {
581                 LOG_FATAL("TeamBalance_FindBestTeam: "
582                         "Team balance entity is not initialized.");
583         }
584         // count how many players are in each team
585         if (ignore_player)
586         {
587                 TeamBalance_GetTeamCounts(balance, player);
588         }
589         else
590         {
591                 TeamBalance_GetTeamCounts(balance, NULL);
592         }
593         int team_bits = TeamBalance_FindBestTeams(balance, player, true);
594         if (team_bits == 0)
595         {
596                 LOG_FATALF("TeamBalance_FindBestTeam: No teams available for %s\n",
597                         MapInfo_Type_ToString(MapInfo_CurrentGametype()));
598         }
599         RandomSelection_Init();
600         for (int i = 1; i <= NUM_TEAMS; ++i)
601         {
602                 if (team_bits & Team_IndexToBit(i))
603                 {
604                         RandomSelection_AddFloat(i, 1, 1);
605                 }
606         }
607         return RandomSelection_chosen_float;
608 }
609
610 int TeamBalance_FindBestTeams(entity balance, entity player, bool use_score)
611 {
612         if (balance == NULL)
613         {
614                 LOG_FATAL("TeamBalance_FindBestTeams: Team balance entity is NULL.");
615         }
616         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
617         {
618                 LOG_FATAL("TeamBalance_FindBestTeams: "
619                         "TeamBalance_GetTeamCounts has not been called.");
620         }
621         if (MUTATOR_CALLHOOK(TeamBalance_FindBestTeams, player) == true)
622         {
623                 return M_ARGV(1, float);
624         }
625         int team_bits = 0;
626         int previous_team = 0;
627         for (int i = 1; i <= NUM_TEAMS; ++i)
628         {
629                 if (!TeamBalance_IsTeamAllowedInternal(balance, i))
630                 {
631                         continue;
632                 }
633                 if (previous_team == 0)
634                 {
635                         team_bits = Team_IndexToBit(i);
636                         previous_team = i;
637                         continue;
638                 }
639                 int compare = TeamBalance_CompareTeams(balance, i, previous_team,
640                         player, use_score);
641                 if (compare == TEAMS_COMPARE_LESS)
642                 {
643                         team_bits = Team_IndexToBit(i);
644                         previous_team = i;
645                         continue;
646                 }
647                 if (compare == TEAMS_COMPARE_EQUAL)
648                 {
649                         team_bits |= Team_IndexToBit(i);
650                         previous_team = i;
651                 }
652         }
653         return team_bits;
654 }
655
656 void TeamBalance_JoinBestTeam(entity this, bool force_best_team)
657 {
658         // don't join a team if we're not playing a team game
659         if (!teamplay)
660         {
661                 return;
662         }
663
664         // find out what teams are available
665         entity balance = TeamBalance_CheckAllowedTeams(this);
666
667         // if we don't care what team they end up on, put them on whatever team they entered as.
668         // if they're not on a valid team, then let other code put them on the smallest team
669         if (!force_best_team)
670         {
671                 int selected_team_index = -1;
672                 for (int i = 1; i <= NUM_TEAMS; ++i)
673                 {
674                         if (TeamBalance_IsTeamAllowedInternal(balance, i) &&
675                                 (Team_TeamToIndex(this.team) == i))
676                         {
677                                 selected_team_index = i;
678                                 break;
679                         }
680                 }
681                 
682                 if (Team_IsValidIndex(selected_team_index))
683                 {
684                         Player_SetTeamIndex(this, selected_team_index);
685                         LogTeamchange(this.playerid, this.team, TEAM_CHANGE_AUTO_RELAXED);
686                         TeamBalance_Destroy(balance);
687                         return;
688                 }
689         }
690         // otherwise end up on the smallest team (handled below)
691         if (this.bot_forced_team)
692         {
693                 TeamBalance_Destroy(balance);
694                 return;
695         }
696         int best_team_index = TeamBalance_FindBestTeam(balance, this, true);
697         int old_team_index = Team_TeamToIndex(this.team);
698         PlayerScore_Clear(this);
699         Player_SetTeamIndex(this, best_team_index);
700         LogTeamchange(this.playerid, this.team, TEAM_CHANGE_AUTO);
701         if ((old_team_index != -1) && !IS_BOT_CLIENT(this))
702         {
703                 TeamBalance_AutoBalanceBots(balance, old_team_index, best_team_index);
704         }
705         KillPlayerForTeamChange(this);
706         TeamBalance_Destroy(balance);
707 }
708
709 int TeamBalance_CompareTeams(entity balance, int team_index_a, int team_index_b,
710         entity player, bool use_score)
711 {
712         if (balance == NULL)
713         {
714                 LOG_FATAL("TeamBalance_CompareTeams: Team balance entity is NULL.");
715         }
716         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
717         {
718                 LOG_FATAL("TeamBalance_CompareTeams: "
719                         "TeamBalance_GetTeamCounts has not been called.");
720         }
721         if (!Team_IsValidIndex(team_index_a))
722         {
723                 LOG_FATALF("TeamBalance_CompareTeams: team_index_a is invalid: %f",
724                         team_index_a);
725         }
726         if (!Team_IsValidIndex(team_index_b))
727         {
728                 LOG_FATALF("TeamBalance_CompareTeams: team_index_b is invalid: %f",
729                         team_index_b);
730         }
731         if (team_index_a == team_index_b)
732         {
733                 return TEAMS_COMPARE_EQUAL;
734         }
735         entity team_a = TeamBalance_GetTeamFromIndex(balance, team_index_a);
736         entity team_b = TeamBalance_GetTeamFromIndex(balance, team_index_b);
737         return TeamBalance_CompareTeamsInternal(team_a, team_b, player, use_score);
738 }
739
740 void TeamBalance_AutoBalanceBots(entity balance, int source_team_index,
741         int destination_team_index)
742 {
743         if (balance == NULL)
744         {
745                 LOG_FATAL("TeamBalance_AutoBalanceBots: Team balance entity is NULL.");
746         }
747         if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
748         {
749                 LOG_FATAL("TeamBalance_AutoBalanceBots: "
750                         "TeamBalance_GetTeamCounts has not been called.");
751         }
752         if (!Team_IsValidIndex(source_team_index))
753         {
754                 LOG_WARNF("AutoBalanceBots: Source team index is invalid: %f",
755                         source_team_index);
756                 return;
757         }
758         if (!Team_IsValidIndex(destination_team_index))
759         {
760                 LOG_WARNF("AutoBalanceBots: Destination team index is invalid: %f",
761                         destination_team_index);
762                 return;
763         }
764         if (!autocvar_g_balance_teams ||
765                 !autocvar_g_balance_teams_prevent_imbalance)
766         {
767                 return;
768         }
769         entity source_team = TeamBalance_GetTeamFromIndex(balance,
770                 source_team_index);
771         if (!TeamBalanceTeam_IsAllowed(source_team))
772         {
773                 return;
774         }
775         entity destination_team = TeamBalance_GetTeamFromIndex(balance,
776                 destination_team_index);
777         if ((destination_team.m_num_players <= source_team.m_num_players) ||
778                 (destination_team.m_lowest_bot == NULL))
779         {
780                 return;
781         }
782         Player_SetTeamIndex(destination_team.m_lowest_bot, source_team_index);
783         KillPlayerForTeamChange(destination_team.m_lowest_bot);
784 }
785
786 bool TeamBalance_IsTeamAllowedInternal(entity balance, int index)
787 {
788         return balance.m_team_balance_team[index - 1].m_num_players !=
789                 TEAM_NOT_ALLOWED;
790 }
791
792 void TeamBalance_BanTeamsExcept(entity balance, int index)
793 {
794         for (int i = 1; i <= NUM_TEAMS; ++i)
795         {
796                 if (i != index)
797                 {
798                         balance.m_team_balance_team[i - 1].m_num_players = TEAM_NOT_ALLOWED;
799                 }
800         }
801 }
802
803 entity TeamBalance_GetTeamFromIndex(entity balance, int index)
804 {
805         if (!Team_IsValidIndex(index))
806         {
807                 LOG_FATALF("TeamBalance_GetTeamFromIndex: Index is invalid: %f", index);
808         }
809         return balance.m_team_balance_team[index - 1];
810 }
811
812 entity TeamBalance_GetTeam(entity balance, int team_num)
813 {
814         return TeamBalance_GetTeamFromIndex(balance, Team_TeamToIndex(team_num));
815 }
816
817 bool TeamBalanceTeam_IsAllowed(entity team_)
818 {
819         return team_.m_num_players != TEAM_NOT_ALLOWED;
820 }
821
822 int TeamBalanceTeam_GetNumberOfPlayers(entity team_)
823 {
824         return team_.m_num_players;
825 }
826
827 int TeamBalanceTeam_GetNumberOfBots(entity team_)
828 {
829         return team_.m_num_bots;
830 }
831
832 entity TeamBalanceTeam_GetLowestHuman(entity team_)
833 {
834         return team_.m_lowest_human;
835 }
836
837 entity TeamBalanceTeam_GetLowestBot(entity team_)
838 {
839         return team_.m_lowest_bot;
840 }
841
842 int TeamBalance_CompareTeamsInternal(entity team_a, entity team_b,
843         entity player, bool use_score)
844 {
845         if (team_a == team_b)
846         {
847                 return TEAMS_COMPARE_EQUAL;
848         }
849         if (!TeamBalanceTeam_IsAllowed(team_a) ||
850                 !TeamBalanceTeam_IsAllowed(team_b))
851         {
852                 return TEAMS_COMPARE_INVALID;
853         }
854         int num_players_team_a = team_a.m_num_players;
855         int num_players_team_b = team_b.m_num_players;
856         if (IS_REAL_CLIENT(player) && bots_would_leave)
857         {
858                 num_players_team_a -= team_a.m_num_bots;
859                 num_players_team_b -= team_b.m_num_bots;
860         }
861         if (num_players_team_a < num_players_team_b)
862         {
863                 return TEAMS_COMPARE_LESS;
864         }
865         if (num_players_team_a > num_players_team_b)
866         {
867                 return TEAMS_COMPARE_GREATER;
868         }
869         if (!use_score)
870         {
871                 return TEAMS_COMPARE_EQUAL;
872         }
873         if (team_a.m_team_score < team_b.m_team_score)
874         {
875                 return TEAMS_COMPARE_LESS;
876         }
877         if (team_a.m_team_score > team_b.m_team_score)
878         {
879                 return TEAMS_COMPARE_GREATER;
880         }
881         return TEAMS_COMPARE_EQUAL;
882 }
883
884 void SV_ChangeTeam(entity this, float _color)
885 {
886         int source_color, destination_color;
887         int source_team_index, destination_team_index;
888
889         // in normal deathmatch we can just apply the color and we're done
890         if(!teamplay)
891                 SetPlayerColors(this, _color);
892
893         if(!IS_CLIENT(this))
894         {
895                 // since this is an engine function, and gamecode doesn't have any calls earlier than this, do the connecting message here
896                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_CONNECTING, this.netname);
897                 return;
898         }
899
900         if(!teamplay)
901                 return;
902
903         source_color = this.clientcolors & 0x0F;
904         destination_color = _color & 0x0F;
905
906         source_team_index = Team_TeamToIndex(source_color + 1);
907         destination_team_index = Team_TeamToIndex(destination_color + 1);
908
909         if (destination_team_index == -1)
910         {
911                 return;
912         }
913
914         entity balance = TeamBalance_CheckAllowedTeams(this);
915
916         if (destination_team_index == 1 && !TeamBalance_IsTeamAllowedInternal(
917                 balance, 1))
918         {
919                 destination_team_index = 4;
920         }
921         if (destination_team_index == 4 && !TeamBalance_IsTeamAllowedInternal(
922                 balance, 4))
923         {
924                 destination_team_index = 3;
925         }
926         if (destination_team_index == 3 && !TeamBalance_IsTeamAllowedInternal(
927                 balance, 3))
928         {
929                 destination_team_index = 2;
930         }
931         if (destination_team_index == 2 && !TeamBalance_IsTeamAllowedInternal(
932                 balance, 2))
933         {
934                 destination_team_index = 1;
935         }
936
937         // not changing teams
938         if (source_color == destination_color)
939         {
940                 SetPlayerTeam(this, destination_team_index, source_team_index, true);
941                 TeamBalance_Destroy(balance);
942                 return;
943         }
944
945         if((autocvar_g_campaign) || (autocvar_g_changeteam_banned && CS(this).wasplayer)) {
946                 Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_NOTALLOWED);
947                 return; // changing teams is not allowed
948         }
949
950         // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
951         if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
952         {
953                 TeamBalance_GetTeamCounts(balance, this);
954                 if ((Team_IndexToBit(destination_team_index) &
955                         TeamBalance_FindBestTeams(balance, this, false)) == 0)
956                 {
957                         Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
958                         TeamBalance_Destroy(balance);
959                         return;
960                 }
961         }
962         if (IS_PLAYER(this) && source_team_index != destination_team_index)
963         {
964                 // reduce frags during a team change
965                 PlayerScore_Clear(this);
966         }
967         if (!SetPlayerTeam(this, destination_team_index, source_team_index,
968                 !IS_CLIENT(this)))
969         {
970                 TeamBalance_Destroy(balance);
971                 return;
972         }
973         TeamBalance_AutoBalanceBots(balance, source_team_index,
974                 destination_team_index);
975         if (!IS_PLAYER(this) || (source_team_index == destination_team_index))
976         {
977                 TeamBalance_Destroy(balance);
978                 return;
979         }
980         KillPlayerForTeamChange(this);
981         TeamBalance_Destroy(balance);
982 }