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