]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/commitdiff
Merged master.
authorLyberta <lyberta@lyberta.net>
Sat, 5 Aug 2017 09:57:41 +0000 (12:57 +0300)
committerLyberta <lyberta@lyberta.net>
Sat, 5 Aug 2017 09:57:41 +0000 (12:57 +0300)
qcsrc/server/autocvars.qh
qcsrc/server/client.qc
qcsrc/server/client.qh
qcsrc/server/command/cmd.qc
qcsrc/server/command/sv_cmd.qc
qcsrc/server/mutators/events.qh
qcsrc/server/player.qc
qcsrc/server/player.qh
qcsrc/server/scores_rules.qc
qcsrc/server/teamplay.qc
qcsrc/server/teamplay.qh

index f585a9a2c33db3eafb7b72168b2b3d8a50de8afd..61b9df462e98a7c60d59063b57c24ba1f2cff763 100644 (file)
@@ -88,7 +88,7 @@ float autocvar_g_balance_superweapons_time;
 float autocvar_g_balance_selfdamagepercent;
 bool autocvar_g_balance_teams;
 bool autocvar_g_balance_teams_prevent_imbalance;
-float autocvar_g_balance_teams_scorefactor;
+//float autocvar_g_balance_teams_scorefactor;
 float autocvar_g_ballistics_density_corpse;
 float autocvar_g_ballistics_density_player;
 float autocvar_g_ballistics_mindistance;
index 14b854bc6eb5f35cc279db18b12bf70634b45d94..e255174c008c32fb715ef65de6cee1d98ac3fa33 100644 (file)
@@ -267,7 +267,9 @@ void PutObserverInServer(entity this)
        if (mutator_returnvalue) {
            // mutator prevents resetting teams+score
        } else {
+               int oldteam = this.team;
                this.team = -1;  // move this as it is needed to log the player spectating in eventlog
+               MUTATOR_CALLHOOK(Player_ChangedTeam, this, oldteam, this.team);
         this.frags = FRAGS_SPECTATOR;
         PlayerScore_Clear(this);  // clear scores when needed
     }
@@ -891,8 +893,10 @@ void ClientKill_Now(entity this)
        if(CS(this).killindicator_teamchange)
                ClientKill_Now_TeamChange(this);
 
-       if(!IS_SPEC(this) && !IS_OBSERVER(this))
+       if (!IS_SPEC(this) && !IS_OBSERVER(this) && MUTATOR_CALLHOOK(ClientKill_Now, this) == false)
+       {
                Damage(this, this, this, 100000, DEATH_KILL.m_id, this.origin, '0 0 0');
+       }
 
        // now I am sure the player IS dead
 }
index ee00c60ca6f97f4603c1572ec34099a1cb800e46..2928aae1c927bd5685acd4f576b629719c14a953 100644 (file)
@@ -189,8 +189,6 @@ METHOD(Client, m_unwind, bool(Client this))
     return false;
 }
 
-float c1, c2, c3, c4;
-
 void play_countdown(entity this, float finished, Sound samp);
 
 float CalcRotRegen(float current, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit);
