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