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