index 03f484d2e68f566e42c526a7239a88bacf0312ec..6c5e3829f7ae31fe0e9d5ee401b703dc3771d28f 100644 (file)
@@ -319,82 +319,98 @@ void ClientCommand_selectteam(entity caller, float request, float argc)
        {
                case CMD_REQUEST_COMMAND:
                {
-                       if (argv(1) != "")
+                       if (argv(1) == "")
                        {
-                               if (IS_CLIENT(caller))
+                               return;
+                       }
+                       if (!IS_CLIENT(caller))
+                       {
+                               return;
+                       }
+                       if (!teamplay)
+                       {
+                               sprint(caller, "^7selectteam can only be used in teamgames\n");
+                               return;
+                       }
+                       if (caller.team_forced > 0)
+                       {
+                               sprint(caller, "^7selectteam can not be used as your team is forced\n");
+                               return;
+                       }
+                       if (lockteams)
+                       {
+                               sprint(caller, "^7The game has already begun, you must wait until the next map to be able to join a team.\n");
+                               return;
+                       }
+                       float selection;
+                       switch (argv(1))
+                       {
+                               case "red":
                                {
-                                       if (teamplay)
-                                       {
-                                               if (caller.team_forced <= 0)
-                                               {
-                                                       if (!lockteams)
-                                                       {
-                                                               float selection;
-
-                                                               switch (argv(1))
-                                                               {
-                                                                       case "red": selection = NUM_TEAM_1;
-                                                                               break;
-                                                                       case "blue": selection = NUM_TEAM_2;
-                                                                               break;
-                                                                       case "yellow": selection = NUM_TEAM_3;
-                                                                               break;
-                                                                       case "pink": selection = NUM_TEAM_4;
-                                                                               break;
-                                                                       case "auto": selection = (-1);
-                                                                               break;
-
-                                                                       default: selection = 0;
-                                                                               break;
-                                                               }
-
-                                                               if (selection)
-                                                               {
-                                                                       if (caller.team == selection && selection != -1 && !IS_DEAD(caller))
-                                                                       {
-                                                                               sprint(caller, "^7You already are on that team.\n");
-                                                                       }
-                                                                       else if (CS(caller).wasplayer && autocvar_g_changeteam_banned)
-                                                                       {
-                                                                               sprint(caller, "^1You cannot change team, forbidden by the server.\n");
-                                                                       }
-                                                                       else
-                                                                       {
-                                                                               if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
-                                                                               {
-                                                                                       CheckAllowedTeams(caller);
-                                                                                       GetTeamCounts(caller);
-                                                                                       if (!TeamSmallerEqThanTeam(Team_TeamToNumber(selection), Team_TeamToNumber(caller.team), caller))
-                                                                                       {
-                                                                                               Send_Notification(NOTIF_ONE, caller, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
-                                                                                               return;
-                                                                                       }
-                                                                               }
-                                                                               ClientKill_TeamChange(caller, selection);
-                                                                       }
-                                                                       if(!IS_PLAYER(caller))
-                                                                               caller.team_selected = true; // avoids asking again for team selection on join
-                                                               }
-                                                       }
-                                                       else
-                                                       {
-                                                               sprint(caller, "^7The game has already begun, you must wait until the next map to be able to join a team.\n");
-                                                       }
-                                               }
-                                               else
-                                               {
-                                                       sprint(caller, "^7selectteam can not be used as your team is forced\n");
-                                               }
-                                       }
-                                       else
-                                       {
-                                               sprint(caller, "^7selectteam can only be used in teamgames\n");
-                                       }
+                                       selection = NUM_TEAM_1;
+                                       break;
+                               }
+                               case "blue":
+                               {
+                                       selection = NUM_TEAM_2;
+                                       break;
                                }
+                               case "yellow":
+                               {
+                                       selection = NUM_TEAM_3;
+                                       break;
+                               }
+                               case "pink":
+                               {
+                                       selection = NUM_TEAM_4;
+                                       break;
+                               }
+                               case "auto":
+                               {
+                                       selection = (-1);
+                                       break;
+                               }
+                               default:
+                               {
+                                       return;
+                               }
+                       }
+                       if (caller.team == selection && selection != -1 && !IS_DEAD(caller))
+                       {
+                               sprint(caller, "^7You already are on that team.\n");
+                               return;
+                       }
+                       if (CS(caller).wasplayer && autocvar_g_changeteam_banned)
+                       {
+                               sprint(caller, "^1You cannot change team, forbidden by the server.\n");
                                return;
                        }
+                       if (selection == -1)
+                       {
+                               ClientKill_TeamChange(caller, selection);
+                               if (!IS_PLAYER(caller))
+                               {
+                                       caller.team_selected = true; // avoids asking again for team selection on join
+                               }
+                               return;
+                       }
+                       if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
+                       {
+                               CheckAllowedTeams(caller);
+                               GetTeamCounts(caller);
+                               if ((BIT(Team_TeamToNumber(selection) - 1) & FindBestTeams(caller, false)) == 0)
+                               {
+                                       Send_Notification(NOTIF_ONE, caller, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
+                                       return;
+                               }
+                       }
+                       ClientKill_TeamChange(caller, selection);
+                       if (!IS_PLAYER(caller))
+                       {
+                               caller.team_selected = true; // avoids asking again for team selection on join
+                       }
+                       return;
                }
-
                default:
                        sprint(caller, "Incorrect parameters for ^2selectteam^7\n");
                case CMD_REQUEST_USAGE:
index 0bc47c0acf67fcdb2d81234429b5ef1a585a7836..4687403d2a0006124861a204f9e8914bf8081244 100644 (file)
@@ -1091,9 +1091,15 @@ void GameCommand_moveplayer(float request, float argc)
 
                                                                // If so, lets continue and finally move the player
                                                                client.team_forced = 0;
-                                                               MoveToTeam(client, team_id, 6);
-                                                               successful = strcat(successful, (successful ? ", " : ""), playername(client, false));
-                                                               LOG_INFO("Player ", ftos(GetFilteredNumber(t)), " (", playername(client, false), ") has been moved to the ", Team_ColoredFullName(team_id), "^7.\n");
+                                                               if (MoveToTeam(client, team_id, 6))
+                                                               {
+                                                                       successful = strcat(successful, (successful ? ", " : ""), playername(client, false));
+                                                                       LOG_INFO("Player ", ftos(GetFilteredNumber(t)), " (", playername(client, false), ") has been moved to the ", Team_ColoredFullName(team_id), "^7.\n");
+                                                               }
+                                                               else
+                                                               {
+                                                                       LOG_INFO("Unable to move player ", ftos(GetFilteredNumber(t)), " (", playername(client, false), ")");
+                                                               }
                                                                continue;
                                                        }
                                                        else
index bc09d7a8cd9d92d3da6340807e8a09fd13b384cc..ec5d3f1ecdeceb65f25c41460800ac3616f49ed5 100644 (file)
@@ -130,6 +130,31 @@ MUTATOR_HOOKABLE(MatchEnd, EV_NO_ARGS);
     /**/
 MUTATOR_HOOKABLE(CheckAllowedTeams, EV_CheckAllowedTeams);
 
+/** return true to manually override team counts */
+MUTATOR_HOOKABLE(GetTeamCounts, EV_NO_ARGS);
+
+/** allow overriding of team counts */
+#define EV_GetTeamCount(i, o) \
+    /** team to count                   */ i(float, MUTATOR_ARGV_0_float) \
+    /** player to ignore                */ i(entity, MUTATOR_ARGV_1_entity) \
+    /** number of players in a team     */ i(float, MUTATOR_ARGV_2_float) \
+    /**/                                   o(float, MUTATOR_ARGV_2_float) \
+    /** number of bots in a team        */ i(float, MUTATOR_ARGV_3_float) \
+    /**/                                   o(float, MUTATOR_ARGV_3_float) \
+    /** lowest scoring human in a team  */ i(entity, MUTATOR_ARGV_4_entity) \
+    /**/                                   o(entity, MUTATOR_ARGV_4_entity) \
+    /** lowest scoring bot in a team    */ i(entity, MUTATOR_ARGV_5_entity) \
+    /**/                                   o(entity, MUTATOR_ARGV_5_entity) \
+    /**/
+MUTATOR_HOOKABLE(GetTeamCount, EV_GetTeamCount);
+
+/** allows overriding best teams */
+#define EV_FindBestTeams(i, o) \
+    /** player checked   */ i(entity, MUTATOR_ARGV_0_entity) \
+    /** bitmask of teams */ o(float, MUTATOR_ARGV_1_float) \
+    /**/
+MUTATOR_HOOKABLE(FindBestTeams, EV_FindBestTeams);
+
 /** copies variables for spectating "spectatee" to "this" */
 #define EV_SpectateCopy(i, o) \
     /** spectatee   */ i(entity, MUTATOR_ARGV_0_entity) \
@@ -728,6 +753,12 @@ MUTATOR_HOOKABLE(Race_FinalCheckpoint, EV_Race_FinalCheckpoint);
     /**/
 MUTATOR_HOOKABLE(ClientKill, EV_ClientKill);
 
+/** called when player is about to be killed during kill command or changing teams */
+#define EV_ClientKill_Now(i, o) \
+    /** player */        i(entity, MUTATOR_ARGV_0_entity) \
+    /**/
+MUTATOR_HOOKABLE(ClientKill_Now, EV_ClientKill_Now);
+
 #define EV_FixClientCvars(i, o) \
     /** player */        i(entity, MUTATOR_ARGV_0_entity) \
     /**/
@@ -875,7 +906,9 @@ MUTATOR_HOOKABLE(PrepareExplosionByDamage, EV_PrepareExplosionByDamage);
     /**/
 MUTATOR_HOOKABLE(MonsterModel, EV_MonsterModel);
 
-/**/
+/**
+ * Called before player changes their team. Return true to block team change.
+ */
 #define EV_Player_ChangeTeam(i, o) \
     /** player */         i(entity, MUTATOR_ARGV_0_entity) \
        /** current team */   i(float, MUTATOR_ARGV_1_float) \
@@ -883,6 +916,24 @@ MUTATOR_HOOKABLE(MonsterModel, EV_MonsterModel);
     /**/
 MUTATOR_HOOKABLE(Player_ChangeTeam, EV_Player_ChangeTeam);
 
+/**
+ * Called after player has changed their team.
+ */
+#define EV_Player_ChangedTeam(i, o) \
+    /** player */         i(entity, MUTATOR_ARGV_0_entity) \
+       /** old team */       i(float, MUTATOR_ARGV_1_float) \
+       /** current team */   i(float, MUTATOR_ARGV_2_float) \
+    /**/
+MUTATOR_HOOKABLE(Player_ChangedTeam, EV_Player_ChangedTeam);
+
+/**
+ * Called when player is about to be killed when changing teams. Return true to block killing.
+ */
+#define EV_Player_ChangeTeamKill(i, o) \
+    /** player */    i(entity, MUTATOR_ARGV_0_entity) \
+    /**/
+MUTATOR_HOOKABLE(Player_ChangeTeamKill, EV_Player_ChangeTeamKill);
+
 /**/
 #define EV_URI_GetCallback(i, o) \
        /** id */       i(float, MUTATOR_ARGV_0_float) \
index d70210feab5b3726645b74706ca34afebcaa4131..e41bf931b7cf1d1402fcf74aedad0aca9d4193f7 100644 (file)
@@ -667,15 +667,19 @@ void PlayerDamage(entity this, entity inflictor, entity attacker, float damage,
        }
 }
 
-void MoveToTeam(entity client, int team_colour, int type)
+bool MoveToTeam(entity client, int team_colour, int type)
 {
        int lockteams_backup = lockteams;  // backup any team lock
        lockteams = 0;  // disable locked teams
        TeamchangeFrags(client);  // move the players frags
-       SetPlayerColors(client, team_colour - 1);  // set the players colour
+       if (!SetPlayerTeamSimple(client, team_colour))
+       {
+               return false;
+       }
        Damage(client, client, client, 100000, DEATH_AUTOTEAMCHANGE.m_id, client.origin, '0 0 0');  // kill the player
        lockteams = lockteams_backup;  // restore the team lock
        LogTeamchange(client.playerid, client.team, type);
+       return true;
 }
 
 /** print(), but only print if the server is not local */
index 1834bb865ffbb668801e525eb40b7e90f5afa341..dfa485e5f11fddad33799689e9d354fae640e572 100644 (file)
@@ -69,7 +69,12 @@ void calculate_player_respawn_time(entity this);
 
 void ClientKill_Now_TeamChange(entity this);
 
-void MoveToTeam(entity client, float team_colour, float type);
+/// \brief Moves player to the specified team.
+/// \param[in,out] client Client to move.
+/// \param[in] team_colour Color of the team.
+/// \param[in] type ???
+/// \return True on success, false otherwise.
+bool MoveToTeam(entity client, float team_colour, float type);
 
 void PlayerDamage(entity this, entity inflictor, entity attacker, float damage, int deathtype, vector hitloc, vector force);
 
index 9c416472f40a207b0870c9bc5be4fc416502d48b..5ee25f5bf369d4574c1d4064734672e906784c9b 100644 (file)
@@ -2,6 +2,7 @@
 
 #include "client.qh"
 #include "scores.qh"
+#include "teamplay.qh"
 
 int ScoreRules_teams;
 
index 793a227b897bb1d6b92a5c438184568f44e0b564..92cd8ebccedede1cfabe53bbb3211cb31df71890 100644 (file)
@@ -169,58 +169,79 @@ void setcolor(entity this, int clr)
 #endif
 }
 
