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