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