-void SetPlayerColors(entity pl, float _color)
+void SetPlayerColors(entity player, float _color)
 {
-       /*string s;
-       s = ftos(cl);
-       stuffcmd(pl, strcat("color ", s, " ", s, "\n")  );
-       pl.team = cl + 1;
-       //pl.clientcolors = pl.clientcolors - (pl.clientcolors & 15) + cl;
-       pl.clientcolors = 16*cl + cl;*/
-
-       float pants, shirt;
-       pants = _color & 0x0F;
-       shirt = _color & 0xF0;
-
-
-       if(teamplay) {
-               setcolor(pl, 16*pants + pants);
-       } else {
-               setcolor(pl, shirt + pants);
+       float pants = _color & 0x0F;
+       float shirt = _color & 0xF0;
+       if (teamplay)
+       {
+               setcolor(player, 16 * pants + pants);
+       }
+       else
+       {
+               setcolor(player, shirt + pants);
        }
 }
 
-void SetPlayerTeam(entity pl, float t, float s, float noprint)
+void KillPlayerForTeamChange(entity player)
 {
-       float _color;
-
-       if(t == 4)
-               _color = NUM_TEAM_4 - 1;
-       else if(t == 3)
-               _color = NUM_TEAM_3 - 1;
-       else if(t == 2)
-               _color = NUM_TEAM_2 - 1;
-       else
-               _color = NUM_TEAM_1 - 1;
-
-       SetPlayerColors(pl,_color);
-
-       if(t != s) {
-               LogTeamchange(pl.playerid, pl.team, 3);  // log manual team join
+       if (IS_DEAD(player))
+       {
+               return;
+       }
+       if (MUTATOR_CALLHOOK(Player_ChangeTeamKill, player) == true)
+       {
+               return;
+       }
+       Damage(player, player, player, 100000, DEATH_TEAMCHANGE.m_id, player.origin,
+               '0 0 0');
+}
 
-               if(!noprint)
-                       bprint(playername(pl, false), "^7 has changed from ", Team_NumberToColoredFullName(s), "^7 to ", Team_NumberToColoredFullName(t), "\n");
+bool SetPlayerTeamSimple(entity player, int team_num)
+{
+       if (player.team == team_num)
+       {
+               // This is important when players join the game and one of their color
+               // matches the team color while other doesn't. For example [BOT]Lion.
+               SetPlayerColors(player, team_num - 1);
+               return true;
        }
+       if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, Team_TeamToNumber(
+               player.team), Team_TeamToNumber(team_num)) == true)
+       {
+               // Mutator has blocked team change.
+               return false;
+       }
+       int old_team = player.team;
+       SetPlayerColors(player, team_num - 1);
+       MUTATOR_CALLHOOK(Player_ChangedTeam, player, old_team, player.team);
+       return true;
+}
 
+bool SetPlayerTeam(entity player, int destination_team, int source_team,
+       bool no_print)
+{
+       int team_num = Team_NumberToTeam(destination_team);
+       if (!SetPlayerTeamSimple(player, team_num))
+       {
+               return false;
+       }
+       LogTeamchange(player.playerid, player.team, 3);  // log manual team join
+       if (no_print)
+       {
+               return true;
+       }
+       bprint(playername(player, false), "^7 has changed from ", Team_NumberToColoredFullName(source_team), "^7 to ", Team_NumberToColoredFullName(destination_team), "\n");
+       return true;
 }
 
 // set c1...c4 to show what teams are allowed
