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