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