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