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