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