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