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