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