-void CheckAllowedTeams (entity for_whom)
+void CheckAllowedTeams(entity for_whom)
 {
        int teams_mask = 0;
 
        c1 = c2 = c3 = c4 = -1;
-       cb1 = cb2 = cb3 = cb4 = 0;
+       num_bots_team1 = num_bots_team2 = num_bots_team3 = num_bots_team4 = 0;
 
        string teament_name = string_null;
 
@@ -322,284 +343,571 @@ float PlayerValue(entity p)
 // teams that are allowed will now have their player counts stored in c1...c4
 void GetTeamCounts(entity ignore)
 {
-       float value, bvalue;
-       // now count how many players are on each team already
-
-       // FIXME: also find and memorize the lowest-scoring bot on each team (in case players must be shuffled around)
-       // also remember the lowest-scoring player
-
-       FOREACH_CLIENT(true, {
-               float t;
-               if(IS_PLAYER(it) || it.caplayer)
-                       t = it.team;
-               else if(it.team_forced > 0)
-                       t = it.team_forced; // reserve the spot
-               else
-                       continue;
-               if(it != ignore)// && it.netname != "")
+       if (MUTATOR_CALLHOOK(GetTeamCounts) == true)
+       {
+               if (c1 >= 0)
+               {
+                       MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_1, ignore, c1,
+                               num_bots_team1, lowest_human_team1, lowest_bot_team1);
+                       c1 = M_ARGV(2, float);
+                       num_bots_team1 = M_ARGV(3, float);
+                       lowest_human_team1 = M_ARGV(4, entity);
+                       lowest_bot_team1 = M_ARGV(5, entity);
+               }
+               if (c2 >= 0)
+               {
+                       MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_2, ignore, c2,
+                               num_bots_team2, lowest_human_team2, lowest_bot_team2);
+                       c2 = M_ARGV(2, float);
+                       num_bots_team2 = M_ARGV(3, float);
+                       lowest_human_team2 = M_ARGV(4, entity);
+                       lowest_bot_team2 = M_ARGV(5, entity);
+               }
+               if (c3 >= 0)
+               {
+                       MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_3, ignore, c3,
+                               num_bots_team3, lowest_human_team3, lowest_bot_team3);
+                       c3 = M_ARGV(2, float);
+                       num_bots_team3 = M_ARGV(3, float);
+                       lowest_human_team3 = M_ARGV(4, entity);
+                       lowest_bot_team3 = M_ARGV(5, entity);
+               }
+               if (c4 >= 0)
+               {
+                       MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_4, ignore,
+                               c4, num_bots_team4, lowest_human_team4, lowest_bot_team4);
+                       c4 = M_ARGV(2, float);
+                       num_bots_team4 = M_ARGV(3, float);
+                       lowest_human_team4 = M_ARGV(4, entity);
+                       lowest_bot_team4 = M_ARGV(5, entity);
+               }
+       }
+       else
+       {
+               float value, bvalue;
+               // now count how many players are on each team already
+               float lowest_human_score1 = FLOAT_MAX;
+               float lowest_bot_score1 = FLOAT_MAX;
+               float lowest_human_score2 = FLOAT_MAX;
+               float lowest_bot_score2 = FLOAT_MAX;
+               float lowest_human_score3 = FLOAT_MAX;
+               float lowest_bot_score3 = FLOAT_MAX;
+               float lowest_human_score4 = FLOAT_MAX;
+               float lowest_bot_score4 = FLOAT_MAX;
+               FOREACH_CLIENT(true,
                {
+                       float t;
+                       if (IS_PLAYER(it) || it.caplayer)
+                       {
+                               t = it.team;
+                       }
+                       else if (it.team_forced > 0)
+                       {
+                               t = it.team_forced; // reserve the spot
+                       }
+                       else
+                       {
+                               continue;
+                       }
+                       if (it == ignore)
+                       {
+                               continue;
+                       }
                        value = PlayerValue(it);
-                       if(IS_BOT_CLIENT(it))
+                       if (IS_BOT_CLIENT(it))
+                       {
                                bvalue = value;
+                       }
                        else
+                       {
                                bvalue = 0;
-                       if(t == NUM_TEAM_1)
+                       }
+                       if (value == 0)
                        {
-                               if(c1 >= 0)
-                               {
-                                       c1 = c1 + value;
-                                       cb1 = cb1 + bvalue;
-                               }
+                               continue;
                        }
-                       else if(t == NUM_TEAM_2)
+                       switch (t)
                        {
-                               if(c2 >= 0)
+                               case NUM_TEAM_1:
                                {
-                                       c2 = c2 + value;
-                                       cb2 = cb2 + bvalue;
+                                       if (c1 < 0)
+                                       {
+                                               break;
+                                       }
+                                       c1 += value;
+                                       num_bots_team1 += bvalue;
+                                       float temp_score = PlayerScore_Get(it, SP_SCORE);
+                                       if (!bvalue)
+                                       {
+                                               if (temp_score < lowest_human_score1)
+                                               {
+                                                       lowest_human_team1 = it;
+                                                       lowest_human_score1 = temp_score;
+                                               }
+                                               break;
+                                       }
+                                       if (temp_score < lowest_bot_score1)
+                                       {
+                                               lowest_bot_team1 = it;
+                                               lowest_bot_score1 = temp_score;
+                                       }
+                                       break;
                                }
-                       }
-                       else if(t == NUM_TEAM_3)
-                       {
-                               if(c3 >= 0)
+                               case NUM_TEAM_2:
                                {
-                                       c3 = c3 + value;
-                                       cb3 = cb3 + bvalue;
+                                       if (c2 < 0)
+                                       {
+                                               break;
+                                       }
+                                       c2 += value;
+                                       num_bots_team2 += bvalue;
+                                       float temp_score = PlayerScore_Get(it, SP_SCORE);
+                                       if (!bvalue)
+                                       {
+                                               if (temp_score < lowest_human_score2)
+                                               {
+                                                       lowest_human_team2 = it;
+                                                       lowest_human_score2 = temp_score;
+                                               }
+                                               break;
+                                       }
+                                       if (temp_score < lowest_bot_score2)
+                                       {
+                                               lowest_bot_team2 = it;
+                                               lowest_bot_score2 = temp_score;
+                                       }
+                                       break;
                                }
-                       }
-                       else if(t == NUM_TEAM_4)
-                       {
-                               if(c4 >= 0)
+                               case NUM_TEAM_3:
+                               {
+                                       if (c3 < 0)
+                                       {
+                                               break;
+                                       }
+                                       c3 += value;
+                                       num_bots_team3 += bvalue;
+                                       float temp_score = PlayerScore_Get(it, SP_SCORE);
+                                       if (!bvalue)
+                                       {
+                                               if (temp_score < lowest_human_score3)
+                                               {
+                                                       lowest_human_team3 = it;
+                                                       lowest_human_score3 = temp_score;
+                                               }
+                                               break;
+                                       }
+                                       if (temp_score < lowest_bot_score3)
+                                       {
+                                               lowest_bot_team3 = it;
+                                               lowest_bot_score3 = temp_score;
+                                       }
+                                       break;
+                               }
+                               case NUM_TEAM_4:
                                {
-                                       c4 = c4 + value;
-                                       cb4 = cb4 + bvalue;
+                                       if (c4 < 0)
+                                       {
+                                               break;
+                                       }
+                                       c4 += value;
+                                       num_bots_team4 += bvalue;
+                                       float temp_score = PlayerScore_Get(it, SP_SCORE);
+                                       if (!bvalue)
+                                       {
+                                               if (temp_score < lowest_human_score4)
+                                               {
+                                                       lowest_human_team4 = it;
+                                                       lowest_human_score4 = temp_score;
+                                               }
+                                               break;
+                                       }
+                                       if (temp_score < lowest_bot_score4)
+                                       {
+                                               lowest_bot_team4 = it;
+                                               lowest_bot_score4 = temp_score;
+                                       }
+                                       break;
                                }
                        }
-               }
-       });
+               });
+       }
 
        // if the player who has a forced team has not joined yet, reserve the spot
        if(autocvar_g_campaign)
        {
                switch(autocvar_g_campaign_forceteam)
                {
-                       case 1: if(c1 == cb1) ++c1; break;
-                       case 2: if(c2 == cb2) ++c2; break;
-                       case 3: if(c3 == cb3) ++c3; break;
-                       case 4: if(c4 == cb4) ++c4; break;
+                       case 1: if(c1 == num_bots_team1) ++c1; break;
+                       case 2: if(c2 == num_bots_team2) ++c2; break;
+                       case 3: if(c3 == num_bots_team3) ++c3; break;
+                       case 4: if(c4 == num_bots_team4) ++c4; break;
                }
        }
 }
 
