]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/mutators/gamemode_ctf.qc
Fix quite a lot of bugs/finish bringing back the old features. MIGHT be stable now...
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / mutators / gamemode_ctf.qc
1 // ================================================================
2 //  Official capture the flag game mode coding, reworked by Samual
3 //  Last updated: March 27th, 2012
4 // ================================================================
5
6 float ctf_ReadScore(string parameter) // make this obsolete
7 {
8         //if(g_ctf_win_mode != 2)
9                 return cvar(strcat("g_ctf_personal", parameter));
10         //else
11         //      return cvar(strcat("g_ctf_flag", parameter));
12 }
13
14 void ctf_FakeTimeLimit(entity e, float t)
15 {
16         msg_entity = e;
17         WriteByte(MSG_ONE, 3); // svc_updatestat
18         WriteByte(MSG_ONE, 236); // STAT_TIMELIMIT
19         if(t < 0)
20                 WriteCoord(MSG_ONE, autocvar_timelimit);
21         else
22                 WriteCoord(MSG_ONE, (t + 1) / 60);
23 }
24
25 void ctf_EventLog(string mode, float flagteam, entity actor) // use an alias for easy changing and quick editing later
26 {
27         if(autocvar_sv_eventlog)
28                 GameLogEcho(strcat(":ctf:", mode, ":", ftos(flagteam), ((actor != world) ? (strcat(":", ftos(actor.playerid))) : "")));
29 }
30
31
32 // =======================
33 // CaptureShield Functions 
34 // =======================
35
36 float ctf_CaptureShield_CheckStatus(entity p) 
37 {
38         float s, se;
39         entity e;
40         float players_worseeq, players_total;
41
42         if(ctf_captureshield_max_ratio <= 0)
43                 return FALSE;
44
45         s = PlayerScore_Add(p, SP_SCORE, 0);
46         if(s >= -ctf_captureshield_min_negscore)
47                 return FALSE;
48
49         players_total = players_worseeq = 0;
50         FOR_EACH_PLAYER(e)
51         {
52                 if(e.team != p.team)
53                         continue;
54                 se = PlayerScore_Add(e, SP_SCORE, 0);
55                 if(se <= s)
56                         ++players_worseeq;
57                 ++players_total;
58         }
59
60         // player is in the worse half, if >= half the players are better than him, or consequently, if < half of the players are worse
61         // use this rule here
62         
63         if(players_worseeq >= players_total * ctf_captureshield_max_ratio)
64                 return FALSE;
65
66         return TRUE;
67 }
68
69 void ctf_CaptureShield_Update(entity player, float wanted_status)
70 {
71         float updated_status = ctf_CaptureShield_CheckStatus(player);
72         if((wanted_status == player.ctf_captureshielded) && (updated_status != wanted_status)) // 0: shield only, 1: unshield only
73         {
74                 if(updated_status) // TODO csqc notifier for this // Samual: How?
75                         Send_CSQC_Centerprint_Generic(player, CPID_CTF_CAPTURESHIELD, "^3You are now ^4shielded^3 from the flag\n^3for ^1too many unsuccessful attempts^3 to capture.\n\n^3Make some defensive scores before trying again.", 5, 0);
76                 else
77                         Send_CSQC_Centerprint_Generic(player, CPID_CTF_CAPTURESHIELD, "^3You are now free.\n\n^3Feel free to ^1try to capture^3 the flag again\n^3if you think you will succeed.", 5, 0);
78                         
79                 player.ctf_captureshielded = updated_status;
80         }
81 }
82
83 float ctf_CaptureShield_Customize()
84 {
85         if not(other.ctf_captureshielded)
86                 return FALSE;
87         if(self.team == other.team)
88                 return FALSE;
89         return TRUE;
90 }
91
92 void ctf_CaptureShield_Touch()
93 {
94         if not(other.ctf_captureshielded)
95                 return;
96         if(self.team == other.team)
97                 return;
98         vector mymid;
99         vector othermid;
100         mymid = (self.absmin + self.absmax) * 0.5;
101         othermid = (other.absmin + other.absmax) * 0.5;
102         Damage(other, self, self, 0, DEATH_HURTTRIGGER, mymid, normalize(othermid - mymid) * ctf_captureshield_force);
103         Send_CSQC_Centerprint_Generic(other, CPID_CTF_CAPTURESHIELD, "^3You are ^4shielded^3 from the flag\n^3for ^1too many unsuccessful attempts^3 to capture.\n\n^3Get some defensive scores before trying again.", 5, 0);
104 }
105
106 void ctf_CaptureShield_Spawn(entity flag)
107 {
108         entity e;
109         e = spawn();
110         e.enemy = self;
111         e.team = self.team;
112         e.touch = ctf_CaptureShield_Touch;
113         e.customizeentityforclient = ctf_CaptureShield_Customize;
114         e.classname = "ctf_captureshield";
115         e.effects = EF_ADDITIVE;
116         e.movetype = MOVETYPE_NOCLIP;
117         e.solid = SOLID_TRIGGER;
118         e.avelocity = '7 0 11';
119         setorigin(e, self.origin);
120         setmodel(e, "models/ctf/shield.md3");
121         e.scale = 0.5;
122         setsize(e, e.scale * e.mins, e.scale * e.maxs);
123 }
124
125
126 // ==============
127 // Event Handlers
128 // ==============
129
130 void ctf_Handle_Drop(entity player)
131 {
132         entity flag = player.flagcarried;
133
134         if(!flag) { return; }
135         if(flag.speedrunning) { ctf_RespawnFlag(flag); return; }
136         
137         // reset the flag
138         setattachment(flag, world, "");
139         setorigin(flag, player.origin - '0 0 24' + '0 0 37');
140         flag.owner.flagcarried = world;
141         flag.owner = world;
142         flag.movetype = MOVETYPE_TOSS;
143         flag.solid = SOLID_TRIGGER;
144         flag.takedamage = DAMAGE_YES;
145         flag.velocity = ('0 0 200' + ('0 100 0' * crandom()) + ('100 0 0' * crandom()));
146         flag.pain_finished = time + autocvar_g_ctf_flag_returntime; // replace this later
147         
148         flag.ctf_droptime = time;
149         flag.ctf_dropperid = player.playerid;
150         flag.ctf_status = FLAG_DROPPED;
151
152         // messages and sounds
153         Send_KillNotification(player.netname, flag.netname, "", INFO_LOSTFLAG, MSG_INFO);
154         sound(flag, CH_TRIGGER, flag.noise4, VOL_BASE, ATTN_NONE);
155         ctf_EventLog("dropped", player.team, player);
156         
157         // scoring
158         PlayerTeamScore_AddScore(player, -ctf_ReadScore("penalty_drop"));       
159         PlayerScore_Add(player, SP_CTF_DROPS, 1);
160
161         // waypoints
162         WaypointSprite_Spawn("flagdropped", 0, 0, flag, '0 0 64', world, player.team, flag, wps_flagdropped, FALSE, RADARICON_FLAG, '0 1 1'); // (COLOR_TEAM1 + COLOR_TEAM2 - flag.team)
163         WaypointSprite_Ping(player.wps_flagcarrier);
164         WaypointSprite_Kill(player.wps_flagcarrier);
165
166         // captureshield
167         ctf_CaptureShield_Update(player, 0); // shield only
168
169         // check if the flag will fall off the map
170         trace_startsolid = FALSE;
171         tracebox(flag.origin, flag.mins, flag.maxs, flag.origin, TRUE, flag);
172         if(trace_startsolid)
173                 dprint("FLAG FALLTHROUGH will happen SOON\n");
174 }
175
176 void ctf_Handle_Capture(entity flag, entity player)
177 {
178         // declarations
179         float cap_time, cap_record, success;
180         string cap_message, refername;
181
182         // records
183         if((autocvar_g_ctf_captimerecord_always) || (player_count - currentbots)) {
184                 cap_record = ctf_captimerecord;
185                 cap_time = (time - player.flagcarried.ctf_pickuptime);
186
187                 refername = db_get(ServerProgsDB, strcat(GetMapname(), "/captimerecord/netname"));
188                 refername = ((refername == player.netname) ? "their" : strcat(refername, "^7's"));
189
190                 if(!ctf_captimerecord) 
191                         { cap_message = strcat(" in ", ftos_decimals(cap_time, 2), " seconds"); success = TRUE; }
192                 else if(cap_time < cap_record) 
193                         { cap_message = strcat(" in ", ftos_decimals(cap_time, 2), " seconds, breaking ", refername, " previous record of ", ftos_decimals(cap_record, 2), " seconds"); success = TRUE; }
194                 else
195                         { cap_message = strcat(" in ", ftos_decimals(cap_time, 2), " seconds, failing to break ", refername, " record of ", ftos_decimals(cap_record, 2), " seconds"); success = FALSE; }
196
197                 if(success) {
198                         ctf_captimerecord = cap_time;
199                         db_put(ServerProgsDB, strcat(GetMapname(), "/captimerecord/time"), ftos(cap_time));
200                         db_put(ServerProgsDB, strcat(GetMapname(), "/captimerecord/netname"), player.netname);
201                         write_recordmarker(player, (time - cap_time), cap_time); } }
202         
203         // messages and sounds
204         Send_KillNotification(player.netname, player.flagcarried.netname, cap_message, INFO_CAPTUREFLAG, MSG_INFO);
205         sound(player, CH_TRIGGER, flag.noise2, VOL_BASE, ATTN_NONE); // "ctf/*_capture.wav"
206         ctf_EventLog("capture", player.flagcarried.team, player);
207         
208         // scoring
209         PlayerTeamScore_AddScore(player, ctf_ReadScore("score_capture"));
210         PlayerTeamScore_Add(player, SP_CTF_CAPS, ST_CTF_CAPS, 1);
211
212         // effects
213         if (autocvar_g_ctf_flag_capture_effects) 
214         {
215                 pointparticles(particleeffectnum((player.team == COLOR_TEAM1) ? "red_ground_quake" : "blue_ground_quake"), flag.origin, '0 0 0', 1);
216                 //shockwave_spawn("models/ctf/shockwavetransring.md3", flag.origin - '0 0 15', -0.8, 0, 1);
217         }
218
219         // waypointsprites
220         WaypointSprite_Kill(player.wps_flagcarrier);
221
222         // reset the flag
223         if(flag.speedrunning) { ctf_FakeTimeLimit(player, -1); }
224         
225         ctf_RespawnFlag(player.flagcarried);
226 }
227
228 void ctf_Handle_Return(entity flag, entity player)
229 {
230         // messages and sounds
231         Send_KillNotification (player.netname, flag.netname, "", INFO_RETURNFLAG, MSG_INFO);
232         sound(player, CH_TRIGGER, flag.noise1, VOL_BASE, ATTN_NONE);
233         ctf_EventLog("return", flag.team, player);
234
235         // scoring
236         PlayerTeamScore_AddScore(player, ctf_ReadScore(strcat("score_return", ((player.playerid == flag.playerid) ? "_by_killer" : "")))); // reward for return
237         PlayerScore_Add(player, SP_CTF_RETURNS, 1); // add to count of returns
238
239         TeamScore_AddToTeam(((flag.team == COLOR_TEAM1) ? COLOR_TEAM2 : COLOR_TEAM1), ST_SCORE, -ctf_ReadScore("penalty_returned")); // punish the team who was last carrying it
240         FOR_EACH_PLAYER(player) if(player.playerid == flag.ctf_dropperid) // punish the player who dropped the flag
241         {
242                 PlayerScore_Add(player, SP_SCORE, -ctf_ReadScore("penalty_returned"));
243                 ctf_CaptureShield_Update(player, 0); // shield only
244         }
245         
246         // reset the flag
247         ctf_RespawnFlag(flag);
248 }
249
250 void ctf_Handle_Pickup_Base(entity flag, entity player)
251 {
252         entity tmp_player; // temporary entity which the FOR_EACH_PLAYER loop uses to scan players
253         string verbosename; // holds the name of the player OR no name at all for printing in the centerprints
254
255         // attach the flag to the player
256         flag.owner = player;
257         player.flagcarried = flag;
258         setattachment(flag, player, "");
259         setorigin(flag, FLAG_CARRY_OFFSET);
260         
261         // set up the flag
262         flag.movetype = MOVETYPE_NONE;
263         flag.takedamage = DAMAGE_NO;
264         flag.solid = SOLID_NOT;
265         flag.angles = '0 0 0';
266         flag.ctf_pickuptime = time; // used for timing runs
267         flag.ctf_pickupid = player.playerid;
268         flag.ctf_status = FLAG_CARRY;
269         
270         // messages and sounds
271         Send_KillNotification (player.netname, flag.netname, "", INFO_GOTFLAG, MSG_INFO);
272         sound(player, CH_TRIGGER, flag.noise, VOL_BASE, ATTN_NONE);
273         ctf_EventLog("steal", flag.team, player);
274         verbosename = ((autocvar_g_ctf_flag_pickup_verbosename) ? strcat("(", player.netname, ")") : ""); // replace TRUE with an autocvar for it.
275         FOR_EACH_PLAYER(tmp_player)
276                 if(tmp_player.team == flag.team)
277                         centerprint(tmp_player, strcat("The enemy ", verbosename, "got your flag! Retrieve it!"));
278                 else if((tmp_player.team == player.team) && (tmp_player != player))
279                         centerprint(tmp_player, strcat("Your team mate ", verbosename, "got the flag! Protect them!"));
280         
281         // scoring
282         PlayerTeamScore_AddScore(player, ctf_ReadScore("score_pickup_base"));
283         PlayerScore_Add(player, SP_CTF_PICKUPS, 1);
284         
285         // speedrunning
286         flag.speedrunning = player.speedrunning; // if speedrunning, flag will flag-return and teleport the owner back after the record
287         if((player.speedrunning) && (ctf_captimerecord))
288                 ctf_FakeTimeLimit(player, time + ctf_captimerecord);
289                 
290         // effects
291         if (autocvar_g_ctf_flag_pickup_effects)
292         {
293                 pointparticles(particleeffectnum("smoke_ring"), 0.5 * (flag.absmin + flag.absmax), '0 0 0', 1);
294         }
295         
296         // waypoints 
297         WaypointSprite_Spawn("flagcarrier", 0, 0, player, '0 0 64', world, player.team, player, wps_flagcarrier, FALSE, RADARICON_FLAG, '1 1 0'); // (COLOR_TEAM1 + COLOR_TEAM2 - flag.team)
298         WaypointSprite_UpdateMaxHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(start_health, start_armorvalue, autocvar_g_balance_armor_blockpercent) * 2);
299         WaypointSprite_UpdateHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(player.health, player.armorvalue, autocvar_g_balance_armor_blockpercent));
300         WaypointSprite_UpdateTeamRadar(player.wps_flagcarrier, RADARICON_FLAGCARRIER, '1 1 0');
301         WaypointSprite_Ping(player.wps_flagcarrier);
302 }
303  
304 void ctf_Handle_Pickup_Dropped(entity flag, entity player) // make sure this works
305 {
306         // declarations
307         float returnscore = bound(0, (flag.pain_finished - time) / autocvar_g_ctf_flag_returntime, 1); // can this be division by zero?
308         entity tmp_player; // temporary entity which the FOR_EACH_PLAYER loop uses to scan players
309         string verbosename; // holds the name of the player OR no name at all for printing in the centerprints
310
311         // attach the flag to the player
312         flag.owner = player;
313         player.flagcarried = flag;
314         setattachment(flag, player, "");
315         setorigin(flag, FLAG_CARRY_OFFSET);
316         
317         // set up the flag
318         flag.movetype = MOVETYPE_NONE;
319         flag.takedamage = DAMAGE_NO;
320         flag.solid = SOLID_NOT;
321         flag.angles = '0 0 0';
322         //flag.ctf_pickuptime = time; // don't update pickuptime since this isn't a real steal. 
323         flag.ctf_pickupid = player.playerid;
324         flag.ctf_status = FLAG_CARRY;
325
326         // messages and sounds
327         Send_KillNotification (player.netname, flag.netname, "", INFO_PICKUPFLAG, MSG_INFO);
328         sound (player, CH_TRIGGER, flag.noise, VOL_BASE, ATTN_NONE);
329         ctf_EventLog("pickup", flag.team, player);
330         verbosename = ((autocvar_g_ctf_flag_pickup_verbosename) ? strcat("(", player.netname, ")") : "");
331         FOR_EACH_PLAYER(tmp_player)
332                 if(tmp_player.team == flag.team)
333                         centerprint(tmp_player, strcat("The enemy ", verbosename, "got your flag! Retrieve it!"));
334                 else if((tmp_player.team == player.team) && (tmp_player != player))
335                         centerprint(tmp_player, strcat("Your team mate ", verbosename, "got the flag! Protect them!"));
336
337         // scoring
338         returnscore = floor((ctf_ReadScore("score_pickup_dropped_late") * (1-returnscore) + ctf_ReadScore("score_pickup_dropped_early") * returnscore) + 0.5);
339         print("score is ", ftos(returnscore), "\n");
340         PlayerTeamScore_AddScore(player, returnscore);
341         PlayerScore_Add(player, SP_CTF_PICKUPS, 1);
342
343         // effects
344         if (autocvar_g_ctf_flag_pickup_effects) // field pickup effect
345         {
346                 pointparticles(particleeffectnum("smoke_ring"), 0.5 * (flag.absmin + flag.absmax), '0 0 0', 1); 
347         }
348
349         // waypoints
350         WaypointSprite_Kill(flag.wps_flagdropped);
351         WaypointSprite_Spawn("flagcarrier", 0, 0, player, '0 0 64', world, player.team, player, wps_flagcarrier, FALSE, RADARICON_FLAG, '1 1 0'); // (COLOR_TEAM1 + COLOR_TEAM2 - flag.team)
352         WaypointSprite_UpdateMaxHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(start_health, start_armorvalue, autocvar_g_balance_armor_blockpercent) * 2);
353         WaypointSprite_UpdateHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(player.health, player.armorvalue, autocvar_g_balance_armor_blockpercent));
354         WaypointSprite_UpdateTeamRadar(player.wps_flagcarrier, RADARICON_FLAGCARRIER, '1 1 0');
355         WaypointSprite_Ping(player.wps_flagcarrier);
356 }
357
358
359 // ===================
360 // Main Flag Functions
361 // ===================
362
363 void ctf_FlagThink()
364 {
365         // declarations
366         entity tmp_entity;
367
368         self.nextthink = time + 0.1; // only 10 fps, more is unnecessary.
369
370         // captureshield
371         if(self == ctf_worldflaglist) // only for the first flag
372                 FOR_EACH_CLIENT(tmp_entity)
373                         ctf_CaptureShield_Update(tmp_entity, 1); // release shield only
374
375         // sanity checks
376         if(self.mins != FLAG_MIN || self.maxs != FLAG_MAX) { // reset the flag boundaries in case it got squished
377                 dprint("wtf the flag got squished?\n");
378                 tracebox(self.origin, FLAG_MIN, FLAG_MAX, self.origin, MOVE_NOMONSTERS, self);
379                 if(!trace_startsolid) // can we resize it without getting stuck?
380                         setsize(self, FLAG_MIN, FLAG_MAX); }
381
382         if(self.owner.classname != "player" || (self.owner.deadflag) || (self.owner.flagcarried != self)) {
383                 dprint("CANNOT HAPPEN - player dead and STILL had a flag!\n");
384                 ctf_Handle_Drop(self.owner);
385                 return; }
386
387         // main think method
388         switch(self.ctf_status) 
389         {       
390                 case FLAG_BASE: // nothing to do here
391                         return;
392                 
393                 case FLAG_DROPPED:
394                         if(time > self.ctf_droptime + autocvar_g_ctf_flag_returntime)
395                         {
396                                 bprint("The ", self.netname, " has returned to base\n");
397                                 sound (self, CH_TRIGGER, self.noise3, VOL_BASE, ATTN_NONE);
398                                 ctf_EventLog("returned", self.team, world);
399                                 ctf_RespawnFlag(self);
400                         }
401                         return;
402                                 
403                 case FLAG_CARRY:
404                         if((self.owner) && (self.speedrunning) && (ctf_captimerecord) && (time >= self.ctf_pickuptime + ctf_captimerecord)) 
405                         {
406                                 bprint("The ", self.netname, " became impatient after ", ftos_decimals(ctf_captimerecord, 2), " seconds and returned itself\n");
407                                 sound (self, CH_TRIGGER, self.noise3, VOL_BASE, ATTN_NONE);
408
409                                 self.owner.impulse = 141; // returning!
410
411                                 tmp_entity = self;
412                                 self = self.owner;
413                                 ctf_RespawnFlag(tmp_entity);
414                                 ImpulseCommands();
415                                 self = tmp_entity;
416                         }
417                         return;
418
419                 default: // this should never happen
420                         dprint("Think: Flag exists with no status?\n");
421                         return;
422         }
423 }
424
425 void ctf_FlagTouch()
426 {
427         if(gameover) { return; }
428         if(!self) { return; }
429         if((trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT) 
430                 || ((trace_dpstartcontents | trace_dphitcontents) & (DPCONTENTS_SLIME | DPCONTENTS_LAVA | DPCONTENTS_NODROP)))
431         { // The flag fell off the map or into lava/slime, respawn it since players can't get to it
432                 bprint("The ", self.netname, " has returned to base\n");
433                 sound (self, CH_TRIGGER, self.noise3, VOL_BASE, ATTN_NONE);
434                 ctf_EventLog("returned", self.team, world);
435                 ctf_RespawnFlag(self);
436                 return;
437         }
438         if(other.deadflag != DEAD_NO) { return; }
439         if(other.classname != "player") 
440         {  // The flag just touched an object, most likely the world
441                 pointparticles(particleeffectnum("kaball_sparks"), self.origin, '0 0 0', 1);
442                 sound(self, CH_TRIGGER, "keepaway/touch.wav", VOL_BASE, ATTN_NORM);
443                 return; 
444         }
445         else if(self.wait > time) { return; }
446
447         switch(self.ctf_status) 
448         {       
449                 case FLAG_BASE:
450                         if((other.team == self.team) && (other.flagcarried) && (other.flagcarried.team != self.team))
451                                 ctf_Handle_Capture(self, other); // other just captured the enemies flag to his base
452                         else if((other.team != self.team) && (!other.flagcarried) && (!other.ctf_captureshielded))
453                                 ctf_Handle_Pickup_Base(self, other); // other just stole the enemies flag
454                         break;
455                 
456                 case FLAG_DROPPED:
457                         if(other.team == self.team)
458                                 ctf_Handle_Return(self, other); // other just returned his own flag
459                         else if((!other.flagcarried) && ((other.playerid != self.ctf_dropperid) || (time > self.ctf_droptime + autocvar_g_balance_ctf_delay_collect)))
460                                 ctf_Handle_Pickup_Dropped(self, other); // other just picked up a dropped enemy flag
461                         break;
462                                 
463                 case FLAG_CARRY:
464                         dprint("Someone touched a flag even though it was being carried?\n");
465                         break;
466
467                 default: // this should never happen
468                         dprint("Touch: Flag exists with no status?\n");
469                         break;
470         }
471 }
472
473 void ctf_RespawnFlag(entity flag)
474 {
475         // reset the player (if there is one)
476         if((flag.owner) && (flag.owner.flagcarried == flag))
477         {
478                 WaypointSprite_Kill(flag.wps_flagcarrier);
479                 flag.owner.flagcarried = world;
480
481                 if(flag.speedrunning)
482                         ctf_FakeTimeLimit(flag.owner, -1);
483         }
484
485         if((flag.ctf_status == FLAG_DROPPED) && (flag.wps_flagdropped))
486                 { WaypointSprite_Kill(flag.wps_flagdropped); }
487
488         // reset the flag
489         setattachment(flag, world, "");
490         setorigin(flag, flag.ctf_spawnorigin); // replace with flag.ctf_spawnorigin
491         flag.movetype = ((flag.noalign) ? MOVETYPE_NONE : MOVETYPE_TOSS);
492         flag.takedamage = DAMAGE_NO;
493         flag.solid = SOLID_TRIGGER;
494         flag.velocity = '0 0 0';
495         flag.angles = flag.mangle;
496         flag.ctf_status = FLAG_BASE;
497         flag.flags = FL_ITEM | FL_NOTARGET;
498         flag.owner = world;
499 }
500
501 void ctf_Reset()
502 {
503         if(self.owner)
504                 if(self.owner.classname == "player")
505                         ctf_Handle_Drop(self.owner);
506                         
507         ctf_RespawnFlag(self);
508 }
509
510 void ctf_DelayedFlagSetup(void) // called after a flag is placed on a map by ctf_FlagSetup()
511 {
512         // declarations
513         float teamnumber = ((self.team == COLOR_TEAM1) ? TRUE : FALSE); // if we were originally 1, this will become 0. If we were originally 0, this will become 1. 
514
515         // bot waypoints
516         waypoint_spawnforitem_force(self, self.origin);
517         self.nearestwaypointtimeout = 0; // activate waypointing again
518         self.bot_basewaypoint = self.nearestwaypoint;
519
520         // waypointsprites
521         WaypointSprite_SpawnFixed(((teamnumber) ? "redbase" : "bluebase"), self.origin + '0 0 64', self, wps_flagbase, RADARICON_FLAG, colormapPaletteColor(((teamnumber) ? COLOR_TEAM1 : COLOR_TEAM2) - 1, FALSE));
522         WaypointSprite_UpdateTeamRadar(self.wps_flagbase, RADARICON_FLAG, colormapPaletteColor(((teamnumber) ? COLOR_TEAM1 : COLOR_TEAM2) - 1, FALSE));
523
524         // captureshield setup
525         ctf_CaptureShield_Spawn(self);
526 }
527
528 void ctf_FlagSetup(float teamnumber, entity flag) // called when spawning a flag entity on the map as a spawnfunc 
529 {       
530         // declarations
531         teamnumber = fabs(teamnumber - bound(0, g_ctf_reverse, 1)); // if we were originally 1, this will become 0. If we were originally 0, this will become 1. 
532         self = flag; // for later usage with droptofloor()
533         
534         // main setup
535         flag.ctf_worldflagnext = ctf_worldflaglist; // link flag into ctf_worldflaglist // todo: find out if this can be simplified
536         ctf_worldflaglist = flag;
537
538         setattachment(flag, world, ""); 
539
540         flag.netname = ((teamnumber) ? "^1RED^7 flag" : "^4BLUE^7 flag");
541         flag.team = ((teamnumber) ? COLOR_TEAM1 : COLOR_TEAM2); // COLOR_TEAM1: color 4 team (red) - COLOR_TEAM2: color 13 team (blue)
542         flag.items = ((teamnumber) ? IT_KEY2 : IT_KEY1); // IT_KEY2: gold key (redish enough) - IT_KEY1: silver key (bluish enough)
543         flag.classname = "item_flag_team";
544         flag.target = "###item###"; // wut?
545         flag.flags = FL_ITEM | FL_NOTARGET;
546         flag.solid = SOLID_TRIGGER;
547         flag.takedamage = DAMAGE_NO;
548         flag.damageforcescale = autocvar_g_ctf_flag_damageforcescale;   
549         flag.velocity = '0 0 0';
550         flag.mangle = flag.angles;
551         flag.reset = ctf_Reset;
552         flag.touch = ctf_FlagTouch;
553         flag.think = ctf_FlagThink;
554         flag.ctf_status = FLAG_BASE;
555
556         // appearence
557         if(!flag.model) { flag.model = ((teamnumber) ? autocvar_g_ctf_flag_red_model : autocvar_g_ctf_flag_blue_model); }
558         setmodel(flag, flag.model); // precision set below
559         setsize(flag, FLAG_MIN, FLAG_MAX);
560         setorigin(flag, (flag.origin + FLAG_SPAWN_OFFSET));
561         if(!flag.scale) { flag.scale = 0.6; } // FIXME: why hard coded 0.6?
562         
563         flag.skin = ((teamnumber) ? autocvar_g_ctf_flag_red_skin : autocvar_g_ctf_flag_blue_skin);
564         
565         if(autocvar_g_ctf_flag_glowtrails)
566         {
567                 flag.glow_color = ((teamnumber) ? 251 : 210); // 251: red - 210: blue
568                 flag.glow_size = 25;
569                 flag.glow_trail = 1;
570         }
571         
572         flag.effects |= EF_LOWPRECISION;
573         if(autocvar_g_ctf_fullbrightflags) { flag.effects |= EF_FULLBRIGHT; }
574         if(autocvar_g_ctf_dynamiclights)   { flag.effects |= ((teamnumber) ? EF_RED : EF_BLUE); }
575         
576         // sound 
577         if(!flag.noise)  { flag.noise  = ((teamnumber) ? "ctf/red_taken.wav" : "ctf/blue_taken.wav"); }
578         if(!flag.noise1) { flag.noise1 = ((teamnumber) ? "ctf/red_returned.wav" : "ctf/blue_returned.wav"); }
579         if(!flag.noise2) { flag.noise2 = ((teamnumber) ? "ctf/red_capture.wav" : "ctf/blue_capture.wav"); } // blue team scores by capturing the red flag
580         if(!flag.noise3) { flag.noise3 = "ctf/flag_respawn.wav"; } // if there is ever a team-based sound for this, update the code to match.
581         if(!flag.noise4) { flag.noise4 = ((teamnumber) ? "ctf/red_dropped.wav" : "ctf/blue_dropped.wav"); }
582         
583         // precache
584         precache_sound(flag.noise);
585         precache_sound(flag.noise1);
586         precache_sound(flag.noise2);
587         precache_sound(flag.noise3);
588         precache_sound(flag.noise4);
589         precache_model(flag.model);
590         precache_model("models/ctf/shield.md3");
591         precache_model("models/ctf/shockwavetransring.md3");
592         
593         // flag placement
594         if((flag.spawnflags & 1) || flag.noalign) // don't drop to floor, just stay at fixed location
595         {       
596                 flag.dropped_origin = flag.origin; 
597                 flag.noalign = TRUE;
598                 flag.movetype = MOVETYPE_NONE;
599                 print("^1|^3||||^1| This map was loaded with flags using MOVETYPE_NONE\n");
600         }
601         else // drop to floor, automatically find a platform and set that as spawn origin
602         { 
603                 flag.noalign = FALSE;
604                 self = flag;
605                 droptofloor();
606                 flag.movetype = MOVETYPE_TOSS; 
607                 print("^1|^3||||^1| This map was loaded with flags using MOVETYPE_TOSS\n");
608         }       
609         
610         InitializeEntity(flag, ctf_DelayedFlagSetup, INITPRIO_SETLOCATION);
611 }
612
613
614 // ==============
615 // Hook Functions
616 // ==============
617
618 // g_ctf_ignore_frags
619
620 MUTATOR_HOOKFUNCTION(ctf_RemovePlayer)
621 {
622         if(self.flagcarried) { ctf_Handle_Drop(self); }
623         return 0;
624 }
625
626 MUTATOR_HOOKFUNCTION(ctf_PlayerPreThink)
627 {
628         entity flag;
629         
630         // initially clear items so they can be set as necessary later.
631         self.items &~= (IT_RED_FLAG_CARRYING | IT_RED_FLAG_TAKEN | IT_RED_FLAG_LOST 
632                 | IT_BLUE_FLAG_CARRYING | IT_BLUE_FLAG_TAKEN | IT_BLUE_FLAG_LOST | IT_CTF_SHIELDED);
633
634         // item for stopping players from capturing the flag too often
635         if(self.ctf_captureshielded)
636                 self.items |= IT_CTF_SHIELDED;
637
638         // scan through all the flags and notify the client about them 
639         for (flag = ctf_worldflaglist; flag; flag = flag.ctf_worldflagnext)
640         {
641                 if(flag.ctf_status == FLAG_CARRY)
642                         if(flag.owner == self)
643                                 self.items |= ((flag.items & IT_KEY2) ? IT_RED_FLAG_CARRYING : IT_BLUE_FLAG_CARRYING); // carrying: self is currently carrying the flag
644                         else 
645                                 self.items |= ((flag.items & IT_KEY2) ? IT_RED_FLAG_TAKEN : IT_BLUE_FLAG_TAKEN); // taken: someone on self's team is carrying the flag
646                 else if(flag.ctf_status == FLAG_DROPPED) 
647                         self.items |= ((flag.items & IT_KEY2) ? IT_RED_FLAG_LOST : IT_BLUE_FLAG_LOST); // lost: the flag is dropped somewhere on the map
648         }
649         
650         return 0;
651 }
652
653 MUTATOR_HOOKFUNCTION(ctf_PlayerDamage) // for changing damage and force values that are applied to players in g_damage.qc
654 {       /*
655         if(frag_attacker.flagcarried) // if the attacker is a flagcarrier
656         {
657                 if(frag_target == frag_attacker) // damage done to yourself
658                 {
659                         frag_damage *= autocvar_g_ctf_flagcarrier_selfdamagefactor;
660                         frag_force *= autocvar_g_ctf_flagcarrier_selfforcefactor;
661                 }
662                 else // damage done to noncarriers
663                 {
664                         frag_damage *= autocvar_g_ctf_flagcarrier_damagefactor;
665                         frag_force *= autocvar_g_ctf_flagcarrier_forcefactor;
666                 }
667         }*/
668         return 0;
669 }
670
671 MUTATOR_HOOKFUNCTION(ctf_GiveFragsForKill)
672 {
673         frag_score = 0; // no frags counted in ctf
674         return (g_ctf_ignore_frags); // you deceptive little bugger ;3 This needs to be true in order for this function to even count. 
675 }
676
677 MUTATOR_HOOKFUNCTION(ctf_PlayerUseKey)
678 {
679         if(autocvar_g_ctf_allow_drop)
680                 ctf_Handle_Drop(self);
681                 
682         return 0;
683 }
684
685 // ==========
686 // Spawnfuncs
687 // ==========
688
689 /*QUAKED spawnfunc_info_player_team1 (1 0 0) (-16 -16 -24) (16 16 24)
690 CTF Starting point for a player in team one (Red).
691 Keys: "angle" viewing angle when spawning. */
692 void spawnfunc_info_player_team1()
693 {
694         if(g_assault) { remove(self); return; }
695         
696         self.team = COLOR_TEAM1; // red
697         spawnfunc_info_player_deathmatch();
698 }
699
700
701 /*QUAKED spawnfunc_info_player_team2 (1 0 0) (-16 -16 -24) (16 16 24)
702 CTF Starting point for a player in team two (Blue).
703 Keys: "angle" viewing angle when spawning. */
704 void spawnfunc_info_player_team2()
705 {
706         if(g_assault) { remove(self); return; }
707         
708         self.team = COLOR_TEAM2; // blue
709         spawnfunc_info_player_deathmatch();
710 }
711
712 /*QUAKED spawnfunc_info_player_team3 (1 0 0) (-16 -16 -24) (16 16 24)
713 CTF Starting point for a player in team three (Yellow).
714 Keys: "angle" viewing angle when spawning. */
715 void spawnfunc_info_player_team3()
716 {
717         if(g_assault) { remove(self); return; }
718         
719         self.team = COLOR_TEAM3; // yellow
720         spawnfunc_info_player_deathmatch();
721 }
722
723
724 /*QUAKED spawnfunc_info_player_team4 (1 0 0) (-16 -16 -24) (16 16 24)
725 CTF Starting point for a player in team four (Purple).
726 Keys: "angle" viewing angle when spawning. */
727 void spawnfunc_info_player_team4()
728 {
729         if(g_assault) { remove(self); return; }
730         
731         self.team = COLOR_TEAM4; // purple
732         spawnfunc_info_player_deathmatch();
733 }
734
735 /*QUAKED spawnfunc_item_flag_team1 (0 0.5 0.8) (-48 -48 -37) (48 48 37)
736 CTF flag for team one (Red). Multiple flags are allowed.
737 Keys: 
738 "angle" Angle the flag will point (minus 90 degrees)... 
739 "model" model to use, note this needs red and blue as skins 0 and 1 (default models/ctf/flag.md3)...
740 "noise" sound played when flag is picked up (default ctf/take.wav)...
741 "noise1" sound played when flag is returned by a teammate (default ctf/return.wav)...
742 "noise2" sound played when flag is captured (default ctf/redcapture.wav)...
743 "noise3" sound played when flag is lost in the field and respawns itself (default ctf/respawn.wav)... */
744 void spawnfunc_item_flag_team1()
745 {
746         if(!g_ctf) { remove(self); return; }
747
748         ctf_FlagSetup(1, self); // 1 = red
749 }
750
751 /*QUAKED spawnfunc_item_flag_team2 (0 0.5 0.8) (-48 -48 -37) (48 48 37)
752 CTF flag for team two (Blue). Multiple flags are allowed.
753 Keys: 
754 "angle" Angle the flag will point (minus 90 degrees)... 
755 "model" model to use, note this needs red and blue as skins 0 and 1 (default models/ctf/flag.md3)...
756 "noise" sound played when flag is picked up (default ctf/take.wav)...
757 "noise1" sound played when flag is returned by a teammate (default ctf/return.wav)...
758 "noise2" sound played when flag is captured (default ctf/redcapture.wav)...
759 "noise3" sound played when flag is lost in the field and respawns itself (default ctf/respawn.wav)... */
760 void spawnfunc_item_flag_team2()
761 {
762         if(!g_ctf) { remove(self); return; }
763
764         ctf_FlagSetup(0, self); // the 0 is misleading, but -- 0 = blue.
765 }
766
767 /*QUAKED spawnfunc_ctf_team (0 .5 .8) (-16 -16 -24) (16 16 32)
768 Team declaration for CTF gameplay, this allows you to decide what team names and control point models are used in your map.
769 Note: If you use spawnfunc_ctf_team entities you must define at least 2!  However, unlike domination, you don't need to make a blank one too.
770 Keys:
771 "netname" Name of the team (for example Red, Blue, Green, Yellow, Life, Death, Offense, Defense, etc)...
772 "cnt" Scoreboard color of the team (for example 4 is red and 13 is blue)... */
773 void spawnfunc_ctf_team()
774 {
775         if(!g_ctf) { remove(self); return; }
776         
777         self.classname = "ctf_team";
778         self.team = self.cnt + 1;
779 }
780
781
782 // ==============
783 // Initialization
784 // ==============
785
786 // code from here on is just to support maps that don't have flag and team entities
787 void ctf_SpawnTeam (string teamname, float teamcolor)
788 {
789         entity oldself;
790         oldself = self;
791         self = spawn();
792         self.classname = "ctf_team";
793         self.netname = teamname;
794         self.cnt = teamcolor;
795
796         spawnfunc_ctf_team();
797
798         self = oldself;
799 }
800
801 void ctf_DelayedInit() // Do this check with a delay so we can wait for teams to be set up.
802 {
803         // if no teams are found, spawn defaults
804         if(find(world, classname, "ctf_team") == world)
805         {
806                 print("No ""ctf_team"" entities found on this map, creating them anyway.\n");
807                 ctf_SpawnTeam("Red", COLOR_TEAM1 - 1);
808                 ctf_SpawnTeam("Blue", COLOR_TEAM2 - 1);
809         }
810         
811         ScoreRules_ctf();
812 }
813
814 void ctf_Initialize()
815 {
816         ctf_captimerecord = stof(db_get(ServerProgsDB, strcat(GetMapname(), "/captimerecord/time")));
817
818         ctf_captureshield_min_negscore = autocvar_g_ctf_shield_min_negscore;
819         ctf_captureshield_max_ratio = autocvar_g_ctf_shield_max_ratio;
820         ctf_captureshield_force = autocvar_g_ctf_shield_force;
821
822         //g_ctf_win_mode = cvar("g_ctf_win_mode");
823         
824         InitializeEntity(world, ctf_DelayedInit, INITPRIO_GAMETYPE);
825 }
826
827
828 MUTATOR_DEFINITION(gamemode_ctf)
829 {
830         MUTATOR_HOOK(MakePlayerObserver, ctf_RemovePlayer, CBC_ORDER_ANY);
831         MUTATOR_HOOK(ClientDisconnect, ctf_RemovePlayer, CBC_ORDER_ANY);
832         MUTATOR_HOOK(PlayerDies, ctf_RemovePlayer, CBC_ORDER_ANY);
833         MUTATOR_HOOK(GiveFragsForKill, ctf_GiveFragsForKill, CBC_ORDER_ANY);
834         MUTATOR_HOOK(PlayerPreThink, ctf_PlayerPreThink, CBC_ORDER_ANY);
835         MUTATOR_HOOK(PlayerDamage_Calculate, ctf_PlayerDamage, CBC_ORDER_ANY);
836         MUTATOR_HOOK(PlayerUseKey, ctf_PlayerUseKey, CBC_ORDER_ANY);
837         //MUTATOR_HOOK(PlayerPowerups, ctf_PlayerPowerups, CBC_ORDER_ANY);
838
839         MUTATOR_ONADD
840         {
841                 if(time > 1) // game loads at time 1
842                         error("This is a game type and it cannot be added at runtime.");
843                 g_ctf = 1;
844                 ctf_Initialize();
845         }
846
847         MUTATOR_ONREMOVE
848         {
849                 g_ctf = 0;
850                 error("This is a game type and it cannot be removed at runtime.");
851         }
852
853         return 0;
854 }