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