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