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