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