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