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