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