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