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