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