-float TeamSmallerEqThanTeam(float ta, float tb, entity e)
+bool IsTeamSmallerThanTeam(int team_a, int team_b, entity player,
+       bool use_score)
 {
+       if (team_a == team_b)
+       {
+               return false;
+       }
        // we assume that CheckAllowedTeams and GetTeamCounts have already been called
-       float f;
-       float ca = -1, cb = -1, cba = 0, cbb = 0, sa = 0, sb = 0;
-
-       switch(ta)
+       int num_players_team_a = -1, num_players_team_b = -1;
+       int num_bots_team_a = 0, num_bots_team_b = 0;
+       float score_team_a = 0, score_team_b = 0;
+       switch (team_a)
        {
-               case 1: ca = c1; cba = cb1; sa = team1_score; break;
-               case 2: ca = c2; cba = cb2; sa = team2_score; break;
-               case 3: ca = c3; cba = cb3; sa = team3_score; break;
-               case 4: ca = c4; cba = cb4; sa = team4_score; break;
+               case 1:
+               {
+                       num_players_team_a = c1;
+                       num_bots_team_a = num_bots_team1;
+                       score_team_a = team1_score;
+                       break;
+               }
+               case 2:
+               {
+                       num_players_team_a = c2;
+                       num_bots_team_a = num_bots_team2;
+                       score_team_a = team2_score;
+                       break;
+               }
+               case 3:
+               {
+                       num_players_team_a = c3;
+                       num_bots_team_a = num_bots_team3;
+                       score_team_a = team3_score;
+                       break;
+               }
+               case 4:
+               {
+                       num_players_team_a = c4;
+                       num_bots_team_a = num_bots_team4;
+                       score_team_a = team4_score;
+                       break;
+               }
        }
-       switch(tb)
+       switch (team_b)
        {
-               case 1: cb = c1; cbb = cb1; sb = team1_score; break;
-               case 2: cb = c2; cbb = cb2; sb = team2_score; break;
-               case 3: cb = c3; cbb = cb3; sb = team3_score; break;
-               case 4: cb = c4; cbb = cb4; sb = team4_score; break;
+               case 1:
+               {
+                       num_players_team_b = c1;
+                       num_bots_team_b = num_bots_team1;
+                       score_team_b = team1_score;
+                       break;
+               }
+               case 2:
+               {
+                       num_players_team_b = c2;
+                       num_bots_team_b = num_bots_team2;
+                       score_team_b = team2_score;
+                       break;
+               }
+               case 3:
+               {
+                       num_players_team_b = c3;
+                       num_bots_team_b = num_bots_team3;
+                       score_team_b = team3_score;
+                       break;
+               }
+               case 4:
+               {
+                       num_players_team_b = c4;
+                       num_bots_team_b = num_bots_team4;
+                       score_team_b = team4_score;
+                       break;
+               }
        }
-
        // invalid
-       if(ca < 0 || cb < 0)
+       if (num_players_team_a < 0 || num_players_team_b < 0)
+       {
                return false;
-
-       // equal
-       if(ta == tb)
+       }
+       if (IS_REAL_CLIENT(player) && bots_would_leave)
+       {
+               num_players_team_a -= num_bots_team_a;
+               num_players_team_b -= num_bots_team_b;
+       }
+       if (!use_score)
+       {
+               return num_players_team_a < num_players_team_b;
+       }
+       if (num_players_team_a < num_players_team_b)
+       {
                return true;
+       }
+       if (num_players_team_a > num_players_team_b)
+       {
+               return false;
+       }
+       return score_team_a < score_team_b;
+}
 
-       if(IS_REAL_CLIENT(e))
+bool IsTeamEqualToTeam(int team_a, int team_b, entity player, bool use_score)
+{
+       if (team_a == team_b)
+       {
+               return true;
+       }
+       // we assume that CheckAllowedTeams and GetTeamCounts have already been called
+       int num_players_team_a = -1, num_players_team_b = -1;
+       int num_bots_team_a = 0, num_bots_team_b = 0;
+       float score_team_a = 0, score_team_b = 0;
+       switch (team_a)
        {
-               if(bots_would_leave)
+               case 1:
                {
-                       ca -= cba * 0.999;
-                       cb -= cbb * 0.999;
+                       num_players_team_a = c1;
+                       num_bots_team_a = num_bots_team1;
+                       score_team_a = team1_score;
+                       break;
+               }
+               case 2:
+               {
+                       num_players_team_a = c2;
+                       num_bots_team_a = num_bots_team2;
+                       score_team_a = team2_score;
+                       break;
+               }
+               case 3:
+               {
+                       num_players_team_a = c3;
+                       num_bots_team_a = num_bots_team3;
+                       score_team_a = team3_score;
+                       break;
+               }
+               case 4:
+               {
+                       num_players_team_a = c4;
+                       num_bots_team_a = num_bots_team4;
+                       score_team_a = team4_score;
+                       break;
                }
        }
+       switch (team_b)
+       {
+               case 1:
+               {
+                       num_players_team_b = c1;
+                       num_bots_team_b = num_bots_team1;
+                       score_team_b = team1_score;
+                       break;
+               }
+               case 2:
+               {
+                       num_players_team_b = c2;
+                       num_bots_team_b = num_bots_team2;
+                       score_team_b = team2_score;
+                       break;
+               }
+               case 3:
+               {
+                       num_players_team_b = c3;
+                       num_bots_team_b = num_bots_team3;
+                       score_team_b = team3_score;
+                       break;
+               }
+               case 4:
+               {
+                       num_players_team_b = c4;
+                       num_bots_team_b = num_bots_team4;
+                       score_team_b = team4_score;
+                       break;
+               }
+       }
+       // invalid
+       if (num_players_team_a < 0 || num_players_team_b < 0)
+               return false;
 
-       // keep teams alive (teams of size 0 always count as smaller, ignoring score)
-       if(ca < 1)
-               if(cb >= 1)
-                       return true;
-       if(ca >= 1)
-               if(cb < 1)
-                       return false;
-
-       // first, normalize
-       f = max(ca, cb, 1);
-       ca /= f;
-       cb /= f;
-       f = max(sa, sb, 1);
-       sa /= f;
-       sb /= f;
-
-       // the more we're at the end of the match, the more take scores into account
-       f = bound(0, game_completion_ratio * autocvar_g_balance_teams_scorefactor, 1);
-       ca += (sa - ca) * f;
-       cb += (sb - cb) * f;
+       if (IS_REAL_CLIENT(player) && bots_would_leave)
+       {
+               num_players_team_a -= num_bots_team_a;
+               num_players_team_b -= num_bots_team_b;
+       }
+       if (!use_score)
+       {
+               return num_players_team_a == num_players_team_b;
+       }
+       if (num_players_team_a != num_players_team_b)
+       {
+               return false;
+       }
+       return score_team_a == score_team_b;
+}
 
-       return ca <= cb;
+int FindBestTeams(entity player, bool use_score)
+{
+       if (MUTATOR_CALLHOOK(FindBestTeams, player) == true)
+       {
+               return M_ARGV(1, float);
+       }
+       int team_bits = 0;
+       int previous_team = 0;
+       if (c1 >= 0)
+       {
+               team_bits = BIT(0);
+               previous_team = 1;
+       }
+       if (c2 >= 0)
+       {
+               if (previous_team == 0)
+               {
+                       team_bits = BIT(1);
+                       previous_team = 2;
+               }
+               else if (IsTeamSmallerThanTeam(2, previous_team, player, use_score))
+               {
+                       team_bits = BIT(1);
+                       previous_team = 2;
+               }
+               else if (IsTeamEqualToTeam(2, previous_team, player, use_score))
+               {
+                       team_bits |= BIT(1);
+                       previous_team = 2;
+               }
+       }
+       if (c3 >= 0)
+       {
+               if (previous_team == 0)
+               {
+                       team_bits = BIT(2);
+                       previous_team = 3;
+               }
+               else if (IsTeamSmallerThanTeam(3, previous_team, player, use_score))
+               {
+                       team_bits = BIT(2);
+                       previous_team = 3;
+               }
+               else if (IsTeamEqualToTeam(3, previous_team, player, use_score))
+               {
+                       team_bits |= BIT(2);
+                       previous_team = 3;
+               }
+       }
+       if (c4 >= 0)
+       {
+               if (previous_team == 0)
+               {
+                       team_bits = BIT(3);
+               }
+               else if (IsTeamSmallerThanTeam(4, previous_team, player, use_score))
+               {
+                       team_bits = BIT(3);
+               }
+               else if (IsTeamEqualToTeam(4, previous_team, player, use_score))
+               {
+                       team_bits |= BIT(3);
+               }
+       }
+       return team_bits;
 }
 
 // returns # of smallest team (1, 2, 3, 4)
 // NOTE: Assumes CheckAllowedTeams has already been called!
