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