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