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