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