-float FindSmallestTeam(entity pl, float ignore_pl)
+int FindSmallestTeam(entity player, float ignore_player)
 {
-       int totalteams = 0;
-       int t = 1; // initialize with a random team?
-       if(c4 >= 0) t = 4;
-       if(c3 >= 0) t = 3;
-       if(c2 >= 0) t = 2;
-       if(c1 >= 0) t = 1;
-
-       // find out what teams are available
-       //CheckAllowedTeams();
-
-       // make sure there are at least 2 teams to join
-       if(c1 >= 0)
-               totalteams = totalteams + 1;
-       if(c2 >= 0)
-               totalteams = totalteams + 1;
-       if(c3 >= 0)
-               totalteams = totalteams + 1;
-       if(c4 >= 0)
-               totalteams = totalteams + 1;
-
-       if((autocvar_bot_vs_human || pl.team_forced > 0) && totalteams == 1)
-               totalteams += 1;
-
-       if(totalteams <= 1)
+       // count how many players are in each team
+       if (ignore_player)
        {
-               if(autocvar_g_campaign && pl && IS_REAL_CLIENT(pl))
-                       return 1; // special case for campaign and player joining
-               else if(totalteams == 1) // single team
-                       LOG_TRACEF("Only 1 team available for %s, you may need to fix your map", MapInfo_Type_ToString(MapInfo_CurrentGametype()));
-               else // no teams, major no no
-                       error(sprintf("No teams available for %s\n", MapInfo_Type_ToString(MapInfo_CurrentGametype())));
+               GetTeamCounts(player);
        }
-
-       // count how many players are in each team
-       if(ignore_pl)
-               GetTeamCounts(pl);
        else
+       {
                GetTeamCounts(NULL);
-
+       }
+       int team_bits = FindBestTeams(player, true);
+       if (team_bits == 0)
+       {
+               error(sprintf("No teams available for %s\n", MapInfo_Type_ToString(MapInfo_CurrentGametype())));
+       }
        RandomSelection_Init();
-
-       if(TeamSmallerEqThanTeam(1, t, pl))
-               t = 1;
-       if(TeamSmallerEqThanTeam(2, t, pl))
-               t = 2;
-       if(TeamSmallerEqThanTeam(3, t, pl))
-               t = 3;
-       if(TeamSmallerEqThanTeam(4, t, pl))
-               t = 4;
-
-       // now t is the minimum, or A minimum!
-       if(t == 1 || TeamSmallerEqThanTeam(1, t, pl))
+       if ((team_bits & BIT(0)) != 0)
+       {
                RandomSelection_AddFloat(1, 1, 1);
-       if(t == 2 || TeamSmallerEqThanTeam(2, t, pl))
+       }
+       if ((team_bits & BIT(1)) != 0)
+       {
                RandomSelection_AddFloat(2, 1, 1);
-       if(t == 3 || TeamSmallerEqThanTeam(3, t, pl))
+       }
+       if ((team_bits & BIT(2)) != 0)
+       {
                RandomSelection_AddFloat(3, 1, 1);
-       if(t == 4 || TeamSmallerEqThanTeam(4, t, pl))
+       }
+       if ((team_bits & BIT(3)) != 0)
+       {
                RandomSelection_AddFloat(4, 1, 1);
-
+       }
        return RandomSelection_chosen_float;
 }
 
-int JoinBestTeam(entity this, bool only_return_best, bool forcebestteam)
+int JoinBestTeam(entity this, bool only_return_best, bool force_best_team)
 {
-       float smallest, selectedteam;
-
        // don't join a team if we're not playing a team game
-       if(!teamplay)
+       if (!teamplay)
+       {
                return 0;
+       }
 
        // find out what teams are available
        CheckAllowedTeams(this);
 
+       int selected_team;
+
        // if we don't care what team he ends up on, put him on whatever team he entered as.
        // if he's not on a valid team, then let other code put him on the smallest team
-       if(!forcebestteam)
+       if (!force_best_team)
        {
                if(     c1 >= 0 && this.team == NUM_TEAM_1)
-                       selectedteam = this.team;
+                       selected_team = this.team;
                else if(c2 >= 0 && this.team == NUM_TEAM_2)
-                       selectedteam = this.team;
+                       selected_team = this.team;
                else if(c3 >= 0 && this.team == NUM_TEAM_3)
-                       selectedteam = this.team;
+                       selected_team = this.team;
                else if(c4 >= 0 && this.team == NUM_TEAM_4)
-                       selectedteam = this.team;
+                       selected_team = this.team;
                else
-                       selectedteam = -1;
+                       selected_team = -1;
 
-               if(selectedteam > 0)
+               if (selected_team > 0)
                {
-                       if(!only_return_best)
+                       if (!only_return_best)
                        {
-                               SetPlayerColors(this, selectedteam - 1);
+                               SetPlayerTeamSimple(this, selected_team);
 
                                // when JoinBestTeam is called by client.qc/ClientKill_Now_TeamChange the players team is -1 and thus skipped
                                // when JoinBestTeam is called by client.qc/ClientConnect the player_id is 0 the log attempt is rejected
                                LogTeamchange(this.playerid, this.team, 99);
                        }
-                       return selectedteam;
+                       return selected_team;
                }
                // otherwise end up on the smallest team (handled below)
        }
 
-       smallest = FindSmallestTeam(this, true);
-
-       if(!only_return_best && !this.bot_forced_team)
+       int best_team = FindSmallestTeam(this, true);
+       if (only_return_best || this.bot_forced_team)
        {
-               TeamchangeFrags(this);
-               if(smallest == 1)
-               {
-                       SetPlayerColors(this, NUM_TEAM_1 - 1);
-               }
-               else if(smallest == 2)
-               {
-                       SetPlayerColors(this, NUM_TEAM_2 - 1);
-               }
-               else if(smallest == 3)
-               {
-                       SetPlayerColors(this, NUM_TEAM_3 - 1);
-               }
-               else if(smallest == 4)
-               {
-                       SetPlayerColors(this, NUM_TEAM_4 - 1);
-               }
-               else
-               {
-                       error("smallest team: invalid team\n");
-               }
-
-               LogTeamchange(this.playerid, this.team, 2); // log auto join
-
-               if(!IS_DEAD(this))
-                       Damage(this, this, this, 100000, DEATH_TEAMCHANGE.m_id, this.origin, '0 0 0');
+               return best_team;
        }
-
-       return smallest;
+       best_team = Team_NumberToTeam(best_team);
+       if (best_team == -1)
+       {
+               error("JoinBestTeam: invalid team\n");
+       }
+       int old_team = Team_TeamToNumber(this.team);
+       TeamchangeFrags(this);
+       SetPlayerTeamSimple(this, best_team);
+       LogTeamchange(this.playerid, this.team, 2); // log auto join
+       if (!IS_BOT_CLIENT(this))
+       {
+               AutoBalanceBots(old_team, Team_TeamToNumber(best_team));
+       }
+       KillPlayerForTeamChange(this);
+       return best_team;
 }
 
