Merge branch 'master' into terencehill/itemstime
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / weapons / weaponsystem.qc
1 #include "weaponsystem.qh"
2 #include "../_all.qh"
3
4 #include "selection.qh"
5
6 #include "../command/common.qh"
7 #include "../mutators/mutators_include.qh"
8 #include "../round_handler.qh"
9 #include "../t_items.qh"
10 #include "../../common/animdecide.qh"
11 #include "../../common/constants.qh"
12 #include "../../common/monsters/all.qh"
13 #include "../../common/notifications.qh"
14 #include "../../common/util.qh"
15 #include "../../common/weapons/all.qh"
16 #include "../../csqcmodellib/sv_model.qh"
17
18 /*
19 ===========================================================================
20
21   CLIENT WEAPONSYSTEM CODE
22   Bring back W_Weaponframe
23
24 ===========================================================================
25 */
26
27 .float weapon_frametime;
28
29 float W_WeaponRateFactor()
30 {
31         float t;
32         t = 1.0 / g_weaponratefactor;
33
34         weapon_rate = t;
35         MUTATOR_CALLHOOK(WeaponRateFactor);
36         t = weapon_rate;
37
38         return t;
39 }
40
41
42 void(float fr, float t, void() func) weapon_thinkf;
43
44 float CL_Weaponentity_CustomizeEntityForClient()
45 {
46         self.viewmodelforclient = self.owner;
47         if(IS_SPEC(other))
48                 if(other.enemy == self.owner)
49                         self.viewmodelforclient = other;
50         return true;
51 }
52
53 /*
54  * supported formats:
55  *
56  * 1. simple animated model, muzzle flash handling on h_ model:
57  *    h_tuba.dpm, h_tuba.dpm.framegroups - invisible model controlling the animation
58  *      tags:
59  *        shot = muzzle end (shot origin, also used for muzzle flashes)
60  *        shell = casings ejection point (must be on the right hand side of the gun)
61  *        weapon = attachment for v_tuba.md3
62  *    v_tuba.md3 - first and third person model
63  *    g_tuba.md3 - pickup model
64  *
65  * 2. simple animated model, muzzle flash handling on v_ model:
66  *    h_tuba.dpm, h_tuba.dpm.framegroups - invisible model controlling the animation
67  *      tags:
68  *        weapon = attachment for v_tuba.md3
69  *    v_tuba.md3 - first and third person model
70  *      tags:
71  *        shot = muzzle end (shot origin, also used for muzzle flashes)
72  *        shell = casings ejection point (must be on the right hand side of the gun)
73  *    g_tuba.md3 - pickup model
74  *
75  * 3. fully animated model, muzzle flash handling on h_ model:
76  *    h_tuba.dpm, h_tuba.dpm.framegroups - animated first person model
77  *      tags:
78  *        shot = muzzle end (shot origin, also used for muzzle flashes)
79  *        shell = casings ejection point (must be on the right hand side of the gun)
80  *        handle = corresponding to the origin of v_tuba.md3 (used for muzzle flashes)
81  *    v_tuba.md3 - third person model
82  *    g_tuba.md3 - pickup model
83  *
84  * 4. fully animated model, muzzle flash handling on v_ model:
85  *    h_tuba.dpm, h_tuba.dpm.framegroups - animated first person model
86  *      tags:
87  *        shot = muzzle end (shot origin)
88  *        shell = casings ejection point (must be on the right hand side of the gun)
89  *    v_tuba.md3 - third person model
90  *      tags:
91  *        shot = muzzle end (for muzzle flashes)
92  *    g_tuba.md3 - pickup model
93  */
94
95 // writes:
96 //   self.origin, self.angles
97 //   self.weaponentity
98 //   self.movedir, self.view_ofs
99 //   attachment stuff
100 //   anim stuff
101 // to free:
102 //   call again with ""
103 //   remove the ent
104 void CL_WeaponEntity_SetModel(string name)
105 {
106         float v_shot_idx;
107         if (name != "")
108         {
109                 // if there is a child entity, hide it until we're sure we use it
110                 if (self.weaponentity)
111                         self.weaponentity.model = "";
112                 setmodel(self, strcat("models/weapons/v_", name, ".md3")); // precision set below
113                 v_shot_idx = gettagindex(self, "shot"); // used later
114                 if(!v_shot_idx)
115                         v_shot_idx = gettagindex(self, "tag_shot");
116
117                 setmodel(self, strcat("models/weapons/h_", name, ".iqm")); // precision set below
118                 // preset some defaults that work great for renamed zym files (which don't need an animinfo)
119                 self.anim_fire1  = animfixfps(self, '0 1 0.01', '0 0 0');
120                 self.anim_fire2  = animfixfps(self, '1 1 0.01', '0 0 0');
121                 self.anim_idle   = animfixfps(self, '2 1 0.01', '0 0 0');
122                 self.anim_reload = animfixfps(self, '3 1 0.01', '0 0 0');
123
124                 // if we have a "weapon" tag, let's attach the v_ model to it ("invisible hand" style model)
125                 // if we don't, this is a "real" animated model
126                 if(gettagindex(self, "weapon"))
127                 {
128                         if (!self.weaponentity)
129                                 self.weaponentity = spawn();
130                         setmodel(self.weaponentity, strcat("models/weapons/v_", name, ".md3")); // precision does not matter
131                         setattachment(self.weaponentity, self, "weapon");
132                 }
133                 else if(gettagindex(self, "tag_weapon"))
134                 {
135                         if (!self.weaponentity)
136                                 self.weaponentity = spawn();
137                         setmodel(self.weaponentity, strcat("models/weapons/v_", name, ".md3")); // precision does not matter
138                         setattachment(self.weaponentity, self, "tag_weapon");
139                 }
140                 else
141                 {
142                         if(self.weaponentity)
143                                 remove(self.weaponentity);
144                         self.weaponentity = world;
145                 }
146
147                 setorigin(self,'0 0 0');
148                 self.angles = '0 0 0';
149                 self.frame = 0;
150                 self.viewmodelforclient = world;
151
152                 float idx;
153
154                 if(v_shot_idx) // v_ model attached to invisible h_ model
155                 {
156                         self.movedir = gettaginfo(self.weaponentity, v_shot_idx);
157                 }
158                 else
159                 {
160                         idx = gettagindex(self, "shot");
161                         if(!idx)
162                                 idx = gettagindex(self, "tag_shot");
163                         if(idx)
164                                 self.movedir = gettaginfo(self, idx);
165                         else
166                         {
167                                 print("WARNING: weapon model ", self.model, " does not support the 'shot' tag, will display shots TOTALLY wrong\n");
168                                 self.movedir = '0 0 0';
169                         }
170                 }
171
172                 if(self.weaponentity) // v_ model attached to invisible h_ model
173                 {
174                         idx = gettagindex(self.weaponentity, "shell");
175                         if(!idx)
176                                 idx = gettagindex(self.weaponentity, "tag_shell");
177                         if(idx)
178                                 self.spawnorigin = gettaginfo(self.weaponentity, idx);
179                 }
180                 else
181                         idx = 0;
182                 if(!idx)
183                 {
184                         idx = gettagindex(self, "shell");
185                         if(!idx)
186                                 idx = gettagindex(self, "tag_shell");
187                         if(idx)
188                                 self.spawnorigin = gettaginfo(self, idx);
189                         else
190                         {
191                                 print("WARNING: weapon model ", self.model, " does not support the 'shell' tag, will display casings wrong\n");
192                                 self.spawnorigin = self.movedir;
193                         }
194                 }
195
196                 if(v_shot_idx)
197                 {
198                         self.oldorigin = '0 0 0'; // use regular attachment
199                 }
200                 else
201                 {
202                         if(self.weaponentity)
203                         {
204                                 idx = gettagindex(self, "weapon");
205                                 if(!idx)
206                                         idx = gettagindex(self, "tag_weapon");
207                         }
208                         else
209                         {
210                                 idx = gettagindex(self, "handle");
211                                 if(!idx)
212                                         idx = gettagindex(self, "tag_handle");
213                         }
214                         if(idx)
215                         {
216                                 self.oldorigin = self.movedir - gettaginfo(self, idx);
217                         }
218                         else
219                         {
220                                 print("WARNING: weapon model ", self.model, " does not support the 'handle' tag and neither does the v_ model support the 'shot' tag, will display muzzle flashes TOTALLY wrong\n");
221                                 self.oldorigin = '0 0 0'; // there is no way to recover from this
222                         }
223                 }
224
225                 self.viewmodelforclient = self.owner;
226         }
227         else
228         {
229                 self.model = "";
230                 if(self.weaponentity)
231                         remove(self.weaponentity);
232                 self.weaponentity = world;
233                 self.movedir = '0 0 0';
234                 self.spawnorigin = '0 0 0';
235                 self.oldorigin = '0 0 0';
236                 self.anim_fire1  = '0 1 0.01';
237                 self.anim_fire2  = '0 1 0.01';
238                 self.anim_idle   = '0 1 0.01';
239                 self.anim_reload = '0 1 0.01';
240         }
241
242         self.view_ofs = '0 0 0';
243
244         if(self.movedir.x >= 0)
245         {
246                 vector v0;
247                 v0 = self.movedir;
248                 self.movedir = shotorg_adjust(v0, false, false);
249                 self.view_ofs = shotorg_adjust(v0, false, true) - v0;
250         }
251         self.owner.stat_shotorg = compressShotOrigin(self.movedir);
252         self.movedir = decompressShotOrigin(self.owner.stat_shotorg); // make them match perfectly
253
254         self.spawnorigin += self.view_ofs; // offset the casings origin by the same amount
255
256         // check if an instant weapon switch occurred
257         setorigin(self, self.view_ofs);
258         // reset animstate now
259         self.wframe = WFRAME_IDLE;
260         setanim(self, self.anim_idle, true, false, true);
261 }
262
263 vector CL_Weapon_GetShotOrg(float wpn)
264 {
265         entity wi, oldself;
266         vector ret;
267         wi = get_weaponinfo(wpn);
268         oldself = self;
269         self = spawn();
270         CL_WeaponEntity_SetModel(wi.mdl);
271         ret = self.movedir;
272         CL_WeaponEntity_SetModel("");
273         remove(self);
274         self = oldself;
275         return ret;
276 }
277
278 void CL_Weaponentity_Think()
279 {
280         int tb;
281         self.nextthink = time;
282         if (intermission_running)
283                 self.frame = self.anim_idle.x;
284         if (self.owner.weaponentity != self)
285         {
286                 if (self.weaponentity)
287                         remove(self.weaponentity);
288                 remove(self);
289                 return;
290         }
291         if (self.owner.deadflag != DEAD_NO)
292         {
293                 self.model = "";
294                 if (self.weaponentity)
295                         self.weaponentity.model = "";
296                 return;
297         }
298         if (self.weaponname != self.owner.weaponname || self.dmg != self.owner.modelindex || self.deadflag != self.owner.deadflag)
299         {
300                 self.weaponname = self.owner.weaponname;
301                 self.dmg = self.owner.modelindex;
302                 self.deadflag = self.owner.deadflag;
303
304                 CL_WeaponEntity_SetModel(self.owner.weaponname);
305         }
306
307         tb = (self.effects & (EF_TELEPORT_BIT | EF_RESTARTANIM_BIT));
308         self.effects = self.owner.effects & EFMASK_CHEAP;
309         self.effects &= ~EF_LOWPRECISION;
310         self.effects &= ~EF_FULLBRIGHT; // can mask team color, so get rid of it
311         self.effects &= ~EF_TELEPORT_BIT;
312         self.effects &= ~EF_RESTARTANIM_BIT;
313         self.effects |= tb;
314
315         if(self.owner.alpha == default_player_alpha)
316                 self.alpha = default_weapon_alpha;
317         else if(self.owner.alpha != 0)
318                 self.alpha = self.owner.alpha;
319         else
320                 self.alpha = 1;
321
322         self.glowmod = self.owner.weaponentity_glowmod;
323         self.colormap = self.owner.colormap;
324         if (self.weaponentity)
325         {
326                 self.weaponentity.effects = self.effects;
327                 self.weaponentity.alpha = self.alpha;
328                 self.weaponentity.colormap = self.colormap;
329                 self.weaponentity.glowmod = self.glowmod;
330         }
331
332         self.angles = '0 0 0';
333
334         float f = (self.owner.weapon_nextthink - time);
335         if (self.state == WS_RAISE && !intermission_running)
336         {
337                 entity newwep = get_weaponinfo(self.owner.switchweapon);
338                 f = f * g_weaponratefactor / max(f, newwep.switchdelay_raise);
339                 self.angles_x = -90 * f * f;
340         }
341         else if (self.state == WS_DROP && !intermission_running)
342         {
343                 entity oldwep = get_weaponinfo(self.owner.weapon);
344                 f = 1 - f * g_weaponratefactor / max(f, oldwep.switchdelay_drop);
345                 self.angles_x = -90 * f * f;
346         }
347         else if (self.state == WS_CLEAR)
348         {
349                 f = 1;
350                 self.angles_x = -90 * f * f;
351         }
352 }
353
354 void CL_ExteriorWeaponentity_Think()
355 {
356         float tag_found;
357         self.nextthink = time;
358         if (self.owner.exteriorweaponentity != self)
359         {
360                 remove(self);
361                 return;
362         }
363         if (self.owner.deadflag != DEAD_NO)
364         {
365                 self.model = "";
366                 return;
367         }
368         if (self.weaponname != self.owner.weaponname || self.dmg != self.owner.modelindex || self.deadflag != self.owner.deadflag)
369         {
370                 self.weaponname = self.owner.weaponname;
371                 self.dmg = self.owner.modelindex;
372                 self.deadflag = self.owner.deadflag;
373                 if (self.owner.weaponname != "")
374                         setmodel(self, strcat("models/weapons/v_", self.owner.weaponname, ".md3")); // precision set below
375                 else
376                         self.model = "";
377
378                 if((tag_found = gettagindex(self.owner, "tag_weapon")))
379                 {
380                         self.tag_index = tag_found;
381                         self.tag_entity = self.owner;
382                 }
383                 else
384                         setattachment(self, self.owner, "bip01 r hand");
385         }
386         self.effects = self.owner.effects;
387         self.effects |= EF_LOWPRECISION;
388         self.effects = self.effects & EFMASK_CHEAP; // eat performance
389         if(self.owner.alpha == default_player_alpha)
390                 self.alpha = default_weapon_alpha;
391         else if(self.owner.alpha != 0)
392                 self.alpha = self.owner.alpha;
393         else
394                 self.alpha = 1;
395
396         self.glowmod = self.owner.weaponentity_glowmod;
397         self.colormap = self.owner.colormap;
398
399         CSQCMODEL_AUTOUPDATE();
400 }
401
402 // spawning weaponentity for client
403 void CL_SpawnWeaponentity()
404 {
405         self.weaponentity = spawn();
406         self.weaponentity.classname = "weaponentity";
407         self.weaponentity.solid = SOLID_NOT;
408         self.weaponentity.owner = self;
409         setmodel(self.weaponentity, ""); // precision set when changed
410         setorigin(self.weaponentity, '0 0 0');
411         self.weaponentity.angles = '0 0 0';
412         self.weaponentity.viewmodelforclient = self;
413         self.weaponentity.flags = 0;
414         self.weaponentity.think = CL_Weaponentity_Think;
415         self.weaponentity.customizeentityforclient = CL_Weaponentity_CustomizeEntityForClient;
416         self.weaponentity.nextthink = time;
417
418         self.exteriorweaponentity = spawn();
419         self.exteriorweaponentity.classname = "exteriorweaponentity";
420         self.exteriorweaponentity.solid = SOLID_NOT;
421         self.exteriorweaponentity.exteriorweaponentity = self.exteriorweaponentity;
422         self.exteriorweaponentity.owner = self;
423         setorigin(self.exteriorweaponentity, '0 0 0');
424         self.exteriorweaponentity.angles = '0 0 0';
425         self.exteriorweaponentity.think = CL_ExteriorWeaponentity_Think;
426         self.exteriorweaponentity.nextthink = time;
427
428         {
429                 entity oldself = self;
430                 self = self.exteriorweaponentity;
431                 CSQCMODEL_AUTOINIT();
432                 self = oldself;
433         }
434 }
435
436 // Weapon subs
437 void w_clear()
438 {
439         if (self.weapon != -1)
440         {
441                 self.weapon = 0;
442                 self.switchingweapon = 0;
443         }
444         if (self.weaponentity)
445         {
446                 self.weaponentity.state = WS_CLEAR;
447                 self.weaponentity.effects = 0;
448         }
449 }
450
451 void w_ready()
452 {
453         if (self.weaponentity)
454                 self.weaponentity.state = WS_READY;
455         weapon_thinkf(WFRAME_IDLE, 1000000, w_ready);
456 }
457
458 .float prevdryfire;
459 .float prevwarntime;
460 float weapon_prepareattack_checkammo(float secondary)
461 {
462         if (!(self.items & IT_UNLIMITED_WEAPON_AMMO))
463         if (!WEP_ACTION(self.weapon, WR_CHECKAMMO1 + secondary))
464         {
465                 // always keep the Mine Layer if we placed mines, so that we can detonate them
466                 entity mine;
467                 if(self.weapon == WEP_MINE_LAYER)
468                 for(mine = world; (mine = find(mine, classname, "mine")); ) if(mine.owner == self)
469                         return false;
470
471                 if(self.weapon == WEP_SHOTGUN)
472                 if(!secondary && WEP_CVAR(shotgun, secondary) == 1)
473                         return false; // no clicking, just allow
474
475                 if(self.weapon == self.switchweapon && time - self.prevdryfire > 1) // only play once BEFORE starting to switch weapons
476                 {
477                         sound (self, CH_WEAPON_A, "weapons/dryfire.wav", VOL_BASE, ATTEN_NORM);
478                         self.prevdryfire = time;
479                 }
480
481                 if(WEP_ACTION(self.weapon, WR_CHECKAMMO2 - secondary)) // check if the other firing mode has enough ammo
482                 {
483                         if(time - self.prevwarntime > 1)
484                         {
485                                 Send_Notification(
486                                         NOTIF_ONE,
487                                         self,
488                                         MSG_MULTI,
489                                         ITEM_WEAPON_PRIMORSEC,
490                                         self.weapon,
491                                         secondary,
492                                         (1 - secondary)
493                                 );
494                         }
495                         self.prevwarntime = time;
496                 }
497                 else // this weapon is totally unable to fire, switch to another one
498                 {
499                         W_SwitchToOtherWeapon(self);
500                 }
501
502                 return false;
503         }
504         return true;
505 }
506 .float race_penalty;
507 float weapon_prepareattack_check(float secondary, float attacktime)
508 {
509         if(!weapon_prepareattack_checkammo(secondary))
510                 return false;
511
512         //if sv_ready_restart_after_countdown is set, don't allow the player to shoot
513         //if all players readied up and the countdown is running
514         if(time < game_starttime || time < self.race_penalty) {
515                 return false;
516         }
517
518         if (timeout_status == TIMEOUT_ACTIVE) //don't allow the player to shoot while game is paused
519                 return false;
520
521         // do not even think about shooting if switching
522         if(self.switchweapon != self.weapon)
523                 return false;
524
525         if(attacktime >= 0)
526         {
527                 // don't fire if previous attack is not finished
528                 if (ATTACK_FINISHED(self) > time + self.weapon_frametime * 0.5)
529                         return false;
530                 // don't fire while changing weapon
531                 if (self.weaponentity.state != WS_READY)
532                         return false;
533         }
534
535         return true;
536 }
537 float weapon_prepareattack_do(float secondary, float attacktime)
538 {
539         self.weaponentity.state = WS_INUSE;
540
541         self.spawnshieldtime = min(self.spawnshieldtime, time); // kill spawn shield when you fire
542
543         // if the weapon hasn't been firing continuously, reset the timer
544         if(attacktime >= 0)
545         {
546                 if (ATTACK_FINISHED(self) < time - self.weapon_frametime * 1.5)
547                 {
548                         ATTACK_FINISHED(self) = time;
549                         //dprint("resetting attack finished to ", ftos(time), "\n");
550                 }
551                 ATTACK_FINISHED(self) = ATTACK_FINISHED(self) + attacktime * W_WeaponRateFactor();
552         }
553         self.bulletcounter += 1;
554         //dprint("attack finished ", ftos(ATTACK_FINISHED(self)), "\n");
555         return true;
556 }
557 float weapon_prepareattack(float secondary, float attacktime)
558 {
559         if(weapon_prepareattack_check(secondary, attacktime))
560         {
561                 weapon_prepareattack_do(secondary, attacktime);
562                 return true;
563         }
564         else
565                 return false;
566 }
567
568 void weapon_thinkf(float fr, float t, void() func)
569 {
570         vector a;
571         vector of, or, ou;
572         float restartanim;
573
574         if(fr == WFRAME_DONTCHANGE)
575         {
576                 fr = self.weaponentity.wframe;
577                 restartanim = false;
578         }
579         else if (fr == WFRAME_IDLE)
580                 restartanim = false;
581         else
582                 restartanim = true;
583
584         of = v_forward;
585         or = v_right;
586         ou = v_up;
587
588         if (self.weaponentity)
589         {
590                 self.weaponentity.wframe = fr;
591                 a = '0 0 0';
592                 if (fr == WFRAME_IDLE)
593                         a = self.weaponentity.anim_idle;
594                 else if (fr == WFRAME_FIRE1)
595                         a = self.weaponentity.anim_fire1;
596                 else if (fr == WFRAME_FIRE2)
597                         a = self.weaponentity.anim_fire2;
598                 else // if (fr == WFRAME_RELOAD)
599                         a = self.weaponentity.anim_reload;
600                 a.z *= g_weaponratefactor;
601                 setanim(self.weaponentity, a, restartanim == false, restartanim, restartanim);
602         }
603
604         v_forward = of;
605         v_right = or;
606         v_up = ou;
607
608         if(self.weapon_think == w_ready && func != w_ready && self.weaponentity.state == WS_RAISE)
609         {
610                 backtrace("Tried to override initial weapon think function - should this really happen?");
611         }
612
613         t *= W_WeaponRateFactor();
614
615         // VorteX: haste can be added here
616         if (self.weapon_think == w_ready)
617         {
618                 self.weapon_nextthink = time;
619                 //dprint("started firing at ", ftos(time), "\n");
620         }
621         if (self.weapon_nextthink < time - self.weapon_frametime * 1.5 || self.weapon_nextthink > time + self.weapon_frametime * 1.5)
622         {
623                 self.weapon_nextthink = time;
624                 //dprint("reset weapon animation timer at ", ftos(time), "\n");
625         }
626         self.weapon_nextthink = self.weapon_nextthink + t;
627         self.weapon_think = func;
628         //dprint("next ", ftos(self.weapon_nextthink), "\n");
629
630         if((fr == WFRAME_FIRE1 || fr == WFRAME_FIRE2) && t)
631         {
632                 if((self.weapon == WEP_SHOCKWAVE || self.weapon == WEP_SHOTGUN) && fr == WFRAME_FIRE2)
633                         animdecide_setaction(self, ANIMACTION_MELEE, restartanim);
634                 else
635                         animdecide_setaction(self, ANIMACTION_SHOOT, restartanim);
636         }
637         else
638         {
639                 if(self.anim_upper_action == ANIMACTION_SHOOT || self.anim_upper_action == ANIMACTION_MELEE)
640                         self.anim_upper_action = 0;
641         }
642 }
643
644 float forbidWeaponUse()
645 {
646         if(time < game_starttime && !autocvar_sv_ready_restart_after_countdown)
647                 return 1;
648         if(round_handler_IsActive() && !round_handler_IsRoundStarted())
649                 return 1;
650         if(self.player_blocked)
651                 return 1;
652         if(self.frozen)
653                 return 1;
654         if(self.weapon_blocked)
655                 return 1;
656         return 0;
657 }
658
659 void W_WeaponFrame()
660 {
661         vector fo, ri, up;
662
663         if (frametime)
664                 self.weapon_frametime = frametime;
665
666         if (!self.weaponentity || self.health < 1)
667                 return; // Dead player can't use weapons and injure impulse commands
668
669         if(forbidWeaponUse())
670         if(self.weaponentity.state != WS_CLEAR)
671         {
672                 w_ready();
673                 return;
674         }
675
676         if(!self.switchweapon)
677         {
678                 self.weapon = 0;
679                 self.switchingweapon = 0;
680                 self.weaponentity.state = WS_CLEAR;
681                 self.weaponname = "";
682                 //self.items &= ~IT_AMMO;
683                 return;
684         }
685
686         makevectors(self.v_angle);
687         fo = v_forward; // save them in case the weapon think functions change it
688         ri = v_right;
689         up = v_up;
690
691         // Change weapon
692         if (self.weapon != self.switchweapon)
693         {
694                 if (self.weaponentity.state == WS_CLEAR)
695                 {
696                         // end switching!
697                         self.switchingweapon = self.switchweapon;
698                         entity newwep = get_weaponinfo(self.switchweapon);
699
700                         // the two weapon entities will notice this has changed and update their models
701                         self.weapon = self.switchweapon;
702                         self.weaponname = newwep.mdl;
703                         self.bulletcounter = 0;
704                         self.ammo_field = newwep.ammo_field;
705                         WEP_ACTION(self.switchweapon, WR_SETUP);
706                         self.weaponentity.state = WS_RAISE;
707
708                         // set our clip load to the load of the weapon we switched to, if it's reloadable
709                         if(newwep.spawnflags & WEP_FLAG_RELOADABLE && newwep.reloading_ammo) // prevent accessing undefined cvars
710                         {
711                                 self.clip_load = self.(weapon_load[self.switchweapon]);
712                                 self.clip_size = newwep.reloading_ammo;
713                         }
714                         else
715                                 self.clip_load = self.clip_size = 0;
716
717                         weapon_thinkf(WFRAME_IDLE, newwep.switchdelay_raise, w_ready);
718                 }
719                 else if (self.weaponentity.state == WS_DROP)
720                 {
721                         // in dropping phase we can switch at any time
722                         self.switchingweapon = self.switchweapon;
723                 }
724                 else if (self.weaponentity.state == WS_READY)
725                 {
726                         // start switching!
727                         self.switchingweapon = self.switchweapon;
728                         entity oldwep = get_weaponinfo(self.weapon);
729
730                         // set up weapon switch think in the future, and start drop anim
731                         #ifndef INDEPENDENT_ATTACK_FINISHED
732                         if(ATTACK_FINISHED(self) <= time + self.weapon_frametime * 0.5)
733                         {
734                         #endif
735                                 sound(self, CH_WEAPON_SINGLE, "weapons/weapon_switch.wav", VOL_BASE, ATTN_NORM);
736                                 self.weaponentity.state = WS_DROP;
737                                 weapon_thinkf(WFRAME_DONTCHANGE, oldwep.switchdelay_drop, w_clear);
738                         #ifndef INDEPENDENT_ATTACK_FINISHED
739                         }
740                         #endif
741                 }
742         }
743
744         // LordHavoc: network timing test code
745         //if (self.button0)
746         //      print(ftos(frametime), " ", ftos(time), " >= ", ftos(ATTACK_FINISHED(self)), " >= ", ftos(self.weapon_nextthink), "\n");
747
748         float w;
749         w = self.weapon;
750
751         // call the think code which may fire the weapon
752         // and do so multiple times to resolve framerate dependency issues if the
753         // server framerate is very low and the weapon fire rate very high
754         float c;
755         c = 0;
756         while (c < W_TICSPERFRAME)
757         {
758                 c = c + 1;
759                 if(w && !(self.weapons & WepSet_FromWeapon(w)))
760                 {
761                         if(self.weapon == self.switchweapon)
762                                 W_SwitchWeapon_Force(self, w_getbestweapon(self));
763                         w = 0;
764                 }
765
766                 v_forward = fo;
767                 v_right = ri;
768                 v_up = up;
769
770                 if(w)
771                         WEP_ACTION(self.weapon, WR_THINK);
772                 else
773                         WEP_ACTION(self.weapon, WR_GONETHINK);
774
775                 if (time + self.weapon_frametime * 0.5 >= self.weapon_nextthink)
776                 {
777                         if(self.weapon_think)
778                         {
779                                 v_forward = fo;
780                                 v_right = ri;
781                                 v_up = up;
782                                 self.weapon_think();
783                         }
784                         else
785                                 bprint("\{1}^1ERROR: undefined weapon think function for ", self.netname, "\n");
786                 }
787         }
788 }
789
790 void W_AttachToShotorg(entity flash, vector offset)
791 {
792         entity xflash;
793         flash.owner = self;
794         flash.angles_z = random() * 360;
795
796         if(gettagindex(self.weaponentity, "shot"))
797                 setattachment(flash, self.weaponentity, "shot");
798         else
799                 setattachment(flash, self.weaponentity, "tag_shot");
800         setorigin(flash, offset);
801
802         xflash = spawn();
803         copyentity(flash, xflash);
804
805         flash.viewmodelforclient = self;
806
807         if(self.weaponentity.oldorigin.x > 0)
808         {
809                 setattachment(xflash, self.exteriorweaponentity, "");
810                 setorigin(xflash, self.weaponentity.oldorigin + offset);
811         }
812         else
813         {
814                 if(gettagindex(self.exteriorweaponentity, "shot"))
815                         setattachment(xflash, self.exteriorweaponentity, "shot");
816                 else
817                         setattachment(xflash, self.exteriorweaponentity, "tag_shot");
818                 setorigin(xflash, offset);
819         }
820 }
821
822 void W_DecreaseAmmo(float ammo_use)
823 {
824         entity wep = get_weaponinfo(self.weapon);
825
826         if(cvar("g_overkill"))
827         if(self.ok_use_ammocharge)
828         {
829                 ok_DecreaseCharge(self, self.weapon);
830                 return; // TODO
831         }
832
833         if((self.items & IT_UNLIMITED_WEAPON_AMMO) && !wep.reloading_ammo)
834                 return;
835
836         // if this weapon is reloadable, decrease its load. Else decrease the player's ammo
837         if(wep.reloading_ammo)
838         {
839                 self.clip_load -= ammo_use;
840                 self.(weapon_load[self.weapon]) = self.clip_load;
841         }
842         else if(wep.ammo_field != ammo_none)
843         {
844                 self.(wep.ammo_field) -= ammo_use;
845                 if(self.(wep.ammo_field) < 0)
846                 {
847                         backtrace(sprintf(
848                                 "W_DecreaseAmmo(%.2f): '%s' subtracted too much %s from '%s', resulting with '%.2f' left... "
849                                 "Please notify Samual immediately with a copy of this backtrace!\n",
850                                 ammo_use,
851                                 wep.netname,
852                                 GetAmmoPicture(wep.ammo_field),
853                                 self.netname,
854                                 self.(wep.ammo_field)
855                         ));
856                 }
857         }
858 }
859
860 // weapon reloading code
861
862 .float reload_ammo_amount, reload_ammo_min, reload_time;
863 .float reload_complain;
864 .string reload_sound;
865
866 void W_ReloadedAndReady()
867 {
868         // finish the reloading process, and do the ammo transfer
869
870         self.clip_load = self.old_clip_load; // restore the ammo counter, in case we still had ammo in the weapon before reloading
871
872         // if the gun uses no ammo, max out weapon load, else decrease ammo as we increase weapon load
873         if(!self.reload_ammo_min || self.items & IT_UNLIMITED_WEAPON_AMMO || self.ammo_field == ammo_none)
874                 self.clip_load = self.reload_ammo_amount;
875         else
876         {
877                 // make sure we don't add more ammo than we have
878                 float load = min(self.reload_ammo_amount - self.clip_load, self.(self.ammo_field));
879         self.clip_load += load;
880         self.(self.ammo_field) -= load;
881         }
882         self.(weapon_load[self.weapon]) = self.clip_load;
883
884         // do not set ATTACK_FINISHED in reload code any more. This causes annoying delays if eg: You start reloading a weapon,
885         // then quickly switch to another weapon and back. Reloading is canceled, but the reload delay is still there,
886         // so your weapon is disabled for a few seconds without reason
887
888         //ATTACK_FINISHED(self) -= self.reload_time - 1;
889
890         w_ready();
891 }
892
893 void W_Reload(float sent_ammo_min, string sent_sound)
894 {
895         // set global values to work with
896         entity e;
897         e = get_weaponinfo(self.weapon);
898
899         if(cvar("g_overkill"))
900         if(self.ok_use_ammocharge)
901                 return; // TODO
902
903         self.reload_ammo_min = sent_ammo_min;
904         self.reload_ammo_amount = e.reloading_ammo;
905         self.reload_time = e.reloading_time;
906         self.reload_sound = sent_sound;
907
908         // don't reload weapons that don't have the RELOADABLE flag
909         if (!(e.spawnflags & WEP_FLAG_RELOADABLE))
910         {
911                 dprint("Warning: Attempted to reload a weapon that does not have the WEP_FLAG_RELOADABLE flag. Fix your code!\n");
912                 return;
913         }
914
915         // return if reloading is disabled for this weapon
916         if(!self.reload_ammo_amount)
917                 return;
918
919         // our weapon is fully loaded, no need to reload
920         if (self.clip_load >= self.reload_ammo_amount)
921                 return;
922
923         // no ammo, so nothing to load
924         if(self.ammo_field != ammo_none)
925         if(!self.(self.ammo_field) && self.reload_ammo_min)
926         if (!(self.items & IT_UNLIMITED_WEAPON_AMMO))
927         {
928                 if(IS_REAL_CLIENT(self) && self.reload_complain < time)
929                 {
930                         play2(self, "weapons/unavailable.wav");
931                         sprint(self, strcat("You don't have enough ammo to reload the ^2", WEP_NAME(self.weapon), "\n"));
932                         self.reload_complain = time + 1;
933                 }
934                 // switch away if the amount of ammo is not enough to keep using this weapon
935                 if (!(WEP_ACTION(self.weapon, WR_CHECKAMMO1) + WEP_ACTION(self.weapon, WR_CHECKAMMO2)))
936                 {
937                         self.clip_load = -1; // reload later
938                         W_SwitchToOtherWeapon(self);
939                 }
940                 return;
941         }
942
943         if (self.weaponentity)
944         {
945                 if (self.weaponentity.wframe == WFRAME_RELOAD)
946                         return;
947
948                 // allow switching away while reloading, but this will cause a new reload!
949                 self.weaponentity.state = WS_READY;
950         }
951
952         // now begin the reloading process
953
954         sound(self, CH_WEAPON_SINGLE, self.reload_sound, VOL_BASE, ATTEN_NORM);
955
956         // do not set ATTACK_FINISHED in reload code any more. This causes annoying delays if eg: You start reloading a weapon,
957         // then quickly switch to another weapon and back. Reloading is canceled, but the reload delay is still there,
958         // so your weapon is disabled for a few seconds without reason
959
960         //ATTACK_FINISHED(self) = max(time, ATTACK_FINISHED(self)) + self.reload_time + 1;
961
962         weapon_thinkf(WFRAME_RELOAD, self.reload_time, W_ReloadedAndReady);
963
964         if(self.clip_load < 0)
965                 self.clip_load = 0;
966         self.old_clip_load = self.clip_load;
967         self.clip_load = self.(weapon_load[self.weapon]) = -1;
968 }
969
970 void W_DropEvent(float event, entity player, float weapon_type, entity weapon_item)
971 {
972         entity oldself = self;
973         self = player;
974         weapon_dropevent_item = weapon_item;
975         WEP_ACTION(weapon_type, event);
976         self = oldself;
977 }