]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/turrets/sv_turrets.qc
Add Read/WriteAngleVector macros to simplify the networking of angles
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / turrets / sv_turrets.qc
1 #include "sv_turrets.qh"
2 #ifdef SVQC
3 #include <server/autocvars.qh>
4
5 // Generic aiming
6 vector turret_aim_generic(entity this)
7 {
8
9         vector pre_pos, prep;
10         float distance, impact_time = 0, i, mintime;
11
12         turret_tag_fire_update(this);
13
14         if(this.aim_flags & TFL_AIM_SIMPLE)
15                 return real_origin(this.enemy);
16
17         mintime = max(this.attack_finished_single[0] - time,0) + sys_frametime;
18
19         // Baseline
20         pre_pos = real_origin(this.enemy);
21
22         // Lead?
23         if (this.aim_flags & TFL_AIM_LEAD)
24         {
25                 if (this.aim_flags & TFL_AIM_SHOTTIMECOMPENSATE)           // Need to conpensate for shot traveltime
26                 {
27                         prep = pre_pos;
28
29                         distance = vlen(prep - this.tur_shotorg);
30                         impact_time = distance / this.shot_speed;
31
32                         prep = pre_pos + (this.enemy.velocity * (impact_time + mintime));
33
34                         if(this.aim_flags & TFL_AIM_ZPREDICT)
35                         if(!IS_ONGROUND(this.enemy))
36                         if(this.enemy.move_movetype == MOVETYPE_WALK || this.enemy.move_movetype == MOVETYPE_TOSS || this.enemy.move_movetype == MOVETYPE_BOUNCE)
37                         {
38                                 float vz;
39                                 prep_z = pre_pos_z;
40                                 vz = this.enemy.velocity_z;
41                                 for(i = 0; i < impact_time; i += sys_frametime)
42                                 {
43                                         vz = vz - (autocvar_sv_gravity * sys_frametime);
44                                         prep_z = prep_z + vz * sys_frametime;
45                                 }
46                         }
47                         pre_pos = prep;
48                 }
49                 else
50                         pre_pos = pre_pos + this.enemy.velocity * mintime;
51         }
52
53         if(this.aim_flags & TFL_AIM_SPLASH)
54         {
55                 //tracebox(pre_pos + '0 0 32',this.enemy.mins,this.enemy.maxs,pre_pos -'0 0 64',MOVE_WORLDONLY,this.enemy);
56                 traceline(pre_pos + '0 0 32',pre_pos -'0 0 64',MOVE_WORLDONLY,this.enemy);
57                 if(trace_fraction != 1.0)
58                         pre_pos = trace_endpos;
59         }
60
61         return pre_pos;
62 }
63
64 float turret_targetscore_support(entity _turret,entity _target)
65 {
66         float score;            // Total score
67         float s_score = 0, d_score;
68
69         if (_turret.enemy == _target) s_score = 1;
70
71         d_score = min(_turret.target_range_optimal,tvt_dist) / max(_turret.target_range_optimal,tvt_dist);
72
73         score = (d_score * _turret.target_select_rangebias) +
74                         (s_score * _turret.target_select_samebias);
75
76         return score;
77 }
78
79 /*
80 * Generic bias aware score system.
81 */
82 float turret_targetscore_generic(entity _turret, entity _target)
83 {
84         float d_dist;      // Defendmode Distance
85         float score;            // Total score
86         float d_score;    // Distance score
87         float a_score;    // Angular score
88         float m_score = 0;  // missile score
89         float p_score = 0;  // player score
90         float ikr;                // ideal kill range
91
92         if (_turret.tur_defend)
93         {
94                 d_dist = vlen(real_origin(_target) - _turret.tur_defend.origin);
95                 ikr = vlen(_turret.origin - _turret.tur_defend.origin);
96                 d_score = 1 - d_dist / _turret.target_range;
97         }
98         else
99         {
100                 // Make a normlized value base on the targets distance from our optimal killzone
101                 ikr = _turret.target_range_optimal;
102                 d_score = min(ikr, tvt_dist) / max(ikr, tvt_dist);
103         }
104
105         a_score = 1 - tvt_thadf / _turret.aim_maxrot;
106
107         if ((_turret.target_select_missilebias > 0) && (_target.flags & FL_PROJECTILE))
108                 m_score = 1;
109
110         if ((_turret.target_select_playerbias > 0) && IS_CLIENT(_target))
111                 p_score = 1;
112
113         d_score = max(d_score, 0);
114         a_score = max(a_score, 0);
115         m_score = max(m_score, 0);
116         p_score = max(p_score, 0);
117
118         score = (d_score * _turret.target_select_rangebias) +
119                         (a_score * _turret.target_select_anglebias) +
120                         (m_score * _turret.target_select_missilebias) +
121                         (p_score * _turret.target_select_playerbias);
122
123         if(vdist((_turret.tur_shotorg - real_origin(_target)), >, _turret.target_range))
124         {
125                 //dprint("Wtf?\n");
126                 score *= 0.001;
127         }
128
129 #ifdef TURRET_DEBUG
130         string sd,sa,sm,sp,ss;
131         string sdt,sat,smt,spt;
132
133         sd = ftos(d_score);
134         d_score *= _turret.target_select_rangebias;
135         sdt = ftos(d_score);
136
137         //sv = ftos(v_score);
138         //v_score *= _turret.target_select_samebias;
139         //svt = ftos(v_score);
140
141         sa = ftos(a_score);
142         a_score *= _turret.target_select_anglebias;
143         sat = ftos(a_score);
144
145         sm = ftos(m_score);
146         m_score *= _turret.target_select_missilebias;
147         smt = ftos(m_score);
148
149         sp = ftos(p_score);
150         p_score *= _turret.target_select_playerbias;
151         spt = ftos(p_score);
152
153
154         ss = ftos(score);
155         bprint("^3Target scores^7 \[  ",_turret.netname, "  \] ^3for^7 \[  ", _target.netname,"  \]\n");
156         bprint("^5Range:\[  ",sd,  "  \]^2+bias:\[  ",sdt,"  \]\n");
157         bprint("^5Angle:\[  ",sa,  "  \]^2+bias:\[  ",sat,"  \]\n");
158         bprint("^5Missile:\[  ",sm,"  \]^2+bias:\[  ",smt,"  \]\n");
159         bprint("^5Player:\[  ",sp, "  \]^2+bias:\[  ",spt,"  \]\n");
160         bprint("^3Total (w/bias):\[^1",ss,"\]\n");
161
162 #endif
163
164         return score;
165 }
166
167 // Generic damage handling
168 void turret_hide(entity this)
169 {
170         this.effects   |= EF_NODRAW;
171         this.nextthink = time + this.respawntime - 0.2;
172         setthink(this, turret_respawn);
173 }
174
175 void turret_die(entity this)
176 {
177         this.deadflag             = DEAD_DEAD;
178         this.tur_head.deadflag = this.deadflag;
179
180 // Unsolidify and hide real parts
181         this.solid                       = SOLID_NOT;
182         this.tur_head.solid      = this.solid;
183
184         this.event_damage                 = func_null;
185         this.event_heal = func_null;
186         this.takedamage                  = DAMAGE_NO;
187
188         SetResourceExplicit(this, RES_HEALTH, 0);
189
190 // Go boom
191         //RadiusDamage (this,this, min(this.ammo,50),min(this.ammo,50) * 0.25,250,NULL,min(this.ammo,50)*5,DEATH_TURRET,NULL);
192
193         Turret tur = get_turretinfo(this.m_id);
194         if(this.damage_flags & TFL_DMG_DEATH_NORESPAWN)
195         {
196                 // do a simple explosion effect here, since CSQC can't do it on a to-be-removed entity
197                 sound(this, CH_SHOTS, SND_ROCKET_IMPACT, VOL_BASE, ATTEN_NORM);
198                 Send_Effect(EFFECT_ROCKET_EXPLODE, this.origin, '0 0 0', 1);
199
200                 tur.tr_death(tur, this);
201
202                 delete(this.tur_head);
203                 delete(this);
204         }
205         else
206         {
207                 // Setup respawn
208                 this.SendFlags    |= TNSF_STATUS;
209                 this.nextthink   = time + 0.2;
210                 setthink(this, turret_hide);
211
212                 tur.tr_death(tur, this);
213         }
214 }
215
216 void turret_damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector vforce)
217 {
218         // Enough already!
219         if(this.deadflag == DEAD_DEAD)
220                 return;
221
222         // Inactive turrets take no damage. (hm..)
223         if(!this.active)
224                 return;
225
226         if(SAME_TEAM(this, attacker))
227         {
228                 if(autocvar_g_friendlyfire)
229                         damage = damage * autocvar_g_friendlyfire;
230                 else
231                         return;
232         }
233
234         TakeResource(this, RES_HEALTH, damage);
235
236         // thorw head slightly off aim when hit?
237         if (this.damage_flags & TFL_DMG_HEADSHAKE)
238         {
239                 this.tur_head.angles_x = this.tur_head.angles_x + (-0.5 + random()) * damage;
240                 this.tur_head.angles_y = this.tur_head.angles_y + (-0.5 + random()) * damage;
241
242                 this.SendFlags  |= TNSF_ANG;
243         }
244
245         if (this.turret_flags & TUR_FLAG_MOVE)
246                 this.velocity = this.velocity + vforce;
247
248         if (GetResource(this, RES_HEALTH) <= 0)
249         {
250                 this.event_damage                 = func_null;
251                 this.tur_head.event_damage = func_null;
252                 this.event_heal = func_null;
253                 this.tur_head.event_heal = func_null;
254                 this.takedamage                  = DAMAGE_NO;
255                 this.nextthink = time;
256                 setthink(this, turret_die);
257         }
258
259         this.SendFlags  |= TNSF_STATUS;
260 }
261
262 bool turret_heal(entity targ, entity inflictor, float amount, float limit)
263 {
264         float true_limit = ((limit != RES_LIMIT_NONE) ? limit : targ.max_health);
265         if(GetResource(targ, RES_HEALTH) <= 0 || GetResource(targ, RES_HEALTH) >= true_limit)
266                 return false;
267
268         GiveResourceWithLimit(targ, RES_HEALTH, amount, true_limit);
269         targ.SendFlags |= TNSF_STATUS;
270         return true;
271 }
272
273 void turret_think(entity this);
274 void turret_respawn(entity this)
275 {
276         // Make sure all parts belong to the same team since
277         // this function doubles as "teamchange" function.
278         this.tur_head.team      = this.team;
279         this.effects                       &= ~EF_NODRAW;
280         this.deadflag                           = DEAD_NO;
281         this.effects                            = EF_LOWPRECISION;
282         this.solid                                      = SOLID_BBOX;
283         this.takedamage                         = DAMAGE_AIM;
284         this.event_damage                       = turret_damage;
285         this.event_heal                         = turret_heal;
286         this.avelocity                          = '0 0 0';
287         this.tur_head.avelocity         = this.avelocity;
288         this.tur_head.angles            = this.idle_aim;
289         SetResourceExplicit(this, RES_HEALTH, this.max_health);
290         this.enemy                                      = NULL;
291         this.volly_counter                      = this.shot_volly;
292         this.ammo                                       = this.ammo_max;
293
294         this.nextthink = time + this.ticrate;
295         setthink(this, turret_think);
296
297         this.SendFlags = TNSF_FULL_UPDATE;
298
299         Turret tur = get_turretinfo(this.m_id);
300         tur.tr_setup(tur, this);
301 }
302
303
304 // Main functions
305 .float clientframe;
306 void turrets_setframe(entity this, float _frame, float client_only)
307 {
308         if((client_only ? this.clientframe : this.frame ) != _frame)
309         {
310                 this.SendFlags |= TNSF_ANIM;
311                 this.anim_start_time = time;
312         }
313
314          if(client_only)
315                 this.clientframe = _frame;
316         else
317                 this.frame = _frame;
318
319 }
320
321 bool turret_send(entity this, entity to, float sf)
322 {
323         WriteHeader(MSG_ENTITY, ENT_CLIENT_TURRET);
324         WriteByte(MSG_ENTITY, sf);
325         if(sf & TNSF_SETUP)
326         {
327                 WriteByte(MSG_ENTITY, this.m_id);
328
329                 WriteVector(MSG_ENTITY, this.origin);
330
331                 WriteAngleVector2D(MSG_ENTITY, this.angles);
332         }
333
334         if(sf & TNSF_ANG)
335         {
336                 WriteShort(MSG_ENTITY, rint(this.tur_head.angles_x));
337                 WriteShort(MSG_ENTITY, rint(this.tur_head.angles_y));
338         }
339
340         if(sf & TNSF_AVEL)
341         {
342                 WriteShort(MSG_ENTITY, rint(this.tur_head.avelocity_x));
343                 WriteShort(MSG_ENTITY, rint(this.tur_head.avelocity_y));
344         }
345
346         if(sf & TNSF_MOVE)
347         {
348                 WriteVector(MSG_ENTITY, this.origin);
349
350                 WriteVector(MSG_ENTITY, this.velocity);
351
352                 WriteShort(MSG_ENTITY, rint(this.angles_y));
353         }
354
355         if(sf & TNSF_ANIM)
356         {
357                 WriteCoord(MSG_ENTITY, this.anim_start_time);
358                 WriteByte(MSG_ENTITY, this.frame);
359         }
360
361         if(sf & TNSF_STATUS)
362         {
363                 WriteByte(MSG_ENTITY, this.team);
364
365                 if(GetResource(this, RES_HEALTH) <= 0)
366                         WriteByte(MSG_ENTITY, 0);
367                 else
368                         WriteByte(MSG_ENTITY, ceil((GetResource(this, RES_HEALTH) / this.max_health) * 255));
369         }
370
371         return true;
372 }
373
374 void load_unit_settings(entity ent, bool is_reload)
375 {
376         if (ent == NULL)
377                 return;
378
379         if(!ent.turret_scale_damage)    ent.turret_scale_damage = 1;
380         if(!ent.turret_scale_range)             ent.turret_scale_range  = 1;
381         if(!ent.turret_scale_refire)    ent.turret_scale_refire = 1;
382         if(!ent.turret_scale_ammo)              ent.turret_scale_ammo   = 1;
383         if(!ent.turret_scale_aim)               ent.turret_scale_aim     = 1;
384         if(!ent.turret_scale_health)    ent.turret_scale_health = 1;
385         if(!ent.turret_scale_respawn)   ent.turret_scale_respawn = 1;
386
387         if (is_reload)
388         {
389                 ent.enemy = NULL;
390                 ent.tur_head.avelocity = '0 0 0';
391
392                 ent.tur_head.angles = '0 0 0';
393         }
394
395         string unitname = ent.netname;
396         #define X(class, prefix, fld, type) ent.fld = cvar(strcat("g_turrets_unit_", prefix, "_", #fld));
397         TR_PROPS_COMMON(X, , unitname)
398         #undef X
399
400         ent.ammo_max             *= ent.turret_scale_ammo;
401         ent.ammo_recharge        *= ent.turret_scale_ammo;
402         ent.aim_speed            *= ent.turret_scale_aim;
403         SetResourceExplicit(ent, RES_HEALTH, GetResource(ent, RES_HEALTH) * ent.turret_scale_health);
404         ent.respawntime          *= ent.turret_scale_respawn;
405         ent.shot_dmg             *= ent.turret_scale_damage;
406         ent.shot_refire          *= ent.turret_scale_refire;
407         ent.shot_radius          *= ent.turret_scale_damage;
408         ent.shot_force           *= ent.turret_scale_damage;
409         ent.shot_volly_refire    *= ent.turret_scale_refire;
410         ent.target_range         *= ent.turret_scale_range;
411         ent.target_range_min     *= ent.turret_scale_range;
412         ent.target_range_optimal *= ent.turret_scale_range;
413
414         if(is_reload) {
415                 Turret tur = get_turretinfo(ent.m_id);
416                 tur.tr_setup(tur, ent);
417         }
418 }
419
420 void turret_projectile_explode(entity this)
421 {
422
423         this.takedamage = DAMAGE_NO;
424         this.event_damage = func_null;
425 #ifdef TURRET_DEBUG
426         float d;
427         d = RadiusDamage (this, this.owner, this.owner.shot_dmg, 0, this.owner.shot_radius, this, NULL, this.owner.shot_force, this.totalfrags, DMG_NOWEP, NULL);
428         this.owner.tur_debug_dmg_t_h = this.owner.tur_debug_dmg_t_h + d;
429         this.owner.tur_debug_dmg_t_f = this.owner.tur_debug_dmg_t_f + this.owner.shot_dmg;
430 #else
431         RadiusDamage (this, this.realowner, this.owner.shot_dmg, 0, this.owner.shot_radius, this, NULL, this.owner.shot_force, this.totalfrags, DMG_NOWEP, NULL);
432 #endif
433         delete(this);
434 }
435
436 void turret_projectile_touch(entity this, entity toucher)
437 {
438         PROJECTILE_TOUCH(this, toucher);
439         turret_projectile_explode(this);
440 }
441
442 void turret_projectile_damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector vforce)
443 {
444         this.velocity  += vforce;
445         TakeResource(this, RES_HEALTH, damage);
446         //this.realowner = attacker; // Dont change realowner, it does not make much sense for turrets
447         if(GetResource(this, RES_HEALTH) <= 0)
448                 W_PrepareExplosionByDamage(this, this.owner, turret_projectile_explode);
449 }
450
451 entity turret_projectile(entity actor, Sound _snd, float _size, float _health, float _death, float _proj_type, float _cull, float _cli_anim)
452 {
453         TC(Sound, _snd);
454         entity proj;
455
456         sound (actor, CH_WEAPON_A, _snd, VOL_BASE, ATTEN_NORM);
457         proj                             = spawn ();
458         setorigin(proj, actor.tur_shotorg);
459         setsize(proj, '-0.5 -0.5 -0.5' * _size, '0.5 0.5 0.5' * _size);
460         proj.owner                = actor;
461         proj.realowner    = actor;
462         proj.bot_dodge    = true;
463         proj.bot_dodgerating = actor.shot_dmg;
464         setthink(proj, turret_projectile_explode);
465         settouch(proj, turret_projectile_touch);
466         proj.nextthink    = time + 9;
467         set_movetype(proj, MOVETYPE_FLYMISSILE);
468         proj.velocity           = normalize(actor.tur_shotdir_updated + randomvec() * actor.shot_spread) * actor.shot_speed;
469         proj.flags = FL_PROJECTILE;
470         IL_PUSH(g_projectiles, proj);
471         IL_PUSH(g_bot_dodge, proj);
472         proj.enemy                = actor.enemy;
473         proj.totalfrags  = _death;
474         PROJECTILE_MAKETRIGGER(proj);
475         if(_health)
476         {
477                 SetResourceExplicit(proj, RES_HEALTH, _health);
478                 proj.takedamage  = DAMAGE_YES;
479                 proj.event_damage  = turret_projectile_damage;
480         }
481         else
482                 proj.flags |= FL_NOTARGET;
483
484         CSQCProjectile(proj, _cli_anim, _proj_type, _cull);
485
486         return proj;
487 }
488
489 /**
490 ** updates enemy distances, predicted impact point/time
491 ** and updated aim<->predict impact distance.
492 **/
493 void turret_do_updates(entity t_turret)
494 {
495         vector enemy_pos = real_origin(t_turret.enemy);
496
497         turret_tag_fire_update(t_turret);
498
499         t_turret.tur_shotdir_updated = v_forward;
500         t_turret.tur_dist_enemy = vlen(t_turret.tur_shotorg - enemy_pos);
501         t_turret.tur_dist_aimpos = vlen(t_turret.tur_shotorg - t_turret.tur_aimpos);
502
503         /*if((t_turret.firecheck_flags & TFL_FIRECHECK_VERIFIED) && (t_turret.enemy))
504         {
505                 oldpos = t_turret.enemy.origin;
506                 setorigin(t_turret.enemy, t_turret.tur_aimpos);
507                 tracebox(t_turret.tur_shotorg, '-1 -1 -1', '1 1 1', t_turret.tur_shotorg + (t_turret.tur_shotdir_updated * t_turret.tur_dist_aimpos), MOVE_NORMAL,t_turret);
508                 setorigin(t_turret.enemy, oldpos);
509
510                 if(trace_ent == t_turret.enemy)
511                         t_turret.tur_dist_impact_to_aimpos = 0;
512                 else
513                         t_turret.tur_dist_impact_to_aimpos = vlen(trace_endpos - t_turret.tur_aimpos);
514         }
515         else*/
516                 tracebox(t_turret.tur_shotorg, '-1 -1 -1','1 1 1', t_turret.tur_shotorg + (t_turret.tur_shotdir_updated * t_turret.tur_dist_aimpos), MOVE_NORMAL,t_turret);
517
518         t_turret.tur_dist_impact_to_aimpos = vlen(trace_endpos - t_turret.tur_aimpos) - (vlen(t_turret.enemy.maxs - t_turret.enemy.mins) * 0.5);
519         t_turret.tur_impactent                   = trace_ent;
520         t_turret.tur_impacttime                 = vlen(t_turret.tur_shotorg - trace_endpos) / t_turret.shot_speed;
521 }
522
523 /**
524 ** Handles head rotation according to
525 ** the units .track_type and .track_flags
526 **/
527 .float turret_framecounter;
528 void turret_track(entity this)
529 {
530         vector target_angle; // This is where we want to aim
531         vector move_angle;   // This is where we can aim
532         float f_tmp;
533         vector v1, v2;
534         v1 = this.tur_head.angles;
535         v2 = this.tur_head.avelocity;
536
537         if (this.track_flags == TFL_TRACK_NO)
538                 return;
539
540         if(!this.active)
541                 target_angle = this.idle_aim - ('1 0 0' * this.aim_maxpitch);
542         else if (this.enemy == NULL)
543         {
544                 if(time > this.lip)
545                         target_angle = this.idle_aim + this.angles;
546                 else
547                         target_angle = vectoangles(normalize(this.tur_aimpos - this.tur_shotorg));
548         }
549         else
550         {
551                 target_angle = vectoangles(normalize(this.tur_aimpos - this.tur_shotorg));
552         }
553
554         this.tur_head.angles_x = anglemods(this.tur_head.angles_x);
555         this.tur_head.angles_y = anglemods(this.tur_head.angles_y);
556
557         // Find the diffrence between where we currently aim and where we want to aim
558         //move_angle = target_angle - (this.angles + this.tur_head.angles);
559         //move_angle = shortangle_vxy(move_angle,(this.angles + this.tur_head.angles));
560
561         move_angle = AnglesTransform_ToAngles(AnglesTransform_LeftDivide(AnglesTransform_FromAngles(this.angles), AnglesTransform_FromAngles(target_angle))) - this.tur_head.angles;
562         move_angle = shortangle_vxy(move_angle, this.tur_head.angles);
563
564         switch(this.track_type)
565         {
566                 case TFL_TRACKTYPE_STEPMOTOR:
567                         f_tmp = this.aim_speed * this.ticrate; // dgr/sec -> dgr/tic
568                         if (this.track_flags & TFL_TRACK_PITCH)
569                         {
570                                 this.tur_head.angles_x += bound(-f_tmp,move_angle_x, f_tmp);
571                                 if(this.tur_head.angles_x > this.aim_maxpitch)
572                                         this.tur_head.angles_x = this.aim_maxpitch;
573
574                                 if(this.tur_head.angles_x  < -this.aim_maxpitch)
575                                         this.tur_head.angles_x = this.aim_maxpitch;
576                         }
577
578                         if (this.track_flags & TFL_TRACK_ROTATE)
579                         {
580                                 this.tur_head.angles_y += bound(-f_tmp, move_angle_y, f_tmp);
581                                 if(this.tur_head.angles_y > this.aim_maxrot)
582                                         this.tur_head.angles_y = this.aim_maxrot;
583
584                                 if(this.tur_head.angles_y  < -this.aim_maxrot)
585                                         this.tur_head.angles_y = this.aim_maxrot;
586                         }
587
588                         // CSQC
589                         this.SendFlags  |= TNSF_ANG;
590
591                         return;
592
593                 case TFL_TRACKTYPE_FLUIDINERTIA:
594                         f_tmp = this.aim_speed * this.ticrate; // dgr/sec -> dgr/tic
595                         move_angle_x = bound(-this.aim_speed, move_angle_x * this.track_accel_pitch * f_tmp, this.aim_speed);
596                         move_angle_y = bound(-this.aim_speed, move_angle_y * this.track_accel_rot * f_tmp, this.aim_speed);
597                         move_angle = (this.tur_head.avelocity * this.track_blendrate) + (move_angle * (1 - this.track_blendrate));
598                         break;
599
600                 case TFL_TRACKTYPE_FLUIDPRECISE:
601
602                         move_angle_y = bound(-this.aim_speed, move_angle_y, this.aim_speed);
603                         move_angle_x = bound(-this.aim_speed, move_angle_x, this.aim_speed);
604
605                         break;
606         }
607
608         //  pitch
609         if (this.track_flags & TFL_TRACK_PITCH)
610         {
611                 this.tur_head.avelocity_x = move_angle_x;
612                 if((this.tur_head.angles_x + this.tur_head.avelocity_x * this.ticrate) > this.aim_maxpitch)
613                 {
614                         this.tur_head.avelocity_x = 0;
615                         this.tur_head.angles_x = this.aim_maxpitch;
616
617                         this.SendFlags  |= TNSF_ANG;
618                 }
619
620                 if((this.tur_head.angles_x + this.tur_head.avelocity_x * this.ticrate) < -this.aim_maxpitch)
621                 {
622                         this.tur_head.avelocity_x = 0;
623                         this.tur_head.angles_x = -this.aim_maxpitch;
624
625                         this.SendFlags  |= TNSF_ANG;
626                 }
627         }
628
629         //  rot
630         if (this.track_flags & TFL_TRACK_ROTATE)
631         {
632                 this.tur_head.avelocity_y = move_angle_y;
633
634                 if((this.tur_head.angles_y + this.tur_head.avelocity_y * this.ticrate) > this.aim_maxrot)
635                 {
636                         this.tur_head.avelocity_y = 0;
637                         this.tur_head.angles_y = this.aim_maxrot;
638
639                         this.SendFlags  |= TNSF_ANG;
640                 }
641
642                 if((this.tur_head.angles_y + this.tur_head.avelocity_y * this.ticrate) < -this.aim_maxrot)
643                 {
644                         this.tur_head.avelocity_y = 0;
645                         this.tur_head.angles_y = -this.aim_maxrot;
646
647                         this.SendFlags  |= TNSF_ANG;
648                 }
649         }
650
651         this.SendFlags  |= TNSF_AVEL;
652
653         // Force a angle update every 10'th frame
654         this.turret_framecounter += 1;
655         if(this.turret_framecounter >= 10)
656         {
657                 this.SendFlags |= TNSF_ANG;
658                 this.turret_framecounter = 0;
659         }
660 }
661
662 /*
663  + TFL_TARGETSELECT_NO
664  + TFL_TARGETSELECT_LOS
665  + TFL_TARGETSELECT_PLAYERS
666  + TFL_TARGETSELECT_MISSILES
667  + TFL_TARGETSELECT_VEHICLES
668  - TFL_TARGETSELECT_TRIGGERTARGET
669  + TFL_TARGETSELECT_ANGLELIMITS
670  + TFL_TARGETSELECT_RANGELIMITS
671  + TFL_TARGETSELECT_TEAMCHECK
672  - TFL_TARGETSELECT_NOBUILTIN
673  + TFL_TARGETSELECT_OWNTEAM
674 */
675
676 /**
677 ** Evaluate a entity for target valitity based on validate_flags
678 ** NOTE: the caller must check takedamage before calling this, to inline this check.
679 **/
680 float turret_validate_target(entity e_turret, entity e_target, float validate_flags)
681 {
682         vector v_tmp;
683
684         //if(!validate_flags & TFL_TARGETSELECT_NOBUILTIN)
685         //      return -0.5;
686
687         if(!e_target)
688                 return -2;
689
690         if(e_target.owner == e_turret)
691                 return -0.5;
692
693         if(!checkpvs(e_target.origin, e_turret))
694                 return -1;
695
696         if(e_target.alpha != 0 && e_target.alpha <= 0.3)
697                 return -1;
698
699         if(MUTATOR_CALLHOOK(TurretValidateTarget, e_turret, e_target, validate_flags))
700                 return M_ARGV(3, float);
701
702         if (validate_flags & TFL_TARGETSELECT_NO)
703                 return -4;
704
705         // If only this was used more..
706         if (e_target.flags & FL_NOTARGET)
707                 return -5;
708
709         // Cant touch this
710         if (GetResource(e_target, RES_HEALTH) <= 0)
711                 return -6;
712         else if (STAT(FROZEN, e_target))
713                 return -6;
714
715         // vehicle
716         if(IS_VEHICLE(e_target))
717         {
718                 if ((validate_flags & TFL_TARGETSELECT_VEHICLES) && !e_target.owner)
719                         return -7;
720         }
721
722         // player
723         if (IS_CLIENT(e_target))
724         {
725                 if(!(validate_flags & TFL_TARGETSELECT_PLAYERS))
726                         return -7;
727
728                 if (IS_DEAD(e_target))
729                         return -8;
730         }
731
732         // enemy turrets
733         if(validate_flags & TFL_TARGETSELECT_NOTURRETS)
734         if(e_target.owner.tur_head == e_target)
735         if(e_target.team != e_turret.team) // Dont break support units.
736                 return -9;
737
738         // Missile
739         if (e_target.flags & FL_PROJECTILE)
740         if(!(validate_flags & TFL_TARGETSELECT_MISSILES))
741                 return -10;
742
743         if (validate_flags & TFL_TARGETSELECT_MISSILESONLY)
744         if(!(e_target.flags & FL_PROJECTILE))
745                 return -10.5;
746
747         // Team check
748         if (validate_flags & TFL_TARGETSELECT_TEAMCHECK)
749         {
750                 if (validate_flags & TFL_TARGETSELECT_OWNTEAM)
751                 {
752                         if (e_target.team != e_turret.team)
753                                 return -11;
754
755                         if (e_turret.team != e_target.owner.team)
756                                 return -12;
757
758                         if (e_turret.team != e_target.aiment.team)
759                                 return -12; // portals
760                 }
761                 else
762                 {
763                         if (e_target.team == e_turret.team)
764                                 return -13;
765
766                         if (e_turret.team == e_target.owner.team)
767                                 return -14;
768
769                         if (e_turret.team == e_target.aiment.team)
770                                 return -14; // portals
771                 }
772         }
773
774         // Range limits?
775         tvt_dist = vlen(e_turret.origin - real_origin(e_target));
776         if (validate_flags & TFL_TARGETSELECT_RANGELIMITS)
777         {
778                 if (tvt_dist < e_turret.target_range_min)
779                         return -15;
780
781                 if (tvt_dist > e_turret.target_range)
782                         return -16;
783         }
784
785         // Can we even aim this thing?
786         tvt_thadv = angleofs3(e_turret.tur_head.origin, e_turret.angles + e_turret.tur_head.angles, e_target.origin);
787         tvt_tadv = shortangle_vxy(angleofs(e_turret, e_target), e_turret.angles);
788         tvt_thadf = vlen(tvt_thadv);
789
790         /*
791         if(validate_flags & TFL_TARGETSELECT_FOV)
792         {
793                 if(e_turret.target_select_fov < tvt_thadf)
794                         return -21;
795         }
796         */
797
798         if (validate_flags & TFL_TARGETSELECT_ANGLELIMITS)
799         {
800                 if (fabs(tvt_tadv_x) > e_turret.aim_maxpitch)
801                         return -17;
802
803                 if (fabs(tvt_tadv_y) > e_turret.aim_maxrot)
804                         return -18;
805         }
806
807         // Line of sight?
808         if (validate_flags & TFL_TARGETSELECT_LOS)
809         {
810                 v_tmp = real_origin(e_target) + ((e_target.mins + e_target.maxs) * 0.5);
811
812                 traceline(e_turret.origin + '0 0 16', v_tmp, 0, e_turret);
813
814                 if(vdist(v_tmp - trace_endpos, >, e_turret.aim_firetolerance_dist))
815                         return -19;
816         }
817
818         if (e_target.classname == "grapplinghook")
819                 return -20;
820
821         /*
822         if (e_target.classname == "func_button")
823                 return -21;
824         */
825
826 #ifdef TURRET_DEBUG_TARGETSELECT
827         LOG_TRACE("Target:",e_target.netname," is a valid target for ",e_turret.netname);
828 #endif
829
830         return 1;
831 }
832
833 entity turret_select_target(entity this)
834 {
835         entity e;               // target looper entity
836         float  score;   // target looper entity score
837         entity e_enemy;  // currently best scoreing target
838         float  m_score;  // currently best scoreing target's score
839
840         m_score = 0;
841         if(this.enemy && this.enemy.takedamage && turret_validate_target(this,this.enemy,this.target_validate_flags) > 0)
842         {
843                 e_enemy = this.enemy;
844                 m_score = this.turret_score_target(this,e_enemy) * this.target_select_samebias;
845         }
846         else
847                 e_enemy = this.enemy = NULL;
848
849         e = findradius(this.origin, this.target_range);
850
851         // Nothing to aim at?
852         if (!e)
853                 return NULL;
854
855         while (e)
856         {
857                 if(e.takedamage)
858                 {
859                         float f = turret_validate_target(this, e, this.target_select_flags);
860                         //dprint("F is: ", ftos(f), "\n");
861                         if ( f > 0)
862                         {
863                                 score = this.turret_score_target(this,e);
864                                 if ((score > m_score) && (score > 0))
865                                 {
866                                         e_enemy = e;
867                                         m_score = score;
868                                 }
869                         }
870                 }
871                 e = e.chain;
872         }
873
874         return e_enemy;
875 }
876
877
878 /*
879  + = implemented
880  - = not implemented
881
882  + TFL_FIRECHECK_NO
883  + TFL_FIRECHECK_WORLD
884  + TFL_FIRECHECK_DEAD
885  + TFL_FIRECHECK_DISTANCES
886  - TFL_FIRECHECK_LOS
887  + TFL_FIRECHECK_AIMDIST
888  + TFL_FIRECHECK_REALDIST
889  - TFL_FIRECHECK_ANGLEDIST
890  - TFL_FIRECHECK_TEAMCECK
891  + TFL_FIRECHECK_AFF
892  + TFL_FIRECHECK_AMMO_OWN
893  + TFL_FIRECHECK_AMMO_OTHER
894  + TFL_FIRECHECK_REFIRE
895 */
896
897 /**
898 ** Preforms pre-fire checks based on the uints firecheck_flags
899 **/
900 bool turret_firecheck(entity this)
901 {
902         // This one just dont care =)
903         if (this.firecheck_flags & TFL_FIRECHECK_NO)
904                 return true;
905
906         if (this.enemy == NULL)
907                 return false;
908
909         // Ready?
910         if (this.firecheck_flags & TFL_FIRECHECK_REFIRE)
911                 if (this.attack_finished_single[0] > time) return false;
912
913         // Special case: volly fire turret that has to fire a full volly if a shot was fired.
914         if (this.shoot_flags & TFL_SHOOT_VOLLYALWAYS)
915                 if (this.volly_counter != this.shot_volly)
916                         if(this.ammo >= this.shot_dmg)
917                                 return true;
918
919         // Lack of zombies makes shooting dead things unnecessary :P
920         if (this.firecheck_flags & TFL_FIRECHECK_DEAD)
921                 if (IS_DEAD(this.enemy))
922                         return false;
923
924         // Own ammo?
925         if (this.firecheck_flags & TFL_FIRECHECK_AMMO_OWN)
926                 if (this.ammo < this.shot_dmg)
927                         return false;
928
929         // Other's ammo? (support-supply units)
930         if (this.firecheck_flags & TFL_FIRECHECK_AMMO_OTHER)
931                 if (this.enemy.ammo >= this.enemy.ammo_max)
932                         return false;
933
934         // Target of opertunity?
935         if(turret_validate_target(this, this.tur_impactent, this.target_validate_flags) > 0)
936         {
937                 this.enemy = this.tur_impactent;
938                 return true;
939         }
940
941         if (this.firecheck_flags & TFL_FIRECHECK_DISTANCES)
942         {
943                 // To close?
944                 if (this.tur_dist_aimpos < this.target_range_min)
945                 {
946                         if(turret_validate_target(this, this.tur_impactent, this.target_validate_flags) > 0)
947                                 return true; // Target of opertunity?
948                         return false;
949                 }
950         }
951
952         // Try to avoid FF?
953         if (this.firecheck_flags & TFL_FIRECHECK_AFF)
954                 if (this.tur_impactent.team == this.team)
955                         return false;
956
957         // aim<->predicted impact
958         if (this.firecheck_flags & TFL_FIRECHECK_AIMDIST)
959                 if (this.tur_dist_impact_to_aimpos > this.aim_firetolerance_dist)
960                         return false;
961
962         // Volly status
963         if (this.shot_volly > 1)
964                 if (this.volly_counter == this.shot_volly)
965                         if (this.ammo < (this.shot_dmg * this.shot_volly))
966                                 return false;
967
968         /*if(this.firecheck_flags & TFL_FIRECHECK_VERIFIED)
969                 if(this.tur_impactent != this.enemy)
970                         return false;*/
971
972         return true;
973 }
974
975 bool turret_checkfire(entity this)
976 {
977         if(MUTATOR_CALLHOOK(Turret_CheckFire, this))
978                 return M_ARGV(1, bool);
979
980         return this.turret_firecheckfunc(this);
981 }
982
983 void turret_fire(entity this)
984 {
985         if (autocvar_g_turrets_nofire != 0)
986                 return;
987
988         if(MUTATOR_CALLHOOK(TurretFire, this))
989                 return;
990
991         Turret info = get_turretinfo(this.m_id);
992         info.tr_attack(info, this);
993
994         this.attack_finished_single[0] = time + this.shot_refire;
995         this.ammo -= this.shot_dmg;
996         this.volly_counter = this.volly_counter - 1;
997
998         if (this.volly_counter <= 0)
999         {
1000                 this.volly_counter = this.shot_volly;
1001
1002                 if (this.shoot_flags & TFL_SHOOT_CLEARTARGET)
1003                         this.enemy = NULL;
1004
1005                 if (this.shot_volly > 1)
1006                         this.attack_finished_single[0] = time + this.shot_volly_refire;
1007         }
1008
1009 #ifdef TURRET_DEBUG
1010         if (this.enemy) paint_target3(this.tur_aimpos, 64, this.tur_debug_rvec, this.tur_impacttime + 0.25);
1011 #endif
1012 }
1013
1014 void turret_think(entity this)
1015 {
1016         this.nextthink = time + this.ticrate;
1017
1018         MUTATOR_CALLHOOK(TurretThink, this);
1019
1020 #ifdef TURRET_DEBUG
1021         if (this.tur_debug_tmr1 < time)
1022         {
1023                 if (this.enemy) paint_target (this.enemy,128,this.tur_debug_rvec,0.9);
1024                 paint_target(this,256,this.tur_debug_rvec,0.9);
1025                 this.tur_debug_tmr1 = time + 1;
1026         }
1027 #endif
1028
1029         // Handle ammo
1030         if (!(this.spawnflags & TSF_NO_AMMO_REGEN))
1031         if (this.ammo < this.ammo_max)
1032                 this.ammo = min(this.ammo + this.ammo_recharge, this.ammo_max);
1033
1034         // Inactive turrets needs to run the think loop,
1035         // So they can handle animation and wake up if need be.
1036         if(!this.active)
1037         {
1038                 turret_track(this);
1039                 return;
1040         }
1041
1042         // This is typicaly used for zaping every target in range
1043         // turret_fusionreactor uses this to recharge friendlys.
1044         if (this.shoot_flags & TFL_SHOOT_HITALLVALID)
1045         {
1046                 // Do a this.turret_fire for every valid target.
1047                 entity e = findradius(this.origin,this.target_range);
1048                 while (e)
1049                 {
1050                         if(e.takedamage)
1051                         {
1052                                 if (turret_validate_target(this,e,this.target_validate_flags))
1053                                 {
1054                                         this.enemy = e;
1055
1056                                         turret_do_updates(this);
1057
1058                                         if (turret_checkfire(this))
1059                                                 turret_fire(this);
1060                                 }
1061                         }
1062
1063                         e = e.chain;
1064                 }
1065                 this.enemy = NULL;
1066         }
1067         else if(this.shoot_flags & TFL_SHOOT_CUSTOM)
1068         {
1069                 // This one is doing something.. oddball. assume its handles what needs to be handled.
1070
1071                 // Predict?
1072                 if(!(this.aim_flags & TFL_AIM_NO))
1073                         this.tur_aimpos = turret_aim_generic(this);
1074
1075                 // Turn & pitch?
1076                 if(!(this.track_flags & TFL_TRACK_NO))
1077                         turret_track(this);
1078
1079                 turret_do_updates(this);
1080
1081                 // Fire?
1082                 if (turret_checkfire(this))
1083                         turret_fire(this);
1084         }
1085         else
1086         {
1087                 // Special case for volly always. if it fired once it must compleate the volly.
1088                 if(this.shoot_flags & TFL_SHOOT_VOLLYALWAYS)
1089                         if(this.volly_counter != this.shot_volly)
1090                         {
1091                                 // Predict or whatnot
1092                                 if(!(this.aim_flags & TFL_AIM_NO))
1093                                         this.tur_aimpos = turret_aim_generic(this);
1094
1095                                 // Turn & pitch
1096                                 if(!(this.track_flags & TFL_TRACK_NO))
1097                                         turret_track(this);
1098
1099                                 turret_do_updates(this);
1100
1101                                 // Fire!
1102                                 if (turret_checkfire(this))
1103                                         turret_fire(this);
1104
1105                                 Turret tur = get_turretinfo(this.m_id);
1106                                 tur.tr_think(tur, this);
1107
1108                                 return;
1109                         }
1110
1111                 // Check if we have a vailid enemy, and try to find one if we dont.
1112
1113                 // g_turrets_targetscan_maxdelay forces a target re-scan at least this often
1114                 float do_target_scan = 0;
1115                 if((this.target_select_time + autocvar_g_turrets_targetscan_maxdelay) < time)
1116                         do_target_scan = 1;
1117
1118                 // Old target (if any) invalid?
1119                 if(this.target_validate_time < time)
1120                 if (turret_validate_target(this, this.enemy, this.target_validate_flags) <= 0)
1121                 {
1122                         this.enemy = NULL;
1123                         this.target_validate_time = time + 0.5;
1124                         do_target_scan = 1;
1125                 }
1126
1127                 // But never more often then g_turrets_targetscan_mindelay!
1128                 if (this.target_select_time + autocvar_g_turrets_targetscan_mindelay > time)
1129                         do_target_scan = 0;
1130
1131                 if(do_target_scan)
1132                 {
1133                         this.enemy = turret_select_target(this);
1134                         this.target_select_time = time;
1135                 }
1136
1137                 // No target, just go to idle, do any custom stuff and bail.
1138                 if (this.enemy == NULL)
1139                 {
1140                         // Turn & pitch
1141                         if(!(this.track_flags & TFL_TRACK_NO))
1142                                 turret_track(this);
1143
1144                         Turret tur = get_turretinfo(this.m_id);
1145                         tur.tr_think(tur, this);
1146
1147                         // And bail.
1148                         return;
1149                 }
1150                 else
1151                         this.lip = time + autocvar_g_turrets_aimidle_delay; // Keep track of the last time we had a target.
1152
1153                 // Predict?
1154                 if(!(this.aim_flags & TFL_AIM_NO))
1155                         this.tur_aimpos = turret_aim_generic(this);
1156
1157                 // Turn & pitch?
1158                 if(!(this.track_flags & TFL_TRACK_NO))
1159                         turret_track(this);
1160
1161                 turret_do_updates(this);
1162
1163                 // Fire?
1164                 if (turret_checkfire(this))
1165                         turret_fire(this);
1166         }
1167
1168         Turret tur = get_turretinfo(this.m_id);
1169         tur.tr_think(tur, this);
1170 }
1171
1172 /*
1173         When .used a turret switch team to activator.team.
1174         If activator is NULL, the turret go inactive.
1175 */
1176 void turret_use(entity this, entity actor, entity trigger)
1177 {
1178         LOG_TRACE("Turret ",this.netname, " used by ", actor.classname);
1179
1180         this.team = actor.team;
1181
1182         if(this.team == 0)
1183                 this.active = ACTIVE_NOT;
1184         else
1185                 this.active = ACTIVE_ACTIVE;
1186
1187 }
1188
1189 void turret_link(entity this)
1190 {
1191         Net_LinkEntity(this, true, 0, turret_send);
1192         setthink(this, turret_think);
1193         this.nextthink = time;
1194         this.tur_head.effects = EF_NODRAW;
1195 }
1196
1197 void turrets_manager_think(entity this)
1198 {
1199         this.nextthink = time + 1;
1200
1201         if (autocvar_g_turrets_reloadcvars == 1)
1202         {
1203                 IL_EACH(g_turrets, true,
1204                 {
1205                         load_unit_settings(it, true);
1206                         Turret tur = get_turretinfo(it.m_id);
1207                         tur.tr_think(tur, it);
1208                 });
1209                 cvar_set("g_turrets_reloadcvars", "0");
1210         }
1211 }
1212
1213 void turret_initparams(entity tur)
1214 {
1215         #define TRY(x) (x) ? (x)
1216         tur.respawntime                 = max  (-1,              (TRY(tur.respawntime)               :  60                                         ));
1217         tur.shot_refire                 = bound(0.01,            (TRY(tur.shot_refire)               :  1                                          ), 9999);
1218         tur.shot_dmg                    = max  (1,               (TRY(tur.shot_dmg)                  :  tur.shot_refire * 50                       ));
1219         tur.shot_radius                 = max  (1,               (TRY(tur.shot_radius)               :  tur.shot_dmg * 0.5                         ));
1220         tur.shot_speed                  = max  (1,               (TRY(tur.shot_speed)                :  2500                                       ));
1221         tur.shot_spread                 = bound(0.0001,          (TRY(tur.shot_spread)               :  0.0125                                     ), 500);
1222         tur.shot_force                  = bound(0.001,           (TRY(tur.shot_force)                :  tur.shot_dmg * 0.5 + tur.shot_radius * 0.5 ), 5000);
1223         tur.shot_volly                  = bound(1,               (TRY(tur.shot_volly)                :  1                                          ), floor(tur.ammo_max / tur.shot_dmg));
1224         tur.shot_volly_refire           = bound(tur.shot_refire, (TRY(tur.shot_volly_refire)         :  tur.shot_refire * tur.shot_volly           ), 60);
1225         tur.target_range                = bound(0,               (TRY(tur.target_range)              :  tur.shot_speed * 0.5                       ), max_shot_distance);
1226         tur.target_range_min            = bound(0,               (TRY(tur.target_range_min)          :  tur.shot_radius * 2                        ), max_shot_distance);
1227         tur.target_range_optimal        = bound(0,               (TRY(tur.target_range_optimal)      :  tur.target_range * 0.5                     ), max_shot_distance);
1228         tur.aim_maxrot                  = bound(0,               (TRY(tur.aim_maxrot)                :  90                                         ), 360);
1229         tur.aim_maxpitch                = bound(0,               (TRY(tur.aim_maxpitch)              :  20                                         ), 90);
1230         tur.aim_speed                   = bound(0.1,             (TRY(tur.aim_speed)                 :  36                                         ), 1000);
1231         tur.aim_firetolerance_dist      = bound(0.1,             (TRY(tur.aim_firetolerance_dist)    :  5 + (tur.shot_radius * 2)                  ), max_shot_distance);
1232         tur.target_select_rangebias     = bound(-10,             (TRY(tur.target_select_rangebias)   :  1                                          ), 10);
1233         tur.target_select_samebias      = bound(-10,             (TRY(tur.target_select_samebias)    :  1                                          ), 10);
1234         tur.target_select_anglebias     = bound(-10,             (TRY(tur.target_select_anglebias)   :  1                                          ), 10);
1235         tur.target_select_missilebias   = bound(-10,             (TRY(tur.target_select_missilebias) :  1                                          ), 10);
1236         tur.target_select_playerbias    = bound(-10,             (TRY(tur.target_select_playerbias)  :  1                                          ), 10);
1237         tur.ammo_max                    = max  (tur.shot_dmg,    (TRY(tur.ammo_max)                  :  tur.shot_dmg * 10                          ));
1238         tur.ammo_recharge               = max  (0,               (TRY(tur.ammo_recharge)             :  tur.shot_dmg * 0.5                         ));
1239         #undef TRY
1240 }
1241
1242 bool turret_closetotarget(entity this, vector targ)
1243 {
1244         vector path_extra_size = '64 64 64';
1245         return boxesoverlap(targ - path_extra_size, targ + path_extra_size, this.absmin - path_extra_size, this.absmax + path_extra_size);
1246 }
1247
1248 void turret_findtarget(entity this)
1249 {
1250         entity e = find(NULL, classname, "turret_manager");
1251         if(!e)
1252         {
1253                 e = new(turret_manager);
1254                 setthink(e, turrets_manager_think);
1255                 e.nextthink = time + 2;
1256         }
1257
1258         entity targ = find(NULL, targetname, this.target);
1259         if(targ.classname == "turret_checkpoint")
1260                 return; // turrets don't defend checkpoints?
1261
1262         if (!targ)
1263         {
1264                 this.target = "";
1265                 LOG_TRACE("Turret has invalid defendpoint!");
1266         }
1267
1268         this.tur_defend = targ;
1269         this.idle_aim = this.tur_head.angles + angleofs(this.tur_head, targ);
1270 }
1271
1272 void turret_reset(entity this)
1273 {
1274         turret_respawn(this);
1275 }
1276
1277 bool turret_initialize(entity this, Turret tur)
1278 {
1279         if(!autocvar_g_turrets)
1280                 return false;
1281
1282         if(tur.m_id == 0)
1283                 return false; // invalid turret
1284
1285         // if tur_head exists, we can assume this turret re-spawned
1286         if(!this.tur_head) {
1287                 tur.tr_precache(tur);
1288                 IL_PUSH(g_turrets, this);
1289                 IL_PUSH(g_bot_targets, this);
1290         }
1291
1292         if(!(this.spawnflags & TSF_SUSPENDED))
1293                 droptofloor(this);
1294
1295         this.netname = tur.netname;
1296         load_unit_settings(this, 0);
1297
1298         if(!this.team || !teamplay)             { this.team = FLOAT_MAX; }
1299         if(!this.ticrate)                               { this.ticrate = ((this.turret_flags & TUR_FLAG_SUPPORT) ? 0.2 : 0.1); }
1300         if(!GetResource(this, RES_HEALTH)) { SetResourceExplicit(this, RES_HEALTH, 1000); }
1301         if(!this.shot_refire)                   { this.shot_refire = 1; }
1302         if(!this.tur_shotorg)                   { this.tur_shotorg = '50 0 50'; }
1303         if(!this.turret_flags)                  { this.turret_flags = TUR_FLAG_SPLASH | TUR_FLAG_MEDPROJ | TUR_FLAG_PLAYER; }
1304         if(!this.damage_flags)                  { this.damage_flags = TFL_DMG_YES | TFL_DMG_RETALIATE | TFL_DMG_AIMSHAKE; }
1305         if(!this.aim_flags)                             { this.aim_flags = TFL_AIM_LEAD | TFL_AIM_SHOTTIMECOMPENSATE; }
1306         if(!this.track_type)                    { this.track_type = TFL_TRACKTYPE_STEPMOTOR; }
1307         if(!this.track_flags)                   { this.track_flags = TFL_TRACK_PITCH | TFL_TRACK_ROTATE; }
1308         if(!this.ammo_flags)                    { this.ammo_flags = TFL_AMMO_ENERGY | TFL_AMMO_RECHARGE; }
1309         if(!this.target_select_flags)   { this.target_select_flags = TFL_TARGETSELECT_LOS | TFL_TARGETSELECT_TEAMCHECK | TFL_TARGETSELECT_RANGELIMITS | TFL_TARGETSELECT_ANGLELIMITS; }
1310         if(!this.firecheck_flags)               { this.firecheck_flags = TFL_FIRECHECK_DEAD | TFL_FIRECHECK_DISTANCES | TFL_FIRECHECK_LOS
1311                                                                                                                    | TFL_FIRECHECK_AIMDIST | TFL_FIRECHECK_TEAMCHECK | TFL_FIRECHECK_AMMO_OWN | TFL_FIRECHECK_REFIRE; }
1312
1313         if(this.track_type != TFL_TRACKTYPE_STEPMOTOR)
1314         {
1315                 // Fluid / Ineria mode. Looks mutch nicer.
1316                 // Can reduce aim preformance alot, needs a bit diffrent aimspeed
1317
1318                 this.aim_speed = bound(0.1, ((!this.aim_speed) ? 180 : this.aim_speed), 1000);
1319
1320                 if(!this.track_accel_pitch)             { this.track_accel_pitch = 0.5; }
1321                 if(!this.track_accel_rot)               { this.track_accel_rot = 0.5; }
1322                 if(!this.track_blendrate)               { this.track_blendrate = 0.35; }
1323         }
1324
1325         turret_initparams(this);
1326
1327         this.turret_flags = TUR_FLAG_ISTURRET | (tur.spawnflags);
1328
1329         if(this.turret_flags & TUR_FLAG_SPLASH)
1330                 this.aim_flags |= TFL_AIM_SPLASH;
1331
1332         if(this.turret_flags & TUR_FLAG_MISSILE)
1333                 this.target_select_flags |= TFL_TARGETSELECT_MISSILES;
1334
1335         if(this.turret_flags & TUR_FLAG_PLAYER)
1336                 this.target_select_flags |= TFL_TARGETSELECT_PLAYERS;
1337
1338         if(this.spawnflags & TSL_NO_RESPAWN)
1339                 this.damage_flags |= TFL_DMG_DEATH_NORESPAWN;
1340
1341         if (this.turret_flags & TUR_FLAG_SUPPORT)
1342                 this.turret_score_target = turret_targetscore_support;
1343         else
1344                 this.turret_score_target = turret_targetscore_generic;
1345
1346         ++turret_count;
1347
1348         _setmodel(this, tur.model);
1349         setsize(this, tur.m_mins, tur.m_maxs);
1350
1351         this.m_id                                       = tur.m_id;
1352         this.active                                     = ACTIVE_ACTIVE;
1353         this.effects                            = EF_NODRAW;
1354         this.netname                            = tur.turret_name;
1355         this.ticrate                            = bound(sys_frametime, this.ticrate, 60);
1356         this.max_health                         = GetResource(this, RES_HEALTH);
1357         this.target_validate_flags      = this.target_select_flags;
1358         this.ammo                                       = this.ammo_max;
1359         this.ammo_recharge                 *= this.ticrate;
1360         this.solid                                      = SOLID_BBOX;
1361         this.takedamage                         = DAMAGE_AIM;
1362         set_movetype(this, MOVETYPE_NOCLIP);
1363         this.view_ofs                           = '0 0 0';
1364         this.idle_aim                           = '0 0 0';
1365         this.turret_firecheckfunc       = turret_firecheck;
1366         this.event_damage                       = turret_damage;
1367         this.event_heal                         = turret_heal;
1368         this.use                                        = turret_use;
1369         this.bot_attack                         = true;
1370         this.nextthink                          = time + 1 + turret_count * sys_frametime;
1371         this.reset                                      = turret_reset;
1372
1373         this.tur_head = new(turret_head);
1374         _setmodel(this.tur_head, tur.head_model);
1375         setsize(this.tur_head, '0 0 0', '0 0 0');
1376         setorigin(this.tur_head, '0 0 0');
1377         setattachment(this.tur_head, this, "tag_head");
1378
1379         this.tur_head.netname           = this.tur_head.classname;
1380         this.tur_head.team                      = this.team;
1381         this.tur_head.owner                     = this;
1382         this.tur_head.takedamage        = DAMAGE_NO;
1383         this.tur_head.solid                     = SOLID_NOT;
1384         set_movetype(this.tur_head, this.move_movetype);
1385
1386         this.weaponentities[0] = this; // lol
1387
1388         if(!this.tur_defend && this.target != "")
1389                 InitializeEntity(this, turret_findtarget, INITPRIO_FINDTARGET);
1390
1391 #ifdef TURRET_DEBUG
1392         this.tur_debug_start = this.nextthink;
1393         while(vdist(this.tur_debug_rvec, <, 2))
1394                 this.tur_debug_rvec = randomvec() * 4;
1395
1396         this.tur_debug_rvec_x = fabs(this.tur_debug_rvec_x);
1397         this.tur_debug_rvec_y = fabs(this.tur_debug_rvec_y);
1398         this.tur_debug_rvec_z = fabs(this.tur_debug_rvec_z);
1399 #endif
1400
1401         turret_link(this);
1402         turret_respawn(this);
1403         turret_tag_fire_update(this);
1404
1405         tur.tr_setup(tur, this);
1406
1407         if(MUTATOR_CALLHOOK(TurretSpawn, this))
1408                 return false;
1409
1410         return true;
1411 }
1412 #endif