Merge branch 'master' into Mario/vaporizer_damage
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / mutators / gamemode_keyhunt.qc
1 #include "gamemode_keyhunt.qh"
2 #include "../_all.qh"
3
4 #include "gamemode.qh"
5
6
7 // #define KH_PLAYER_USE_ATTACHMENT
8 // #define KH_PLAYER_USE_CARRIEDMODEL
9
10 #ifdef KH_PLAYER_USE_ATTACHMENT
11 const vector KH_PLAYER_ATTACHMENT_DIST_ROTATED = '0 -4 0';
12 const vector KH_PLAYER_ATTACHMENT_DIST = '4 0 0';
13 const vector KH_PLAYER_ATTACHMENT = '0 0 0';
14 const vector KH_PLAYER_ATTACHMENT_ANGLES = '0 0 0';
15 const string KH_PLAYER_ATTACHMENT_BONE = "";
16 #else
17 const float KH_KEY_ZSHIFT = 22;
18 const float KH_KEY_XYDIST = 24;
19 const float KH_KEY_XYSPEED = 45;
20 #endif
21 const float KH_KEY_WP_ZSHIFT = 20;
22
23 const vector KH_KEY_MIN = '-10 -10 -46';
24 const vector KH_KEY_MAX = '10 10 3';
25 const float KH_KEY_BRIGHTNESS = 2;
26
27 float kh_no_radar_circles;
28
29 // kh_state
30 //     bits  0- 4: team of key 1, or 0 for no such key, or 30 for dropped, or 31 for self
31 //     bits  5- 9: team of key 2, or 0 for no such key, or 30 for dropped, or 31 for self
32 //     bits 10-14: team of key 3, or 0 for no such key, or 30 for dropped, or 31 for self
33 //     bits 15-19: team of key 4, or 0 for no such key, or 30 for dropped, or 31 for self
34 .float kh_state;
35 .float siren_time;  //  time delay the siren
36 //.float stuff_time;  //  time delay to stuffcmd a cvar
37
38 float kh_keystatus[17];
39 //kh_keystatus[0] = status of dropped keys, kh_keystatus[1 - 16] = player #
40 //replace 17 with cvar("maxplayers") or similar !!!!!!!!!
41 //for(i = 0; i < maxplayers; ++i)
42 //      kh_keystatus[i] = "0";
43
44 float kh_Team_ByID(float t)
45 {
46         if(t == 0) return NUM_TEAM_1;
47         if(t == 1) return NUM_TEAM_2;
48         if(t == 2) return NUM_TEAM_3;
49         if(t == 3) return NUM_TEAM_4;
50         return 0;
51 }
52
53 //entity kh_worldkeylist;
54 .entity kh_worldkeynext;
55 entity kh_controller;
56 //float kh_tracking_enabled;
57 float kh_teams;
58 float kh_interferemsg_time, kh_interferemsg_team;
59 .entity kh_next, kh_prev; // linked list
60 .float kh_droptime;
61 .float kh_dropperteam;
62 .entity kh_previous_owner;
63 .float kh_previous_owner_playerid;
64 .float kh_cp_duration;
65
66 string kh_sound_capture = "kh/capture.wav";
67 string kh_sound_destroy = "kh/destroy.wav";
68 string kh_sound_drop = "kh/drop.wav";
69 string kh_sound_collect = "kh/collect.wav";
70 string kh_sound_alarm = "kh/alarm.wav";  // the new siren/alarm
71
72 float kh_key_dropped, kh_key_carried;
73
74 const float ST_KH_CAPS = 1;
75 const float SP_KH_CAPS = 4;
76 const float SP_KH_PUSHES = 5;
77 const float SP_KH_DESTROYS = 6;
78 const float SP_KH_PICKUPS = 7;
79 const float SP_KH_KCKILLS = 8;
80 const float SP_KH_LOSSES = 9;
81 void kh_ScoreRules(float teams)
82 {
83         ScoreRules_basics(teams, SFL_SORT_PRIO_PRIMARY, SFL_SORT_PRIO_PRIMARY, true);
84         ScoreInfo_SetLabel_TeamScore(  ST_KH_CAPS,      "caps",      SFL_SORT_PRIO_SECONDARY);
85         ScoreInfo_SetLabel_PlayerScore(SP_KH_CAPS,      "caps",      SFL_SORT_PRIO_SECONDARY);
86         ScoreInfo_SetLabel_PlayerScore(SP_KH_PUSHES,    "pushes",    0);
87         ScoreInfo_SetLabel_PlayerScore(SP_KH_DESTROYS,  "destroyed", SFL_LOWER_IS_BETTER);
88         ScoreInfo_SetLabel_PlayerScore(SP_KH_PICKUPS,   "pickups",   0);
89         ScoreInfo_SetLabel_PlayerScore(SP_KH_KCKILLS,   "kckills",   0);
90         ScoreInfo_SetLabel_PlayerScore(SP_KH_LOSSES,    "losses",    SFL_LOWER_IS_BETTER);
91         ScoreRules_basics_end();
92 }
93
94 float kh_KeyCarrier_waypointsprite_visible_for_player(entity e)  // runs all the time
95 {
96         if(!IS_PLAYER(e) || self.team != e.team)
97                 if(!kh_tracking_enabled)
98                         return false;
99
100         return true;
101 }
102
103 float kh_Key_waypointsprite_visible_for_player(entity e) // ??
104 {
105         if(!kh_tracking_enabled)
106                 return false;
107         if(!self.owner)
108                 return true;
109         if(!self.owner.owner)
110                 return true;
111         return false;  // draw only when key is not owned
112 }
113
114 void kh_update_state()
115 {
116         entity player;
117         entity key;
118         float s;
119         float f;
120
121         s = 0;
122         FOR_EACH_KH_KEY(key)
123         {
124                 if(key.owner)
125                         f = key.team;
126                 else
127                         f = 30;
128                 s |= pow(32, key.count) * f;
129         }
130
131         FOR_EACH_CLIENT(player)
132         {
133                 player.kh_state = s;
134         }
135
136         FOR_EACH_KH_KEY(key)
137         {
138                 if(key.owner)
139                         key.owner.kh_state |= pow(32, key.count) * 31;
140         }
141         //print(ftos((nextent(world)).kh_state), "\n");
142 }
143
144
145
146
147 var kh_Think_t kh_Controller_Thinkfunc;
148 void kh_Controller_SetThink(float t, kh_Think_t func)  // runs occasionaly
149 {
150         kh_Controller_Thinkfunc = func;
151         kh_controller.cnt = ceil(t);
152         if(t == 0)
153                 kh_controller.nextthink = time; // force
154 }
155 void kh_WaitForPlayers();
156 void kh_Controller_Think()  // called a lot
157 {
158         if(intermission_running)
159                 return;
160         if(self.cnt > 0)
161         { if(self.think != kh_WaitForPlayers) { self.cnt -= 1; } }
162         else if(self.cnt == 0)
163         {
164                 self.cnt -= 1;
165                 kh_Controller_Thinkfunc();
166         }
167         self.nextthink = time + 1;
168 }
169
170 // frags f: take from cvar * f
171 // frags 0: no frags
172 void kh_Scores_Event(entity player, entity key, string what, float frags_player, float frags_owner)  // update the score when a key is captured
173 {
174         string s;
175         if(intermission_running)
176                 return;
177
178         if(frags_player)
179                 UpdateFrags(player, frags_player);
180
181         if(key && key.owner && frags_owner)
182                 UpdateFrags(key.owner, frags_owner);
183
184         if(!autocvar_sv_eventlog)  //output extra info to the console or text file
185                 return;
186
187         s = strcat(":keyhunt:", what, ":", ftos(player.playerid), ":", ftos(frags_player));
188
189         if(key && key.owner)
190                 s = strcat(s, ":", ftos(key.owner.playerid));
191         else
192                 s = strcat(s, ":0");
193
194         s = strcat(s, ":", ftos(frags_owner), ":");
195
196         if(key)
197                 s = strcat(s, key.netname);
198
199         GameLogEcho(s);
200 }
201
202 vector kh_AttachedOrigin(entity e)  // runs when a team captures the flag, it can run 2 or 3 times.
203 {
204         if(e.tag_entity)
205         {
206                 makevectors(e.tag_entity.angles);
207                 return e.tag_entity.origin + e.origin.x * v_forward - e.origin.y * v_right + e.origin.z * v_up;
208         }
209         else
210                 return e.origin;
211 }
212
213 void kh_Key_Attach(entity key)  // runs when a player picks up a key and several times when a key is assigned to a player at the start of a round
214 {
215 #ifdef KH_PLAYER_USE_ATTACHMENT
216         entity first;
217         first = key.owner.kh_next;
218         if(key == first)
219         {
220                 setattachment(key, key.owner, KH_PLAYER_ATTACHMENT_BONE);
221                 if(key.kh_next)
222                 {
223                         setattachment(key.kh_next, key, "");
224                         setorigin(key, key.kh_next.origin - 0.5 * KH_PLAYER_ATTACHMENT_DIST);
225                         setorigin(key.kh_next, KH_PLAYER_ATTACHMENT_DIST_ROTATED);
226                         key.kh_next.angles = '0 0 0';
227                 }
228                 else
229                         setorigin(key, KH_PLAYER_ATTACHMENT);
230                 key.angles = KH_PLAYER_ATTACHMENT_ANGLES;
231         }
232         else
233         {
234                 setattachment(key, key.kh_prev, "");
235                 if(key.kh_next)
236                         setattachment(key.kh_next, key, "");
237                 setorigin(key, KH_PLAYER_ATTACHMENT_DIST_ROTATED);
238                 setorigin(first, first.origin - 0.5 * KH_PLAYER_ATTACHMENT_DIST);
239                 key.angles = '0 0 0';
240         }
241 #else
242         setattachment(key, key.owner, "");
243         setorigin(key, '0 0 1' * KH_KEY_ZSHIFT);  // fixing x, y in think
244         key.angles_y -= key.owner.angles.y;
245 #endif
246         key.flags = 0;
247         key.solid = SOLID_NOT;
248         key.movetype = MOVETYPE_NONE;
249         key.team = key.owner.team;
250         key.nextthink = time;
251         key.damageforcescale = 0;
252         key.takedamage = DAMAGE_NO;
253         key.modelindex = kh_key_carried;
254 }
255
256 void kh_Key_Detach(entity key) // runs every time a key is dropped or lost. Runs several times times when all the keys are captured
257 {
258 #ifdef KH_PLAYER_USE_ATTACHMENT
259         entity first;
260         first = key.owner.kh_next;
261         if(key == first)
262         {
263                 if(key.kh_next)
264                 {
265                         setattachment(key.kh_next, key.owner, KH_PLAYER_ATTACHMENT_BONE);
266                         setorigin(key.kh_next, key.origin + 0.5 * KH_PLAYER_ATTACHMENT_DIST);
267                         key.kh_next.angles = KH_PLAYER_ATTACHMENT_ANGLES;
268                 }
269         }
270         else
271         {
272                 if(key.kh_next)
273                         setattachment(key.kh_next, key.kh_prev, "");
274                 setorigin(first, first.origin + 0.5 * KH_PLAYER_ATTACHMENT_DIST);
275         }
276         // in any case:
277         setattachment(key, world, "");
278         setorigin(key, key.owner.origin + '0 0 1' * (PL_MIN.z - KH_KEY_MIN_z));
279         key.angles = key.owner.angles;
280 #else
281         setorigin(key, key.owner.origin + key.origin.z * '0 0 1');
282         setattachment(key, world, "");
283         key.angles_y += key.owner.angles.y;
284 #endif
285         key.flags = FL_ITEM;
286         key.solid = SOLID_TRIGGER;
287         key.movetype = MOVETYPE_TOSS;
288         key.pain_finished = time + autocvar_g_balance_keyhunt_delay_return;
289         key.damageforcescale = autocvar_g_balance_keyhunt_damageforcescale;
290         key.takedamage = DAMAGE_YES;
291         // let key.team stay
292         key.modelindex = kh_key_dropped;
293         key.kh_previous_owner = key.owner;
294         key.kh_previous_owner_playerid = key.owner.playerid;
295 }
296
297 void kh_Key_AssignTo(entity key, entity player)  // runs every time a key is picked up or assigned. Runs prior to kh_key_attach
298 {
299         entity k;
300         float ownerteam0, ownerteam;
301         if(key.owner == player)
302                 return;
303
304         ownerteam0 = kh_Key_AllOwnedByWhichTeam();
305
306         if(key.owner)
307         {
308                 kh_Key_Detach(key);
309
310                 // remove from linked list
311                 if(key.kh_next)
312                         key.kh_next.kh_prev = key.kh_prev;
313                 key.kh_prev.kh_next = key.kh_next;
314                 key.kh_next = world;
315                 key.kh_prev = world;
316
317                 if(key.owner.kh_next == world)
318                 {
319                         // No longer a key carrier
320                         if(!kh_no_radar_circles)
321                                 WaypointSprite_Ping(key.owner.waypointsprite_attachedforcarrier);
322                         WaypointSprite_DetachCarrier(key.owner);
323                 }
324         }
325
326         key.owner = player;
327
328         if(player)
329         {
330                 // insert into linked list
331                 key.kh_next = player.kh_next;
332                 key.kh_prev = player;
333                 player.kh_next = key;
334                 if(key.kh_next)
335                         key.kh_next.kh_prev = key;
336
337                 float i;
338                 i = kh_keystatus[key.owner.playerid];
339                         if(key.netname == "^1red key")
340                                 i += 1;
341                         if(key.netname == "^4blue key")
342                                 i += 2;
343                         if(key.netname == "^3yellow key")
344                                 i += 4;
345                         if(key.netname == "^6pink key")
346                                 i += 8;
347                 kh_keystatus[key.owner.playerid] = i;
348
349                 kh_Key_Attach(key);
350
351                 if(key.kh_next == world)
352                 {
353                         // player is now a key carrier
354                         entity wp = WaypointSprite_AttachCarrier(WP_Null, player, RADARICON_FLAGCARRIER);
355                         wp.colormod = colormapPaletteColor(player.team - 1, 0);
356                         player.waypointsprite_attachedforcarrier.waypointsprite_visible_for_player = kh_KeyCarrier_waypointsprite_visible_for_player;
357                         WaypointSprite_UpdateRule(player.waypointsprite_attachedforcarrier, player.team, SPRITERULE_TEAMPLAY);
358                         if(player.team == NUM_TEAM_1)
359                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierRed, WP_KeyCarrierFriend, WP_KeyCarrierRed);
360                         else if(player.team == NUM_TEAM_2)
361                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierBlue, WP_KeyCarrierFriend, WP_KeyCarrierBlue);
362                         else if(player.team == NUM_TEAM_3)
363                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierYellow, WP_KeyCarrierFriend, WP_KeyCarrierYellow);
364                         else if(player.team == NUM_TEAM_4)
365                                 WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierPink, WP_KeyCarrierFriend, WP_KeyCarrierPink);
366                         if(!kh_no_radar_circles)
367                                 WaypointSprite_Ping(player.waypointsprite_attachedforcarrier);
368                 }
369         }
370
371         // moved that here, also update if there's no player
372         kh_update_state();
373
374         key.pusher = world;
375
376         ownerteam = kh_Key_AllOwnedByWhichTeam();
377         if(ownerteam != ownerteam0)
378         {
379                 if(ownerteam != -1)
380                 {
381                         kh_interferemsg_time = time + 0.2;
382                         kh_interferemsg_team = player.team;
383
384                         // audit all key carrier sprites, update them to RUN HERE
385                         FOR_EACH_KH_KEY(k)
386                         {
387                                 if (!k.owner) continue;
388                                 entity first = WP_Null;
389                                 FOREACH(WAYPOINTS, it.netname == k.owner.waypointsprite_attachedforcarrier.model1, LAMBDA(first = it; break));
390                                 entity third = WP_Null;
391                                 FOREACH(WAYPOINTS, it.netname == k.owner.waypointsprite_attachedforcarrier.model3, LAMBDA(third = it; break));
392                                 WaypointSprite_UpdateSprites(k.owner.waypointsprite_attachedforcarrier, first, WP_KeyCarrierFinish, third);
393                         }
394                 }
395                 else
396                 {
397                         kh_interferemsg_time = 0;
398
399                         // audit all key carrier sprites, update them to RUN HERE
400                         FOR_EACH_KH_KEY(k)
401                         {
402                                 if (!k.owner) continue;
403                                 entity first = WP_Null;
404                                 FOREACH(WAYPOINTS, it.netname == k.owner.waypointsprite_attachedforcarrier.model1, LAMBDA(first = it; break));
405                                 entity third = WP_Null;
406                                 FOREACH(WAYPOINTS, it.netname == k.owner.waypointsprite_attachedforcarrier.model3, LAMBDA(third = it; break));
407                                 WaypointSprite_UpdateSprites(k.owner.waypointsprite_attachedforcarrier, first, WP_KeyCarrierFriend, third);
408                         }
409                 }
410         }
411 }
412
413 void kh_Key_Damage(entity inflictor, entity attacker, float damage, int deathtype, vector hitloc, vector force)
414 {
415         if(self.owner)
416                 return;
417         if(ITEM_DAMAGE_NEEDKILL(deathtype))
418         {
419                 // touching lava, or hurt trigger
420                 // what shall we do?
421                 // immediately return is bad
422                 // maybe start a shorter countdown?
423         }
424         if(vlen(force) <= 0)
425                 return;
426         if(time > self.pushltime)
427                 if(IS_PLAYER(attacker))
428                         self.team = attacker.team;
429 }
430
431 void kh_Key_Collect(entity key, entity player)  //a player picks up a dropped key
432 {
433         sound(player, CH_TRIGGER, kh_sound_collect, VOL_BASE, ATTEN_NORM);
434
435         if(key.kh_dropperteam != player.team)
436         {
437                 kh_Scores_Event(player, key, "collect", autocvar_g_balance_keyhunt_score_collect, 0);
438                 PlayerScore_Add(player, SP_KH_PICKUPS, 1);
439         }
440         key.kh_dropperteam = 0;
441         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(key, INFO_KEYHUNT_PICKUP_), player.netname);
442
443         kh_Key_AssignTo(key, player); // this also updates .kh_state
444 }
445
446 void kh_Key_Touch()  // runs many, many times when a key has been dropped and can be picked up
447 {
448         if(intermission_running)
449                 return;
450
451         if(self.owner) // already carried
452                 return;
453
454         if(ITEM_TOUCH_NEEDKILL())
455         {
456                 // touching sky, or nodrop
457                 // what shall we do?
458                 // immediately return is bad
459                 // maybe start a shorter countdown?
460         }
461
462         if (!IS_PLAYER(other))
463                 return;
464         if(other.deadflag != DEAD_NO)
465                 return;
466         if(other == self.enemy)
467                 if(time < self.kh_droptime + autocvar_g_balance_keyhunt_delay_collect)
468                         return;  // you just dropped it!
469         kh_Key_Collect(self, other);
470 }
471
472 void kh_Key_Remove(entity key)  // runs after when all the keys have been collected or when a key has been dropped for more than X seconds
473 {
474         entity o;
475         o = key.owner;
476         kh_Key_AssignTo(key, world);
477         if(o) // it was attached
478                 WaypointSprite_Kill(key.waypointsprite_attachedforcarrier);
479         else // it was dropped
480                 WaypointSprite_DetachCarrier(key);
481
482         // remove key from key list
483         if (kh_worldkeylist == key)
484                 kh_worldkeylist = kh_worldkeylist.kh_worldkeynext;
485         else
486         {
487                 o = kh_worldkeylist;
488                 while (o)
489                 {
490                         if (o.kh_worldkeynext == key)
491                         {
492                                 o.kh_worldkeynext = o.kh_worldkeynext.kh_worldkeynext;
493                                 break;
494                         }
495                         o = o.kh_worldkeynext;
496                 }
497         }
498
499         remove(key);
500
501         kh_update_state();
502 }
503
504 void kh_FinishRound()  // runs when a team captures the keys
505 {
506         // prepare next round
507         kh_interferemsg_time = 0;
508         entity key;
509
510         kh_no_radar_circles = true;
511         FOR_EACH_KH_KEY(key)
512                 kh_Key_Remove(key);
513         kh_no_radar_circles = false;
514
515         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_KEYHUNT_ROUNDSTART, autocvar_g_balance_keyhunt_delay_round);
516         kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_round, kh_StartRound);
517 }
518
519 void kh_WinnerTeam(float teem)  // runs when a team wins // Samual: Teem?.... TEEM?!?! what the fuck is wrong with you people
520 {
521         // all key carriers get some points
522         vector firstorigin, lastorigin, midpoint;
523         float first;
524         entity key;
525         float score;
526         score = (kh_teams - 1) * autocvar_g_balance_keyhunt_score_capture;
527         DistributeEvenly_Init(score, kh_teams);
528         // twice the score for 3 team games, three times the score for 4 team games!
529         // note: for a win by destroying the key, this should NOT be applied
530         FOR_EACH_KH_KEY(key)
531         {
532                 float f;
533                 f = DistributeEvenly_Get(1);
534                 kh_Scores_Event(key.owner, key, "capture", f, 0);
535                 PlayerTeamScore_Add(key.owner, SP_KH_CAPS, ST_KH_CAPS, 1);
536                 nades_GiveBonus(key.owner, autocvar_g_nades_bonus_score_high);
537         }
538
539         first = true;
540         string keyowner = "";
541         FOR_EACH_KH_KEY(key)
542                 if(key.owner.kh_next == key)
543                 {
544                         if(!first)
545                                 keyowner = strcat(keyowner, ", ");
546                         keyowner = key.owner.netname;
547                         first = false;
548                 }
549
550         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_NUM_4(teem, INFO_KEYHUNT_CAPTURE_), keyowner);
551
552         first = true;
553         midpoint = '0 0 0';
554         firstorigin = '0 0 0';
555         lastorigin = '0 0 0';
556         FOR_EACH_KH_KEY(key)
557         {
558                 vector thisorigin;
559
560                 thisorigin = kh_AttachedOrigin(key);
561                 //dprint("Key origin: ", vtos(thisorigin), "\n");
562                 midpoint += thisorigin;
563
564                 if(!first)
565                         te_lightning2(world, lastorigin, thisorigin);
566                 lastorigin = thisorigin;
567                 if(first)
568                         firstorigin = thisorigin;
569                 first = false;
570         }
571         if(kh_teams > 2)
572         {
573                 te_lightning2(world, lastorigin, firstorigin);
574         }
575         midpoint = midpoint * (1 / kh_teams);
576         te_customflash(midpoint, 1000, 1, Team_ColorRGB(teem) * 0.5 + '0.5 0.5 0.5');  // make the color >=0.5 in each component
577
578         play2all(kh_sound_capture);
579         kh_FinishRound();
580 }
581
582 void kh_LoserTeam(float teem, entity lostkey)  // runs when a player pushes a flag carrier off the map
583 {
584         entity player, key, attacker;
585         float players;
586         float keys;
587         float f;
588
589         attacker = world;
590         if(lostkey.pusher)
591                 if(lostkey.pusher.team != teem)
592                         if(IS_PLAYER(lostkey.pusher))
593                                 attacker = lostkey.pusher;
594
595         players = keys = 0;
596
597         if(attacker)
598         {
599                 if(lostkey.kh_previous_owner)
600                         kh_Scores_Event(lostkey.kh_previous_owner, world, "pushed", 0, -autocvar_g_balance_keyhunt_score_push);
601                         // don't actually GIVE him the -nn points, just log
602                 kh_Scores_Event(attacker, world, "push", autocvar_g_balance_keyhunt_score_push, 0);
603                 PlayerScore_Add(attacker, SP_KH_PUSHES, 1);
604                 //centerprint(attacker, "Your push is the best!"); // does this really need to exist?
605         }
606         else
607         {
608                 float of, fragsleft, i, j, thisteam;
609                 of = autocvar_g_balance_keyhunt_score_destroyed_ownfactor;
610
611                 FOR_EACH_PLAYER(player)
612                         if(player.team != teem)
613                                 ++players;
614
615                 FOR_EACH_KH_KEY(key)
616                         if(key.owner && key.team != teem)
617                                 ++keys;
618
619                 if(lostkey.kh_previous_owner)
620                         kh_Scores_Event(lostkey.kh_previous_owner, world, "destroyed", 0, -autocvar_g_balance_keyhunt_score_destroyed);
621                         // don't actually GIVE him the -nn points, just log
622
623                 if(lostkey.kh_previous_owner.playerid == lostkey.kh_previous_owner_playerid)
624                         PlayerScore_Add(lostkey.kh_previous_owner, SP_KH_DESTROYS, 1);
625
626                 DistributeEvenly_Init(autocvar_g_balance_keyhunt_score_destroyed, keys * of + players);
627
628                 FOR_EACH_KH_KEY(key)
629                         if(key.owner && key.team != teem)
630                         {
631                                 f = DistributeEvenly_Get(of);
632                                 kh_Scores_Event(key.owner, world, "destroyed_holdingkey", f, 0);
633                         }
634
635                 fragsleft = DistributeEvenly_Get(players);
636
637                 // Now distribute these among all other teams...
638                 j = kh_teams - 1;
639                 for(i = 0; i < kh_teams; ++i)
640                 {
641                         thisteam = kh_Team_ByID(i);
642                         if(thisteam == teem) // bad boy, no cookie - this WILL happen
643                                 continue;
644
645                         players = 0;
646                         FOR_EACH_PLAYER(player)
647                                 if(player.team == thisteam)
648                                         ++players;
649
650                         DistributeEvenly_Init(fragsleft, j);
651                         fragsleft = DistributeEvenly_Get(j - 1);
652                         DistributeEvenly_Init(DistributeEvenly_Get(1), players);
653
654                         FOR_EACH_PLAYER(player)
655                                 if(player.team == thisteam)
656                                 {
657                                         f = DistributeEvenly_Get(1);
658                                         kh_Scores_Event(player, world, "destroyed", f, 0);
659                                 }
660
661                         --j;
662                 }
663         }
664
665         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(lostkey, INFO_KEYHUNT_LOST_), lostkey.kh_previous_owner.netname);
666
667         play2all(kh_sound_destroy);
668         te_tarexplosion(lostkey.origin);
669
670         kh_FinishRound();
671 }
672
673 void kh_Key_Think()  // runs all the time
674 {
675         entity head;
676         //entity player;  // needed by FOR_EACH_PLAYER
677
678         if(intermission_running)
679                 return;
680
681         if(self.owner)
682         {
683 #ifndef KH_PLAYER_USE_ATTACHMENT
684                 makevectors('0 1 0' * (self.cnt + (time % 360) * KH_KEY_XYSPEED));
685                 setorigin(self, v_forward * KH_KEY_XYDIST + '0 0 1' * self.origin.z);
686 #endif
687         }
688
689         // if in nodrop or time over, end the round
690         if(!self.owner)
691                 if(time > self.pain_finished)
692                         kh_LoserTeam(self.team, self);
693
694         if(self.owner)
695         if(kh_Key_AllOwnedByWhichTeam() != -1)
696         {
697                 if(self.siren_time < time)
698                 {
699                         sound(self.owner, CH_TRIGGER, kh_sound_alarm, VOL_BASE, ATTEN_NORM);  // play a simple alarm
700                         self.siren_time = time + 2.5;  // repeat every 2.5 seconds
701                 }
702
703                 entity key;
704                 vector p;
705                 p = self.owner.origin;
706                 FOR_EACH_KH_KEY(key)
707                         if(vlen(key.owner.origin - p) > autocvar_g_balance_keyhunt_maxdist)
708                                 goto not_winning;
709                 kh_WinnerTeam(self.team);
710 :not_winning
711         }
712
713         if(kh_interferemsg_time && time > kh_interferemsg_time)
714         {
715                 kh_interferemsg_time = 0;
716                 FOR_EACH_PLAYER(head)
717                 {
718                         if(head.team == kh_interferemsg_team)
719                                 if(head.kh_next)
720                                         Send_Notification(NOTIF_ONE, head, MSG_CENTER, CENTER_KEYHUNT_MEET);
721                                 else
722                                         Send_Notification(NOTIF_ONE, head, MSG_CENTER, CENTER_KEYHUNT_HELP);
723                         else
724                                 Send_Notification(NOTIF_ONE, head, MSG_CENTER, APP_TEAM_NUM_4(kh_interferemsg_team, CENTER_KEYHUNT_INTERFERE_));
725                 }
726         }
727
728         self.nextthink = time + 0.05;
729 }
730
731 void key_reset()
732 {
733         kh_Key_AssignTo(self, world);
734         kh_Key_Remove(self);
735 }
736
737 const string STR_ITEM_KH_KEY = "item_kh_key";
738 void kh_Key_Spawn(entity initial_owner, float angle, float i)  // runs every time a new flag is created, ie after all the keys have been collected
739 {
740         entity key;
741         key = spawn();
742         key.count = i;
743         key.classname = STR_ITEM_KH_KEY;
744         key.touch = kh_Key_Touch;
745         key.think = kh_Key_Think;
746         key.nextthink = time;
747         key.items = IT_KEY1 | IT_KEY2;
748         key.cnt = angle;
749         key.angles = '0 360 0' * random();
750         key.event_damage = kh_Key_Damage;
751         key.takedamage = DAMAGE_YES;
752         key.modelindex = kh_key_dropped;
753         key.model = "key";
754         key.kh_dropperteam = 0;
755         key.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP | DPCONTENTS_BOTCLIP;
756         setsize(key, KH_KEY_MIN, KH_KEY_MAX);
757         key.colormod = Team_ColorRGB(initial_owner.team) * KH_KEY_BRIGHTNESS;
758         key.reset = key_reset;
759
760         switch(initial_owner.team)
761         {
762                 case NUM_TEAM_1:
763                         key.netname = "^1red key";
764                         break;
765                 case NUM_TEAM_2:
766                         key.netname = "^4blue key";
767                         break;
768                 case NUM_TEAM_3:
769                         key.netname = "^3yellow key";
770                         break;
771                 case NUM_TEAM_4:
772                         key.netname = "^6pink key";
773                         break;
774                 default:
775                         key.netname = "NETGIER key";
776                         break;
777         }
778
779         // link into key list
780         key.kh_worldkeynext = kh_worldkeylist;
781         kh_worldkeylist = key;
782
783         Send_Notification(NOTIF_ONE, initial_owner, MSG_CENTER, APP_TEAM_NUM_4(initial_owner.team, CENTER_KEYHUNT_START_));
784
785         WaypointSprite_Spawn(WP_KeyDropped, 0, 0, key, '0 0 1' * KH_KEY_WP_ZSHIFT, world, key.team, key, waypointsprite_attachedforcarrier, false, RADARICON_FLAG);
786         key.waypointsprite_attachedforcarrier.waypointsprite_visible_for_player = kh_Key_waypointsprite_visible_for_player;
787
788         kh_Key_AssignTo(key, initial_owner);
789 }
790
791 // -1 when no team completely owns all keys yet
792 float kh_Key_AllOwnedByWhichTeam()  // constantly called. check to see if all the keys are owned by the same team
793 {
794         entity key;
795         float teem;
796         float keys;
797
798         teem = -1;
799         keys = kh_teams;
800         FOR_EACH_KH_KEY(key)
801         {
802                 if(!key.owner)
803                         return -1;
804                 if(teem == -1)
805                         teem = key.team;
806                 else if(teem != key.team)
807                         return -1;
808                 --keys;
809         }
810         if(keys != 0)
811                 return -1;
812         return teem;
813 }
814
815 void kh_Key_DropOne(entity key)
816 {
817         // prevent collecting this one for some time
818         entity player;
819         player = key.owner;
820
821         key.kh_droptime = time;
822         key.enemy = player;
823
824         kh_Scores_Event(player, key, "dropkey", 0, 0);
825         PlayerScore_Add(player, SP_KH_LOSSES, 1);
826         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(key, INFO_KEYHUNT_DROP_), player.netname);
827
828         kh_Key_AssignTo(key, world);
829         makevectors(player.v_angle);
830         key.velocity = W_CalculateProjectileVelocity(player.velocity, autocvar_g_balance_keyhunt_throwvelocity * v_forward, false);
831         key.pusher = world;
832         key.pushltime = time + autocvar_g_balance_keyhunt_protecttime;
833         key.kh_dropperteam = key.team;
834
835         sound(player, CH_TRIGGER, kh_sound_drop, VOL_BASE, ATTEN_NORM);
836 }
837
838 void kh_Key_DropAll(entity player, float suicide) // runs whenever a player dies
839 {
840         entity key;
841         entity mypusher;
842         if(player.kh_next)
843         {
844                 mypusher = world;
845                 if(player.pusher)
846                         if(time < player.pushltime)
847                                 mypusher = player.pusher;
848                 while((key = player.kh_next))
849                 {
850                         kh_Scores_Event(player, key, "losekey", 0, 0);
851                         PlayerScore_Add(player, SP_KH_LOSSES, 1);
852                         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(key, INFO_KEYHUNT_LOST_), player.netname);
853                         kh_Key_AssignTo(key, world);
854                         makevectors('-1 0 0' * (45 + 45 * random()) + '0 360 0' * random());
855                         key.velocity = W_CalculateProjectileVelocity(player.velocity, autocvar_g_balance_keyhunt_dropvelocity * v_forward, false);
856                         key.pusher = mypusher;
857                         key.pushltime = time + autocvar_g_balance_keyhunt_protecttime;
858                         if(suicide)
859                                 key.kh_dropperteam = player.team;
860                 }
861                 sound(player, CH_TRIGGER, kh_sound_drop, VOL_BASE, ATTEN_NORM);
862         }
863 }
864
865 float kh_CheckPlayers(float num)
866 {
867         if(num < kh_teams)
868         {
869                 float t_team = kh_Team_ByID(num);
870                 float players = 0;
871                 entity tmp_player;
872                 FOR_EACH_PLAYER(tmp_player)
873                         if(tmp_player.deadflag == DEAD_NO)
874                                 if(!tmp_player.BUTTON_CHAT)
875                                         if(tmp_player.team == t_team)
876                                                 ++players;
877
878                 if (!players) { return t_team; }
879         }
880         return 0;
881 }
882
883 #define KH_READY_TEAMS() (!p1 + !p2 + ((kh_teams >= 3) ? !p3 : p3) + ((kh_teams >= 4) ? !p4 : p4))
884 #define KH_READY_TEAMS_OK() (KH_READY_TEAMS() == kh_teams)
885 void kh_WaitForPlayers()  // delay start of the round until enough players are present
886 {
887         if(time < game_starttime)
888         {
889                 kh_Controller_SetThink(game_starttime - time + 0.1, kh_WaitForPlayers);
890                 return;
891         }
892
893         static float prev_missing_teams_mask;
894         float p1 = kh_CheckPlayers(0), p2 = kh_CheckPlayers(1), p3 = kh_CheckPlayers(2), p4 = kh_CheckPlayers(3);
895         if(KH_READY_TEAMS_OK())
896         {
897                 if(prev_missing_teams_mask > 0)
898                         Kill_Notification(NOTIF_ALL, world, MSG_CENTER_CPID, CPID_MISSING_TEAMS);
899                 prev_missing_teams_mask = -1;
900                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_KEYHUNT_ROUNDSTART, autocvar_g_balance_keyhunt_delay_round);
901                 kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_round, kh_StartRound);
902         }
903         else
904         {
905                 if(player_count == 0)
906                 {
907                         if(prev_missing_teams_mask > 0)
908                                 Kill_Notification(NOTIF_ALL, world, MSG_CENTER_CPID, CPID_MISSING_TEAMS);
909                         prev_missing_teams_mask = -1;
910                 }
911                 else
912                 {
913                         float missing_teams_mask = (!!p1) + (!!p2) * 2;
914                         if(kh_teams >= 3) missing_teams_mask += (!!p3) * 4;
915                         if(kh_teams >= 4) missing_teams_mask += (!!p4) * 8;
916                         if(prev_missing_teams_mask != missing_teams_mask)
917                         {
918                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_MISSING_TEAMS, missing_teams_mask);
919                                 prev_missing_teams_mask = missing_teams_mask;
920                         }
921                 }
922                 kh_Controller_SetThink(1, kh_WaitForPlayers);
923         }
924 }
925
926 void kh_EnableTrackingDevice()  // runs after each round
927 {
928         Kill_Notification(NOTIF_ALL, world, MSG_CENTER_CPID, CPID_KEYHUNT);
929         Kill_Notification(NOTIF_ALL, world, MSG_CENTER_CPID, CPID_KEYHUNT_OTHER);
930
931         kh_tracking_enabled = true;
932 }
933
934 void kh_StartRound()  // runs at the start of each round
935 {
936         float i, players, teem;
937         entity player;
938
939         if(time < game_starttime)
940         {
941                 kh_Controller_SetThink(game_starttime - time + 0.1, kh_WaitForPlayers);
942                 return;
943         }
944
945         float p1 = kh_CheckPlayers(0), p2 = kh_CheckPlayers(1), p3 = kh_CheckPlayers(2), p4 = kh_CheckPlayers(3);
946         if(!KH_READY_TEAMS_OK())
947         {
948                 kh_Controller_SetThink(1, kh_WaitForPlayers);
949                 return;
950         }
951
952         Kill_Notification(NOTIF_ALL, world, MSG_CENTER_CPID, CPID_KEYHUNT);
953         Kill_Notification(NOTIF_ALL, world, MSG_CENTER_CPID, CPID_KEYHUNT_OTHER);
954
955         for(i = 0; i < kh_teams; ++i)
956         {
957                 teem = kh_Team_ByID(i);
958                 players = 0;
959                 entity my_player = world;
960                 FOR_EACH_PLAYER(player)
961                         if(player.deadflag == DEAD_NO)
962                                 if(!player.BUTTON_CHAT)
963                                         if(player.team == teem)
964                                         {
965                                                 ++players;
966                                                 if(random() * players <= 1)
967                                                         my_player = player;
968                                         }
969                 kh_Key_Spawn(my_player, 360 * i / kh_teams, i);
970         }
971
972         kh_tracking_enabled = false;
973         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_KEYHUNT_SCAN, autocvar_g_balance_keyhunt_delay_tracking);
974         kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_tracking, kh_EnableTrackingDevice);
975 }
976
977 float kh_HandleFrags(entity attacker, entity targ, float f)  // adds to the player score
978 {
979         if(attacker == targ)
980                 return f;
981
982         if(targ.kh_next)
983         {
984                 if(attacker.team == targ.team)
985                 {
986                         entity k;
987                         float nk;
988                         nk = 0;
989                         for(k = targ.kh_next; k != world; k = k.kh_next)
990                                 ++nk;
991                         kh_Scores_Event(attacker, targ.kh_next, "carrierfrag", -nk * autocvar_g_balance_keyhunt_score_collect, 0);
992                 }
993                 else
994                 {
995                         kh_Scores_Event(attacker, targ.kh_next, "carrierfrag", autocvar_g_balance_keyhunt_score_carrierfrag-1, 0);
996                         PlayerScore_Add(attacker, SP_KH_KCKILLS, 1);
997                         // the frag gets added later
998                 }
999         }
1000
1001         return f;
1002 }
1003
1004 void kh_Initialize()  // sets up th KH environment
1005 {
1006         precache_sound(kh_sound_capture);
1007         precache_sound(kh_sound_destroy);
1008         precache_sound(kh_sound_drop);
1009         precache_sound(kh_sound_collect);
1010         precache_sound(kh_sound_alarm);  // the new siren
1011
1012 #ifdef KH_PLAYER_USE_CARRIEDMODEL
1013         precache_model("models/keyhunt/key-carried.md3");
1014 #endif
1015         precache_model("models/keyhunt/key.md3");
1016
1017         // setup variables
1018         kh_teams = autocvar_g_keyhunt_teams_override;
1019         if(kh_teams < 2)
1020                 kh_teams = autocvar_g_keyhunt_teams;
1021         kh_teams = bound(2, kh_teams, 4);
1022
1023         // make a KH entity for controlling the game
1024         kh_controller = spawn();
1025         kh_controller.think = kh_Controller_Think;
1026         kh_Controller_SetThink(0, kh_WaitForPlayers);
1027
1028         setmodel(kh_controller, "models/keyhunt/key.md3");
1029         kh_key_dropped = kh_controller.modelindex;
1030         /*
1031         dprint(vtos(kh_controller.mins));
1032         dprint(vtos(kh_controller.maxs));
1033         dprint("\n");
1034         */
1035 #ifdef KH_PLAYER_USE_CARRIEDMODEL
1036         setmodel(kh_controller, "models/keyhunt/key-carried.md3");
1037         kh_key_carried = kh_controller.modelindex;
1038 #else
1039         kh_key_carried = kh_key_dropped;
1040 #endif
1041
1042         kh_controller.model = "";
1043         kh_controller.modelindex = 0;
1044
1045         addstat(STAT_KH_KEYS, AS_INT, kh_state);
1046
1047         kh_ScoreRules(kh_teams);
1048 }
1049
1050 void kh_finalize()
1051 {
1052         // to be called before intermission
1053         kh_FinishRound();
1054         remove(kh_controller);
1055         kh_controller = world;
1056 }
1057
1058 // register this as a mutator
1059
1060 MUTATOR_HOOKFUNCTION(kh_Key_DropAll)
1061 {
1062         kh_Key_DropAll(self, true);
1063         return 0;
1064 }
1065
1066 MUTATOR_HOOKFUNCTION(kh_PlayerDies)
1067 {
1068         if(self == other)
1069                 kh_Key_DropAll(self, true);
1070         else if(IS_PLAYER(other))
1071                 kh_Key_DropAll(self, false);
1072         else
1073                 kh_Key_DropAll(self, true);
1074         return 0;
1075 }
1076
1077 MUTATOR_HOOKFUNCTION(kh_GiveFragsForKill)
1078 {
1079         frag_score = kh_HandleFrags(frag_attacker, frag_target, frag_score);
1080         return 0;
1081 }
1082
1083 MUTATOR_HOOKFUNCTION(kh_finalize)
1084 {
1085         kh_finalize();
1086         return 0;
1087 }
1088
1089 MUTATOR_HOOKFUNCTION(kh_GetTeamCount)
1090 {
1091         ret_float = kh_teams;
1092         return 0;
1093 }
1094
1095 MUTATOR_HOOKFUNCTION(kh_SpectateCopy)
1096 {
1097         self.kh_state = other.kh_state;
1098         return 0;
1099 }
1100
1101 MUTATOR_HOOKFUNCTION(kh_PlayerUseKey)
1102 {
1103         if(MUTATOR_RETURNVALUE == 0)
1104         {
1105                 entity k;
1106                 k = self.kh_next;
1107                 if(k)
1108                 {
1109                         kh_Key_DropOne(k);
1110                         return 1;
1111                 }
1112         }
1113         return 0;
1114 }
1115
1116 MUTATOR_DEFINITION(gamemode_keyhunt)
1117 {
1118         MUTATOR_HOOK(MakePlayerObserver, kh_Key_DropAll, CBC_ORDER_ANY);
1119         MUTATOR_HOOK(ClientDisconnect, kh_Key_DropAll, CBC_ORDER_ANY);
1120         MUTATOR_HOOK(PlayerDies, kh_PlayerDies, CBC_ORDER_ANY);
1121         MUTATOR_HOOK(GiveFragsForKill, kh_GiveFragsForKill, CBC_ORDER_FIRST);
1122         MUTATOR_HOOK(MatchEnd, kh_finalize, CBC_ORDER_ANY);
1123         MUTATOR_HOOK(GetTeamCount, kh_GetTeamCount, CBC_ORDER_EXCLUSIVE);
1124         MUTATOR_HOOK(SpectateCopy, kh_SpectateCopy, CBC_ORDER_ANY);
1125         MUTATOR_HOOK(PlayerUseKey, kh_PlayerUseKey, CBC_ORDER_ANY);
1126
1127         MUTATOR_ONADD
1128         {
1129                 if(time > 1) // game loads at time 1
1130                         error("This is a game type and it cannot be added at runtime.");
1131                 kh_Initialize();
1132         }
1133
1134         MUTATOR_ONROLLBACK_OR_REMOVE
1135         {
1136                 // we actually cannot roll back kh_Initialize here
1137                 // BUT: we don't need to! If this gets called, adding always
1138                 // succeeds.
1139         }
1140
1141         MUTATOR_ONREMOVE
1142         {
1143                 LOG_INFO("This is a game type and it cannot be removed at runtime.");
1144                 return -1;
1145         }
1146
1147         return 0;
1148 }