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