]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/teamplay.qc
SetPlayerTeam now returns bool.
[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 void TeamchangeFrags(entity e)
19 {
20         PlayerScore_Clear(e);
21 }
22
23 void LogTeamchange(float player_id, float team_number, float type)
24 {
25         if(!autocvar_sv_eventlog)
26                 return;
27
28         if(player_id < 1)
29                 return;
30
31         GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
32 }
33
34 void default_delayedinit(entity this)
35 {
36         if(!scores_initialized)
37                 ScoreRules_generic();
38 }
39
40 void ActivateTeamplay()
41 {
42         serverflags |= SERVERFLAG_TEAMPLAY;
43         teamplay = 1;
44         cvar_set("teamplay", "2");  // DP needs this for sending proper getstatus replies.
45 }
46
47 void InitGameplayMode()
48 {
49         VoteReset();
50
51         // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
52         get_mi_min_max(1);
53         world.mins = mi_min;
54         world.maxs = mi_max;
55         // currently, NetRadiant's limit is 131072 qu for each side
56         // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
57         // set the distance according to map size but don't go over the limit to avoid issues with float precision
58         // in case somebody makes extremely large maps
59         max_shot_distance = min(230000, vlen(world.maxs - world.mins));
60
61         MapInfo_LoadMapSettings(mapname);
62         serverflags &= ~SERVERFLAG_TEAMPLAY;
63         teamplay = 0;
64         cvar_set("teamplay", "0");  // DP needs this for sending proper getstatus replies.
65
66         if (!cvar_value_issafe(world.fog))
67         {
68                 LOG_INFO("The current map contains a potentially harmful fog setting, ignored\n");
69                 world.fog = string_null;
70         }
71         if(MapInfo_Map_fog != "")
72                 if(MapInfo_Map_fog == "none")
73                         world.fog = string_null;
74                 else
75                         world.fog = strzone(MapInfo_Map_fog);
76         clientstuff = strzone(MapInfo_Map_clientstuff);
77
78         MapInfo_ClearTemps();
79
80         gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
81
82         cache_mutatormsg = strzone("");
83         cache_lastmutatormsg = strzone("");
84
85         InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
86 }
87
88 string GetClientVersionMessage(entity this)
89 {
90         if (CS(this).version_mismatch) {
91                 if(CS(this).version < autocvar_gameversion) {
92                         return strcat("This is Xonotic ", autocvar_g_xonoticversion,
93                                 "\n^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8");
94                 } else {
95                         return strcat("This is Xonotic ", autocvar_g_xonoticversion,
96                                 "\n^3This server is using an outdated Xonotic version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8");
97                 }
98         } else {
99                 return strcat("Welcome to Xonotic ", autocvar_g_xonoticversion);
100         }
101 }
102
103 string getwelcomemessage(entity this)
104 {
105         MUTATOR_CALLHOOK(BuildMutatorsPrettyString, "");
106         string modifications = M_ARGV(0, string);
107
108         if(g_weaponarena)
109         {
110                 if(g_weaponarena_random)
111                         modifications = strcat(modifications, ", ", ftos(g_weaponarena_random), " of ", g_weaponarena_list, " Arena");
112                 else
113                         modifications = strcat(modifications, ", ", g_weaponarena_list, " Arena");
114         }
115         else if(cvar("g_balance_blaster_weaponstartoverride") == 0)
116                 modifications = strcat(modifications, ", No start weapons");
117         if(cvar("sv_gravity") < stof(cvar_defstring("sv_gravity")))
118                 modifications = strcat(modifications, ", Low gravity");
119         if(g_weapon_stay && !g_cts)
120                 modifications = strcat(modifications, ", Weapons stay");
121         if(g_jetpack)
122                 modifications = strcat(modifications, ", Jet pack");
123         if(autocvar_g_powerups == 0)
124                 modifications = strcat(modifications, ", No powerups");
125         if(autocvar_g_powerups > 0)
126                 modifications = strcat(modifications, ", Powerups");
127         modifications = substring(modifications, 2, strlen(modifications) - 2);
128
129         string versionmessage = GetClientVersionMessage(this);
130         string s = strcat(versionmessage, "^8\n^8\nmatch type is ^1", gamemode_name, "^8\n");
131
132         if(modifications != "")
133                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
134
135         if(cache_lastmutatormsg != autocvar_g_mutatormsg)
136         {
137                 if(cache_lastmutatormsg)
138                         strunzone(cache_lastmutatormsg);
139                 if(cache_mutatormsg)
140                         strunzone(cache_mutatormsg);
141                 cache_lastmutatormsg = strzone(autocvar_g_mutatormsg);
142                 cache_mutatormsg = strzone(cache_lastmutatormsg);
143         }
144
145         if (cache_mutatormsg != "") {
146                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
147         }
148
149         string mutator_msg = "";
150         MUTATOR_CALLHOOK(BuildGameplayTipsString, mutator_msg);
151         mutator_msg = M_ARGV(0, string);
152
153         s = strcat(s, mutator_msg); // trust that the mutator will do proper formatting
154
155         string motd = autocvar_sv_motd;
156         if (motd != "") {
157                 s = strcat(s, "\n\n^8MOTD: ^7", strreplace("\\n", "\n", motd));
158         }
159         return s;
160 }
161
162 void setcolor(entity this, int clr)
163 {
164 #if 0
165         this.clientcolors = clr;
166         this.team = (clr & 15) + 1;
167 #else
168         builtin_setcolor(this, clr);
169 #endif
170 }
171
172 void SetPlayerColors(entity player, float _color)
173 {
174         float pants = _color & 0x0F;
175         float shirt = _color & 0xF0;
176         if (teamplay)
177         {
178                 setcolor(player, 16 * pants + pants);
179         }
180         else
181         {
182                 setcolor(player, shirt + pants);
183         }
184 }
185
186 bool SetPlayerTeamSimple(entity player, int teamnum)
187 {
188         if (player.team == teamnum)
189         {
190                 // This is important when players join the game and one of their color
191                 // matches the team color while other doesn't. For example [BOT]Lion.
192                 SetPlayerColors(player, teamnum - 1);
193                 return true;
194         }
195         if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, Team_TeamToNumber(
196                 player.team), Team_TeamToNumber(teamnum)) == true)
197         {
198                 // Mutator has blocked team change.
199                 return false;
200         }
201         int oldteam = player.team;
202         SetPlayerColors(player, teamnum - 1);
203         MUTATOR_CALLHOOK(Player_ChangedTeam, player, oldteam, player.team);
204         return true;
205 }
206
207 bool SetPlayerTeam(entity player, int destinationteam, int sourceteam, bool noprint)
208 {
209         int teamnum = Team_NumberToTeam(destinationteam);
210         if (!SetPlayerTeamSimple(player, teamnum))
211         {
212                 return false;
213         }
214         LogTeamchange(player.playerid, player.team, 3);  // log manual team join
215         if (noprint)
216         {
217                 return true;
218         }
219         bprint(playername(player, false), "^7 has changed from ", Team_NumberToColoredFullName(sourceteam), "^7 to ", Team_NumberToColoredFullName(destinationteam), "\n");
220         return true;
221 }
222
223 // set c1...c4 to show what teams are allowed
224 void CheckAllowedTeams (entity for_whom)
225 {
226         int teams_mask = 0;
227
228         c1 = c2 = c3 = c4 = -1;
229         numbotsteam1 = numbotsteam2 = numbotsteam3 = numbotsteam4 = 0;
230
231         string teament_name = string_null;
232
233         bool mutator_returnvalue = MUTATOR_CALLHOOK(CheckAllowedTeams, teams_mask, teament_name, for_whom);
234         teams_mask = M_ARGV(0, float);
235         teament_name = M_ARGV(1, string);
236
237         if(!mutator_returnvalue)
238         {
239                 if(teams_mask & BIT(0)) c1 = 0;
240                 if(teams_mask & BIT(1)) c2 = 0;
241                 if(teams_mask & BIT(2)) c3 = 0;
242                 if(teams_mask & BIT(3)) c4 = 0;
243         }
244
245         // find out what teams are allowed if necessary
246         if(teament_name)
247         {
248                 entity head = find(NULL, classname, teament_name);
249                 while(head)
250                 {
251                         switch(head.team)
252                         {
253                                 case NUM_TEAM_1: c1 = 0; break;
254                                 case NUM_TEAM_2: c2 = 0; break;
255                                 case NUM_TEAM_3: c3 = 0; break;
256                                 case NUM_TEAM_4: c4 = 0; break;
257                         }
258
259                         head = find(head, classname, teament_name);
260                 }
261         }
262
263         // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
264         if(AvailableTeams() == 2)
265         if(autocvar_bot_vs_human && for_whom)
266         {
267                 if(autocvar_bot_vs_human > 0)
268                 {
269                         // find last team available
270
271                         if(IS_BOT_CLIENT(for_whom))
272                         {
273                                 if(c4 >= 0) { c3 = c2 = c1 = -1; }
274                                 else if(c3 >= 0) { c4 = c2 = c1 = -1; }
275                                 else { c4 = c3 = c1 = -1; }
276                                 // no further cases, we know at least 2 teams exist
277                         }
278                         else
279                         {
280                                 if(c1 >= 0) { c2 = c3 = c4 = -1; }
281                                 else if(c2 >= 0) { c1 = c3 = c4 = -1; }
282                                 else { c1 = c2 = c4 = -1; }
283                                 // no further cases, bots have one of the teams
284                         }
285                 }
286                 else
287                 {
288                         // find first team available
289
290                         if(IS_BOT_CLIENT(for_whom))
291                         {
292                                 if(c1 >= 0) { c2 = c3 = c4 = -1; }
293                                 else if(c2 >= 0) { c1 = c3 = c4 = -1; }
294                                 else { c1 = c2 = c4 = -1; }
295                                 // no further cases, we know at least 2 teams exist
296                         }
297                         else
298                         {
299                                 if(c4 >= 0) { c3 = c2 = c1 = -1; }
300                                 else if(c3 >= 0) { c4 = c2 = c1 = -1; }
301                                 else { c4 = c3 = c1 = -1; }
302                                 // no further cases, bots have one of the teams
303                         }
304                 }
305         }
306
307         if(!for_whom)
308                 return;
309
310         // if player has a forced team, ONLY allow that one
311         if(for_whom.team_forced == NUM_TEAM_1 && c1 >= 0)
312                 c2 = c3 = c4 = -1;
313         else if(for_whom.team_forced == NUM_TEAM_2 && c2 >= 0)
314                 c1 = c3 = c4 = -1;
315         else if(for_whom.team_forced == NUM_TEAM_3 && c3 >= 0)
316                 c1 = c2 = c4 = -1;
317         else if(for_whom.team_forced == NUM_TEAM_4 && c4 >= 0)
318                 c1 = c2 = c3 = -1;
319 }
320
321 float PlayerValue(entity p)
322 {
323         return 1;
324         // FIXME: it always returns 1...
325 }
326
327 // c1...c4 should be set to -1 (not allowed) or 0 (allowed).
328 // teams that are allowed will now have their player counts stored in c1...c4
329 void GetTeamCounts(entity ignore)
330 {
331         if (MUTATOR_CALLHOOK(GetTeamCounts) == true)
332         {
333                 if (c1 >= 0)
334                 {
335                         MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_1, ignore, c1, numbotsteam1,
336                                 lowestplayerteam1, lowestbotteam1);
337                         c1 = M_ARGV(2, float);
338                         numbotsteam1 = M_ARGV(3, float);
339                         lowestplayerteam1 = M_ARGV(4, entity);
340                         lowestbotteam1 = M_ARGV(5, entity);
341                 }
342                 if (c2 >= 0)
343                 {
344                         MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_2, ignore, c2, numbotsteam2,
345                                 lowestplayerteam2, lowestbotteam2);
346                         c2 = M_ARGV(2, float);
347                         numbotsteam2 = M_ARGV(3, float);
348                         lowestplayerteam2 = M_ARGV(4, entity);
349                         lowestbotteam2 = M_ARGV(5, entity);
350                 }
351                 if (c3 >= 0)
352                 {
353                         MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_3, ignore, c3, numbotsteam3,
354                                 lowestplayerteam3, lowestbotteam3);
355                         c3 = M_ARGV(2, float);
356                         numbotsteam3 = M_ARGV(3, float);
357                         lowestplayerteam3 = M_ARGV(4, entity);
358                         lowestbotteam3 = M_ARGV(5, entity);
359                 }
360                 if (c4 >= 0)
361                 {
362                         MUTATOR_CALLHOOK(GetTeamCount, NUM_TEAM_4, ignore, c4, numbotsteam4,
363                                 lowestplayerteam4, lowestbotteam4);
364                         c4 = M_ARGV(2, float);
365                         numbotsteam4 = M_ARGV(3, float);
366                         lowestplayerteam4 = M_ARGV(4, entity);
367                         lowestbotteam4 = M_ARGV(5, entity);
368                 }
369         }
370         else
371         {
372                 float value, bvalue;
373                 // now count how many players are on each team already
374                 float lowestplayerscore1 = FLOAT_MAX;
375                 float lowestbotscore1 = FLOAT_MAX;
376                 float lowestplayerscore2 = FLOAT_MAX;
377                 float lowestbotscore2 = FLOAT_MAX;
378                 float lowestplayerscore3 = FLOAT_MAX;
379                 float lowestbotscore3 = FLOAT_MAX;
380                 float lowestplayerscore4 = FLOAT_MAX;
381                 float lowestbotscore4 = FLOAT_MAX;
382                 FOREACH_CLIENT(true, LAMBDA(
383                         float t;
384                         if (IS_PLAYER(it) || it.caplayer)
385                         {
386                                 t = it.team;
387                         }
388                         else if (it.team_forced > 0)
389                         {
390                                 t = it.team_forced; // reserve the spot
391                         }
392                         else
393                         {
394                                 continue;
395                         }
396                         if (it == ignore)
397                         {
398                                 continue;
399                         }
400                         value = PlayerValue(it);
401                         if (IS_BOT_CLIENT(it))
402                         {
403                                 bvalue = value;
404                         }
405                         else
406                         {
407                                 bvalue = 0;
408                         }
409                         if (value == 0)
410                         {
411                                 continue;
412                         }
413                         switch (t)
414                         {
415                                 case NUM_TEAM_1:
416                                 {
417                                         if (c1 < 0)
418                                         {
419                                                 break;
420                                         }
421                                         c1 += value;
422                                         numbotsteam1 += bvalue;
423                                         float tempscore = PlayerScore_Get(it, SP_SCORE);
424                                         if (!bvalue)
425                                         {
426                                                 if (tempscore < lowestplayerscore1)
427                                                 {
428                                                         lowestplayerteam1 = it;
429                                                         lowestplayerscore1 = tempscore;
430                                                 }
431                                                 break;
432                                         }
433                                         if (tempscore < lowestbotscore1)
434                                         {
435                                                 lowestbotteam1 = it;
436                                                 lowestbotscore1 = tempscore;
437                                         }
438                                         break;
439                                 }
440                                 case NUM_TEAM_2:
441                                 {
442                                         if (c2 < 0)
443                                         {
444                                                 break;
445                                         }
446                                         c2 += value;
447                                         numbotsteam2 += bvalue;
448                                         float tempscore = PlayerScore_Get(it, SP_SCORE);
449                                         if (!bvalue)
450                                         {
451                                                 if (tempscore < lowestplayerscore2)
452                                                 {
453                                                         lowestplayerteam2 = it;
454                                                         lowestplayerscore2 = tempscore;
455                                                 }
456                                                 break;
457                                         }
458                                         if (tempscore < lowestbotscore2)
459                                         {
460                                                 lowestbotteam2 = it;
461                                                 lowestbotscore2 = tempscore;
462                                         }
463                                         break;
464                                 }
465                                 case NUM_TEAM_3:
466                                 {
467                                         if (c3 < 0)
468                                         {
469                                                 break;
470                                         }
471                                         c3 += value;
472                                         numbotsteam3 += bvalue;
473                                         float tempscore = PlayerScore_Get(it, SP_SCORE);
474                                         if (!bvalue)
475                                         {
476                                                 if (tempscore < lowestplayerscore3)
477                                                 {
478                                                         lowestplayerteam3 = it;
479                                                         lowestplayerscore3 = tempscore;
480                                                 }
481                                                 break;
482                                         }
483                                         if (tempscore < lowestbotscore3)
484                                         {
485                                                 lowestbotteam3 = it;
486                                                 lowestbotscore3 = tempscore;
487                                         }
488                                         break;
489                                 }
490                                 case NUM_TEAM_4:
491                                 {
492                                         if (c4 < 0)
493                                         {
494                                                 break;
495                                         }
496                                         c4 += value;
497                                         numbotsteam4 += bvalue;
498                                         float tempscore = PlayerScore_Get(it, SP_SCORE);
499                                         if (!bvalue)
500                                         {
501                                                 if (tempscore < lowestplayerscore4)
502                                                 {
503                                                         lowestplayerteam4 = it;
504                                                         lowestplayerscore4 = tempscore;
505                                                 }
506                                                 break;
507                                         }
508                                         if (tempscore < lowestbotscore4)
509                                         {
510                                                 lowestbotteam4 = it;
511                                                 lowestbotscore4 = tempscore;
512                                         }
513                                         break;
514                                 }
515                         }
516                 ));
517         }
518
519         // if the player who has a forced team has not joined yet, reserve the spot
520         if(autocvar_g_campaign)
521         {
522                 switch(autocvar_g_campaign_forceteam)
523                 {
524                         case 1: if(c1 == numbotsteam1) ++c1; break;
525                         case 2: if(c2 == numbotsteam2) ++c2; break;
526                         case 3: if(c3 == numbotsteam3) ++c3; break;
527                         case 4: if(c4 == numbotsteam4) ++c4; break;
528                 }
529         }
530 }
531
532 bool IsTeamSmallerThanTeam(int teama, int teamb, entity e, bool usescore)
533 {
534         // equal
535         if (teama == teamb)
536         {
537                 return false;
538         }
539         // we assume that CheckAllowedTeams and GetTeamCounts have already been called
540         float numplayersteama = -1, numplayersteamb = -1;
541         float numbotsteama = 0, numbotsteamb = 0;
542         float scoreteama = 0, scoreteamb = 0;
543
544         switch (teama)
545         {
546                 case 1: numplayersteama = c1; numbotsteama = numbotsteam1; scoreteama = team1_score; break;
547                 case 2: numplayersteama = c2; numbotsteama = numbotsteam2; scoreteama = team2_score; break;
548                 case 3: numplayersteama = c3; numbotsteama = numbotsteam3; scoreteama = team3_score; break;
549                 case 4: numplayersteama = c4; numbotsteama = numbotsteam4; scoreteama = team4_score; break;
550         }
551         switch (teamb)
552         {
553                 case 1: numplayersteamb = c1; numbotsteamb = numbotsteam1; scoreteamb = team1_score; break;
554                 case 2: numplayersteamb = c2; numbotsteamb = numbotsteam2; scoreteamb = team2_score; break;
555                 case 3: numplayersteamb = c3; numbotsteamb = numbotsteam3; scoreteamb = team3_score; break;
556                 case 4: numplayersteamb = c4; numbotsteamb = numbotsteam4; scoreteamb = team4_score; break;
557         }
558
559         // invalid
560         if (numplayersteama < 0 || numplayersteamb < 0)
561                 return false;
562
563         if ((IS_REAL_CLIENT(e) && bots_would_leave))
564         {
565                 numplayersteama -= numbotsteama;
566                 numplayersteamb -= numbotsteamb;
567         }
568         if (!usescore)
569         {
570                 return numplayersteama < numplayersteamb;
571         }
572         if (numplayersteama < numplayersteamb)
573         {
574                 return true;
575         }
576         if (numplayersteama > numplayersteamb)
577         {
578                 return false;
579         }
580         return scoreteama < scoreteamb; 
581 }
582
583 bool IsTeamEqualToTeam(int teama, int teamb, entity e, bool usescore)
584 {
585         // equal
586         if (teama == teamb)
587         {
588                 return true;
589         }
590         // we assume that CheckAllowedTeams and GetTeamCounts have already been called
591         float numplayersteama = -1, numplayersteamb = -1;
592         float numbotsteama = 0, numbotsteamb = 0;
593         float scoreteama = 0, scoreteamb = 0;
594
595         switch (teama)
596         {
597                 case 1: numplayersteama = c1; numbotsteama = numbotsteam1; scoreteama = team1_score; break;
598                 case 2: numplayersteama = c2; numbotsteama = numbotsteam2; scoreteama = team2_score; break;
599                 case 3: numplayersteama = c3; numbotsteama = numbotsteam3; scoreteama = team3_score; break;
600                 case 4: numplayersteama = c4; numbotsteama = numbotsteam4; scoreteama = team4_score; break;
601         }
602         switch (teamb)
603         {
604                 case 1: numplayersteamb = c1; numbotsteamb = numbotsteam1; scoreteamb = team1_score; break;
605                 case 2: numplayersteamb = c2; numbotsteamb = numbotsteam2; scoreteamb = team2_score; break;
606                 case 3: numplayersteamb = c3; numbotsteamb = numbotsteam3; scoreteamb = team3_score; break;
607                 case 4: numplayersteamb = c4; numbotsteamb = numbotsteam4; scoreteamb = team4_score; break;
608         }
609
610         // invalid
611         if (numplayersteama < 0 || numplayersteamb < 0)
612                 return false;
613
614         if ((IS_REAL_CLIENT(e) && bots_would_leave))
615         {
616                 numplayersteama -= numbotsteama;
617                 numplayersteamb -= numbotsteamb;
618         }
619         if (!usescore)
620         {
621                 return numplayersteama == numplayersteamb;
622         }
623         if (numplayersteama < numplayersteamb)
624         {
625                 return false;
626         }
627         if (numplayersteama > numplayersteamb)
628         {
629                 return false;
630         }
631         return scoreteama == scoreteamb;        
632 }
633
634 int FindBestTeams(entity player, bool usescore)
635 {
636         if (MUTATOR_CALLHOOK(FindBestTeams, player) == true)
637         {
638                 return M_ARGV(1, float);
639         }
640         int teambits = 0;
641         int previousteam = 0;
642         if (c1 >= 0)
643         {
644                 teambits = BIT(0);
645                 previousteam = 1;
646         }
647         if (c2 >= 0)
648         {
649                 if (previousteam == 0)
650                 {
651                         teambits = BIT(1);
652                         previousteam = 2;
653                 }
654                 else if (IsTeamSmallerThanTeam(2, previousteam, player, usescore))
655                 {
656                         teambits = BIT(1);
657                         previousteam = 2;
658                 }
659                 else if (IsTeamEqualToTeam(2, previousteam, player, usescore))
660                 {
661                         teambits |= BIT(1);
662                         previousteam = 2;
663                 }
664         }
665         if (c3 >= 0)
666         {
667                 if (previousteam == 0)
668                 {
669                         teambits = BIT(2);
670                         previousteam = 3;
671                 }
672                 else if (IsTeamSmallerThanTeam(3, previousteam, player, usescore))
673                 {
674                         teambits = BIT(2);
675                         previousteam = 3;
676                 }
677                 else if (IsTeamEqualToTeam(3, previousteam, player, usescore))
678                 {
679                         teambits |= BIT(2);
680                         previousteam = 3;
681                 }
682         }
683         if (c4 >= 0)
684         {
685                 if (previousteam == 0)
686                 {
687                         teambits = BIT(3);
688                 }
689                 else if (IsTeamSmallerThanTeam(4, previousteam, player, usescore))
690                 {
691                         teambits = BIT(3);
692                 }
693                 else if (IsTeamEqualToTeam(4, previousteam, player, usescore))
694                 {
695                         teambits |= BIT(3);
696                 }
697         }
698         return teambits;
699 }
700
701 // returns # of smallest team (1, 2, 3, 4)
702 // NOTE: Assumes CheckAllowedTeams has already been called!
703 float FindSmallestTeam(entity player, float ignore_player)
704 {
705         // count how many players are in each team
706         if (ignore_player)
707         {
708                 GetTeamCounts(player);
709         }
710         else
711         {
712                 GetTeamCounts(NULL);
713         }
714         int teambits = FindBestTeams(player, true);
715         if (teambits == 0)
716         {
717                 error(sprintf("No teams available for %s\n", MapInfo_Type_ToString(MapInfo_CurrentGametype())));
718         }
719         RandomSelection_Init();
720         if ((teambits & BIT(0)) != 0)
721         {
722                 RandomSelection_AddFloat(1, 1, 1);
723         }
724         if ((teambits & BIT(1)) != 0)
725         {
726                 RandomSelection_AddFloat(2, 1, 1);
727         }
728         if ((teambits & BIT(2)) != 0)
729         {
730                 RandomSelection_AddFloat(3, 1, 1);
731         }
732         if ((teambits & BIT(3)) != 0)
733         {
734                 RandomSelection_AddFloat(4, 1, 1);
735         }
736         return RandomSelection_chosen_float;
737 }
738
739 int JoinBestTeam(entity this, bool only_return_best, bool forcebestteam)
740 {
741         // don't join a team if we're not playing a team game
742         if (!teamplay)
743         {
744                 return 0;
745         }
746
747         // find out what teams are available
748         CheckAllowedTeams(this);
749
750         float selectedteam;
751
752         // if we don't care what team he ends up on, put him on whatever team he entered as.
753         // if he's not on a valid team, then let other code put him on the smallest team
754         if (!forcebestteam)
755         {
756                 if(     c1 >= 0 && this.team == NUM_TEAM_1)
757                         selectedteam = this.team;
758                 else if(c2 >= 0 && this.team == NUM_TEAM_2)
759                         selectedteam = this.team;
760                 else if(c3 >= 0 && this.team == NUM_TEAM_3)
761                         selectedteam = this.team;
762                 else if(c4 >= 0 && this.team == NUM_TEAM_4)
763                         selectedteam = this.team;
764                 else
765                         selectedteam = -1;
766
767                 if (selectedteam > 0)
768                 {
769                         if (!only_return_best)
770                         {
771                                 SetPlayerTeamSimple(this, selectedteam);
772
773                                 // when JoinBestTeam is called by client.qc/ClientKill_Now_TeamChange the players team is -1 and thus skipped
774                                 // when JoinBestTeam is called by client.qc/ClientConnect the player_id is 0 the log attempt is rejected
775                                 LogTeamchange(this.playerid, this.team, 99);
776                         }
777                         return selectedteam;
778                 }
779                 // otherwise end up on the smallest team (handled below)
780         }
781
782         float bestteam = FindSmallestTeam(this, true);
783         if (only_return_best || this.bot_forced_team)
784         {
785                 return bestteam;
786         }
787         bestteam = Team_NumberToTeam(bestteam);
788         if (bestteam == -1)
789         {
790                 error("JoinBestTeam: invalid team\n");
791         }
792         int oldteam = Team_TeamToNumber(this.team);
793         TeamchangeFrags(this);
794         SetPlayerTeamSimple(this, bestteam);
795         LogTeamchange(this.playerid, this.team, 2); // log auto join
796         if (!IS_BOT_CLIENT(this))
797         {
798                 AutoBalanceBots(oldteam, Team_TeamToNumber(bestteam));
799         }
800         if (!IS_DEAD(this) && (MUTATOR_CALLHOOK(Player_ChangeTeamKill, this) ==
801                 false))
802         {
803                 Damage(this, this, this, 100000, DEATH_TEAMCHANGE.m_id, this.origin, '0 0 0');
804         }
805         return bestteam;
806 }
807
808 void SV_ChangeTeam(entity this, float _color)
809 {
810         float sourcecolor, destinationcolor, sourceteam, destinationteam;
811
812         // in normal deathmatch we can just apply the color and we're done
813         if(!teamplay)
814                 SetPlayerColors(this, _color);
815
816         if(!IS_CLIENT(this))
817         {
818                 // since this is an engine function, and gamecode doesn't have any calls earlier than this, do the connecting message here
819                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_CONNECTING, this.netname);
820                 return;
821         }
822
823         if(!teamplay)
824                 return;
825
826         sourcecolor = this.clientcolors & 0x0F;
827         destinationcolor = _color & 0x0F;
828
829         sourceteam = Team_TeamToNumber(sourcecolor + 1);
830         destinationteam = Team_TeamToNumber(destinationcolor + 1);
831         
832         CheckAllowedTeams(this);
833
834         if (destinationteam == 1 && c1 < 0) destinationteam = 4;
835         if (destinationteam == 4 && c4 < 0) destinationteam = 3;
836         if (destinationteam == 3 && c3 < 0) destinationteam = 2;
837         if (destinationteam == 2 && c2 < 0) destinationteam = 1;
838
839         // not changing teams
840         if (sourcecolor == destinationcolor)
841         {
842                 SetPlayerTeam(this, destinationteam, sourceteam, true);
843                 return;
844         }
845
846         if((autocvar_g_campaign) || (autocvar_g_changeteam_banned && CS(this).wasplayer)) {
847                 Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_NOTALLOWED);
848                 return; // changing teams is not allowed
849         }
850
851         // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
852         if (autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
853         {
854                 GetTeamCounts(this);
855                 if ((BIT(destinationteam - 1) & FindBestTeams(this, false)) == 0)
856                 {
857                         Send_Notification(NOTIF_ONE, this, MSG_INFO, INFO_TEAMCHANGE_LARGERTEAM);
858                         return;
859                 }
860         }
861         if(IS_PLAYER(this) && sourceteam != destinationteam)
862         {
863                 // reduce frags during a team change
864                 TeamchangeFrags(this);
865         }
866         if (!SetPlayerTeam(this, destinationteam, sourceteam, !IS_CLIENT(this)))
867         {
868                 return;
869         }
870         AutoBalanceBots(sourceteam, destinationteam);
871         if (!IS_PLAYER(this) || (sourceteam == destinationteam))
872         {
873                 return;
874         }
875         // kill player when changing teams
876         if (IS_DEAD(this) || (MUTATOR_CALLHOOK(Player_ChangeTeamKill, this) == true))
877         {
878                 return;
879         }
880         Damage(this, this, this, 100000, DEATH_TEAMCHANGE.m_id, this.origin, '0 0 0');
881 }
882
883 void AutoBalanceBots(int sourceteam, int destinationteam)
884 {
885         if ((sourceteam == -1) || (destinationteam == -1))
886         {
887                 return;
888         }
889         if (!autocvar_g_balance_teams ||
890                 !autocvar_g_balance_teams_prevent_imbalance)
891         {
892                 return;
893         }
894         int numplayerssourceteam = 0;
895         int numplayersdestinationteam = 0;
896         entity lowestbotdestinationteam = NULL;
897         switch (sourceteam)
898         {
899                 case 1:
900                 {
901                         numplayerssourceteam = c1;
902                         break;
903                 }
904                 case 2:
905                 {
906                         numplayerssourceteam = c2;
907                         break;
908                 }
909                 case 3:
910                 {
911                         numplayerssourceteam = c3;
912                         break;
913                 }
914                 case 4:
915                 {
916                         numplayerssourceteam = c4;
917                         break;
918                 }
919         }
920         switch (destinationteam)
921         {
922                 case 1:
923                 {
924                         numplayersdestinationteam = c1;
925                         lowestbotdestinationteam = lowestbotteam1;
926                         break;
927                 }
928                 case 2:
929                 {
930                         numplayersdestinationteam = c2;
931                         lowestbotdestinationteam = lowestbotteam2;
932                         break;
933                 }
934                 case 3:
935                 {
936                         numplayersdestinationteam = c3;
937                         lowestbotdestinationteam = lowestbotteam3;
938                         break;
939                 }
940                 case 4:
941                 {
942                         numplayersdestinationteam = c4;
943                         lowestbotdestinationteam = lowestbotteam4;
944                         break;
945                 }
946         }
947         if ((numplayersdestinationteam <= numplayerssourceteam) ||
948                 (lowestbotdestinationteam == NULL))
949         {
950                 return;
951         }
952         SetPlayerTeamSimple(lowestbotdestinationteam, Team_NumberToTeam(sourceteam));
953         if (IS_DEAD(lowestbotdestinationteam) || (MUTATOR_CALLHOOK(
954                 Player_ChangeTeamKill, lowestbotdestinationteam) == true))
955         {
956                 return;
957         }
958         Damage(lowestbotdestinationteam, lowestbotdestinationteam,
959                 lowestbotdestinationteam, 100000, DEATH_TEAMCHANGE.m_id,
960                 lowestbotdestinationteam.origin, '0 0 0');
961 }
962
963 void ShufflePlayerOutOfTeam (float source_team)
964 {
965         float smallestteam, smallestteam_count, steam;
966         float lowest_bot_score, lowest_player_score;
967         entity lowest_bot, lowest_player, selected;
968
969         smallestteam = 0;
970         smallestteam_count = 999999999;
971
972         if(c1 >= 0 && c1 < smallestteam_count)
973         {
974                 smallestteam = 1;
975                 smallestteam_count = c1;
976         }
977         if(c2 >= 0 && c2 < smallestteam_count)
978         {
979                 smallestteam = 2;
980                 smallestteam_count = c2;
981         }
982         if(c3 >= 0 && c3 < smallestteam_count)
983         {
984                 smallestteam = 3;
985                 smallestteam_count = c3;
986         }
987         if(c4 >= 0 && c4 < smallestteam_count)
988         {
989                 smallestteam = 4;
990                 smallestteam_count = c4;
991         }
992
993         if(!smallestteam)
994         {
995                 bprint("warning: no smallest team\n");
996                 return;
997         }
998
999         if(source_team == 1)
1000                 steam = NUM_TEAM_1;
1001         else if(source_team == 2)
1002                 steam = NUM_TEAM_2;
1003         else if(source_team == 3)
1004                 steam = NUM_TEAM_3;
1005         else // if(source_team == 4)
1006                 steam = NUM_TEAM_4;
1007
1008         lowest_bot = NULL;
1009         lowest_bot_score = 999999999;
1010         lowest_player = NULL;
1011         lowest_player_score = 999999999;
1012
1013         // find the lowest-scoring player & bot of that team
1014         FOREACH_CLIENT(IS_PLAYER(it) && it.team == steam, LAMBDA(
1015                 if(it.isbot)
1016                 {
1017                         if(it.totalfrags < lowest_bot_score)
1018                         {
1019                                 lowest_bot = it;
1020                                 lowest_bot_score = it.totalfrags;
1021                         }
1022                 }
1023                 else
1024                 {
1025                         if(it.totalfrags < lowest_player_score)
1026                         {
1027                                 lowest_player = it;
1028                                 lowest_player_score = it.totalfrags;
1029                         }
1030                 }
1031         ));
1032
1033         // prefers to move a bot...
1034         if(lowest_bot != NULL)
1035                 selected = lowest_bot;
1036         // but it will move a player if it has to
1037         else
1038                 selected = lowest_player;
1039         // don't do anything if it couldn't find anyone
1040         if(!selected)
1041         {
1042                 bprint("warning: couldn't find a player to move from team\n");
1043                 return;
1044         }
1045
1046         // smallest team gains a member
1047         if(smallestteam == 1)
1048         {
1049                 c1 = c1 + 1;
1050         }
1051         else if(smallestteam == 2)
1052         {
1053                 c2 = c2 + 1;
1054         }
1055         else if(smallestteam == 3)
1056         {
1057                 c3 = c3 + 1;
1058         }
1059         else if(smallestteam == 4)
1060         {
1061                 c4 = c4 + 1;
1062         }
1063         else
1064         {
1065                 bprint("warning: destination team invalid\n");
1066                 return;
1067         }
1068         // source team loses a member
1069         if(source_team == 1)
1070         {
1071                 c1 = c1 + 1;
1072         }
1073         else if(source_team == 2)
1074         {
1075                 c2 = c2 + 2;
1076         }
1077         else if(source_team == 3)
1078         {
1079                 c3 = c3 + 3;
1080         }
1081         else if(source_team == 4)
1082         {
1083                 c4 = c4 + 4;
1084         }
1085         else
1086         {
1087                 bprint("warning: source team invalid\n");
1088                 return;
1089         }
1090
1091         // move the player to the new team
1092         TeamchangeFrags(selected);
1093         if (!SetPlayerTeam(selected, smallestteam, source_team, false))
1094         {
1095                 return;
1096         }
1097         if (IS_DEAD(selected) || MUTATOR_CALLHOOK(Player_ChangeTeamKill, selected) == true)
1098         {
1099                 return;
1100         }
1101         Damage(selected, selected, selected, 100000, DEATH_AUTOTEAMCHANGE.m_id, selected.origin, '0 0 0');
1102         Send_Notification(NOTIF_ONE, selected, MSG_CENTER, CENTER_DEATH_SELF_AUTOTEAMCHANGE, selected.team);
1103 }