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