-//void() ctf_playerchanged;
 void SV_ChangeTeam(entity this, float _color)
 {
-       float scolor, dcolor, steam, dteam; //, dbotcount, scount, dcount;
+       float source_color, destination_color, source_team, destination_team;
 
        // in normal deathmatch we can just apply the color and we're done
        if(!teamplay)
@@ -615,38 +923,23 @@ void SV_ChangeTeam(entity this, float _color)
        if(!teamplay)
                return;
 
-       scolor = this.clientcolors & 0x0F;
-       dcolor = _color & 0x0F;
-
-       if(scolor == NUM_TEAM_1 - 1)
-               steam = 1;
-       else if(scolor == NUM_TEAM_2 - 1)
-               steam = 2;
-       else if(scolor == NUM_TEAM_3 - 1)
-               steam = 3;
-       else // if(scolor == NUM_TEAM_4 - 1)
-               steam = 4;
-       if(dcolor == NUM_TEAM_1 - 1)
-               dteam = 1;
-       else if(dcolor == NUM_TEAM_2 - 1)
-               dteam = 2;
-       else if(dcolor == NUM_TEAM_3 - 1)
-               dteam = 3;
-       else // if(dcolor == NUM_TEAM_4 - 1)
-               dteam = 4;
+       source_color = this.clientcolors & 0x0F;
+       destination_color = _color & 0x0F;
+
+       source_team = Team_TeamToNumber(source_color + 1);
+       destination_team = Team_TeamToNumber(destination_color + 1);
 
        CheckAllowedTeams(this);
 
-       if(dteam == 1 && c1 < 0) dteam = 4;
-       if(dteam == 4 && c4 < 0) dteam = 3;
-       if(dteam == 3 && c3 < 0) dteam = 2;
-       if(dteam == 2 && c2 < 0) dteam = 1;
+       if (destination_team == 1 && c1 < 0) destination_team = 4;
+       if (destination_team == 4 && c4 < 0) destination_team = 3;
+       if (destination_team == 3 && c3 < 0) destination_team = 2;
+       if (destination_team == 2 && c2 < 0) destination_team = 1;
 
        // not changing teams
-       if(scolor == dcolor)
+       if (source_color == destination_color)
        {
-               //bprint("same team change\n");
-               SetPlayerTeam(this, dteam, steam, true);
+               SetPlayerTeam(this, destination_team, source_team, true);
                return;
        }
 
@@ -656,169 +949,102 @@ void SV_ChangeTeam(entity this, float _color)
        }
 
        // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
-       if(autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
+       if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
        {
                GetTeamCounts(this);
-               if(!TeamSmallerEqThanTeam(dteam, steam, this))
+               if ((BIT(destination_team - 1) & FindBestTeams(this, false)) == 0)
                {
                        Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
                        return;
                }
        }
-
-//     bprint("allow change teams from ", ftos(steam), " to ", ftos(dteam), "\n");
-
-       if(IS_PLAYER(this) && steam != dteam)
+       if(IS_PLAYER(this) && source_team != destination_team)
        {
                // reduce frags during a team change
                TeamchangeFrags(this);
        }
-
-       MUTATOR_CALLHOOK(Player_ChangeTeam, this, steam, dteam);
-
-       SetPlayerTeam(this, dteam, steam, !IS_CLIENT(this));
-
-       if(IS_PLAYER(this) && steam != dteam)
+       if (!SetPlayerTeam(this, destination_team, source_team, !IS_CLIENT(this)))
+       {
+               return;
+       }
+       AutoBalanceBots(source_team, destination_team);
+       if (!IS_PLAYER(this) || (source_team == destination_team))
        {
-               // kill player when changing teams
-               if(!IS_DEAD(this))
-                       Damage(this, this, this, 100000, DEATH_TEAMCHANGE.m_id, this.origin, '0 0 0');
+               return;
        }
+       KillPlayerForTeamChange(this);
 }
 
