Merge remote-tracking branch 'origin/master' into Mario/lms_updates
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / teamplay.qc
1 string cache_mutatormsg;
2 string cache_lastmutatormsg;
3
4 // client counts for each team
5 float c1, c2, c3, c4;
6 // # of bots on those teams
7 float cb1, cb2, cb3, cb4;
8
9 //float audit_teams_time;
10
11 void TeamchangeFrags(entity e)
12 {
13         PlayerScore_Clear(e);
14 }
15
16 void tdm_init();
17 void entcs_init();
18
19 void LogTeamchange(float player_id, float team_number, float type)
20 {
21         if(!autocvar_sv_eventlog)
22                 return;
23
24         if(player_id < 1)
25                 return;
26
27         GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
28 }
29
30 void default_delayedinit()
31 {
32         if(!scores_initialized)
33                 ScoreRules_generic();
34 }
35
36 void ActivateTeamplay()
37 {
38         serverflags |= SERVERFLAG_TEAMPLAY;
39         teamplay = 1;
40 }
41
42 void InitGameplayMode()
43 {
44         float fraglimit_override, timelimit_override, leadlimit_override, qualifying_override;
45
46         qualifying_override = -1;
47
48         VoteReset();
49
50         // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
51         get_mi_min_max(1);
52         world.mins = mi_min;
53         world.maxs = mi_max;
54
55         MapInfo_LoadMapSettings(mapname);
56         teamplay = 0;
57         serverflags &~= SERVERFLAG_TEAMPLAY;
58
59         if not(cvar_value_issafe(world.fog))
60         {
61                 print("The current map contains a potentially harmful fog setting, ignored\n");
62                 world.fog = string_null;
63         }
64         if(MapInfo_Map_fog != "")
65                 if(MapInfo_Map_fog == "none")
66                         world.fog = string_null;
67                 else
68                         world.fog = strzone(MapInfo_Map_fog);
69         clientstuff = strzone(MapInfo_Map_clientstuff);
70
71         MapInfo_ClearTemps();
72
73         // set both here, gamemode can override it later
74         timelimit_override = autocvar_timelimit_override;
75         fraglimit_override = autocvar_fraglimit_override;
76         leadlimit_override = autocvar_leadlimit_override;
77         gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
78
79         if(g_dm)
80         {
81         }
82
83         if(g_tdm)
84         {
85                 ActivateTeamplay();
86                 tdm_init();
87                 if(autocvar_g_tdm_team_spawns)
88                         have_team_spawns = -1; // request team spawns
89         }
90
91         if(g_domination)
92         {
93                 ActivateTeamplay();
94                 fraglimit_override = autocvar_g_domination_point_limit;
95                 leadlimit_override = autocvar_g_domination_point_leadlimit;
96                 MUTATOR_ADD(gamemode_domination);
97                 have_team_spawns = -1; // request team spawns
98         }
99
100         if(g_ctf)
101         {
102                 ActivateTeamplay();
103                 fraglimit_override = autocvar_capturelimit_override;
104                 leadlimit_override = autocvar_captureleadlimit_override;
105                 MUTATOR_ADD(gamemode_ctf);
106                 have_team_spawns = -1; // request team spawns
107         }
108
109         if(g_lms)
110         {
111                 fraglimit_override = autocvar_g_lms_lives_override;
112                 leadlimit_override = 0; // not supported by LMS
113                 if(fraglimit_override == 0)
114                         fraglimit_override = -1;
115                 MUTATOR_ADD(gamemode_lms);
116         }
117
118         if(g_arena)
119         {
120                 fraglimit_override = autocvar_g_arena_point_limit;
121                 leadlimit_override = autocvar_g_arena_point_leadlimit;
122                 MUTATOR_ADD(gamemode_arena);
123         }
124
125         if(g_ca)
126         {
127                 ActivateTeamplay();
128                 fraglimit_override = autocvar_g_ca_point_limit;
129                 leadlimit_override = autocvar_g_ca_point_leadlimit;
130                 MUTATOR_ADD(gamemode_ca);
131         }
132
133         if(g_keyhunt)
134         {
135                 ActivateTeamplay();
136                 fraglimit_override = autocvar_g_keyhunt_point_limit;
137                 leadlimit_override = autocvar_g_keyhunt_point_leadlimit;
138                 MUTATOR_ADD(gamemode_keyhunt);
139         }
140
141         if(g_freezetag)
142         {
143                 ActivateTeamplay();
144                 fraglimit_override = autocvar_g_freezetag_point_limit;
145                 leadlimit_override = autocvar_g_freezetag_point_leadlimit;
146                 MUTATOR_ADD(gamemode_freezetag);
147         }
148
149         if(g_assault)
150         {
151                 ActivateTeamplay();
152                 ScoreRules_assault();
153                 have_team_spawns = -1; // request team spawns
154         }
155
156         if(g_onslaught)
157         {
158                 ActivateTeamplay();
159                 have_team_spawns = -1; // request team spawns
160                 MUTATOR_ADD(gamemode_onslaught);
161         }
162
163         if(g_race)
164         {
165
166                 if(autocvar_g_race_teams)
167                 {
168                         ActivateTeamplay();
169                         race_teams = bound(2, autocvar_g_race_teams, 4);
170                         have_team_spawns = -1; // request team spawns
171                 }
172                 else
173                         race_teams = 0;
174
175                 qualifying_override = autocvar_g_race_qualifying_timelimit_override;
176                 fraglimit_override = autocvar_g_race_laps_limit;
177                 leadlimit_override = 0; // currently not supported by race
178         }
179
180         if(g_cts)
181         {
182                 g_race_qualifying = 1;
183                 fraglimit_override = 0;
184                 leadlimit_override = 0;
185         }
186
187         if(g_nexball)
188         {
189         fraglimit_override = autocvar_g_nexball_goallimit;
190         leadlimit_override = autocvar_g_nexball_goalleadlimit;
191         ActivateTeamplay();
192         have_team_spawns = -1; // request team spawns
193             MUTATOR_ADD(gamemode_nexball);
194         }
195         
196         if(g_keepaway)
197         {
198                 MUTATOR_ADD(gamemode_keepaway);
199         }
200
201         if(teamplay)
202                 entcs_init();
203
204         cache_mutatormsg = strzone("");
205         cache_lastmutatormsg = strzone("");
206
207         // enforce the server's universal frag/time limits
208         if(!autocvar_g_campaign)
209         {
210                 if(fraglimit_override >= 0)
211                         cvar_set("fraglimit", ftos(fraglimit_override));
212                 if(timelimit_override >= 0)
213                         cvar_set("timelimit", ftos(timelimit_override));
214                 if(leadlimit_override >= 0)
215                         cvar_set("leadlimit", ftos(leadlimit_override));
216                 if(qualifying_override >= 0)
217                         cvar_set("g_race_qualifying_timelimit", ftos(qualifying_override));
218         }
219
220         if(g_race)
221         {
222                 // we need to find out the correct value for g_race_qualifying
223                 if(autocvar_g_campaign)
224                 {
225                         g_race_qualifying = 1;
226                 }
227                 else if(!autocvar_g_campaign && autocvar_g_race_qualifying_timelimit > 0)
228                 {
229                         g_race_qualifying = 2;
230                         race_fraglimit = autocvar_fraglimit;
231                         race_leadlimit = autocvar_leadlimit;
232                         race_timelimit = autocvar_timelimit;
233                         cvar_set("fraglimit", "0");
234                         cvar_set("leadlimit", "0");
235                         cvar_set("timelimit", ftos(autocvar_g_race_qualifying_timelimit));
236                 }
237                 else
238                         g_race_qualifying = 0;
239         }
240
241         if(g_race || g_cts)
242         {
243                 if(g_race_qualifying)
244                         independent_players = 1;
245
246                 ScoreRules_race();
247         }
248
249         InitializeEntity(world, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
250 }
251
252 string GetClientVersionMessage() {
253         string versionmsg;
254         if (self.version_mismatch) {
255                 if(self.version < autocvar_gameversion) {
256                         versionmsg = "^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8";
257                 } else {
258                         versionmsg = "^3This server is using an outdated Xonotic version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8";
259                 }
260         } else {
261                 versionmsg = "^2client version and server version are compatible.^8";
262         }
263         return versionmsg;
264 }
265
266 string getwelcomemessage(void)
267 {
268         string s, modifications, motd;
269
270         ret_string = "";
271         MUTATOR_CALLHOOK(BuildMutatorsPrettyString);
272         modifications = ret_string;
273         
274         if(g_minstagib)
275                 modifications = strcat(modifications, ", MinstaGib");
276         if(g_weaponarena)
277         {
278                 if(g_weaponarena_random)
279                         modifications = strcat(modifications, ", ", ftos(g_weaponarena_random), " of ", g_weaponarena_list, " Arena");
280                 else
281                         modifications = strcat(modifications, ", ", g_weaponarena_list, " Arena");
282         }
283         if(autocvar_g_start_weapon_laser == 0)
284                 modifications = strcat(modifications, ", No start weapons");
285         if(autocvar_sv_gravity < 800)
286                 modifications = strcat(modifications, ", Low gravity");
287         if(g_cloaked && !g_cts)
288                 modifications = strcat(modifications, ", Cloaked");
289         if(g_grappling_hook)
290                 modifications = strcat(modifications, ", Hook");
291         if(g_midair)
292                 modifications = strcat(modifications, ", Midair");
293         if(g_pinata)
294                 modifications = strcat(modifications, ", PiƱata");
295         if(g_weapon_stay && !g_cts)
296                 modifications = strcat(modifications, ", Weapons stay");
297         if(g_bloodloss > 0)
298                 modifications = strcat(modifications, ", Blood loss");
299         if(g_jetpack)
300                 modifications = strcat(modifications, ", Jet pack");
301         if(autocvar_g_powerups == 0)
302                 modifications = strcat(modifications, ", No powerups");
303         if(autocvar_g_powerups > 0)
304                 modifications = strcat(modifications, ", Powerups");
305         modifications = substring(modifications, 2, strlen(modifications) - 2);
306
307         string versionmessage;
308         versionmessage = GetClientVersionMessage();
309
310         s = strcat("This is Xonotic ", autocvar_g_xonoticversion, "\n", versionmessage);
311         s = strcat(s, "^8\n\nmatch type is ^1", gamemode_name, "^8\n");
312
313         if(modifications != "")
314                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
315
316         if (g_grappling_hook)
317                 s = strcat(s, "\n\n^3grappling hook^8 is enabled, press 'e' to use it\n");
318
319         if(cache_lastmutatormsg != autocvar_g_mutatormsg)
320         {
321                 if(cache_lastmutatormsg)
322                         strunzone(cache_lastmutatormsg);
323                 if(cache_mutatormsg)
324                         strunzone(cache_mutatormsg);
325                 cache_lastmutatormsg = strzone(autocvar_g_mutatormsg);
326                 cache_mutatormsg = strzone(cache_lastmutatormsg);
327         }
328
329         if (cache_mutatormsg != "") {
330                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
331         }
332
333         motd = autocvar_sv_motd;
334         if (motd != "") {
335                 s = strcat(s, "\n\n^8MOTD: ^7", strreplace("\\n", "\n", motd));
336         }
337         return s;
338 }
339
340 void SetPlayerColors(entity pl, float _color)
341 {
342         /*string s;
343         s = ftos(cl);
344         stuffcmd(pl, strcat("color ", s, " ", s, "\n")  );
345         pl.team = cl + 1;
346         //pl.clientcolors = pl.clientcolors - (pl.clientcolors & 15) + cl;
347         pl.clientcolors = 16*cl + cl;*/
348
349         float pants, shirt;
350         pants = _color & 0x0F;
351         shirt = _color & 0xF0;
352
353
354         if(teamplay) {
355                 setcolor(pl, 16*pants + pants);
356         } else {
357                 setcolor(pl, shirt + pants);
358         }
359 }
360
361 void SetPlayerTeam(entity pl, float t, float s, float noprint)
362 {
363         float _color;
364
365         if(t == 4)
366                 _color = NUM_TEAM_4 - 1;
367         else if(t == 3)
368                 _color = NUM_TEAM_3 - 1;
369         else if(t == 2)
370                 _color = NUM_TEAM_2 - 1;
371         else
372                 _color = NUM_TEAM_1 - 1;
373
374         SetPlayerColors(pl,_color);
375
376         if(t != s) {
377                 LogTeamchange(pl.playerid, pl.team, 3);  // log manual team join
378
379                 if(!noprint)
380                 bprint(pl.netname, "^7 has changed from ", Team_NumberToColoredFullName(s), "^7 to ", Team_NumberToColoredFullName(t), "\n");
381         }
382
383 }
384
385 // set c1...c4 to show what teams are allowed
386 void CheckAllowedTeams (entity for_whom)
387 {
388         float dm;
389         entity head;
390         string teament_name;
391
392         c1 = c2 = c3 = c4 = -1;
393         cb1 = cb2 = cb3 = cb4 = 0;
394
395         teament_name = string_null;
396         if(g_onslaught)
397         {
398                 // onslaught is special
399                 head = findchain(classname, "onslaught_generator");
400                 while (head)
401                 {
402                         if (head.team == NUM_TEAM_1) c1 = 0;
403                         if (head.team == NUM_TEAM_2) c2 = 0;
404                         if (head.team == NUM_TEAM_3) c3 = 0;
405                         if (head.team == NUM_TEAM_4) c4 = 0;
406                         head = head.chain;
407                 }
408         }
409         else if(g_domination)
410                 teament_name = "dom_team";
411         else if(g_ctf)
412                 teament_name = "ctf_team";
413         else if(g_tdm)
414                 teament_name = "tdm_team";
415         else if(g_nexball)
416                 teament_name = "nexball_team";
417         else if(g_assault)
418                 c1 = c2 = 0; // Assault always has 2 teams
419         else
420         {
421                 // cover anything else by treating it like tdm with no teams spawned
422                 if(g_race)
423                         dm = race_teams;
424                 else
425                         dm = 2;
426
427                 ret_float = dm;
428                 MUTATOR_CALLHOOK(GetTeamCount);
429                 dm = ret_float;
430
431                 if(dm >= 4)
432                         c1 = c2 = c3 = c4 = 0;
433                 else if(dm >= 3)
434                         c1 = c2 = c3 = 0;
435                 else
436                         c1 = c2 = 0;
437         }
438
439         // find out what teams are allowed if necessary
440         if(teament_name)
441         {
442                 head = find(world, classname, teament_name);
443                 while(head)
444                 {
445                         if(!(g_domination && head.netname == ""))
446                         {
447                                 if(head.team == NUM_TEAM_1)
448                                         c1 = 0;
449                                 else if(head.team == NUM_TEAM_2)
450                                         c2 = 0;
451                                 else if(head.team == NUM_TEAM_3)
452                                         c3 = 0;
453                                 else if(head.team == NUM_TEAM_4)
454                                         c4 = 0;
455                         }
456                         head = find(head, classname, teament_name);
457                 }
458         }
459
460         // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
461         if(c3==-1 && c4==-1)
462         if(autocvar_bot_vs_human && for_whom)
463         {
464                 if(autocvar_bot_vs_human > 0)
465                 {
466                         // bots are all blue
467                         if(clienttype(for_whom) == CLIENTTYPE_BOT)
468                                 c1 = c3 = c4 = -1;
469                         else
470                                 c2 = -1;
471                 }
472                 else
473                 {
474                         // bots are all red
475                         if(clienttype(for_whom) == CLIENTTYPE_BOT)
476                                 c2 = c3 = c4 = -1;
477                         else
478                                 c1 = -1;
479                 }
480         }
481
482         // if player has a forced team, ONLY allow that one
483         if(self.team_forced == NUM_TEAM_1 && c1 >= 0)
484                 c2 = c3 = c4 = -1;
485         else if(self.team_forced == NUM_TEAM_2 && c2 >= 0)
486                 c1 = c3 = c4 = -1;
487         else if(self.team_forced == NUM_TEAM_3 && c3 >= 0)
488                 c1 = c2 = c4 = -1;
489         else if(self.team_forced == NUM_TEAM_4 && c4 >= 0)
490                 c1 = c2 = c3 = -1;
491 }
492
493 float PlayerValue(entity p)
494 {
495         return 1;
496         // FIXME: it always returns 1...
497 }
498
499 // c1...c4 should be set to -1 (not allowed) or 0 (allowed).
500 // teams that are allowed will now have their player counts stored in c1...c4
501 void GetTeamCounts(entity ignore)
502 {
503         entity head;
504         float value, bvalue;
505         // now count how many players are on each team already
506
507         // FIXME: also find and memorize the lowest-scoring bot on each team (in case players must be shuffled around)
508         // also remember the lowest-scoring player
509
510         FOR_EACH_CLIENT(head)
511         {
512                 float t;
513                 if(head.classname == "player")
514                         t = head.team;
515                 else if(head.team_forced > 0)
516                         t = head.team_forced; // reserve the spot
517                 else
518                         continue;
519                 if(head != ignore)// && head.netname != "")
520                 {
521                         value = PlayerValue(head);
522                         if(clienttype(head) == CLIENTTYPE_BOT)
523                                 bvalue = value;
524                         else
525                                 bvalue = 0;
526                         if(t == NUM_TEAM_1)
527                         {
528                                 if(c1 >= 0)
529                                 {
530                                         c1 = c1 + value;
531                                         cb1 = cb1 + bvalue;
532                                 }
533                         }
534                         if(t == NUM_TEAM_2)
535                         {
536                                 if(c2 >= 0)
537                                 {
538                                         c2 = c2 + value;
539                                         cb2 = cb2 + bvalue;
540                                 }
541                         }
542                         if(t == NUM_TEAM_3)
543                         {
544                                 if(c3 >= 0)
545                                 {
546                                         c3 = c3 + value;
547                                         cb3 = cb3 + bvalue;
548                                 }
549                         }
550                         if(t == NUM_TEAM_4)
551                         {
552                                 if(c4 >= 0)
553                                 {
554                                         c4 = c4 + value;
555                                         cb4 = cb4 + bvalue;
556                                 }
557                         }
558                 }
559         }
560
561         // if the player who has a forced team has not joined yet, reserve the spot
562         if(autocvar_g_campaign)
563         {
564                 switch(autocvar_g_campaign_forceteam)
565                 {
566                         case 1: if(c1 == cb1) ++c1; break;
567                         case 2: if(c2 == cb2) ++c2; break;
568                         case 3: if(c3 == cb3) ++c3; break;
569                         case 4: if(c4 == cb4) ++c4; break;
570                 }
571         }
572 }
573
574 float TeamSmallerEqThanTeam(float ta, float tb, entity e)
575 {
576         // we assume that CheckAllowedTeams and GetTeamCounts have already been called
577         float f;
578         float ca = -1, cb = -1, cba = 0, cbb = 0, sa = 0, sb = 0;
579
580         switch(ta)
581         {
582                 case 1: ca = c1; cba = cb1; sa = team1_score; break;
583                 case 2: ca = c2; cba = cb2; sa = team2_score; break;
584                 case 3: ca = c3; cba = cb3; sa = team3_score; break;
585                 case 4: ca = c4; cba = cb4; sa = team4_score; break;
586         }
587         switch(tb)
588         {
589                 case 1: cb = c1; cbb = cb1; sb = team1_score; break;
590                 case 2: cb = c2; cbb = cb2; sb = team2_score; break;
591                 case 3: cb = c3; cbb = cb3; sb = team3_score; break;
592                 case 4: cb = c4; cbb = cb4; sb = team4_score; break;
593         }
594
595         // invalid
596         if(ca < 0 || cb < 0)
597                 return FALSE;
598
599         // equal
600         if(ta == tb)
601                 return TRUE;
602
603         if(clienttype(e) == CLIENTTYPE_REAL)
604         {
605                 if(bots_would_leave)
606                 {
607                         ca -= cba * 0.999;
608                         cb -= cbb * 0.999;
609                 }
610         }
611         
612         // keep teams alive (teams of size 0 always count as smaller, ignoring score)
613         if(ca < 1)
614                 if(cb >= 1)
615                         return TRUE;
616         if(ca >= 1)
617                 if(cb < 1)
618                         return FALSE;
619
620         // first, normalize
621         f = max(ca, cb, 1);
622         ca /= f;
623         cb /= f;
624         f = max(sa, sb, 1);
625         sa /= f;
626         sb /= f;
627
628         // the more we're at the end of the match, the more take scores into account
629         f = bound(0, game_completion_ratio * autocvar_g_balance_teams_scorefactor, 1);
630         ca += (sa - ca) * f;
631         cb += (sb - cb) * f;
632
633         return ca <= cb;
634 }
635
636 // returns # of smallest team (1, 2, 3, 4)
637 // NOTE: Assumes CheckAllowedTeams has already been called!
638 float FindSmallestTeam(entity pl, float ignore_pl)
639 {
640         float totalteams, t;
641         totalteams = 0;
642
643         // find out what teams are available
644         //CheckAllowedTeams();
645
646         // make sure there are at least 2 teams to join
647         if(c1 >= 0)
648                 totalteams = totalteams + 1;
649         if(c2 >= 0)
650                 totalteams = totalteams + 1;
651         if(c3 >= 0)
652                 totalteams = totalteams + 1;
653         if(c4 >= 0)
654                 totalteams = totalteams + 1;
655
656         if((autocvar_bot_vs_human || pl.team_forced > 0) && totalteams == 1)
657                 totalteams += 1;
658
659         if(totalteams <= 1)
660         {
661                 if(autocvar_g_campaign && pl && clienttype(pl) == CLIENTTYPE_REAL)
662                         return 1; // special case for campaign and player joining
663                 else if(g_domination)
664                         error("Too few teams available for domination\n");
665                 else if(g_ctf)
666                         error("Too few teams available for ctf\n");
667                 else if(g_keyhunt)
668                         error("Too few teams available for key hunt\n");
669                 else if(g_freezetag)
670                         error("Too few teams available for freeze tag\n");
671                 else
672                         error("Too few teams available for team deathmatch\n");
673         }
674
675         // count how many players are in each team
676         if(ignore_pl)
677                 GetTeamCounts(pl);
678         else
679                 GetTeamCounts(world);
680
681         RandomSelection_Init();
682         
683         t = 1;
684         if(TeamSmallerEqThanTeam(2, t, pl))
685                 t = 2;
686         if(TeamSmallerEqThanTeam(3, t, pl))
687                 t = 3;
688         if(TeamSmallerEqThanTeam(4, t, pl))
689                 t = 4;
690
691         // now t is the minimum, or A minimum!
692         if(t == 1 || TeamSmallerEqThanTeam(1, t, pl))
693                 RandomSelection_Add(world, 1, string_null, 1, 1);
694         if(t == 2 || TeamSmallerEqThanTeam(2, t, pl))
695                 RandomSelection_Add(world, 2, string_null, 1, 1);
696         if(t == 3 || TeamSmallerEqThanTeam(3, t, pl))
697                 RandomSelection_Add(world, 3, string_null, 1, 1);
698         if(t == 4 || TeamSmallerEqThanTeam(4, t, pl))
699                 RandomSelection_Add(world, 4, string_null, 1, 1);
700
701         return RandomSelection_chosen_float;
702 }
703
704 float JoinBestTeam(entity pl, float only_return_best, float forcebestteam)
705 {
706         float smallest, selectedteam;
707
708         // don't join a team if we're not playing a team game
709         if(!teamplay)
710                 return 0;
711
712         // find out what teams are available
713         CheckAllowedTeams(pl);
714
715         // if we don't care what team he ends up on, put him on whatever team he entered as.
716         // if he's not on a valid team, then let other code put him on the smallest team
717         if(!forcebestteam)
718         {
719                 if(     c1 >= 0 && pl.team == NUM_TEAM_1)
720                         selectedteam = pl.team;
721                 else if(c2 >= 0 && pl.team == NUM_TEAM_2)
722                         selectedteam = pl.team;
723                 else if(c3 >= 0 && pl.team == NUM_TEAM_3)
724                         selectedteam = pl.team;
725                 else if(c4 >= 0 && pl.team == NUM_TEAM_4)
726                         selectedteam = pl.team;
727                 else
728                         selectedteam = -1;
729
730                 if(selectedteam > 0)
731                 {
732                         if(!only_return_best)
733                         {
734                                 SetPlayerColors(pl, selectedteam - 1);
735
736                                 // when JoinBestTeam is called by client.qc/ClientKill_Now_TeamChange the players team is -1 and thus skipped
737                                 // when JoinBestTeam is called by cl_client.qc/ClientConnect the player_id is 0 the log attempt is rejected
738                                 LogTeamchange(pl.playerid, pl.team, 99);
739                         }
740                         return selectedteam;
741                 }
742                 // otherwise end up on the smallest team (handled below)
743         }
744
745         smallest = FindSmallestTeam(pl, TRUE);
746
747         if(!only_return_best && !pl.bot_forced_team)
748         {
749                 TeamchangeFrags(self);
750                 if(smallest == 1)
751                 {
752                         SetPlayerColors(pl, NUM_TEAM_1 - 1);
753                 }
754                 else if(smallest == 2)
755                 {
756                         SetPlayerColors(pl, NUM_TEAM_2 - 1);
757                 }
758                 else if(smallest == 3)
759                 {
760                         SetPlayerColors(pl, NUM_TEAM_3 - 1);
761                 }
762                 else if(smallest == 4)
763                 {
764                         SetPlayerColors(pl, NUM_TEAM_4 - 1);
765                 }
766                 else
767                 {
768                         error("smallest team: invalid team\n");
769                 }
770
771                 LogTeamchange(pl.playerid, pl.team, 2); // log auto join
772
773                 if(pl.deadflag == DEAD_NO)
774                         Damage(pl, pl, pl, 100000, DEATH_TEAMCHANGE, pl.origin, '0 0 0');
775         }
776
777         return smallest;
778 }
779
780 //void() ctf_playerchanged;
781 void SV_ChangeTeam(float _color)
782 {
783         float scolor, dcolor, steam, dteam; //, dbotcount, scount, dcount;
784
785         // in normal deathmatch we can just apply the color and we're done
786         if(!teamplay) {
787                 SetPlayerColors(self, _color);
788                 return;
789         }
790
791         scolor = self.clientcolors & 0x0F;
792         dcolor = _color & 0x0F;
793
794         if(scolor == NUM_TEAM_1 - 1)
795                 steam = 1;
796         else if(scolor == NUM_TEAM_2 - 1)
797                 steam = 2;
798         else if(scolor == NUM_TEAM_3 - 1)
799                 steam = 3;
800         else // if(scolor == NUM_TEAM_4 - 1)
801                 steam = 4;
802         if(dcolor == NUM_TEAM_1 - 1)
803                 dteam = 1;
804         else if(dcolor == NUM_TEAM_2 - 1)
805                 dteam = 2;
806         else if(dcolor == NUM_TEAM_3 - 1)
807                 dteam = 3;
808         else // if(dcolor == NUM_TEAM_4 - 1)
809                 dteam = 4;
810
811         CheckAllowedTeams(self);
812
813         if(dteam == 1 && c1 < 0) dteam = 4;
814         if(dteam == 4 && c4 < 0) dteam = 3;
815         if(dteam == 3 && c3 < 0) dteam = 2;
816         if(dteam == 2 && c2 < 0) dteam = 1;
817
818         // not changing teams
819         if(scolor == dcolor)
820         {
821                 //bprint("same team change\n");
822                 SetPlayerTeam(self, dteam, steam, TRUE);
823                 return;
824         }
825
826         if((autocvar_g_campaign) || (autocvar_g_changeteam_banned && self.wasplayer)) {
827                 sprint(self, "Team changes not allowed\n");
828                 return; // changing teams is not allowed
829         }
830
831         // autocvar_g_balance_teams_prevent_imbalance only makes sense if autocvar_g_balance_teams is on, as it makes the team selection dialog pointless
832         if(autocvar_g_balance_teams && autocvar_g_balance_teams_prevent_imbalance)
833         {
834                 GetTeamCounts(self);
835                 if(!TeamSmallerEqThanTeam(dteam, steam, self))
836                 {
837                         sprint(self, "Cannot change to a larger/better/shinier team\n");
838                         return;
839                 }
840         }
841
842 //      bprint("allow change teams from ", ftos(steam), " to ", ftos(dteam), "\n");
843
844         if(self.classname == "player" && steam != dteam)
845         {
846                 // reduce frags during a team change
847                 TeamchangeFrags(self);
848         }
849
850         SetPlayerTeam(self, dteam, steam, FALSE);
851
852         if(self.classname == "player" && steam != dteam)
853         {
854                 // kill player when changing teams
855                 if(self.deadflag == DEAD_NO)
856                         Damage(self, self, self, 100000, DEATH_TEAMCHANGE, self.origin, '0 0 0');
857         }
858 }
859
860 void ShufflePlayerOutOfTeam (float source_team)
861 {
862         float smallestteam, smallestteam_count, steam;
863         float lowest_bot_score, lowest_player_score;
864         entity head, lowest_bot, lowest_player, selected;
865
866         smallestteam = 0;
867         smallestteam_count = 999999999;
868
869         if(c1 >= 0 && c1 < smallestteam_count)
870         {
871                 smallestteam = 1;
872                 smallestteam_count = c1;
873         }
874         if(c2 >= 0 && c2 < smallestteam_count)
875         {
876                 smallestteam = 2;
877                 smallestteam_count = c2;
878         }
879         if(c3 >= 0 && c3 < smallestteam_count)
880         {
881                 smallestteam = 3;
882                 smallestteam_count = c3;
883         }
884         if(c4 >= 0 && c4 < smallestteam_count)
885         {
886                 smallestteam = 4;
887                 smallestteam_count = c4;
888         }
889
890         if(!smallestteam)
891         {
892                 bprint("warning: no smallest team\n");
893                 return;
894         }
895
896         if(source_team == 1)
897                 steam = NUM_TEAM_1;
898         else if(source_team == 2)
899                 steam = NUM_TEAM_2;
900         else if(source_team == 3)
901                 steam = NUM_TEAM_3;
902         else // if(source_team == 4)
903                 steam = NUM_TEAM_4;
904
905         lowest_bot = world;
906         lowest_bot_score = 999999999;
907         lowest_player = world;
908         lowest_player_score = 999999999;
909
910         // find the lowest-scoring player & bot of that team
911         FOR_EACH_PLAYER(head)
912         {
913                 if(head.team == steam)
914                 {
915                         if(head.isbot)
916                         {
917                                 if(head.totalfrags < lowest_bot_score)
918                                 {
919                                         lowest_bot = head;
920                                         lowest_bot_score = head.totalfrags;
921                                 }
922                         }
923                         else
924                         {
925                                 if(head.totalfrags < lowest_player_score)
926                                 {
927                                         lowest_player = head;
928                                         lowest_player_score = head.totalfrags;
929                                 }
930                         }
931                 }
932         }
933
934         // prefers to move a bot...
935         if(lowest_bot != world)
936                 selected = lowest_bot;
937         // but it will move a player if it has to
938         else
939                 selected = lowest_player;
940         // don't do anything if it couldn't find anyone
941         if(!selected)
942         {
943                 bprint("warning: couldn't find a player to move from team\n");
944                 return;
945         }
946
947         // smallest team gains a member
948         if(smallestteam == 1)
949         {
950                 c1 = c1 + 1;
951         }
952         else if(smallestteam == 2)
953         {
954                 c2 = c2 + 1;
955         }
956         else if(smallestteam == 3)
957         {
958                 c3 = c3 + 1;
959         }
960         else if(smallestteam == 4)
961         {
962                 c4 = c4 + 1;
963         }
964         else
965         {
966                 bprint("warning: destination team invalid\n");
967                 return;
968         }
969         // source team loses a member
970         if(source_team == 1)
971         {
972                 c1 = c1 + 1;
973         }
974         else if(source_team == 2)
975         {
976                 c2 = c2 + 2;
977         }
978         else if(source_team == 3)
979         {
980                 c3 = c3 + 3;
981         }
982         else if(source_team == 4)
983         {
984                 c4 = c4 + 4;
985         }
986         else
987         {
988                 bprint("warning: source team invalid\n");
989                 return;
990         }
991
992         // move the player to the new team
993         TeamchangeFrags(selected);
994         SetPlayerTeam(selected, smallestteam, source_team, FALSE);
995
996         if(selected.deadflag == DEAD_NO)
997                 Damage(selected, selected, selected, 100000, DEATH_AUTOTEAMCHANGE, selected.origin, '0 0 0');
998         centerprint(selected, strcat("You have been moved into a different team to improve team balance\nYou are now on: ", Team_ColoredFullName(selected.team)));
999 }
1000
1001 // code from here on is just to support maps that don't have team entities
1002 void tdm_spawnteam (string teamname, float teamcolor)
1003 {
1004         entity e;
1005         e = spawn();
1006         e.classname = "tdm_team";
1007         e.netname = teamname;
1008         e.cnt = teamcolor;
1009         e.team = e.cnt + 1;
1010 }
1011
1012 // spawn some default teams if the map is not set up for tdm
1013 void tdm_spawnteams()
1014 {
1015         float numteams;
1016
1017         numteams = autocvar_g_tdm_teams_override;
1018         if(numteams < 2)
1019                 numteams = autocvar_g_tdm_teams;
1020         numteams = bound(2, numteams, 4);
1021
1022         tdm_spawnteam("Red", NUM_TEAM_1-1);
1023         tdm_spawnteam("Blue", NUM_TEAM_2-1);
1024         if(numteams >= 3)
1025                 tdm_spawnteam("Yellow", NUM_TEAM_3-1);
1026         if(numteams >= 4)
1027                 tdm_spawnteam("Pink", NUM_TEAM_4-1);
1028 }
1029
1030 void tdm_delayedinit()
1031 {
1032         // if no teams are found, spawn defaults
1033         if (find(world, classname, "tdm_team") == world)
1034                 tdm_spawnteams();
1035 }
1036
1037 void tdm_init()
1038 {
1039         InitializeEntity(world, tdm_delayedinit, INITPRIO_GAMETYPE);
1040 }