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