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