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