Merge branch 'master' into terencehill/lms_itemtimes_fix
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / gamemodes / gamemode / onslaught / onslaught.qc
1 #ifndef GAMEMODE_ONSLAUGHT_H
2 #define GAMEMODE_ONSLAUGHT_H
3
4 float autocvar_g_onslaught_point_limit;
5 void ons_Initialize();
6
7 REGISTER_MUTATOR(ons, false)
8 {
9         MUTATOR_ONADD
10         {
11                 if (time > 1) // game loads at time 1
12                         error("This is a game type and it cannot be added at runtime.");
13                 ons_Initialize();
14
15                 ActivateTeamplay();
16                 SetLimits(autocvar_g_onslaught_point_limit, -1, -1, -1);
17                 have_team_spawns = -1; // request team spawns
18         }
19
20         MUTATOR_ONROLLBACK_OR_REMOVE
21         {
22                 // we actually cannot roll back ons_Initialize here
23                 // BUT: we don't need to! If this gets called, adding always
24                 // succeeds.
25         }
26
27         MUTATOR_ONREMOVE
28         {
29                 LOG_INFO("This is a game type and it cannot be removed at runtime.");
30                 return -1;
31         }
32
33         return false;
34 }
35
36 #ifdef SVQC
37
38 .entity ons_toucher; // player who touched the control point
39
40 // control point / generator constants
41 const float ONS_CP_THINKRATE = 0.2;
42 const float GEN_THINKRATE = 1;
43 #define CPGEN_SPAWN_OFFSET ('0 0 1' * (PL_MAX_CONST.z - 13))
44 const vector CPGEN_WAYPOINT_OFFSET = ('0 0 128');
45 const vector CPICON_OFFSET = ('0 0 96');
46
47 // list of generators on the map
48 entity ons_worldgeneratorlist;
49 .entity ons_worldgeneratornext;
50 .entity ons_stalegeneratornext;
51
52 // list of control points on the map
53 entity ons_worldcplist;
54 .entity ons_worldcpnext;
55 .entity ons_stalecpnext;
56
57 // list of links on the map
58 entity ons_worldlinklist;
59 .entity ons_worldlinknext;
60 .entity ons_stalelinknext;
61
62 // definitions
63 .entity sprite;
64 .string target2;
65 .int iscaptured;
66 .int islinked;
67 .int isshielded;
68 .float lasthealth;
69 .int lastteam;
70 .int lastshielded;
71 .int lastcaptured;
72
73 .bool waslinked;
74
75 bool ons_stalemate;
76
77 .float teleport_antispam;
78
79 .bool ons_roundlost = _STAT(ROUNDLOST);
80
81 // waypoint sprites
82 .entity bot_basewaypoint; // generator waypointsprite
83
84 .bool isgenneighbor[17];
85 .bool iscpneighbor[17];
86 float ons_notification_time[17];
87
88 .float ons_overtime_damagedelay;
89
90 .vector ons_deathloc;
91
92 .entity ons_spawn_by;
93
94 // declarations for functions used outside gamemode_onslaught.qc
95 void ons_Generator_UpdateSprite(entity e);
96 void ons_ControlPoint_UpdateSprite(entity e);
97 bool ons_ControlPoint_Attackable(entity cp, int teamnumber);
98
99 // CaptureShield: Prevent capturing or destroying control point/generator if it is not available yet
100 float ons_captureshield_force; // push force of the shield
101
102 // bot player logic
103 const int HAVOCBOT_ONS_ROLE_NONE                = 0;
104 const int HAVOCBOT_ONS_ROLE_DEFENSE     = 2;
105 const int HAVOCBOT_ONS_ROLE_ASSISTANT   = 4;
106 const int HAVOCBOT_ONS_ROLE_OFFENSE     = 8;
107
108 .entity havocbot_ons_target;
109
110 .int havocbot_role_flags;
111 .float havocbot_attack_time;
112
113 void havocbot_role_ons_defense();
114 void havocbot_role_ons_offense();
115 void havocbot_role_ons_assistant();
116
117 void havocbot_ons_reset_role(entity bot);
118 void havocbot_goalrating_items(float ratingscale, vector org, float sradius);
119 void havocbot_goalrating_enemyplayers(float ratingscale, vector org, float sradius);
120
121 // score rule declarations
122 const int ST_ONS_CAPS = 1;
123 const int SP_ONS_CAPS = 4;
124 const int SP_ONS_TAKES = 6;
125
126 #endif
127 #endif
128
129 #ifdef IMPLEMENTATION
130
131 #include "sv_controlpoint.qh"
132 #include "sv_generator.qh"
133
134 bool g_onslaught;
135
136 float autocvar_g_onslaught_teleport_wait;
137 bool autocvar_g_onslaught_spawn_at_controlpoints;
138 bool autocvar_g_onslaught_spawn_at_generator;
139 float autocvar_g_onslaught_cp_proxydecap;
140 float autocvar_g_onslaught_cp_proxydecap_distance = 512;
141 float autocvar_g_onslaught_cp_proxydecap_dps = 100;
142 float autocvar_g_onslaught_spawn_at_controlpoints_chance = 0.5;
143 float autocvar_g_onslaught_spawn_at_controlpoints_random;
144 float autocvar_g_onslaught_spawn_at_generator_chance;
145 float autocvar_g_onslaught_spawn_at_generator_random;
146 float autocvar_g_onslaught_cp_buildhealth;
147 float autocvar_g_onslaught_cp_buildtime;
148 float autocvar_g_onslaught_cp_health;
149 float autocvar_g_onslaught_cp_regen;
150 float autocvar_g_onslaught_gen_health;
151 float autocvar_g_onslaught_shield_force = 100;
152 float autocvar_g_onslaught_allow_vehicle_touch;
153 float autocvar_g_onslaught_round_timelimit;
154 float autocvar_g_onslaught_warmup;
155 float autocvar_g_onslaught_teleport_radius;
156 float autocvar_g_onslaught_spawn_choose;
157 float autocvar_g_onslaught_click_radius;
158
159 void FixSize(entity e);
160
161 // =======================
162 // CaptureShield Functions
163 // =======================
164
165 bool ons_CaptureShield_Customize()
166 {SELFPARAM();
167         entity e = WaypointSprite_getviewentity(other);
168
169         if(!self.enemy.isshielded && (ons_ControlPoint_Attackable(self.enemy, e.team) > 0 || self.enemy.classname != "onslaught_controlpoint")) { return false; }
170         if(SAME_TEAM(self, e)) { return false; }
171
172         return true;
173 }
174
175 void ons_CaptureShield_Touch()
176 {SELFPARAM();
177         if(!self.enemy.isshielded && (ons_ControlPoint_Attackable(self.enemy, other.team) > 0 || self.enemy.classname != "onslaught_controlpoint")) { return; }
178         if(!IS_PLAYER(other)) { return; }
179         if(SAME_TEAM(other, self)) { return; }
180
181         vector mymid = (self.absmin + self.absmax) * 0.5;
182         vector othermid = (other.absmin + other.absmax) * 0.5;
183
184         Damage(other, self, self, 0, DEATH_HURTTRIGGER.m_id, mymid, normalize(othermid - mymid) * ons_captureshield_force);
185
186         if(IS_REAL_CLIENT(other))
187         {
188                 play2(other, SND(ONS_DAMAGEBLOCKEDBYSHIELD));
189
190                 if(self.enemy.classname == "onslaught_generator")
191                         Send_Notification(NOTIF_ONE, other, MSG_CENTER, CENTER_ONS_GENERATOR_SHIELDED);
192                 else
193                         Send_Notification(NOTIF_ONE, other, MSG_CENTER, CENTER_ONS_CONTROLPOINT_SHIELDED);
194         }
195 }
196
197 void ons_CaptureShield_Reset(entity this)
198 {
199         this.colormap = this.enemy.colormap;
200         this.team = this.enemy.team;
201 }
202
203 void ons_CaptureShield_Spawn(entity generator, bool is_generator)
204 {
205         entity shield = new(ons_captureshield);
206
207         shield.enemy = generator;
208         shield.team = generator.team;
209         shield.colormap = generator.colormap;
210         shield.reset = ons_CaptureShield_Reset;
211         shield.touch = ons_CaptureShield_Touch;
212         shield.customizeentityforclient = ons_CaptureShield_Customize;
213         shield.effects = EF_ADDITIVE;
214         shield.movetype = MOVETYPE_NOCLIP;
215         shield.solid = SOLID_TRIGGER;
216         shield.avelocity = '7 0 11';
217         shield.scale = 1;
218         shield.model = ((is_generator) ? "models/onslaught/generator_shield.md3" : "models/onslaught/controlpoint_shield.md3");
219
220         precache_model(shield.model);
221         setorigin(shield, generator.origin);
222         _setmodel(shield, shield.model);
223         setsize(shield, shield.scale * shield.mins, shield.scale * shield.maxs);
224 }
225
226
227 // ==========
228 // Junk Pile
229 // ==========
230
231 void setmodel_fixsize(entity e, Model m)
232 {
233         setmodel(e, m);
234         FixSize(e);
235 }
236
237 void onslaught_updatelinks()
238 {
239         entity l;
240         // first check if the game has ended
241         LOG_DEBUG("--- updatelinks ---\n");
242         // mark generators as being shielded and networked
243         for(l = ons_worldgeneratorlist; l; l = l.ons_worldgeneratornext)
244         {
245                 if (l.iscaptured)
246                         LOG_DEBUG(strcat(etos(l), " (generator) belongs to team ", ftos(l.team), "\n"));
247                 else
248                         LOG_DEBUG(strcat(etos(l), " (generator) is destroyed\n"));
249                 l.islinked = l.iscaptured;
250                 l.isshielded = l.iscaptured;
251                 l.sprite.SendFlags |= 16;
252         }
253         // mark points as shielded and not networked
254         for(l = ons_worldcplist; l; l = l.ons_worldcpnext)
255         {
256                 l.islinked = false;
257                 l.isshielded = true;
258                 int i;
259                 for(i = 0; i < 17; ++i) { l.isgenneighbor[i] = false; l.iscpneighbor[i] = false; }
260                 LOG_DEBUG(strcat(etos(l), " (point) belongs to team ", ftos(l.team), "\n"));
261                 l.sprite.SendFlags |= 16;
262         }
263         // flow power outward from the generators through the network
264         bool stop = false;
265         while (!stop)
266         {
267                 stop = true;
268                 for(l = ons_worldlinklist; l; l = l.ons_worldlinknext)
269                 {
270                         // if both points are captured by the same team, and only one of
271                         // them is powered, mark the other one as powered as well
272                         if (l.enemy.iscaptured && l.goalentity.iscaptured)
273                                 if (l.enemy.islinked != l.goalentity.islinked)
274                                         if(SAME_TEAM(l.enemy, l.goalentity))
275                                         {
276                                                 if (!l.goalentity.islinked)
277                                                 {
278                                                         stop = false;
279                                                         l.goalentity.islinked = true;
280                                                         LOG_DEBUG(strcat(etos(l), " (link) is marking ", etos(l.goalentity), " (point) because its team matches ", etos(l.enemy), " (point)\n"));
281                                                 }
282                                                 else if (!l.enemy.islinked)
283                                                 {
284                                                         stop = false;
285                                                         l.enemy.islinked = true;
286                                                         LOG_DEBUG(strcat(etos(l), " (link) is marking ", etos(l.enemy), " (point) because its team matches ", etos(l.goalentity), " (point)\n"));
287                                                 }
288                                         }
289                 }
290         }
291         // now that we know which points are powered we can mark their neighbors
292         // as unshielded if team differs
293         for(l = ons_worldlinklist; l; l = l.ons_worldlinknext)
294         {
295                 if (l.goalentity.islinked)
296                 {
297                         if(DIFF_TEAM(l.goalentity, l.enemy))
298                         {
299                                 LOG_DEBUG(strcat(etos(l), " (link) is unshielding ", etos(l.enemy), " (point) because its team does not match ", etos(l.goalentity), " (point)\n"));
300                                 l.enemy.isshielded = false;
301                         }
302                         if(l.goalentity.classname == "onslaught_generator")
303                                 l.enemy.isgenneighbor[l.goalentity.team] = true;
304                         else
305                                 l.enemy.iscpneighbor[l.goalentity.team] = true;
306                 }
307                 if (l.enemy.islinked)
308                 {
309                         if(DIFF_TEAM(l.goalentity, l.enemy))
310                         {
311                                 LOG_DEBUG(strcat(etos(l), " (link) is unshielding ", etos(l.goalentity), " (point) because its team does not match ", etos(l.enemy), " (point)\n"));
312                                 l.goalentity.isshielded = false;
313                         }
314                         if(l.enemy.classname == "onslaught_generator")
315                                 l.goalentity.isgenneighbor[l.enemy.team] = true;
316                         else
317                                 l.goalentity.iscpneighbor[l.enemy.team] = true;
318                 }
319         }
320         // now update the generators
321         for(l = ons_worldgeneratorlist; l; l = l.ons_worldgeneratornext)
322         {
323                 if (l.isshielded)
324                 {
325                         LOG_DEBUG(strcat(etos(l), " (generator) is shielded\n"));
326                         l.takedamage = DAMAGE_NO;
327                         l.bot_attack = false;
328                 }
329                 else
330                 {
331                         LOG_DEBUG(strcat(etos(l), " (generator) is not shielded\n"));
332                         l.takedamage = DAMAGE_AIM;
333                         l.bot_attack = true;
334                 }
335
336                 ons_Generator_UpdateSprite(l);
337         }
338         // now update the takedamage and alpha variables on control point icons
339         for(l = ons_worldcplist; l; l = l.ons_worldcpnext)
340         {
341                 if (l.isshielded)
342                 {
343                         LOG_DEBUG(strcat(etos(l), " (point) is shielded\n"));
344                         if (l.goalentity)
345                         {
346                                 l.goalentity.takedamage = DAMAGE_NO;
347                                 l.goalentity.bot_attack = false;
348                         }
349                 }
350                 else
351                 {
352                         LOG_DEBUG(strcat(etos(l), " (point) is not shielded\n"));
353                         if (l.goalentity)
354                         {
355                                 l.goalentity.takedamage = DAMAGE_AIM;
356                                 l.goalentity.bot_attack = true;
357                         }
358                 }
359                 ons_ControlPoint_UpdateSprite(l);
360         }
361         l = findchain(classname, "ons_captureshield");
362         while(l)
363         {
364                 l.team = l.enemy.team;
365                 l.colormap = l.enemy.colormap;
366                 l = l.chain;
367         }
368 }
369
370
371 // ===================
372 // Main Link Functions
373 // ===================
374
375 bool ons_Link_Send(entity this, entity to, int sendflags)
376 {
377         WriteHeader(MSG_ENTITY, ENT_CLIENT_RADARLINK);
378         WriteByte(MSG_ENTITY, sendflags);
379         if(sendflags & 1)
380         {
381                 WriteCoord(MSG_ENTITY, self.goalentity.origin_x);
382                 WriteCoord(MSG_ENTITY, self.goalentity.origin_y);
383                 WriteCoord(MSG_ENTITY, self.goalentity.origin_z);
384         }
385         if(sendflags & 2)
386         {
387                 WriteCoord(MSG_ENTITY, self.enemy.origin_x);
388                 WriteCoord(MSG_ENTITY, self.enemy.origin_y);
389                 WriteCoord(MSG_ENTITY, self.enemy.origin_z);
390         }
391         if(sendflags & 4)
392         {
393                 WriteByte(MSG_ENTITY, self.clientcolors); // which is goalentity's color + enemy's color * 16
394         }
395         return true;
396 }
397
398 void ons_Link_CheckUpdate()
399 {SELFPARAM();
400         // TODO check if the two sides have moved (currently they won't move anyway)
401         float cc = 0, cc1 = 0, cc2 = 0;
402
403         if(self.goalentity.islinked || self.goalentity.iscaptured) { cc1 = (self.goalentity.team - 1) * 0x01; }
404         if(self.enemy.islinked || self.enemy.iscaptured) { cc2 = (self.enemy.team - 1) * 0x10; }
405
406         cc = cc1 + cc2;
407
408         if(cc != self.clientcolors)
409         {
410                 self.clientcolors = cc;
411                 self.SendFlags |= 4;
412         }
413
414         self.nextthink = time;
415 }
416
417 void ons_DelayedLinkSetup()
418 {SELFPARAM();
419         self.goalentity = find(world, targetname, self.target);
420         self.enemy = find(world, targetname, self.target2);
421         if(!self.goalentity) { objerror("can not find target\n"); }
422         if(!self.enemy) { objerror("can not find target2\n"); }
423
424         LOG_DEBUG(strcat(etos(self.goalentity), " linked with ", etos(self.enemy), "\n"));
425         self.SendFlags |= 3;
426         self.think = ons_Link_CheckUpdate;
427         self.nextthink = time;
428 }
429
430
431 // =============================
432 // Main Control Point Functions
433 // =============================
434
435 int ons_ControlPoint_CanBeLinked(entity cp, int teamnumber)
436 {
437         if(cp.isgenneighbor[teamnumber]) { return 2; }
438         if(cp.iscpneighbor[teamnumber]) { return 1; }
439
440         return 0;
441 }
442
443 int ons_ControlPoint_Attackable(entity cp, int teamnumber)
444         // -2: SAME TEAM, attackable by enemy!
445         // -1: SAME TEAM!
446         // 0: off limits
447         // 1: attack it
448         // 2: touch it
449         // 3: attack it (HIGH PRIO)
450         // 4: touch it (HIGH PRIO)
451 {
452         int a;
453
454         if(cp.isshielded)
455         {
456                 return 0;
457         }
458         else if(cp.goalentity)
459         {
460                 // if there's already an icon built, nothing happens
461                 if(cp.team == teamnumber)
462                 {
463                         a = ons_ControlPoint_CanBeLinked(cp, teamnumber);
464                         if(a) // attackable by enemy?
465                                 return -2; // EMERGENCY!
466                         return -1;
467                 }
468                 // we know it can be linked, so no need to check
469                 // but...
470                 a = ons_ControlPoint_CanBeLinked(cp, teamnumber);
471                 if(a == 2) // near our generator?
472                         return 3; // EMERGENCY!
473                 return 1;
474         }
475         else
476         {
477                 // free point
478                 if(ons_ControlPoint_CanBeLinked(cp, teamnumber))
479                 {
480                         a = ons_ControlPoint_CanBeLinked(cp, teamnumber); // why was this here NUM_TEAM_1 + NUM_TEAM_2 - t
481                         if(a == 2)
482                                 return 4; // GET THIS ONE NOW!
483                         else
484                                 return 2; // TOUCH ME
485                 }
486         }
487         return 0;
488 }
489
490 void ons_ControlPoint_Icon_Damage(entity inflictor, entity attacker, float damage, int deathtype, vector hitloc, vector force)
491 {SELFPARAM();
492         if(damage <= 0) { return; }
493
494         if (self.owner.isshielded)
495         {
496                 // this is protected by a shield, so ignore the damage
497                 if (time > self.pain_finished)
498                         if (IS_PLAYER(attacker))
499                         {
500                                 play2(attacker, SND(ONS_DAMAGEBLOCKEDBYSHIELD));
501                                 self.pain_finished = time + 1;
502                                 attacker.typehitsound += 1; // play both sounds (shield is way too quiet)
503                         }
504
505                 return;
506         }
507
508         if(IS_PLAYER(attacker))
509         if(time - ons_notification_time[self.team] > 10)
510         {
511                 play2team(self.team, SND(ONS_CONTROLPOINT_UNDERATTACK));
512                 ons_notification_time[self.team] = time;
513         }
514
515         self.health = self.health - damage;
516         if(self.owner.iscaptured)
517                 WaypointSprite_UpdateHealth(self.owner.sprite, self.health);
518         else
519                 WaypointSprite_UpdateBuildFinished(self.owner.sprite, time + (self.max_health - self.health) / (self.count / ONS_CP_THINKRATE));
520         self.pain_finished = time + 1;
521         // particles on every hit
522         pointparticles(EFFECT_SPARKS, hitloc, force*-1, 1);
523         //sound on every hit
524         if (random() < 0.5)
525                 sound(self, CH_TRIGGER, SND_ONS_HIT1, VOL_BASE+0.3, ATTEN_NORM);
526         else
527                 sound(self, CH_TRIGGER, SND_ONS_HIT2, VOL_BASE+0.3, ATTEN_NORM);
528
529         if (self.health < 0)
530         {
531                 sound(self, CH_TRIGGER, SND_GRENADE_IMPACT, VOL_BASE, ATTEN_NORM);
532                 pointparticles(EFFECT_ROCKET_EXPLODE, self.origin, '0 0 0', 1);
533                 Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_NUM_4(self.team, INFO_ONSLAUGHT_CPDESTROYED_), self.owner.message, attacker.netname);
534
535                 PlayerScore_Add(attacker, SP_ONS_TAKES, 1);
536                 PlayerScore_Add(attacker, SP_SCORE, 10);
537
538                 self.owner.goalentity = world;
539                 self.owner.islinked = false;
540                 self.owner.iscaptured = false;
541                 self.owner.team = 0;
542                 self.owner.colormap = 1024;
543
544                 WaypointSprite_UpdateMaxHealth(self.owner.sprite, 0);
545
546                 onslaught_updatelinks();
547
548                 // Use targets now (somebody make sure this is in the right place..)
549                 setself(self.owner);
550                 activator = self;
551                 SUB_UseTargets ();
552                 setself(this);
553
554                 self.owner.waslinked = self.owner.islinked;
555                 if(self.owner.model != "models/onslaught/controlpoint_pad.md3")
556                         setmodel_fixsize(self.owner, MDL_ONS_CP_PAD1);
557                 //setsize(self, '-32 -32 0', '32 32 8');
558
559                 remove(self);
560         }
561
562         self.SendFlags |= CPSF_STATUS;
563 }
564
565 void ons_ControlPoint_Icon_Think()
566 {SELFPARAM();
567         self.nextthink = time + ONS_CP_THINKRATE;
568
569         if(autocvar_g_onslaught_cp_proxydecap)
570         {
571                 int _enemy_count = 0;
572                 int _friendly_count = 0;
573                 float _dist;
574
575                 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it), LAMBDA(
576                         _dist = vlen(it.origin - self.origin);
577                         if(_dist < autocvar_g_onslaught_cp_proxydecap_distance)
578                         {
579                                 if(SAME_TEAM(it, self))
580                                         ++_friendly_count;
581                                 else
582                                         ++_enemy_count;
583                         }
584                 ));
585
586                 _friendly_count = _friendly_count * (autocvar_g_onslaught_cp_proxydecap_dps * ONS_CP_THINKRATE);
587                 _enemy_count = _enemy_count * (autocvar_g_onslaught_cp_proxydecap_dps * ONS_CP_THINKRATE);
588
589                 self.health = bound(0, self.health + (_friendly_count - _enemy_count), self.max_health);
590                 self.SendFlags |= CPSF_STATUS;
591                 if(self.health <= 0)
592                 {
593                         ons_ControlPoint_Icon_Damage(self, self, 1, 0, self.origin, '0 0 0');
594                         return;
595                 }
596         }
597
598         if (time > self.pain_finished + 5)
599         {
600                 if(self.health < self.max_health)
601                 {
602                         self.health = self.health + self.count;
603                         if (self.health >= self.max_health)
604                                 self.health = self.max_health;
605                         WaypointSprite_UpdateHealth(self.owner.sprite, self.health);
606                 }
607         }
608
609         if(self.owner.islinked != self.owner.waslinked)
610         {
611                 // unteam the spawnpoint if needed
612                 int t = self.owner.team;
613                 if(!self.owner.islinked)
614                         self.owner.team = 0;
615
616                 setself(self.owner);
617                 activator = self;
618                 SUB_UseTargets ();
619                 setself(this);
620
621                 self.owner.team = t;
622
623                 self.owner.waslinked = self.owner.islinked;
624         }
625
626         // damaged fx
627         if(random() < 0.6 - self.health / self.max_health)
628         {
629                 Send_Effect(EFFECT_ELECTRIC_SPARKS, self.origin + randompos('-10 -10 -20', '10 10 20'), '0 0 0', 1);
630
631                 if(random() > 0.8)
632                         sound(self, CH_PAIN, SND_ONS_SPARK1, VOL_BASE, ATTEN_NORM);
633                 else if (random() > 0.5)
634                         sound(self, CH_PAIN, SND_ONS_SPARK2, VOL_BASE, ATTEN_NORM);
635         }
636 }
637
638 void ons_ControlPoint_Icon_BuildThink()
639 {SELFPARAM();
640         int a;
641
642         self.nextthink = time + ONS_CP_THINKRATE;
643
644         // only do this if there is power
645         a = ons_ControlPoint_CanBeLinked(self.owner, self.owner.team);
646         if(!a)
647                 return;
648
649         self.health = self.health + self.count;
650
651         self.SendFlags |= CPSF_STATUS;
652
653         if (self.health >= self.max_health)
654         {
655                 self.health = self.max_health;
656                 self.count = autocvar_g_onslaught_cp_regen * ONS_CP_THINKRATE; // slow repair rate from now on
657                 self.think = ons_ControlPoint_Icon_Think;
658                 sound(self, CH_TRIGGER, SND_ONS_CONTROLPOINT_BUILT, VOL_BASE, ATTEN_NORM);
659                 self.owner.iscaptured = true;
660                 self.solid = SOLID_BBOX;
661
662                 Send_Effect(EFFECT_CAP(self.owner.team), self.owner.origin, '0 0 0', 1);
663
664                 WaypointSprite_UpdateMaxHealth(self.owner.sprite, self.max_health);
665                 WaypointSprite_UpdateHealth(self.owner.sprite, self.health);
666
667                 if(IS_PLAYER(self.owner.ons_toucher))
668                 {
669                         Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_ONSLAUGHT_CAPTURE, self.owner.ons_toucher.netname, self.owner.message);
670                         Send_Notification(NOTIF_ALL_EXCEPT, self.owner.ons_toucher, MSG_CENTER, APP_TEAM_ENT_4(self.owner.ons_toucher, CENTER_ONS_CAPTURE_), self.owner.message);
671                         Send_Notification(NOTIF_ONE, self.owner.ons_toucher, MSG_CENTER, CENTER_ONS_CAPTURE, self.owner.message);
672                         PlayerScore_Add(self.owner.ons_toucher, SP_ONS_CAPS, 1);
673                         PlayerTeamScore_AddScore(self.owner.ons_toucher, 10);
674                 }
675
676                 self.owner.ons_toucher = world;
677
678                 onslaught_updatelinks();
679
680                 // Use targets now (somebody make sure this is in the right place..)
681                 setself(self.owner);
682                 activator = self;
683                 SUB_UseTargets ();
684                 setself(this);
685
686                 self.SendFlags |= CPSF_SETUP;
687         }
688         if(self.owner.model != MDL_ONS_CP_PAD2.model_str())
689                 setmodel_fixsize(self.owner, MDL_ONS_CP_PAD2);
690
691         if(random() < 0.9 - self.health / self.max_health)
692                 Send_Effect(EFFECT_RAGE, self.origin + 10 * randomvec(), '0 0 -1', 1);
693 }
694
695 void onslaught_controlpoint_icon_link(entity e, void() spawnproc);
696
697 void ons_ControlPoint_Icon_Spawn(entity cp, entity player)
698 {
699         entity e = new(onslaught_controlpoint_icon);
700
701         setsize(e, CPICON_MIN, CPICON_MAX);
702         setorigin(e, cp.origin + CPICON_OFFSET);
703
704         e.owner = cp;
705         e.max_health = autocvar_g_onslaught_cp_health;
706         e.health = autocvar_g_onslaught_cp_buildhealth;
707         e.solid = SOLID_NOT;
708         e.takedamage = DAMAGE_AIM;
709         e.bot_attack = true;
710         e.event_damage = ons_ControlPoint_Icon_Damage;
711         e.team = player.team;
712         e.colormap = 1024 + (e.team - 1) * 17;
713         e.count = (e.max_health - e.health) * ONS_CP_THINKRATE / autocvar_g_onslaught_cp_buildtime; // how long it takes to build
714
715         sound(e, CH_TRIGGER, SND_ONS_CONTROLPOINT_BUILD, VOL_BASE, ATTEN_NORM);
716
717         cp.goalentity = e;
718         cp.team = e.team;
719         cp.colormap = e.colormap;
720
721         Send_Effect(EFFECT_FLAG_TOUCH(player.team), e.origin, '0 0 0', 1);
722
723         WaypointSprite_UpdateBuildFinished(cp.sprite, time + (e.max_health - e.health) / (e.count / ONS_CP_THINKRATE));
724         WaypointSprite_UpdateRule(cp.sprite,cp.team,SPRITERULE_TEAMPLAY);
725         cp.sprite.SendFlags |= 16;
726
727         onslaught_controlpoint_icon_link(e, ons_ControlPoint_Icon_BuildThink);
728 }
729
730 entity ons_ControlPoint_Waypoint(entity e)
731 {
732         if(e.team)
733         {
734                 int a = ons_ControlPoint_Attackable(e, e.team);
735
736                 if(a == -2) { return WP_OnsCPDefend; } // defend now
737                 if(a == -1 || a == 1 || a == 2) { return WP_OnsCP; } // touch
738                 if(a == 3 || a == 4) { return WP_OnsCPAttack; } // attack
739         }
740         else
741                 return WP_OnsCP;
742
743         return WP_Null;
744 }
745
746 void ons_ControlPoint_UpdateSprite(entity e)
747 {
748         entity s1 = ons_ControlPoint_Waypoint(e);
749         WaypointSprite_UpdateSprites(e.sprite, s1, s1, s1);
750
751         bool sh;
752         sh = !(ons_ControlPoint_CanBeLinked(e, NUM_TEAM_1) || ons_ControlPoint_CanBeLinked(e, NUM_TEAM_2) || ons_ControlPoint_CanBeLinked(e, NUM_TEAM_3) || ons_ControlPoint_CanBeLinked(e, NUM_TEAM_4));
753
754         if(e.lastteam != e.team + 2 || e.lastshielded != sh || e.iscaptured != e.lastcaptured)
755         {
756                 if(e.iscaptured) // don't mess up build bars!
757                 {
758                         if(sh)
759                         {
760                                 WaypointSprite_UpdateMaxHealth(e.sprite, 0);
761                         }
762                         else
763                         {
764                                 WaypointSprite_UpdateMaxHealth(e.sprite, e.goalentity.max_health);
765                                 WaypointSprite_UpdateHealth(e.sprite, e.goalentity.health);
766                         }
767                 }
768                 if(e.lastshielded)
769                 {
770                         if(e.team)
771                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, 0.5 * colormapPaletteColor(e.team - 1, false));
772                         else
773                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, '0.5 0.5 0.5');
774                 }
775                 else
776                 {
777                         if(e.team)
778                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, colormapPaletteColor(e.team - 1, false));
779                         else
780                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, '0.75 0.75 0.75');
781                 }
782                 WaypointSprite_Ping(e.sprite);
783
784                 e.lastteam = e.team + 2;
785                 e.lastshielded = sh;
786                 e.lastcaptured = e.iscaptured;
787         }
788 }
789
790 void ons_ControlPoint_Touch()
791 {SELFPARAM();
792         entity toucher = other;
793         int attackable;
794
795         if(IS_VEHICLE(toucher) && toucher.owner)
796         if(autocvar_g_onslaught_allow_vehicle_touch)
797                 toucher = toucher.owner;
798         else
799                 return;
800
801         if(!IS_PLAYER(toucher)) { return; }
802         if(STAT(FROZEN, toucher)) { return; }
803         if(IS_DEAD(toucher)) { return; }
804
805         if ( SAME_TEAM(self,toucher) )
806         if ( self.iscaptured )
807         {
808                 if(time <= toucher.teleport_antispam)
809                         Send_Notification(NOTIF_ONE, toucher, MSG_CENTER, CENTER_ONS_TELEPORT_ANTISPAM, rint(toucher.teleport_antispam - time));
810                 else
811                         Send_Notification(NOTIF_ONE, toucher, MSG_CENTER, CENTER_ONS_TELEPORT);
812         }
813
814         attackable = ons_ControlPoint_Attackable(self, toucher.team);
815         if(attackable != 2 && attackable != 4)
816                 return;
817         // we've verified that this player has a legitimate claim to this point,
818         // so start building the captured point icon (which only captures this
819         // point if it successfully builds without being destroyed first)
820         ons_ControlPoint_Icon_Spawn(self, toucher);
821
822         self.ons_toucher = toucher;
823
824         onslaught_updatelinks();
825 }
826
827 void ons_ControlPoint_Think()
828 {SELFPARAM();
829         self.nextthink = time + ONS_CP_THINKRATE;
830         CSQCMODEL_AUTOUPDATE(self);
831 }
832
833 void ons_ControlPoint_Reset(entity this)
834 {
835         if(this.goalentity)
836                 remove(this.goalentity);
837
838         this.goalentity = world;
839         this.team = 0;
840         this.colormap = 1024;
841         this.iscaptured = false;
842         this.islinked = false;
843         this.isshielded = true;
844         this.think = ons_ControlPoint_Think;
845         this.ons_toucher = world;
846         this.nextthink = time + ONS_CP_THINKRATE;
847         setmodel_fixsize(this, MDL_ONS_CP_PAD1);
848
849         WaypointSprite_UpdateMaxHealth(this.sprite, 0);
850         WaypointSprite_UpdateRule(this.sprite,this.team,SPRITERULE_TEAMPLAY);
851
852         onslaught_updatelinks();
853
854         activator = this;
855         SUB_UseTargets(); // to reset the structures, playerspawns etc.
856
857         CSQCMODEL_AUTOUPDATE(this);
858 }
859
860 void ons_DelayedControlPoint_Setup()
861 {SELFPARAM();
862         onslaught_updatelinks();
863
864         // captureshield setup
865         ons_CaptureShield_Spawn(self, false);
866
867         CSQCMODEL_AUTOINIT(self);
868 }
869
870 void ons_ControlPoint_Setup(entity cp)
871 {SELFPARAM();
872         // declarations
873         setself(cp); // for later usage with droptofloor()
874
875         // main setup
876         cp.ons_worldcpnext = ons_worldcplist; // link control point into ons_worldcplist
877         ons_worldcplist = cp;
878
879         cp.netname = "Control point";
880         cp.team = 0;
881         cp.solid = SOLID_BBOX;
882         cp.movetype = MOVETYPE_NONE;
883         cp.touch = ons_ControlPoint_Touch;
884         cp.think = ons_ControlPoint_Think;
885         cp.nextthink = time + ONS_CP_THINKRATE;
886         cp.reset = ons_ControlPoint_Reset;
887         cp.colormap = 1024;
888         cp.iscaptured = false;
889         cp.islinked = false;
890         cp.isshielded = true;
891
892         if(cp.message == "") { cp.message = "a"; }
893
894         // appearence
895         setmodel_fixsize(cp, MDL_ONS_CP_PAD1);
896
897         // control point placement
898         if((cp.spawnflags & 1) || cp.noalign) // don't drop to floor, just stay at fixed location
899         {
900                 cp.noalign = true;
901                 cp.movetype = MOVETYPE_NONE;
902         }
903         else // drop to floor, automatically find a platform and set that as spawn origin
904         {
905                 setorigin(cp, cp.origin + '0 0 20');
906                 cp.noalign = false;
907                 setself(cp);
908                 droptofloor();
909                 cp.movetype = MOVETYPE_TOSS;
910         }
911
912         // waypointsprites
913         WaypointSprite_SpawnFixed(WP_Null, self.origin + CPGEN_WAYPOINT_OFFSET, self, sprite, RADARICON_NONE);
914         WaypointSprite_UpdateRule(self.sprite, self.team, SPRITERULE_TEAMPLAY);
915
916         InitializeEntity(cp, ons_DelayedControlPoint_Setup, INITPRIO_SETLOCATION);
917 }
918
919
920 // =========================
921 // Main Generator Functions
922 // =========================
923
924 entity ons_Generator_Waypoint(entity e)
925 {
926         if (e.isshielded)
927                 return WP_OnsGenShielded;
928         return WP_OnsGen;
929 }
930
931 void ons_Generator_UpdateSprite(entity e)
932 {
933         entity s1 = ons_Generator_Waypoint(e);
934         WaypointSprite_UpdateSprites(e.sprite, s1, s1, s1);
935
936         if(e.lastteam != e.team + 2 || e.lastshielded != e.isshielded)
937         {
938                 e.lastteam = e.team + 2;
939                 e.lastshielded = e.isshielded;
940                 if(e.lastshielded)
941                 {
942                         if(e.team)
943                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, 0.5 * colormapPaletteColor(e.team - 1, false));
944                         else
945                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, '0.5 0.5 0.5');
946                 }
947                 else
948                 {
949                         if(e.team)
950                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, colormapPaletteColor(e.team - 1, false));
951                         else
952                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, '0.75 0.75 0.75');
953                 }
954                 WaypointSprite_Ping(e.sprite);
955         }
956 }
957
958 void ons_GeneratorDamage(entity inflictor, entity attacker, float damage, int deathtype, vector hitloc, vector force)
959 {SELFPARAM();
960         if(damage <= 0) { return; }
961         if(warmup_stage || gameover) { return; }
962         if(!round_handler_IsRoundStarted()) { return; }
963
964         if (attacker != self)
965         {
966                 if (self.isshielded)
967                 {
968                         // this is protected by a shield, so ignore the damage
969                         if (time > self.pain_finished)
970                                 if (IS_PLAYER(attacker))
971                                 {
972                                         play2(attacker, SND(ONS_DAMAGEBLOCKEDBYSHIELD));
973                                         attacker.typehitsound += 1;
974                                         self.pain_finished = time + 1;
975                                 }
976                         return;
977                 }
978                 if (time > self.pain_finished)
979                 {
980                         self.pain_finished = time + 10;
981                         FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it) && SAME_TEAM(it, self), LAMBDA(Send_Notification(NOTIF_ONE, it, MSG_CENTER, CENTER_GENERATOR_UNDERATTACK)));
982                         play2team(self.team, SND(ONS_GENERATOR_UNDERATTACK));
983                 }
984         }
985         self.health = self.health - damage;
986         WaypointSprite_UpdateHealth(self.sprite, self.health);
987         // choose an animation frame based on health
988         self.frame = 10 * bound(0, (1 - self.health / self.max_health), 1);
989         // see if the generator is still functional, or dying
990         if (self.health > 0)
991         {
992                 self.lasthealth = self.health;
993         }
994         else
995         {
996                 if (attacker == self)
997                         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_NUM_4(self.team, INFO_ONSLAUGHT_GENDESTROYED_OVERTIME_));
998                 else
999                 {
1000                         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_NUM_4(self.team, INFO_ONSLAUGHT_GENDESTROYED_));
1001                         PlayerScore_Add(attacker, SP_SCORE, 100);
1002                 }
1003                 self.iscaptured = false;
1004                 self.islinked = false;
1005                 self.isshielded = false;
1006                 self.takedamage = DAMAGE_NO; // can't be hurt anymore
1007                 self.event_damage = func_null; // won't do anything if hurt
1008                 self.count = 0; // reset counter
1009                 self.think = func_null;
1010                 self.nextthink = 0;
1011                 //self.think(); // do the first explosion now
1012
1013                 WaypointSprite_UpdateMaxHealth(self.sprite, 0);
1014                 WaypointSprite_Ping(self.sprite);
1015                 //WaypointSprite_Kill(self.sprite); // can't do this yet, code too poor
1016
1017                 onslaught_updatelinks();
1018         }
1019
1020         // Throw some flaming gibs on damage, more damage = more chance for gib
1021         if(random() < damage/220)
1022         {
1023                 sound(self, CH_TRIGGER, SND_ROCKET_IMPACT, VOL_BASE, ATTEN_NORM);
1024         }
1025         else
1026         {
1027                 // particles on every hit
1028                 Send_Effect(EFFECT_SPARKS, hitloc, force * -1, 1);
1029
1030                 //sound on every hit
1031                 if (random() < 0.5)
1032                         sound(self, CH_TRIGGER, SND_ONS_HIT1, VOL_BASE, ATTEN_NORM);
1033                 else
1034                         sound(self, CH_TRIGGER, SND_ONS_HIT2, VOL_BASE, ATTEN_NORM);
1035         }
1036
1037         self.SendFlags |= GSF_STATUS;
1038 }
1039
1040 void ons_GeneratorThink()
1041 {SELFPARAM();
1042         self.nextthink = time + GEN_THINKRATE;
1043         if (!gameover)
1044         {
1045                 if(!self.isshielded && self.wait < time)
1046                 {
1047                         self.wait = time + 5;
1048                         FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it), LAMBDA(
1049                                 if(SAME_TEAM(it, self))
1050                                 {
1051                                         Send_Notification(NOTIF_ONE, it, MSG_CENTER, CENTER_ONS_NOTSHIELDED_TEAM);
1052                                         soundto(MSG_ONE, it, CHAN_AUTO, SND(KH_ALARM), VOL_BASE, ATTEN_NONE);    // FIXME: unique sound?
1053                                 }
1054                                 else
1055                                         Send_Notification(NOTIF_ONE, it, MSG_CENTER, APP_TEAM_NUM_4(self.team, CENTER_ONS_NOTSHIELDED_));
1056                         ));
1057                 }
1058         }
1059 }
1060
1061 void ons_GeneratorReset(entity this)
1062 {
1063         this.team = this.team_saved;
1064         this.lasthealth = this.max_health = this.health = autocvar_g_onslaught_gen_health;
1065         this.takedamage = DAMAGE_AIM;
1066         this.bot_attack = true;
1067         this.iscaptured = true;
1068         this.islinked = true;
1069         this.isshielded = true;
1070         this.event_damage = ons_GeneratorDamage;
1071         this.think = ons_GeneratorThink;
1072         this.nextthink = time + GEN_THINKRATE;
1073
1074         Net_LinkEntity(this, false, 0, generator_send);
1075
1076         this.SendFlags = GSF_SETUP; // just incase
1077         this.SendFlags |= GSF_STATUS;
1078
1079         WaypointSprite_UpdateMaxHealth(this.sprite, this.max_health);
1080         WaypointSprite_UpdateHealth(this.sprite, this.health);
1081         WaypointSprite_UpdateRule(this.sprite,this.team,SPRITERULE_TEAMPLAY);
1082
1083         onslaught_updatelinks();
1084 }
1085
1086 void ons_DelayedGeneratorSetup()
1087 {SELFPARAM();
1088         // bot waypoints
1089         waypoint_spawnforitem_force(self, self.origin);
1090         self.nearestwaypointtimeout = 0; // activate waypointing again
1091         self.bot_basewaypoint = self.nearestwaypoint;
1092
1093         // captureshield setup
1094         ons_CaptureShield_Spawn(self, true);
1095
1096         onslaught_updatelinks();
1097
1098         Net_LinkEntity(self, false, 0, generator_send);
1099 }
1100
1101
1102 void onslaught_generator_touch()
1103 {SELFPARAM();
1104         if ( IS_PLAYER(other) )
1105         if ( SAME_TEAM(self,other) )
1106         if ( self.iscaptured )
1107         {
1108                 Send_Notification(NOTIF_ONE, other, MSG_CENTER, CENTER_ONS_TELEPORT);
1109         }
1110 }
1111
1112 void ons_GeneratorSetup(entity gen) // called when spawning a generator entity on the map as a spawnfunc
1113 {SELFPARAM();
1114         // declarations
1115         int teamnumber = gen.team;
1116         setself(gen); // for later usage with droptofloor()
1117
1118         // main setup
1119         gen.ons_worldgeneratornext = ons_worldgeneratorlist; // link generator into ons_worldgeneratorlist
1120         ons_worldgeneratorlist = gen;
1121
1122         gen.netname = sprintf("%s generator", Team_ColoredFullName(teamnumber));
1123         gen.classname = "onslaught_generator";
1124         gen.solid = SOLID_BBOX;
1125         gen.team_saved = teamnumber;
1126         gen.movetype = MOVETYPE_NONE;
1127         gen.lasthealth = gen.max_health = gen.health = autocvar_g_onslaught_gen_health;
1128         gen.takedamage = DAMAGE_AIM;
1129         gen.bot_attack = true;
1130         gen.event_damage = ons_GeneratorDamage;
1131         gen.reset = ons_GeneratorReset;
1132         gen.think = ons_GeneratorThink;
1133         gen.nextthink = time + GEN_THINKRATE;
1134         gen.iscaptured = true;
1135         gen.islinked = true;
1136         gen.isshielded = true;
1137         gen.touch = onslaught_generator_touch;
1138
1139         // appearence
1140         // model handled by CSQC
1141         setsize(gen, GENERATOR_MIN, GENERATOR_MAX);
1142         setorigin(gen, (gen.origin + CPGEN_SPAWN_OFFSET));
1143         gen.colormap = 1024 + (teamnumber - 1) * 17;
1144
1145         // generator placement
1146         setself(gen);
1147         droptofloor();
1148
1149         // waypointsprites
1150         WaypointSprite_SpawnFixed(WP_Null, self.origin + CPGEN_WAYPOINT_OFFSET, self, sprite, RADARICON_NONE);
1151         WaypointSprite_UpdateRule(self.sprite, self.team, SPRITERULE_TEAMPLAY);
1152         WaypointSprite_UpdateMaxHealth(self.sprite, self.max_health);
1153         WaypointSprite_UpdateHealth(self.sprite, self.health);
1154
1155         InitializeEntity(gen, ons_DelayedGeneratorSetup, INITPRIO_SETLOCATION);
1156 }
1157
1158
1159 // ===============
1160 //  Round Handler
1161 // ===============
1162
1163 int total_generators;
1164 void Onslaught_count_generators()
1165 {
1166         entity e;
1167         total_generators = redowned = blueowned = yellowowned = pinkowned = 0;
1168         for(e = ons_worldgeneratorlist; e; e = e.ons_worldgeneratornext)
1169         {
1170                 ++total_generators;
1171                 redowned += (e.team == NUM_TEAM_1 && e.health > 0);
1172                 blueowned += (e.team == NUM_TEAM_2 && e.health > 0);
1173                 yellowowned += (e.team == NUM_TEAM_3 && e.health > 0);
1174                 pinkowned += (e.team == NUM_TEAM_4 && e.health > 0);
1175         }
1176 }
1177
1178 int Onslaught_GetWinnerTeam()
1179 {
1180         int winner_team = 0;
1181         if(redowned > 0)
1182                 winner_team = NUM_TEAM_1;
1183         if(blueowned > 0)
1184         {
1185                 if(winner_team) return 0;
1186                 winner_team = NUM_TEAM_2;
1187         }
1188         if(yellowowned > 0)
1189         {
1190                 if(winner_team) return 0;
1191                 winner_team = NUM_TEAM_3;
1192         }
1193         if(pinkowned > 0)
1194         {
1195                 if(winner_team) return 0;
1196                 winner_team = NUM_TEAM_4;
1197         }
1198         if(winner_team)
1199                 return winner_team;
1200         return -1; // no generators left?
1201 }
1202
1203 void nades_Clear(entity e);
1204
1205 #define ONS_OWNED_GENERATORS() ((redowned > 0) + (blueowned > 0) + (yellowowned > 0) + (pinkowned > 0))
1206 #define ONS_OWNED_GENERATORS_OK() (ONS_OWNED_GENERATORS() > 1)
1207 bool Onslaught_CheckWinner()
1208 {
1209         if ((autocvar_timelimit && time > game_starttime + autocvar_timelimit * 60) || (round_handler_GetEndTime() > 0 && round_handler_GetEndTime() - time <= 0))
1210         {
1211                 ons_stalemate = true;
1212
1213                 if (!wpforenemy_announced)
1214                 {
1215                         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_CONTROLPOINT);
1216                         sound(world, CH_INFO, SND_ONS_GENERATOR_DECAY, VOL_BASE, ATTEN_NONE);
1217
1218                         wpforenemy_announced = true;
1219                 }
1220
1221                 entity tmp_entity; // temporary entity
1222                 float d;
1223                 for(tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext) if(time >= tmp_entity.ons_overtime_damagedelay)
1224                 {
1225                         // tmp_entity.max_health / 300 gives 5 minutes of overtime.
1226                         // control points reduce the overtime duration.
1227                         d = 1;
1228                         entity e;
1229                         for(e = ons_worldcplist; e; e = e.ons_worldcpnext)
1230                         {
1231                                 if(DIFF_TEAM(e, tmp_entity))
1232                                 if(e.islinked)
1233                                         d = d + 1;
1234                         }
1235
1236                         if(autocvar_g_campaign && autocvar__campaign_testrun)
1237                                 d = d * tmp_entity.max_health;
1238                         else
1239                                 d = d * tmp_entity.max_health / max(30, 60 * autocvar_timelimit_suddendeath);
1240
1241                         Damage(tmp_entity, tmp_entity, tmp_entity, d, DEATH_HURTTRIGGER.m_id, tmp_entity.origin, '0 0 0');
1242
1243                         tmp_entity.sprite.SendFlags |= 16;
1244
1245                         tmp_entity.ons_overtime_damagedelay = time + 1;
1246                 }
1247         }
1248         else { wpforenemy_announced = false; ons_stalemate = false; }
1249
1250         Onslaught_count_generators();
1251
1252         if(ONS_OWNED_GENERATORS_OK())
1253                 return 0;
1254
1255         int winner_team = Onslaught_GetWinnerTeam();
1256
1257         if(winner_team > 0)
1258         {
1259                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, APP_TEAM_NUM_4(winner_team, CENTER_ROUND_TEAM_WIN_));
1260                 Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_NUM_4(winner_team, INFO_ROUND_TEAM_WIN_));
1261                 TeamScore_AddToTeam(winner_team, ST_ONS_CAPS, +1);
1262         }
1263         else if(winner_team == -1)
1264         {
1265                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_ROUND_TIED);
1266                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_ROUND_TIED);
1267         }
1268
1269         ons_stalemate = false;
1270
1271         play2all(SND(CTF_CAPTURE(winner_team)));
1272
1273         round_handler_Init(7, autocvar_g_onslaught_warmup, autocvar_g_onslaught_round_timelimit);
1274
1275         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
1276                 it.ons_roundlost = true;
1277                 it.player_blocked = true;
1278
1279                 nades_Clear(it);
1280         ));
1281
1282         return 1;
1283 }
1284
1285 bool Onslaught_CheckPlayers()
1286 {
1287         return 1;
1288 }
1289
1290 void Onslaught_RoundStart()
1291 {
1292         entity tmp_entity;
1293         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(it.player_blocked = false));
1294
1295         for(tmp_entity = ons_worldcplist; tmp_entity; tmp_entity = tmp_entity.ons_worldcpnext)
1296                 tmp_entity.sprite.SendFlags |= 16;
1297
1298         for(tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext)
1299                 tmp_entity.sprite.SendFlags |= 16;
1300 }
1301
1302
1303 // ================
1304 // Bot player logic
1305 // ================
1306
1307 // NOTE: LEGACY CODE, needs to be re-written!
1308
1309 void havocbot_goalrating_ons_offenseitems(float ratingscale, vector org, float sradius)
1310 {SELFPARAM();
1311         entity head;
1312         float t, c;
1313         bool needarmor = false, needweapons = false;
1314
1315         // Needs armor/health?
1316         if(self.health<100)
1317                 needarmor = true;
1318
1319         // Needs weapons?
1320         c = 0;
1321         FOREACH(Weapons, it != WEP_Null, LAMBDA(
1322                 if(self.weapons & (it.m_wepset))
1323                 if(++c >= 4)
1324                         break;
1325         ));
1326
1327         if(c<4)
1328                 needweapons = true;
1329
1330         if(!needweapons && !needarmor)
1331                 return;
1332
1333         LOG_DEBUG(strcat(self.netname, " needs weapons ", ftos(needweapons) , "\n"));
1334         LOG_DEBUG(strcat(self.netname, " needs armor ", ftos(needarmor) , "\n"));
1335
1336         // See what is around
1337         head = findchainfloat(bot_pickup, true);
1338         while (head)
1339         {
1340                 // gather health and armor only
1341                 if (head.solid)
1342                 if ( ((head.health || head.armorvalue) && needarmor) || (head.weapons && needweapons ) )
1343                 if (vlen(head.origin - org) < sradius)
1344                 {
1345                         t = head.bot_pickupevalfunc(self, head);
1346                         if (t > 0)
1347                                 navigation_routerating(head, t * ratingscale, 500);
1348                 }
1349                 head = head.chain;
1350         }
1351 }
1352
1353 void havocbot_role_ons_setrole(entity bot, int role)
1354 {
1355         LOG_DEBUG(strcat(bot.netname," switched to "));
1356         switch(role)
1357         {
1358                 case HAVOCBOT_ONS_ROLE_DEFENSE:
1359                         LOG_DEBUG("defense");
1360                         bot.havocbot_role = havocbot_role_ons_defense;
1361                         bot.havocbot_role_flags = HAVOCBOT_ONS_ROLE_DEFENSE;
1362                         bot.havocbot_role_timeout = 0;
1363                         break;
1364                 case HAVOCBOT_ONS_ROLE_ASSISTANT:
1365                         LOG_DEBUG("assistant");
1366                         bot.havocbot_role = havocbot_role_ons_assistant;
1367                         bot.havocbot_role_flags = HAVOCBOT_ONS_ROLE_ASSISTANT;
1368                         bot.havocbot_role_timeout = 0;
1369                         break;
1370                 case HAVOCBOT_ONS_ROLE_OFFENSE:
1371                         LOG_DEBUG("offense");
1372                         bot.havocbot_role = havocbot_role_ons_offense;
1373                         bot.havocbot_role_flags = HAVOCBOT_ONS_ROLE_OFFENSE;
1374                         bot.havocbot_role_timeout = 0;
1375                         break;
1376         }
1377         LOG_DEBUG("\n");
1378 }
1379
1380 void havocbot_goalrating_ons_controlpoints_attack(float ratingscale)
1381 {SELFPARAM();
1382         entity cp, cp1, cp2, best, wp;
1383         float radius, bestvalue;
1384         int c;
1385         bool found;
1386
1387         // Filter control points
1388         for(cp2 = ons_worldcplist; cp2; cp2 = cp2.ons_worldcpnext)
1389         {
1390                 cp2.wpcost = c = 0;
1391                 cp2.wpconsidered = false;
1392
1393                 if(cp2.isshielded)
1394                         continue;
1395
1396                 // Ignore owned controlpoints
1397                 if(!(cp2.isgenneighbor[self.team] || cp2.iscpneighbor[self.team]))
1398                         continue;
1399
1400                 // Count team mates interested in this control point
1401                 // (easier and cleaner than keeping counters per cp and teams)
1402                 FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
1403                         if(SAME_TEAM(it, self))
1404                         if(it.havocbot_role_flags & HAVOCBOT_ONS_ROLE_OFFENSE)
1405                         if(it.havocbot_ons_target == cp2)
1406                                 ++c;
1407                 ));
1408
1409                 // NOTE: probably decrease the cost of attackable control points
1410                 cp2.wpcost = c;
1411                 cp2.wpconsidered = true;
1412         }
1413
1414         // We'll consider only the best case
1415         bestvalue = 99999999999;
1416         cp = world;
1417         for(cp1 = ons_worldcplist; cp1; cp1 = cp1.ons_worldcpnext)
1418         {
1419                 if (!cp1.wpconsidered)
1420                         continue;
1421
1422                 if(cp1.wpcost<bestvalue)
1423                 {
1424                         bestvalue = cp1.wpcost;
1425                         cp = cp1;
1426                         self.havocbot_ons_target = cp1;
1427                 }
1428         }
1429
1430         if (!cp)
1431                 return;
1432
1433         LOG_DEBUG(strcat(self.netname, " chose cp ranked ", ftos(bestvalue), "\n"));
1434
1435         if(cp.goalentity)
1436         {
1437                 // Should be attacked
1438                 // Rate waypoints near it
1439                 found = false;
1440                 best = world;
1441                 bestvalue = 99999999999;
1442                 for(radius=0; radius<1000 && !found; radius+=500)
1443                 {
1444                         for(wp=findradius(cp.origin,radius); wp; wp=wp.chain)
1445                         {
1446                                 if(!(wp.wpflags & WAYPOINTFLAG_GENERATED))
1447                                 if(wp.classname=="waypoint")
1448                                 if(checkpvs(wp.origin,cp))
1449                                 {
1450                                         found = true;
1451                                         if(wp.cnt<bestvalue)
1452                                         {
1453                                                 best = wp;
1454                                                 bestvalue = wp.cnt;
1455                                         }
1456                                 }
1457                         }
1458                 }
1459
1460                 if(best)
1461                 {
1462                         navigation_routerating(best, ratingscale, 10000);
1463                         best.cnt += 1;
1464
1465                         self.havocbot_attack_time = 0;
1466                         if(checkpvs(self.view_ofs,cp))
1467                         if(checkpvs(self.view_ofs,best))
1468                                 self.havocbot_attack_time = time + 2;
1469                 }
1470                 else
1471                 {
1472                         navigation_routerating(cp, ratingscale, 10000);
1473                 }
1474                 LOG_DEBUG(strcat(self.netname, " found an attackable controlpoint at ", vtos(cp.origin) ,"\n"));
1475         }
1476         else
1477         {
1478                 // Should be touched
1479                 LOG_DEBUG(strcat(self.netname, " found a touchable controlpoint at ", vtos(cp.origin) ,"\n"));
1480                 found = false;
1481
1482                 // Look for auto generated waypoint
1483                 if (!bot_waypoints_for_items)
1484                 for (wp = findradius(cp.origin,100); wp; wp = wp.chain)
1485                 {
1486                         if(wp.classname=="waypoint")
1487                         {
1488                                 navigation_routerating(wp, ratingscale, 10000);
1489                                 found = true;
1490                         }
1491                 }
1492
1493                 // Nothing found, rate the controlpoint itself
1494                 if (!found)
1495                         navigation_routerating(cp, ratingscale, 10000);
1496         }
1497 }
1498
1499 bool havocbot_goalrating_ons_generator_attack(float ratingscale)
1500 {SELFPARAM();
1501         entity g, wp, bestwp;
1502         bool found;
1503         int best;
1504
1505         for(g = ons_worldgeneratorlist; g; g = g.ons_worldgeneratornext)
1506         {
1507                 if(SAME_TEAM(g, self) || g.isshielded)
1508                         continue;
1509
1510                 // Should be attacked
1511                 // Rate waypoints near it
1512                 found = false;
1513                 bestwp = world;
1514                 best = 99999999999;
1515
1516                 for(wp=findradius(g.origin,400); wp; wp=wp.chain)
1517                 {
1518                         if(wp.classname=="waypoint")
1519                         if(checkpvs(wp.origin,g))
1520                         {
1521                                 found = true;
1522                                 if(wp.cnt<best)
1523                                 {
1524                                         bestwp = wp;
1525                                         best = wp.cnt;
1526                                 }
1527                         }
1528                 }
1529
1530                 if(bestwp)
1531                 {
1532                         LOG_DEBUG("waypoints found around generator\n");
1533                         navigation_routerating(bestwp, ratingscale, 10000);
1534                         bestwp.cnt += 1;
1535
1536                         self.havocbot_attack_time = 0;
1537                         if(checkpvs(self.view_ofs,g))
1538                         if(checkpvs(self.view_ofs,bestwp))
1539                                 self.havocbot_attack_time = time + 5;
1540
1541                         return true;
1542                 }
1543                 else
1544                 {
1545                         LOG_DEBUG("generator found without waypoints around\n");
1546                         // if there aren't waypoints near the generator go straight to it
1547                         navigation_routerating(g, ratingscale, 10000);
1548                         self.havocbot_attack_time = 0;
1549                         return true;
1550                 }
1551         }
1552         return false;
1553 }
1554
1555 void havocbot_role_ons_offense()
1556 {SELFPARAM();
1557         if(IS_DEAD(self))
1558         {
1559                 self.havocbot_attack_time = 0;
1560                 havocbot_ons_reset_role(self);
1561                 return;
1562         }
1563
1564         // Set the role timeout if necessary
1565         if (!self.havocbot_role_timeout)
1566                 self.havocbot_role_timeout = time + 120;
1567
1568         if (time > self.havocbot_role_timeout)
1569         {
1570                 havocbot_ons_reset_role(self);
1571                 return;
1572         }
1573
1574         if(self.havocbot_attack_time>time)
1575                 return;
1576
1577         if (self.bot_strategytime < time)
1578         {
1579                 navigation_goalrating_start();
1580                 havocbot_goalrating_enemyplayers(20000, self.origin, 650);
1581                 if(!havocbot_goalrating_ons_generator_attack(20000))
1582                         havocbot_goalrating_ons_controlpoints_attack(20000);
1583                 havocbot_goalrating_ons_offenseitems(10000, self.origin, 10000);
1584                 navigation_goalrating_end();
1585
1586                 self.bot_strategytime = time + autocvar_bot_ai_strategyinterval;
1587         }
1588 }
1589
1590 void havocbot_role_ons_assistant()
1591 {SELFPARAM();
1592         havocbot_ons_reset_role(self);
1593 }
1594
1595 void havocbot_role_ons_defense()
1596 {SELFPARAM();
1597         havocbot_ons_reset_role(self);
1598 }
1599
1600 void havocbot_ons_reset_role(entity bot)
1601 {SELFPARAM();
1602         if(IS_DEAD(self))
1603                 return;
1604
1605         bot.havocbot_ons_target = world;
1606
1607         // TODO: Defend control points or generator if necessary
1608
1609         havocbot_role_ons_setrole(bot, HAVOCBOT_ONS_ROLE_OFFENSE);
1610 }
1611
1612
1613 /*
1614  * Find control point or generator owned by the same team self which is nearest to pos
1615  * if max_dist is positive, only control points within this range will be considered
1616  */
1617 entity ons_Nearest_ControlPoint(vector pos, float max_dist)
1618 {SELFPARAM();
1619         entity tmp_entity, closest_target = world;
1620         tmp_entity = findchain(classname, "onslaught_controlpoint");
1621         while(tmp_entity)
1622         {
1623                 if(SAME_TEAM(tmp_entity, self))
1624                 if(tmp_entity.iscaptured)
1625                 if(max_dist <= 0 || vlen(tmp_entity.origin - pos) <= max_dist)
1626                 if(vlen(tmp_entity.origin - pos) <= vlen(closest_target.origin - pos) || closest_target == world)
1627                         closest_target = tmp_entity;
1628                 tmp_entity = tmp_entity.chain;
1629         }
1630         tmp_entity = findchain(classname, "onslaught_generator");
1631         while(tmp_entity)
1632         {
1633                 if(SAME_TEAM(tmp_entity, self))
1634                 if(max_dist <= 0 || vlen(tmp_entity.origin - pos) < max_dist)
1635                 if(vlen(tmp_entity.origin - pos) <= vlen(closest_target.origin - pos) || closest_target == world)
1636                         closest_target = tmp_entity;
1637                 tmp_entity = tmp_entity.chain;
1638         }
1639
1640         return closest_target;
1641 }
1642
1643 /*
1644  * Find control point or generator owned by the same team self which is nearest to pos
1645  * if max_dist is positive, only control points within this range will be considered
1646  * This function only check distances on the XY plane, disregarding Z
1647  */
1648 entity ons_Nearest_ControlPoint_2D(vector pos, float max_dist)
1649 {SELFPARAM();
1650         entity tmp_entity, closest_target = world;
1651         vector delta;
1652         float smallest_distance = 0, distance;
1653
1654         tmp_entity = findchain(classname, "onslaught_controlpoint");
1655         while(tmp_entity)
1656         {
1657                 delta = tmp_entity.origin - pos;
1658                 delta_z = 0;
1659                 distance = vlen(delta);
1660
1661                 if(SAME_TEAM(tmp_entity, self))
1662                 if(tmp_entity.iscaptured)
1663                 if(max_dist <= 0 || distance <= max_dist)
1664                 if(closest_target == world || distance <= smallest_distance )
1665                 {
1666                         closest_target = tmp_entity;
1667                         smallest_distance = distance;
1668                 }
1669
1670                 tmp_entity = tmp_entity.chain;
1671         }
1672         tmp_entity = findchain(classname, "onslaught_generator");
1673         while(tmp_entity)
1674         {
1675                 delta = tmp_entity.origin - pos;
1676                 delta_z = 0;
1677                 distance = vlen(delta);
1678
1679                 if(SAME_TEAM(tmp_entity, self))
1680                 if(max_dist <= 0 || distance <= max_dist)
1681                 if(closest_target == world || distance <= smallest_distance )
1682                 {
1683                         closest_target = tmp_entity;
1684                         smallest_distance = distance;
1685                 }
1686
1687                 tmp_entity = tmp_entity.chain;
1688         }
1689
1690         return closest_target;
1691 }
1692 /**
1693  * find the number of control points and generators in the same team as self
1694  */
1695 int ons_Count_SelfControlPoints()
1696 {SELFPARAM();
1697         entity tmp_entity;
1698         tmp_entity = findchain(classname, "onslaught_controlpoint");
1699         int n = 0;
1700         while(tmp_entity)
1701         {
1702                 if(SAME_TEAM(tmp_entity, self))
1703                 if(tmp_entity.iscaptured)
1704                         n++;
1705                 tmp_entity = tmp_entity.chain;
1706         }
1707         tmp_entity = findchain(classname, "onslaught_generator");
1708         while(tmp_entity)
1709         {
1710                 if(SAME_TEAM(tmp_entity, self))
1711                         n++;
1712                 tmp_entity = tmp_entity.chain;
1713         }
1714         return n;
1715 }
1716
1717 /**
1718  * Teleport player to a random position near tele_target
1719  * if tele_effects is true, teleport sound+particles are created
1720  * return false on failure
1721  */
1722 bool ons_Teleport(entity player, entity tele_target, float range, bool tele_effects)
1723 {
1724         if ( !tele_target )
1725                 return false;
1726
1727         int i;
1728         vector loc;
1729         float theta;
1730         // narrow the range for each iteration to increase chances that a spawnpoint
1731         // can be found even if there's little room around the control point
1732         float iteration_scale = 1;
1733         for(i = 0; i < 16; ++i)
1734         {
1735                 iteration_scale -= i / 16;
1736                 theta = random() * 2 * M_PI;
1737                 loc_y = sin(theta);
1738                 loc_x = cos(theta);
1739                 loc_z = 0;
1740                 loc *= random() * range * iteration_scale;
1741
1742                 loc += tele_target.origin + '0 0 128' * iteration_scale;
1743
1744                 tracebox(loc, STAT(PL_MIN, NULL), STAT(PL_MAX, NULL), loc, MOVE_NORMAL, player);
1745                 if(trace_fraction == 1.0 && !trace_startsolid)
1746                 {
1747                         traceline(tele_target.origin, loc, MOVE_NOMONSTERS, tele_target); // double check to make sure we're not spawning outside the world
1748                         if(trace_fraction == 1.0 && !trace_startsolid)
1749                         {
1750                                 if ( tele_effects )
1751                                 {
1752                                         Send_Effect(EFFECT_TELEPORT, player.origin, '0 0 0', 1);
1753                                         sound (player, CH_TRIGGER, SND_TELEPORT, VOL_BASE, ATTEN_NORM);
1754                                 }
1755                                 setorigin(player, loc);
1756                                 player.angles = '0 1 0' * ( theta * RAD2DEG + 180 );
1757                                 makevectors(player.angles);
1758                                 player.fixangle = true;
1759                                 player.teleport_antispam = time + autocvar_g_onslaught_teleport_wait;
1760
1761                                 if ( tele_effects )
1762                                         Send_Effect(EFFECT_TELEPORT, player.origin + v_forward * 32, '0 0 0', 1);
1763                                 return true;
1764                         }
1765                 }
1766         }
1767
1768         return false;
1769 }
1770
1771 // ==============
1772 // Hook Functions
1773 // ==============
1774
1775 MUTATOR_HOOKFUNCTION(ons, reset_map_global)
1776 {SELFPARAM();
1777         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
1778                 it.ons_roundlost = false;
1779                 it.ons_deathloc = '0 0 0';
1780                 WITH(entity, self, it, PutClientInServer());
1781         ));
1782         return false;
1783 }
1784
1785 MUTATOR_HOOKFUNCTION(ons, ClientDisconnect)
1786 {SELFPARAM();
1787         self.ons_deathloc = '0 0 0';
1788         return false;
1789 }
1790
1791 MUTATOR_HOOKFUNCTION(ons, MakePlayerObserver)
1792 {SELFPARAM();
1793         self.ons_deathloc = '0 0 0';
1794         return false;
1795 }
1796
1797 MUTATOR_HOOKFUNCTION(ons, PlayerSpawn)
1798 {SELFPARAM();
1799         if(!round_handler_IsRoundStarted())
1800         {
1801                 self.player_blocked = true;
1802                 return false;
1803         }
1804
1805         entity l;
1806         for(l = ons_worldgeneratorlist; l; l = l.ons_worldgeneratornext)
1807         {
1808                 l.sprite.SendFlags |= 16;
1809         }
1810         for(l = ons_worldcplist; l; l = l.ons_worldcpnext)
1811         {
1812                 l.sprite.SendFlags |= 16;
1813         }
1814
1815         if(ons_stalemate) { Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_OVERTIME_CONTROLPOINT); }
1816
1817         if ( autocvar_g_onslaught_spawn_choose )
1818         if ( self.ons_spawn_by )
1819         if ( ons_Teleport(self,self.ons_spawn_by,autocvar_g_onslaught_teleport_radius,false) )
1820         {
1821                 self.ons_spawn_by = world;
1822                 return false;
1823         }
1824
1825         if(autocvar_g_onslaught_spawn_at_controlpoints)
1826         if(random() <= autocvar_g_onslaught_spawn_at_controlpoints_chance)
1827         {
1828                 float random_target = autocvar_g_onslaught_spawn_at_controlpoints_random;
1829                 entity tmp_entity, closest_target = world;
1830                 vector spawn_loc = self.ons_deathloc;
1831
1832                 // new joining player or round reset, don't bother checking
1833                 if(spawn_loc == '0 0 0') { return false; }
1834
1835                 if(random_target) { RandomSelection_Init(); }
1836
1837                 for(tmp_entity = ons_worldcplist; tmp_entity; tmp_entity = tmp_entity.ons_worldcpnext)
1838                 {
1839                         if(SAME_TEAM(tmp_entity, self))
1840                         if(random_target)
1841                                 RandomSelection_Add(tmp_entity, 0, string_null, 1, 1);
1842                         else if(vlen(tmp_entity.origin - spawn_loc) <= vlen(closest_target.origin - spawn_loc) || closest_target == world)
1843                                 closest_target = tmp_entity;
1844                 }
1845
1846                 if(random_target) { closest_target = RandomSelection_chosen_ent; }
1847
1848                 if(closest_target)
1849                 {
1850                         float i;
1851                         vector loc;
1852                         float iteration_scale = 1;
1853                         for(i = 0; i < 10; ++i)
1854                         {
1855                                 iteration_scale -= i / 10;
1856                                 loc = closest_target.origin + '0 0 96' * iteration_scale;
1857                                 loc += ('0 1 0' * random()) * 128 * iteration_scale;
1858                                 tracebox(loc, STAT(PL_MIN, NULL), STAT(PL_MAX, NULL), loc, MOVE_NORMAL, self);
1859                                 if(trace_fraction == 1.0 && !trace_startsolid)
1860                                 {
1861                                         traceline(closest_target.origin, loc, MOVE_NOMONSTERS, closest_target); // double check to make sure we're not spawning outside the world
1862                                         if(trace_fraction == 1.0 && !trace_startsolid)
1863                                         {
1864                                                 setorigin(self, loc);
1865                                                 self.angles = normalize(loc - closest_target.origin) * RAD2DEG;
1866                                                 return false;
1867                                         }
1868                                 }
1869                         }
1870                 }
1871         }
1872
1873         if(autocvar_g_onslaught_spawn_at_generator)
1874         if(random() <= autocvar_g_onslaught_spawn_at_generator_chance)
1875         {
1876                 float random_target = autocvar_g_onslaught_spawn_at_generator_random;
1877                 entity tmp_entity, closest_target = world;
1878                 vector spawn_loc = self.ons_deathloc;
1879
1880                 // new joining player or round reset, don't bother checking
1881                 if(spawn_loc == '0 0 0') { return false; }
1882
1883                 if(random_target) { RandomSelection_Init(); }
1884
1885                 for(tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext)
1886                 {
1887                         if(random_target)
1888                                 RandomSelection_Add(tmp_entity, 0, string_null, 1, 1);
1889                         else
1890                         {
1891                                 if(SAME_TEAM(tmp_entity, self))
1892                                 if(vlen(tmp_entity.origin - spawn_loc) <= vlen(closest_target.origin - spawn_loc) || closest_target == world)
1893                                         closest_target = tmp_entity;
1894                         }
1895                 }
1896
1897                 if(random_target) { closest_target = RandomSelection_chosen_ent; }
1898
1899                 if(closest_target)
1900                 {
1901                         float i;
1902                         vector loc;
1903                         float iteration_scale = 1;
1904                         for(i = 0; i < 10; ++i)
1905                         {
1906                                 iteration_scale -= i / 10;
1907                                 loc = closest_target.origin + '0 0 128' * iteration_scale;
1908                                 loc += ('0 1 0' * random()) * 256 * iteration_scale;
1909                                 tracebox(loc, STAT(PL_MIN, NULL), STAT(PL_MAX, NULL), loc, MOVE_NORMAL, self);
1910                                 if(trace_fraction == 1.0 && !trace_startsolid)
1911                                 {
1912                                         traceline(closest_target.origin, loc, MOVE_NOMONSTERS, closest_target); // double check to make sure we're not spawning outside the world
1913                                         if(trace_fraction == 1.0 && !trace_startsolid)
1914                                         {
1915                                                 setorigin(self, loc);
1916                                                 self.angles = normalize(loc - closest_target.origin) * RAD2DEG;
1917                                                 return false;
1918                                         }
1919                                 }
1920                         }
1921                 }
1922         }
1923
1924         return false;
1925 }
1926
1927 MUTATOR_HOOKFUNCTION(ons, PlayerDies)
1928 {SELFPARAM();
1929         frag_target.ons_deathloc = frag_target.origin;
1930         entity l;
1931         for(l = ons_worldgeneratorlist; l; l = l.ons_worldgeneratornext)
1932         {
1933                 l.sprite.SendFlags |= 16;
1934         }
1935         for(l = ons_worldcplist; l; l = l.ons_worldcpnext)
1936         {
1937                 l.sprite.SendFlags |= 16;
1938         }
1939
1940         if ( autocvar_g_onslaught_spawn_choose )
1941         if ( ons_Count_SelfControlPoints() > 1 )
1942                 stuffcmd(self, "qc_cmd_cl hud clickradar\n");
1943
1944         return false;
1945 }
1946
1947 MUTATOR_HOOKFUNCTION(ons, MonsterMove)
1948 {SELFPARAM();
1949         entity e = find(world, targetname, self.target);
1950         if (e != world)
1951                 self.team = e.team;
1952
1953         return false;
1954 }
1955
1956 void ons_MonsterSpawn_Delayed()
1957 {SELFPARAM();
1958         entity e, own = self.owner;
1959
1960         if(!own) { remove(self); return; }
1961
1962         if(own.targetname)
1963         {
1964                 e = find(world, target, own.targetname);
1965                 if(e != world)
1966                 {
1967                         own.team = e.team;
1968
1969                         activator = e;
1970                         own.use();
1971                 }
1972         }
1973
1974         remove(self);
1975 }
1976
1977 MUTATOR_HOOKFUNCTION(ons, MonsterSpawn)
1978 {SELFPARAM();
1979         entity e = spawn();
1980         e.owner = self;
1981         InitializeEntity(e, ons_MonsterSpawn_Delayed, INITPRIO_FINDTARGET);
1982
1983         return false;
1984 }
1985
1986 void ons_TurretSpawn_Delayed()
1987 {SELFPARAM();
1988         entity e, own = self.owner;
1989
1990         if(!own) { remove(self); return; }
1991
1992         if(own.targetname)
1993         {
1994                 e = find(world, target, own.targetname);
1995                 if(e != world)
1996                 {
1997                         own.team = e.team;
1998                         own.active = ACTIVE_NOT;
1999
2000                         activator = e;
2001                         own.use();
2002                 }
2003         }
2004
2005         remove(self);
2006 }
2007
2008 MUTATOR_HOOKFUNCTION(ons, TurretSpawn)
2009 {SELFPARAM();
2010         entity e = spawn();
2011         e.owner = self;
2012         InitializeEntity(e, ons_TurretSpawn_Delayed, INITPRIO_FINDTARGET);
2013
2014         return false;
2015 }
2016
2017 MUTATOR_HOOKFUNCTION(ons, HavocBot_ChooseRole)
2018 {SELFPARAM();
2019         havocbot_ons_reset_role(self);
2020         return true;
2021 }
2022
2023 MUTATOR_HOOKFUNCTION(ons, GetTeamCount)
2024 {
2025         // onslaught is special
2026         for(entity tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext)
2027         {
2028                 switch(tmp_entity.team)
2029                 {
2030                         case NUM_TEAM_1: c1 = 0; break;
2031                         case NUM_TEAM_2: c2 = 0; break;
2032                         case NUM_TEAM_3: c3 = 0; break;
2033                         case NUM_TEAM_4: c4 = 0; break;
2034                 }
2035         }
2036
2037         return true;
2038 }
2039
2040 MUTATOR_HOOKFUNCTION(ons, SpectateCopy)
2041 {SELFPARAM();
2042         self.ons_roundlost = other.ons_roundlost; // make spectators see it too
2043         return false;
2044 }
2045
2046 MUTATOR_HOOKFUNCTION(ons, SV_ParseClientCommand)
2047 {SELFPARAM();
2048         if(MUTATOR_RETURNVALUE) // command was already handled?
2049                 return false;
2050
2051         if ( cmd_name == "ons_spawn" )
2052         {
2053                 vector pos = self.origin;
2054                 if(cmd_argc > 1)
2055                         pos_x = stof(argv(1));
2056                 if(cmd_argc > 2)
2057                         pos_y = stof(argv(2));
2058                 if(cmd_argc > 3)
2059                         pos_z = stof(argv(3));
2060
2061                 if ( IS_PLAYER(self) )
2062                 {
2063                         if ( !STAT(FROZEN, self) )
2064                         {
2065                                 entity source_point = ons_Nearest_ControlPoint(self.origin, autocvar_g_onslaught_teleport_radius);
2066
2067                                 if ( !source_point && self.health > 0 )
2068                                 {
2069                                         sprint(self, "\nYou need to be next to a control point\n");
2070                                         return 1;
2071                                 }
2072
2073
2074                                 entity closest_target = ons_Nearest_ControlPoint_2D(pos, autocvar_g_onslaught_click_radius);
2075
2076                                 if ( closest_target == world )
2077                                 {
2078                                         sprint(self, "\nNo control point found\n");
2079                                         return 1;
2080                                 }
2081
2082                                 if ( self.health <= 0 )
2083                                 {
2084                                         self.ons_spawn_by = closest_target;
2085                                         self.respawn_flags = self.respawn_flags | RESPAWN_FORCE;
2086                                 }
2087                                 else
2088                                 {
2089                                         if ( source_point == closest_target )
2090                                         {
2091                                                 sprint(self, "\nTeleporting to the same point\n");
2092                                                 return 1;
2093                                         }
2094
2095                                         if ( !ons_Teleport(self,closest_target,autocvar_g_onslaught_teleport_radius,true) )
2096                                                 sprint(self, "\nUnable to teleport there\n");
2097                                 }
2098
2099                                 return 1;
2100                         }
2101
2102                         sprint(self, "\nNo teleportation for you\n");
2103                 }
2104
2105                 return 1;
2106         }
2107         return 0;
2108 }
2109
2110 MUTATOR_HOOKFUNCTION(ons, PlayerUseKey)
2111 {SELFPARAM();
2112         if(MUTATOR_RETURNVALUE || gameover) { return false; }
2113
2114         if((time > self.teleport_antispam) && (!IS_DEAD(self)) && !self.vehicle)
2115         {
2116                 entity source_point = ons_Nearest_ControlPoint(self.origin, autocvar_g_onslaught_teleport_radius);
2117                 if ( source_point )
2118                 {
2119                         stuffcmd(self, "qc_cmd_cl hud clickradar\n");
2120                         return true;
2121                 }
2122         }
2123
2124         return false;
2125 }
2126
2127 MUTATOR_HOOKFUNCTION(ons, PlayHitsound)
2128 {
2129         return (frag_victim.classname == "onslaught_generator" && !frag_victim.isshielded)
2130                 || (frag_victim.classname == "onslaught_controlpoint_icon" && !frag_victim.owner.isshielded);
2131 }
2132
2133 MUTATOR_HOOKFUNCTION(ons, SendWaypoint)
2134 {
2135         if(wp_sendflags & 16)
2136         {
2137                 if(self.owner.classname == "onslaught_controlpoint")
2138                 {
2139                         entity wp_owner = self.owner;
2140                         entity e = WaypointSprite_getviewentity(wp_sendto);
2141                         if(SAME_TEAM(e, wp_owner) && wp_owner.goalentity.health >= wp_owner.goalentity.max_health) { wp_flag |= 2; }
2142                         if(!ons_ControlPoint_Attackable(wp_owner, e.team)) { wp_flag |= 2; }
2143                 }
2144                 if(self.owner.classname == "onslaught_generator")
2145                 {
2146                         entity wp_owner = self.owner;
2147                         if(wp_owner.isshielded && wp_owner.health >= wp_owner.max_health) { wp_flag |= 2; }
2148                         if(wp_owner.health <= 0) { wp_flag |= 2; }
2149                 }
2150         }
2151
2152         return false;
2153 }
2154
2155 MUTATOR_HOOKFUNCTION(ons, TurretValidateTarget)
2156 {
2157         if(substring(turret_target.classname, 0, 10) == "onslaught_") // don't attack onslaught targets, that's the player's job!
2158         {
2159                 ret_float = -3;
2160                 return true;
2161         }
2162
2163         return false;
2164 }
2165
2166 MUTATOR_HOOKFUNCTION(ons, TurretThink)
2167 {
2168         // ONS uses somewhat backwards linking.
2169         if(self.target)
2170         {
2171                 entity e = find(world, targetname, self.target);
2172                 if (e != world)
2173                         self.team = e.team;
2174         }
2175
2176         if(self.team != self.tur_head.team)
2177                 turret_respawn();
2178
2179         return false;
2180 }
2181
2182
2183 // ==========
2184 // Spawnfuncs
2185 // ==========
2186
2187 /*QUAKED spawnfunc_onslaught_link (0 .5 .8) (-16 -16 -16) (16 16 16)
2188   Link between control points.
2189
2190   This entity targets two different spawnfunc_onslaught_controlpoint or spawnfunc_onslaught_generator entities, and suppresses shielding on both if they are owned by different teams.
2191
2192 keys:
2193 "target" - first control point.
2194 "target2" - second control point.
2195  */
2196 spawnfunc(onslaught_link)
2197 {
2198         if(!g_onslaught) { remove(self); return; }
2199
2200         if (self.target == "" || self.target2 == "")
2201                 objerror("target and target2 must be set\n");
2202
2203         self.ons_worldlinknext = ons_worldlinklist; // link into ons_worldlinklist
2204         ons_worldlinklist = self;
2205
2206         InitializeEntity(self, ons_DelayedLinkSetup, INITPRIO_FINDTARGET);
2207         Net_LinkEntity(self, false, 0, ons_Link_Send);
2208 }
2209
2210 /*QUAKED spawnfunc_onslaught_controlpoint (0 .5 .8) (-32 -32 0) (32 32 128)
2211   Control point. Be sure to give this enough clearance so that the shootable part has room to exist
2212
2213   This should link to an spawnfunc_onslaught_controlpoint entity or spawnfunc_onslaught_generator entity.
2214
2215 keys:
2216 "targetname" - name that spawnfunc_onslaught_link entities will use to target this.
2217 "target" - target any entities that are tied to this control point, such as vehicles and buildable structure entities.
2218 "message" - name of this control point (should reflect the location in the map, such as "center bridge", "north tower", etc)
2219  */
2220
2221 spawnfunc(onslaught_controlpoint)
2222 {
2223         if(!g_onslaught) { remove(self); return; }
2224
2225         ons_ControlPoint_Setup(self);
2226 }
2227
2228 /*QUAKED spawnfunc_onslaught_generator (0 .5 .8) (-32 -32 -24) (32 32 64)
2229   Base generator.
2230
2231   spawnfunc_onslaught_link entities can target this.
2232
2233 keys:
2234 "team" - team that owns this generator (5 = red, 14 = blue, etc), MUST BE SET.
2235 "targetname" - name that spawnfunc_onslaught_link entities will use to target this.
2236  */
2237 spawnfunc(onslaught_generator)
2238 {
2239         if(!g_onslaught) { remove(self); return; }
2240         if(!self.team) { objerror("team must be set"); }
2241
2242         ons_GeneratorSetup(self);
2243 }
2244
2245 // scoreboard setup
2246 void ons_ScoreRules()
2247 {
2248         CheckAllowedTeams(world);
2249         ScoreRules_basics(((c4>=0) ? 4 : (c3>=0) ? 3 : 2), SFL_SORT_PRIO_PRIMARY, 0, true);
2250         ScoreInfo_SetLabel_TeamScore  (ST_ONS_CAPS,     "destroyed", SFL_SORT_PRIO_PRIMARY);
2251         ScoreInfo_SetLabel_PlayerScore(SP_ONS_CAPS,     "caps",      SFL_SORT_PRIO_SECONDARY);
2252         ScoreInfo_SetLabel_PlayerScore(SP_ONS_TAKES,    "takes",     0);
2253         ScoreRules_basics_end();
2254 }
2255
2256 void ons_DelayedInit() // Do this check with a delay so we can wait for teams to be set up
2257 {
2258         ons_ScoreRules();
2259
2260         round_handler_Spawn(Onslaught_CheckPlayers, Onslaught_CheckWinner, Onslaught_RoundStart);
2261         round_handler_Init(5, autocvar_g_onslaught_warmup, autocvar_g_onslaught_round_timelimit);
2262 }
2263
2264 void ons_Initialize()
2265 {
2266         g_onslaught = true;
2267         ons_captureshield_force = autocvar_g_onslaught_shield_force;
2268
2269         InitializeEntity(world, ons_DelayedInit, INITPRIO_GAMETYPE);
2270 }
2271
2272 #endif