]> icculus.org git repositories - taylor/freespace2.git/blob - src/weapon/weapons.cpp
add support for retail FS1 pilot files
[taylor/freespace2.git] / src / weapon / weapons.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Weapon/Weapons.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Code to handle the weapon systems
16  *
17  * $Log$
18  * Revision 1.13  2005/10/01 22:04:58  taylor
19  * fix FS1 (de)briefing voices, the directory names are different in FS1
20  * hard code the table values so that the fs1.vp file isn't needed
21  * hard code a mission fix for sm2-08a since a have no idea how to fix it otherwise
22  * generally cleanup some FS1 code
23  * fix volume sliders in the options screen that never went all the way up
24  *
25  * Revision 1.12  2005/08/12 08:48:11  taylor
26  * don't scale weapon damage for FS1, this way you can still kill a capship with lasers rather than bombs
27  *
28  * Revision 1.11  2004/09/20 01:31:45  theoddone33
29  * GCC 3.4 fixes.
30  *
31  * Revision 1.10  2003/06/11 18:30:33  taylor
32  * plug memory leaks
33  *
34  * Revision 1.9  2003/05/25 02:30:44  taylor
35  * Freespace 1 support
36  *
37  * Revision 1.8  2002/06/21 03:04:12  relnev
38  * nothing important
39  *
40  * Revision 1.7  2002/06/17 06:33:11  relnev
41  * ryan's struct patch for gcc 2.95
42  *
43  * Revision 1.6  2002/06/09 04:41:30  relnev
44  * added copyright header
45  *
46  * Revision 1.5  2002/06/05 08:05:29  relnev
47  * stub/warning removal.
48  *
49  * reworked the sound code.
50  *
51  * Revision 1.4  2002/06/01 03:32:00  relnev
52  * fix texture loading mistake.
53  *
54  * enable some d3d stuff for opengl also
55  *
56  * Revision 1.3  2002/05/28 08:52:03  relnev
57  * implemented two assembly stubs.
58  *
59  * cleaned up a few warnings.
60  *
61  * added a little demo hackery to make it progress a little farther.
62  *
63  * Revision 1.2  2002/05/07 03:16:53  theoddone33
64  * The Great Newline Fix
65  *
66  * Revision 1.1.1.1  2002/05/03 03:28:11  root
67  * Initial import.
68  *
69  * 
70  * 69    9/14/99 3:26a Dave
71  * Fixed laser fogging problem in nebula (D3D)> Fixed multiplayer
72  * respawn-too-early problem. Made a few crash points safe.
73  * 
74  * 68    9/14/99 1:32a Andsager
75  * Better LOD for weapon explosions when behind.  Move point ahead to get
76  * vertex and then find size.
77  * 
78  * 67    9/07/99 1:10p Mikek
79  * Fix code I busted due to adding lifeleft to missiles.
80  * 
81  * 66    9/07/99 12:20a Andsager
82  * LOD less agressive at lower hardware detail level
83  * 
84  * 65    9/06/99 7:21p Dave
85  * Commented out bad lifeleft scaling code in weapon_set_tracking_info()
86  * 
87  * 64    9/06/99 3:23p Andsager
88  * Make fireball and weapon expl ani LOD choice look at resolution of the
89  * bitmap
90  * 
91  * 63    9/06/99 12:46a Andsager
92  * Add weapon_explosion_ani LOD
93  * 
94  * 62    9/05/99 11:24p Mikek
95  * Fixed problems caused by earlier checkin (that was rolled back).
96  * Problem was wp->target_pos was not set for swarmers.
97  * 
98  * More tweaking of missile behavior.  Also add 20% to lifetime of a
99  * locked missile.
100  * 
101  * [Rolled back -- MK] 63    9/05/99 2:23p Mikek
102  * Make aspect seekers a little less likely to miss their target.
103  * Mysterious why they do it so often.  Maybe fix for FS3...
104  * 
105  * [Rolled back -- MK] 62    9/04/99 12:09p Mikek
106  * Limit number of spawned weapons that can home on player based on skill
107  * level.  Works same as for non-spawned weapons.  Only do in single
108  * player.
109  * 
110  * 61    8/27/99 1:34a Andsager
111  * Modify damage by shockwaves for BIG|HUGE ships.  Modify shockwave damge
112  * when weapon blows up.
113  * 
114  * 60    8/24/99 10:47a Jefff
115  * tech room weapon anims.  added tech anim field to weapons.tbl
116  * 
117  * 59    8/16/99 11:58p Andsager
118  * Disable collision on proximity for ships with SIF_DONT_COLLIDE_INVIS
119  * hulls.
120  * 
121  * 58    8/10/99 5:30p Jefff
122  * Added tech_title string to weapon_info.  Changed parser accordingly.
123  * 
124  * 57    8/05/99 2:06a Dave
125  * Whee.
126  * 
127  * 56    8/02/99 5:16p Dave
128  * Bumped up weapon title string length from 32 to 48
129  * 
130  * 55    7/29/99 5:41p Jefff
131  * Sound hooks for cmeasure success
132  * 
133  * 54    7/24/99 1:54p Dave
134  * Hud text flash gauge. Reworked dead popup to use 4 buttons in red-alert
135  * missions.
136  * 
137  * 53    7/19/99 7:20p Dave
138  * Beam tooling. Specialized player-killed-self messages. Fixed d3d nebula
139  * pre-rendering.
140  * 
141  * 52    7/18/99 12:32p Dave
142  * Randomly oriented shockwaves.
143  * 
144  * 51    7/16/99 1:50p Dave
145  * 8 bit aabitmaps. yay.
146  * 
147  * 50    7/15/99 9:20a Andsager
148  * FS2_DEMO initial checkin
149  * 
150  * 49    7/08/99 10:53a Dave
151  * New multiplayer interpolation scheme. Not 100% done yet, but still
152  * better than the old way.
153  * 
154  * 48    7/02/99 4:31p Dave
155  * Much more sophisticated lightning support.
156  * 
157  * 47    7/01/99 5:57p Johnson
158  * Oops. Fixed big ship damage.
159  * 
160  * 46    7/01/99 4:23p Dave
161  * Full support for multiple linked ambient engine sounds. Added "big
162  * damage" flag.
163  * 
164  * 45    6/30/99 5:53p Dave
165  * Put in new anti-camper code.
166  * 
167  * 44    6/22/99 3:24p Danw
168  * Fixed incorrect weapon hit sound culling.
169  * 
170  * 43    6/21/99 7:25p Dave
171  * netplayer pain packet. Added type E unmoving beams.
172  * 
173  * 42    6/14/99 10:45a Dave
174  * Made beam weapons specify accuracy by skill level in the weapons.tbl
175  * 
176  * 41    6/11/99 11:13a Dave
177  * last minute changes before press tour build.
178  * 
179  * 40    6/04/99 2:16p Dave
180  * Put in shrink effect for beam weapons.
181  * 
182  * 39    6/01/99 8:35p Dave
183  * Finished lockarm weapons. Added proper supercap weapons/damage. Added
184  * awacs-set-radius sexpression.
185  * 
186  * 38    6/01/99 3:52p Dave
187  * View footage screen. Fixed xstrings to not display the & symbol. Popup,
188  * dead popup, pxo find player popup, pxo private room popup.
189  * 
190  * 37    5/27/99 6:17p Dave
191  * Added in laser glows.
192  * 
193  * 36    5/20/99 7:00p Dave
194  * Added alternate type names for ships. Changed swarm missile table
195  * entries.
196  * 
197  * 35    5/08/99 8:25p Dave
198  * Upped object pairs. First run of nebula lightning.
199  * 
200  * 34    4/28/99 11:13p Dave
201  * Temporary checkin of artillery code.
202  * 
203  * 33    4/28/99 3:11p Andsager
204  * Stagger turret weapon fire times.  Make turrets smarter when target is
205  * protected or beam protected.  Add weaopn range to weapon info struct.
206  * 
207  * 32    4/22/99 11:06p Dave
208  * Final pass at beam weapons. Solidified a lot of stuff. All that remains
209  * now is to tweak and fix bugs as they come up. No new beam weapon
210  * features.
211  * 
212  * 31    4/19/99 11:01p Dave
213  * More sophisticated targeting laser support. Temporary checkin.
214  * 
215  * 30    4/16/99 5:54p Dave
216  * Support for on/off style "stream" weapons. Real early support for
217  * target-painting lasers.
218  * 
219  * 29    4/07/99 6:22p Dave
220  * Fred and Freespace support for multiple background bitmaps and suns.
221  * Fixed link errors on all subprojects. Moved encrypt_init() to
222  * cfile_init() and lcl_init(), since its safe to call twice.
223  * 
224  * 28    4/02/99 1:35p Dave
225  * Removed weapon hit packet. No good for causing pain.
226  * 
227  * 27    4/02/99 9:55a Dave
228  * Added a few more options in the weapons.tbl for beam weapons. Attempt
229  * at putting "pain" packets into multiplayer.
230  * 
231  * 26    3/31/99 9:26p Dave
232  * Don't load beam textures when in Fred.
233  * 
234  * 25    3/31/99 8:24p Dave
235  * Beefed up all kinds of stuff, incluging beam weapons, nebula effects
236  * and background nebulae. Added per-ship non-dimming pixel colors.
237  * 
238  * 24    3/23/99 2:29p Andsager
239  * Fix shockwaves for kamikazi and Fred defined.  Collect together
240  * shockwave_create_info struct.
241  * 
242  * 23    3/23/99 11:03a Dave
243  * Added a few new fields and fixed parsing code for new weapon stuff.
244  * 
245  * 22    3/19/99 9:52a Dave
246  * Checkin to repair massive source safe crash. Also added support for
247  * pof-style nebulae, and some new weapons code.
248  * 
249  * 24    3/15/99 6:45p Daveb
250  * Put in rough nebula bitmap support.
251  * 
252  * 23    3/12/99 3:19p Enricco
253  * Remove spurious Int3()
254  * 
255  * 22    3/11/99 5:53p Dave
256  * More network optimization. Spliced in Dell OEM planet bitmap crap.
257  * 
258  * 21    3/10/99 6:51p Dave
259  * Changed the way we buffer packets for all clients. Optimized turret
260  * fired packets. Did some weapon firing optimizations.
261  * 
262  * 20    2/24/99 4:02p Dave
263  * Fixed weapon locking and homing problems for multiplayer dogfight mode.
264  * 
265  * 19    2/05/99 12:52p Dave
266  * Fixed Glide nondarkening textures.
267  * 
268  * 18    1/29/99 12:47a Dave
269  * Put in sounds for beam weapon. A bunch of interface screens (tech
270  * database stuff).
271  * 
272  * 17    1/27/99 9:56a Dave
273  * Temporary checkin of beam weapons for Dan to make cool sounds.
274  * 
275  * 16    1/25/99 5:03a Dave
276  * First run of stealth, AWACS and TAG missile support. New mission type
277  * :)
278  * 
279  * 15    1/24/99 11:37p Dave
280  * First full rev of beam weapons. Very customizable. Removed some bogus
281  * Int3()'s in low level net code.
282  * 
283  * 14    1/21/99 10:45a Dave
284  * More beam weapon stuff. Put in warmdown time.
285  * 
286  * 13    1/12/99 5:45p Dave
287  * Moved weapon pipeline in multiplayer to almost exclusively client side.
288  * Very good results. Bandwidth goes down, playability goes up for crappy
289  * connections. Fixed object update problem for ship subsystems.
290  * 
291  * 12    1/08/99 2:08p Dave
292  * Fixed software rendering for pofview. Super early support for AWACS and
293  * beam weapons.
294  * 
295  * 11    1/06/99 2:24p Dave
296  * Stubs and release build fixes.
297  * 
298  * 10    12/01/98 6:12p Johnson
299  * Make sure to page in weapon impact animations as xparent textures.
300  * 
301  * 9     11/20/98 4:08p Dave
302  * Fixed flak effect in multiplayer.
303  * 
304  * 8     11/14/98 5:33p Dave
305  * Lots of nebula work. Put in ship contrails.
306  * 
307  * 7     11/05/98 4:18p Dave
308  * First run nebula support. Beefed up localization a bit. Removed all
309  * conditional compiles for foreign versions. Modified mission file
310  * format.
311  * 
312  * 6     10/26/98 9:42a Dave
313  * Early flak gun support.
314  * 
315  * 5     10/23/98 3:51p Dave
316  * Full support for tstrings.tbl and foreign languages. All that remains
317  * is to make it active in Fred.
318  * 
319  * 4     10/07/98 6:27p Dave
320  * Globalized mission and campaign file extensions. Removed Silent Threat
321  * special code. Moved \cache \players and \multidata into the \data
322  * directory.
323  * 
324  * 3     10/07/98 4:49p Andsager
325  * don't do weapon swap (was needed for mission disk)
326  * 
327  * 2     10/07/98 10:54a Dave
328  * Initial checkin.
329  * 
330  * 1     10/07/98 10:51a Dave
331  * 
332  * 314   9/21/98 11:19p Dave
333  * Weapon name fix.
334  * 
335  * 313   9/19/98 4:33p Adam
336  * Changed default values for particle spew (used on Leech Cannon)
337  * 
338  * 312   9/13/98 10:51p Dave
339  * Put in newfangled icons for mission simulator room. New mdisk.vp
340  * checksum and file length.
341  * 
342  * 311   9/13/98 4:29p Andsager
343  * Maintain Weapon_info compataiblity with mission disk
344  * 
345  * 310   9/13/98 4:26p Andsager
346  * 
347  * 309   9/01/98 4:25p Dave
348  * Put in total (I think) backwards compatibility between mission disk
349  * freespace and non mission disk freespace, including pilot files and
350  * campaign savefiles.
351  * 
352  * 308   8/28/98 3:29p Dave
353  * EMP effect done. AI effects may need some tweaking as required.
354  * 
355  * 307   8/25/98 1:49p Dave
356  * First rev of EMP effect. Player side stuff basically done. Next comes
357  * AI code.
358  * 
359  * 306   8/18/98 10:15a Dave
360  * Touchups on the corkscrew missiles. Added particle spewing weapons.
361  * 
362  * 305   8/17/98 5:07p Dave
363  * First rev of corkscrewing missiles.
364  * 
365  * 304   6/30/98 2:23p Dave
366  * Revised object update system. Removed updates for all weapons. Put
367  * button info back into control info packet.
368  * 
369  * 303   6/22/98 8:36a Allender
370  * revamping of homing weapon system.  don't send as object updates
371  * anymore
372  * 
373  * 302   5/24/98 2:25p Allender
374  * be sure that homing missiles die on client when lifeleft gets too
375  * negative (lost packets)
376  * 
377  * 301   5/20/98 5:47p Sandeep
378  * 
379  * 300   5/18/98 1:58a Mike
380  * Make Phoenix not be fired at fighters (but yes bombers).
381  * Improve positioning of ships in guard mode.
382  * Make turrets on player ship not fire near end of support ship docking.
383  * 
384  * $NoKeywords: $
385  */
386
387 #include <stdlib.h>
388
389 #include "pstypes.h"
390 #include "systemvars.h"
391 #include "vecmat.h"
392 #include "tmapper.h"
393 #include "2d.h"
394 #include "3d.h"
395 #include "bmpman.h"
396 #include "model.h"
397 #include "key.h"
398 #include "physics.h"
399 #include "floating.h"
400 #include "model.h"
401 #include "lighting.h"
402 #include "object.h"
403 #include "weapon.h"
404 #include "ship.h"
405 #include "fireballs.h"
406 #include "player.h"
407 #include "hudtarget.h"
408 #include "freespace.h"
409 #include "radar.h"
410 #include "ai.h"
411 #include "sound.h"
412 #include "multi.h"
413 #include "multimsgs.h"
414 #include "linklist.h"
415 #include "timer.h"
416 #include "gamesnd.h"
417 #include "cmeasure.h"
418 #include "shockwave.h"
419 #include "model.h"
420 #include "staticrand.h"
421 #include "swarm.h"
422 #include "multiutil.h"
423 #include "shiphit.h"
424 #include "trails.h"
425 #include "hud.h"
426 #include "objcollide.h"
427 #include "aibig.h"
428 #include "particle.h"
429 #include "asteroid.h"
430 #include "joy_ff.h"
431 #include "multi_obj.h"
432 #include "corkscrew.h"
433 #include "emp.h"
434 #include "localize.h"
435 #include "flak.h"
436 #include "muzzleflash.h"
437
438 #ifndef NDEBUG
439 int Weapon_flyby_sound_enabled = 1;
440 DCF_BOOL( weapon_flyby, Weapon_flyby_sound_enabled )
441 #endif
442
443 static int Weapon_flyby_sound_timer;    
444
445 weapon Weapons[MAX_WEAPONS];
446 weapon_info Weapon_info[MAX_WEAPON_TYPES];
447
448 #define         MISSILE_OBJ_USED        (1<<0)                  // flag used in missile_obj struct
449 #define         MAX_MISSILE_OBJS        MAX_WEAPONS             // max number of missiles tracked in missile list
450 missile_obj Missile_objs[MAX_MISSILE_OBJS];     // array used to store missile object indexes
451 missile_obj Missile_obj_list;                                           // head of linked list of missile_obj structs
452
453
454 // WEAPON EXPLOSION INFO
455 #define MAX_weapon_expl_lod                                             4
456 #define MAX_Weapon_expl_info                                    3
457
458 typedef struct weapon_expl_lod {
459         char    filename[MAX_FILENAME_LEN];
460         int     bitmap_id;
461         int     num_frames;
462         int     fps;
463 } weapon_expl_lod;
464
465 typedef struct weapon_expl_info {
466         int                                     lod_count;      
467         weapon_expl_lod         lod[MAX_weapon_expl_lod];
468 } weapon_expl_info;
469
470 weapon_expl_info Weapon_expl_info[MAX_Weapon_expl_info];
471
472 int Num_weapon_expl = 0;
473
474 int Num_weapon_types = 0;
475
476 int Num_weapons = 0;
477 int Weapons_inited = 0;
478
479 int laser_model_inner = -1;
480 int laser_model_outer = -1;
481
482 int missile_model = -1;
483
484 char    *Weapon_names[MAX_WEAPON_TYPES];
485
486 int     First_secondary_index = -1;
487
488 #define MAX_SPAWN_WEAPONS       10                      //      Up to 10 weapons can spawn weapons.
489
490 int     Num_spawn_types;
491 char    Spawn_names[MAX_SPAWN_WEAPONS][NAME_LENGTH];
492
493 int Num_player_weapon_precedence;                               // Number of weapon types in Player_weapon_precedence
494 int Player_weapon_precedence[MAX_WEAPON_TYPES]; // Array of weapon types, precedence list for player weapon selection
495
496 // Used to avoid playing too many impact sounds in too short a time interval.
497 // This will elimate the odd "stereo" effect that occurs when two weapons impact at 
498 // nearly the same time, like from a double laser (also saves sound channels!)
499 #define IMPACT_SOUND_DELTA      50              // in milliseconds
500 int             Weapon_impact_timer;                    // timer, initalized at start of each mission
501
502 // energy suck defines
503 #define ESUCK_DEFAULT_WEAPON_REDUCE                             (10.0f)
504 #define ESUCK_DEFAULT_AFTERBURNER_REDUCE                (10.0f)
505
506 // scale factor for supercaps taking damage from weapons which are not "supercap" weapons
507 #define SUPERCAP_DAMAGE_SCALE                   0.25f
508
509 // scale factor for big ships getting hit by flak
510 #define FLAK_DAMAGE_SCALE                               0.05f
511
512 extern int Max_allowed_player_homers[];
513 extern int compute_num_homing_objects(object *target_objp);
514
515 // 
516 void parse_weapon_expl_tbl()
517 {
518 #ifndef MAKE_FS1
519         int     idx;
520         char base_filename[256] = "";
521
522         // open localization
523         lcl_ext_open();
524
525         try {
526                 read_file_text(NOX("weapon_expl.tbl"));
527                 reset_parse();
528
529                 Num_weapon_expl = 0;
530                 required_string("#Start");
531                 while (required_string_either("#End","$Name:")) {
532                         SDL_assert( Num_weapon_expl < MAX_Weapon_expl_info);
533
534                         // base filename
535                         required_string("$Name:");
536                         stuff_string(base_filename, F_NAME, NULL);
537
538                         // # of lod levels - make sure old fireball.tbl is compatible
539                         Weapon_expl_info[Num_weapon_expl].lod_count = 1;
540                         if(optional_string("$LOD:")){
541                                 stuff_int(&Weapon_expl_info[Num_weapon_expl].lod_count);
542                         }
543
544                         // stuff default filename
545                         SDL_strlcpy(Weapon_expl_info[Num_weapon_expl].lod[0].filename, base_filename, MAX_FILENAME_LEN);
546
547                         // stuff LOD level filenames
548                         for(idx=1; idx<Weapon_expl_info[Num_weapon_expl].lod_count; idx++){
549                                 if(idx >= MAX_weapon_expl_lod){
550                                         break;
551                                 }
552
553                                 SDL_snprintf(Weapon_expl_info[Num_weapon_expl].lod[idx].filename, MAX_FILENAME_LEN, "%s_%d", base_filename, idx);
554                         }
555
556                         Num_weapon_expl++;
557                 }
558                 required_string("#End");
559         } catch (parse_error_t rval) {
560                 Error(LOCATION, "Unable to parse weapon_expl.tbl!  Code = %i.\n", (int)rval);
561         }
562
563         // close localization
564         lcl_ext_close();
565 #else
566         // hard coded value for FS1
567         Num_weapon_expl = 0;
568
569         Weapon_expl_info[Num_weapon_expl].lod_count = 1;
570         SDL_strlcpy(Weapon_expl_info[Num_weapon_expl].lod[0].filename, "ExpMissileHit1", MAX_FILENAME_LEN);
571
572         Num_weapon_expl++;
573 #endif
574 }
575
576 int get_weapon_expl_info_index(char *filename)
577 {
578         for (int i=0; i<MAX_Weapon_expl_info; i++) {
579                 if ( SDL_strcasecmp(Weapon_expl_info[i].lod[0].filename, filename) == 0) {
580                         return i;
581                 }
582         }
583
584         return -1;
585 }
586 // ----------------------------------------------------------------------
587 // missile_obj_list_init()
588 //
589 // Clear out the Missile_obj_list
590 //
591 void missile_obj_list_init()
592 {
593         int i;
594
595         list_init(&Missile_obj_list);
596         for ( i = 0; i < MAX_MISSILE_OBJS; i++ ) {
597                 Missile_objs[i].flags = 0;
598         }
599 }
600
601 // ---------------------------------------------------
602 // missile_obj_list_add()
603 //
604 // Function to add a node from the Missile_obj_list.  Only
605 // called from weapon_create()
606 int missile_obj_list_add(int objnum)
607 {
608         int i;
609
610         for ( i = 0; i < MAX_MISSILE_OBJS; i++ ) {
611                 if ( !(Missile_objs[i].flags & MISSILE_OBJ_USED) )
612                         break;
613         }
614         if ( i == MAX_MISSILE_OBJS ) {
615                 Error(LOCATION, "Fatal Error: Ran out of missile object nodes\n");
616                 return -1;
617         }
618         
619         Missile_objs[i].flags = 0;
620         Missile_objs[i].objnum = objnum;
621         list_append(&Missile_obj_list, &Missile_objs[i]);
622         Missile_objs[i].flags |= MISSILE_OBJ_USED;
623
624         return i;
625 }
626
627 // ---------------------------------------------------
628 // missle_obj_list_remove()
629 //
630 // Function to remove a node from the Missile_obj_list.  Only
631 // called from weapon_delete()
632 void missle_obj_list_remove(int index)
633 {
634         SDL_assert(index >= 0 && index < MAX_MISSILE_OBJS);
635         list_remove(&Missile_obj_list, &Missile_objs[index]);   
636         Missile_objs[index].flags = 0;
637 }
638
639 // ---------------------------------------------------
640 // missile_obj_list_rebuild()
641 //
642 // Called by the save/restore code to rebuild Missile_obj_list
643 //
644 void missile_obj_list_rebuild()
645 {
646         object *objp;
647
648         missile_obj_list_init();
649
650         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
651                 if ( objp->type == OBJ_WEAPON && Weapon_info[Weapons[objp->instance].weapon_info_index].subtype == WP_MISSILE ) {
652                         Weapons[objp->instance].missile_list_index = missile_obj_list_add(OBJ_INDEX(objp));
653                 }
654         }
655 }
656
657 // If this is a player countermeasure, let the player know he evaded a missile
658 void weapon_maybe_alert_cmeasure_success(object *objp)
659 {
660         if ( objp->type == OBJ_CMEASURE ) {
661                 cmeasure *cmp;
662                 cmp = &Cmeasures[objp->instance];
663                 if ( cmp->source_objnum == OBJ_INDEX(Player_obj) ) {
664                         hud_start_text_flash(XSTR("Evaded", 1430), 800);
665                         snd_play(&Snds[SND_MISSILE_EVADED_POPUP]);
666                 } else if ( Objects[cmp->source_objnum].flags & OF_PLAYER_SHIP ) {
667                         send_countermeasure_success_packet( cmp->source_objnum );
668                 }
669         }
670 }
671
672 // ---------------------------------------------------
673 // missile_obj_return_address()
674 //
675 // Called externally to generate an address from an index into
676 // the Missile_objs[] array
677 //
678 missile_obj *missile_obj_return_address(int index)
679 {
680         SDL_assert(index >= 0 && index < MAX_MISSILE_OBJS);
681         return &Missile_objs[index];
682 }
683
684 //      Return the index of Weapon_info[].name that is *name.
685 int weapon_info_lookup(const char *name)
686 {
687         int     i;
688
689 #ifdef MAKE_FS1
690         // fix the stupid table stuff - it's non-fatal but annoying error messages
691         if (!strcmp(name, "Disruptor Missile")) {
692                 name = "D-Missile";
693         // this one fixes the same issue with a SilentThreat mission
694         } else if (!strcmp(name, "Shield Breaker")) {
695                 name = "S-Breaker";
696         }
697 #endif
698
699         for (i=0; i<Num_weapon_types; i++)
700                 if (!SDL_strcasecmp(name, Weapon_info[i].name))
701                         return i;
702
703         return -1;
704 }
705
706 #define DEFAULT_WEAPON_SPAWN_COUNT      10
707
708 //      Parse the weapon flags.
709 void parse_wi_flags(weapon_info *weaponp)
710 {
711         char    weapon_strings[MAX_WEAPON_FLAGS][NAME_LENGTH];
712         int     num_strings;
713
714         required_string("$Flags:");
715
716         num_strings = stuff_string_list(weapon_strings, MAX_WEAPON_FLAGS);
717         
718         for (int i=0; i<num_strings; i++) {
719                 if (!SDL_strcasecmp(NOX("Electronics"), weapon_strings[i]))
720                         weaponp->wi_flags |= WIF_ELECTRONICS;           
721                 else if (!SDL_strncasecmp(NOX("Spawn"), weapon_strings[i], 5)) {
722                         if (weaponp->spawn_type == -1) {
723                                 int     skip_length, name_length;
724                                 char    *temp_string;
725
726                                 temp_string = weapon_strings[i];
727
728                                 weaponp->wi_flags |= WIF_SPAWN;
729                                 weaponp->spawn_type = (short)Num_spawn_types;
730                                 skip_length = strlen(NOX("Spawn")) + strspn(&temp_string[strlen(NOX("Spawn"))], NOX(" \t"));
731                                 char *num_start = SDL_strchr(&temp_string[skip_length], ',');
732                                 if (num_start == NULL) {
733                                         weaponp->spawn_count = DEFAULT_WEAPON_SPAWN_COUNT;
734                                         name_length = NAME_LENGTH;
735                                 } else {
736                                         weaponp->spawn_count = (short)atoi(num_start+1);
737                                         name_length = min(num_start - temp_string - skip_length + 1, NAME_LENGTH);
738                                 }
739
740                                 SDL_strlcpy(Spawn_names[Num_spawn_types++], &(weapon_strings[i][skip_length]), name_length);
741                                 SDL_assert(Num_spawn_types < MAX_SPAWN_WEAPONS);
742                         } else
743                                 Warning(LOCATION, "Illegal to have two spawn types for one weapon.\n"
744                                                                                 "Ignoring weapon %s", weapon_strings[i]);
745                 } else if (!SDL_strcasecmp(NOX("Remote Detonate"), weapon_strings[i]))
746                         weaponp->wi_flags |= WIF_REMOTE;
747                 else if (!SDL_strcasecmp(NOX("Puncture"), weapon_strings[i]))
748                         weaponp->wi_flags |= WIF_PUNCTURE;              
749                 else if (!SDL_strcasecmp(NOX("Big Ship"), weapon_strings[i]))
750                         weaponp->wi_flags |= WIF_BIG_ONLY;
751                 else if (!SDL_strcasecmp(NOX("Huge"), weapon_strings[i]))
752                         weaponp->wi_flags |= WIF_HUGE;
753                 else if (!SDL_strcasecmp(NOX("Bomber+"), weapon_strings[i]))
754                         weaponp->wi_flags |= WIF_BOMBER_PLUS;
755                 else if (!SDL_strcasecmp(NOX("child"), weapon_strings[i]))
756                         weaponp->wi_flags |= WIF_CHILD;
757                 else if (!SDL_strcasecmp(NOX("Bomb"), weapon_strings[i]))
758                         weaponp->wi_flags |= WIF_BOMB;
759                 else if (!SDL_strcasecmp(NOX("No Dumbfire"), weapon_strings[i]))
760                         weaponp->wi_flags |= WIF_NO_DUMBFIRE;
761                 else if (!SDL_strcasecmp(NOX("In tech database"), weapon_strings[i]))
762                         weaponp->wi_flags |= WIF_IN_TECH_DATABASE;
763                 else if (!SDL_strcasecmp(NOX("Player allowed"), weapon_strings[i]))
764                         weaponp->wi_flags |= WIF_PLAYER_ALLOWED;                
765                 else if (!SDL_strcasecmp(NOX("Particle Spew"), weapon_strings[i]))
766                         weaponp->wi_flags |= WIF_PARTICLE_SPEW;
767                 else if (!SDL_strcasecmp(NOX("EMP"), weapon_strings[i]))
768                         weaponp->wi_flags |= WIF_EMP;
769                 else if (!SDL_strcasecmp(NOX("Esuck"), weapon_strings[i]))
770                         weaponp->wi_flags |= WIF_ENERGY_SUCK;
771                 else if (!SDL_strcasecmp(NOX("Flak"), weapon_strings[i]))
772                         weaponp->wi_flags |= WIF_FLAK;
773                 else if (!SDL_strcasecmp(NOX("Corkscrew"), weapon_strings[i]))
774                         weaponp->wi_flags |= WIF_CORKSCREW;
775                 else if (!SDL_strcasecmp(NOX("Shudder"), weapon_strings[i]))
776                         weaponp->wi_flags |= WIF_SHUDDER;               
777                 else if (!SDL_strcasecmp(NOX("lockarm"), weapon_strings[i]))
778                         weaponp->wi_flags |= WIF_LOCKARM;               
779                 else if (!SDL_strcasecmp(NOX("beam"), weapon_strings[i]))
780                         weaponp->wi_flags |= WIF_BEAM;
781                 else if (!SDL_strcasecmp(NOX("stream"), weapon_strings[i]))
782                         weaponp->wi_flags |= WIF_STREAM;
783                 else if (!SDL_strcasecmp(NOX("supercap"), weapon_strings[i]))
784                         weaponp->wi_flags |= WIF_SUPERCAP;
785 #ifdef MAKE_FS1
786                 else if (!SDL_strcasecmp(NOX("Swarm"), weapon_strings[i]))
787                         weaponp->wi_flags |= WIF_SWARM;
788                 else if (!SDL_strcasecmp(NOX("No Ship"), weapon_strings[i]))
789                         weaponp->wi_flags |= WIF_CHILD;
790 #endif 
791                 else
792                         Warning(LOCATION, "Bogus string in weapon flags: %s\n", weapon_strings[i]);
793         }       
794
795         // SWARM, CORKSCREW and FLAK should be mutually exclusive
796         if(weaponp->wi_flags & WIF_FLAK){
797                 SDL_assert(!(weaponp->wi_flags & WIF_CORKSCREW) && !(weaponp->wi_flags & WIF_SWARM));
798         }
799         if(weaponp->wi_flags & WIF_CORKSCREW){
800                 SDL_assert(!(weaponp->wi_flags & WIF_FLAK) && !(weaponp->wi_flags & WIF_SWARM));
801         }
802         if(weaponp->wi_flags & WIF_SWARM){
803                 SDL_assert(!(weaponp->wi_flags & WIF_CORKSCREW) && !(weaponp->wi_flags & WIF_FLAK));
804         }
805
806         // make sure flak guns are only placed on turrets
807         if(weaponp->wi_flags & WIF_FLAK){
808                 SDL_assert(weaponp->wi_flags & WIF_BIG_ONLY);
809         }
810 }
811
812 // function to parse the information for a specific weapon type.        
813 // return 0 if successful, otherwise return -1
814 #define WEAPONS_MULTITEXT_LENGTH 2048
815
816 int parse_weapon()
817 {
818         char buf[WEAPONS_MULTITEXT_LENGTH];
819         weapon_info *wip;
820         char fname[255] = "";
821         int idx;
822
823         wip = &Weapon_info[Num_weapon_types];
824
825         wip->wi_flags = 0;
826
827         required_string("$Name:");
828         stuff_string(wip->name, F_NAME, NULL);
829         diag_printf ("Weapon name -- %s\n", wip->name);
830
831         // AL 28-3-98: If this is a demo build, we only want to parse weapons that are preceded with
832         //             the '@' symbol
833         #ifdef DEMO // not needed FS2_DEMO (separate table file)
834                 if ( wip->name[0] != '@' ) {
835                         // advance to next weapon, and return -1
836
837                         if ( skip_to_start_of_strings("$Name:", "#End") != 1 ) {
838                                 Int3();
839                         }
840                         return -1;
841                 }
842         #endif
843
844         if ( wip->name[0] == '@' ) {
845                 char old_name[NAME_LENGTH];
846                 SDL_strlcpy(old_name, wip->name, SDL_arraysize(old_name));
847                 SDL_strlcpy(wip->name, old_name+1, SDL_arraysize(wip->name));
848         }
849
850         wip->title[0] = 0;
851         if (optional_string("+Title:")) {
852                 stuff_string(wip->title, F_NAME, NULL, WEAPON_TITLE_LEN);
853         }
854
855         wip->desc = NULL;
856         if (optional_string("+Description:")) {
857                 stuff_string(buf, F_MULTITEXT, NULL);
858                 wip->desc = strdup(buf);
859         }
860
861         wip->tech_title[0] = 0;
862         if (optional_string("+Tech Title:")) {
863                 stuff_string(wip->tech_title, F_NAME, NULL, NAME_LENGTH);
864         }
865
866         wip->tech_anim_filename[0] = 0;
867         if (optional_string("+Tech Anim:")) {
868                 stuff_string(wip->tech_anim_filename, F_NAME, NULL, NAME_LENGTH);
869         }
870
871         wip->tech_desc = NULL;
872         if (optional_string("+Tech Description:")) {
873                 stuff_string(buf, F_MULTITEXT, NULL, WEAPONS_MULTITEXT_LENGTH);
874                 wip->tech_desc = strdup(buf);
875         }
876
877         //      Read the model file.  It can be a POF file or none.
878         //      If there is no model file (Model file: = "none") then we use our special
879         //      laser renderer which requires inner, middle and outer information.
880         required_string("$Model file:");
881         stuff_string(wip->pofbitmap_name, F_NAME, NULL);
882         diag_printf ("Model pof file -- %s\n", wip->pofbitmap_name );
883         if ( SDL_strcasecmp(wip->pofbitmap_name, NOX("none")) ) {
884                 wip->model_num = -1;                            
885                 wip->render_type = WRT_POF;
886                 wip->laser_bitmap = -1;
887         } else {
888                 //      No POF or AVI file specified, render as special laser type.
889                 ubyte r,g,b;
890
891                 wip->render_type = WRT_LASER;
892                 wip->model_num = -1;
893
894                 // laser bitmap itself
895                 required_string("@Laser Bitmap:");
896                 stuff_string(wip->pofbitmap_name, F_NAME, NULL);
897                 wip->laser_bitmap = -1;
898                 if(!Fred_running){
899                         wip->laser_bitmap = bm_load( wip->pofbitmap_name );
900                 }
901
902                 // optional laser glow
903                 wip->laser_glow_bitmap = -1;
904                 if(optional_string("@Laser Glow:")){
905                         stuff_string(fname, F_NAME, NULL);              
906                         if(!Fred_running){
907                                 wip->laser_glow_bitmap = bm_load( fname );
908
909                                 // might as well lock it down as an aabitmap now
910                                 if(wip->laser_glow_bitmap >= 0){
911                                         bm_lock(wip->laser_glow_bitmap, 8, BMP_AABITMAP);
912                                         bm_unlock(wip->laser_glow_bitmap);
913                                 }
914                         }
915                 }
916                 
917                 required_string("@Laser Color:");
918                 stuff_byte(&r); stuff_byte(&g); stuff_byte(&b);
919                 gr_init_color( &wip->laser_color_1, r, g, b );
920
921                 // optional string for cycling laser colors
922                 gr_init_color(&wip->laser_color_2, 0, 0, 0);
923                 if(optional_string("@Laser Color2:")){
924                         stuff_byte(&r); stuff_byte(&g); stuff_byte(&b);
925                         gr_init_color( &wip->laser_color_2, r, g, b );
926                 }
927
928                 required_string("@Laser Length:");
929                 stuff_float(&wip->laser_length);
930                 
931                 required_string("@Laser Head Radius:");
932                 stuff_float(&wip->laser_head_radius);
933
934                 required_string("@Laser Tail Radius:");
935                 stuff_float(&wip->laser_tail_radius );
936         }
937
938         required_string("$Mass:");
939         stuff_float( &(wip->mass) );
940         diag_printf ("Weapon mass -- %7.3f\n", wip->mass);
941
942         required_string("$Velocity:");
943         stuff_float( &(wip->max_speed) );
944         diag_printf ("Weapon mass -- %7.3f\n", wip->max_speed);
945
946         required_string("$Fire Wait:");
947         stuff_float( &(wip->fire_wait) );
948         diag_printf ("Weapon fire wait -- %7.3f\n", wip->fire_wait);
949
950         required_string("$Damage:");
951         stuff_float(&wip->damage);
952
953         // secondary weapons require these values
954         if (First_secondary_index != -1) {
955                 required_string("$Blast Force:");
956                 stuff_float( &(wip->blast_force) );
957                 diag_printf ("Weapon blast force -- %7.3f\n", wip->blast_force);
958
959                 required_string("$Inner Radius:");
960                 stuff_float( &(wip->inner_radius) );
961                 if ( wip->inner_radius != 0 ) {
962                         wip->wi_flags |= WIF_AREA_EFFECT;
963                 }
964                 diag_printf ("Weapon inner blast radius -- %7.3f\n", wip->inner_radius);
965
966                 required_string("$Outer Radius:");
967                 stuff_float( &(wip->outer_radius) );
968                 if ( wip->outer_radius != 0 ) {
969                         wip->wi_flags |= WIF_AREA_EFFECT;
970                 }
971                 diag_printf ("Weapon outer blast radius -- %7.3f\n", wip->outer_radius);
972
973                 required_string("$Shockwave Speed:");
974                 stuff_float( &(wip->shockwave_speed) );
975                 if ( wip->shockwave_speed != 0 ) {
976                         wip->wi_flags |= WIF_SHOCKWAVE;
977                 }
978                 diag_printf ("Shockwave speed -- %7.3f\n", wip->shockwave_speed);
979         } 
980         // for primary weapons they're optional
981         else {
982                 if(optional_string("$Blast Force:")){
983                         stuff_float( &(wip->blast_force) );
984                         diag_printf ("Weapon blast force -- %7.3f\n", wip->blast_force);
985                 }
986
987                 if(optional_string("$Inner Radius:")){
988                         stuff_float( &(wip->inner_radius) );
989                         if ( wip->inner_radius != 0 ) {
990                                 wip->wi_flags |= WIF_AREA_EFFECT;
991                         }
992                         diag_printf ("Weapon inner blast radius -- %7.3f\n", wip->inner_radius);
993                 }
994
995                 if(optional_string("$Outer Radius:")){
996                         stuff_float( &(wip->outer_radius) );
997                         if ( wip->outer_radius != 0 ) {
998                                 wip->wi_flags |= WIF_AREA_EFFECT;
999                         }
1000                         diag_printf ("Weapon outer blast radius -- %7.3f\n", wip->outer_radius);
1001                 }
1002
1003                 if(optional_string("$Shockwave Speed:")){
1004                         stuff_float( &(wip->shockwave_speed) );
1005                         if ( wip->shockwave_speed != 0 ) {
1006                                 wip->wi_flags |= WIF_SHOCKWAVE;
1007                         }
1008                         diag_printf ("Shockwave speed -- %7.3f\n", wip->shockwave_speed);
1009                 }
1010         }
1011
1012         required_string("$Armor Factor:");
1013         stuff_float(&wip->armor_factor);
1014
1015         required_string("$Shield Factor:");
1016         stuff_float(&wip->shield_factor);
1017
1018         required_string("$Subsystem Factor:");
1019         stuff_float(&wip->subsystem_factor);
1020
1021         required_string("$Lifetime:");
1022         stuff_float(&wip->lifetime);
1023
1024         required_string("$Energy Consumed:");
1025         stuff_float(&wip->energy_consumed);
1026
1027         required_string("$Cargo Size:");
1028         stuff_float(&wip->cargo_size);
1029
1030         int is_homing=0;
1031         required_string("$Homing:");
1032         stuff_boolean(&is_homing);
1033
1034         if (is_homing == 1) {
1035                 char    temp_type[128];
1036
1037                 // the following five items only need to be recorded if the weapon is a homing weapon
1038                 required_string("+Type:");
1039                 stuff_string(temp_type, F_NAME, NULL);
1040
1041                 if (!SDL_strcasecmp(temp_type, NOX("HEAT"))) {
1042                         float   view_cone_angle;
1043
1044                         wip->wi_flags |= WIF_HOMING_HEAT | WIF_TURNS;
1045
1046                         required_string("+Turn Time:");                 
1047                         stuff_float(&wip->turn_time);
1048
1049                         required_string("+View Cone:");
1050                         stuff_float(&view_cone_angle);
1051
1052                         wip->fov = (float)cos((float)(ANG_TO_RAD(view_cone_angle/2.0f)));
1053
1054                 } else if (!SDL_strcasecmp(temp_type, NOX("ASPECT"))) {
1055                         wip->wi_flags |= WIF_HOMING_ASPECT | WIF_TURNS;
1056
1057                         required_string("+Turn Time:");                 
1058                         stuff_float(&wip->turn_time);
1059
1060                         required_string("+Min Lock Time:");                     // minimum time (in seconds) to achieve lock
1061                         stuff_float(&wip->min_lock_time);
1062
1063                         required_string("+Lock Pixels/Sec:");           // pixels/sec moved while locking
1064                         stuff_int(&wip->lock_pixels_per_sec);
1065
1066                         required_string("+Catch-up Pixels/Sec:");       // pixels/sec moved while catching-up for a lock
1067                         stuff_int(&wip->catchup_pixels_per_sec);
1068
1069                         required_string("+Catch-up Penalty:");          // number of extra pixels to move while locking as a penalty for catching up for a lock
1070                         stuff_int(&wip->catchup_pixel_penalty);
1071                 } else
1072                         Error(LOCATION, "Illegal homing type = %s.\nMust be HEAT or ASPECT.\n", temp_type);
1073
1074         }
1075
1076         // swarm missiles
1077         int s_count;
1078         wip->swarm_count = -1;
1079         if(optional_string("$Swarm:")){
1080                 wip->swarm_count = SWARM_DEFAULT_NUM_MISSILES_FIRED;
1081                 stuff_int(&s_count);
1082                 wip->swarm_count = (short)s_count;
1083
1084                 // flag as being a swarm weapon
1085                 wip->wi_flags |= WIF_SWARM;
1086         }
1087
1088         required_string("$LaunchSnd:");
1089         stuff_int(&wip->launch_snd);
1090
1091         required_string("$ImpactSnd:");
1092         stuff_int(&wip->impact_snd);
1093
1094         if (First_secondary_index != -1) {
1095                 required_string("$FlyBySnd:");
1096                 stuff_int(&wip->flyby_snd);
1097         }
1098
1099         //      Secondary weapons are required to have a rearm rate.
1100         if (First_secondary_index != -1) {
1101                 required_string( "$Rearm Rate:");
1102                 stuff_float( &wip->rearm_rate );
1103                 if (wip->rearm_rate > 0.1f)
1104                         wip->rearm_rate = 1.0f/wip->rearm_rate;
1105                 else
1106                         wip->rearm_rate = 1.0f;
1107         }
1108
1109         wip->weapon_range = 999999999.9f;
1110         if (optional_string("+Weapon Range:")) {
1111                 stuff_float(&wip->weapon_range);
1112         }
1113
1114         wip->spawn_type = -1;
1115         parse_wi_flags(wip);
1116
1117         char trail_name[MAX_FILENAME_LEN] = "";
1118         trail_info *ti = &wip->tr_info;
1119         memset(ti, 0, sizeof(trail_info));
1120 #ifndef MAKE_FS1
1121         if(optional_string("$Trail:")){ 
1122                 wip->wi_flags |= WIF_TRAIL;             // missile leaves a trail
1123
1124                 required_string("+Start Width:");
1125                 stuff_float(&ti->w_start);
1126
1127                 required_string("+End Width:");
1128                 stuff_float(&ti->w_end);
1129
1130                 required_string("+Start Alpha:");
1131                 stuff_float(&ti->a_start);
1132
1133                 required_string("+End Alpha:");
1134                 stuff_float(&ti->a_end);                
1135
1136                 required_string("+Max Life:");
1137                 stuff_float(&ti->max_life);
1138
1139                 ti->stamp = fl2i(1000.0f*ti->max_life)/(NUM_TRAIL_SECTIONS+1);
1140
1141                 required_string("+Bitmap:");
1142                 stuff_string(trail_name, F_NAME, NULL);
1143                 ti->bitmap = bm_load(trail_name);
1144                 // wip->delta_time = fl2i(1000.0f*wip->max_life)/(NUM_TRAIL_SECTIONS+1);                // time between sections.  max_life / num_sections basically.
1145         }
1146 #else
1147         // seemed easier to separate this out from above
1148         int has_trail=0;
1149         required_string("$Trail:");
1150         stuff_boolean(&has_trail);
1151
1152         if (has_trail == 1) {
1153                 wip->wi_flags |= WIF_TRAIL;     // missile leaves a trail
1154
1155                 required_string("+Head Width:");
1156                 stuff_float(&ti->w_start);
1157
1158                 required_string("+Tail Width:");
1159                 stuff_float(&ti->w_end);
1160
1161                 ti->a_start = 1.0;
1162                 ti->a_end = 0.0;
1163
1164                 required_string("+Life:");
1165                 stuff_float(&ti->max_life);
1166
1167                 ti->stamp = fl2i(1000.0f*ti->max_life)/(NUM_TRAIL_SECTIONS+1);
1168
1169                 required_string("+Bitmap:");
1170                 stuff_string(trail_name, F_NAME, NULL);
1171                 ti->bitmap = bm_load(trail_name);
1172         }
1173 #endif
1174
1175         // read in filename for icon that is used in weapons selection
1176         wip->icon_filename[0] = 0;
1177         if ( optional_string("$Icon:") ) {
1178                 stuff_string(wip->icon_filename, F_NAME, NULL);
1179         }
1180
1181         // read in filename for animation that is used in weapons selection
1182         wip->anim_filename[0] = 0;
1183         if ( optional_string("$Anim:") ) {
1184                 stuff_string(wip->anim_filename, F_NAME, NULL);
1185         }
1186
1187         wip->impact_weapon_expl_index = -1;
1188         if ( optional_string("$Impact Explosion:") ) {
1189                 char impact_ani_file[FILESPEC_LENGTH];
1190                 stuff_string(impact_ani_file, F_NAME, NULL);
1191                 if ( SDL_strcasecmp(impact_ani_file,NOX("none")))       {
1192                         wip->impact_weapon_expl_index = get_weapon_expl_info_index(impact_ani_file);
1193                         //int num_frames, fps;
1194                         //wip->impact_explosion_ani = bm_load_animation( impact_ani_file, &num_frames, &fps, 1 );
1195
1196                         required_string("$Impact Explosion Radius:");
1197                         stuff_float(&wip->impact_explosion_radius);
1198                 }
1199         }
1200
1201         // muzzle flash
1202         char mflash_string[255] = "";
1203         wip->muzzle_flash = -1;
1204         if( optional_string("$Muzzleflash:") ){
1205                 stuff_string(mflash_string, F_NAME, NULL);
1206
1207                 // look it up
1208                 wip->muzzle_flash = mflash_lookup(mflash_string);
1209
1210                 if(wip->muzzle_flash >= 0){                     
1211                         wip->wi_flags |= WIF_MFLASH;
1212                 }
1213         }
1214
1215         // EMP optional stuff (if WIF_EMP is not set, none of this matters, anyway)
1216         if( optional_string("$EMP Intensity:") ){
1217                 stuff_float(&wip->emp_intensity);
1218         } else {
1219                 wip->emp_intensity = EMP_DEFAULT_INTENSITY;
1220         }
1221         if( optional_string("$EMP Time:") ){
1222                 stuff_float(&wip->emp_time);
1223         } else {
1224                 wip->emp_intensity = EMP_DEFAULT_TIME;
1225         }
1226
1227         // Energy suck optional stuff (if WIF_ENERGY_SUCK is not set, none of this matters anyway)
1228         if( optional_string("$Leech Weapon:") ){
1229                 stuff_float(&wip->weapon_reduce);
1230         } else {
1231                 wip->weapon_reduce = ESUCK_DEFAULT_WEAPON_REDUCE;
1232         }
1233         if( optional_string("$Leech Afterburner:") ){
1234                 stuff_float(&wip->afterburner_reduce);
1235         } else {
1236                 wip->afterburner_reduce = ESUCK_DEFAULT_AFTERBURNER_REDUCE;
1237         }
1238
1239         // beam weapon optional stuff
1240         wip->b_info.beam_type = -1;
1241         wip->b_info.beam_life = -1.0f;
1242         wip->b_info.beam_warmup = -1;
1243         wip->b_info.beam_warmdown = -1;
1244         wip->b_info.beam_muzzle_radius = 0.0f;
1245         wip->b_info.beam_particle_count = -1;
1246         wip->b_info.beam_particle_radius = 0.0f;
1247         wip->b_info.beam_particle_angle = 0.0f;
1248         wip->b_info.beam_particle_ani = -1;     
1249         wip->b_info.beam_loop_sound = -1;
1250         wip->b_info.beam_warmup_sound = -1;
1251         wip->b_info.beam_warmdown_sound = -1;
1252         wip->b_info.beam_num_sections = 0;
1253         wip->b_info.beam_glow_bitmap = -1;
1254         wip->b_info.beam_shots = 0;
1255         wip->b_info.beam_shrink_factor = 0.0f;
1256         wip->b_info.beam_shrink_pct = 0.0f;
1257         if( optional_string("$BeamInfo:")){
1258                 // beam type
1259                 required_string("+Type:");
1260                 stuff_int(&wip->b_info.beam_type);
1261
1262                 // how long it lasts
1263                 required_string("+Life:");
1264                 stuff_float(&wip->b_info.beam_life);
1265
1266                 // warmup time
1267                 required_string("+Warmup:");
1268                 stuff_int(&wip->b_info.beam_warmup);
1269
1270                 // warmdowm time
1271                 required_string("+Warmdown:");
1272                 stuff_int(&wip->b_info.beam_warmdown);
1273
1274                 // muzzle glow radius
1275                 required_string("+Radius:");
1276                 stuff_float(&wip->b_info.beam_muzzle_radius);
1277
1278                 // particle spew count
1279                 required_string("+PCount:");
1280                 stuff_int(&wip->b_info.beam_particle_count);
1281
1282                 // particle radius
1283                 required_string("+PRadius:");
1284                 stuff_float(&wip->b_info.beam_particle_radius);
1285
1286                 // angle off turret normal
1287                 required_string("+PAngle:");
1288                 stuff_float(&wip->b_info.beam_particle_angle);
1289
1290                 // particle bitmap/ani          
1291                 required_string("+PAni:");
1292                 stuff_string(fname, F_NAME, NULL);
1293                 if(!Fred_running){
1294                         int num_frames, fps;
1295                         wip->b_info.beam_particle_ani = bm_load_animation(fname, &num_frames, &fps, 1);
1296                 }
1297
1298                 // magic miss #
1299                 required_string("+Miss Factor:");               
1300                 for(idx=0; idx<NUM_SKILL_LEVELS; idx++){
1301                         wip->b_info.beam_miss_factor[idx] = 0.00001f;
1302                         stuff_float(&wip->b_info.beam_miss_factor[idx]);
1303                 }
1304
1305                 // beam fire sound
1306                 required_string("+BeamSound:");
1307                 stuff_int(&wip->b_info.beam_loop_sound);
1308
1309                 // warmup sound
1310                 required_string("+WarmupSound:");
1311                 stuff_int(&wip->b_info.beam_warmup_sound);
1312
1313                 // warmdown sound
1314                 required_string("+WarmdownSound:");
1315                 stuff_int(&wip->b_info.beam_warmdown_sound);
1316
1317                 // glow bitmap
1318                 required_string("+Muzzleglow:");
1319                 stuff_string(fname, F_NAME, NULL);
1320                 if(!Fred_running){
1321                         wip->b_info.beam_glow_bitmap = bm_load(fname);
1322                 }
1323
1324                 // # of shots (only used for type D beams)
1325                 required_string("+Shots:");
1326                 stuff_int(&wip->b_info.beam_shots);
1327
1328                 // shrinkage
1329                 required_string("+ShrinkFactor:");
1330                 stuff_float(&wip->b_info.beam_shrink_factor);
1331                 required_string("+ShrinkPct:");
1332                 stuff_float(&wip->b_info.beam_shrink_pct);
1333
1334                 // beam sections
1335                 while( optional_string("$Section:") ){
1336                         beam_weapon_section_info i;
1337                         char tex_name[255] = "";
1338                         
1339                         // section width
1340                         required_string("+Width:");
1341                         stuff_float(&i.width);
1342
1343                         // texture
1344                         required_string("+Texture:");
1345                         stuff_string(tex_name, F_NAME, NULL);
1346                         i.texture = -1;
1347                         if(!Fred_running){
1348                                 i.texture = bm_load(tex_name);
1349                                 if(i.texture >= 0){
1350                                         bm_lock(i.texture, 16, BMP_TEX_OTHER);
1351                                         bm_unlock(i.texture);
1352                                 }
1353                         }
1354
1355                         // rgba inner
1356                         required_string("+RGBA Inner:");
1357                         stuff_byte(&i.rgba_inner[0]);
1358                         stuff_byte(&i.rgba_inner[1]);
1359                         stuff_byte(&i.rgba_inner[2]);
1360                         stuff_byte(&i.rgba_inner[3]);
1361
1362                         // rgba outer
1363                         required_string("+RGBA Outer:");
1364                         stuff_byte(&i.rgba_outer[0]);
1365                         stuff_byte(&i.rgba_outer[1]);
1366                         stuff_byte(&i.rgba_outer[2]);
1367                         stuff_byte(&i.rgba_outer[3]);
1368
1369                         // flicker
1370                         required_string("+Flicker:");
1371                         stuff_float(&i.flicker);                        
1372
1373                         // zadd
1374                         required_string("+Zadd:");
1375                         stuff_float(&i.z_add);
1376
1377                         // maybe copy it
1378                         if(wip->b_info.beam_num_sections < MAX_BEAM_SECTIONS - 1){
1379                                 wip->b_info.sections[wip->b_info.beam_num_sections++] = i;
1380                         }
1381                 }               
1382         }
1383
1384         // tag weapon optional stuff
1385         wip->tag_level = -1;
1386         wip->tag_time = -1.0f;
1387         if( optional_string("$Tag:")){
1388                 stuff_int(&wip->tag_level);
1389                 stuff_float(&wip->tag_time);            
1390                 wip->wi_flags |= WIF_TAG;
1391         }       
1392
1393         return 0;
1394 }
1395
1396 // function to parse the information for a specific ship type.  
1397 void parse_cmeasure()
1398 {
1399         cmeasure_info *cmeasurep;
1400
1401         cmeasurep = &Cmeasure_info[Num_cmeasure_types];
1402
1403         required_string("$Name:");
1404         stuff_string(cmeasurep->cmeasure_name, F_NAME, NULL);
1405
1406 /*$Name:                                        Type One
1407 $Velocity:                              20.0                            ;; speed relative to ship, rear-fired until POF info added, MK, 5/22/97
1408 $Fire Wait:                             0.5
1409 $Lifetime Min:                  1.0                             ;; Minimum lifetime
1410 $Lifetime Max:                  2.0                             ;; Maximum lifetime.  Actual lifetime is rand(min..max).
1411 $LaunchSnd:                             counter_1.wav,  .8, 10, 300     ;; countermeasure 1 fired (sound is 3d)
1412 */
1413
1414         required_string("$Velocity:");
1415         stuff_float( &(cmeasurep->max_speed) );
1416
1417         required_string("$Fire Wait:");
1418         stuff_float( &(cmeasurep->fire_wait) );
1419
1420         required_string("$Lifetime Min:");
1421         stuff_float(&cmeasurep->life_min);
1422
1423         required_string("$Lifetime Max:");
1424         stuff_float(&cmeasurep->life_max);
1425
1426         required_string("$LaunchSnd:");
1427         stuff_int(&cmeasurep->launch_sound);
1428
1429         required_string("$Model:");
1430         stuff_string(cmeasurep->pof_name, F_NAME, NULL);
1431         cmeasurep->model_num = -1;              
1432 }
1433
1434
1435 //      For all weapons that spawn weapons, given an index at weaponp->spawn_type,
1436 // convert the strings in Spawn_names to indices in the Weapon_types array.
1437 void translate_spawn_types()
1438 {
1439         int     i,j;
1440
1441         for (i=0; i<Num_weapon_types; i++)
1442                 if (Weapon_info[i].spawn_type != -1) {
1443                         int     spawn_type = Weapon_info[i].spawn_type;
1444
1445                         for (j=0; j<Num_weapon_types; j++)
1446                                 if (!SDL_strcasecmp(Spawn_names[spawn_type], Weapon_info[j].name)) {
1447                                         Weapon_info[i].spawn_type = (short)j;
1448                                         if (i == j){
1449                                                 Warning(LOCATION, "Weapon %s spawns itself.  Infinite recursion?\n", Weapon_info[i].name);
1450                                         }
1451                                 }
1452                 }
1453 }
1454
1455 void parse_weaponstbl()
1456 {
1457         // open localization
1458         lcl_ext_open();
1459
1460         read_file_text("weapons.tbl");
1461         reset_parse();
1462
1463         Num_weapon_types = 0;
1464         First_secondary_index = -1;
1465         Num_spawn_types = 0;
1466         
1467         required_string("#Primary Weapons");
1468         while (required_string_either("#End", "$Name:")) {
1469                 SDL_assert( Num_weapon_types < MAX_WEAPON_TYPES );
1470                 // AL 28-3-98: If parse_weapon() fails, try next .tbl weapon
1471                 if ( parse_weapon() ) {
1472                         continue;
1473                 }
1474                 Weapon_info[Num_weapon_types].subtype = WP_LASER;
1475                 Num_weapon_types++;
1476         }
1477         required_string("#End");
1478
1479         required_string("#Secondary Weapons");
1480         First_secondary_index = Num_weapon_types;
1481         while (required_string_either("#End", "$Name:")) {
1482                 SDL_assert( Num_weapon_types < MAX_WEAPON_TYPES );
1483                 // AL 28-3-98: If parse_weapon() fails, try next .tbl weapon
1484                 if ( parse_weapon() ) {
1485                         continue;
1486                 }
1487                 Weapon_info[Num_weapon_types].subtype = WP_MISSILE;
1488                 Num_weapon_types++;
1489         }
1490         required_string("#End");
1491
1492         required_string("#Beam Weapons");
1493         while (required_string_either("#End", "$Name:")) {
1494                 SDL_assert( Num_weapon_types < MAX_WEAPON_TYPES );
1495                 // AL 28-3-98: If parse_weapon() fails, try next .tbl weapon
1496                 if ( parse_weapon() ) {
1497                         continue;
1498                 }
1499                 Weapon_info[Num_weapon_types].subtype = WP_BEAM;
1500                 Num_weapon_types++;
1501         }
1502         required_string("#End");
1503
1504         required_string("#Countermeasures");
1505         while (required_string_either("#End", "$Name:")) {
1506                 SDL_assert( Num_cmeasure_types < MAX_CMEASURE_TYPES );
1507                 parse_cmeasure();
1508                 Num_cmeasure_types++;
1509         }
1510
1511         required_string("#End");
1512
1513         // Read in a list of weapon_info indicies that are an ordering of the player weapon precedence.
1514         // This list is used to select an alternate weapon when a particular weapon is not available
1515         // during weapon selection.
1516         required_string("$Player Weapon Precedence:");
1517         Num_player_weapon_precedence = stuff_int_list(Player_weapon_precedence, MAX_WEAPON_TYPES, WEAPON_LIST_TYPE);
1518
1519         translate_spawn_types();
1520
1521         // close localization
1522         lcl_ext_close();
1523 }
1524
1525 void create_weapon_names()
1526 {
1527         int     i;
1528
1529         for (i=0; i<Num_weapon_types; i++)
1530                 Weapon_names[i] = Weapon_info[i].name;
1531 }
1532
1533 // This will get called once at game startup
1534 void weapon_init()
1535 {
1536         if ( !Weapons_inited ) {
1537 #if !(defined(FS2_DEMO) || defined(FS1_DEMO))
1538                 // parse weapon_exp.tbl
1539                 parse_weapon_expl_tbl();
1540 #endif
1541                 // parse weapons.tbl
1542                 try {
1543                         parse_weaponstbl();
1544                         create_weapon_names();
1545                         Weapons_inited = 1;
1546                 } catch (parse_error_t rval) {
1547                         Error(LOCATION, "Error parsing 'weapons.tbl'\r\nError code = %i.\r\n", (int)rval);
1548                 }
1549         }
1550
1551         weapon_level_init();
1552 }
1553
1554
1555 // This will get called at the start of each level.
1556 void weapon_level_init()
1557 {
1558         int i;
1559
1560         // Reset everything between levels
1561         Num_weapons = 0;
1562         for (i=0; i<MAX_WEAPONS; i++)   {
1563                 Weapons[i].objnum = -1;
1564                 Weapons[i].weapon_info_index = -1;
1565         }
1566
1567         trail_level_init();             // reset all missile trails
1568
1569         swarm_level_init();
1570         missile_obj_list_init();
1571         
1572         cscrew_level_init();
1573
1574         // emp effect
1575         emp_level_init();
1576
1577         Weapon_flyby_sound_timer = timestamp(0);
1578         Weapon_impact_timer = 1;        // inited each level, used to reduce impact sounds
1579 }
1580
1581 MONITOR( NumWeaponsRend );      
1582
1583 static const float weapon_glow_scale_f = 2.3f;
1584 static const float weapon_glow_scale_r = 2.3f;
1585 static const float weapon_glow_scale_l = 1.5f;
1586 static const float weapon_glow_alpha = 0.85f;
1587
1588 void weapon_render(object *obj)
1589 {
1590         int num;
1591         weapon_info *wip;
1592         weapon *wp;
1593         color c;
1594
1595         MONITOR_INC(NumWeaponsRend, 1);
1596
1597         SDL_assert(obj->type == OBJ_WEAPON);
1598
1599         num = obj->instance;
1600         wp = &Weapons[num];
1601         wip = &Weapon_info[Weapons[num].weapon_info_index];
1602
1603         switch (wip->render_type) {
1604                 case WRT_LASER: {
1605                         // turn off fogging for good measure
1606                         gr_fog_set(GR_FOGMODE_NONE, 0, 0, 0, -1.0f, -1.0f);
1607
1608                         if (wip->laser_bitmap >= 0) {                                   
1609                                 gr_set_color_fast(&wip->laser_color_1);
1610                                 gr_set_bitmap(wip->laser_bitmap, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, 0.99999f, -1, -1);
1611
1612                                 vector headp;
1613                                 vm_vec_scale_add(&headp, &obj->pos, &obj->orient.v.fvec, wip->laser_length);
1614                                 wp->weapon_flags &= ~WF_CONSIDER_FOR_FLYBY_SOUND;
1615                                 if ( g3_draw_laser(&headp, wip->laser_head_radius, &obj->pos, wip->laser_tail_radius) ) {
1616                                         wp->weapon_flags |= WF_CONSIDER_FOR_FLYBY_SOUND;
1617                                 }
1618                         }                       
1619
1620                         // maybe draw laser glow bitmap
1621 #ifndef MAKE_FS1
1622                         if(wip->laser_glow_bitmap >= 0){
1623 #else
1624                         if ( (Detail.weapon_detail >= 1) && (wip->laser_glow_bitmap >= 0) ) {
1625 #endif
1626                                 // get the laser color
1627                                 weapon_get_laser_color(&c, obj);
1628
1629                                 vector headp2 = ZERO_VECTOR;
1630                                 vm_vec_scale_add(&headp2, &obj->pos, &obj->orient.v.fvec, wip->laser_length * weapon_glow_scale_l);
1631                                 gr_set_bitmap(wip->laser_glow_bitmap, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, weapon_glow_alpha, -1, -1);
1632                                 g3_draw_laser_rgb(&headp2, wip->laser_head_radius * weapon_glow_scale_f, &obj->pos, wip->laser_tail_radius * weapon_glow_scale_r, c.red, c.green, c.blue);
1633                         }                                               
1634                         break;
1635                 }
1636
1637                 case WRT_POF:   {
1638                                 uint render_flags = MR_NORMAL|MR_IS_MISSILE|MR_NO_LIGHTING;
1639
1640                                 model_clear_instance(wip->model_num);
1641
1642                                 if ( (wip->wi_flags & WIF_THRUSTER) && (wp->thruster_bitmap > -1) ) {
1643                                         float   ft;
1644
1645                                         //      Add noise to thruster geometry.
1646                                         //ft = obj->phys_info.forward_thrust;                                   
1647                                         ft = 1.0f;              // Always use 1.0f for missiles                                 
1648                                         ft *= (1.0f + frand()/5.0f - 1.0f/10.0f);
1649                                         if (ft > 1.0f)
1650                                                 ft = 1.0f;
1651
1652                                         model_set_thrust( wip->model_num, ft, wp->thruster_bitmap, wp->thruster_glow_bitmap, wp->thruster_glow_noise);
1653                                         render_flags |= MR_SHOW_THRUSTERS;
1654                                 }
1655
1656                                 model_render(wip->model_num, &obj->orient, &obj->pos, render_flags);
1657
1658                                 // render a missile plume as well
1659                                 /*
1660                                 static int plume = -1;  
1661                                 extern float Interp_thrust_twist;
1662                                 extern float Interp_thrust_twist2;
1663                                 if(plume == -1){
1664                                         plume = model_load("plume01.pof", -1, NULL);
1665                                 }
1666                                 if(plume != -1){
1667                                         Interp_thrust_twist = tw;
1668                                         Interp_thrust_twist2 = tw2;
1669                                         model_set_alpha(plume_alpha);
1670                                         model_render(plume, &obj->orient, &obj->pos, MR_ALL_XPARENT);
1671                                         Interp_thrust_twist = -1.0f;
1672                                         Interp_thrust_twist2 = -1.0f;
1673                                 }
1674                                 */
1675                         }
1676                         break;
1677
1678                 default:
1679                         Warning(LOCATION, "Unknown weapon rendering type = %i\n", wip->render_type);
1680         }
1681 }
1682
1683 void weapon_delete(object *obj)
1684 {
1685         weapon *wp;
1686         int num;
1687
1688         num = obj->instance;
1689
1690         SDL_assert( Weapons[num].objnum == OBJ_INDEX(obj));
1691         wp = &Weapons[num];
1692
1693         SDL_assert(wp->weapon_info_index >= 0);
1694         wp->weapon_info_index = -1;
1695         if (wp->swarm_index >= 0) {
1696                 swarm_delete(wp->swarm_index);
1697                 wp->swarm_index = -1;
1698         }
1699
1700         if(wp->cscrew_index >= 0) {
1701                 cscrew_delete(wp->cscrew_index);
1702                 wp->cscrew_index = -1;
1703         }
1704
1705         if (wp->missile_list_index >= 0) {
1706                 missle_obj_list_remove(wp->missile_list_index);
1707                 wp->missile_list_index = -1;
1708         }
1709
1710         if (wp->flak_index >= 0){
1711                 flak_delete(wp->flak_index);
1712                 wp->flak_index = -1;
1713         }
1714
1715         if (wp->trail_num > -1) {
1716                 trail_object_died(wp->trail_num);
1717         }
1718
1719         wp->objnum = -1;
1720         Num_weapons--;
1721         SDL_assert(Num_weapons >= 0);
1722 }
1723
1724 // Check if missile is newly locked onto the Player, maybe play a launch warning
1725 void weapon_maybe_play_warning(weapon *wp)
1726 {
1727         if ( wp->homing_object == Player_obj ) {
1728                 if ( !(wp->weapon_flags & WF_LOCK_WARNING_PLAYED) ) {
1729                         wp->weapon_flags |= WF_LOCK_WARNING_PLAYED;
1730                         if ( Weapon_info[wp->weapon_info_index].wi_flags & WIF_HOMING_HEAT ) {
1731                                 snd_play(&Snds[SND_HEATLOCK_WARN]);
1732                         } else {
1733                                 SDL_assert(Weapon_info[wp->weapon_info_index].wi_flags & WIF_HOMING_ASPECT);
1734                                 snd_play(&Snds[SND_ASPECTLOCK_WARN]);
1735                         }
1736                 }
1737         }
1738 }
1739
1740 #define CMEASURE_DETONATE_DISTANCE              40.0f
1741
1742 //      Detonate all missiles near this countermeasure.
1743 void detonate_nearby_missiles(cmeasure *cmp)
1744 {
1745         missile_obj     *mop;
1746         vector          cmeasure_pos;
1747
1748         cmeasure_pos = Objects[cmp->objnum].pos;
1749
1750         mop = GET_FIRST(&Missile_obj_list);
1751         while(mop != END_OF_LIST(&Missile_obj_list)) {
1752                 object  *objp;
1753                 weapon  *wp;
1754
1755                 objp = &Objects[mop->objnum];
1756                 wp = &Weapons[objp->instance];
1757
1758                 if (wp->team != cmp->team) {
1759                         if ( Missiontime - wp->creation_time > F1_0/2) {
1760                                 if (vm_vec_dist_quick(&cmeasure_pos, &objp->pos) < CMEASURE_DETONATE_DISTANCE) {
1761                                         if (wp->lifeleft > 0.2f) { 
1762                                                 //nprintf(("Jim", "Frame %i: Cmeasure #%i detonating weapon #%i\n", Framecount, cmp-Cmeasures, wp-Weapons));
1763                                                 wp->lifeleft = 0.2f;
1764                                                 // nprintf(("AI", "Frame %i: Flagging weapon %i for detonation.\n", Framecount, wp-Weapons));
1765                                         }
1766                                 }
1767                         }
1768                 }
1769
1770                 mop = mop->next;
1771         }
1772 }
1773
1774 //      Find an object for weapon #num (object *weapon_objp) to home on due to heat.
1775 void find_homing_object(object *weapon_objp, int num)
1776 {
1777         object          *objp, *old_homing_objp;
1778         weapon_info     *wip;
1779         weapon          *wp;
1780         float                   best_dist;
1781
1782         wp = &Weapons[num];
1783
1784         wip = &Weapon_info[Weapons[num].weapon_info_index];
1785
1786         best_dist = 99999.9f;
1787
1788         // save the old homing object so that multiplayer servers can give the right information
1789         // to clients if the object changes
1790         old_homing_objp = wp->homing_object;
1791
1792         wp->homing_object = &obj_used_list;
1793
1794         //      Scan all objects, find a weapon to home on.
1795         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
1796                 if ((objp->type == OBJ_SHIP) || (objp->type == OBJ_CMEASURE)) {
1797                         if (objp->type == OBJ_CMEASURE)
1798                                 if (Cmeasures[objp->instance].flags & CMF_DUD_HEAT)
1799                                         continue;
1800
1801                         int homing_object_team = obj_team(objp);
1802                         if ( (homing_object_team != wp->team) || (homing_object_team == TEAM_TRAITOR) ) {
1803                                 float           dist;
1804                                 float           dot;
1805                                 vector  vec_to_object;
1806
1807                                 // AL 2-17-98: If ship is immune to sensors, can't home on it (Sandeep says so)!
1808                                 if ( objp->type == OBJ_SHIP ) {
1809                                         if ( Ships[objp->instance].flags & SF_HIDDEN_FROM_SENSORS ) {
1810                                                 continue;
1811                                         }
1812
1813                                         //      MK, 9/4/99.
1814                                         //      If this is a player object, make sure there aren't already too many homers.
1815                                         //      Only in single player.  In multiplayer, we don't want to restrict it in dogfight on team vs. team.
1816                                         //      For co-op, it's probably also OK.
1817                                         if (!( Game_mode & GM_MULTIPLAYER )) {
1818                                                 int     num_homers = compute_num_homing_objects(objp);
1819                                                 if (Max_allowed_player_homers[Game_skill_level] < num_homers)
1820                                                         continue;
1821                                         }
1822                                 }
1823
1824                                 dist = vm_vec_normalized_dir(&vec_to_object, &objp->pos, &weapon_objp->pos);
1825
1826                                 if (objp->type == OBJ_CMEASURE)
1827                                         dist *= 0.5f;
1828
1829                                 dot = vm_vec_dot(&vec_to_object, &weapon_objp->orient.v.fvec);
1830
1831                                 if (dot > wip->fov) {
1832                                         if (dist < best_dist) {
1833                                                 best_dist = dist;
1834                                                 wp->homing_object = objp;
1835                                                 wp->target_sig = objp->signature;
1836
1837                                                 weapon_maybe_alert_cmeasure_success(objp);
1838                                         }
1839                                 }
1840                         }
1841                 }
1842         }
1843
1844 //      if (wp->homing_object->type == OBJ_CMEASURE)
1845 //              nprintf(("AI", "Frame %i: Weapon #%i homing on cmeasure #%i\n", Framecount, num, objp-Objects));
1846
1847         if (wp->homing_object == Player_obj)
1848                 weapon_maybe_play_warning(wp);
1849
1850         // if the old homing object is different that the new one, send a packet to clients
1851         if ( MULTIPLAYER_MASTER && (old_homing_objp != wp->homing_object) ) {
1852                 send_homing_weapon_info( num );
1853         }
1854 }
1855
1856 //      Scan all countermeasures.  Maybe make weapon_objp home on it.
1857 void find_homing_object_cmeasures_1(object *weapon_objp)
1858 {
1859         object  *objp;
1860         weapon  *wp;
1861         weapon_info     *wip;
1862         float           best_dot, dist, dot;
1863
1864         wp = &Weapons[weapon_objp->instance];
1865         wip = &Weapon_info[wp->weapon_info_index];
1866
1867         best_dot = wip->fov;                    //      Note, setting to this avoids comparison below.
1868
1869         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
1870                 if (objp->type == OBJ_CMEASURE) {
1871                         vector  vec_to_object;
1872                         dist = vm_vec_normalized_dir(&vec_to_object, &objp->pos, &weapon_objp->pos);
1873
1874                         if (dist < MAX_CMEASURE_TRACK_DIST) {
1875                                 float   chance;
1876                                 if (wip->wi_flags & WIF_HOMING_ASPECT) {
1877                                         chance = 1.0f/2.0f;     //      aspect seeker this likely to chase a countermeasure
1878                                 } else {
1879                                         chance = 1.0f/1.5f;     //      heat seeker this likely to chase a countermeasure
1880                                 }
1881                                 if ((objp->signature != wp->cmeasure_ignore_objnum) && (objp->signature != wp->cmeasure_chase_objnum)) {
1882                                         if (frand() < chance) {
1883                                                 wp->cmeasure_ignore_objnum = objp->signature;   //      Don't process this countermeasure again.
1884                                                 //nprintf(("Jim", "Frame %i: Weapon #%i ignoring cmeasure #%i\n", Framecount, OBJ_INDEX(weapon_objp), objp->signature));
1885                                         } else  {
1886                                                 wp->cmeasure_chase_objnum = objp->signature;    //      Don't process this countermeasure again.
1887                                                 //nprintf(("Jim", "Frame %i: Weapon #%i CHASING cmeasure #%i\n", Framecount, OBJ_INDEX(weapon_objp), objp->signature));
1888                                         }
1889                                 }
1890                                 
1891                                 if (objp->signature != wp->cmeasure_ignore_objnum) {
1892
1893                                         dot = vm_vec_dot(&vec_to_object, &weapon_objp->orient.v.fvec);
1894
1895                                         if (dot > best_dot) {
1896                                                 //nprintf(("Jim", "Frame %i: Weapon #%i homing on cmeasure #%i\n", Framecount, weapon_objp-Objects, objp->signature));
1897                                                 best_dot = dot;
1898                                                 wp->homing_object = objp;
1899                                                 weapon_maybe_alert_cmeasure_success(objp);
1900                                         }
1901                                 }
1902                         }
1903                 }
1904         }
1905 }
1906
1907
1908 //      Someone launched countermeasures.
1909 //      For all heat-seeking homing objects, see if should favor tracking a countermeasure instead.
1910 void find_homing_object_cmeasures()
1911 {
1912         object  *weapon_objp;
1913
1914         // nprintf(("AI", "Scanning for countermeasures in frame %i\n", Framecount));
1915
1916         if (Cmeasures_homing_check == 0)
1917                 return;
1918
1919         if (Cmeasures_homing_check <= 0)
1920                 Cmeasures_homing_check = 1;
1921
1922         Cmeasures_homing_check--;
1923
1924         for (weapon_objp = GET_FIRST(&obj_used_list); weapon_objp != END_OF_LIST(&obj_used_list); weapon_objp = GET_NEXT(weapon_objp) ) {
1925                 if (weapon_objp->type == OBJ_WEAPON) {
1926                         weapon_info     *wip = &Weapon_info[Weapons[weapon_objp->instance].weapon_info_index];
1927
1928                         if (wip->wi_flags & WIF_HOMING)
1929                                 find_homing_object_cmeasures_1(weapon_objp);
1930                 }
1931         }
1932
1933 }
1934
1935 //      Find object with signature "sig" and make weapon home on it.
1936 void find_homing_object_by_sig(object *weapon_objp, int sig)
1937 {
1938         ship_obj                *sop;
1939         weapon          *wp;
1940         object          *old_homing_objp;
1941
1942         wp = &Weapons[weapon_objp->instance];
1943
1944         // save the old object so that multiplayer masters know whether to send a homing update packet
1945         old_homing_objp = wp->homing_object;
1946
1947         sop = GET_FIRST(&Ship_obj_list);
1948         while(sop != END_OF_LIST(&Ship_obj_list)) {
1949                 object  *objp;
1950
1951                 objp = &Objects[sop->objnum];
1952                 if (objp->signature == sig) {
1953                         wp->homing_object = objp;
1954                         wp->target_sig = objp->signature;
1955                         break;
1956                 }
1957
1958                 sop = sop->next;
1959         }
1960
1961         // if the old homing object is different that the new one, send a packet to clients
1962         if ( MULTIPLAYER_MASTER && (old_homing_objp != wp->homing_object) ) {
1963                 send_homing_weapon_info( weapon_objp->instance );
1964         }
1965
1966 }
1967
1968 //      Make weapon num home.  It's also object *obj.
1969 void weapon_home(object *obj, int num, float frame_time)
1970 {
1971         weapon          *wp;
1972         weapon_info     *wip;
1973         object          *hobjp;
1974
1975         SDL_assert(obj->type == OBJ_WEAPON);
1976         SDL_assert(obj->instance == num);
1977         wp = &Weapons[num];
1978         wip = &Weapon_info[wp->weapon_info_index];
1979         hobjp = Weapons[num].homing_object;
1980
1981         //      If not 1/2 second gone by, don't home yet.
1982         if ((hobjp == &obj_used_list) || ( f2fl(Missiontime - wp->creation_time) < 0.25f )) {
1983                 //      If this is a heat seeking homing missile and 1/2 second has elapsed since firing
1984                 //      and we don't have a target (else we wouldn't be inside the IF), find a new target.
1985                 if (wip->wi_flags & WIF_HOMING_HEAT)
1986                         if ( f2fl(Missiontime - wp->creation_time) > 0.5f )
1987                                 find_homing_object(obj, num);
1988
1989                 if (obj->phys_info.speed > wip->max_speed) {
1990                         obj->phys_info.speed -= frame_time * 4;
1991                         vm_vec_copy_scale( &obj->phys_info.desired_vel, &obj->orient.v.fvec, obj->phys_info.speed);
1992                 } else if ((obj->phys_info.speed < wip->max_speed/4) && (wip->wi_flags & WIF_HOMING_HEAT)) {
1993                         obj->phys_info.speed = wip->max_speed/4;
1994                         vm_vec_copy_scale( &obj->phys_info.desired_vel, &obj->orient.v.fvec, obj->phys_info.speed);
1995                 }
1996
1997 /*      Removed code that makes bombs drop for a bit.  They looked odd and it was confusing.  People wondered where their weapons went.
1998                 //      Make bombs drop down for first second of life.
1999                 if (wip->wi_flags & WIF_BOMB) {
2000                         if (wip->lifetime - wp->lifeleft < 0.5f) {
2001                                 float   time_scale = wip->lifetime - wp->lifeleft;
2002                                 vm_vec_scale_add2(&obj->phys_info.desired_vel, &obj->orient.uvec, (time_scale - 0.5f) * max(10.0f, obj->phys_info.speed/2.0f));
2003                         }
2004                 }
2005 */
2006                 return;
2007         }
2008
2009         // AL 4-8-98: If orgiginal target for aspect lock missile is lost, stop homing
2010         if (wip->wi_flags & WIF_HOMING_ASPECT) {
2011                 if ( wp->target_sig > 0 ) {
2012                         if ( wp->homing_object->signature != wp->target_sig ) {
2013                                 wp->homing_object = &obj_used_list;
2014                                 return;
2015                         }
2016                 }
2017         }
2018
2019         // AL 4-13-98: Stop homing on a subsystem if parent ship has changed
2020         if (wip->wi_flags & WIF_HOMING_HEAT) {
2021                 if ( wp->target_sig > 0 ) {
2022                         if ( wp->homing_object->signature != wp->target_sig ) {
2023                                 wp->homing_subsys = NULL;
2024                         }
2025                 }
2026         }
2027
2028 /*
2029         if (hobjp->type == OBJ_NONE) {
2030                 find_homing_object(obj, num);
2031                 return;
2032         }
2033 */
2034
2035         switch (hobjp->type) {
2036         case OBJ_NONE:
2037                 if (wip->wi_flags & WIF_HOMING_ASPECT)
2038                         find_homing_object_by_sig(obj, wp->target_sig);
2039                 else
2040                         find_homing_object(obj, num);
2041                 return;
2042                 break;
2043         case OBJ_SHIP:
2044                 if (hobjp->signature != wp->target_sig) {
2045                         if (wip->wi_flags & WIF_HOMING_ASPECT)
2046                                 find_homing_object_by_sig(obj, wp->target_sig);
2047                         else
2048                                 find_homing_object(obj, num);
2049                         return;
2050                 }
2051                 break;
2052         case OBJ_WEAPON:
2053                 // only allowed to home on bombs
2054                 SDL_assert(Weapon_info[Weapons[hobjp->instance].weapon_info_index].wi_flags & WIF_BOMB);
2055                 if (wip->wi_flags & WIF_HOMING_ASPECT)
2056                         find_homing_object_by_sig(obj, wp->target_sig);
2057                 else
2058                         find_homing_object(obj, num);
2059                 break;
2060         case OBJ_CMEASURE:
2061                 break;
2062         default:
2063                 return;
2064         }
2065
2066         //      See if this weapon is the nearest homing object to the object it is homing on.
2067         //      If so, update some fields in the target object's ai_info.
2068         if (hobjp != &obj_used_list) {
2069                 float   dist;
2070
2071                 dist = vm_vec_dist_quick(&obj->pos, &hobjp->pos);
2072
2073                 if (hobjp->type == OBJ_SHIP) {
2074                         ai_info *aip;
2075
2076                         aip = &Ai_info[Ships[hobjp->instance].ai_index];
2077
2078                         if ((aip->nearest_locked_object == -1) || (dist < aip->nearest_locked_distance)) {
2079                                 aip->nearest_locked_object = obj-Objects;
2080                                 aip->nearest_locked_distance = dist;
2081                         }
2082                 }
2083         }
2084
2085         //      If the object it is homing on is still valid, home some more!
2086         if (hobjp != &obj_used_list) {
2087                 float           old_dot, vel;
2088                 vector  vec_to_goal;
2089                 vector  target_pos;     // position of what the homing missile is seeking
2090
2091                 vm_vec_zero(&target_pos);
2092
2093                 // the homing missile may be seeking a subsystem on a ship.  If so, we need to calculate the
2094                 // world coordinates of that subsystem so the homing missile can seek it out.
2095                 //      For now, March 7, 1997, MK, heat seeking homing missiles will be able to home on
2096                 //      any subsystem.  Probably makes sense for them to only home on certain kinds of subsystems.
2097                 if ( wp->homing_subsys != NULL ) {
2098                         get_subsystem_world_pos(hobjp, Weapons[num].homing_subsys, &target_pos);
2099                         wp->homing_pos = target_pos;    // store the homing position in weapon data
2100                         SDL_assert( !vm_is_vec_nan(&wp->homing_pos) );
2101                 } else {
2102                         float   fov;
2103                         float   dist;
2104
2105                         dist = vm_vec_dist_quick(&obj->pos, &hobjp->pos);
2106                         if (hobjp->type == OBJ_CMEASURE) {
2107                                 if (dist < CMEASURE_DETONATE_DISTANCE) {
2108                                         cmeasure        *cmp;
2109
2110                                         cmp = &Cmeasures[hobjp->instance];
2111
2112                                         //      Make this missile detonate soon.  Not right away, not sure why.  Seems better.
2113                                         if (cmp->team != wp->team) {
2114                                                 detonate_nearby_missiles(cmp);
2115                                                 //nprintf(("AI", "Frame %i: Weapon %i hit cmeasure, will die!\n", Framecount, wp-Weapons));
2116                                                 return;
2117                                         }
2118                                 }
2119                         }
2120
2121                         fov = 0.8f;
2122                         if (wip->fov > 0.8f)
2123                                 fov = wip->fov;
2124
2125                         int pick_homing_point = 0;
2126                         if ( IS_VEC_NULL(&wp->homing_pos) ) {
2127                                 pick_homing_point = 1;
2128                         }
2129
2130                         //      Update homing position if it hasn't been set, you're within 500 meters, or every half second, approximately.
2131                         //      For large objects, don't lead them.
2132                         if (hobjp->radius < 40.0f) {
2133                                 target_pos = hobjp->pos;
2134                                 wp->homing_pos = target_pos;
2135                         } else if ( pick_homing_point || (dist < 500.0f) || (rand_chance(flFrametime, 2.0f)) ) {
2136
2137                                 if (hobjp->type == OBJ_SHIP) {
2138                                         if ( !pick_homing_point ) {
2139                                                 // ensure that current attack point is only updated in world coords (ie not pick a different vertex)
2140                                                 wp->pick_big_attack_point_timestamp = 0;
2141                                         }
2142
2143                                         if ( pick_homing_point ) {
2144                                                 // If *any* player is parent of homing missile, then use position where lock indicator is
2145                                                 if ( Objects[obj->parent].flags & OF_PLAYER_SHIP ) {
2146                                                         player *pp;
2147
2148                                                         // determine the player
2149                                                         pp = Player;
2150                                                         if ( Game_mode & GM_MULTIPLAYER ) {
2151                                                                 int pnum;
2152
2153                                                                 pnum = multi_find_player_by_object( &Objects[obj->parent] );
2154                                                                 if ( pnum != -1 ){
2155                                                                         pp = Net_players[pnum].player;
2156                                                                 }
2157                                                         }
2158
2159                                                         // If player has apect lock, we don't want to find a homing point on the closest
2160                                                         // octant... setting the timestamp to 0 ensures this.
2161                                                         if (wip->wi_flags & WIF_HOMING_ASPECT) {
2162                                                                 wp->pick_big_attack_point_timestamp = 0;
2163                                                         } else {
2164                                                                 wp->pick_big_attack_point_timestamp = 1;
2165                                                         }
2166
2167                                                         if ( pp && pp->locking_subsys ) {
2168                                                                 wp->big_attack_point = pp->locking_subsys->system_info->pnt;
2169                                                         } else {
2170                                                                 vm_vec_zero(&wp->big_attack_point);
2171                                                         }
2172                                                 }
2173                                         }
2174
2175                                         ai_big_pick_attack_point(hobjp, obj, &target_pos, fov);
2176
2177                                 } else {
2178                                         target_pos = hobjp->pos;
2179                                 }
2180
2181                                 wp->homing_pos = target_pos;
2182                                 SDL_assert( !vm_is_vec_nan(&wp->homing_pos) );
2183                                 // nprintf(("AI", "Attack point = %7.3f %7.3f %7.3f\n", target_pos.xyz.x, target_pos.xyz.y, target_pos.xyz.z));
2184                         } else
2185                                 target_pos = wp->homing_pos;
2186                 }
2187
2188                 //      Couldn't find a lock.
2189                 if (IS_VEC_NULL(&target_pos))
2190                         return;
2191
2192                 //      Cause aspect seeking weapon to home at target's predicted position.
2193                 //      But don't use predicted position if dot product small or negative.
2194                 //      If do this, with a ship headed towards missile, could choose a point behind missile.``1
2195                 float   dist_to_target, time_to_target;
2196                 
2197                 dist_to_target = vm_vec_normalized_dir(&vec_to_goal, &target_pos, &obj->pos);
2198                 time_to_target = dist_to_target/wip->max_speed;
2199
2200                 vector  tvec;
2201                 tvec = obj->phys_info.vel;
2202                 vm_vec_normalize(&tvec);
2203
2204                 old_dot = vm_vec_dot(&tvec, &vec_to_goal);
2205
2206                 //      If a weapon has missed its target, detonate it.
2207                 //      This solves the problem of a weapon circling the center of a subsystem that has been blown away.
2208                 //      Problem: It does not do impact damage, just proximity damage.
2209                 if ((dist_to_target < flFrametime * obj->phys_info.speed * 4.0f + 10.0f) && (old_dot < 0.0f)) {
2210                         int kill_missile = TRUE;
2211                         if (wp->homing_object) {
2212                                 if (wp->homing_object->type == OBJ_SHIP) {
2213                                         ship *shipp = &Ships[wp->homing_object->instance];
2214                                         if (Ship_info[shipp->ship_info_index].flags & SIF_DONT_COLLIDE_INVIS) {
2215                                                 kill_missile = FALSE;
2216                                         }
2217                                 }
2218                         }
2219                         
2220                         if (kill_missile && (wp->lifeleft > 0.01f)) {
2221                                 wp->lifeleft = 0.01f;
2222                         }
2223                 }
2224
2225                 //      Only lead target if more than one second away.  Otherwise can miss target.  I think this
2226                 //      is what's causing Harbingers to miss the super destroyer. -- MK, 4/15/98
2227                 if ((wip->wi_flags & WIF_HOMING_ASPECT) && (old_dot > 0.1f) && (time_to_target > 0.1f))
2228                         vm_vec_scale_add2(&target_pos, &hobjp->phys_info.vel, min(time_to_target, 2.0f));
2229
2230                 //nprintf(("AI", "Dot = %7.3f, dist = %7.3f, time_to = %6.3f, deg/sec = %7.3f\n", old_dot, dist_to_target, time_to_target, angles/flFrametime));
2231
2232                 // nprintf(("AI", "Weapon %i, lifeleft = %7.3f, dist = %7.3f, dot = %6.3f\n", num, Weapons[num].lifeleft, vm_vec_dist_quick(&obj->pos, &Weapons[num].homing_object->pos), old_dot));
2233
2234                 //      If a HEAT seeking (rather than ASPECT seeking) homing missile, verify that target is in viewcone.
2235                 if (wip->wi_flags & WIF_HOMING_HEAT) {
2236                         if ((old_dot < wip->fov) && (dist_to_target > wip->inner_radius*1.1f)) {        //      Delay finding new target one frame to allow detonation.
2237                                 find_homing_object(obj, num);
2238                                 return;                 //      Maybe found a new homing object.  Return, process more next frame.
2239                         } else  //      Subtract out life based on how far from target this missile points.
2240                                 if (wip->fov < 0.95f) {
2241                                         wp->lifeleft -= flFrametime * (0.95f - old_dot);
2242                                         //Should only happen when time is compressed.
2243                                         //if (flFrametime * (1.0f - old_dot) > 1.0f)
2244                                         //      Int3();
2245                                 }
2246                 } else if (wip->wi_flags & WIF_HOMING_ASPECT) { //      subtract life as if max turn is 90 degrees.
2247                         if (wip->fov < 0.95f)
2248                                 wp->lifeleft -= flFrametime * (0.95f - old_dot);
2249                 } else
2250                         SDL_assert(0);  //      Hmm, a homing missile, but not aspect or heat?
2251
2252
2253                 //      Control speed based on dot product to goal.  If close to straight ahead, move
2254                 //      at max speed, else move slower based on how far from ahead.
2255                 if (old_dot < 0.90f) {
2256                         obj->phys_info.speed = max(0.2f, old_dot* (float) fabs(old_dot));
2257                         if (obj->phys_info.speed < wip->max_speed*0.75f)
2258                                 obj->phys_info.speed = wip->max_speed*0.75f;
2259                 } else
2260                         obj->phys_info.speed = wip->max_speed;
2261
2262                 //      For first second of weapon's life, it doesn't fly at top speed.  It ramps up.
2263                 if (Missiontime - wp->creation_time < i2f(1)) {
2264                         float   t;
2265
2266                         t = f2fl(Missiontime - wp->creation_time);
2267                         obj->phys_info.speed *= t*t;
2268                 }
2269
2270                 SDL_assert( obj->phys_info.speed > 0.0f );
2271
2272                 vm_vec_copy_scale( &obj->phys_info.desired_vel, &obj->orient.v.fvec, obj->phys_info.speed);
2273
2274                 // turn the missile towards the target only if non-swarm.  Homing swarm missiles choose
2275                 // a different vector to turn towards, this is done in swarm_update_direction().
2276 //              if ( !(wip->wi_flags & WIF_SWARM) ) {
2277                 if ( wp->swarm_index < 0 ) {
2278                         // nprintf(("AI", "Dot, dist = %7.3f, %7.3f, target pos = %7.3f %7.3f %7.3f\n", old_dot, vm_vec_dist_quick(&obj->pos, &target_pos), target_pos.xyz.x, target_pos.xyz.y, target_pos.xyz.z));
2279                         ai_turn_towards_vector(&target_pos, obj, frame_time, wip->turn_time, NULL, NULL, 0.0f, 0, NULL);
2280                         vel = vm_vec_mag(&obj->phys_info.desired_vel);
2281
2282                         vm_vec_copy_scale(&obj->phys_info.desired_vel, &obj->orient.v.fvec, vel);
2283
2284                 }
2285
2286 /*              //      If this weapon shot past its target, make it detonate.
2287                 if ((old_dot < 0.0f) && (dist_to_target < 50.0f)) {
2288                         if (wp->lifeleft > 0.01f)
2289                                 wp->lifeleft = 0.01f;
2290                 }
2291 */      }
2292 }
2293
2294 // as Mike K did with ships -- break weapon into process_pre and process_post for code to execute
2295 // before and after physics movement
2296
2297 void weapon_process_pre( object *obj, float frame_time)
2298 {
2299         // if the object is a corkscrew style weapon, process it now
2300         if((obj->type == OBJ_WEAPON) && (Weapons[obj->instance].cscrew_index >= 0)){
2301                 cscrew_process_pre(obj);
2302         }
2303
2304         // if the weapon is a flak weapon, maybe detonate it early
2305         if((obj->type == OBJ_WEAPON) && (Weapon_info[Weapons[obj->instance].weapon_info_index].wi_flags & WIF_FLAK) && (Weapons[obj->instance].flak_index >= 0)){
2306                 flak_maybe_detonate(obj);               
2307         }
2308 }
2309
2310 int     Homing_hits = 0, Homing_misses = 0;
2311
2312
2313 MONITOR( NumWeapons );  
2314
2315 // maybe play a "whizz sound" if close enough to view position
2316 void weapon_maybe_play_flyby_sound(object *weapon_objp, weapon *wp)
2317 {       
2318         // do a quick out if not a laser
2319         if ( Weapon_info[wp->weapon_info_index].subtype != WP_LASER ) {
2320                 return;
2321         }
2322
2323         // don't play flyby sounds too close together
2324         if ( !timestamp_elapsed(Weapon_flyby_sound_timer) ) {
2325                 return;
2326         }
2327
2328         if ( !(wp->weapon_flags & WF_PLAYED_FLYBY_SOUND) && (wp->weapon_flags & WF_CONSIDER_FOR_FLYBY_SOUND) ) {
2329                 float           dist, dot, radius;
2330
2331                 dist = vm_vec_dist_quick(&weapon_objp->pos, &Eye_position);
2332
2333                 if ( Viewer_obj ) {
2334                         radius = Viewer_obj->radius;
2335                 } else {
2336                         radius = 0.0f;
2337                 }
2338
2339                 if ( (dist > radius) && (dist < 55) ) {
2340                         vector  vec_to_weapon;
2341
2342                         vm_vec_sub(&vec_to_weapon, &weapon_objp->pos, &Eye_position);
2343                         vm_vec_normalize(&vec_to_weapon);
2344
2345                         // ensure laser is in front of eye
2346                         dot = vm_vec_dot(&vec_to_weapon, &Eye_matrix.v.fvec);
2347                         if ( dot < 0.1 ) {
2348                                 return;
2349                         }
2350
2351                         // ensure that laser is moving in similar direction to fvec
2352                         dot = vm_vec_dot(&vec_to_weapon, &weapon_objp->orient.v.fvec);
2353                         
2354 //                      nprintf(("Alan", "Weapon dot: %.2f\n", dot));
2355                         if ( (dot < -0.80) && (dot > -0.98) ) {
2356                                 snd_play_3d( &Snds[SND_WEAPON_FLYBY], &weapon_objp->pos, &Eye_position );
2357                                 Weapon_flyby_sound_timer = timestamp(200);
2358                                 wp->weapon_flags |= WF_PLAYED_FLYBY_SOUND;
2359                         }
2360                 }
2361         }
2362 }
2363
2364 // process a weapon after physics movement.  MWA reorders some of the code on 8/13 for multiplayer.  When
2365 // adding something to this function, decide whether or not a client in a multiplayer game needs to do
2366 // what is normally done in a single player game.  Things like plotting an object on a radar, effect
2367 // for exhaust are things that are done on all machines.  Things which calculate weapon targets, new
2368 // velocities, etc, are server only functions and should go after the if ( !MULTIPLAYER_MASTER ) statement
2369 // See Allender if you cannot decide what to do.
2370 void weapon_process_post(object * obj, float frame_time)
2371 {
2372         int                     num;    
2373         weapon_info     *wip;
2374         weapon          *wp;
2375
2376         MONITOR_INC( NumWeapons, 1 );   
2377         
2378         SDL_assert(obj->type == OBJ_WEAPON);
2379
2380         num = obj->instance;
2381
2382 #ifndef NDEBUG
2383         int objnum = OBJ_INDEX(obj);
2384         SDL_assert( Weapons[num].objnum == objnum );
2385 #endif
2386
2387         wp = &Weapons[num];
2388
2389         wp->lifeleft -= frame_time;
2390         wip = &Weapon_info[wp->weapon_info_index];
2391
2392         // check life left.  Multiplayer client code will go through here as well.  We must be careful in weapon_hit
2393         // when killing a missile that spawn child weapons!!!!
2394         if ( wp->lifeleft < 0.0f ) {
2395                 if ( wip->subtype & WP_MISSILE ) {
2396                         if(Game_mode & GM_MULTIPLAYER){                         
2397                                 if ( !MULTIPLAYER_CLIENT || (MULTIPLAYER_CLIENT && (wp->lifeleft < -2.0f)) || (MULTIPLAYER_CLIENT && (wip->wi_flags & WIF_CHILD))) {                                    // don't call this function multiplayer client -- host will send this packet to us
2398                                         // nprintf(("AI", "Frame %i: Weapon %i detonated, dist = %7.3f!\n", Framecount, obj-Objects));
2399                                         weapon_detonate(obj);                                   
2400                                 }
2401                         } else {
2402                                 // nprintf(("AI", "Frame %i: Weapon %i detonated, dist = %7.3f!\n", Framecount, obj-Objects));
2403                                 weapon_detonate(obj);                                                                   
2404                         }
2405                         if (wip->wi_flags & WIF_HOMING) {
2406                                 Homing_misses++;
2407                                 // nprintf(("AI", "Miss!  Hits = %i/%i\n", Homing_hits, (Homing_hits + Homing_misses)));
2408                         }
2409                 } else {
2410                         obj->flags |= OF_SHOULD_BE_DEAD;
2411 //                      demo_do_flag_dead(OBJ_INDEX(obj));
2412                 }
2413
2414                 return;
2415         }
2416
2417         // plot homing missiles on the radar
2418         if (wip->wi_flags & WIF_HOMING) {
2419                 if ( hud_gauge_active(HUD_RADAR) ) {
2420                         radar_plot_object( obj );
2421                 }
2422         }
2423
2424         // trail missiles
2425         if ((wip->wi_flags & WIF_TRAIL) && !(wip->wi_flags & WIF_CORKSCREW)) {
2426                 if ( wp->trail_num > -1 )       {
2427                         if (trail_stamp_elapsed(wp->trail_num)) {
2428
2429                                 trail_add_segment( wp->trail_num, &obj->pos );
2430                                 
2431                                 trail_set_stamp(wp->trail_num);
2432                         } else {
2433                                 trail_set_segment( wp->trail_num, &obj->pos );
2434                         }
2435
2436                 }
2437         }
2438
2439         if ( wip->wi_flags & WIF_THRUSTER )     {
2440                 ship_do_weapon_thruster_frame( wp, obj, flFrametime );  
2441         }
2442
2443         // maybe play a "whizz sound" if close enough to view position
2444         #ifndef NDEBUG
2445         if ( Weapon_flyby_sound_enabled ) {
2446                 weapon_maybe_play_flyby_sound(obj, wp);
2447         }
2448         #else
2449                 weapon_maybe_play_flyby_sound(obj, wp);
2450         #endif  
2451         
2452         //      If our target is still valid, then update some info.
2453         if (wp->target_num != -1) {
2454                 if (Objects[wp->target_num].signature == wp->target_sig) {
2455                         float           cur_dist;
2456                         vector  v0;
2457
2458                         vm_vec_avg(&v0, &obj->pos, &obj->last_pos);
2459
2460                         cur_dist = vm_vec_dist_quick(&v0, &Objects[wp->target_num].pos);
2461
2462                         if (cur_dist < wp->nearest_dist) {
2463                                 wp->nearest_dist = cur_dist;
2464                         } else if (cur_dist > wp->nearest_dist + 1.0f) {
2465                                 float           dot;
2466                                 vector  tvec;
2467                                 ai_info *parent_aip;
2468                         //      float           lead_scale = 0.0f;
2469
2470                                 parent_aip = NULL;
2471                                 if (obj->parent != Player_obj-Objects) {
2472                                         parent_aip = &Ai_info[Ships[Objects[obj->parent].instance].ai_index];
2473                                 //      lead_scale = parent_aip->lead_scale;
2474                                 }
2475
2476                                 vm_vec_normalized_dir(&tvec, &v0, &Objects[wp->target_num].pos);
2477                                 dot = vm_vec_dot(&tvec, &Objects[wp->target_num].orient.v.fvec);
2478                                 // nprintf(("AI", "Miss dot = %7.3f, dist = %7.3f, lead_scale = %7.3f\n", dot, cur_dist, lead_scale));
2479                                 wp->target_num = -1;
2480
2481                                 //      Learn!  If over-shooting or under-shooting, compensate.
2482                                 //      Really need to compensate for left/right errors.  This does no good against someone circling
2483                                 //      in a plane perpendicular to the attacker's forward vector.
2484                                 if (parent_aip != NULL) {
2485                                         if (cur_dist > 100.0f)
2486                                                 parent_aip->lead_scale = 0.0f;
2487
2488                                         if (dot < -0.1f){
2489                                                 parent_aip->lead_scale += cur_dist/2000.0f;
2490                                         } else if (dot > 0.1f) {
2491                                                 parent_aip->lead_scale -= cur_dist/2000.0f;
2492                                         }
2493                                         
2494                                         if (fl_abs(parent_aip->lead_scale) > 1.0f){
2495                                                 parent_aip->lead_scale *= 0.9f;
2496                                         }
2497                                 }
2498                         }
2499                 }
2500         }
2501
2502         if(wip->wi_flags & WIF_PARTICLE_SPEW){
2503                 weapon_maybe_spew_particle(obj);
2504         }
2505
2506         // a single player or multiplayer server function -- it affects actual weapon movement.
2507         if (wip->wi_flags & WIF_HOMING) {
2508                 weapon_home(obj, num, frame_time);
2509
2510 /*              if (wip->wi_flags & WIF_BOMB) {
2511                         if (wip->lifetime - obj->lifeleft < 1.0f) {
2512                                 
2513                         }
2514                 }
2515 */              
2516                 // If this is a swarm type missile, 
2517 //              if ( wip->wi_flags & WIF_SWARM ) 
2518                 if ( wp->swarm_index >= 0 ) {
2519                         swarm_update_direction(obj, frame_time);
2520                 }
2521
2522                 if( wp->cscrew_index >= 0) {
2523                         cscrew_process_post(obj);                       
2524                 }
2525         }
2526 }
2527
2528 //      Update weapon tracking information.
2529 void weapon_set_tracking_info(int weapon_objnum, int parent_objnum, int target_objnum, int target_is_locked, ship_subsys *target_subsys)
2530 {
2531         int                     ai_index;
2532         object          *parent_objp;
2533         weapon          *wp;
2534         weapon_info     *wip;
2535         int targeting_same = 0;
2536
2537         if ( weapon_objnum < 0 ) {
2538                 return;
2539         }
2540
2541         SDL_assert(Objects[weapon_objnum].type == OBJ_WEAPON);
2542
2543         wp = &Weapons[Objects[weapon_objnum].instance];
2544         wip = &Weapon_info[wp->weapon_info_index];
2545         parent_objp = &Objects[parent_objnum];
2546
2547         SDL_assert(parent_objp->type == OBJ_SHIP);
2548         ai_index = Ships[parent_objp->instance].ai_index;
2549
2550         if ( ai_index >= 0 ) {
2551                 int target_team = -1;
2552                 if ( target_objnum >= 0 ) {
2553                         int obj_type = Objects[target_objnum].type;
2554                         if ( (obj_type == OBJ_SHIP) || (obj_type == OBJ_WEAPON) ) {
2555                                 target_team = obj_team(&Objects[target_objnum]);
2556                         }
2557                 }
2558         
2559                 // determining if we're targeting the same team
2560                 if(Ships[parent_objp->instance].team == target_team){
2561                         targeting_same = 1;
2562                 } else {
2563                         targeting_same = 0;
2564                 }
2565
2566                 if ((target_objnum != -1) && (!targeting_same || ((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_DOGFIGHT) && (target_team == TEAM_TRAITOR))) ) {
2567                         wp->target_num = target_objnum;
2568                         wp->target_sig = Objects[target_objnum].signature;
2569                         wp->nearest_dist = 99999.0f;
2570                         if ( (wip->wi_flags & WIF_HOMING_ASPECT) && target_is_locked) {
2571                                 wp->homing_object = &Objects[target_objnum];
2572                                 wp->homing_subsys = target_subsys;
2573                                 weapon_maybe_play_warning(wp);
2574                         } else if ( wip->wi_flags & WIF_HOMING_HEAT ) {
2575                                 //      Make a heat seeking missile try to home.  If the target is outside the view cone, it will
2576                                 //      immediately drop it and try to find one in its view cone.
2577                                 if (target_objnum != -1) {
2578                                         wp->homing_object = &Objects[target_objnum];
2579                                         weapon_maybe_play_warning(wp);
2580                                 } else
2581                                         wp->homing_object = &obj_used_list;
2582
2583                                 wp->homing_subsys = target_subsys;
2584                         }
2585                 } else {
2586                         wp->target_num = -1;
2587                         wp->target_sig = -1;
2588                 }
2589
2590                 //      If missile is locked on target, increase its lifetime by 20% since missiles can be fired at limit of range
2591                 //      as defined by velocity*lifeleft, but missiles often slow down a bit, plus can be fired at a moving away target.
2592                 //      Confusing to many players when their missiles run out of gas before getting to target.  
2593                 // DB - removed 7:14 pm 9/6/99. was totally messing up lifetimes for all weapons.
2594                 //      MK, 7:11 am, 9/7/99.  Put it back in, but with a proper check here to make sure it's an aspect seeker and
2595                 //      put a sanity check in the color changing laser code that was broken by this code.
2596                 if (target_is_locked && (wp->target_num != -1) && (wip->wi_flags & WIF_HOMING_ASPECT) ) {
2597                         wp->lifeleft *= 1.2f;
2598                 }
2599
2600                 ai_update_danger_weapon(target_objnum, weapon_objnum);          
2601         }
2602 }
2603
2604
2605 // weapon_create() will create a weapon object
2606 //
2607 // Returns:  index of weapon in the Objects[] array, -1 if the weapon object was not created
2608 int Weapons_created = 0;
2609 int weapon_create( vector * pos, matrix * orient, int weapon_id, int parent_objnum, int secondary_flag, int group_id, int is_locked )
2610 {
2611         int                     n, objnum;
2612         int num_deleted;
2613         object          *objp, *parent_objp;
2614         weapon          *wp;
2615         weapon_info     *wip;
2616
2617         SDL_assert(weapon_id >= 0 && weapon_id < Num_weapon_types);
2618
2619         // beam weapons should never come through here!
2620         SDL_assert(!(Weapon_info[weapon_id].wi_flags & WIF_BEAM));
2621
2622         num_deleted = 0;
2623         if (Num_weapons >= MAX_WEAPONS-5) {
2624
2625                 //No, do remove for AI ships -- MK, 3/12/98  // don't need to try and delete weapons for ai ships
2626                 //if ( !(Objects[parent_objnum].flags & OF_PLAYER_SHIP) )
2627                 //      return -1;
2628
2629                 num_deleted = collide_remove_weapons();
2630                 nprintf(("WARNING", "Deleted %d weapons because of lack of slots\n", num_deleted));
2631                 if (num_deleted == 0){
2632                         return -1;
2633                 }
2634         }
2635
2636         for (n=0; n<MAX_WEAPONS; n++ ){
2637                 if (Weapons[n].weapon_info_index < 0){
2638                         break;
2639                 }
2640         }
2641
2642         if (n == MAX_WEAPONS) {
2643                 // if we supposedly deleted weapons above, what happened here!!!!
2644                 if (num_deleted){
2645                         Int3();                         // get allender -- something funny is going on!!!
2646                 }
2647
2648                 return -1;
2649         }
2650
2651         Weapons_created++;
2652         objnum = obj_create( OBJ_WEAPON, parent_objnum, n, orient, pos, 2.0f, OF_RENDERS | OF_COLLIDES | OF_PHYSICS );
2653         SDL_assert(objnum >= 0);
2654         SDL_assert(First_secondary_index != -1);
2655         objp = &Objects[objnum];
2656
2657         parent_objp = NULL;
2658         if(parent_objnum >= 0){
2659                 parent_objp = &Objects[parent_objnum];
2660         }
2661
2662         // Create laser n!
2663         wp = &Weapons[n];
2664         wip = &Weapon_info[weapon_id];
2665
2666         // check if laser or dumbfire missile
2667         // set physics flag to allow optimization
2668         if ((wip->subtype == WP_LASER) || ((wip->subtype == WP_MISSILE) && !(wip->wi_flags & WIF_HOMING))) {
2669                 // set physics flag
2670                 objp->phys_info.flags |= PF_CONST_VEL;
2671         }
2672
2673         wp->weapon_info_index = weapon_id;
2674         wp->lifeleft = wip->lifetime;
2675
2676         wp->objnum = objnum;
2677         wp->homing_object = &obj_used_list;             //      Assume not homing on anything.
2678         wp->homing_subsys = NULL;
2679         wp->creation_time = Missiontime;
2680         wp->group_id = group_id;
2681
2682         // we don't necessarily need a parent
2683         if(parent_objp != NULL){
2684                 SDL_assert(parent_objp->type == OBJ_SHIP);      //      Get Mike, a non-ship has fired a weapon!
2685                 SDL_assert((parent_objp->instance >= 0) && (parent_objp->instance < MAX_SHIPS));
2686                 wp->team = Ships[parent_objp->instance].team;
2687                 wp->species = Ship_info[Ships[parent_objp->instance].ship_info_index].species;
2688         } else {
2689                 wp->team = 0;
2690                 wp->species = 0;
2691         }
2692         wp->turret_subsys = NULL;
2693         vm_vec_zero(&wp->homing_pos);
2694         wp->weapon_flags = 0;
2695         wp->target_sig = -1;
2696         wp->cmeasure_ignore_objnum = -1;
2697         wp->cmeasure_chase_objnum = -1;
2698
2699         // Init the thruster info
2700         wp->thruster_bitmap = -1;
2701         wp->thruster_frame = 0.0f;
2702         wp->thruster_glow_bitmap = -1;
2703         wp->thruster_glow_noise = 1.0f;
2704         wp->thruster_glow_frame = 0.0f;
2705
2706         if ( wip->wi_flags & WIF_SWARM ) {
2707                 wp->swarm_index = (short)swarm_create();
2708         } else {
2709                 wp->swarm_index = -1;
2710         }               
2711
2712         // if this is a particle spewing weapon, setup some stuff
2713         if(wip->wi_flags & WIF_PARTICLE_SPEW){
2714                 wp->particle_spew_time = -1;            
2715         }
2716
2717         // assign the network signature.  The starting sig is sent to all clients, so this call should
2718         // result in the same net signature numbers getting assigned to every player in the game
2719         if ( Game_mode & GM_MULTIPLAYER ) {
2720                 if(wip->subtype == WP_MISSILE){
2721                         Objects[objnum].net_signature = multi_assign_network_signature( MULTI_SIG_NON_PERMANENT );
2722
2723                         // for weapons that respawn, add the number of respawnable weapons to the net signature pool
2724                         // to reserve N signatures for the spawned weapons
2725                         if ( wip->wi_flags & WIF_SPAWN ){
2726                                 multi_set_network_signature( (ushort)(Objects[objnum].net_signature + wip->spawn_count), MULTI_SIG_NON_PERMANENT );
2727                         }
2728                 } else {
2729                         Objects[objnum].net_signature = multi_assign_network_signature( MULTI_SIG_NON_PERMANENT );
2730                 }
2731                 // for multiplayer clients, when creating lasers, add some more life to the lasers.  This helps
2732                 // to overcome some problems associated with lasers dying on client machine before they get message
2733                 // from server saying it hit something.
2734                 // removed 1/13/98 -- MWA if ( MULTIPLAYER_CLIENT && (wip->subtype == WP_LASER) )
2735                 //      removed 1/13/98 -- MWA  wp->lifeleft += 1.5f;
2736         }
2737
2738         //      Make remote detonate missiles look like they're getting detonated by firer simply by giving them variable lifetimes.
2739         if (!(Objects[parent_objnum].flags & OF_PLAYER_SHIP) && (wip->wi_flags & WIF_REMOTE)) {
2740                 float rand_val;
2741
2742                 if ( Game_mode & GM_NORMAL ){
2743                         rand_val = frand();
2744                 } else {
2745                         rand_val = static_randf(Objects[objnum].net_signature);
2746                 }
2747
2748                 wp->lifeleft = wp->lifeleft/2.0f + rand_val * wp->lifeleft/2.0f;
2749         }
2750
2751         objp->phys_info.mass = wip->mass;
2752         objp->phys_info.side_slip_time_const = 0.0f;
2753         objp->phys_info.rotdamp = 0.0f;
2754         vm_vec_zero(&objp->phys_info.max_vel);
2755         objp->phys_info.max_vel.xyz.z = wip->max_speed;
2756         vm_vec_zero(&objp->phys_info.max_rotvel);
2757         objp->shields[0] = wip->damage;
2758         if (wip->wi_flags & WIF_BOMB){
2759                 objp->hull_strength = 50.0f;
2760         } else {
2761                 objp->hull_strength = 0.0f;
2762         }
2763
2764         if ( wip->subtype == WP_MISSILE ){
2765                 objp->radius = model_get_radius(wip->model_num);
2766         } else if ( wip->subtype == WP_LASER ) {
2767                 objp->radius = wip->laser_head_radius;
2768         }
2769
2770         //      Set desired velocity and initial velocity.
2771         //      For lasers, velocity is always the same.
2772         //      For missiles, it is a small amount plus the firing ship's velocity.
2773         //      For missiles, the velocity trends towards some goal.
2774         //      Note: If you change how speed works here, such as adding in speed of parent ship, you'll need to change the AI code
2775         //      that predicts collision points.  See Mike Kulas or Dave Andsager.  (Or see ai_get_weapon_speed().)
2776         if (!(wip->wi_flags & WIF_HOMING)) {
2777                 vm_vec_copy_scale(&objp->phys_info.desired_vel, &objp->orient.v.fvec, objp->phys_info.max_vel.xyz.z );
2778                 objp->phys_info.vel = objp->phys_info.desired_vel;
2779                 objp->phys_info.speed = vm_vec_mag(&objp->phys_info.desired_vel);
2780         } else {                
2781                 //      For weapons that home, set velocity to sum of forward component of parent's velocity and 1/4 weapon's max speed.
2782                 //      Note that it is important to extract the forward component of the parent's velocity to factor out sliding, else
2783                 //      the missile will not be moving forward.
2784                 if(parent_objp != NULL){
2785                         vm_vec_copy_scale(&objp->phys_info.desired_vel, &objp->orient.v.fvec, vm_vec_dot(&parent_objp->phys_info.vel, &parent_objp->orient.v.fvec) + objp->phys_info.max_vel.xyz.z/4 );
2786                 } else {
2787                         vm_vec_copy_scale(&objp->phys_info.desired_vel, &objp->orient.v.fvec, objp->phys_info.max_vel.xyz.z/4 );
2788                 }
2789                 objp->phys_info.vel = objp->phys_info.desired_vel;
2790                 objp->phys_info.speed = vm_vec_mag(&objp->phys_info.vel);
2791         }
2792
2793         // create the corkscrew
2794         if ( wip->wi_flags & WIF_CORKSCREW ) {
2795                 wp->cscrew_index = (short)cscrew_create(objp);
2796         } else {
2797                 wp->cscrew_index = -1;
2798         }
2799
2800         // if this is a flak weapon shell, make it so
2801         // NOTE : this function will change some fundamental things about the weapon object
2802         if ( wip->wi_flags & WIF_FLAK ){
2803                 flak_create(wp);
2804         } else {
2805                 wp->flak_index = -1;
2806         }       
2807
2808         wp->missile_list_index = -1;
2809         // If this is a missile, then add it to the Missile_obj_list
2810         if ( wip->subtype == WP_MISSILE ) {
2811                 wp->missile_list_index = missile_obj_list_add(objnum);
2812         }
2813
2814         if (wip->wi_flags & WIF_TRAIL /*&& !(wip->wi_flags & WIF_CORKSCREW) */) {
2815                 wp->trail_num = trail_create(wip->tr_info);             
2816
2817                 if ( wp->trail_num > -1 )       {
2818                         // Add two segments.  One to stay at launch pos, one to move.
2819                         trail_add_segment( wp->trail_num, &objp->pos );
2820                         trail_add_segment( wp->trail_num, &objp->pos );
2821                 }
2822         }
2823
2824         // Ensure weapon flyby sound doesn't get played for player lasers
2825         if ( parent_objp == Player_obj ) {
2826                 wp->weapon_flags |= WF_PLAYED_FLYBY_SOUND;
2827         }
2828
2829         wp->pick_big_attack_point_timestamp = timestamp(1);
2830
2831         //      Set detail levels for POF-type weapons.
2832         if (Weapon_info[wp->weapon_info_index].model_num != -1) {
2833                 polymodel * pm;
2834                 int     i;
2835                 pm = model_get(Weapon_info[wp->weapon_info_index].model_num);
2836
2837                 for (i=0; i<pm->n_detail_levels; i++){
2838                         pm->detail_depth[i] = (objp->radius*20.0f + 20.0f) * i;
2839                 }
2840         }
2841
2842                 // if the weapon was fired locked
2843         if(is_locked){
2844                 wp->weapon_flags |= WF_LOCKED_WHEN_FIRED;
2845         }
2846
2847         Num_weapons++;
2848         return objnum;
2849 }
2850
2851 //      Spawn child weapons from object *objp.
2852 void spawn_child_weapons(object *objp)
2853 {
2854         int     i;
2855         int     child_id;
2856         int     parent_num;
2857         ushort starting_sig;
2858         weapon  *wp;
2859         weapon_info     *wip;
2860
2861         SDL_assert(objp->type == OBJ_WEAPON);
2862         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_WEAPONS));
2863
2864         wp = &Weapons[objp->instance];
2865         SDL_assert((wp->weapon_info_index >= 0) && (wp->weapon_info_index < MAX_WEAPON_TYPES));
2866         wip = &Weapon_info[wp->weapon_info_index];
2867
2868         child_id = wip->spawn_type;
2869
2870         parent_num = objp->parent;
2871
2872         if ((Objects[parent_num].type != objp->parent_type) || (Objects[parent_num].signature != objp->parent_sig)) {
2873                 mprintf(("Warning: Parent of spawn weapon does not exist.  Not spawning.\n"));
2874                 return;
2875         }
2876
2877         starting_sig = 0;
2878         if ( Game_mode & GM_MULTIPLAYER ) {             
2879                 // get the next network signature and save it.  Set the next usable network signature to be
2880                 // the passed in objects signature + 1.  We "reserved" N of these slots when we created objp
2881                 // for it's spawned children.
2882                 starting_sig = multi_get_next_network_signature( MULTI_SIG_NON_PERMANENT );
2883                 multi_set_network_signature( objp->net_signature, MULTI_SIG_NON_PERMANENT );
2884         }
2885
2886         for (i=0; i<wip->spawn_count; i++) {
2887                 int             weapon_objnum;
2888                 vector  tvec, pos;
2889                 matrix  orient;
2890
2891                 // for multiplayer, use the static randvec functions based on the network signatures to provide
2892                 // the randomness so that it is the same on all machines.
2893                 if ( Game_mode & GM_MULTIPLAYER ){
2894                         static_randvec(objp->net_signature + i, &tvec);
2895                 } else {
2896                         vm_vec_rand_vec_quick(&tvec);
2897                 }
2898                 vm_vec_scale_add(&pos, &objp->pos, &tvec, objp->radius);
2899
2900                 vm_vector_2_matrix(&orient, &tvec, NULL, NULL);
2901                 weapon_objnum = weapon_create(&pos, &orient, child_id, parent_num, 1, -1, wp->weapon_flags & WF_LOCKED_WHEN_FIRED);
2902
2903                 //      Assign a little randomness to lifeleft so they don't all disappear at the same time.
2904                 if (weapon_objnum != -1) {
2905                         float rand_val;
2906
2907                         if ( Game_mode & GM_NORMAL ){
2908                                 rand_val = frand();
2909                         } else {
2910                                 rand_val = static_randf(objp->net_signature + i);
2911                         }
2912
2913                         Weapons[Objects[weapon_objnum].instance].lifeleft *= rand_val*0.4f + 0.8f;
2914                 }
2915
2916         }
2917
2918         // in multiplayer, reset the next network signature to the one that was saved.
2919         if ( Game_mode & GM_MULTIPLAYER ){
2920                 multi_set_network_signature( starting_sig, MULTI_SIG_NON_PERMANENT );
2921         }
2922 }
2923
2924 // -----------------------------------------------------------------------
2925 // weapon_hit_do_sound()
2926 //
2927 // Play a sound effect when a weapon hits a ship
2928 //
2929 // To elimate the "stereo" effect of two lasers hitting at nearly
2930 // the same time, and to reduce the number of sound channels used,
2931 // only play one impact sound if IMPACT_SOUND_DELTA has elapsed
2932 //
2933 // Note: Uses Weapon_impact_timer global for timer variable
2934 //
2935 void weapon_hit_do_sound(object *hit_obj, weapon_info *wip, vector *hitpos)
2936 {
2937         int     is_hull_hit;
2938         float shield_str;
2939
2940         // If non-missiles (namely lasers) expire without hitting a ship, don't play impact sound
2941         if      ( wip->subtype != WP_MISSILE ) {                
2942                 if ( !hit_obj ) {
2943                         // flak weapons make sounds             
2944                         if(wip->wi_flags & WIF_FLAK){
2945                                 snd_play_3d( &Snds[wip->impact_snd], hitpos, &Eye_position );                           
2946                         }
2947                         return;
2948                 }
2949
2950                 switch(hit_obj->type) {
2951                 case OBJ_SHIP:
2952                         // do nothing
2953                         break;
2954
2955                 case OBJ_ASTEROID:
2956                         if ( timestamp_elapsed(Weapon_impact_timer) ) {
2957                                 snd_play_3d( &Snds[wip->impact_snd], hitpos, &Eye_position );
2958                                 Weapon_impact_timer = timestamp(IMPACT_SOUND_DELTA);
2959                         }
2960                         return;
2961                         break;
2962
2963                 default:
2964                         return;
2965                 }
2966         }
2967
2968         if ( hit_obj == NULL ) {
2969                 snd_play_3d( &Snds[wip->impact_snd], hitpos, &Eye_position );
2970                 return;
2971         }
2972
2973         if ( timestamp_elapsed(Weapon_impact_timer) ) {
2974
2975                 is_hull_hit = 1;
2976                 if ( hit_obj->type == OBJ_SHIP ) {
2977                         shield_str = ship_quadrant_shield_strength(hit_obj, hitpos);
2978                 } else {
2979                         shield_str = 0.0f;
2980                 }
2981
2982                 // play a shield hit if shields are above 10% max in this quadrant
2983                 if ( shield_str > 0.1f ) {
2984                         is_hull_hit = 0;
2985                 }
2986
2987                 if ( !is_hull_hit ) {
2988                         // Play a shield impact sound effect
2989                         if ( hit_obj == Player_obj ) {
2990                                 snd_play_3d( &Snds[SND_SHIELD_HIT_YOU], hitpos, &Eye_position );
2991                                 // AL 12-15-97: Add missile impact sound even when shield is hit
2992                                 if ( wip->subtype == WP_MISSILE ) {
2993                                         snd_play_3d( &Snds[SND_PLAYER_HIT_MISSILE], hitpos, &Eye_position);
2994                                 }
2995                         } else {
2996                                 snd_play_3d( &Snds[SND_SHIELD_HIT], hitpos, &Eye_position );
2997                         }
2998                 } else {
2999                         // Play a hull impact sound effect
3000                         switch ( wip->subtype ) {
3001                                 case WP_LASER:
3002                                         if ( hit_obj == Player_obj )
3003                                                 snd_play_3d( &Snds[SND_PLAYER_HIT_LASER], hitpos, &Eye_position );
3004                                         else {
3005                                                 if ( wip->impact_snd != -1 ) {
3006                                                         snd_play_3d( &Snds[wip->impact_snd], hitpos, &Eye_position );
3007                                                 }
3008                                         }
3009                                         break;
3010                                 case WP_MISSILE:
3011                                         if ( hit_obj == Player_obj ) 
3012                                                 snd_play_3d( &Snds[SND_PLAYER_HIT_MISSILE], hitpos, &Eye_position);
3013                                         else {
3014                                                 if ( wip->impact_snd != -1 ) {
3015                                                         snd_play_3d( &Snds[wip->impact_snd], hitpos, &Eye_position );
3016                                                 }
3017                                         }
3018                                         break;
3019                                 default:        
3020                                         nprintf(("Warning","WARNING ==> Cannot determine sound to play for weapon impact\n"));
3021                                         break;
3022                         } // end switch
3023                 }
3024
3025                 Weapon_impact_timer = timestamp(IMPACT_SOUND_DELTA);
3026         }
3027 }
3028
3029 // distrupt any subsystems that fall into damage sphere of this Electronics missile
3030 //
3031 // input:       ship_obj                =>              pointer to ship that holds subsystem
3032 //                              blast_pos       =>              world pos of weapon blast
3033 //                              wi_index                =>              weapon info index of weapon causing blast
3034 void weapon_do_electronics_affect(object *ship_objp, vector *blast_pos, int wi_index)
3035 {
3036         weapon_info                     *wip;
3037         ship                                    *shipp;
3038         ship_subsys                     *ss;
3039         model_subsystem *psub;
3040         vector                          subsys_world_pos;
3041         float                                   dist;
3042
3043         shipp = &Ships[ship_objp->instance];
3044         wip = &Weapon_info[wi_index];
3045
3046         for ( ss = GET_FIRST(&shipp->subsys_list); ss != END_OF_LIST(&shipp->subsys_list); ss = GET_NEXT(ss) ) {
3047                 psub = ss->system_info;
3048
3049                 // convert subsys point to world coords
3050                 vm_vec_unrotate(&subsys_world_pos, &psub->pnt, &ship_objp->orient);
3051                 vm_vec_add2(&subsys_world_pos, &ship_objp->pos);
3052
3053                 // see if subsys point is within damage sphere
3054                 dist = vm_vec_dist_quick(blast_pos, &subsys_world_pos); 
3055                 if ( dist < wip->outer_radius ) {
3056                         ship_subsys_set_disrupted(ss, fl2i(6000.0f + frand()*4000.0f));
3057                 }
3058         }
3059 }
3060
3061 //      ----------------------------------------------------------------------
3062 //      weapon_area_calc_damage()
3063 //
3064 // Calculate teh damage for an object based on the location of an area-effect
3065 // explosion.
3066 //
3067 // input:               objp                    =>              object pointer ship receiving blast effect
3068 //                                      pos                     =>              world pos of blast center
3069 //                                      inner_rad       =>              smallest radius at which full damage is done
3070 //                                      outer_rad       =>              radius at which no damage is done
3071 //                                      max_blast       =>              maximum blast possible from explosion
3072 //                                      max_damage      =>              maximum damage possible from explosion
3073 //                                      blast                   =>              OUTPUT PARAMETER: receives blast value from explosion
3074 //                                      damage          =>              OUTPUT PARAMETER: receives damage value from explosion
3075 //                                      limit                   =>              a limit on the area, needed for shockwave damage
3076 //
3077 //      returns:                no damage occurred      =>              -1
3078 //                                      damage occured                  =>              0
3079 //
3080 int weapon_area_calc_damage(object *objp, vector *pos, float inner_rad, float outer_rad, float max_blast, float max_damage, float *blast, float *damage, float limit)
3081 {
3082         float                   dist, max_dist, min_dist;
3083
3084         // only blast ships and asteroids
3085         if ( (objp->type != OBJ_SHIP) && (objp->type != OBJ_ASTEROID)) {
3086                 return -1;
3087         }
3088
3089         max_dist = objp->radius + outer_rad;
3090         dist = vm_vec_dist_quick(&objp->pos, pos);      
3091         if ( (dist > max_dist) || (dist > (limit+objp->radius)) ) {
3092                 return -1;      // spheres don't intersect at all
3093         }
3094
3095         if ( dist < (inner_rad+objp->radius) ) {
3096                 // damage is maximum within inner radius
3097                 *damage = max_damage;
3098                 *blast = max_blast;
3099         } else {
3100                 float dist_to_outer_rad_squared, total_dist_squared;
3101                 min_dist = dist - objp->radius;
3102                 SDL_assert(min_dist < outer_rad);
3103                 dist_to_outer_rad_squared = (outer_rad-min_dist)*(outer_rad-min_dist);
3104                 total_dist_squared = (inner_rad-outer_rad)*(inner_rad-outer_rad);
3105                 // AL 2-24-98: drop off damage relative to square of distance
3106                 SDL_assert(dist_to_outer_rad_squared <= total_dist_squared);
3107                 *damage = max_damage * dist_to_outer_rad_squared/total_dist_squared;
3108
3109
3110 //              *damage = (min_dist - outer_rad) * max_damage/(inner_rad - outer_rad);
3111                 *blast =  (min_dist - outer_rad) * max_blast /(inner_rad - outer_rad);
3112         }
3113
3114         // nprintf(("AI", "Frame %i: Damage = %7.3f, %7.3f meters away.\n", Framecount, *damage, dist));
3115
3116         return 0;
3117 }
3118
3119 //      ----------------------------------------------------------------------
3120 //      weapon_area_apply_blast()
3121 //
3122 // Apply the blast effects of an explosion to a ship
3123 //
3124 // input:       force_apply_pos =>              world pos of where force is applied to object
3125 //                              ship_obj                                =>              object pointer of ship receiving the blast
3126 //                              blast_pos                       =>              world pos of blast center
3127 //                              blast                                   =>              force of blast
3128 //                              make_shockwave          =>              boolean, whether to create a shockwave or not
3129 //
3130 void weapon_area_apply_blast(vector *force_apply_pos, object *ship_obj, vector *blast_pos, float blast, int make_shockwave)
3131 {
3132         #define SHAKE_CONST 3000
3133         vector          force, vec_blast_to_ship, vec_ship_to_impact;
3134         polymodel               *pm;
3135
3136         // apply blast force based on distance from center of explosion
3137         vm_vec_sub(&vec_blast_to_ship, &ship_obj->pos, blast_pos);
3138         vm_vec_normalize_safe(&vec_blast_to_ship);
3139         vm_vec_copy_scale(&force, &vec_blast_to_ship, blast );
3140
3141
3142         vm_vec_sub(&vec_ship_to_impact, blast_pos, &ship_obj->pos);
3143
3144         pm = model_get(Ships[ship_obj->instance].modelnum);
3145         SDL_assert ( pm != NULL );
3146
3147         if (make_shockwave) {
3148                 physics_apply_shock (&force, blast, &ship_obj->phys_info, &ship_obj->orient, &pm->mins, &pm->maxs, pm->rad);
3149                 if (ship_obj == Player_obj) {
3150                         joy_ff_play_vector_effect(&vec_blast_to_ship, blast * 2.0f);
3151                 }
3152         } else {
3153                 ship_apply_whack( &force, &vec_ship_to_impact, ship_obj);
3154         }
3155 }
3156
3157 //      ----------------------------------------------------------------------
3158 //      weapon_do_area_effect()
3159 //
3160 // Do the area effect for a weapon
3161 //
3162 // input:       wobjp                   =>              object pointer to weapon causing explosion
3163 //                              pos                     =>              world pos of explosion center
3164 //                              other_obj       =>              object pointer to ship that weapon impacted on (can be NULL)
3165 //
3166 void weapon_do_area_effect(object *wobjp, vector *pos, object *other_obj)
3167 {
3168         weapon_info     *wip;
3169         object          *objp;
3170         float                   damage, blast;
3171
3172         wip = &Weapon_info[Weapons[wobjp->instance].weapon_info_index]; 
3173
3174         SDL_assert(wip->inner_radius != 0);
3175
3176         // only blast ships and asteroids
3177         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
3178                 if ( (objp->type != OBJ_SHIP) && (objp->type != OBJ_ASTEROID) ) {
3179                         continue;
3180                 }
3181         
3182                 if ( objp->type == OBJ_SHIP ) {
3183                         // don't blast navbuoys
3184                         if ( ship_get_SIF(objp->instance) & SIF_NAVBUOY ) {
3185                                 continue;
3186                         }
3187                 }
3188
3189                 if ( weapon_area_calc_damage(objp, pos, wip->inner_radius, wip->outer_radius, wip->blast_force, wip->damage, &blast, &damage, wip->outer_radius) == -1 ){
3190                         continue;
3191                 }
3192
3193                 // scale damage
3194                 damage *= weapon_get_damage_scale(wip, wobjp, other_obj);               
3195
3196                 switch ( objp->type ) {
3197                 case OBJ_SHIP:
3198                         ship_apply_global_damage(objp, wobjp, pos, damage);
3199                         weapon_area_apply_blast(NULL, objp, pos, blast, 0);                     
3200                         break;
3201                 case OBJ_ASTEROID:
3202                         asteroid_hit(objp, NULL, NULL, damage);
3203                         break;
3204                 default:
3205                         Int3();
3206                         break;
3207                 }       
3208
3209         }       // end for
3210
3211         // if this weapon has the "Electronics" flag set, then disrupt subsystems in sphere
3212         if ( (other_obj != NULL) && (wip->wi_flags & WIF_ELECTRONICS) ) {
3213                 if ( other_obj->type == OBJ_SHIP ) {
3214                         weapon_do_electronics_affect(other_obj, pos, Weapons[wobjp->instance].weapon_info_index);
3215                 }
3216         }
3217 }
3218
3219
3220 //      ----------------------------------------------------------------------
3221 //      weapon_hit()
3222 //
3223 // This function is called when a weapon hits something (or, in the case of
3224 // missiles explodes for any particular reason)
3225 //
3226 void weapon_hit( object * weapon_obj, object * other_obj, vector * hitpos )
3227 {
3228         SDL_assert(weapon_obj != NULL);
3229         if(weapon_obj == NULL){
3230                 return;
3231         }
3232         SDL_assert((weapon_obj->type == OBJ_WEAPON) && (weapon_obj->instance >= 0) && (weapon_obj->instance < MAX_WEAPONS));
3233         if((weapon_obj->type != OBJ_WEAPON) || (weapon_obj->instance < 0) || (weapon_obj->instance >= MAX_WEAPONS)){
3234                 return;
3235         }
3236
3237         int                     num = weapon_obj->instance;
3238         int                     weapon_type = Weapons[num].weapon_info_index;
3239         weapon_info     *wip;
3240         // int np_index;
3241
3242         SDL_assert((weapon_type >= 0) && (weapon_type < MAX_WEAPONS));
3243         if((weapon_type < 0) || (weapon_type >= MAX_WEAPONS)){
3244                 return;
3245         }
3246         wip = &Weapon_info[weapon_type];
3247
3248         // if this is the player ship, and is a laser hit, skip it. wait for player "pain" to take care of it
3249         // if( ((wip->subtype != WP_LASER) || !MULTIPLAYER_CLIENT) && (Player_obj != NULL) && (other_obj == Player_obj) ){
3250         if((other_obj != Player_obj) || (wip->subtype != WP_LASER) || !MULTIPLAYER_CLIENT){
3251                 weapon_hit_do_sound(other_obj, wip, hitpos);
3252         }
3253
3254         if ( wip->impact_weapon_expl_index > -1 )       {
3255                 int expl_ani_handle = weapon_get_expl_handle(wip->impact_weapon_expl_index, hitpos, wip->impact_explosion_radius);
3256                 particle_create( hitpos, &vmd_zero_vector, 0.0f, wip->impact_explosion_radius, PARTICLE_BITMAP_PERSISTENT, expl_ani_handle );
3257         }
3258
3259         weapon_obj->flags |= OF_SHOULD_BE_DEAD;
3260
3261         int sw_flag = SW_WEAPON;
3262
3263         // check if this is an area effect weapon
3264         if ( wip->wi_flags & WIF_AREA_EFFECT ) {
3265         // if ( wip->subtype & WP_MISSILE && wip->wi_flags & WIF_AREA_EFFECT ) {
3266                 if ( wip->wi_flags & WIF_SHOCKWAVE ) {
3267                         float actual_damage = wip->damage;
3268                         // Shockwaves caused by weapons hitting weapons are 1/4 as powerful
3269                         if ( ((other_obj) && (other_obj->type == OBJ_WEAPON)) || (Weapons[num].weapon_flags & WF_DESTROYED_BY_WEAPON)) {
3270                                 actual_damage /= 4.0f;
3271                                 sw_flag |= SW_WEAPON_KILL;
3272                         }
3273                         shockwave_create_info sci;
3274                         sci.blast = wip->blast_force;
3275                         sci.damage = actual_damage;
3276                         sci.inner_rad = wip->inner_radius;
3277                         sci.outer_rad = wip->outer_radius;
3278                         sci.speed = wip->shockwave_speed;
3279                         sci.rot_angle = 0.0f;
3280
3281                         shockwave_create(OBJ_INDEX(weapon_obj), hitpos, &sci, sw_flag);
3282 //                      snd_play_3d( &Snds[SND_SHOCKWAVE_IMPACT], hitpos, &Eye_position );
3283                 }
3284                 else {
3285                         weapon_do_area_effect(weapon_obj, hitpos, other_obj);
3286                 }
3287         }
3288
3289         // check if this is an EMP weapon
3290         if(wip->wi_flags & WIF_EMP){
3291                 emp_apply(&weapon_obj->pos, wip->inner_radius, wip->outer_radius, wip->emp_intensity, wip->emp_time);
3292         }       
3293
3294         // spawn weapons - note the change from FS 1 multiplayer.
3295         if (wip->wi_flags & WIF_SPAWN){
3296                 spawn_child_weapons(weapon_obj);
3297         }       
3298 }
3299
3300 void weapon_detonate(object *objp)
3301 {
3302         SDL_assert(objp != NULL);
3303         if(objp == NULL){
3304                 return;
3305         }
3306         SDL_assert((objp->type == OBJ_WEAPON) && (objp->instance >= 0));
3307         if((objp->type != OBJ_WEAPON) || (objp->instance < 0)){
3308                 return;
3309         }       
3310
3311         // send a detonate packet in multiplayer
3312         if(MULTIPLAYER_MASTER){
3313                 send_weapon_detonate_packet(objp);
3314         }
3315
3316         // call weapon hit
3317         weapon_hit(objp, NULL, &objp->pos);
3318 }
3319
3320 //      Return the Weapon_info[] index of the weapon with name *name.
3321 int weapon_name_lookup(const char *name)
3322 {
3323         int     i;
3324
3325         for ( i=0; i < Num_weapon_types; i++) {
3326                 if (!SDL_strcasecmp(name, Weapon_info[i].name)) {
3327                         return i;
3328                 }
3329         }
3330
3331         return -1;
3332 }
3333
3334 // Group_id:  If you should quad lasers, they should all have the same group id.  
3335 // This will be used to optimize lighting, since each group only needs to cast one light.
3336 // Call this to get a new group id, then pass it to each weapon_create call for all the
3337 // weapons in the group.   Number will be between 0 and WEAPON_MAX_GROUP_IDS and will
3338 // get reused.
3339 int weapon_create_group_id()
3340 {
3341         static int current_id = 0;
3342
3343         int n = current_id;
3344         
3345         current_id++;
3346         if ( current_id >= WEAPON_MAX_GROUP_IDS )       {
3347                 current_id = 0;
3348         }
3349         return n;
3350 }
3351
3352
3353 void weapons_page_in()
3354 {
3355         int i, j, idx;
3356
3357         // Page in bitmaps for all weapons
3358         for (i=0; i<Num_weapon_types; i++ )     {
3359                 weapon_info *wip = &Weapon_info[i];
3360
3361                 wip->wi_flags &= (~WIF_THRUSTER);               // Assume no thrusters
3362                 
3363                 switch( wip->render_type )      {
3364                         case WRT_POF:
3365                                 {
3366                                         wip->model_num = model_load( wip->pofbitmap_name, 0, NULL );
3367
3368                                         polymodel *pm = model_get( wip->model_num );
3369
3370                                         // If it has a model, and the model pof has thrusters, then set
3371                                         // the flags
3372                                         if ( pm->n_thrusters > 0 )      {
3373                                                 //mprintf(( "Weapon %s has thrusters!\n", wip->name ));
3374                                                 wip->wi_flags |= WIF_THRUSTER;
3375                                         }
3376                 
3377                                         for (j=0; j<pm->n_textures; j++ )       {
3378                                                 int bitmap_num = pm->original_textures[j];
3379
3380                                                 if ( bitmap_num > -1 )  {
3381                                                         bm_page_in_texture( bitmap_num );
3382                                                 }
3383                                         }
3384                                 }
3385                                 break;
3386
3387                         case WRT_LASER:
3388                                 {
3389                                         bm_page_in_texture( wip->laser_bitmap );
3390
3391                                         if(wip->laser_glow_bitmap >= 0){
3392                                                 bm_page_in_texture(wip->laser_glow_bitmap);
3393                                         }
3394                                 }
3395                                 break;
3396
3397                         default:
3398                                 Int3(); // Invalid weapon rendering type.
3399                 }
3400
3401                 // If this has an impact vclip page it in.
3402 //              if ( wip->impact_explosion_ani > -1 )   {
3403 //                      int nframes, fps;
3404 //                      bm_get_info( wip->impact_explosion_ani, NULL, NULL, NULL, &nframes, &fps );
3405 //                      bm_page_in_xparent_texture( wip->impact_explosion_ani, nframes );
3406 //              }
3407
3408                 // trail bitmaps
3409                 if ( (wip->wi_flags & WIF_TRAIL) && (wip->tr_info.bitmap > -1) )        {
3410                         bm_page_in_texture( wip->tr_info.bitmap );
3411                 }
3412
3413                 // if this is a beam weapon, page in its stuff
3414                 if(wip->wi_flags & WIF_BEAM){
3415                         // all beam sections
3416                         for(idx=0; idx<wip->b_info.beam_num_sections; idx++){
3417                                 if((idx < MAX_BEAM_SECTIONS) && (wip->b_info.sections[idx].texture >= 0)){
3418                                         bm_page_in_texture(wip->b_info.sections[idx].texture);
3419                                 }
3420                         }
3421
3422                         // muzzle glow
3423                         if(wip->b_info.beam_glow_bitmap >= 0){
3424                                 bm_page_in_texture(wip->b_info.beam_glow_bitmap);
3425                         }
3426
3427                         // particle ani
3428                         if(wip->b_info.beam_particle_ani >= 0){
3429                                 int nframes, fps;
3430                                 bm_get_info( wip->b_info.beam_particle_ani, NULL, NULL, NULL, &nframes, &fps );
3431                                 bm_page_in_texture( wip->b_info.beam_particle_ani, nframes );
3432                         }
3433                 }
3434         }
3435
3436         // explosion ani's
3437         for (i=0; i<Num_weapon_expl; i++) {
3438                 int bitmap_handle, nframes, fps;
3439
3440                 for (j=0; j<Weapon_expl_info[i].lod_count; j++) {
3441                         //load ani
3442                         bitmap_handle = bm_load_animation(Weapon_expl_info[i].lod[j].filename, &nframes, &fps, 1);
3443                         Weapon_expl_info[i].lod[j].bitmap_id = bitmap_handle;
3444                         Weapon_expl_info[i].lod[j].fps = fps;
3445                         Weapon_expl_info[i].lod[j].num_frames = nframes;
3446
3447                         // page it in
3448                         bm_page_in_xparent_texture(bitmap_handle, nframes);
3449                 }
3450         }
3451
3452         // Counter measures
3453         for (i=0; i<Num_cmeasure_types; i++ )   {
3454                 cmeasure_info *cmeasurep;
3455
3456                 cmeasurep = &Cmeasure_info[i];
3457         
3458                 cmeasurep->model_num = model_load( cmeasurep->pof_name, 0, NULL );
3459
3460                 polymodel *pm = model_get( cmeasurep->model_num );
3461
3462                 for (j=0; j<pm->n_textures; j++ )       {
3463                         int bitmap_num = pm->original_textures[j];
3464
3465                         if ( bitmap_num > -1 )  {
3466                                 bm_page_in_texture( bitmap_num );
3467                         }
3468                 }
3469                 SDL_assert( cmeasurep->model_num > -1 );
3470         }
3471
3472 }
3473
3474 // call to get the "color" of the laser at the given moment (since glowing lasers can cycle colors)
3475 void weapon_get_laser_color(color *c, object *objp)
3476 {
3477         weapon *wep;
3478         weapon_info *winfo;
3479         float pct;
3480
3481         // sanity
3482         if(c == NULL){
3483                 return;
3484         }
3485
3486         // sanity
3487         SDL_assert(objp->type == OBJ_WEAPON);
3488         SDL_assert(objp->instance >= 0);
3489         SDL_assert(Weapons[objp->instance].weapon_info_index >= 0);
3490         if((objp->type != OBJ_WEAPON) || (objp->instance < 0) || (Weapons[objp->instance].weapon_info_index < 0)){
3491                 return;
3492         }
3493         wep = &Weapons[objp->instance];
3494         winfo = &Weapon_info[wep->weapon_info_index];
3495
3496         // if we're a one-color laser
3497         if((winfo->laser_color_2.red == 0) && (winfo->laser_color_2.green == 0) && (winfo->laser_color_2.blue == 0)){
3498                 *c = winfo->laser_color_1;
3499         }
3500
3501         // lifetime pct
3502         pct = 1.0f - (wep->lifeleft / winfo->lifetime);
3503         if(pct > 0.5f){
3504                 pct = 0.5f;
3505         } else if (pct < 0.0f)
3506                 pct = 0.0f;
3507
3508         pct *= 2.0f;
3509         
3510         // otherwise interpolate between the colors
3511         gr_init_color( c, (int)((float)winfo->laser_color_1.red + (((float)winfo->laser_color_2.red - (float)winfo->laser_color_1.red) * pct)), 
3512                                                         (int)((float)winfo->laser_color_1.green + (((float)winfo->laser_color_2.green - (float)winfo->laser_color_1.green) * pct)), 
3513                                                         (int)((float)winfo->laser_color_1.blue + (((float)winfo->laser_color_2.blue - (float)winfo->laser_color_1.blue) * pct)) );
3514 }
3515
3516 // default weapon particle spew data
3517 int Weapon_particle_spew_count = 1;
3518 int Weapon_particle_spew_time = 25;
3519 float Weapon_particle_spew_vel = 0.4f;
3520 float Weapon_particle_spew_radius = 2.0f;
3521 float Weapon_particle_spew_lifetime = 0.15f;
3522 float Weapon_particle_spew_scale = 0.8f;
3523
3524 // for weapons flagged as particle spewers, spew particles. wheee
3525 void weapon_maybe_spew_particle(object *obj)
3526 {
3527         weapon *wp;
3528         int idx;
3529         vector direct, direct_temp, particle_pos;
3530         vector null_vec = ZERO_VECTOR;
3531         vector vel;
3532         float ang;
3533
3534         // check some stuff
3535         SDL_assert(obj->type == OBJ_WEAPON);
3536         SDL_assert(obj->instance >= 0);
3537         SDL_assert(Weapons[obj->instance].weapon_info_index >= 0);
3538         SDL_assert(Weapon_info[Weapons[obj->instance].weapon_info_index].wi_flags & WIF_PARTICLE_SPEW);
3539         
3540         wp = &Weapons[obj->instance];   
3541
3542         // if the weapon's particle timestamp has elapse`d
3543         if((wp->particle_spew_time == -1) || timestamp_elapsed(wp->particle_spew_time)){
3544                 // reset the timestamp
3545                 wp->particle_spew_time = timestamp(Weapon_particle_spew_time);
3546
3547                 // spew some particles
3548                 for(idx=0; idx<Weapon_particle_spew_count; idx++){
3549                         // get the backward vector of the weapon
3550                         direct = obj->orient.v.fvec;
3551                         vm_vec_negate(&direct);
3552
3553                         //      randomly perturb x, y and z
3554                         
3555                         // uvec
3556                         ang = fl_radian(frand_range(-90.0f, 90.0f));
3557                         vm_rot_point_around_line(&direct_temp, &direct, ang, &null_vec, &obj->orient.v.fvec);                   
3558                         direct = direct_temp;
3559                         vm_vec_scale(&direct, Weapon_particle_spew_scale);
3560
3561                         // rvec
3562                         ang = fl_radian(frand_range(-90.0f, 90.0f));
3563                         vm_rot_point_around_line(&direct_temp, &direct, ang, &null_vec, &obj->orient.v.rvec);                   
3564                         direct = direct_temp;
3565                         vm_vec_scale(&direct, Weapon_particle_spew_scale);
3566
3567                         // fvec
3568                         ang = fl_radian(frand_range(-90.0f, 90.0f));
3569                         vm_rot_point_around_line(&direct_temp, &direct, ang, &null_vec, &obj->orient.v.uvec);                   
3570                         direct = direct_temp;
3571                         vm_vec_scale(&direct, Weapon_particle_spew_scale);
3572
3573                         // get a velovity vector of some percentage of the weapon's velocity
3574                         vel = obj->phys_info.vel;
3575                         vm_vec_scale(&vel, Weapon_particle_spew_vel);
3576
3577                         // emit the particle
3578                         vm_vec_add(&particle_pos, &obj->pos, &direct);
3579                         particle_create(&particle_pos, &vel, Weapon_particle_spew_lifetime, Weapon_particle_spew_radius, PARTICLE_SMOKE);
3580                 }
3581         }
3582 }
3583
3584 // debug console functionality
3585 void pspew_display_dcf()
3586 {
3587         dc_printf("Particle spew settings\n\n");
3588         dc_printf("Particle spew count (pspew_count) : %d\n", Weapon_particle_spew_count);
3589         dc_printf("Particle spew time (pspew_time) : %d\n", Weapon_particle_spew_time);
3590         dc_printf("Particle spew velocity (pspew_vel) : %f\n", Weapon_particle_spew_vel);
3591         dc_printf("Particle spew size (pspew_size) : %f\n", Weapon_particle_spew_radius);
3592         dc_printf("Particle spew lifetime (pspew_life) : %f\n", Weapon_particle_spew_lifetime);
3593         dc_printf("Particle spew scale (psnew_scale) : %f\n", Weapon_particle_spew_scale);
3594 }
3595
3596 DCF(pspew_count, "Number of particles spewed at a time")
3597 {       
3598         dc_get_arg(ARG_INT);
3599         if(Dc_arg_type & ARG_INT){
3600                 Weapon_particle_spew_count = Dc_arg_int;
3601         }
3602
3603         pspew_display_dcf();
3604 }
3605
3606 DCF(pspew_time, "Time between particle spews")
3607 {       
3608         dc_get_arg(ARG_INT);
3609         if(Dc_arg_type & ARG_INT){
3610                 Weapon_particle_spew_time = Dc_arg_int;
3611         }
3612
3613         pspew_display_dcf();
3614 }
3615
3616 DCF(pspew_vel, "Relative velocity of particles (0.0 - 1.0)")
3617 {       
3618         dc_get_arg(ARG_FLOAT);
3619         if(Dc_arg_type & ARG_FLOAT){
3620                 Weapon_particle_spew_vel = Dc_arg_float;
3621         }
3622
3623         pspew_display_dcf();
3624 }
3625
3626 DCF(pspew_size, "Size of spewed particles")
3627 {       
3628         dc_get_arg(ARG_FLOAT);
3629         if(Dc_arg_type & ARG_FLOAT){
3630                 Weapon_particle_spew_radius = Dc_arg_float;
3631         }
3632
3633         pspew_display_dcf();
3634 }
3635
3636 DCF(pspew_life, "Lifetime of spewed particles")
3637 {       
3638         dc_get_arg(ARG_FLOAT);
3639         if(Dc_arg_type & ARG_FLOAT){
3640                 Weapon_particle_spew_lifetime = Dc_arg_float;
3641         }
3642
3643         pspew_display_dcf();
3644 }
3645
3646 DCF(pspew_scale, "How far away particles are from the weapon path")
3647 {       
3648         dc_get_arg(ARG_FLOAT);
3649         if(Dc_arg_type & ARG_FLOAT){
3650                 Weapon_particle_spew_scale = Dc_arg_float;
3651         }
3652
3653         pspew_display_dcf();
3654 }
3655
3656 // return a scale factor for damage which should be applied for 2 collisions
3657 float weapon_get_damage_scale(weapon_info *wip, object *wep, object *target)
3658 {
3659 #ifdef MAKE_FS1
3660         // don't do special damage scaling for capships in FS1
3661         return 1.0f;
3662
3663 #else
3664
3665         weapon *wp;
3666         int from_player = 0;
3667         float total_scale = 1.0f;
3668         float hull_pct;
3669         int is_big_damage_ship = 0;
3670
3671         // sanity
3672         if((wip == NULL) || (wep == NULL) || (target == NULL)){
3673                 return 1.0f;
3674         }
3675
3676         // don't scale any damage if its not a weapon   
3677         if((wep->type != OBJ_WEAPON) || (wep->instance < 0) || (wep->instance >= MAX_WEAPONS)){
3678                 return 1.0f;
3679         }
3680         wp = &Weapons[wep->instance];
3681
3682         // was the weapon fired by the player
3683         from_player = 0;
3684         if((wep->parent >= 0) && (wep->parent < MAX_OBJECTS) && (Objects[wep->parent].flags & OF_PLAYER_SHIP)){
3685                 from_player = 1;
3686         }
3687                 
3688         // if this is a lockarm weapon, and it was fired unlocked
3689         if((wip->wi_flags & WIF_LOCKARM) && !(wp->weapon_flags & WF_LOCKED_WHEN_FIRED)){                
3690                 total_scale *= 0.1f;
3691         }
3692
3693         // if the hit object was a ship
3694         if(target->type == OBJ_SHIP){
3695                 ship_info *sip;
3696
3697                 // get some info on the ship
3698                 SDL_assert((target->instance >= 0) && (target->instance < MAX_SHIPS));
3699                 if((target->instance < 0) || (target->instance >= MAX_SHIPS)){
3700                         return total_scale;
3701                 }
3702
3703                 sip = &Ship_info[Ships[target->instance].ship_info_index];
3704
3705                 // get hull pct of the ship currently
3706                 hull_pct = target->hull_strength / sip->initial_hull_strength;
3707
3708                 // if it has hit a supercap ship and is not a supercap class weapon
3709                 if((sip->flags & SIF_SUPERCAP) && !(wip->wi_flags & WIF_SUPERCAP)){
3710                         // if the supercap is around 3/4 damage, apply nothing
3711                         if(hull_pct <= 0.75f){
3712                                 return 0.0f;
3713                         } else {
3714                                 total_scale *= SUPERCAP_DAMAGE_SCALE;
3715                         }
3716                 }
3717
3718                 // determine if this is a big damage ship
3719                 is_big_damage_ship = (sip->flags & SIF_BIG_DAMAGE);
3720
3721                 // if this is a large ship, and is being hit by flak
3722                 if(is_big_damage_ship && (wip->wi_flags & WIF_FLAK)){
3723                         total_scale *= FLAK_DAMAGE_SCALE;
3724                 }
3725                 
3726                 // if the player is firing small weapons at a big ship
3727                 if( from_player && is_big_damage_ship && !(wip->wi_flags & (WIF_HURTS_BIG_SHIPS)) ){
3728
3729                         // if its a laser weapon
3730                         if(wip->subtype == WP_LASER){
3731                                 total_scale *= 0.01f;
3732                         } else {
3733                                 total_scale *= 0.05f;
3734                         }
3735                 }
3736
3737                 // if the weapon is a small weapon being fired at a big ship
3738                 if( is_big_damage_ship && !(wip->wi_flags & (WIF_HURTS_BIG_SHIPS)) ){
3739                         if(hull_pct > 0.1f){
3740                                 total_scale *= hull_pct;
3741                         } else {
3742                                 return 0.0f;
3743                         }
3744                 }
3745         }
3746         
3747         return total_scale;
3748 #endif
3749 }
3750
3751 int weapon_get_expl_handle(int weapon_expl_index, vector *pos, float size)
3752 {
3753         weapon_expl_info *wei = &Weapon_expl_info[weapon_expl_index];
3754
3755         if (wei->lod_count == 1) {
3756                 return wei->lod[0].bitmap_id;
3757         }
3758
3759         // now we have to do some work
3760         vertex v;
3761         int x, y, w, h, bm_size;
3762         int must_stop = 0;
3763         int best_lod = 1;
3764         int behind = 0;
3765
3766         // start the frame
3767         extern float Viewer_zoom;
3768         extern int G3_count;
3769
3770         if(!G3_count){
3771                 g3_start_frame(1);
3772                 must_stop = 1;
3773         }
3774         g3_set_view_matrix(&Eye_position, &Eye_matrix, Viewer_zoom);
3775
3776         // get extents of the rotated bitmap
3777         g3_rotate_vertex(&v, pos);
3778
3779         // if vertex is behind, find size if in front, then drop down 1 LOD
3780         if (v.codes & CC_BEHIND) {
3781                 float dist = vm_vec_dist_quick(&Eye_position, pos);
3782                 vector temp;
3783
3784                 behind = 1;
3785                 vm_vec_scale_add(&temp, &Eye_position, &Eye_matrix.v.fvec, dist);
3786                 g3_rotate_vertex(&v, &temp);
3787
3788                 // if still behind, bail and go with default
3789                 if (v.codes & CC_BEHIND) {
3790                         behind = 0;
3791                 }
3792         }
3793
3794         if (!g3_get_bitmap_dims(wei->lod[0].bitmap_id, &v, size, &x, &y, &w, &h, &bm_size)) {
3795                 if (Detail.hardware_textures == 4) {
3796                         // straight LOD
3797                         if(w <= bm_size/8){
3798                                 best_lod = 3;
3799                         } else if(w <= bm_size/2){
3800                                 best_lod = 2;
3801                         } else if(w <= 1.3f*bm_size){
3802                                 best_lod = 1;
3803                         } else {
3804                                 best_lod = 0;
3805                         }
3806                 } else {
3807                         // less aggressive LOD for lower detail settings
3808                         if(w <= bm_size/8){
3809                                 best_lod = 3;
3810                         } else if(w <= bm_size/3){
3811                                 best_lod = 2;
3812                         } else if(w <= (1.15f*bm_size)){
3813                                 best_lod = 1;
3814                         } else {
3815                                 best_lod = 0;
3816                         }               
3817                 }
3818         }
3819
3820         // if it's behind, bump up LOD by 1
3821         if (behind) {
3822                 best_lod++;
3823         }
3824
3825         // end the frame
3826         if(must_stop){
3827                 g3_end_frame();
3828         }
3829
3830         best_lod = min(best_lod, wei->lod_count - 1);
3831         return wei->lod[best_lod].bitmap_id;
3832 }
3833
3834 // -------------------------------------------------------------------------------------------------
3835 // weapon_close()
3836 //
3837 // called in game_shutdown() to free malloced memory
3838 //
3839 // NOTE: do not call this function.  It is only called from game_shutdown()
3840 void weapon_close()
3841 {
3842         int i;
3843         
3844         // free info from parsed table data
3845         for (i=0; i<MAX_WEAPON_TYPES; i++) {
3846                 if ( Weapon_info[i].desc != NULL ) {
3847                         free(Weapon_info[i].desc);
3848                         Weapon_info[i].desc = NULL;
3849                 }
3850                 if ( Weapon_info[i].tech_desc != NULL ) {
3851                         free(Weapon_info[i].tech_desc);
3852                         Weapon_info[i].tech_desc = NULL;
3853                 }
3854         }
3855 }