turn NIX into a mutator; fix keyhunt
[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 float IsTeamBalanceForced()
12 {
13         if(intermission_running)
14                 return 0; // no rebalancing whatsoever please
15         if(!teams_matter)
16                 return 0;
17         if(cvar("g_campaign"))
18                 return 0;
19         if(!cvar("g_balance_teams_force"))
20                 return -1;
21         return 1;
22 }
23
24 void TeamchangeFrags(entity e)
25 {
26         PlayerScore_Clear(e);
27 }
28
29 vector TeamColor(float teem)
30 {
31         switch(teem)
32         {
33                 case COLOR_TEAM1:
34                         return '1 0.0625 0.0625';
35                 case COLOR_TEAM2:
36                         return '0.0625 0.0625 1';
37                 case COLOR_TEAM3:
38                         return '1 1 0.0625';
39                 case COLOR_TEAM4:
40                         return '1 0.0625 1';
41                 default:
42                         return '1 1 1';
43         }
44 }
45
46 string TeamName(float t)
47 {
48         return strcat(Team_ColorName(t), " Team");
49 }
50 string ColoredTeamName(float t)
51 {
52         return strcat(Team_ColorCode(t), Team_ColorName(t), " Team^7");
53 }
54 string TeamNoName(float t)
55 {
56         // fixme: Search for team entities and get their .netname's!
57         if(t == 1)
58                 return "Red Team";
59         if(t == 2)
60                 return "Blue Team";
61         if(t == 3)
62                 return "Yellow Team";
63         if(t == 4)
64                 return "Pink Team";
65         return "Neutral Team";
66 }
67
68 void dom_init();
69 void ctf_init();
70 void runematch_init();
71 void tdm_init();
72 void nb_init();
73 void entcs_init();
74
75 void LogTeamchange(float player_id, float team_number, float type)
76 {
77         if(!cvar("sv_eventlog"))
78                 return;
79
80         if(player_id < 1)
81                 return;
82
83         GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type)));
84 }
85
86 void WriteGameCvars()
87 {
88         cvar_set("g_dm", ftos(g_dm));
89         cvar_set("g_tdm", ftos(g_tdm));
90         cvar_set("g_domination", ftos(g_domination));
91         cvar_set("g_ctf", ftos(g_ctf));
92         cvar_set("g_runematch", ftos(g_runematch));
93         cvar_set("g_lms", ftos(g_lms));
94         cvar_set("g_arena", ftos(g_arena));
95         cvar_set("g_ca", ftos(g_ca));
96         cvar_set("g_keyhunt", ftos(g_keyhunt));
97         cvar_set("g_assault", ftos(g_assault));
98         cvar_set("g_onslaught", ftos(g_onslaught));
99         cvar_set("g_race", ftos(g_race));
100         cvar_set("g_nexball", ftos(g_nexball));
101         cvar_set("g_cts", ftos(g_cts));
102 }
103
104 void ReadGameCvars()
105 {
106         float found;
107         float prev;
108         float i;
109
110         found = 0;
111         prev = cvar("gamecfg");
112         for(i = 0; i < 2; ++i)
113         {
114                 found += (g_dm = (!found && (prev != GAME_DEATHMATCH) && cvar("g_dm")));
115                 found += (g_tdm = (!found && (prev != GAME_TEAM_DEATHMATCH) && cvar("g_tdm")));
116                 found += (g_domination = (!found && (prev != GAME_DOMINATION) && cvar("g_domination")));
117                 found += (g_ctf = (!found && (prev != GAME_CTF) && cvar("g_ctf")));
118                 found += (g_runematch = (!found && (prev != GAME_RUNEMATCH) && cvar("g_runematch")));
119                 found += (g_lms = (!found && (prev != GAME_LMS) && cvar("g_lms")));
120                 found += (g_arena = (!found && (prev != GAME_ARENA) && cvar("g_arena")));
121                 found += (g_ca = (!found && (prev != GAME_CA) && cvar("g_ca")));
122                 found += (g_keyhunt = (!found && (prev != GAME_KEYHUNT) && cvar("g_keyhunt")));
123                 found += (g_assault = (!found && (prev != GAME_ASSAULT) && cvar("g_assault")));
124                 found += (g_onslaught = (!found && (prev != GAME_ONSLAUGHT) && cvar("g_onslaught")));
125                 found += (g_race = (!found && (prev != GAME_RACE) && cvar("g_race")));
126                 found += (g_nexball = (!found && (prev != GAME_NEXBALL) && cvar("g_nexball")));
127                 found += (g_cts = (!found && (prev != GAME_CTS) && cvar("g_cts")));
128
129                 if(found)
130                         break;
131
132                 prev = -1; // second attempt takes place WITHOUT prev set
133         }
134
135         if(!found)
136                 g_dm = 1;
137
138         if(g_dm && cvar("deathmatch_force_teamplay"))
139         {
140                 g_dm = 0;
141                 g_tdm = 1;
142         }
143
144         teams_matter = 0;
145 }
146
147 void default_delayedinit()
148 {
149         if(!scores_initialized)
150                 ScoreRules_generic();
151 }
152
153 void ActivateTeamplay()
154 {
155         float teamplay_default;
156         teamplay_default = cvar("teamplay_default");
157
158         if(teamplay_default)
159                 teamplay = teamplay_default;
160         else
161                 teamplay = 3;
162         cvar_set("teamplay", ftos(teamplay));
163
164         teams_matter = 1;
165 }
166
167 void InitGameplayMode()
168 {
169         float fraglimit_override, timelimit_override, leadlimit_override, qualifying_override;
170
171         qualifying_override = -1;
172
173         VoteReset();
174
175         teams_matter = 0;
176         cvar_set("teamplay", "0");
177
178         // make sure only ONE type is selected
179         ReadGameCvars();
180         WriteGameCvars();
181
182         // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
183         get_mi_min_max(1);
184         world.mins = mi_min;
185         world.maxs = mi_max;
186
187         MapInfo_LoadMapSettings(mapname);
188
189         if not(cvar_value_issafe(world.fog))
190         {
191                 print("The current map contains a potentially harmful fog setting, ignored\n");
192                 world.fog = string_null;
193         }
194         if(MapInfo_Map_fog != "")
195                 if(MapInfo_Map_fog == "none")
196                         world.fog = string_null;
197                 else
198                         world.fog = strzone(MapInfo_Map_fog);
199         clientstuff = strzone(MapInfo_Map_clientstuff);
200
201         MapInfo_ClearTemps();
202
203         // in case mapinfo switched the type
204         ReadGameCvars();
205
206         // set both here, gamemode can override it later
207         timelimit_override = cvar("timelimit_override");
208         fraglimit_override = cvar("fraglimit_override");
209         leadlimit_override = cvar("leadlimit_override");
210
211         if(g_dm)
212         {
213                 game = GAME_DEATHMATCH;
214                 gamemode_name = "Deathmatch";
215         }
216
217         if(g_tdm)
218         {
219                 game = GAME_TEAM_DEATHMATCH;
220                 gamemode_name = "Team Deathmatch";
221                 ActivateTeamplay();
222                 tdm_init();
223                 if(cvar("g_tdm_team_spawns"))
224                         have_team_spawns = -1; // request team spawns
225         }
226
227         if(g_domination)
228         {
229                 game = GAME_DOMINATION;
230                 gamemode_name = "Domination";
231                 ActivateTeamplay();
232                 fraglimit_override = cvar("g_domination_point_limit");
233                 leadlimit_override = cvar("g_domination_point_leadlimit");
234                 dom_init();
235                 have_team_spawns = -1; // request team spawns
236         }
237
238         if(g_ctf)
239         {
240                 game = GAME_CTF;
241                 gamemode_name = "Capture the Flag";
242                 ActivateTeamplay();
243                 if(cvar("g_campaign"))
244                         g_ctf_win_mode = 2;
245                 else
246                         g_ctf_win_mode = cvar("g_ctf_win_mode");
247                 g_ctf_ignore_frags = cvar("g_ctf_ignore_frags");
248                 if(g_ctf_win_mode == 2)
249                 {
250                         fraglimit_override = cvar("g_ctf_capture_limit");
251                         leadlimit_override = cvar("g_ctf_capture_leadlimit");
252                 }
253                 else
254                 {
255                         fraglimit_override = cvar("capturelimit_override");
256                         leadlimit_override = cvar("captureleadlimit_override");
257                 }
258                 ctf_init();
259                 have_team_spawns = -1; // request team spawns
260         }
261
262         if(g_runematch)
263         {
264                 game = GAME_RUNEMATCH;
265                 gamemode_name = "Rune Match";
266                 if(cvar("deathmatch_force_teamplay"))
267                         ActivateTeamplay();
268                 fraglimit_override = cvar("g_runematch_point_limit");
269                 leadlimit_override = cvar("g_runematch_point_leadlimit");
270                 runematch_init();
271         }
272
273         if(g_lms)
274         {
275                 game = GAME_LMS;
276                 gamemode_name = "Last Man Standing";
277                 fraglimit_override = cvar("g_lms_lives_override");
278                 leadlimit_override = 0; // not supported by LMS
279                 if(fraglimit_override == 0)
280                         fraglimit_override = -1;
281                 lms_lowest_lives = 9999;
282                 lms_next_place = 0;
283                 ScoreRules_lms();
284         }
285
286         if(g_arena)
287         {
288                 game = GAME_ARENA;
289                 gamemode_name = "Arena";
290                 fraglimit_override = cvar("g_arena_point_limit");
291                 leadlimit_override = cvar("g_arena_point_leadlimit");
292                 maxspawned = cvar("g_arena_maxspawned");
293                 if(maxspawned < 2)
294                         maxspawned = 2;
295                 arena_roundbased = cvar("g_arena_roundbased");
296         }
297
298         if(g_ca)
299         {
300                 game = GAME_CA;
301                 gamemode_name = "Clan Arena";
302                 ActivateTeamplay();
303                 fraglimit_override = cvar("g_ca_point_limit");
304                 leadlimit_override = cvar("g_ca_point_leadlimit");
305                 precache_sound("ctf/red_capture.wav");
306                 precache_sound("ctf/blue_capture.wav");
307         }
308         if(g_keyhunt)
309         {
310                 game = GAME_KEYHUNT;
311                 gamemode_name = "Key Hunt";
312                 ActivateTeamplay();
313                 fraglimit_override = cvar("g_keyhunt_point_limit");
314                 leadlimit_override = cvar("g_keyhunt_point_leadlimit");
315                 MUTATOR_ADD(gamemode_keyhunt);
316         }
317
318         if(g_assault)
319         {
320                 game = GAME_ASSAULT;
321                 gamemode_name = "Assault";
322                 ActivateTeamplay();
323                 ScoreRules_assault();
324                 have_team_spawns = -1; // request team spawns
325         }
326
327         if(g_onslaught)
328         {
329                 game = GAME_ONSLAUGHT;
330                 gamemode_name = "Onslaught";
331                 ActivateTeamplay();
332                 have_team_spawns = -1; // request team spawns
333         }
334
335         if(g_race)
336         {
337                 game = GAME_RACE;
338                 gamemode_name = "Race";
339
340                 if(cvar("g_race_teams"))
341                 {
342                         ActivateTeamplay();
343                         race_teams = bound(2, cvar("g_race_teams"), 4);
344                         have_team_spawns = -1; // request team spawns
345                 }
346                 else
347                         race_teams = 0;
348
349                 qualifying_override = cvar("g_race_qualifying_timelimit_override");
350                 fraglimit_override = cvar("g_race_laps_limit");
351                 leadlimit_override = 0; // currently not supported by race
352         }
353
354         if(g_cts)
355         {
356                 game = GAME_CTS;
357                 gamemode_name = "CTS";
358                 g_race_qualifying = 1;
359                 fraglimit_override = 0;
360                 leadlimit_override = 0;
361         }
362
363         if(g_nexball)
364         {
365                 game = GAME_NEXBALL;
366                 gamemode_name = "Nexball";
367                 fraglimit_override = cvar("g_nexball_goallimit");
368                 leadlimit_override = cvar("g_nexball_goalleadlimit");
369                 ActivateTeamplay();
370                 nb_init();
371                 have_team_spawns = -1; // request team spawns
372         }
373
374         if(teams_matter)
375                 entcs_init();
376
377         // save it (for the next startup)
378         cvar_set("gamecfg", ftos(game));
379
380         cache_mutatormsg = strzone("");
381         cache_lastmutatormsg = strzone("");
382
383         // enforce the server's universal frag/time limits
384         if(!cvar("g_campaign"))
385         {
386                 if(fraglimit_override >= 0)
387                         cvar_set("fraglimit", ftos(fraglimit_override));
388                 if(timelimit_override >= 0)
389                         cvar_set("timelimit", ftos(timelimit_override));
390                 if(leadlimit_override >= 0)
391                         cvar_set("leadlimit", ftos(leadlimit_override));
392                 if(qualifying_override >= 0)
393                         cvar_set("g_race_qualifying_timelimit", ftos(qualifying_override));
394         }
395
396         if(g_race)
397         {
398                 // we need to find out the correct value for g_race_qualifying
399                 if(cvar("g_campaign"))
400                 {
401                         g_race_qualifying = 1;
402                 }
403                 else if(!cvar("g_campaign") && cvar("g_race_qualifying_timelimit") > 0)
404                 {
405                         g_race_qualifying = 2;
406                         race_fraglimit = cvar("fraglimit");
407                         race_leadlimit = cvar("leadlimit");
408                         race_timelimit = cvar("timelimit");
409                         cvar_set("fraglimit", "0");
410                         cvar_set("leadlimit", "0");
411                         cvar_set("timelimit", cvar_string("g_race_qualifying_timelimit"));
412                 }
413                 else
414                         g_race_qualifying = 0;
415         }
416
417         if(g_race || g_cts)
418         {
419                 if(g_race_qualifying)
420                         independent_players = 1;
421
422                 ScoreRules_race();
423         }
424
425         InitializeEntity(world, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
426 }
427
428 string GetClientVersionMessage() {
429         local string versionmsg;
430         if (self.version_mismatch) {
431                 if(self.version < cvar("gameversion")) {
432                         versionmsg = "^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8";
433                 } else {
434                         versionmsg = "^3This server is using an outdated Xonotic version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8";
435                 }
436         } else {
437                 versionmsg = "^2client version and server version are compatible.^8";
438         }
439         return versionmsg;
440 }
441
442
443 void PrintWelcomeMessage(entity pl)
444 {
445         string s, modifications, motd;
446
447         if(self.cvar_scr_centertime == 0) return;
448
449         if(cvar("g_campaign"))
450         {
451                 if(self.classname == "player" && !self.BUTTON_INFO)
452                         return;
453         }
454         else
455         {
456                 if((time - self.jointime) > cvar("welcome_message_time") && !self.BUTTON_INFO)
457                         return;
458         }
459
460         if( !(timeoutStatus >= 1) ) { //really print the WelcomeMessage to the player every frame when timeout-seconds are shown or the game is restarted, to make sure that the shown number is accurate
461                 if(self.welcomemessage_time > time) return;
462                 self.welcomemessage_time = time + max(0.5, self.cvar_scr_centertime * 0.6);
463         }
464
465         if(cvar("g_campaign"))
466         {
467                 centerprint(pl, campaign_message);
468                 return;
469         }
470
471 //TODO GreEn`mArine: make the timeout-messages clientside as well (just like the ready restart countdown)!
472         if(!self.BUTTON_INFO)
473         {
474                 // TODO get rid of this too
475                 local string specString;
476                 specString = NEWLINES;
477                 //if(time < game_starttime) //also show the countdown when being a spectator
478                 //      specString = strcat(specString, "\n\n^1Game starts in ", ftos(ceil(game_starttime - time)), " seconds^7");
479                 //else
480                 if (timeoutStatus != 0)
481                         specString = strcat(specString, "\n\n", getTimeoutText(1));
482                 else
483                 {
484                         if(self.classname == "player")
485                                 return;
486                         goto normal;
487                 }
488                 return centerprint_atprio(self, CENTERPRIO_SPAM, specString);
489         }
490
491 :normal
492         ret_string = "";
493         MUTATOR_CALLHOOK(BuildMutatorsPrettyString);
494         modifications = ret_string;
495         
496         if(g_minstagib)
497                 modifications = strcat(modifications, ", MinstaGib");
498         if(g_weaponarena)
499         {
500                 if(g_weaponarena_random)
501                         modifications = strcat(modifications, ", ", ftos(g_weaponarena_random), " of ", g_weaponarena_list, " Arena");
502                 else
503                         modifications = strcat(modifications, ", ", g_weaponarena_list, " Arena");
504         }
505         if(cvar("g_start_weapon_laser") == 0)
506                 modifications = strcat(modifications, ", No start weapons");
507         if(cvar("sv_gravity") < 800)
508                 modifications = strcat(modifications, ", Low gravity");
509         if(g_cloaked)
510                 modifications = strcat(modifications, ", Cloaked");
511         if(g_footsteps)
512                 modifications = strcat(modifications, ", Steps");
513         if(g_grappling_hook)
514                 modifications = strcat(modifications, ", Hook");
515         if(g_laserguided_missile)
516                 modifications = strcat(modifications, ", LG missiles");
517         if(g_midair)
518                 modifications = strcat(modifications, ", Midair");
519         if(g_vampire)
520                 modifications = strcat(modifications, ", Vampire");
521         if(g_pinata)
522                 modifications = strcat(modifications, ", Pinata");
523         if(g_weapon_stay)
524                 modifications = strcat(modifications, ", Weapons stay");
525         if(g_bloodloss > 0)
526                 modifications = strcat(modifications, ", Bloodloss");
527         if(g_jetpack)
528                 modifications = strcat(modifications, ", Jet pack");
529         modifications = substring(modifications, 2, strlen(modifications) - 2);
530
531         local string versionmessage;
532         versionmessage = GetClientVersionMessage();
533
534         s = strcat(s, NEWLINES, "This is Xonotic ", cvar_string("g_xonoticversion"), "\n", versionmessage);
535         s = strcat(s, "^8\n\nmatch type is ^1", gamemode_name, "^8\n");
536
537         if(modifications != "")
538                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
539
540         if(timeoutStatus != 0)
541                 s = strcat(s, "\n\n", getTimeoutText(1));
542
543         if (g_grappling_hook)
544                 s = strcat(s, "\n\n^3grappling hook^8 is enabled, press 'e' to use it\n");
545
546         if(cache_lastmutatormsg != cvar_string("g_mutatormsg"))
547         {
548                 if(cache_lastmutatormsg)
549                         strunzone(cache_lastmutatormsg);
550                 if(cache_mutatormsg)
551                         strunzone(cache_mutatormsg);
552                 cache_lastmutatormsg = strzone(cvar_string("g_mutatormsg"));
553                 cache_mutatormsg = strzone(cache_lastmutatormsg);
554         }
555
556         if (cache_mutatormsg != "") {
557                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
558         }
559
560         motd = cvar_string("sv_motd");
561         if (motd != "") {
562                 s = strcat(s, "\n\n^8MOTD: ^7", strreplace("\\n", "\n", motd));
563         }
564         s = strcat(s, "\n");
565
566         centerprint(pl, s);
567 }
568
569
570 void SetPlayerColors(entity pl, float _color)
571 {
572         /*string s;
573         s = ftos(cl);
574         stuffcmd(pl, strcat("color ", s, " ", s, "\n")  );
575         pl.team = cl + 1;
576         //pl.clientcolors = pl.clientcolors - (pl.clientcolors & 15) + cl;
577         pl.clientcolors = 16*cl + cl;*/
578
579         float pants, shirt;
580         pants = _color & 0x0F;
581         shirt = _color & 0xF0;
582
583
584         if(teams_matter) {
585                 setcolor(pl, 16*pants + pants);
586         } else {
587                 setcolor(pl, shirt + pants);
588         }
589 }
590
591 void SetPlayerTeam(entity pl, float t, float s, float noprint)
592 {
593         float _color;
594
595         if(t == 4)
596                 _color = COLOR_TEAM4 - 1;
597         else if(t == 3)
598                 _color = COLOR_TEAM3 - 1;
599         else if(t == 2)
600                 _color = COLOR_TEAM2 - 1;
601         else
602                 _color = COLOR_TEAM1 - 1;
603
604         SetPlayerColors(pl,_color);
605
606         if(t != s) {
607                 LogTeamchange(pl.playerid, pl.team, 3);  // log manual team join
608
609                 if(!noprint)
610                 bprint(pl.netname, "^7 has changed from ", TeamNoName(s), " to ", TeamNoName(t), "\n");
611         }
612
613 }
614
615 // set c1...c4 to show what teams are allowed
616 void CheckAllowedTeams (entity for_whom)
617 {
618         float dm;
619         entity head;
620         string teament_name;
621
622         c1 = c2 = c3 = c4 = -1;
623         cb1 = cb2 = cb3 = cb4 = 0;
624
625         if(g_onslaught)
626         {
627                 // onslaught is special
628                 head = findchain(classname, "onslaught_generator");
629                 while (head)
630                 {
631                         if (head.team == COLOR_TEAM1) c1 = 0;
632                         if (head.team == COLOR_TEAM2) c2 = 0;
633                         if (head.team == COLOR_TEAM3) c3 = 0;
634                         if (head.team == COLOR_TEAM4) c4 = 0;
635                         head = head.chain;
636                 }
637         }
638         else if(g_domination)
639                 teament_name = "dom_team";
640         else if(g_ctf)
641                 teament_name = "ctf_team";
642         else if(g_tdm)
643                 teament_name = "tdm_team";
644         else if(g_nexball)
645                 teament_name = "nexball_team";
646         else if(g_assault)
647                 c1 = c2 = 0; // Assault always has 2 teams
648         else
649         {
650                 // cover anything else by treating it like tdm with no teams spawned
651                 if(g_race)
652                         dm = race_teams;
653                 else
654                         dm = 2;
655
656                 ret_float = dm;
657                 MUTATOR_CALLHOOK(GetTeamCount);
658                 dm = ret_float;
659
660                 if(dm >= 4)
661                         c1 = c2 = c3 = c4 = 0;
662                 else if(dm >= 3)
663                         c1 = c2 = c3 = 0;
664                 else
665                         c1 = c2 = 0;
666         }
667
668         // find out what teams are allowed if necessary
669         if(teament_name)
670         {
671                 head = find(world, classname, teament_name);
672                 while(head)
673                 {
674                         if(!(g_domination && head.netname == ""))
675                         {
676                                 if(head.team == COLOR_TEAM1)
677                                         c1 = 0;
678                                 else if(head.team == COLOR_TEAM2)
679                                         c2 = 0;
680                                 else if(head.team == COLOR_TEAM3)
681                                         c3 = 0;
682                                 else if(head.team == COLOR_TEAM4)
683                                         c4 = 0;
684                         }
685                         head = find(head, classname, teament_name);
686                 }
687         }
688
689         // TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
690         if(c3==-1&&c4==-1)
691         if(cvar("bot_vs_human") && for_whom)
692         {
693                 if(cvar("bot_vs_human") > 0)
694                 {
695                         // bots are all blue
696                         if(clienttype(for_whom) == CLIENTTYPE_BOT)
697                                 c1 = c3 = c4 = -1;
698                         else
699                                 c2 = -1;
700                 }
701                 else
702                 {
703                         // bots are all red
704                         if(clienttype(for_whom) == CLIENTTYPE_BOT)
705                                 c2 = c3 = c4 = -1;
706                         else
707                                 c1 = -1;
708                 }
709         }
710 }
711
712 float PlayerValue(entity p)
713 {
714         if(IsTeamBalanceForced() == 1)
715                 return 1;
716         return 1;
717 }
718
719 // c1...c4 should be set to -1 (not allowed) or 0 (allowed).
720 // teams that are allowed will now have their player counts stored in c1...c4
721 void GetTeamCounts(entity ignore)
722 {
723         entity head;
724         float value, bvalue;
725         // now count how many players are on each team already
726
727         // FIXME: also find and memorize the lowest-scoring bot on each team (in case players must be shuffled around)
728         // also remember the lowest-scoring player
729
730         FOR_EACH_PLAYER(head)
731         {
732                 if(head != ignore)// && head.netname != "")
733                 {
734                         value = PlayerValue(head);
735                         if(clienttype(head) == CLIENTTYPE_BOT)
736                                 bvalue = value;
737                         else
738                                 bvalue = 0;
739                         if(head.team == COLOR_TEAM1)
740                         {
741                                 if(c1 >= 0)
742                                 {
743                                         c1 = c1 + value;
744                                         cb1 = cb1 + bvalue;
745                                 }
746                         }
747                         if(head.team == COLOR_TEAM2)
748                         {
749                                 if(c2 >= 0)
750                                 {
751                                         c2 = c2 + value;
752                                         cb2 = cb2 + bvalue;
753                                 }
754                         }
755                         if(head.team == COLOR_TEAM3)
756                         {
757                                 if(c3 >= 0)
758                                 {
759                                         c3 = c3 + value;
760                                         cb3 = cb3 + bvalue;
761                                 }
762                         }
763                         if(head.team == COLOR_TEAM4)
764                         {
765                                 if(c4 >= 0)
766                                 {
767                                         c4 = c4 + value;
768                                         cb4 = cb4 + bvalue;
769                                 }
770                         }
771                 }
772         }
773 }
774
775 // returns # of smallest team (1, 2, 3, 4)
776 // NOTE: Assumes CheckAllowedTeams has already been called!
777 float FindSmallestTeam(entity pl, float ignore_pl)
778 {
779         float totalteams, balance_type, maxc;
780         totalteams = 0;
781
782         // find out what teams are available
783         //CheckAllowedTeams();
784
785         // make sure there are at least 2 teams to join
786         if(c1 >= 0)
787                 totalteams = totalteams + 1;
788         if(c2 >= 0)
789                 totalteams = totalteams + 1;
790         if(c3 >= 0)
791                 totalteams = totalteams + 1;
792         if(c4 >= 0)
793                 totalteams = totalteams + 1;
794
795         if(cvar("bot_vs_human"))
796                 totalteams += 1;
797
798         if(totalteams <= 1)
799         {
800                 if(g_domination)
801                         error("Too few teams available for domination\n");
802                 else if(g_ctf)
803                         error("Too few teams available for ctf\n");
804                 else if(g_keyhunt)
805                         error("Too few teams available for key hunt\n");
806                 else
807                         error("Too few teams available for team deathmatch\n");
808         }
809
810         // count how many players are in each team
811         if(ignore_pl)
812                 GetTeamCounts(pl);
813         else
814                 GetTeamCounts(world);
815
816         // c1...c4 now have counts of each team
817         // figure out which is smallest, giving priority to the team the player is already on as a tie-breaker
818
819         // 2 gives priority to what team you're already on, 1 goes in order
820         // 2 doesn't seem to work though...
821         balance_type = 1;
822
823         if(bots_would_leave)
824         //if(pl.classname != "player")
825         if(clienttype(pl) != CLIENTTYPE_BOT)
826         {
827                 c1 -= cb1 * 255.0/256.0;
828                 c2 -= cb2 * 255.0/256.0;
829                 c3 -= cb3 * 255.0/256.0;
830                 c4 -= cb4 * 255.0/256.0;
831         }
832         maxc = max4(c1, c2, c3, c4);
833
834         RandomSelection_Init();
835         if(balance_type == 1)
836         {
837                 // 1: use team count, then score (note: can only use 8 significant bits of score)
838                 if(c1 >= 0) RandomSelection_Add(world, 1, string_null, 1, (maxc - c1) + float2range01(-team1_score) / 256.0);
839                 if(c2 >= 0) RandomSelection_Add(world, 2, string_null, 1, (maxc - c2) + float2range01(-team2_score) / 256.0);
840                 if(c3 >= 0) RandomSelection_Add(world, 3, string_null, 1, (maxc - c3) + float2range01(-team3_score) / 256.0);
841                 if(c4 >= 0) RandomSelection_Add(world, 4, string_null, 1, (maxc - c4) + float2range01(-team4_score) / 256.0);
842         }
843         else if(balance_type == 2)
844         {
845                 // 1: use team count, if equal prefer own team
846                 if(c1 >= 0) RandomSelection_Add(world, 1, string_null, 1, (maxc - c1) + (self.team == COLOR_TEAM1) / 512.0);
847                 if(c2 >= 0) RandomSelection_Add(world, 1, string_null, 1, (maxc - c1) + (self.team == COLOR_TEAM2) / 512.0);
848                 if(c3 >= 0) RandomSelection_Add(world, 1, string_null, 1, (maxc - c1) + (self.team == COLOR_TEAM3) / 512.0);
849                 if(c4 >= 0) RandomSelection_Add(world, 1, string_null, 1, (maxc - c1) + (self.team == COLOR_TEAM4) / 512.0);
850         }
851         else if(balance_type == 3)
852         {
853                 // 1: use team count, then score, if equal prefer own team (probably fails due to float accuracy problems)
854                 if(c1 >= 0) RandomSelection_Add(world, 1, string_null, 1, (maxc - c1) + float2range01(-team1_score + 0.5 * (self.team == COLOR_TEAM1)) / 256.0);
855                 if(c2 >= 0) RandomSelection_Add(world, 2, string_null, 1, (maxc - c2) + float2range01(-team2_score + 0.5 * (self.team == COLOR_TEAM2)) / 256.0);
856                 if(c3 >= 0) RandomSelection_Add(world, 3, string_null, 1, (maxc - c3) + float2range01(-team3_score + 0.5 * (self.team == COLOR_TEAM3)) / 256.0);
857                 if(c4 >= 0) RandomSelection_Add(world, 4, string_null, 1, (maxc - c4) + float2range01(-team4_score + 0.5 * (self.team == COLOR_TEAM4)) / 256.0);
858         }
859         return RandomSelection_chosen_float;
860 }
861
862 float JoinBestTeam(entity pl, float only_return_best, float forcebestteam)
863 {
864         float smallest, selectedteam;
865
866         // don't join a team if we're not playing a team game
867         if(!teams_matter)
868                 return 0;
869
870         // find out what teams are available
871         CheckAllowedTeams(pl);
872
873         // if we don't care what team he ends up on, put him on whatever team he entered as.
874         // if he's not on a valid team, then let other code put him on the smallest team
875         if(!forcebestteam)
876         {
877                 if(     c1 >= 0 && pl.team == COLOR_TEAM1)
878                         selectedteam = pl.team;
879                 else if(c2 >= 0 && pl.team == COLOR_TEAM2)
880                         selectedteam = pl.team;
881                 else if(c3 >= 0 && pl.team == COLOR_TEAM3)
882                         selectedteam = pl.team;
883                 else if(c4 >= 0 && pl.team == COLOR_TEAM4)
884                         selectedteam = pl.team;
885                 else
886                         selectedteam = -1;
887
888                 if(selectedteam > 0)
889                 {
890                         if(!only_return_best)
891                         {
892                                 SetPlayerColors(pl, selectedteam - 1);
893
894                                 // when JoinBestTeam is called by client.qc/ClientKill_Now_TeamChange the players team is -1 and thus skipped
895                                 // when JoinBestTeam is called by cl_client.qc/ClientConnect the player_id is 0 the log attempt is rejected
896                                 LogTeamchange(pl.playerid, pl.team, 99);
897                         }
898                         return selectedteam;
899                 }
900                 // otherwise end up on the smallest team (handled below)
901         }
902
903         smallest = FindSmallestTeam(pl, TRUE);
904
905         if(!only_return_best)
906         {
907                 TeamchangeFrags(self);
908                 if(smallest == 1)
909                 {
910                         SetPlayerColors(pl, COLOR_TEAM1 - 1);
911                 }
912                 else if(smallest == 2)
913                 {
914                         SetPlayerColors(pl, COLOR_TEAM2 - 1);
915                 }
916                 else if(smallest == 3)
917                 {
918                         SetPlayerColors(pl, COLOR_TEAM3 - 1);
919                 }
920                 else if(smallest == 4)
921                 {
922                         SetPlayerColors(pl, COLOR_TEAM4 - 1);
923                 }
924                 else
925                 {
926                         error("smallest team: invalid team\n");
927                 }
928
929                 LogTeamchange(pl.playerid, pl.team, 2); // log auto join
930
931                 if(pl.deadflag == DEAD_NO)
932                         Damage(pl, pl, pl, 100000, DEATH_TEAMCHANGE, pl.origin, '0 0 0');
933         }
934
935         return smallest;
936 }
937
938 //void() ctf_playerchanged;
939 void SV_ChangeTeam(float _color)
940 {
941         float scolor, dcolor, steam, dteam, dbotcount, scount, dcount;
942
943         // in normal deathmatch we can just apply the color and we're done
944         if(!teams_matter) {
945                 SetPlayerColors(self, _color);
946                 return;
947         }
948
949         scolor = self.clientcolors & 0x0F;
950         dcolor = _color & 0x0F;
951
952         if(scolor == COLOR_TEAM1 - 1)
953                 steam = 1;
954         else if(scolor == COLOR_TEAM2 - 1)
955                 steam = 2;
956         else if(scolor == COLOR_TEAM3 - 1)
957                 steam = 3;
958         else // if(scolor == COLOR_TEAM4 - 1)
959                 steam = 4;
960         if(dcolor == COLOR_TEAM1 - 1)
961                 dteam = 1;
962         else if(dcolor == COLOR_TEAM2 - 1)
963                 dteam = 2;
964         else if(dcolor == COLOR_TEAM3 - 1)
965                 dteam = 3;
966         else // if(dcolor == COLOR_TEAM4 - 1)
967                 dteam = 4;
968
969         CheckAllowedTeams(self);
970
971         if(dteam == 1 && c1 < 0) dteam = 4;
972         if(dteam == 4 && c4 < 0) dteam = 3;
973         if(dteam == 3 && c3 < 0) dteam = 2;
974         if(dteam == 2 && c2 < 0) dteam = 1;
975
976         // not changing teams
977         if(scolor == dcolor)
978         {
979                 //bprint("same team change\n");
980                 SetPlayerTeam(self, dteam, steam, TRUE);
981                 return;
982         }
983
984         if((cvar("g_campaign")) || (cvar("g_changeteam_banned") && self.wasplayer)) {
985                 sprint(self, "Team changes not allowed\n");
986                 return; // changing teams is not allowed
987         }
988
989         if(cvar("g_balance_teams_prevent_imbalance"))
990         {
991                 // only allow changing to a smaller or equal size team
992
993                 // find out what teams are available
994                 //CheckAllowedTeams();
995                 // count how many players on each team
996                 GetTeamCounts(world);
997
998                 // get desired team
999                 if(dteam == 1 && c1 >= 0)//dcolor == COLOR_TEAM1 - 1)
1000                 {
1001                         dcount = c1;
1002                         dbotcount = cb1;
1003                 }
1004                 else if(dteam == 2 && c2 >= 0)//dcolor == COLOR_TEAM2 - 1)
1005                 {
1006                         dcount = c2;
1007                         dbotcount = cb2;
1008                 }
1009                 else if(dteam == 3 && c3 >= 0)//dcolor == COLOR_TEAM3 - 1)
1010                 {
1011                         dcount = c3;
1012                         dbotcount = cb3;
1013                 }
1014                 else if(dteam == 4 && c4 >= 0)//dcolor == COLOR_TEAM4 - 1)
1015                 {
1016                         dcount = c4;
1017                         dbotcount = cb4;
1018                 }
1019                 else
1020                 {
1021                         sprint(self, "Cannot change to an invalid team\n");
1022
1023                         return;
1024                 }
1025
1026                 // get starting team
1027                 if(steam == 1)//scolor == COLOR_TEAM1 - 1)
1028                         scount = c1;
1029                 else if(steam == 2)//scolor == COLOR_TEAM2 - 1)
1030                         scount = c2;
1031                 else if(steam == 3)//scolor == COLOR_TEAM3 - 1)
1032                         scount = c3;
1033                 else if(steam == 4)//scolor == COLOR_TEAM4 - 1)
1034                         scount = c4;
1035
1036                 if(scount) // started at a valid, nonempty team
1037                 {
1038                         // check if we're trying to change to a larger team that doens't have bots to swap with
1039                         if(dcount >= scount && dbotcount <= 0)
1040                         {
1041                                 sprint(self, "Cannot change to a larger team\n");
1042                                 return; // can't change to a larger team
1043                         }
1044                 }
1045         }
1046
1047 //      bprint("allow change teams from ", ftos(steam), " to ", ftos(dteam), "\n");
1048
1049         if(self.classname == "player" && steam != dteam)
1050         {
1051                 // reduce frags during a team change
1052                 TeamchangeFrags(self);
1053         }
1054
1055         SetPlayerTeam(self, dteam, steam, FALSE);
1056
1057         if(self.classname == "player" && steam != dteam)
1058         {
1059                 // kill player when changing teams
1060                 if(self.deadflag == DEAD_NO)
1061                         Damage(self, self, self, 100000, DEATH_TEAMCHANGE, self.origin, '0 0 0');
1062         }
1063         //ctf_playerchanged();
1064 }
1065
1066 void ShufflePlayerOutOfTeam (float source_team)
1067 {
1068         float smallestteam, smallestteam_count, steam;
1069         float lowest_bot_score, lowest_player_score;
1070         entity head, lowest_bot, lowest_player, selected;
1071
1072         smallestteam = 0;
1073         smallestteam_count = 999999999;
1074
1075         if(c1 >= 0 && c1 < smallestteam_count)
1076         {
1077                 smallestteam = 1;
1078                 smallestteam_count = c1;
1079         }
1080         if(c2 >= 0 && c2 < smallestteam_count)
1081         {
1082                 smallestteam = 2;
1083                 smallestteam_count = c2;
1084         }
1085         if(c3 >= 0 && c3 < smallestteam_count)
1086         {
1087                 smallestteam = 3;
1088                 smallestteam_count = c3;
1089         }
1090         if(c4 >= 0 && c4 < smallestteam_count)
1091         {
1092                 smallestteam = 4;
1093                 smallestteam_count = c4;
1094         }
1095
1096         if(!smallestteam)
1097         {
1098                 bprint("warning: no smallest team\n");
1099                 return;
1100         }
1101
1102         if(source_team == 1)
1103                 steam = COLOR_TEAM1;
1104         else if(source_team == 2)
1105                 steam = COLOR_TEAM2;
1106         else if(source_team == 3)
1107                 steam = COLOR_TEAM3;
1108         else if(source_team == 4)
1109                 steam = COLOR_TEAM4;
1110
1111         lowest_bot = world;
1112         lowest_bot_score = 999999999;
1113         lowest_player = world;
1114         lowest_player_score = 999999999;
1115
1116         // find the lowest-scoring player & bot of that team
1117         FOR_EACH_PLAYER(head)
1118         {
1119                 if(head.team == steam)
1120                 {
1121                         if(head.isbot)
1122                         {
1123                                 if(head.totalfrags < lowest_bot_score)
1124                                 {
1125                                         lowest_bot = head;
1126                                         lowest_bot_score = head.totalfrags;
1127                                 }
1128                         }
1129                         else
1130                         {
1131                                 if(head.totalfrags < lowest_player_score)
1132                                 {
1133                                         lowest_player = head;
1134                                         lowest_player_score = head.totalfrags;
1135                                 }
1136                         }
1137                 }
1138         }
1139
1140         // prefers to move a bot...
1141         if(lowest_bot != world)
1142                 selected = lowest_bot;
1143         // but it will move a player if it has to
1144         else
1145                 selected = lowest_player;
1146         // don't do anything if it couldn't find anyone
1147         if(!selected)
1148         {
1149                 bprint("warning: couldn't find a player to move from team\n");
1150                 return;
1151         }
1152
1153         // smallest team gains a member
1154         if(smallestteam == 1)
1155         {
1156                 c1 = c1 + 1;
1157         }
1158         else if(smallestteam == 2)
1159         {
1160                 c2 = c2 + 1;
1161         }
1162         else if(smallestteam == 3)
1163         {
1164                 c3 = c3 + 1;
1165         }
1166         else if(smallestteam == 4)
1167         {
1168                 c4 = c4 + 1;
1169         }
1170         else
1171         {
1172                 bprint("warning: destination team invalid\n");
1173                 return;
1174         }
1175         // source team loses a member
1176         if(source_team == 1)
1177         {
1178                 c1 = c1 + 1;
1179         }
1180         else if(source_team == 2)
1181         {
1182                 c2 = c2 + 2;
1183         }
1184         else if(source_team == 3)
1185         {
1186                 c3 = c3 + 3;
1187         }
1188         else if(source_team == 4)
1189         {
1190                 c4 = c4 + 4;
1191         }
1192         else
1193         {
1194                 bprint("warning: source team invalid\n");
1195                 return;
1196         }
1197
1198         // move the player to the new team
1199         TeamchangeFrags(selected);
1200         SetPlayerTeam(selected, smallestteam, source_team, FALSE);
1201
1202         if(selected.deadflag == DEAD_NO)
1203                 Damage(selected, selected, selected, 100000, DEATH_AUTOTEAMCHANGE, selected.origin, '0 0 0');
1204         centerprint(selected, strcat("You have been moved into a different team to improve team balance\nYou are now on: ", ColoredTeamName(selected.team)));
1205 }
1206
1207 void CauseRebalance(float source_team, float howmany_toomany)
1208 {
1209         if(IsTeamBalanceForced() == 1)
1210         {
1211                 bprint("Rebalancing Teams\n");
1212                 ShufflePlayerOutOfTeam(source_team);
1213         }
1214 }
1215
1216 // part of g_balance_teams_force
1217 // occasionally perform an audit of the teams to make
1218 // sure they're more or less balanced in player count.
1219 void AuditTeams()
1220 {
1221         float numplayers, numteams, smallest, toomany;
1222         float balance;
1223         balance = IsTeamBalanceForced();
1224         if(balance == 0)
1225                 return;
1226
1227         if(audit_teams_time > time)
1228                 return;
1229
1230         audit_teams_time = time + 4 + random();
1231
1232 //      bprint("Auditing teams\n");
1233
1234         CheckAllowedTeams(world);
1235         GetTeamCounts(world);
1236
1237
1238         numteams = numplayers = smallest = 0;
1239         if(c1 >= 0)
1240         {
1241                 numteams = numteams + 1;
1242                 numplayers = numplayers + c1;
1243                 smallest = c1;
1244         }
1245         if(c2 >= 0)
1246         {
1247                 numteams = numteams + 1;
1248                 numplayers = numplayers + c2;
1249                 if(c2 < smallest)
1250                         smallest = c2;
1251         }
1252         if(c3 >= 0)
1253         {
1254                 numteams = numteams + 1;
1255                 numplayers = numplayers + c3;
1256                 if(c3 < smallest)
1257                         smallest = c3;
1258         }
1259         if(c4 >= 0)
1260         {
1261                 numteams = numteams + 1;
1262                 numplayers = numplayers + c4;
1263                 if(c4 < smallest)
1264                         smallest = c4;
1265         }
1266
1267         if(numplayers <= 0)
1268                 return; // no players to move around
1269         if(numteams < 2)
1270                 return; // don't bother shuffling if for some reason there aren't any teams
1271
1272         toomany = smallest + 1;
1273
1274         if(c1 && c1 > toomany)
1275                 CauseRebalance(1, c1 - toomany);
1276         if(c2 && c2 > toomany)
1277                 CauseRebalance(2, c2 - toomany);
1278         if(c3 && c3 > toomany)
1279                 CauseRebalance(3, c3 - toomany);
1280         if(c4 && c4 > toomany)
1281                 CauseRebalance(4, c4 - toomany);
1282
1283         // if teams are still unbalanced, balance them further in the next audit,
1284         // which will happen sooner (keep doing rapid audits until things are in order)
1285         audit_teams_time = time + 0.7 + random()*0.3;
1286 }
1287
1288 // code from here on is just to support maps that don't have team entities
1289 void tdm_spawnteam (string teamname, float teamcolor)
1290 {
1291         local entity e;
1292         e = spawn();
1293         e.classname = "tdm_team";
1294         e.netname = teamname;
1295         e.cnt = teamcolor;
1296         e.team = e.cnt + 1;
1297 };
1298
1299 // spawn some default teams if the map is not set up for tdm
1300 void tdm_spawnteams()
1301 {
1302         float numteams;
1303
1304         numteams = cvar("g_tdm_teams_override");
1305         if(numteams < 2)
1306                 numteams = cvar("g_tdm_teams");
1307         numteams = bound(2, numteams, 4);
1308
1309         tdm_spawnteam("Red", COLOR_TEAM1-1);
1310         tdm_spawnteam("Blue", COLOR_TEAM2-1);
1311         if(numteams >= 3)
1312                 tdm_spawnteam("Yellow", COLOR_TEAM3-1);
1313         if(numteams >= 4)
1314                 tdm_spawnteam("Pink", COLOR_TEAM4-1);
1315 };
1316
1317 void tdm_delayedinit()
1318 {
1319         // if no teams are found, spawn defaults
1320         if (find(world, classname, "tdm_team") == world)
1321                 tdm_spawnteams();
1322 };
1323
1324 void tdm_init()
1325 {
1326         InitializeEntity(world, tdm_delayedinit, INITPRIO_GAMETYPE);
1327 };