-void ShufflePlayerOutOfTeam (float source_team)
+void AutoBalanceBots(int source_team, int destination_team)
 {
-       float smallestteam, smallestteam_count, steam;
-       float lowest_bot_score, lowest_player_score;
-       entity lowest_bot, lowest_player, selected;
-
-       smallestteam = 0;
-       smallestteam_count = 999999999;
-
-       if(c1 >= 0 && c1 < smallestteam_count)
-       {
-               smallestteam = 1;
-               smallestteam_count = c1;
-       }
-       if(c2 >= 0 && c2 < smallestteam_count)
-       {
-               smallestteam = 2;
-               smallestteam_count = c2;
-       }
-       if(c3 >= 0 && c3 < smallestteam_count)
+       if ((source_team == -1) || (destination_team == -1))
        {
-               smallestteam = 3;
-               smallestteam_count = c3;
+               return;
        }
-       if(c4 >= 0 && c4 < smallestteam_count)
+       if (!autocvar_g_balance_teams ||
+               !autocvar_g_balance_teams_prevent_imbalance)
        {
-               smallestteam = 4;
-               smallestteam_count = c4;
-       }
-
-       if(!smallestteam)
-       {
-               bprint("warning: no smallest team\n");
                return;
        }
-
-       if(source_team == 1)
-               steam = NUM_TEAM_1;
-       else if(source_team == 2)
-               steam = NUM_TEAM_2;
-       else if(source_team == 3)
-               steam = NUM_TEAM_3;
-       else // if(source_team == 4)
-               steam = NUM_TEAM_4;
-
-       lowest_bot = NULL;
-       lowest_bot_score = 999999999;
-       lowest_player = NULL;
-       lowest_player_score = 999999999;
-
-       // find the lowest-scoring player & bot of that team
-       FOREACH_CLIENT(IS_PLAYER(it) && it.team == steam, {
-               if(it.isbot)
+       int num_players_source_team = 0;
+       int num_players_destination_team = 0;
+       entity lowest_bot_destination_team = NULL;
+       switch (source_team)
+       {
+               case 1:
                {
-                       if(it.totalfrags < lowest_bot_score)
-                       {
-                               lowest_bot = it;
-                               lowest_bot_score = it.totalfrags;
-                       }
+                       num_players_source_team = c1;
+                       break;
                }
-               else
+               case 2:
                {
-                       if(it.totalfrags < lowest_player_score)
-                       {
-                               lowest_player = it;
-                               lowest_player_score = it.totalfrags;
-                       }
+                       num_players_source_team = c2;
+                       break;
+               }
+               case 3:
+               {
+                       num_players_source_team = c3;
+                       break;
+               }
+               case 4:
+               {
+                       num_players_source_team = c4;
+                       break;
                }
-       });
-
-       // prefers to move a bot...
-       if(lowest_bot != NULL)
-               selected = lowest_bot;
-       // but it will move a player if it has to
-       else
-               selected = lowest_player;
-       // don't do anything if it couldn't find anyone
-       if(!selected)
-       {
-               bprint("warning: couldn't find a player to move from team\n");
-               return;
-       }
-
-       // smallest team gains a member
-       if(smallestteam == 1)
-       {
-               c1 = c1 + 1;
-       }
-       else if(smallestteam == 2)
-       {
-               c2 = c2 + 1;
-       }
-       else if(smallestteam == 3)
-       {
-               c3 = c3 + 1;
-       }
-       else if(smallestteam == 4)
-       {
-               c4 = c4 + 1;
-       }
-       else
-       {
-               bprint("warning: destination team invalid\n");
-               return;
-       }
-       // source team loses a member
-       if(source_team == 1)
-       {
-               c1 = c1 + 1;
-       }
-       else if(source_team == 2)
-       {
-               c2 = c2 + 2;
-       }
-       else if(source_team == 3)
-       {
-               c3 = c3 + 3;
        }
-       else if(source_team == 4)
+       switch (destination_team)
        {
-               c4 = c4 + 4;
+               case 1:
+               {
+                       num_players_destination_team = c1;
+                       lowest_bot_destination_team = lowest_bot_team1;
+                       break;
+               }
+               case 2:
+               {
+                       num_players_destination_team = c2;
+                       lowest_bot_destination_team = lowest_bot_team2;
+                       break;
+               }
+               case 3:
+               {
+                       num_players_destination_team = c3;
+                       lowest_bot_destination_team = lowest_bot_team3;
+                       break;
+               }
+               case 4:
+               {
+                       num_players_destination_team = c4;
+                       lowest_bot_destination_team = lowest_bot_team4;
+                       break;
+               }
        }
-       else
+       if ((num_players_destination_team <= num_players_source_team) ||
+               (lowest_bot_destination_team == NULL))
        {
-               bprint("warning: source team invalid\n");
                return;
        }
-
-       // move the player to the new team
-       TeamchangeFrags(selected);
-       SetPlayerTeam(selected, smallestteam, source_team, false);
-
-       if(!IS_DEAD(selected))
-               Damage(selected, selected, selected, 100000, DEATH_AUTOTEAMCHANGE.m_id, selected.origin, '0 0 0');
-       Send_Notification(NOTIF_ONE, selected, MSG_CENTER, CENTER_DEATH_SELF_AUTOTEAMCHANGE, selected.team);
+       SetPlayerTeamSimple(lowest_bot_destination_team,
+               Team_NumberToTeam(source_team));
+       KillPlayerForTeamChange(lowest_bot_destination_team);
 }
index 127ac7a6d30caffc887e9571c40104148813eadb..5311d4cb01d54d37c056333feb3a566e518296d6 100644 (file)
@@ -3,10 +3,29 @@
 string cache_mutatormsg;
 string cache_lastmutatormsg;
 
-// client counts for each team
-//float c1, c2, c3, c4;
-// # of bots on those teams
-float cb1, cb2, cb3, cb4;
+// The following variables are used for balancing. They are not updated
+// automatically. You need to call CheckAllowedTeams and GetTeamCounts to get
+// proper values.
+
+// These four have 2 different states. If they are equal to -1, it means that
+// the player can't join the team. Zero or positive value means that player can
+// join the team and means the number of players on that team.
+float c1;
+float c2;
+float c3;
+float c4;
+float num_bots_team1; ///< Number of bots in the first team.
+float num_bots_team2; ///< Number of bots in the second team.
+float num_bots_team3; ///< Number of bots in the third team.
+float num_bots_team4; ///< Number of bots in the fourth team.
+entity lowest_human_team1; ///< Human with the lowest score in the first team.
+entity lowest_human_team2; ///< Human with the lowest score in the second team.
+entity lowest_human_team3; ///< Human with the lowest score in the third team.
+entity lowest_human_team4; ///< Human with the lowest score in the fourth team.
+entity lowest_bot_team1; ///< Bot with the lowest score in the first team.
+entity lowest_bot_team2; ///< Bot with the lowest score in the second team.
+entity lowest_bot_team3; ///< Bot with the lowest score in the third team.
+entity lowest_bot_team4; ///< Bot with the lowest score in the fourth team.
 
 int redowned, blueowned, yellowowned, pinkowned;
 
@@ -26,12 +45,30 @@ string GetClientVersionMessage(entity this);
 
 string getwelcomemessage(entity this);
 
-void SetPlayerColors(entity pl, float _color);
+void SetPlayerColors(entity player, float _color);
 
-void SetPlayerTeam(entity pl, float t, float s, float noprint);
+/// \brief Kills player as a result of team change.
+/// \param[in,out] player Player to kill.
+/// \return No return.
+void KillPlayerForTeamChange(entity player);
+
+/// \brief Sets the team of the player.
+/// \param[in,out] player Player to adjust.
+/// \param[in] team_num Team number to set. See TEAM_NUM constants.
+/// \return True if team switch was successful, false otherwise.
+bool SetPlayerTeamSimple(entity player, int team_num);
+
+/// \brief Sets the team of the player.
+/// \param[in,out] player Player to adjust.
+/// \param[in] destination_team Team to set.
+/// \param[in] source_team Previous team of the player.
+/// \param[in] no_print Whether to print this event to players' console.
+/// \return True if team switch was successful, false otherwise.
+bool SetPlayerTeam(entity player, int destination_team, int source_team,
+       bool no_print);
 
 // set c1...c4 to show what teams are allowed
-void CheckAllowedTeams (entity for_whom);
+void CheckAllowedTeams(entity for_whom);
 
 float PlayerValue(entity p);
 
@@ -39,16 +76,47 @@ float PlayerValue(entity p);
 // teams that are allowed will now have their player counts stored in c1...c4
 void GetTeamCounts(entity ignore);
 
-float TeamSmallerEqThanTeam(float ta, float tb, entity e);
+/// \brief Returns whether one team is smaller than the other.
+/// \param[in] team_a First team.
+/// \param[in] team_b Second team.
+/// \param[in] player Player to check.
+/// \param[in] use_score Whether to take into account team scores.
+/// \return True if first team is smaller than the second one, false otherwise.
+/// \note This function assumes that CheckAllowedTeams and GetTeamCounts have
+/// been called.
+bool IsTeamSmallerThanTeam(int team_a, int team_b, entity player,
+       bool use_score);
+
+/// \brief Returns whether one team is equal to the other.
+/// \param[in] team_a First team.
+/// \param[in] team_b Second team.
+/// \param[in] player Player to check.
+/// \param[in] use_score Whether to take into account team scores.
+/// \return True if first team is equal to the second one, false otherwise.
+/// \note This function assumes that CheckAllowedTeams and GetTeamCounts have
+/// been called.
+bool IsTeamEqualToTeam(int team_a, int team_b, entity player, bool use_score);
+
+/// \brief Returns the bitmask of the best teams for the player to join.
+/// \param[in] player Player to check.
+/// \param[in] use_score Whether to take into account team scores.
+/// \return Bitmask of the best teams for the player to join.
+/// \note This function assumes that CheckAllowedTeams and GetTeamCounts have
+/// been called.
+int FindBestTeams(entity player, bool use_score);
 
 // returns # of smallest team (1, 2, 3, 4)
 // NOTE: Assumes CheckAllowedTeams has already been called!
-float FindSmallestTeam(entity pl, float ignore_pl);
-
-int JoinBestTeam(entity this, bool only_return_best, bool forcebestteam);
+int FindSmallestTeam(entity player, float ignore_player);
 
-//void() ctf_playerchanged;
+int JoinBestTeam(entity this, bool only_return_best, bool force_best_team);
 
-void ShufflePlayerOutOfTeam (float source_team);
+/// \brief Auto balances bots in teams after the player has changed team.
+/// \param[in] source_team Previous team of the player (1, 2, 3, 4).
+/// \param[in] destination_team Current team of the player (1, 2, 3, 4).
+/// \return No return.
+/// \note This function assumes that CheckAllowedTeams and GetTeamCounts have
+/// been called.
+void AutoBalanceBots(int source_team, int destination_team);
 
 void setcolor(entity this, int clr);