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