]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/gamemodes/gamemode/onslaught/onslaught.qc
#define use use1
[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(entity this);
114 void havocbot_role_ons_offense(entity this);
115 void havocbot_role_ons_assistant(entity this);
116
117 void havocbot_ons_reset_role(entity this);
118 void havocbot_goalrating_items(entity this, float ratingscale, vector org, float sradius);
119 void havocbot_goalrating_enemyplayers(entity this, 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(entity this)
418 {
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 this, entity inflictor, entity attacker, float damage, int deathtype, vector hitloc, vector force)
491 {
492         if(damage <= 0) { return; }
493
494         if (this.owner.isshielded)
495         {
496                 // this is protected by a shield, so ignore the damage
497                 if (time > this.pain_finished)
498                         if (IS_PLAYER(attacker))
499                         {
500                                 play2(attacker, SND(ONS_DAMAGEBLOCKEDBYSHIELD));
501                                 this.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[this.team] > 10)
510         {
511                 play2team(this.team, SND(ONS_CONTROLPOINT_UNDERATTACK));
512                 ons_notification_time[this.team] = time;
513         }
514
515         this.health = this.health - damage;
516         if(this.owner.iscaptured)
517                 WaypointSprite_UpdateHealth(this.owner.sprite, this.health);
518         else
519                 WaypointSprite_UpdateBuildFinished(this.owner.sprite, time + (this.max_health - this.health) / (this.count / ONS_CP_THINKRATE));
520         this.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(this, CH_TRIGGER, SND_ONS_HIT1, VOL_BASE+0.3, ATTEN_NORM);
526         else
527                 sound(this, CH_TRIGGER, SND_ONS_HIT2, VOL_BASE+0.3, ATTEN_NORM);
528
529         if (this.health < 0)
530         {
531                 sound(this, CH_TRIGGER, SND_GRENADE_IMPACT, VOL_BASE, ATTEN_NORM);
532                 pointparticles(EFFECT_ROCKET_EXPLODE, this.origin, '0 0 0', 1);
533                 Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_NUM(this.team, INFO_ONSLAUGHT_CPDESTROYED), this.owner.message, attacker.netname);
534
535                 PlayerScore_Add(attacker, SP_ONS_TAKES, 1);
536                 PlayerScore_Add(attacker, SP_SCORE, 10);
537
538                 this.owner.goalentity = world;
539                 this.owner.islinked = false;
540                 this.owner.iscaptured = false;
541                 this.owner.team = 0;
542                 this.owner.colormap = 1024;
543
544                 WaypointSprite_UpdateMaxHealth(this.owner.sprite, 0);
545
546                 onslaught_updatelinks();
547
548                 // Use targets now (somebody make sure this is in the right place..)
549                 SUB_UseTargets(this.owner, this, NULL);
550
551                 this.owner.waslinked = this.owner.islinked;
552                 if(this.owner.model != "models/onslaught/controlpoint_pad.md3")
553                         setmodel_fixsize(this.owner, MDL_ONS_CP_PAD1);
554                 //setsize(this, '-32 -32 0', '32 32 8');
555
556                 remove(this);
557         }
558
559         this.SendFlags |= CPSF_STATUS;
560 }
561
562 void ons_ControlPoint_Icon_Think()
563 {SELFPARAM();
564         self.nextthink = time + ONS_CP_THINKRATE;
565
566         if(autocvar_g_onslaught_cp_proxydecap)
567         {
568                 int _enemy_count = 0;
569                 int _friendly_count = 0;
570
571                 FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it), {
572                         if(vdist(it.origin - self.origin, <, autocvar_g_onslaught_cp_proxydecap_distance))
573                         {
574                                 if(SAME_TEAM(it, self))
575                                         ++_friendly_count;
576                                 else
577                                         ++_enemy_count;
578                         }
579                 });
580
581                 _friendly_count = _friendly_count * (autocvar_g_onslaught_cp_proxydecap_dps * ONS_CP_THINKRATE);
582                 _enemy_count = _enemy_count * (autocvar_g_onslaught_cp_proxydecap_dps * ONS_CP_THINKRATE);
583
584                 self.health = bound(0, self.health + (_friendly_count - _enemy_count), self.max_health);
585                 self.SendFlags |= CPSF_STATUS;
586                 if(self.health <= 0)
587                 {
588                         ons_ControlPoint_Icon_Damage(self, self, self, 1, 0, self.origin, '0 0 0');
589                         return;
590                 }
591         }
592
593         if (time > self.pain_finished + 5)
594         {
595                 if(self.health < self.max_health)
596                 {
597                         self.health = self.health + self.count;
598                         if (self.health >= self.max_health)
599                                 self.health = self.max_health;
600                         WaypointSprite_UpdateHealth(self.owner.sprite, self.health);
601                 }
602         }
603
604         if(self.owner.islinked != self.owner.waslinked)
605         {
606                 // unteam the spawnpoint if needed
607                 int t = self.owner.team;
608                 if(!self.owner.islinked)
609                         self.owner.team = 0;
610
611                 SUB_UseTargets(self.owner, self, NULL);
612
613                 self.owner.team = t;
614
615                 self.owner.waslinked = self.owner.islinked;
616         }
617
618         // damaged fx
619         if(random() < 0.6 - self.health / self.max_health)
620         {
621                 Send_Effect(EFFECT_ELECTRIC_SPARKS, self.origin + randompos('-10 -10 -20', '10 10 20'), '0 0 0', 1);
622
623                 if(random() > 0.8)
624                         sound(self, CH_PAIN, SND_ONS_SPARK1, VOL_BASE, ATTEN_NORM);
625                 else if (random() > 0.5)
626                         sound(self, CH_PAIN, SND_ONS_SPARK2, VOL_BASE, ATTEN_NORM);
627         }
628 }
629
630 void ons_ControlPoint_Icon_BuildThink()
631 {SELFPARAM();
632         int a;
633
634         self.nextthink = time + ONS_CP_THINKRATE;
635
636         // only do this if there is power
637         a = ons_ControlPoint_CanBeLinked(self.owner, self.owner.team);
638         if(!a)
639                 return;
640
641         self.health = self.health + self.count;
642
643         self.SendFlags |= CPSF_STATUS;
644
645         if (self.health >= self.max_health)
646         {
647                 self.health = self.max_health;
648                 self.count = autocvar_g_onslaught_cp_regen * ONS_CP_THINKRATE; // slow repair rate from now on
649                 self.think = ons_ControlPoint_Icon_Think;
650                 sound(self, CH_TRIGGER, SND_ONS_CONTROLPOINT_BUILT, VOL_BASE, ATTEN_NORM);
651                 self.owner.iscaptured = true;
652                 self.solid = SOLID_BBOX;
653
654                 Send_Effect(EFFECT_CAP(self.owner.team), self.owner.origin, '0 0 0', 1);
655
656                 WaypointSprite_UpdateMaxHealth(self.owner.sprite, self.max_health);
657                 WaypointSprite_UpdateHealth(self.owner.sprite, self.health);
658
659                 if(IS_PLAYER(self.owner.ons_toucher))
660                 {
661                         Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_ONSLAUGHT_CAPTURE, self.owner.ons_toucher.netname, self.owner.message);
662                         Send_Notification(NOTIF_ALL_EXCEPT, self.owner.ons_toucher, MSG_CENTER, APP_TEAM_NUM(self.owner.ons_toucher.team, CENTER_ONS_CAPTURE), self.owner.message);
663                         Send_Notification(NOTIF_ONE, self.owner.ons_toucher, MSG_CENTER, CENTER_ONS_CAPTURE, self.owner.message);
664                         PlayerScore_Add(self.owner.ons_toucher, SP_ONS_CAPS, 1);
665                         PlayerTeamScore_AddScore(self.owner.ons_toucher, 10);
666                 }
667
668                 self.owner.ons_toucher = world;
669
670                 onslaught_updatelinks();
671
672                 // Use targets now (somebody make sure this is in the right place..)
673                 SUB_UseTargets(self.owner, self, NULL);
674
675                 self.SendFlags |= CPSF_SETUP;
676         }
677         if(self.owner.model != MDL_ONS_CP_PAD2.model_str())
678                 setmodel_fixsize(self.owner, MDL_ONS_CP_PAD2);
679
680         if(random() < 0.9 - self.health / self.max_health)
681                 Send_Effect(EFFECT_RAGE, self.origin + 10 * randomvec(), '0 0 -1', 1);
682 }
683
684 void onslaught_controlpoint_icon_link(entity e, void() spawnproc);
685
686 void ons_ControlPoint_Icon_Spawn(entity cp, entity player)
687 {
688         entity e = new(onslaught_controlpoint_icon);
689
690         setsize(e, CPICON_MIN, CPICON_MAX);
691         setorigin(e, cp.origin + CPICON_OFFSET);
692
693         e.owner = cp;
694         e.max_health = autocvar_g_onslaught_cp_health;
695         e.health = autocvar_g_onslaught_cp_buildhealth;
696         e.solid = SOLID_NOT;
697         e.takedamage = DAMAGE_AIM;
698         e.bot_attack = true;
699         e.event_damage = ons_ControlPoint_Icon_Damage;
700         e.team = player.team;
701         e.colormap = 1024 + (e.team - 1) * 17;
702         e.count = (e.max_health - e.health) * ONS_CP_THINKRATE / autocvar_g_onslaught_cp_buildtime; // how long it takes to build
703
704         sound(e, CH_TRIGGER, SND_ONS_CONTROLPOINT_BUILD, VOL_BASE, ATTEN_NORM);
705
706         cp.goalentity = e;
707         cp.team = e.team;
708         cp.colormap = e.colormap;
709
710         Send_Effect(EFFECT_FLAG_TOUCH(player.team), e.origin, '0 0 0', 1);
711
712         WaypointSprite_UpdateBuildFinished(cp.sprite, time + (e.max_health - e.health) / (e.count / ONS_CP_THINKRATE));
713         WaypointSprite_UpdateRule(cp.sprite,cp.team,SPRITERULE_TEAMPLAY);
714         cp.sprite.SendFlags |= 16;
715
716         onslaught_controlpoint_icon_link(e, ons_ControlPoint_Icon_BuildThink);
717 }
718
719 entity ons_ControlPoint_Waypoint(entity e)
720 {
721         if(e.team)
722         {
723                 int a = ons_ControlPoint_Attackable(e, e.team);
724
725                 if(a == -2) { return WP_OnsCPDefend; } // defend now
726                 if(a == -1 || a == 1 || a == 2) { return WP_OnsCP; } // touch
727                 if(a == 3 || a == 4) { return WP_OnsCPAttack; } // attack
728         }
729         else
730                 return WP_OnsCP;
731
732         return WP_Null;
733 }
734
735 void ons_ControlPoint_UpdateSprite(entity e)
736 {
737         entity s1 = ons_ControlPoint_Waypoint(e);
738         WaypointSprite_UpdateSprites(e.sprite, s1, s1, s1);
739
740         bool sh;
741         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));
742
743         if(e.lastteam != e.team + 2 || e.lastshielded != sh || e.iscaptured != e.lastcaptured)
744         {
745                 if(e.iscaptured) // don't mess up build bars!
746                 {
747                         if(sh)
748                         {
749                                 WaypointSprite_UpdateMaxHealth(e.sprite, 0);
750                         }
751                         else
752                         {
753                                 WaypointSprite_UpdateMaxHealth(e.sprite, e.goalentity.max_health);
754                                 WaypointSprite_UpdateHealth(e.sprite, e.goalentity.health);
755                         }
756                 }
757                 if(e.lastshielded)
758                 {
759                         if(e.team)
760                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, 0.5 * colormapPaletteColor(e.team - 1, false));
761                         else
762                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, '0.5 0.5 0.5');
763                 }
764                 else
765                 {
766                         if(e.team)
767                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, colormapPaletteColor(e.team - 1, false));
768                         else
769                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_CONTROLPOINT, '0.75 0.75 0.75');
770                 }
771                 WaypointSprite_Ping(e.sprite);
772
773                 e.lastteam = e.team + 2;
774                 e.lastshielded = sh;
775                 e.lastcaptured = e.iscaptured;
776         }
777 }
778
779 void ons_ControlPoint_Touch()
780 {SELFPARAM();
781         entity toucher = other;
782         int attackable;
783
784         if(IS_VEHICLE(toucher) && toucher.owner)
785         if(autocvar_g_onslaught_allow_vehicle_touch)
786                 toucher = toucher.owner;
787         else
788                 return;
789
790         if(!IS_PLAYER(toucher)) { return; }
791         if(STAT(FROZEN, toucher)) { return; }
792         if(IS_DEAD(toucher)) { return; }
793
794         if ( SAME_TEAM(self,toucher) )
795         if ( self.iscaptured )
796         {
797                 if(time <= toucher.teleport_antispam)
798                         Send_Notification(NOTIF_ONE, toucher, MSG_CENTER, CENTER_ONS_TELEPORT_ANTISPAM, rint(toucher.teleport_antispam - time));
799                 else
800                         Send_Notification(NOTIF_ONE, toucher, MSG_CENTER, CENTER_ONS_TELEPORT);
801         }
802
803         attackable = ons_ControlPoint_Attackable(self, toucher.team);
804         if(attackable != 2 && attackable != 4)
805                 return;
806         // we've verified that this player has a legitimate claim to this point,
807         // so start building the captured point icon (which only captures this
808         // point if it successfully builds without being destroyed first)
809         ons_ControlPoint_Icon_Spawn(self, toucher);
810
811         self.ons_toucher = toucher;
812
813         onslaught_updatelinks();
814 }
815
816 void ons_ControlPoint_Think()
817 {SELFPARAM();
818         self.nextthink = time + ONS_CP_THINKRATE;
819         CSQCMODEL_AUTOUPDATE(self);
820 }
821
822 void ons_ControlPoint_Reset(entity this)
823 {
824         if(this.goalentity)
825                 remove(this.goalentity);
826
827         this.goalentity = world;
828         this.team = 0;
829         this.colormap = 1024;
830         this.iscaptured = false;
831         this.islinked = false;
832         this.isshielded = true;
833         this.think = ons_ControlPoint_Think;
834         this.ons_toucher = world;
835         this.nextthink = time + ONS_CP_THINKRATE;
836         setmodel_fixsize(this, MDL_ONS_CP_PAD1);
837
838         WaypointSprite_UpdateMaxHealth(this.sprite, 0);
839         WaypointSprite_UpdateRule(this.sprite,this.team,SPRITERULE_TEAMPLAY);
840
841         onslaught_updatelinks();
842
843         SUB_UseTargets(this, this, NULL); // to reset the structures, playerspawns etc.
844
845         CSQCMODEL_AUTOUPDATE(this);
846 }
847
848 void ons_DelayedControlPoint_Setup(entity this)
849 {
850         onslaught_updatelinks();
851
852         // captureshield setup
853         ons_CaptureShield_Spawn(self, false);
854
855         CSQCMODEL_AUTOINIT(self);
856 }
857
858 void ons_ControlPoint_Setup(entity cp)
859 {SELFPARAM();
860         // declarations
861         setself(cp); // for later usage with droptofloor()
862
863         // main setup
864         cp.ons_worldcpnext = ons_worldcplist; // link control point into ons_worldcplist
865         ons_worldcplist = cp;
866
867         cp.netname = "Control point";
868         cp.team = 0;
869         cp.solid = SOLID_BBOX;
870         cp.movetype = MOVETYPE_NONE;
871         cp.touch = ons_ControlPoint_Touch;
872         cp.think = ons_ControlPoint_Think;
873         cp.nextthink = time + ONS_CP_THINKRATE;
874         cp.reset = ons_ControlPoint_Reset;
875         cp.colormap = 1024;
876         cp.iscaptured = false;
877         cp.islinked = false;
878         cp.isshielded = true;
879
880         if(cp.message == "") { cp.message = "a"; }
881
882         // appearence
883         setmodel_fixsize(cp, MDL_ONS_CP_PAD1);
884
885         // control point placement
886         if((cp.spawnflags & 1) || cp.noalign) // don't drop to floor, just stay at fixed location
887         {
888                 cp.noalign = true;
889                 cp.movetype = MOVETYPE_NONE;
890         }
891         else // drop to floor, automatically find a platform and set that as spawn origin
892         {
893                 setorigin(cp, cp.origin + '0 0 20');
894                 cp.noalign = false;
895                 setself(cp);
896                 droptofloor();
897                 cp.movetype = MOVETYPE_TOSS;
898         }
899
900         // waypointsprites
901         WaypointSprite_SpawnFixed(WP_Null, self.origin + CPGEN_WAYPOINT_OFFSET, self, sprite, RADARICON_NONE);
902         WaypointSprite_UpdateRule(self.sprite, self.team, SPRITERULE_TEAMPLAY);
903
904         InitializeEntity(cp, ons_DelayedControlPoint_Setup, INITPRIO_SETLOCATION);
905 }
906
907
908 // =========================
909 // Main Generator Functions
910 // =========================
911
912 entity ons_Generator_Waypoint(entity e)
913 {
914         if (e.isshielded)
915                 return WP_OnsGenShielded;
916         return WP_OnsGen;
917 }
918
919 void ons_Generator_UpdateSprite(entity e)
920 {
921         entity s1 = ons_Generator_Waypoint(e);
922         WaypointSprite_UpdateSprites(e.sprite, s1, s1, s1);
923
924         if(e.lastteam != e.team + 2 || e.lastshielded != e.isshielded)
925         {
926                 e.lastteam = e.team + 2;
927                 e.lastshielded = e.isshielded;
928                 if(e.lastshielded)
929                 {
930                         if(e.team)
931                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, 0.5 * colormapPaletteColor(e.team - 1, false));
932                         else
933                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, '0.5 0.5 0.5');
934                 }
935                 else
936                 {
937                         if(e.team)
938                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, colormapPaletteColor(e.team - 1, false));
939                         else
940                                 WaypointSprite_UpdateTeamRadar(e.sprite, RADARICON_GENERATOR, '0.75 0.75 0.75');
941                 }
942                 WaypointSprite_Ping(e.sprite);
943         }
944 }
945
946 void ons_GeneratorDamage(entity this, entity inflictor, entity attacker, float damage, int deathtype, vector hitloc, vector force)
947 {
948         if(damage <= 0) { return; }
949         if(warmup_stage || gameover) { return; }
950         if(!round_handler_IsRoundStarted()) { return; }
951
952         if (attacker != this)
953         {
954                 if (this.isshielded)
955                 {
956                         // this is protected by a shield, so ignore the damage
957                         if (time > this.pain_finished)
958                                 if (IS_PLAYER(attacker))
959                                 {
960                                         play2(attacker, SND(ONS_DAMAGEBLOCKEDBYSHIELD));
961                                         attacker.typehitsound += 1;
962                                         this.pain_finished = time + 1;
963                                 }
964                         return;
965                 }
966                 if (time > this.pain_finished)
967                 {
968                         this.pain_finished = time + 10;
969                         FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it) && SAME_TEAM(it, this), Send_Notification(NOTIF_ONE, it, MSG_CENTER, CENTER_GENERATOR_UNDERATTACK));
970                         play2team(this.team, SND(ONS_GENERATOR_UNDERATTACK));
971                 }
972         }
973         this.health = this.health - damage;
974         WaypointSprite_UpdateHealth(this.sprite, this.health);
975         // choose an animation frame based on health
976         this.frame = 10 * bound(0, (1 - this.health / this.max_health), 1);
977         // see if the generator is still functional, or dying
978         if (this.health > 0)
979         {
980                 this.lasthealth = this.health;
981         }
982         else
983         {
984                 if (attacker == this)
985                         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_NUM(this.team, INFO_ONSLAUGHT_GENDESTROYED_OVERTIME));
986                 else
987                 {
988                         Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_NUM(this.team, INFO_ONSLAUGHT_GENDESTROYED));
989                         PlayerScore_Add(attacker, SP_SCORE, 100);
990                 }
991                 this.iscaptured = false;
992                 this.islinked = false;
993                 this.isshielded = false;
994                 this.takedamage = DAMAGE_NO; // can't be hurt anymore
995                 this.event_damage = func_null; // won't do anything if hurt
996                 this.count = 0; // reset counter
997                 this.think = func_null;
998                 this.nextthink = 0;
999                 //this.think(); // do the first explosion now
1000
1001                 WaypointSprite_UpdateMaxHealth(this.sprite, 0);
1002                 WaypointSprite_Ping(this.sprite);
1003                 //WaypointSprite_Kill(this.sprite); // can't do this yet, code too poor
1004
1005                 onslaught_updatelinks();
1006         }
1007
1008         // Throw some flaming gibs on damage, more damage = more chance for gib
1009         if(random() < damage/220)
1010         {
1011                 sound(this, CH_TRIGGER, SND_ROCKET_IMPACT, VOL_BASE, ATTEN_NORM);
1012         }
1013         else
1014         {
1015                 // particles on every hit
1016                 Send_Effect(EFFECT_SPARKS, hitloc, force * -1, 1);
1017
1018                 //sound on every hit
1019                 if (random() < 0.5)
1020                         sound(this, CH_TRIGGER, SND_ONS_HIT1, VOL_BASE, ATTEN_NORM);
1021                 else
1022                         sound(this, CH_TRIGGER, SND_ONS_HIT2, VOL_BASE, ATTEN_NORM);
1023         }
1024
1025         this.SendFlags |= GSF_STATUS;
1026 }
1027
1028 void ons_GeneratorThink()
1029 {SELFPARAM();
1030         self.nextthink = time + GEN_THINKRATE;
1031         if (!gameover)
1032         {
1033                 if(!self.isshielded && self.wait < time)
1034                 {
1035                         self.wait = time + 5;
1036                         FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it), {
1037                                 if(SAME_TEAM(it, self))
1038                                 {
1039                                         Send_Notification(NOTIF_ONE, it, MSG_CENTER, CENTER_ONS_NOTSHIELDED_TEAM);
1040                                         soundto(MSG_ONE, it, CHAN_AUTO, SND(KH_ALARM), VOL_BASE, ATTEN_NONE);    // FIXME: unique sound?
1041                                 }
1042                                 else
1043                                         Send_Notification(NOTIF_ONE, it, MSG_CENTER, APP_TEAM_NUM(self.team, CENTER_ONS_NOTSHIELDED));
1044                         });
1045                 }
1046         }
1047 }
1048
1049 void ons_GeneratorReset(entity this)
1050 {
1051         this.team = this.team_saved;
1052         this.lasthealth = this.max_health = this.health = autocvar_g_onslaught_gen_health;
1053         this.takedamage = DAMAGE_AIM;
1054         this.bot_attack = true;
1055         this.iscaptured = true;
1056         this.islinked = true;
1057         this.isshielded = true;
1058         this.event_damage = ons_GeneratorDamage;
1059         this.think = ons_GeneratorThink;
1060         this.nextthink = time + GEN_THINKRATE;
1061
1062         Net_LinkEntity(this, false, 0, generator_send);
1063
1064         this.SendFlags = GSF_SETUP; // just incase
1065         this.SendFlags |= GSF_STATUS;
1066
1067         WaypointSprite_UpdateMaxHealth(this.sprite, this.max_health);
1068         WaypointSprite_UpdateHealth(this.sprite, this.health);
1069         WaypointSprite_UpdateRule(this.sprite,this.team,SPRITERULE_TEAMPLAY);
1070
1071         onslaught_updatelinks();
1072 }
1073
1074 void ons_DelayedGeneratorSetup(entity this)
1075 {
1076         // bot waypoints
1077         waypoint_spawnforitem_force(self, self.origin);
1078         self.nearestwaypointtimeout = 0; // activate waypointing again
1079         self.bot_basewaypoint = self.nearestwaypoint;
1080
1081         // captureshield setup
1082         ons_CaptureShield_Spawn(self, true);
1083
1084         onslaught_updatelinks();
1085
1086         Net_LinkEntity(self, false, 0, generator_send);
1087 }
1088
1089
1090 void onslaught_generator_touch()
1091 {SELFPARAM();
1092         if ( IS_PLAYER(other) )
1093         if ( SAME_TEAM(self,other) )
1094         if ( self.iscaptured )
1095         {
1096                 Send_Notification(NOTIF_ONE, other, MSG_CENTER, CENTER_ONS_TELEPORT);
1097         }
1098 }
1099
1100 void ons_GeneratorSetup(entity gen) // called when spawning a generator entity on the map as a spawnfunc
1101 {SELFPARAM();
1102         // declarations
1103         int teamnumber = gen.team;
1104         setself(gen); // for later usage with droptofloor()
1105
1106         // main setup
1107         gen.ons_worldgeneratornext = ons_worldgeneratorlist; // link generator into ons_worldgeneratorlist
1108         ons_worldgeneratorlist = gen;
1109
1110         gen.netname = sprintf("%s generator", Team_ColoredFullName(teamnumber));
1111         gen.classname = "onslaught_generator";
1112         gen.solid = SOLID_BBOX;
1113         gen.team_saved = teamnumber;
1114         gen.movetype = MOVETYPE_NONE;
1115         gen.lasthealth = gen.max_health = gen.health = autocvar_g_onslaught_gen_health;
1116         gen.takedamage = DAMAGE_AIM;
1117         gen.bot_attack = true;
1118         gen.event_damage = ons_GeneratorDamage;
1119         gen.reset = ons_GeneratorReset;
1120         gen.think = ons_GeneratorThink;
1121         gen.nextthink = time + GEN_THINKRATE;
1122         gen.iscaptured = true;
1123         gen.islinked = true;
1124         gen.isshielded = true;
1125         gen.touch = onslaught_generator_touch;
1126
1127         // appearence
1128         // model handled by CSQC
1129         setsize(gen, GENERATOR_MIN, GENERATOR_MAX);
1130         setorigin(gen, (gen.origin + CPGEN_SPAWN_OFFSET));
1131         gen.colormap = 1024 + (teamnumber - 1) * 17;
1132
1133         // generator placement
1134         setself(gen);
1135         droptofloor();
1136
1137         // waypointsprites
1138         WaypointSprite_SpawnFixed(WP_Null, self.origin + CPGEN_WAYPOINT_OFFSET, self, sprite, RADARICON_NONE);
1139         WaypointSprite_UpdateRule(self.sprite, self.team, SPRITERULE_TEAMPLAY);
1140         WaypointSprite_UpdateMaxHealth(self.sprite, self.max_health);
1141         WaypointSprite_UpdateHealth(self.sprite, self.health);
1142
1143         InitializeEntity(gen, ons_DelayedGeneratorSetup, INITPRIO_SETLOCATION);
1144 }
1145
1146
1147 // ===============
1148 //  Round Handler
1149 // ===============
1150
1151 int total_generators;
1152 void Onslaught_count_generators()
1153 {
1154         entity e;
1155         total_generators = redowned = blueowned = yellowowned = pinkowned = 0;
1156         for(e = ons_worldgeneratorlist; e; e = e.ons_worldgeneratornext)
1157         {
1158                 ++total_generators;
1159                 redowned += (e.team == NUM_TEAM_1 && e.health > 0);
1160                 blueowned += (e.team == NUM_TEAM_2 && e.health > 0);
1161                 yellowowned += (e.team == NUM_TEAM_3 && e.health > 0);
1162                 pinkowned += (e.team == NUM_TEAM_4 && e.health > 0);
1163         }
1164 }
1165
1166 int Onslaught_GetWinnerTeam()
1167 {
1168         int winner_team = 0;
1169         if(redowned > 0)
1170                 winner_team = NUM_TEAM_1;
1171         if(blueowned > 0)
1172         {
1173                 if(winner_team) return 0;
1174                 winner_team = NUM_TEAM_2;
1175         }
1176         if(yellowowned > 0)
1177         {
1178                 if(winner_team) return 0;
1179                 winner_team = NUM_TEAM_3;
1180         }
1181         if(pinkowned > 0)
1182         {
1183                 if(winner_team) return 0;
1184                 winner_team = NUM_TEAM_4;
1185         }
1186         if(winner_team)
1187                 return winner_team;
1188         return -1; // no generators left?
1189 }
1190
1191 void nades_Clear(entity e);
1192
1193 #define ONS_OWNED_GENERATORS() ((redowned > 0) + (blueowned > 0) + (yellowowned > 0) + (pinkowned > 0))
1194 #define ONS_OWNED_GENERATORS_OK() (ONS_OWNED_GENERATORS() > 1)
1195 bool Onslaught_CheckWinner()
1196 {
1197         if ((autocvar_timelimit && time > game_starttime + autocvar_timelimit * 60) || (round_handler_GetEndTime() > 0 && round_handler_GetEndTime() - time <= 0))
1198         {
1199                 ons_stalemate = true;
1200
1201                 if (!wpforenemy_announced)
1202                 {
1203                         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_CONTROLPOINT);
1204                         sound(world, CH_INFO, SND_ONS_GENERATOR_DECAY, VOL_BASE, ATTEN_NONE);
1205
1206                         wpforenemy_announced = true;
1207                 }
1208
1209                 entity tmp_entity; // temporary entity
1210                 float d;
1211                 for(tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext) if(time >= tmp_entity.ons_overtime_damagedelay)
1212                 {
1213                         // tmp_entity.max_health / 300 gives 5 minutes of overtime.
1214                         // control points reduce the overtime duration.
1215                         d = 1;
1216                         entity e;
1217                         for(e = ons_worldcplist; e; e = e.ons_worldcpnext)
1218                         {
1219                                 if(DIFF_TEAM(e, tmp_entity))
1220                                 if(e.islinked)
1221                                         d = d + 1;
1222                         }
1223
1224                         if(autocvar_g_campaign && autocvar__campaign_testrun)
1225                                 d = d * tmp_entity.max_health;
1226                         else
1227                                 d = d * tmp_entity.max_health / max(30, 60 * autocvar_timelimit_suddendeath);
1228
1229                         Damage(tmp_entity, tmp_entity, tmp_entity, d, DEATH_HURTTRIGGER.m_id, tmp_entity.origin, '0 0 0');
1230
1231                         tmp_entity.sprite.SendFlags |= 16;
1232
1233                         tmp_entity.ons_overtime_damagedelay = time + 1;
1234                 }
1235         }
1236         else { wpforenemy_announced = false; ons_stalemate = false; }
1237
1238         Onslaught_count_generators();
1239
1240         if(ONS_OWNED_GENERATORS_OK())
1241                 return 0;
1242
1243         int winner_team = Onslaught_GetWinnerTeam();
1244
1245         if(winner_team > 0)
1246         {
1247                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, APP_TEAM_NUM(winner_team, CENTER_ROUND_TEAM_WIN));
1248                 Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_NUM(winner_team, INFO_ROUND_TEAM_WIN));
1249                 TeamScore_AddToTeam(winner_team, ST_ONS_CAPS, +1);
1250         }
1251         else if(winner_team == -1)
1252         {
1253                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_ROUND_TIED);
1254                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_ROUND_TIED);
1255         }
1256
1257         ons_stalemate = false;
1258
1259         play2all(SND(CTF_CAPTURE(winner_team)));
1260
1261         round_handler_Init(7, autocvar_g_onslaught_warmup, autocvar_g_onslaught_round_timelimit);
1262
1263         FOREACH_CLIENT(IS_PLAYER(it), {
1264                 it.ons_roundlost = true;
1265                 it.player_blocked = true;
1266
1267                 nades_Clear(it);
1268         });
1269
1270         return 1;
1271 }
1272
1273 bool Onslaught_CheckPlayers()
1274 {
1275         return 1;
1276 }
1277
1278 void Onslaught_RoundStart()
1279 {
1280         entity tmp_entity;
1281         FOREACH_CLIENT(IS_PLAYER(it), it.player_blocked = false);
1282
1283         for(tmp_entity = ons_worldcplist; tmp_entity; tmp_entity = tmp_entity.ons_worldcpnext)
1284                 tmp_entity.sprite.SendFlags |= 16;
1285
1286         for(tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext)
1287                 tmp_entity.sprite.SendFlags |= 16;
1288 }
1289
1290
1291 // ================
1292 // Bot player logic
1293 // ================
1294
1295 // NOTE: LEGACY CODE, needs to be re-written!
1296
1297 void havocbot_goalrating_ons_offenseitems(entity this, float ratingscale, vector org, float sradius)
1298 {
1299         entity head;
1300         float t, c;
1301         bool needarmor = false, needweapons = false;
1302
1303         // Needs armor/health?
1304         if(this.health<100)
1305                 needarmor = true;
1306
1307         // Needs weapons?
1308         c = 0;
1309         FOREACH(Weapons, it != WEP_Null, {
1310                 if(this.weapons & (it.m_wepset))
1311                 if(++c >= 4)
1312                         break;
1313         });
1314
1315         if(c<4)
1316                 needweapons = true;
1317
1318         if(!needweapons && !needarmor)
1319                 return;
1320
1321         LOG_DEBUG(strcat(this.netname, " needs weapons ", ftos(needweapons) , "\n"));
1322         LOG_DEBUG(strcat(this.netname, " needs armor ", ftos(needarmor) , "\n"));
1323
1324         // See what is around
1325         head = findchainfloat(bot_pickup, true);
1326         while (head)
1327         {
1328                 // gather health and armor only
1329                 if (head.solid)
1330                 if ( ((head.health || head.armorvalue) && needarmor) || (head.weapons && needweapons ) )
1331                 if (vlen(head.origin - org) < sradius)
1332                 {
1333                         t = head.bot_pickupevalfunc(this, head);
1334                         if (t > 0)
1335                                 navigation_routerating(this, head, t * ratingscale, 500);
1336                 }
1337                 head = head.chain;
1338         }
1339 }
1340
1341 void havocbot_role_ons_setrole(entity this, int role)
1342 {
1343         LOG_DEBUG(strcat(this.netname," switched to "));
1344         switch(role)
1345         {
1346                 case HAVOCBOT_ONS_ROLE_DEFENSE:
1347                         LOG_DEBUG("defense");
1348                         this.havocbot_role = havocbot_role_ons_defense;
1349                         this.havocbot_role_flags = HAVOCBOT_ONS_ROLE_DEFENSE;
1350                         this.havocbot_role_timeout = 0;
1351                         break;
1352                 case HAVOCBOT_ONS_ROLE_ASSISTANT:
1353                         LOG_DEBUG("assistant");
1354                         this.havocbot_role = havocbot_role_ons_assistant;
1355                         this.havocbot_role_flags = HAVOCBOT_ONS_ROLE_ASSISTANT;
1356                         this.havocbot_role_timeout = 0;
1357                         break;
1358                 case HAVOCBOT_ONS_ROLE_OFFENSE:
1359                         LOG_DEBUG("offense");
1360                         this.havocbot_role = havocbot_role_ons_offense;
1361                         this.havocbot_role_flags = HAVOCBOT_ONS_ROLE_OFFENSE;
1362                         this.havocbot_role_timeout = 0;
1363                         break;
1364         }
1365         LOG_DEBUG("\n");
1366 }
1367
1368 void havocbot_goalrating_ons_controlpoints_attack(entity this, float ratingscale)
1369 {
1370         entity cp, cp1, cp2, best, wp;
1371         float radius, bestvalue;
1372         int c;
1373         bool found;
1374
1375         // Filter control points
1376         for(cp2 = ons_worldcplist; cp2; cp2 = cp2.ons_worldcpnext)
1377         {
1378                 cp2.wpcost = c = 0;
1379                 cp2.wpconsidered = false;
1380
1381                 if(cp2.isshielded)
1382                         continue;
1383
1384                 // Ignore owned controlpoints
1385                 if(!(cp2.isgenneighbor[this.team] || cp2.iscpneighbor[this.team]))
1386                         continue;
1387
1388                 // Count team mates interested in this control point
1389                 // (easier and cleaner than keeping counters per cp and teams)
1390                 FOREACH_CLIENT(IS_PLAYER(it), {
1391                         if(SAME_TEAM(it, this))
1392                         if(it.havocbot_role_flags & HAVOCBOT_ONS_ROLE_OFFENSE)
1393                         if(it.havocbot_ons_target == cp2)
1394                                 ++c;
1395                 });
1396
1397                 // NOTE: probably decrease the cost of attackable control points
1398                 cp2.wpcost = c;
1399                 cp2.wpconsidered = true;
1400         }
1401
1402         // We'll consider only the best case
1403         bestvalue = 99999999999;
1404         cp = world;
1405         for(cp1 = ons_worldcplist; cp1; cp1 = cp1.ons_worldcpnext)
1406         {
1407                 if (!cp1.wpconsidered)
1408                         continue;
1409
1410                 if(cp1.wpcost<bestvalue)
1411                 {
1412                         bestvalue = cp1.wpcost;
1413                         cp = cp1;
1414                         this.havocbot_ons_target = cp1;
1415                 }
1416         }
1417
1418         if (!cp)
1419                 return;
1420
1421         LOG_DEBUG(strcat(this.netname, " chose cp ranked ", ftos(bestvalue), "\n"));
1422
1423         if(cp.goalentity)
1424         {
1425                 // Should be attacked
1426                 // Rate waypoints near it
1427                 found = false;
1428                 best = world;
1429                 bestvalue = 99999999999;
1430                 for(radius=0; radius<1000 && !found; radius+=500)
1431                 {
1432                         for(wp=findradius(cp.origin,radius); wp; wp=wp.chain)
1433                         {
1434                                 if(!(wp.wpflags & WAYPOINTFLAG_GENERATED))
1435                                 if(wp.classname=="waypoint")
1436                                 if(checkpvs(wp.origin,cp))
1437                                 {
1438                                         found = true;
1439                                         if(wp.cnt<bestvalue)
1440                                         {
1441                                                 best = wp;
1442                                                 bestvalue = wp.cnt;
1443                                         }
1444                                 }
1445                         }
1446                 }
1447
1448                 if(best)
1449                 {
1450                         navigation_routerating(this, best, ratingscale, 10000);
1451                         best.cnt += 1;
1452
1453                         this.havocbot_attack_time = 0;
1454                         if(checkpvs(this.view_ofs,cp))
1455                         if(checkpvs(this.view_ofs,best))
1456                                 this.havocbot_attack_time = time + 2;
1457                 }
1458                 else
1459                 {
1460                         navigation_routerating(this, cp, ratingscale, 10000);
1461                 }
1462                 LOG_DEBUG(strcat(this.netname, " found an attackable controlpoint at ", vtos(cp.origin) ,"\n"));
1463         }
1464         else
1465         {
1466                 // Should be touched
1467                 LOG_DEBUG(strcat(this.netname, " found a touchable controlpoint at ", vtos(cp.origin) ,"\n"));
1468                 found = false;
1469
1470                 // Look for auto generated waypoint
1471                 if (!bot_waypoints_for_items)
1472                 for (wp = findradius(cp.origin,100); wp; wp = wp.chain)
1473                 {
1474                         if(wp.classname=="waypoint")
1475                         {
1476                                 navigation_routerating(this, wp, ratingscale, 10000);
1477                                 found = true;
1478                         }
1479                 }
1480
1481                 // Nothing found, rate the controlpoint itself
1482                 if (!found)
1483                         navigation_routerating(this, cp, ratingscale, 10000);
1484         }
1485 }
1486
1487 bool havocbot_goalrating_ons_generator_attack(entity this, float ratingscale)
1488 {
1489         entity g, wp, bestwp;
1490         bool found;
1491         int best;
1492
1493         for(g = ons_worldgeneratorlist; g; g = g.ons_worldgeneratornext)
1494         {
1495                 if(SAME_TEAM(g, this) || g.isshielded)
1496                         continue;
1497
1498                 // Should be attacked
1499                 // Rate waypoints near it
1500                 found = false;
1501                 bestwp = world;
1502                 best = 99999999999;
1503
1504                 for(wp=findradius(g.origin,400); wp; wp=wp.chain)
1505                 {
1506                         if(wp.classname=="waypoint")
1507                         if(checkpvs(wp.origin,g))
1508                         {
1509                                 found = true;
1510                                 if(wp.cnt<best)
1511                                 {
1512                                         bestwp = wp;
1513                                         best = wp.cnt;
1514                                 }
1515                         }
1516                 }
1517
1518                 if(bestwp)
1519                 {
1520                         LOG_DEBUG("waypoints found around generator\n");
1521                         navigation_routerating(this, bestwp, ratingscale, 10000);
1522                         bestwp.cnt += 1;
1523
1524                         this.havocbot_attack_time = 0;
1525                         if(checkpvs(this.view_ofs,g))
1526                         if(checkpvs(this.view_ofs,bestwp))
1527                                 this.havocbot_attack_time = time + 5;
1528
1529                         return true;
1530                 }
1531                 else
1532                 {
1533                         LOG_DEBUG("generator found without waypoints around\n");
1534                         // if there aren't waypoints near the generator go straight to it
1535                         navigation_routerating(this, g, ratingscale, 10000);
1536                         this.havocbot_attack_time = 0;
1537                         return true;
1538                 }
1539         }
1540         return false;
1541 }
1542
1543 void havocbot_role_ons_offense(entity this)
1544 {
1545         if(IS_DEAD(this))
1546         {
1547                 this.havocbot_attack_time = 0;
1548                 havocbot_ons_reset_role(this);
1549                 return;
1550         }
1551
1552         // Set the role timeout if necessary
1553         if (!this.havocbot_role_timeout)
1554                 this.havocbot_role_timeout = time + 120;
1555
1556         if (time > this.havocbot_role_timeout)
1557         {
1558                 havocbot_ons_reset_role(this);
1559                 return;
1560         }
1561
1562         if(this.havocbot_attack_time>time)
1563                 return;
1564
1565         if (this.bot_strategytime < time)
1566         {
1567                 navigation_goalrating_start(this);
1568                 havocbot_goalrating_enemyplayers(this, 20000, this.origin, 650);
1569                 if(!havocbot_goalrating_ons_generator_attack(this, 20000))
1570                         havocbot_goalrating_ons_controlpoints_attack(this, 20000);
1571                 havocbot_goalrating_ons_offenseitems(this, 10000, this.origin, 10000);
1572                 navigation_goalrating_end(this);
1573
1574                 this.bot_strategytime = time + autocvar_bot_ai_strategyinterval;
1575         }
1576 }
1577
1578 void havocbot_role_ons_assistant(entity this)
1579 {
1580         havocbot_ons_reset_role(this);
1581 }
1582
1583 void havocbot_role_ons_defense(entity this)
1584 {
1585         havocbot_ons_reset_role(this);
1586 }
1587
1588 void havocbot_ons_reset_role(entity this)
1589 {
1590         if(IS_DEAD(this))
1591                 return;
1592
1593         this.havocbot_ons_target = world;
1594
1595         // TODO: Defend control points or generator if necessary
1596
1597         havocbot_role_ons_setrole(this, HAVOCBOT_ONS_ROLE_OFFENSE);
1598 }
1599
1600
1601 /*
1602  * Find control point or generator owned by the same team self which is nearest to pos
1603  * if max_dist is positive, only control points within this range will be considered
1604  */
1605 entity ons_Nearest_ControlPoint(vector pos, float max_dist)
1606 {SELFPARAM();
1607         entity tmp_entity, closest_target = world;
1608         tmp_entity = findchain(classname, "onslaught_controlpoint");
1609         while(tmp_entity)
1610         {
1611                 if(SAME_TEAM(tmp_entity, self))
1612                 if(tmp_entity.iscaptured)
1613                 if(max_dist <= 0 || vdist(tmp_entity.origin - pos, <=, max_dist))
1614                 if(vlen2(tmp_entity.origin - pos) <= vlen2(closest_target.origin - pos) || closest_target == world)
1615                         closest_target = tmp_entity;
1616                 tmp_entity = tmp_entity.chain;
1617         }
1618         tmp_entity = findchain(classname, "onslaught_generator");
1619         while(tmp_entity)
1620         {
1621                 if(SAME_TEAM(tmp_entity, self))
1622                 if(max_dist <= 0 || vdist(tmp_entity.origin - pos, <, max_dist))
1623                 if(vlen2(tmp_entity.origin - pos) <= vlen2(closest_target.origin - pos) || closest_target == world)
1624                         closest_target = tmp_entity;
1625                 tmp_entity = tmp_entity.chain;
1626         }
1627
1628         return closest_target;
1629 }
1630
1631 /*
1632  * Find control point or generator owned by the same team self which is nearest to pos
1633  * if max_dist is positive, only control points within this range will be considered
1634  * This function only check distances on the XY plane, disregarding Z
1635  */
1636 entity ons_Nearest_ControlPoint_2D(vector pos, float max_dist)
1637 {SELFPARAM();
1638         entity tmp_entity, closest_target = world;
1639         vector delta;
1640         float smallest_distance = 0, distance;
1641
1642         tmp_entity = findchain(classname, "onslaught_controlpoint");
1643         while(tmp_entity)
1644         {
1645                 delta = tmp_entity.origin - pos;
1646                 delta_z = 0;
1647                 distance = vlen(delta);
1648
1649                 if(SAME_TEAM(tmp_entity, self))
1650                 if(tmp_entity.iscaptured)
1651                 if(max_dist <= 0 || distance <= max_dist)
1652                 if(closest_target == world || distance <= smallest_distance )
1653                 {
1654                         closest_target = tmp_entity;
1655                         smallest_distance = distance;
1656                 }
1657
1658                 tmp_entity = tmp_entity.chain;
1659         }
1660         tmp_entity = findchain(classname, "onslaught_generator");
1661         while(tmp_entity)
1662         {
1663                 delta = tmp_entity.origin - pos;
1664                 delta_z = 0;
1665                 distance = vlen(delta);
1666
1667                 if(SAME_TEAM(tmp_entity, self))
1668                 if(max_dist <= 0 || distance <= max_dist)
1669                 if(closest_target == world || distance <= smallest_distance )
1670                 {
1671                         closest_target = tmp_entity;
1672                         smallest_distance = distance;
1673                 }
1674
1675                 tmp_entity = tmp_entity.chain;
1676         }
1677
1678         return closest_target;
1679 }
1680 /**
1681  * find the number of control points and generators in the same team as this
1682  */
1683 int ons_Count_SelfControlPoints(entity this)
1684 {
1685         entity tmp_entity;
1686         tmp_entity = findchain(classname, "onslaught_controlpoint");
1687         int n = 0;
1688         while(tmp_entity)
1689         {
1690                 if(SAME_TEAM(tmp_entity, this))
1691                 if(tmp_entity.iscaptured)
1692                         n++;
1693                 tmp_entity = tmp_entity.chain;
1694         }
1695         tmp_entity = findchain(classname, "onslaught_generator");
1696         while(tmp_entity)
1697         {
1698                 if(SAME_TEAM(tmp_entity, this))
1699                         n++;
1700                 tmp_entity = tmp_entity.chain;
1701         }
1702         return n;
1703 }
1704
1705 /**
1706  * Teleport player to a random position near tele_target
1707  * if tele_effects is true, teleport sound+particles are created
1708  * return false on failure
1709  */
1710 bool ons_Teleport(entity player, entity tele_target, float range, bool tele_effects)
1711 {
1712         if ( !tele_target )
1713                 return false;
1714
1715         int i;
1716         vector loc;
1717         float theta;
1718         // narrow the range for each iteration to increase chances that a spawnpoint
1719         // can be found even if there's little room around the control point
1720         float iteration_scale = 1;
1721         for(i = 0; i < 16; ++i)
1722         {
1723                 iteration_scale -= i / 16;
1724                 theta = random() * 2 * M_PI;
1725                 loc_y = sin(theta);
1726                 loc_x = cos(theta);
1727                 loc_z = 0;
1728                 loc *= random() * range * iteration_scale;
1729
1730                 loc += tele_target.origin + '0 0 128' * iteration_scale;
1731
1732                 tracebox(loc, STAT(PL_MIN, NULL), STAT(PL_MAX, NULL), loc, MOVE_NORMAL, player);
1733                 if(trace_fraction == 1.0 && !trace_startsolid)
1734                 {
1735                         traceline(tele_target.origin, loc, MOVE_NOMONSTERS, tele_target); // double check to make sure we're not spawning outside the world
1736                         if(trace_fraction == 1.0 && !trace_startsolid)
1737                         {
1738                                 if ( tele_effects )
1739                                 {
1740                                         Send_Effect(EFFECT_TELEPORT, player.origin, '0 0 0', 1);
1741                                         sound (player, CH_TRIGGER, SND_TELEPORT, VOL_BASE, ATTEN_NORM);
1742                                 }
1743                                 setorigin(player, loc);
1744                                 player.angles = '0 1 0' * ( theta * RAD2DEG + 180 );
1745                                 makevectors(player.angles);
1746                                 player.fixangle = true;
1747                                 player.teleport_antispam = time + autocvar_g_onslaught_teleport_wait;
1748
1749                                 if ( tele_effects )
1750                                         Send_Effect(EFFECT_TELEPORT, player.origin + v_forward * 32, '0 0 0', 1);
1751                                 return true;
1752                         }
1753                 }
1754         }
1755
1756         return false;
1757 }
1758
1759 // ==============
1760 // Hook Functions
1761 // ==============
1762
1763 MUTATOR_HOOKFUNCTION(ons, reset_map_global)
1764 {SELFPARAM();
1765         FOREACH_CLIENT(IS_PLAYER(it), {
1766                 it.ons_roundlost = false;
1767                 it.ons_deathloc = '0 0 0';
1768                 WITHSELF(it, PutClientInServer());
1769         });
1770         return false;
1771 }
1772
1773 MUTATOR_HOOKFUNCTION(ons, ClientDisconnect)
1774 {SELFPARAM();
1775         self.ons_deathloc = '0 0 0';
1776         return false;
1777 }
1778
1779 MUTATOR_HOOKFUNCTION(ons, MakePlayerObserver)
1780 {SELFPARAM();
1781         self.ons_deathloc = '0 0 0';
1782         return false;
1783 }
1784
1785 MUTATOR_HOOKFUNCTION(ons, PlayerSpawn)
1786 {SELFPARAM();
1787         if(!round_handler_IsRoundStarted())
1788         {
1789                 self.player_blocked = true;
1790                 return false;
1791         }
1792
1793         entity l;
1794         for(l = ons_worldgeneratorlist; l; l = l.ons_worldgeneratornext)
1795         {
1796                 l.sprite.SendFlags |= 16;
1797         }
1798         for(l = ons_worldcplist; l; l = l.ons_worldcpnext)
1799         {
1800                 l.sprite.SendFlags |= 16;
1801         }
1802
1803         if(ons_stalemate) { Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_OVERTIME_CONTROLPOINT); }
1804
1805         if ( autocvar_g_onslaught_spawn_choose )
1806         if ( self.ons_spawn_by )
1807         if ( ons_Teleport(self,self.ons_spawn_by,autocvar_g_onslaught_teleport_radius,false) )
1808         {
1809                 self.ons_spawn_by = world;
1810                 return false;
1811         }
1812
1813         if(autocvar_g_onslaught_spawn_at_controlpoints)
1814         if(random() <= autocvar_g_onslaught_spawn_at_controlpoints_chance)
1815         {
1816                 float random_target = autocvar_g_onslaught_spawn_at_controlpoints_random;
1817                 entity tmp_entity, closest_target = world;
1818                 vector spawn_loc = self.ons_deathloc;
1819
1820                 // new joining player or round reset, don't bother checking
1821                 if(spawn_loc == '0 0 0') { return false; }
1822
1823                 if(random_target) { RandomSelection_Init(); }
1824
1825                 for(tmp_entity = ons_worldcplist; tmp_entity; tmp_entity = tmp_entity.ons_worldcpnext)
1826                 {
1827                         if(SAME_TEAM(tmp_entity, self))
1828                         if(random_target)
1829                                 RandomSelection_Add(tmp_entity, 0, string_null, 1, 1);
1830                         else if(vlen(tmp_entity.origin - spawn_loc) <= vlen(closest_target.origin - spawn_loc) || closest_target == world)
1831                                 closest_target = tmp_entity;
1832                 }
1833
1834                 if(random_target) { closest_target = RandomSelection_chosen_ent; }
1835
1836                 if(closest_target)
1837                 {
1838                         float i;
1839                         vector loc;
1840                         float iteration_scale = 1;
1841                         for(i = 0; i < 10; ++i)
1842                         {
1843                                 iteration_scale -= i / 10;
1844                                 loc = closest_target.origin + '0 0 96' * iteration_scale;
1845                                 loc += ('0 1 0' * random()) * 128 * iteration_scale;
1846                                 tracebox(loc, STAT(PL_MIN, NULL), STAT(PL_MAX, NULL), loc, MOVE_NORMAL, self);
1847                                 if(trace_fraction == 1.0 && !trace_startsolid)
1848                                 {
1849                                         traceline(closest_target.origin, loc, MOVE_NOMONSTERS, closest_target); // double check to make sure we're not spawning outside the world
1850                                         if(trace_fraction == 1.0 && !trace_startsolid)
1851                                         {
1852                                                 setorigin(self, loc);
1853                                                 self.angles = normalize(loc - closest_target.origin) * RAD2DEG;
1854                                                 return false;
1855                                         }
1856                                 }
1857                         }
1858                 }
1859         }
1860
1861         if(autocvar_g_onslaught_spawn_at_generator)
1862         if(random() <= autocvar_g_onslaught_spawn_at_generator_chance)
1863         {
1864                 float random_target = autocvar_g_onslaught_spawn_at_generator_random;
1865                 entity tmp_entity, closest_target = world;
1866                 vector spawn_loc = self.ons_deathloc;
1867
1868                 // new joining player or round reset, don't bother checking
1869                 if(spawn_loc == '0 0 0') { return false; }
1870
1871                 if(random_target) { RandomSelection_Init(); }
1872
1873                 for(tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext)
1874                 {
1875                         if(random_target)
1876                                 RandomSelection_Add(tmp_entity, 0, string_null, 1, 1);
1877                         else
1878                         {
1879                                 if(SAME_TEAM(tmp_entity, self))
1880                                 if(vlen(tmp_entity.origin - spawn_loc) <= vlen(closest_target.origin - spawn_loc) || closest_target == world)
1881                                         closest_target = tmp_entity;
1882                         }
1883                 }
1884
1885                 if(random_target) { closest_target = RandomSelection_chosen_ent; }
1886
1887                 if(closest_target)
1888                 {
1889                         float i;
1890                         vector loc;
1891                         float iteration_scale = 1;
1892                         for(i = 0; i < 10; ++i)
1893                         {
1894                                 iteration_scale -= i / 10;
1895                                 loc = closest_target.origin + '0 0 128' * iteration_scale;
1896                                 loc += ('0 1 0' * random()) * 256 * iteration_scale;
1897                                 tracebox(loc, STAT(PL_MIN, NULL), STAT(PL_MAX, NULL), loc, MOVE_NORMAL, self);
1898                                 if(trace_fraction == 1.0 && !trace_startsolid)
1899                                 {
1900                                         traceline(closest_target.origin, loc, MOVE_NOMONSTERS, closest_target); // double check to make sure we're not spawning outside the world
1901                                         if(trace_fraction == 1.0 && !trace_startsolid)
1902                                         {
1903                                                 setorigin(self, loc);
1904                                                 self.angles = normalize(loc - closest_target.origin) * RAD2DEG;
1905                                                 return false;
1906                                         }
1907                                 }
1908                         }
1909                 }
1910         }
1911
1912         return false;
1913 }
1914
1915 MUTATOR_HOOKFUNCTION(ons, PlayerDies)
1916 {
1917         frag_target.ons_deathloc = frag_target.origin;
1918         entity l;
1919         for(l = ons_worldgeneratorlist; l; l = l.ons_worldgeneratornext)
1920         {
1921                 l.sprite.SendFlags |= 16;
1922         }
1923         for(l = ons_worldcplist; l; l = l.ons_worldcpnext)
1924         {
1925                 l.sprite.SendFlags |= 16;
1926         }
1927
1928         if ( autocvar_g_onslaught_spawn_choose )
1929         if ( ons_Count_SelfControlPoints(frag_target) > 1 )
1930                 stuffcmd(frag_target, "qc_cmd_cl hud clickradar\n");
1931
1932         return false;
1933 }
1934
1935 MUTATOR_HOOKFUNCTION(ons, MonsterMove)
1936 {SELFPARAM();
1937         entity e = find(world, targetname, self.target);
1938         if (e != world)
1939                 self.team = e.team;
1940
1941         return false;
1942 }
1943
1944 void ons_MonsterSpawn_Delayed(entity this)
1945 {
1946         entity own = self.owner;
1947
1948         if(!own) { remove(this); return; }
1949
1950         if(own.targetname)
1951         {
1952                 entity e = find(world, target, own.targetname);
1953                 if(e != world)
1954                 {
1955                         own.team = e.team;
1956
1957                         own.use(own, e, NULL);
1958                 }
1959         }
1960
1961         remove(this);
1962 }
1963
1964 MUTATOR_HOOKFUNCTION(ons, MonsterSpawn)
1965 {SELFPARAM();
1966         entity e = spawn();
1967         e.owner = self;
1968         InitializeEntity(e, ons_MonsterSpawn_Delayed, INITPRIO_FINDTARGET);
1969
1970         return false;
1971 }
1972
1973 void ons_TurretSpawn_Delayed(entity this)
1974 {
1975         entity own = self.owner;
1976
1977         if(!own) { remove(self); return; }
1978
1979         if(own.targetname)
1980         {
1981                 entity e = find(world, target, own.targetname);
1982                 if(e != world)
1983                 {
1984                         own.team = e.team;
1985                         own.active = ACTIVE_NOT;
1986
1987                         own.use(own, e, NULL);
1988                 }
1989         }
1990
1991         remove(self);
1992 }
1993
1994 MUTATOR_HOOKFUNCTION(ons, TurretSpawn)
1995 {SELFPARAM();
1996         entity e = spawn();
1997         e.owner = self;
1998         InitializeEntity(e, ons_TurretSpawn_Delayed, INITPRIO_FINDTARGET);
1999
2000         return false;
2001 }
2002
2003 MUTATOR_HOOKFUNCTION(ons, HavocBot_ChooseRole)
2004 {SELFPARAM();
2005         havocbot_ons_reset_role(self);
2006         return true;
2007 }
2008
2009 MUTATOR_HOOKFUNCTION(ons, GetTeamCount)
2010 {
2011         // onslaught is special
2012         for(entity tmp_entity = ons_worldgeneratorlist; tmp_entity; tmp_entity = tmp_entity.ons_worldgeneratornext)
2013         {
2014                 switch(tmp_entity.team)
2015                 {
2016                         case NUM_TEAM_1: c1 = 0; break;
2017                         case NUM_TEAM_2: c2 = 0; break;
2018                         case NUM_TEAM_3: c3 = 0; break;
2019                         case NUM_TEAM_4: c4 = 0; break;
2020                 }
2021         }
2022
2023         return true;
2024 }
2025
2026 MUTATOR_HOOKFUNCTION(ons, SpectateCopy)
2027 {SELFPARAM();
2028         self.ons_roundlost = other.ons_roundlost; // make spectators see it too
2029         return false;
2030 }
2031
2032 MUTATOR_HOOKFUNCTION(ons, SV_ParseClientCommand)
2033 {SELFPARAM();
2034         if(MUTATOR_RETURNVALUE) // command was already handled?
2035                 return false;
2036
2037         if ( cmd_name == "ons_spawn" )
2038         {
2039                 vector pos = self.origin;
2040                 if(cmd_argc > 1)
2041                         pos_x = stof(argv(1));
2042                 if(cmd_argc > 2)
2043                         pos_y = stof(argv(2));
2044                 if(cmd_argc > 3)
2045                         pos_z = stof(argv(3));
2046
2047                 if ( IS_PLAYER(self) )
2048                 {
2049                         if ( !STAT(FROZEN, self) )
2050                         {
2051                                 entity source_point = ons_Nearest_ControlPoint(self.origin, autocvar_g_onslaught_teleport_radius);
2052
2053                                 if ( !source_point && self.health > 0 )
2054                                 {
2055                                         sprint(self, "\nYou need to be next to a control point\n");
2056                                         return 1;
2057                                 }
2058
2059
2060                                 entity closest_target = ons_Nearest_ControlPoint_2D(pos, autocvar_g_onslaught_click_radius);
2061
2062                                 if ( closest_target == world )
2063                                 {
2064                                         sprint(self, "\nNo control point found\n");
2065                                         return 1;
2066                                 }
2067
2068                                 if ( self.health <= 0 )
2069                                 {
2070                                         self.ons_spawn_by = closest_target;
2071                                         self.respawn_flags = self.respawn_flags | RESPAWN_FORCE;
2072                                 }
2073                                 else
2074                                 {
2075                                         if ( source_point == closest_target )
2076                                         {
2077                                                 sprint(self, "\nTeleporting to the same point\n");
2078                                                 return 1;
2079                                         }
2080
2081                                         if ( !ons_Teleport(self,closest_target,autocvar_g_onslaught_teleport_radius,true) )
2082                                                 sprint(self, "\nUnable to teleport there\n");
2083                                 }
2084
2085                                 return 1;
2086                         }
2087
2088                         sprint(self, "\nNo teleportation for you\n");
2089                 }
2090
2091                 return 1;
2092         }
2093         return 0;
2094 }
2095
2096 MUTATOR_HOOKFUNCTION(ons, PlayerUseKey)
2097 {SELFPARAM();
2098         if(MUTATOR_RETURNVALUE || gameover) { return false; }
2099
2100         if((time > self.teleport_antispam) && (!IS_DEAD(self)) && !self.vehicle)
2101         {
2102                 entity source_point = ons_Nearest_ControlPoint(self.origin, autocvar_g_onslaught_teleport_radius);
2103                 if ( source_point )
2104                 {
2105                         stuffcmd(self, "qc_cmd_cl hud clickradar\n");
2106                         return true;
2107                 }
2108         }
2109
2110         return false;
2111 }
2112
2113 MUTATOR_HOOKFUNCTION(ons, PlayHitsound)
2114 {
2115         return (frag_victim.classname == "onslaught_generator" && !frag_victim.isshielded)
2116                 || (frag_victim.classname == "onslaught_controlpoint_icon" && !frag_victim.owner.isshielded);
2117 }
2118
2119 MUTATOR_HOOKFUNCTION(ons, SendWaypoint)
2120 {
2121     SELFPARAM();
2122         if(wp_sendflags & 16)
2123         {
2124                 if(self.owner.classname == "onslaught_controlpoint")
2125                 {
2126                         entity wp_owner = self.owner;
2127                         entity e = WaypointSprite_getviewentity(wp_sendto);
2128                         if(SAME_TEAM(e, wp_owner) && wp_owner.goalentity.health >= wp_owner.goalentity.max_health) { wp_flag |= 2; }
2129                         if(!ons_ControlPoint_Attackable(wp_owner, e.team)) { wp_flag |= 2; }
2130                 }
2131                 if(self.owner.classname == "onslaught_generator")
2132                 {
2133                         entity wp_owner = self.owner;
2134                         if(wp_owner.isshielded && wp_owner.health >= wp_owner.max_health) { wp_flag |= 2; }
2135                         if(wp_owner.health <= 0) { wp_flag |= 2; }
2136                 }
2137         }
2138
2139         return false;
2140 }
2141
2142 MUTATOR_HOOKFUNCTION(ons, TurretValidateTarget)
2143 {
2144         if(substring(turret_target.classname, 0, 10) == "onslaught_") // don't attack onslaught targets, that's the player's job!
2145         {
2146                 ret_float = -3;
2147                 return true;
2148         }
2149
2150         return false;
2151 }
2152
2153 MUTATOR_HOOKFUNCTION(ons, TurretThink)
2154 {
2155     SELFPARAM();
2156         // ONS uses somewhat backwards linking.
2157         if(self.target)
2158         {
2159                 entity e = find(world, targetname, self.target);
2160                 if (e != world)
2161                         self.team = e.team;
2162         }
2163
2164         if(self.team != self.tur_head.team)
2165                 turret_respawn();
2166
2167         return false;
2168 }
2169
2170
2171 // ==========
2172 // Spawnfuncs
2173 // ==========
2174
2175 /*QUAKED spawnfunc_onslaught_link (0 .5 .8) (-16 -16 -16) (16 16 16)
2176   Link between control points.
2177
2178   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.
2179
2180 keys:
2181 "target" - first control point.
2182 "target2" - second control point.
2183  */
2184 spawnfunc(onslaught_link)
2185 {
2186         if(!g_onslaught) { remove(self); return; }
2187
2188         if (self.target == "" || self.target2 == "")
2189                 objerror("target and target2 must be set\n");
2190
2191         self.ons_worldlinknext = ons_worldlinklist; // link into ons_worldlinklist
2192         ons_worldlinklist = self;
2193
2194         InitializeEntity(self, ons_DelayedLinkSetup, INITPRIO_FINDTARGET);
2195         Net_LinkEntity(self, false, 0, ons_Link_Send);
2196 }
2197
2198 /*QUAKED spawnfunc_onslaught_controlpoint (0 .5 .8) (-32 -32 0) (32 32 128)
2199   Control point. Be sure to give this enough clearance so that the shootable part has room to exist
2200
2201   This should link to an spawnfunc_onslaught_controlpoint entity or spawnfunc_onslaught_generator entity.
2202
2203 keys:
2204 "targetname" - name that spawnfunc_onslaught_link entities will use to target this.
2205 "target" - target any entities that are tied to this control point, such as vehicles and buildable structure entities.
2206 "message" - name of this control point (should reflect the location in the map, such as "center bridge", "north tower", etc)
2207  */
2208
2209 spawnfunc(onslaught_controlpoint)
2210 {
2211         if(!g_onslaught) { remove(self); return; }
2212
2213         ons_ControlPoint_Setup(self);
2214 }
2215
2216 /*QUAKED spawnfunc_onslaught_generator (0 .5 .8) (-32 -32 -24) (32 32 64)
2217   Base generator.
2218
2219   spawnfunc_onslaught_link entities can target this.
2220
2221 keys:
2222 "team" - team that owns this generator (5 = red, 14 = blue, etc), MUST BE SET.
2223 "targetname" - name that spawnfunc_onslaught_link entities will use to target this.
2224  */
2225 spawnfunc(onslaught_generator)
2226 {
2227         if(!g_onslaught) { remove(self); return; }
2228         if(!self.team) { objerror("team must be set"); }
2229
2230         ons_GeneratorSetup(self);
2231 }
2232
2233 // scoreboard setup
2234 void ons_ScoreRules()
2235 {
2236         CheckAllowedTeams(world);
2237         ScoreRules_basics(((c4>=0) ? 4 : (c3>=0) ? 3 : 2), SFL_SORT_PRIO_PRIMARY, 0, true);
2238         ScoreInfo_SetLabel_TeamScore  (ST_ONS_CAPS,     "destroyed", SFL_SORT_PRIO_PRIMARY);
2239         ScoreInfo_SetLabel_PlayerScore(SP_ONS_CAPS,     "caps",      SFL_SORT_PRIO_SECONDARY);
2240         ScoreInfo_SetLabel_PlayerScore(SP_ONS_TAKES,    "takes",     0);
2241         ScoreRules_basics_end();
2242 }
2243
2244 void ons_DelayedInit(entity this) // Do this check with a delay so we can wait for teams to be set up
2245 {
2246         ons_ScoreRules();
2247
2248         round_handler_Spawn(Onslaught_CheckPlayers, Onslaught_CheckWinner, Onslaught_RoundStart);
2249         round_handler_Init(5, autocvar_g_onslaught_warmup, autocvar_g_onslaught_round_timelimit);
2250 }
2251
2252 void ons_Initialize()
2253 {
2254         g_onslaught = true;
2255         ons_captureshield_force = autocvar_g_onslaught_shield_force;
2256
2257         InitializeEntity(world, ons_DelayedInit, INITPRIO_GAMETYPE);
2258 }
2259
2260 #endif