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