]> icculus.org git repositories - taylor/freespace2.git/blob - src/ship/shiphit.cpp
Initial revision
[taylor/freespace2.git] / src / ship / shiphit.cpp
1 /*
2  * $Logfile: /Freespace2/code/Ship/ShipHit.cpp $
3  * $Revision$
4  * $Date$
5  * $Author$
6  *
7  * Code to deal with a ship getting hit by something, be it a missile, dog, or ship.
8  *
9  * $Log$
10  * Revision 1.1  2002/05/03 03:28:10  root
11  * Initial revision
12  *
13  * 
14  * 61    9/14/99 3:26a Dave
15  * Fixed laser fogging problem in nebula (D3D)> Fixed multiplayer
16  * respawn-too-early problem. Made a few crash points safe.
17  * 
18  * 60    9/13/99 4:52p Dave
19  * RESPAWN FIX
20  * 
21  * 59    9/09/99 11:17a Jimb
22  * Removed bogus Int3() in do_subobj_hit_stuff(). 
23  * 
24  * 58    9/07/99 4:01p Dave
25  * Fixed up a string.tbl paroblem (self destruct message). Make sure IPX
26  * does everything properly (setting up address when binding). Remove
27  * black rectangle background from UI_INPUTBOX.
28  * 
29  * 57    9/03/99 11:39p Mikek
30  * Fix problem in sm3-01 of dual-fired Helios bombs only doing 1/4 damage.
31  * 
32  * 56    9/03/99 2:24p Mikek
33  * Decrease overall damage done to player at Medium and Hard.  I believe
34  * this was the major culprit in Flak cannons being so nasty.  The firing
35  * rate seems to not have been an issue.
36  * 
37  * 55    9/02/99 11:55a Mikek
38  * Zero damage to small ship subsystems from shockwaves.
39  * 
40  * 54    9/01/99 10:15a Dave
41  * 
42  * 53    8/27/99 10:42a Andsager
43  * Don't reposition shockwave for BIG only HUGE ships
44  * 
45  * 52    8/27/99 1:34a Andsager
46  * Modify damage by shockwaves for BIG|HUGE ships.  Modify shockwave damge
47  * when weapon blows up.
48  * 
49  * 51    8/26/99 10:46p Andsager
50  * Apply shockwave damage to lethality.
51  * 
52  * 50    8/26/99 8:52p Dave
53  * Gave multiplayer TvT messaging a heavy dose of sanity. Cheat codes.
54  * 
55  * 49    8/26/99 5:14p Andsager
56  * 
57  * 48    8/26/99 9:45a Dave
58  * First pass at easter eggs and cheats.
59  * 
60  * 47    8/23/99 11:59a Andsager
61  * Force choice of big fireball when Knossos destroyed.  Allow logging of
62  * ship destroyed when no killer_name (ie, from debug).
63  * 
64  * 46    8/22/99 5:53p Dave
65  * Scoring fixes. Added self destruct key. Put callsigns in the logfile
66  * instead of ship designations for multiplayer players.
67  * 
68  * 45    8/22/99 1:19p Dave
69  * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
70  * which d3d cards are detected.
71  * 
72  * 44    8/20/99 5:09p Andsager
73  * Second pass on Knossos device explosion
74  * 
75  * 43    8/20/99 1:42p Andsager
76  * Frist pass on Knossos explosion.
77  * 
78  * 42    8/06/99 9:46p Dave
79  * Hopefully final changes for the demo.
80  * 
81  * 41    8/03/99 11:02p Dave
82  * Maybe fixed sync problems in multiplayer.
83  * 
84  * 40    8/02/99 1:59p Dave
85  * Fixed improper damage application to subobjects on a "big damage" ship.
86  * 
87  * 39    7/24/99 1:54p Dave
88  * Hud text flash gauge. Reworked dead popup to use 4 buttons in red-alert
89  * missions.
90  * 
91  * 38    7/19/99 7:20p Dave
92  * Beam tooling. Specialized player-killed-self messages. Fixed d3d nebula
93  * pre-rendering.
94  * 
95  * 37    7/09/99 12:51a Andsager
96  * Modify engine wash (1) less damage (2) only at a closer range (3) no
97  * damage when engine is disabled
98  * 
99  * 36    6/30/99 5:53p Dave
100  * Put in new anti-camper code.
101  * 
102  * 35    6/28/99 4:51p Andsager
103  * Add ship-guardian sexp (does not allow ship to be killed)
104  * 
105  * 34    6/21/99 7:25p Dave
106  * netplayer pain packet. Added type E unmoving beams.
107  * 
108  * 33    6/10/99 3:43p Dave
109  * Do a better job of syncing text colors to HUD gauges.
110  * 
111  * 32    5/27/99 12:14p Andsager
112  * Some fixes for live debris when more than one subsys on ship with live
113  * debris.  Set subsys strength (when 0) blows off subsystem.
114  * sexp_hits_left_subsystem works for SUBSYSTEM_UNKNOWN.
115  * 
116  * 31    5/21/99 5:03p Andsager
117  * Add code to display engine wash death.  Modify ship_kill_packet
118  * 
119  * 30    5/21/99 1:44p Andsager
120  * Add engine wash gauge
121  * 
122  * 29    5/14/99 11:50a Andsager
123  * Added vaporize for SMALL ships hit by HUGE beams.  Modified dying
124  * frame.  Enlarged debris shards and range at which visible.
125  * 
126  * 28    5/12/99 2:55p Andsager
127  * Implemented level 2 tag as priority in turret object selection
128  * 
129  * 27    5/11/99 10:16p Andsager
130  * First pass on engine wash effect.  Rotation (control input), damage,
131  * shake.  
132  * 
133  * 26    4/28/99 11:13p Dave
134  * Temporary checkin of artillery code.
135  * 
136  * 25    4/23/99 12:01p Johnson
137  * Added SIF_HUGE_SHIP
138  * 
139  * 24    4/20/99 3:43p Andsager
140  * Added normal parameter to ship_apply_local_damage for case of ship_ship
141  * collision.
142  * 
143  * 23    4/16/99 5:54p Dave
144  * Support for on/off style "stream" weapons. Real early support for
145  * target-painting lasers.
146  * 
147  * 22    3/29/99 6:17p Dave
148  * More work on demo system. Got just about everything in except for
149  * blowing ships up, secondary weapons and player death/warpout.
150  * 
151  * 21    3/19/99 9:51a Dave
152  * Checkin to repair massive source safe crash. Also added support for
153  * pof-style nebulae, and some new weapons code.
154  * 
155  * 21    3/15/99 6:45p Daveb
156  * Put in rough nebula bitmap support.
157  * 
158  * 20    3/10/99 6:51p Dave
159  * Changed the way we buffer packets for all clients. Optimized turret
160  * fired packets. Did some weapon firing optimizations.
161  * 
162  * 19    2/26/99 6:01p Andsager
163  * Add sexp has-been-tagged-delay and cap-subsys-cargo-known-delay
164  * 
165  * 18    2/26/99 5:39p Johnson
166  * Put in some handling code for an assert().
167  * 
168  * 17    2/11/99 5:22p Andsager
169  * Fixed bugs, generalized block Sexp_variables
170  * 
171  * 16    2/05/99 10:38a Johnson
172  * Fixed improper object array reference. 
173  * 
174  * 15    2/04/99 1:23p Andsager
175  * Apply max spark limit to ships created in mission parse
176  * 
177  * 14    1/30/99 1:29a Dave
178  * Fixed nebula thumbnail problem. Full support for 1024x768 choose pilot
179  * screen.  Fixed beam weapon death messages.
180  * 
181  * 13    1/29/99 2:08a Dave
182  * Fixed beam weapon collisions with players. Reduced size of scoring
183  * struct for multiplayer. Disabled PXO.
184  * 
185  * 12    1/27/99 10:25p Andsager
186  * Added OEM sparks - make intelligent choice of next spark location for
187  * cruiser and cap ships
188  * 
189  * 11    1/25/99 5:03a Dave
190  * First run of stealth, AWACS and TAG missile support. New mission type
191  * :)
192  * 
193  * 10    1/21/99 4:22p Anoop
194  * Removed bogus Int3() from show_dead_message(...)
195  * 
196  * 9     1/12/99 5:45p Dave
197  * Moved weapon pipeline in multiplayer to almost exclusively client side.
198  * Very good results. Bandwidth goes down, playability goes up for crappy
199  * connections. Fixed object update problem for ship subsystems.
200  * 
201  * 8     12/23/98 2:53p Andsager
202  * Added ship activation and gas collection subsystems, removed bridge
203  * 
204  * 7     11/17/98 4:27p Andsager
205  * Stop sparks from emitting from destroyed subobjects
206  * 
207  * 6     11/09/98 2:11p Dave
208  * Nebula optimizations.
209  * 
210  * 5     10/26/98 9:42a Dave
211  * Early flak gun support.
212  * 
213  * 4     10/20/98 1:39p Andsager
214  * Make so sparks follow animated ship submodels.  Modify
215  * ship_weapon_do_hit_stuff() and ship_apply_local_damage() to add
216  * submodel_num.  Add submodel_num to multiplayer hit packet.
217  * 
218  * 3     10/13/98 9:29a Dave
219  * Started neatening up freespace.h. Many variables renamed and
220  * reorganized. Added AlphaColors.[h,cpp]
221  * 
222  * 2     10/07/98 10:53a Dave
223  * Initial checkin.
224  * 
225  * 1     10/07/98 10:51a Dave
226  * 
227  * 145   9/01/98 6:48p Dave
228  * Energy suck weapon. Removed a couple of now-bogus asserts in tracker
229  * code.
230  * 
231  * 144   8/25/98 1:48p Dave
232  * First rev of EMP effect. Player side stuff basically done. Next comes
233  * AI code.
234  * 
235  * 143   6/09/98 10:31a Hoffoss
236  * Created index numbers for all xstr() references.  Any new xstr() stuff
237  * added from here on out should be added to the end if the list.  The
238  * current list count can be found in FreeSpace.cpp (search for
239  * XSTR_SIZE).
240  * 
241  * 142   5/24/98 8:49p Allender
242  * put in Int3() to try and trap nasty error in multiplayer
243  * 
244  * 141   5/22/98 12:08p Mike
245  * Don't create "Disarmed" event for small ships.
246  * 
247  * 140   5/22/98 11:00a Mike
248  * Balance sm3-09a.
249  * 
250  * 139   5/18/98 12:41a Allender
251  * fixed subsystem problems on clients (i.e. not reporting properly on
252  * damage indicator).  Fixed ingame join problem with respawns.  minor
253  * comm menu stuff
254  * 
255  * 138   5/13/98 6:54p Dave
256  * More sophistication to PXO interface. Changed respawn checking so
257  * there's no window for desynchronization between the server and the
258  * clients.
259  * 
260  * 137   5/11/98 11:37a Mike
261  * Don't allow deathroll duration for large ships to be shortened by
262  * excess damage.
263  * 
264  * 136   5/10/98 11:30p Mike
265  * Better firing of bombs, less likely to go into strafe mode.
266  * 
267  * 135   5/07/98 12:24a Hoffoss
268  * Finished up sidewinder force feedback support.
269  * 
270  * 134   5/06/98 8:47a Andsager
271  * Initial check in, allow ship sparks to turn on and off depending on
272  * damage.
273  * 
274  * 133   5/06/98 1:12a Allender
275  * fix sequencing names, added nprintf to help respawn debugging
276  * 
277  * 132   5/04/98 4:07p Andsager
278  * Reduce deathroll rotvel cap and average by 25%.
279  * 
280  * 131   5/04/98 11:12a Mike
281  * Make kamikaze ships detonate on impact -- no death roll.
282  * 
283  * 130   4/30/98 12:17a Andsager
284  * Increase deathroll time for big ships and decrease max rotvel for big
285  * ships
286  * 
287  * 129   4/27/98 6:02p Dave
288  * Modify how missile scoring works. Fixed a team select ui bug. Speed up
289  * multi_lag system. Put in new main hall.
290  * 
291  * 128   4/27/98 2:23p Andsager
292  * Create fireballs on destroying subsystems of big ships.  Limit number
293  * of sparks on small ships.
294  * 
295  * 127   4/24/98 5:35p Andsager
296  * Fix sparks sometimes drawing not on model.  If ship is sphere in
297  * collision, don't draw sparks.  Modify ship_apply_local_damage() to take
298  * parameter no_spark.
299  * 
300  * 126   4/23/98 4:47p Andsager
301  * Make deathroll rotvel have z component largest.
302  * 
303  * 125   4/22/98 9:10a Andsager
304  * Resrore z component of deathroll rotvel, as before.  
305  * 
306  * 124   4/21/98 11:20p Andsager
307  * Modify deatroll rotvel. Fix bug getting only positive values.  Add
308  * random to current rotvel, make z rotvel always larger than x or y.
309  * Move call to shipfx_large_blowup_init into Ship.cpp.
310  * 
311  * 123   4/21/98 10:38a Mike
312  * Don't allow player to take _any_ kind of damage past stage 2 of
313  * warpout.
314  * 
315  * 122   4/20/98 5:10p John
316  * Took out cap of number of shards using num_particles.
317  * 
318  * 121   4/17/98 1:17p Mike
319  * Fix bug with uninitialized damage_to_apply.
320  * 
321  * 120   4/17/98 11:05a Mike
322  * Make number of pieces of small debris created by subsystem hits be
323  * based on detail level.
324  * Fix location of turret subsystem.  Was doubly globalizing, very bad on
325  * large ships!
326  * 
327  * 119   4/16/98 3:40p Mike
328  * Make subsys destroyed messages only get sent once.
329  * 
330  * 118   4/15/98 11:06p Mike
331  * Better balance of damage done to subsystems by shockwaves.
332  * 
333  * 117   4/15/98 10:13p Mike
334  * Fix application of damage to subsystems.
335  * 
336  * 116   4/14/98 9:15p John
337  * Added flag to specify which ships get the new large ship exploding
338  * effect.
339  * 
340  * 115   4/14/98 4:56p John
341  * Hooked in Andsager's large ship exploding code, but it is temporarily
342  * disabled.
343  * 
344  * 114   4/12/98 11:16a John
345  * Made palette red hit effect more proportional to damage.
346  * 
347  * 113   4/10/98 12:16p Allender
348  * fix ship hit kill and debris packets
349  * 
350  * 112   4/10/98 1:38a Allender
351  * fix bug with -1 vs 255 (for current secondary bank).  Undid previous
352  * code for ship_kill packets.
353  * 
354  * 111   4/09/98 5:44p Allender
355  * multiplayer network object fixes.  debris and self destructed ships
356  * should all sync up.  Fix problem where debris pieces (hull pieces) were
357  * not getting a net signature
358  * 
359  * 110   4/09/98 5:27p Mike
360  * Speed up deathrolls for smaller ships a bit.
361  * 
362  * 109   4/06/98 7:13p Allender
363  * generate the death text
364  * 
365  * 108   4/01/98 1:48p Allender
366  * major changes to ship collision in multiplayer.  Clients now do own
367  * ship/ship collisions (with their own ship only)  Modifed the hull
368  * update packet to be sent quicker when object is target of player.
369  * 
370  * 107   3/31/98 5:19p John
371  * Removed demo/save/restore.  Made NDEBUG defined compile.  Removed a
372  * bunch of debug stuff out of player file.  Made model code be able to
373  * unload models and malloc out only however many models are needed.
374  *  
375  * 
376  * 106   3/30/98 2:38p Mike
377  * Add asteroid_density to detail level support.
378  * No force explosion damage in training missions.
379  * Make cargo deathrolls shorter.
380  * 
381  * 105   3/30/98 1:08a Lawrance
382  * Implement "blast" icon.  Blink HUD icon when player ship is hit by a
383  * blast.
384  * 
385  * 104   3/24/98 4:26p Lawrance
386  * Make finding out if player killed self easier and more reliable
387  * 
388  * 103   3/24/98 2:16p Mike
389  * Fix bug with variation in death roll rotational velocity.  It wasn't
390  * getting initialized!
391  * 
392  * 102   3/21/98 3:36p Lawrance
393  * Let damage gauge know when player has taken damage.
394  * 
395  * 101   3/21/98 3:37p Mike
396  * Fix/optimize attacking of big ships.
397  * 
398  * 100   3/19/98 5:35p Lawrance
399  * Correctly inform player if killed by ship explosion.
400  *
401  * $NoKeywords: $
402  */
403
404 #include "pstypes.h"
405 #include "object.h"
406 #include "fvi.h"
407 #include "physics.h"
408 #include "vecmat.h"
409 #include "ship.h"
410 #include "model.h"
411 #include "key.h"
412 #include "weapon.h"
413 #include "radar.h"
414 #include "2d.h"
415 #include "3d.h"
416 #include "floating.h"
417 #include "ai.h"
418 #include "ailocal.h"
419 #include "fireballs.h"
420 #include "debris.h"
421 #include "hud.h"
422 #include "timer.h"
423 #include "cfile.h"
424 #include "missionlog.h"
425 #include "missionparse.h"
426 #include "bmpman.h"
427 #include "joy.h"
428 #include "joy_ff.h"
429 #include "player.h"
430 #include "parselo.h"
431 #include "freespace.h"
432 #include "sound.h"
433 #include "linklist.h"
434 #include "hudets.h"
435 #include "hudtarget.h"
436 #include "multi.h"
437 #include "multiutil.h"
438 #include "aigoals.h"
439 #include "gamesnd.h"
440 #include "eventmusic.h"
441 #include "shipfx.h"
442 #include "sexp.h"
443 #include "gamesequence.h"
444 #include "objectsnd.h"
445 #include "cmeasure.h"
446 #include "animplay.h"
447 #include "controlsconfig.h"
448 #include "afterburner.h"
449 #include "shockwave.h"
450 #include "hudsquadmsg.h"
451 #include "swarm.h"
452 #include "shiphit.h"
453 #include "multimsgs.h"
454 #include "particle.h"
455 #include "multi_respawn.h"
456 #include "popup.h"
457 #include "emp.h"
458 #include "beam.h"
459 #include "demo.h"
460 #include "multi_pmsg.h"
461
462 //#pragma optimize("", off)
463 //#pragma auto_inline(off)
464
465 typedef struct spark_pair {
466         int index1, index2;
467         float dist;
468 } spark_pair;
469
470 #define MAX_SPARK_PAIRS         ((MAX_SHIP_HITS * MAX_SHIP_HITS - MAX_SHIP_HITS) / 2)
471
472 #define BIG_SHIP_MIN_RADIUS     80.0f   //      ship radius above which death rolls can't be shortened by excessive damage
473
474 vector  Dead_camera_pos;
475 vector  Original_vec_to_deader;
476
477 //      Decrease damage applied to a subsystem based on skill level.
478 float   Skill_level_subsys_damage_scale[NUM_SKILL_LEVELS] = {0.2f, 0.4f, 0.6f, 0.8f, 1.0f};
479
480 bool is_subsys_destroyed(ship *shipp, int submodel)
481 {
482         ship_subsys *subsys;
483
484         if (submodel == -1) {
485                 false;
486         }
487
488         for ( subsys=GET_FIRST(&shipp->subsys_list); subsys != END_OF_LIST(&shipp->subsys_list); subsys = GET_NEXT(subsys) ) {
489                 if (subsys->system_info->subobj_num == submodel) {
490                         if (subsys->current_hits > 0) {
491                                 return false;
492                         } else {
493                                 return true;
494                         }
495                 }
496         }
497
498         return false;
499 }
500
501 // do_subobj_destroyed_stuff is called when a subobject for a ship is killed.  Separated out
502 // to separate function on 10/15/97 by MWA for easy multiplayer access.  It does all of the
503 // cool things like blowing off the model (if applicable, writing the logs, etc)
504 void do_subobj_destroyed_stuff( ship *ship_p, ship_subsys *subsys, vector* hitpos )
505 {
506         ship_info *sip;
507         object *ship_obj;
508         model_subsystem *psub;
509         vector  g_subobj_pos;
510         int type, i, log_index;
511
512         // get some local variables
513         sip = &Ship_info[ship_p->ship_info_index];
514         ship_obj = &Objects[ship_p->objnum];
515         psub = subsys->system_info;
516         type = psub->type;
517         get_subsystem_world_pos(ship_obj, subsys, &g_subobj_pos);
518
519         // create fireballs when subsys destroy for large ships.
520         object* objp = &Objects[ship_p->objnum];
521         if (objp->radius > 100.0f) {
522                 // number of fireballs determined by radius of subsys
523                 int num_fireballs;
524                 if ( psub->radius < 3 ) {
525                         num_fireballs = 1;
526                 } else {
527                          num_fireballs = 5;
528                 }
529
530                 vector temp_vec, center_to_subsys, rand_vec;
531                 vm_vec_sub(&center_to_subsys, &g_subobj_pos, &objp->pos);
532                 for (int i=0; i<num_fireballs; i++) {
533                         if (i==0) {
534                                 // make first fireball at hitpos
535                                 if (hitpos) {
536                                         temp_vec = *hitpos;
537                                 } else {
538                                         temp_vec = g_subobj_pos;
539                                 }
540                         } else {
541                                 // make other fireballs at random positions, but try to keep on the surface
542                                 vm_vec_rand_vec_quick(&rand_vec);
543                                 float dot = vm_vec_dotprod(&center_to_subsys, &rand_vec);
544                                 vm_vec_scale_add2(&rand_vec, &center_to_subsys, -dot/vm_vec_mag_squared(&center_to_subsys));
545                                 vm_vec_scale_add(&temp_vec, &g_subobj_pos, &rand_vec, 0.5f*psub->radius);
546                         }
547
548                         // scale fireball size according to size of subsystem, but not less than 10
549                         float fireball_rad = psub->radius * 0.2f;
550                         if (fireball_rad < 10) {
551                                 fireball_rad = 10.0f;
552                         }
553
554                         vector fb_vel;
555                         vm_vec_crossprod(&fb_vel, &objp->phys_info.rotvel, &center_to_subsys);
556                         vm_vec_add2(&fb_vel, &objp->phys_info.vel);
557                         fireball_create( &temp_vec, FIREBALL_EXPLOSION_MEDIUM, OBJ_INDEX(objp), fireball_rad, 0, &fb_vel );
558                 }
559         }
560
561         if ( MULTIPLAYER_MASTER ) {
562                 int index;
563
564                 index = ship_get_index_from_subsys(subsys, ship_p->objnum);
565                 
566                 vector hit;
567                 if (hitpos) {
568                         hit = *hitpos;
569                 } else {
570                         hit = g_subobj_pos;
571                 }
572                 send_subsystem_destroyed_packet( ship_p, index, hit );
573         }
574
575         // next do a quick sanity check on the current hits that we are keeping for the generic subsystems
576         // I think that there might be rounding problems with the floats.  This code keeps us safe.
577         if ( ship_p->subsys_info[type].num == 1 ) {
578                 ship_p->subsys_info[type].current_hits = 0.0f;
579         } else {
580                 float hits;
581                 ship_subsys *ssp;
582
583                 hits = 0.0f;
584                 for ( ssp=GET_FIRST(&ship_p->subsys_list); ssp != END_OF_LIST(&ship_p->subsys_list); ssp = GET_NEXT(ssp) ) {
585                         if ( ssp->system_info->type == type )
586                                 hits += ssp->current_hits;
587                 }
588                 ship_p->subsys_info[type].current_hits = hits;
589         }
590
591         // store an event in the event log.  Also, determine if all turrets or all
592         // engines have been destroyed (if the subsystem is a turret or engine).
593         // put a disabled or disarmed entry in the log if this is the case
594         // 
595         // MWA -- 1/8/98  A problem was found when trying to determine (via sexpression) when some subsystems
596         // were destroyed.  The bottom line is that is the psub->name and psub->subobj_name are different,
597         // then direct detection doesn't work.  (This scenario happens mainly with turrets and probably with
598         // engines).  So, my solution is to encode the ship_info index, and the subsystem index into one
599         // integer, and pass that as the "index" parameter to add_entry.  We'll use that information to
600         // print out the info in the mission log.
601         Assert( ship_p->ship_info_index < 65535 );
602
603         // get the "index" of this subsystem in the ship info structure.
604         for ( i = 0; i < sip->n_subsystems; i++ ) {
605                 if ( &(sip->subsystems[i]) == psub )
606                         break;
607         }
608         Assert( i < sip->n_subsystems );
609         Assert( i < 65535 );
610         log_index = ((ship_p->ship_info_index << 16) & 0xffff0000) | (i & 0xffff);
611
612         // Don't log or display info about the activation subsytem
613         int display = (psub->type != SUBSYSTEM_ACTIVATION);
614         if (display) {
615                 mission_log_add_entry(LOG_SHIP_SUBSYS_DESTROYED, ship_p->ship_name, psub->subobj_name, log_index );
616                 if ( ship_obj == Player_obj ) {
617                         snd_play( &Snds[SND_SUBSYS_DIE_1], 0.0f );
618                         HUD_printf(XSTR( "Your %s subsystem has been destroyed", 499), psub->name);
619                 }
620         }
621
622         if ( psub->type == SUBSYSTEM_TURRET ) {
623                 if ( ship_p->subsys_info[type].current_hits == 0.0f ) {
624                         //      Don't create "disarmed" event for small ships.
625                         if (!(Ship_info[ship_p->ship_info_index].flags & SIF_SMALL_SHIP)) {
626                                 mission_log_add_entry(LOG_SHIP_DISARMED, ship_p->ship_name, NULL );
627                                 // ship_p->flags |= SF_DISARMED;
628                         }
629                 }
630         } else if (psub->type == SUBSYSTEM_ENGINE ) {
631                 // when an engine is destroyed, we must change the max velocity of the ship
632                 // to be some fraction of its normal maximum value
633
634                 if ( ship_p->subsys_info[type].current_hits == 0.0f ) {
635                         mission_log_add_entry(LOG_SHIP_DISABLED, ship_p->ship_name, NULL );
636                         ship_p->flags |= SF_DISABLED;                           // add the disabled flag
637                 }
638         }
639
640         if ( psub->subobj_num > -1 )    {
641                 shipfx_blow_off_subsystem(ship_obj,ship_p,subsys,&g_subobj_pos);
642                 subsys->submodel_info_1.blown_off = 1;
643         }
644
645         if ( (psub->subobj_num != psub->turret_gun_sobj) && (psub->turret_gun_sobj >-1) )               {
646                 subsys->submodel_info_2.blown_off = 1;
647         }
648
649         // play sound effect when subsys gets blown up
650         int sound_index=-1;
651         if ( Ship_info[ship_p->ship_info_index].flags & SIF_HUGE_SHIP ) {
652                 sound_index=SND_CAPSHIP_SUBSYS_EXPLODE;
653         } else if ( Ship_info[ship_p->ship_info_index].flags & SIF_BIG_SHIP ) {
654                 sound_index=SND_SUBSYS_EXPLODE;
655         }
656         if ( sound_index >= 0 ) {
657                 snd_play_3d( &Snds[sound_index], &g_subobj_pos, &View_position );
658         }
659 }
660
661 // Return weapon type that is associated with damaging_objp
662 // input:       damaging_objp           =>      object pointer responsible for damage
663 //      exit:           -1              =>      no weapon type is associated with damage object
664 //                              >=0     =>      weapon type associated with damage object
665 int shiphit_get_damage_weapon(object *damaging_objp)
666 {
667         int weapon_info_index = -1;
668
669         if ( damaging_objp ) {
670                 switch(damaging_objp->type) {
671                 case OBJ_WEAPON:
672                         weapon_info_index = Weapons[damaging_objp->instance].weapon_info_index;
673                         break;
674                 case OBJ_SHOCKWAVE:
675                         weapon_info_index = shockwave_weapon_index(damaging_objp->instance);
676                         break;
677                 default:
678                         weapon_info_index = -1;
679                         break;
680                 }
681         }
682
683         return weapon_info_index;
684 }
685
686 //      Return range at which this object can apply damage.
687 //      Based on object type and subsystem type.
688 float subsys_get_range(object *other_obj, ship_subsys *subsys)
689 {
690         float   range;
691
692         if (other_obj->type == OBJ_SHOCKWAVE) {
693                 range = Shockwaves[other_obj->instance].outer_radius * 0.75f;   //      Shockwaves were too lethal to subsystems.
694         } else if ( subsys->system_info->type == SUBSYSTEM_TURRET ) {
695                 range = subsys->system_info->radius*3;
696         } else {
697                 range = subsys->system_info->radius*2;
698         }
699
700         return range;
701 }
702
703 #define MAX_DEBRIS_SHARDS       16              // cap the amount of debris shards that fly off per hit
704
705 // Make some random debris particles.  Previous way was not very random.  Create debris 75% of the time.
706 // Don't worry about multiplayer since this debris is the small stuff that cannot collide
707 void create_subsys_debris(object *ship_obj, vector *hitpos)
708 {
709         float show_debris = frand();
710         
711         if ( show_debris <= 0.75f ) {
712                 int ndebris;
713
714                 ndebris = (int)(show_debris * Detail.num_small_debris) + 1;                     // number of pieces of debris to create
715
716                 if ( ndebris > MAX_DEBRIS_SHARDS )
717                         ndebris = MAX_DEBRIS_SHARDS;
718
719                 //mprintf(( "Damage = %.1f, ndebris=%d\n", show_debris, ndebris ));
720                 for (int i=0; i<ndebris; i++ )  {
721                         debris_create( ship_obj, -1, -1, hitpos, hitpos, 0, 1.0f );
722                 }
723         }
724 }
725
726 void create_vaporize_debris(object *ship_obj, vector *hitpos)
727 {
728         int ndebris;
729         float show_debris = frand();
730
731         ndebris = (int)(4.0f * ((0.5f + show_debris) * Detail.num_small_debris)) + 5;                   // number of pieces of debris to create
732
733         if ( ndebris > MAX_DEBRIS_SHARDS ) {
734                 ndebris = MAX_DEBRIS_SHARDS;
735         }
736
737         //mprintf(( "Damage = %.1f, ndebris=%d\n", show_debris, ndebris ));
738         for (int i=0; i<ndebris; i++ )  {
739                 debris_create( ship_obj, -1, -1, hitpos, hitpos, 0, 1.4f );
740         }
741 }
742
743 #define MAX_SUBSYS_LIST 32
744
745 typedef struct {
746         float   dist;
747         float   range;
748         ship_subsys     *ptr;
749 } sublist;
750
751 // do_subobj_hit_stuff() is called when a collision is detected between a ship and something
752 // else.  This is where we see if any sub-objects on the ship should take damage.
753 //
754 //      Depending on where the collision occurs, the sub-system and surrounding hull will take 
755 // different amounts of damage.  The amount of damage a sub-object takes depending on how
756 // close the colliding object is to the center of the sub-object.  The remaining hull damage
757 // will be returned to the caller via the damage parameter.
758 //
759 //
760 // 0   -> 0.5 radius   : 100% subobject    0%  hull
761 // 0.5 -> 1.0 radius   :  50% subobject   50%  hull
762 // 1.0 -> 2.0 radius   :  25% subobject   75%  hull
763 //     >  2.0 radius   :   0% subobject  100%  hull
764 //
765 //
766 // The weapon damage is not neccesarily distributed evently between sub-systems when more than
767 // one sub-system is to take damage.  Whenever damage is to be assigned to a sub-system, the above
768 // percentages are used.  So, if more than one sub-object is taking damage, the second sub-system
769 // to be assigned damage will take less damage.  Eg. weapon hits in the 25% damage range of two
770 // subsytems, and the weapon damage is 12.  First subsystem takes 3 points damage.  Second subsystem
771 // will take 0.25*9 = 2.25 damage.  Should be close enough for most cases, and hull would receive 
772 // 0.75 * 9 = 6.75 damage.
773 //
774 //      Used to use the following constants, but now damage is linearly scaled up to 2x the subsystem
775 //      radius.  Same damage applied as defined by constants below.
776 //
777 //      Returns unapplied damage, which will probably be applied to the hull.
778 //
779 // Shockwave damage is handled here.  If other_obj->type == OBJ_SHOCKWAVE, it's a shockwave.
780 // apply the same damage to all subsystems.
781 //      Note: A negative damage number means to destroy the corresponding subsystem.  For example, call with -SUBSYSTEM_ENGINE to destroy engine.
782
783 float do_subobj_hit_stuff(object *ship_obj, object *other_obj, vector *hitpos, float damage)
784 {
785         vector                  g_subobj_pos;
786         float                           damage_left;
787         int                             weapon_info_index;
788         ship_subsys             *subsys;
789         ship                            *ship_p;
790         sublist                 subsys_list[MAX_SUBSYS_LIST];
791         vector                  hitpos2;
792
793         ship_p = &Ships[ship_obj->instance];
794
795         //      Don't damage player subsystems in a training mission.
796         if ( The_mission.game_type & MISSION_TYPE_TRAINING ) {
797                 if (ship_obj == Player_obj){
798                         return damage;
799                 }
800         }
801
802         //      Shockwave damage is applied like weapon damage.  It gets consumed.
803         if (other_obj->type == OBJ_SHOCKWAVE) {
804                 //      MK, 9/2/99.  Shockwaves do zero subsystem damage on small ships.
805                 if ( Ship_info[ship_p->ship_info_index].flags & (SIF_SMALL_SHIP))
806                         return damage;
807                 else {
808
809                         damage_left = Shockwaves[other_obj->instance].damage/4.0f;
810                 }
811                 hitpos2 = other_obj->pos;
812         } else {
813                 damage_left = damage;
814                 hitpos2 = *hitpos;
815         }
816
817         // scale subsystem damage if appropriate
818         weapon_info_index = shiphit_get_damage_weapon(other_obj);
819         if ((other_obj->type == OBJ_WEAPON) && ( weapon_info_index >= 0 )) {
820                 damage_left *= Weapon_info[weapon_info_index].subsystem_factor;
821         }
822
823
824 #ifndef NDEBUG
825         float hitpos_dist = vm_vec_dist( hitpos, &ship_obj->pos );      
826         if ( hitpos_dist > ship_obj->radius * 2.0f )    {
827                 mprintf(( "BOGUS HITPOS PASSED TO DO_SUBOBJ_HIT_STUFF (%.1f > %.1f)!\n", hitpos_dist, ship_obj->radius * 2.0f ));
828                 // Int3();      // Get John ASAP!!!!  Someone passed a local coordinate instead of world for hitpos probably.
829         }
830 #endif
831
832         create_subsys_debris(ship_obj, hitpos);
833
834         //      First, create a list of the N subsystems within range.
835         //      Then, one at a time, process them in order.
836         int     count = 0;
837         for ( subsys=GET_FIRST(&ship_p->subsys_list); subsys != END_OF_LIST(&ship_p->subsys_list); subsys = GET_NEXT(subsys) ) {
838                 #ifndef NDEBUG
839                 //      Debug option.  If damage is negative of subsystem type, then just destroy that subsystem.
840                 if (damage < 0.0f) {
841                         // single player or multiplayer
842                         Assert(Player_ai->targeted_subsys != NULL);
843                         if ( (subsys == Player_ai->targeted_subsys) && (subsys->current_hits > 0) ) {
844                                 Assert(subsys->system_info->type == (int) -damage);
845                                 ship_p->subsys_info[subsys->system_info->type].current_hits -= subsys->current_hits;
846                                 if (ship_p->subsys_info[subsys->system_info->type].current_hits < 0) {
847                                         ship_p->subsys_info[subsys->system_info->type].current_hits = 0.0f;
848                                 }
849                                 subsys->current_hits = 0.0f;
850                                 do_subobj_destroyed_stuff( ship_p, subsys, hitpos );
851                                 continue;
852                         } else {
853                                 continue;
854                         }
855                 }
856                 #endif
857                 
858                 if (subsys->current_hits > 0.0f) {
859                         float   dist;
860
861                         // calculate the distance between the hit and the subsystem center
862                         get_subsystem_world_pos(ship_obj, subsys, &g_subobj_pos);
863                         dist = vm_vec_dist_quick(&hitpos2, &g_subobj_pos);
864
865                         float range = subsys_get_range(other_obj, subsys);
866
867                         if ( dist < range) {
868                                 subsys_list[count].dist = dist;
869                                 subsys_list[count].range = range;
870                                 subsys_list[count].ptr = subsys;
871                                 count++;
872
873                                 if (count >= MAX_SUBSYS_LIST){
874                                         break;
875                                 }
876                         }
877                 }
878         }
879
880         //      Now scan the sorted list of subsystems in range.
881         //      Apply damage to the nearest one first, subtracting off damage as we go.
882         int     i, j;
883         for (j=0; j<count; j++) {
884                 float   dist, range;
885                 ship_subsys     *subsys;
886
887                 int     min_index = -1;
888                 float   min_dist = 9999999.9f;
889
890                 for (i=0; i<count; i++) {
891                         if (subsys_list[i].dist < min_dist) {
892                                 min_dist = subsys_list[i].dist;
893                                 min_index = i;
894                         }
895                 }
896                 Assert(min_index != -1);
897
898                 float   damage_to_apply = 0.0f;
899                 subsys = subsys_list[min_index].ptr;
900                 range = subsys_list[min_index].range;
901                 dist = subsys_list[min_index].dist;
902                 subsys_list[min_index].dist = 9999999.9f;       //      Make sure we don't use this one again.
903
904                 //      HORRIBLE HACK!
905                 //      MK, 9/4/99
906                 //      When Helios bombs are dual fired against the Juggernaut in sm3-01 (FS2), they often
907                 //      miss their target.  There is code dating to FS1 in the collision code to detect that a bomb or
908                 //      missile has somehow missed its target.  It gets its lifeleft set to 0.1 and then it detonates.
909                 //      Unfortunately, the shockwave damage was cut by 4 above.  So boost it back up here.
910                 if ((dist < 10.0f) && (other_obj->type == OBJ_SHOCKWAVE)) {
911                         damage_left *= 4.0f * Weapon_info[weapon_info_index].subsystem_factor;;
912                 }
913
914 //              if (damage_left > 100.0f)
915 //                      nprintf(("AI", "Applying %7.3f damage to subsystem %7.3f units away.\n", damage_left, dist));
916
917                 if ( dist < range/2.0f ) {
918                         damage_to_apply = damage_left;
919                 } else if ( dist < range ) {
920                         damage_to_apply = damage_left * (1.0f - dist/range);
921                 }
922
923                 // if we're not in CLIENT_NODAMAGE multiplayer mode (which is a the NEW way of doing things)
924                 if (damage_to_apply > 0.1f && !(MULTIPLAYER_CLIENT) && !(Game_mode & GM_DEMO_PLAYBACK)) {
925                         //      Decrease damage to subsystems to player ships.
926                         if (ship_obj->flags & OF_PLAYER_SHIP){
927                                 damage_to_apply *= Skill_level_subsys_damage_scale[Game_skill_level];
928                         }
929                 
930                         subsys->current_hits -= damage_to_apply;
931                         ship_p->subsys_info[subsys->system_info->type].current_hits -= damage_to_apply;
932                         damage_left -= damage_to_apply;         // decrease the damage left to apply to the ship subsystems
933
934                         if (subsys->current_hits < 0.0f) {
935                                 damage_left -= subsys->current_hits;
936                                 ship_p->subsys_info[subsys->system_info->type].current_hits -= subsys->current_hits;
937                                 subsys->current_hits = 0.0f;                                    // set to 0 so repair on subsystem takes immediate effect
938                         }
939
940                         if ( ship_p->subsys_info[subsys->system_info->type].current_hits < 0.0f ){
941                                 ship_p->subsys_info[subsys->system_info->type].current_hits = 0.0f;
942                         }
943
944                         // multiplayer clients never blow up subobj stuff on their own
945                         if ( (subsys->current_hits <= 0.0f) && !MULTIPLAYER_CLIENT && !(Game_mode & GM_DEMO_PLAYBACK)){
946                                 do_subobj_destroyed_stuff( ship_p, subsys, hitpos );
947                         }
948
949                         if (damage_left <= 0)   { // no more damage to distribute, so stop checking
950                                 damage_left = 0.0f;
951                                 break;
952                         }
953                 }
954 //nprintf(("AI", "j=%i, sys = %s, dam = %6.1f, dam left = %6.1f, subhits = %5.0f\n", j, subsys->system_info->name, damage_to_apply, damage_left, subsys->current_hits));
955         }
956
957         //      Note: I changed this to return damage_left and it completely screwed up balance.
958         //      It had taken a few MX-50s to destory an Anubis (with 40% hull), then it took maybe ten.
959         //      So, I left it alone. -- MK, 4/15/98
960         return damage;
961 }
962
963 // Store who/what killed the player, so we can tell the player how he died
964 void shiphit_record_player_killer(object *killer_objp, player *p)
965 {
966         switch (killer_objp->type) {
967
968         case OBJ_WEAPON:
969                 p->killer_objtype=OBJ_WEAPON;
970                 p->killer_weapon_index=Weapons[killer_objp->instance].weapon_info_index;
971                 p->killer_species = Ship_info[Ships[Objects[killer_objp->parent].instance].ship_info_index].species;
972
973                 if ( &Objects[killer_objp->parent] == Player_obj ) {
974                         // killed by a missile?
975                         if(Weapon_info[p->killer_weapon_index].subtype == WP_MISSILE){
976                                 p->flags |= PLAYER_FLAGS_KILLED_SELF_MISSILES;
977                         } else {
978                                 p->flags |= PLAYER_FLAGS_KILLED_SELF_UNKNOWN;
979                         }
980                 }
981
982                 // in multiplayer, record callsign of killer if killed by another player
983                 if ( (Game_mode & GM_MULTIPLAYER) && ( Objects[killer_objp->parent].flags & OF_PLAYER_SHIP) ) {
984                         int pnum;
985
986                         pnum = multi_find_player_by_object( &Objects[killer_objp->parent] );
987                         if ( pnum != -1 ) {
988                                 strcpy(p->killer_parent_name, Net_players[pnum].player->callsign);
989                         } else {
990                                 nprintf(("Network", "Couldn't find player object of weapon for killer of %s\n", p->callsign));
991                         }
992                 } else {
993                         strcpy(p->killer_parent_name, Ships[Objects[killer_objp->parent].instance].ship_name);
994                 }
995                 break;
996
997         case OBJ_SHOCKWAVE:
998                 p->killer_objtype=OBJ_SHOCKWAVE;
999                 p->killer_weapon_index=shockwave_weapon_index(killer_objp->instance);
1000                 p->killer_species = Ship_info[Ships[Objects[killer_objp->parent].instance].ship_info_index].species;
1001
1002                 if ( &Objects[killer_objp->parent] == Player_obj ) {
1003                         p->flags |= PLAYER_FLAGS_KILLED_SELF_SHOCKWAVE;
1004                 }
1005
1006                 if ( (Game_mode & GM_MULTIPLAYER) && ( Objects[killer_objp->parent].flags & OF_PLAYER_SHIP) ) {
1007                         int pnum;
1008
1009                         pnum = multi_find_player_by_object( &Objects[killer_objp->parent] );
1010                         if ( pnum != -1 ) {
1011                                 strcpy(p->killer_parent_name, Net_players[pnum].player->callsign);
1012                         } else {
1013                                 nprintf(("Network", "Couldn't find player object of shockwave for killer of %s\n", p->callsign));
1014                         }
1015                 } else {
1016                         strcpy(p->killer_parent_name, Ships[Objects[killer_objp->parent].instance].ship_name);
1017                 }
1018                 break;
1019
1020         case OBJ_SHIP:
1021                 p->killer_objtype=OBJ_SHIP;
1022                 p->killer_weapon_index=-1;
1023                 p->killer_species = Ship_info[Ships[killer_objp->instance].ship_info_index].species;
1024
1025                 if ( Ships[killer_objp->instance].flags & SF_EXPLODED ) {
1026                         p->flags |= PLAYER_FLAGS_KILLED_BY_EXPLOSION;
1027                 }
1028
1029                 if ( Ships[Objects[p->objnum].instance].wash_killed ) {
1030                         p->flags |= PLAYER_FLAGS_KILLED_BY_ENGINE_WASH;
1031                 }
1032
1033                 // in multiplayer, record callsign of killer if killed by another player
1034                 if ( (Game_mode & GM_MULTIPLAYER) && (killer_objp->flags & OF_PLAYER_SHIP) ) {
1035                         int pnum;
1036
1037                         pnum = multi_find_player_by_object( killer_objp );
1038                         if ( pnum != -1 ) {
1039                                 strcpy(p->killer_parent_name, Net_players[pnum].player->callsign);
1040                         } else {
1041                                 nprintf(("Network", "Couldn't find player object for killer of %s\n", p->callsign));
1042                         }
1043                 } else {
1044                         strcpy(p->killer_parent_name, Ships[killer_objp->instance].ship_name);
1045                 }
1046                 break;
1047         
1048         case OBJ_DEBRIS:
1049         case OBJ_ASTEROID:
1050                 if ( killer_objp->type == OBJ_DEBRIS ) {
1051                         p->killer_objtype = OBJ_DEBRIS;
1052                 } else {
1053                         p->killer_objtype = OBJ_ASTEROID;
1054                 }
1055                 p->killer_weapon_index=-1;
1056                 p->killer_species = SPECIES_NONE;
1057                 p->killer_parent_name[0] = '\0';
1058                 break;
1059
1060         case OBJ_BEAM:
1061                 int beam_obj;
1062                 beam_obj = beam_get_parent(killer_objp);
1063                 p->killer_species = SPECIES_NONE;               
1064                 p->killer_objtype = OBJ_BEAM;
1065                 if(beam_obj != -1){                     
1066                         if((Objects[beam_obj].type == OBJ_SHIP) && (Objects[beam_obj].instance >= 0)){
1067                                 strcpy(p->killer_parent_name, Ships[Objects[beam_obj].instance].ship_name);
1068                         }
1069                         p->killer_species = Ship_info[Ships[Objects[beam_obj].instance].ship_info_index].species;
1070                 } else {                        
1071                         strcpy(p->killer_parent_name, "");
1072                 }
1073                 break;
1074         
1075         case OBJ_NONE:
1076                 if ( Game_mode & GM_MULTIPLAYER ) {
1077                         Int3();
1078                 }
1079                 p->killer_objtype=-1;
1080                 p->killer_weapon_index=-1;
1081                 p->killer_parent_name[0]=0;
1082                 p->killer_species = SPECIES_NONE;
1083                 break;
1084
1085         default:
1086                 Int3();
1087                 break;
1088         }
1089 }
1090
1091 //      Say dead stuff.
1092 void show_dead_message(object *ship_obj, object *other_obj)
1093 {
1094         int pnum;
1095         player *player_p;
1096
1097         // not doing anything when a non player dies.
1098         if ( !(ship_obj->flags & OF_PLAYER_SHIP) ){
1099                 return;
1100         }
1101
1102         if(other_obj == NULL){
1103                 return;
1104         }
1105
1106         // Get a pointer to the player (we are assured a player ship was killed)
1107         if ( Game_mode & GM_NORMAL ) {
1108                 player_p = Player;
1109         } else {
1110                 // in multiplayer, get a pointer to the player that died.
1111                 pnum = multi_find_player_by_object( ship_obj );
1112                 if ( pnum == -1 ) {
1113                         //Int3();                               // this condition is bad bad bad -- get Allender
1114                         return;
1115                 }
1116                 player_p = Net_players[pnum].player;
1117         }
1118
1119         // multiplayer clients should already have this information.
1120         if ( !MULTIPLAYER_CLIENT ){
1121                 shiphit_record_player_killer( other_obj, player_p );
1122         }
1123
1124         // display a hud message is the guy killed isn't me (multiplayer only)
1125         /*
1126         if ( (Game_mode & GM_MULTIPLAYER) && (ship_obj != Player_obj) ) {
1127                 char death_text[256];
1128
1129                 player_generate_death_text( player_p, death_text );
1130                 HUD_sourced_printf(HUD_SOURCE_HIDDEN, death_text);
1131         }
1132         */
1133 }
1134
1135 /* JAS: THIS DOESN'T SEEM TO BE USED, SO I COMMENTED IT OUT
1136 //      Apply damage to a ship, destroying if necessary, etc.
1137 //      Returns portion of damage that exceeds ship shields, ie the "unused" portion of the damage.
1138 //      Note: This system does not use the mesh shield.  It applies damage to the overall ship shield.
1139 float apply_damage_to_ship(object *objp, float damage)
1140 {
1141         float   _ss;
1142
1143         add_shield_strength(objp, -damage);
1144
1145         // check if shields are below 0%, if so take leftover damage and apply to ship integrity
1146         if ((_ss = get_shield_strength(objp)) < 0.0f ) {
1147                 damage = -_ss;
1148                 set_shield_strength(objp, 0.0f);
1149         } else
1150                 damage = 0.0f;
1151
1152         return damage;
1153 }
1154 */
1155
1156 //      Do music processing for a ship hit.
1157 void ship_hit_music(object *ship_obj, object *other_obj)
1158 {
1159         ship* ship_p = &Ships[ship_obj->instance];
1160
1161         // Switch to battle track when a ship is hit by fire 
1162         //
1163         // If the ship hit has an AI class of none, it is a Cargo, NavBuoy or other non-aggressive
1164         // ship, so don't start the battle music        
1165         if (stricmp(Ai_class_names[Ai_info[ship_p->ai_index].ai_class], NOX("none"))) {
1166                 int team_1, team_2;
1167                 // Only start if ship hit and firing ship are from different teams
1168                 team_1 = Ships[ship_obj->instance].team;
1169                 switch ( other_obj->type ) {
1170                         case OBJ_SHIP:
1171                                 team_2 = Ships[other_obj->instance].team;
1172                                 if ( !stricmp(Ai_class_names[Ai_info[Ships[other_obj->instance].ai_index].ai_class], NOX("none")) ) {
1173                                         team_1 = team_2;
1174                                 }
1175                                 break;
1176
1177                         case OBJ_WEAPON:
1178                                 // parent of weapon is object num of ship that fired it
1179                                 team_2 = Ships[Objects[other_obj->parent].instance].team;       
1180                                 break;
1181
1182                         default:
1183                                 team_2 = team_1;
1184                                 break;  // Unexpected object type collided with ship, no big deal.
1185                 } // end switch
1186
1187                 if ( team_1 != team_2 )
1188                         event_music_battle_start();
1189         }
1190 }
1191
1192 //      Make sparks fly off a ship.
1193 // Currently used in misison_parse to create partially damaged ships.
1194 // NOTE: hitpos is in model coordinates on the detail[0] submodel (highest detail hull)
1195 // WILL NOT WORK RIGHT IF ON A ROTATING SUBMODEL
1196 void ship_hit_sparks_no_rotate(object *ship_obj, vector *hitpos)
1197 {
1198         ship            *ship_p = &Ships[ship_obj->instance];
1199
1200         int n = ship_p->num_hits;
1201         if (n >= MAX_SHIP_HITS) {
1202                 n = rand() % MAX_SHIP_HITS;
1203         } else {
1204                 ship_p->num_hits++;
1205         }
1206
1207         // No rotation.  Just make the spark
1208         ship_p->sparks[n].pos = *hitpos;
1209         ship_p->sparks[n].submodel_num = -1;
1210
1211         shipfx_emit_spark(ship_obj->instance, n);               // Create the first wave of sparks
1212
1213         if ( n == 0 )   {
1214                 ship_p->next_hit_spark = timestamp(0);          // when a hit spot will spark
1215         }
1216 }
1217
1218 // find the max number of sparks allowed for ship
1219 // limited for fighter by hull % others by radius.
1220 int get_max_sparks(object* ship_obj)
1221 {
1222         Assert(ship_obj->type == OBJ_SHIP);
1223         Assert((ship_obj->instance >= 0) && (ship_obj->instance < MAX_SHIPS));
1224         if(ship_obj->type != OBJ_SHIP){
1225                 return 1;
1226         }
1227         if((ship_obj->instance < 0) || (ship_obj->instance >= MAX_SHIPS)){
1228                 return 1;
1229         }
1230
1231         ship *ship_p = &Ships[ship_obj->instance];
1232         ship_info* si = &Ship_info[ship_p->ship_info_index];
1233         if (si->flags & SIF_FIGHTER) {
1234                 float hull_percent = ship_obj->hull_strength / Ship_info[ship_p->ship_info_index].initial_hull_strength;
1235
1236                 if (hull_percent > 0.8f) {
1237                         return 1;
1238                 } else if (hull_percent > 0.3f) {
1239                         return 2;
1240                 } else {
1241                         return 3;
1242                 }
1243         } else {
1244                 int num_sparks = (int) (ship_obj->radius * 0.08f);
1245                 if (num_sparks < 3) {
1246                         return 3;
1247                 } else if (num_sparks > MAX_SHIP_HITS) {
1248                         return MAX_SHIP_HITS;
1249                 } else {
1250                         return num_sparks;
1251                 }
1252         }
1253 }
1254
1255
1256 // helper function to qsort, sorting spark pairs by distance
1257 int spark_compare( const void *elem1, const void *elem2 )
1258 {
1259         spark_pair *pair1 = (spark_pair *) elem1;
1260         spark_pair *pair2 = (spark_pair *) elem2;
1261
1262         Assert(pair1->dist >= 0);
1263         Assert(pair2->dist >= 0);
1264
1265         if ( pair1->dist <  pair2->dist ) {
1266                 return -1;
1267         } else {
1268                 return 1;
1269         }
1270 }
1271
1272 // for big ships, when all spark slots are filled, make intelligent choice of one to be recycled
1273 int choose_next_spark(object *ship_obj, vector *hitpos)
1274 {
1275         int i, j, count, num_sparks, num_spark_pairs, spark_num;
1276         vector world_hitpos[MAX_SHIP_HITS];
1277         spark_pair spark_pairs[MAX_SPARK_PAIRS];
1278         ship *shipp = &Ships[ship_obj->instance];
1279
1280         // only choose next spark when all slots are full
1281         Assert(get_max_sparks(ship_obj) == Ships[ship_obj->instance].num_hits);
1282
1283         // get num_sparks
1284         num_sparks = Ships[ship_obj->instance].num_hits;
1285         Assert(num_sparks <= MAX_SHIP_HITS);
1286
1287         // get num_spark_paris -- only sort these
1288         num_spark_pairs = (num_sparks * num_sparks - num_sparks) / 2;
1289
1290         // get the world hitpos for all sparks
1291         bool model_started = false;
1292         for (spark_num=0; spark_num<num_sparks; spark_num++) {
1293                 if (shipp->sparks[spark_num].submodel_num != -1) {
1294                         if ( !model_started) {
1295                                 model_started = true;
1296                                 ship_model_start(ship_obj);
1297                         }
1298                         model_find_world_point(&world_hitpos[spark_num], &shipp->sparks[spark_num].pos, shipp->modelnum, shipp->sparks[spark_num].submodel_num, &ship_obj->orient, &ship_obj->pos);
1299                 } else {
1300                         // rotate sparks correctly with current ship orient
1301                         vm_vec_unrotate(&world_hitpos[spark_num], &shipp->sparks[spark_num].pos, &ship_obj->orient);
1302                         vm_vec_add2(&world_hitpos[spark_num], &ship_obj->pos);
1303                 }
1304         }
1305
1306         if (model_started) {
1307                 ship_model_stop(ship_obj);
1308         }
1309
1310         // check we're not making a spark in the same location as a current one
1311         for (i=0; i<num_sparks; i++) {
1312                 float dist = vm_vec_dist_squared(&world_hitpos[i], hitpos);
1313                 if (dist < 1) {
1314                         return i;
1315                 }
1316         }
1317
1318         // not same location, so maybe do random recyling
1319         if (frand() > 0.5f) {
1320                 return (rand() % num_sparks);
1321         }
1322
1323         // initialize spark pairs
1324         for (i=0; i<num_spark_pairs; i++) {
1325                 spark_pairs[i].index1 = 0;
1326                 spark_pairs[i].index2 = 0;
1327                 spark_pairs[i].dist = FLT_MAX;
1328         }
1329
1330         // set spark pairs
1331         count = 0;
1332         for (i=1; i<num_sparks; i++) {
1333                 for (j=0; j<i; j++) {
1334                         spark_pairs[count].index1 = i;
1335                         spark_pairs[count].index2 = j;
1336                         spark_pairs[count++].dist = vm_vec_dist_squared(&world_hitpos[i], &world_hitpos[j]);
1337                 }
1338         }
1339         Assert(count == num_spark_pairs);
1340
1341         // sort pairs
1342         qsort(spark_pairs, count, sizeof(spark_pair), spark_compare);
1343         //mprintf(("Min spark pair dist %.1f\n", spark_pairs[0].dist));
1344
1345         // look through the first few sorted pairs, counting number of indices of closest pair
1346         int index1 = spark_pairs[0].index1;
1347         int index2 = spark_pairs[0].index2;
1348         int count1 = 0;
1349         int count2 = 0;
1350
1351         for (i=1; i<6; i++) {
1352                 if (spark_pairs[i].index1 == index1) {
1353                         count1++;
1354                 }
1355                 if (spark_pairs[i].index2 == index1) {
1356                         count1++;
1357                 }
1358                 if (spark_pairs[i].index1 == index2) {
1359                         count2++;
1360                 }
1361                 if (spark_pairs[i].index2 == index2) {
1362                         count2++;
1363                 }
1364         }
1365
1366         // recycle spark which has most indices in sorted list of pairs
1367         if (count1 > count2) {
1368                 return index1;
1369         } else {
1370                 return index2;
1371         }
1372 }
1373
1374
1375 //      Make sparks fly off a ship.
1376 void ship_hit_create_sparks(object *ship_obj, vector *hitpos, int submodel_num)
1377 {
1378         vector  tempv;
1379         ship            *ship_p = &Ships[ship_obj->instance];
1380
1381         int n, max_sparks;
1382
1383         n = ship_p->num_hits;
1384         max_sparks = get_max_sparks(ship_obj);
1385
1386         if (n >= max_sparks)    {
1387                 if ( Ship_info[ship_p->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP) ) {
1388                         // large ship, choose intelligently
1389                         n = choose_next_spark(ship_obj, hitpos);
1390                 } else {
1391                         // otherwise, normal choice
1392                         n = rand() % max_sparks;
1393                 }
1394         } else {
1395                 ship_p->num_hits++;
1396         }
1397
1398         ship *pship = &Ships[ship_obj->instance];
1399
1400         bool instancing = false;
1401         // decide whether to do instancing
1402         if (submodel_num != -1) {
1403                 polymodel *pm = model_get(pship->modelnum);
1404                 if (pm->detail[0] != submodel_num) {
1405                         // submodel is not hull
1406                         // OPTIMIZE ... check if submodel can not rotate
1407                         instancing = true;
1408                 }
1409         }
1410
1411         if (instancing) {
1412                 // get the hit position in the subobject RF
1413                 ship_model_start(ship_obj);
1414                 vector temp_zero, temp_x, temp_y, temp_z;
1415                 model_find_world_point(&temp_zero, &vmd_zero_vector, pship->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
1416                 model_find_world_point(&temp_x, &vmd_x_vector, pship->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
1417                 model_find_world_point(&temp_y, &vmd_y_vector, pship->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
1418                 model_find_world_point(&temp_z, &vmd_z_vector, pship->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
1419                 ship_model_stop(ship_obj);
1420
1421                 // find submodel x,y,z axes
1422                 vm_vec_sub2(&temp_x, &temp_zero);
1423                 vm_vec_sub2(&temp_y, &temp_zero);
1424                 vm_vec_sub2(&temp_z, &temp_zero);
1425
1426                 // find displacement from submodel origin
1427                 vector diff;
1428                 vm_vec_sub(&diff, hitpos, &temp_zero);
1429
1430                 // find displacement from submodel origin in submodel RF
1431                 ship_p->sparks[n].pos.x = vm_vec_dotprod(&diff, &temp_x);
1432                 ship_p->sparks[n].pos.y = vm_vec_dotprod(&diff, &temp_y);
1433                 ship_p->sparks[n].pos.z = vm_vec_dotprod(&diff, &temp_z);
1434                 ship_p->sparks[n].submodel_num = submodel_num;
1435                 ship_p->sparks[n].end_time = timestamp(-1);
1436         } else {
1437                 // Rotate hitpos into ship_obj's frame of reference.
1438                 vm_vec_sub(&tempv, hitpos, &ship_obj->pos);
1439                 vm_vec_rotate(&ship_p->sparks[n].pos, &tempv, &ship_obj->orient);
1440                 ship_p->sparks[n].submodel_num = -1;
1441                 ship_p->sparks[n].end_time = timestamp(-1);
1442         }
1443
1444         // Create the first wave of sparks
1445         shipfx_emit_spark(ship_obj->instance, n);
1446
1447         if ( n == 0 )   {
1448                 ship_p->next_hit_spark = timestamp(0);          // when a hit spot will spark
1449         }
1450 }
1451
1452 //      Called from ship_hit_kill() when we detect the player has been killed.
1453 void player_died_start(object *killer_objp)
1454 {
1455         nprintf(("Network", "starting my player death\n"));
1456         gameseq_post_event(GS_EVENT_DEATH_DIED);        
1457         
1458 /*      vm_vec_scale_add(&Dead_camera_pos, &Player_obj->pos, &Player_obj->orient.fvec, -10.0f);
1459         vm_vec_scale_add2(&Dead_camera_pos, &Player_obj->orient.uvec, 3.0f);
1460         vm_vec_scale_add2(&Dead_camera_pos, &Player_obj->orient.rvec, 5.0f);
1461 */
1462
1463         //      Create a good vector for the camera to move along during death sequence.
1464         object  *other_objp = NULL;
1465
1466         // on multiplayer clients, there have been occasions where we haven't been able to determine
1467         // the killer of a ship (due to bogus/mismatched/timed-out signatures on the client side).  If
1468         // we don't know the killer, use the Player_obj as the other_objp for camera position.
1469         if ( killer_objp ) {
1470                 switch (killer_objp->type) {
1471                 case OBJ_WEAPON:
1472                 case OBJ_SHOCKWAVE:
1473                         other_objp = &Objects[killer_objp->parent];
1474                         break;
1475                 case OBJ_SHIP:
1476                 case OBJ_DEBRIS:
1477                 case OBJ_ASTEROID:
1478                 case OBJ_NONE:  //      Something that just got deleted due to also dying -- it happened to me! --MK.           
1479                         other_objp = killer_objp;
1480                         break;
1481
1482                 case OBJ_BEAM:
1483                         int beam_obj_parent;
1484                         beam_obj_parent = beam_get_parent(killer_objp);
1485                         if(beam_obj_parent == -1){
1486                                 other_objp = killer_objp;
1487                         } else {
1488                                 other_objp = &Objects[beam_obj_parent];
1489                         }
1490                         break;
1491
1492                 default:
1493                         Int3();         //      Killed by an object of a peculiar type.  What is it?
1494                         other_objp = killer_objp;       //      Enable to continue, just in case we shipped it with this bug...
1495                 }
1496         } else {
1497                 other_objp = Player_obj;
1498         }
1499
1500         vm_vec_add(&Original_vec_to_deader, &Player_obj->orient.fvec, &Player_obj->orient.rvec);
1501         vm_vec_scale(&Original_vec_to_deader, 2.0f);
1502         vm_vec_add2(&Original_vec_to_deader, &Player_obj->orient.uvec);
1503         vm_vec_normalize(&Original_vec_to_deader);
1504
1505         vector  vec_from_killer;
1506         vector  *side_vec;
1507         float           dist;
1508
1509         Assert(other_objp != NULL);
1510
1511         if (Player_obj == other_objp) {
1512                 dist = 50.0f;
1513                 vec_from_killer = Player_obj->orient.fvec;
1514         } else {
1515                 dist = vm_vec_normalized_dir(&vec_from_killer, &Player_obj->pos, &other_objp->pos);
1516         }
1517
1518         if (dist > 100.0f)
1519                 dist = 100.0f;
1520         vm_vec_scale_add(&Dead_camera_pos, &Player_obj->pos, &vec_from_killer, dist);
1521
1522         float   dot = vm_vec_dot(&Player_obj->orient.rvec, &vec_from_killer);
1523         if (fl_abs(dot) > 0.8f)
1524                 side_vec = &Player_obj->orient.fvec;
1525         else
1526                 side_vec = &Player_obj->orient.rvec;
1527         
1528         vm_vec_scale_add2(&Dead_camera_pos, side_vec, 10.0f);
1529
1530         Player_ai->target_objnum = -1;          //      Clear targeting.  Otherwise, camera pulls away from player as soon as he blows up.
1531
1532         // stop any playing emp effect
1533         emp_stop_local();
1534 }
1535
1536
1537 #define DEATHROLL_TIME                                          3000                    //      generic deathroll is 3 seconds (3 * 1000 milliseconds)
1538 #define MIN_PLAYER_DEATHROLL_TIME               1000                    // at least one second deathroll for a player
1539 #define DEATHROLL_ROTVEL_CAP                            6.3f                    // maximum added deathroll rotvel in rad/sec (about 1 rev / sec)
1540 #define DEATHROLL_ROTVEL_MIN                            0.8f                    // minimum added deathroll rotvel in rad/sec (about 1 rev / 12 sec)
1541 #define DEATHROLL_MASS_STANDARD                 50                              // approximate mass of lightest ship
1542 #define DEATHROLL_VELOCITY_STANDARD     70                              // deathroll rotvel is scaled according to ship velocity
1543 #define DEATHROLL_ROTVEL_SCALE                  4                               // constant determines how quickly deathroll rotvel is ramped up  (smaller is faster)
1544
1545 void ai_announce_ship_dying(object *dying_objp);
1546
1547 void saturate_fabs(float *f, float max)
1548 {
1549         if ( fl_abs(*f) > max) {
1550                 if (*f > 0)
1551                         *f = max;
1552                 else
1553                         *f = -max;
1554         }
1555 }
1556
1557 // function to do generic things when a ship explodes
1558 void ship_generic_kill_stuff( object *objp, float percent_killed )
1559 {
1560         float rotvel_mag;
1561         int     delta_time;
1562         ship    *sp;
1563
1564         Assert(objp->type == OBJ_SHIP);
1565         Assert(objp->instance >= 0 && objp->instance < MAX_SHIPS );
1566         if((objp->type != OBJ_SHIP) || (objp->instance < 0) || (objp->instance >= MAX_SHIPS)){
1567                 return;
1568         }
1569         sp = &Ships[objp->instance];
1570         ship_info *sip = &Ship_info[sp->ship_info_index];
1571
1572         // if recording demo
1573         if(Game_mode & GM_DEMO_RECORD){
1574                 demo_POST_ship_kill(objp);
1575         }
1576
1577         ai_announce_ship_dying(objp);
1578
1579         sp->flags |= SF_DYING;
1580         objp->phys_info.flags |= (PF_DEAD_DAMP | PF_REDUCED_DAMP);
1581         delta_time = (int) (DEATHROLL_TIME);
1582
1583         //      For smaller ships, subtract off time proportional to excess damage delivered.
1584         if (objp->radius < BIG_SHIP_MIN_RADIUS)
1585                 delta_time -=  (int) (1.01f - 4*percent_killed);
1586
1587         //      Cut down cargo death rolls.  Looks a little silly. -- MK, 3/30/98.
1588         if (sip->flags & SIF_CARGO) {
1589                 delta_time /= 4;
1590         }
1591         
1592         //      Prevent bogus timestamps.
1593         if (delta_time < 2)
1594                 delta_time = 2;
1595         
1596         if (objp->flags & OF_PLAYER_SHIP) {
1597                 //      Note: Kamikaze ships have no minimum death time.
1598                 if (!(Ai_info[Ships[objp->instance].ai_index].ai_flags & AIF_KAMIKAZE) && (delta_time < MIN_PLAYER_DEATHROLL_TIME))
1599                         delta_time = MIN_PLAYER_DEATHROLL_TIME;
1600         }
1601
1602         //nprintf(("AI", "ShipHit.cpp: Frame %i, Gametime = %7.3f, Ship %s will die in %7.3f seconds.\n", Framecount, f2fl(Missiontime), Ships[objp->instance].ship_name, (float) delta_time/1000.0f));
1603
1604         //      Make big ships have longer deathrolls.
1605         //      This is debug code by MK to increase the deathroll time so ships have time to evade the shockwave.
1606         //      Perhaps deathroll time should be specified in ships.tbl.
1607         float damage = ship_get_exp_damage(objp);
1608
1609         if (damage >= 250.0f)
1610                 delta_time += 3000 + (int)(damage*4.0f + 4.0f*objp->radius);
1611
1612         if (Ai_info[sp->ai_index].ai_flags & AIF_KAMIKAZE)
1613                 delta_time = 2;
1614
1615         // Knossos gets 7-10 sec to die, time for "little" explosions
1616         if (Ship_info[sp->ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
1617                 delta_time = 7000 + (int)(frand() * 3000.0f);
1618                 Ship_info[sp->ship_info_index].explosion_propagates = 0;
1619         }
1620         sp->final_death_time = timestamp(delta_time);   // Give him 3 secs to explode
1621
1622         if (sp->flags & SF_VAPORIZE) {
1623                 // Assert(Ship_info[sp->ship_info_index].flags & SIF_SMALL_SHIP);
1624
1625                 // LIVE FOR 100 MS
1626                 sp->final_death_time = timestamp(100);
1627         }
1628
1629         //nprintf(("AI", "Time = %7.3f: final_death_time set to %7.3f\n", (float) timestamp_ticker/1000.0f, (float) sp->final_death_time/1000.0f));
1630
1631         sp->pre_death_explosion_happened = 0;                           // The little fireballs haven't came in yet.
1632
1633         sp->next_fireball = timestamp(0);       //start one right away
1634
1635         ai_deathroll_start(objp);
1636
1637         // play death roll begin sound
1638         sp->death_roll_snd = snd_play_3d( &Snds[SND_DEATH_ROLL], &objp->pos, &View_position, objp->radius );
1639         if (objp == Player_obj)
1640                 joy_ff_deathroll();
1641
1642         // apply a whack
1643         //      rotational velocity proportional to original translational velocity, with a bit added in.
1644         //      Also, preserve half of original rotational velocity.
1645
1646         // At standard speed (70) and standard mass (50), deathroll rotvel should be capped at DEATHROLL_ROTVEL_CAP
1647         // Minimum deathroll velocity is set    DEATHROLL_ROTVEL_MIN
1648         // At lower speed, lower death rotvel (scaled linearly)
1649         // At higher mass, lower death rotvel (scaled logarithmically)
1650         // variable scale calculates the deathroll rotational velocity magnitude
1651         float logval = (float) log10(objp->phys_info.mass / (0.05f*DEATHROLL_MASS_STANDARD));
1652         float velval = ((vm_vec_mag_quick(&objp->phys_info.vel) + 3.0f) / DEATHROLL_VELOCITY_STANDARD);
1653         float   p1 = (float) (DEATHROLL_ROTVEL_CAP - DEATHROLL_ROTVEL_MIN);
1654
1655         rotvel_mag = (float) DEATHROLL_ROTVEL_MIN * 2.0f/(logval + 2.0f);
1656         rotvel_mag += (float) (p1 * velval/logval) * 0.75f;
1657
1658         // set so maximum velocity from rotation is less than 200
1659         if (rotvel_mag*objp->radius > 150) {
1660                 rotvel_mag = 150.0f / objp->radius;
1661         }
1662
1663         if (sp->dock_objnum_when_dead != -1) {
1664                 // don't change current rotvel
1665                 sp->deathroll_rotvel = objp->phys_info.rotvel;
1666         } else {
1667                 // if added rotvel is too random, we should decrease the random component, putting a const in front of the rotvel.
1668                 sp->deathroll_rotvel = objp->phys_info.rotvel;
1669                 sp->deathroll_rotvel.x += (frand() - 0.5f) * 2.0f * rotvel_mag;
1670                 saturate_fabs(&sp->deathroll_rotvel.x, 0.75f*DEATHROLL_ROTVEL_CAP);
1671                 sp->deathroll_rotvel.y += (frand() - 0.5f) * 3.0f * rotvel_mag;
1672                 saturate_fabs(&sp->deathroll_rotvel.y, 0.75f*DEATHROLL_ROTVEL_CAP);
1673                 sp->deathroll_rotvel.z += (frand() - 0.5f) * 6.0f * rotvel_mag;
1674                 // make z component  2x larger than larger of x,y
1675                 float largest_mag = max(fl_abs(sp->deathroll_rotvel.x), fl_abs(sp->deathroll_rotvel.y));
1676                 if (fl_abs(sp->deathroll_rotvel.z) < 2.0f*largest_mag) {
1677                         sp->deathroll_rotvel.z *= (2.0f * largest_mag / fl_abs(sp->deathroll_rotvel.z));
1678                 }
1679                 saturate_fabs(&sp->deathroll_rotvel.z, 0.75f*DEATHROLL_ROTVEL_CAP);
1680                 // nprintf(("Physics", "Frame: %i rotvel_mag: %5.2f, rotvel: (%4.2f, %4.2f, %4.2f)\n", Framecount, rotvel_mag, sp->deathroll_rotvel.x, sp->deathroll_rotvel.y, sp->deathroll_rotvel.z));
1681         }
1682
1683         
1684         // blow out his reverse thrusters. Or drag, same thing.
1685         objp->phys_info.rotdamp = (float) DEATHROLL_ROTVEL_SCALE / rotvel_mag;
1686         objp->phys_info.side_slip_time_const = 10000.0f;
1687
1688         vm_vec_zero(&objp->phys_info.max_vel);          // make so he can't turn on his own VOLITION anymore.
1689
1690         vm_vec_zero(&objp->phys_info.max_rotvel);       // make so he can't change speed on his own VOLITION anymore.
1691
1692 }
1693
1694 // called from ship_hit_kill if the ship is vaporized
1695 void ship_vaporize(ship *shipp)
1696 {
1697         object *ship_obj;
1698
1699         // sanity
1700         Assert(shipp != NULL);
1701         if(shipp == NULL){
1702                 return;
1703         }
1704         Assert((shipp->objnum >= 0) && (shipp->objnum < MAX_OBJECTS));
1705         if((shipp->objnum < 0) || (shipp->objnum >= MAX_OBJECTS)){
1706                 return;
1707         }
1708         ship_obj = &Objects[shipp->objnum];
1709
1710         // create debris shards
1711         create_vaporize_debris(ship_obj, &ship_obj->pos);
1712 }
1713
1714 //      *ship_obj was hit and we've determined he's been killed!  By *other_obj!
1715 void ship_hit_kill(object *ship_obj, object *other_obj, float percent_killed, int self_destruct)
1716 {
1717         ship *sp;
1718         char *killer_ship_name;
1719         int killer_damage_percent = NULL;
1720         object *killer_objp = NULL;
1721
1722         sp = &Ships[ship_obj->instance];
1723         show_dead_message(ship_obj, other_obj);
1724
1725         if (ship_obj == Player_obj) {
1726                 player_died_start(other_obj);
1727         }
1728
1729         // maybe vaporize him
1730         if(sp->flags & SF_VAPORIZE){
1731                 ship_vaporize(sp);
1732         }
1733
1734         // hehe
1735         extern void game_tst_mark(object *objp, ship *shipp);
1736         game_tst_mark(ship_obj, sp);
1737
1738         // single player and multiplayer masters evaluate the scoring and kill stuff
1739         if ( !MULTIPLAYER_CLIENT && !(Game_mode & GM_DEMO_PLAYBACK)) {
1740                 scoring_eval_kill( ship_obj );
1741
1742                 // ship is destroyed -- send this event to the mission log stuff to record this event.  Try to find who
1743                 // killed this ship.  scoring_eval_kill above should leave the obj signature of the ship who killed
1744                 // this guy (or a -1 if no one got the kill).
1745                 killer_ship_name = NULL;
1746                 killer_damage_percent = -1;
1747                 if ( sp->damage_ship_id[0] != -1 ) {
1748                         object *objp;
1749                         int sig;
1750
1751                         sig = sp->damage_ship_id[0];
1752                         for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
1753                                 if ( objp->signature == sig ){
1754                                         break;
1755                                 }
1756                         }
1757                         // if the object isn't around, the try to find the object in the list of ships which has exited                 
1758                         if ( objp != END_OF_LIST(&obj_used_list) ) {
1759                                 Assert ( (objp->type == OBJ_SHIP ) || (objp->type == OBJ_GHOST) );                                      // I suppose that this should be true
1760                                 killer_ship_name = Ships[objp->instance].ship_name;
1761
1762                                 killer_objp = objp;
1763                         } else {
1764                                 int ei;
1765
1766                                 ei = ship_find_exited_ship_by_signature( sig );
1767                                 if ( ei != -1 ){
1768                                         killer_ship_name = Ships_exited[ei].ship_name;
1769                                 }
1770                         }
1771                         killer_damage_percent = (int)(sp->damage_ship[0] * 100.0f);
1772                 }               
1773
1774                 if(!self_destruct){
1775                         // multiplayer
1776                         if(Game_mode & GM_MULTIPLAYER){
1777                                 char name1[256] = "";
1778                                 char name2[256] = "";
1779                                 int np_index;
1780
1781                                 // get first name                               
1782                                 np_index = multi_find_player_by_object(ship_obj);                               
1783                                 if((np_index >= 0) && (np_index < MAX_PLAYERS) && (Net_players[np_index].player != NULL)){
1784                                         strcpy(name1, Net_players[np_index].player->callsign);
1785                                 } else {
1786                                         strcpy(name1, sp->ship_name);
1787                                 }
1788
1789                                 // argh
1790                                 if((killer_objp != NULL) || (killer_ship_name != NULL)){
1791
1792                                         // second name
1793                                         if(killer_objp == NULL){
1794                                                 strcpy(name2, killer_ship_name);
1795                                         } else {
1796                                                 np_index = multi_find_player_by_object(killer_objp);
1797                                                 if((np_index >= 0) && (np_index < MAX_PLAYERS) && (Net_players[np_index].player != NULL)){
1798                                                         strcpy(name2, Net_players[np_index].player->callsign);
1799                                                 } else {
1800                                                         strcpy(name2, killer_ship_name);
1801                                                 }
1802                                         }                                       
1803                                 }
1804
1805                                 mission_log_add_entry(LOG_SHIP_DESTROYED, name1, name2, killer_damage_percent);
1806                         } else {
1807                                 // DKA: 8/23/99 allow message log in single player with no killer name
1808                                 //if(killer_ship_name != NULL){
1809                                 mission_log_add_entry(LOG_SHIP_DESTROYED, sp->ship_name, killer_ship_name, killer_damage_percent);
1810                                 //}
1811                         }
1812                 }
1813
1814                 // maybe praise the player for this kill
1815                 if ( (killer_damage_percent > 10) && (other_obj != NULL) && (other_obj->parent_sig == Player_obj->signature) ) {
1816                         ship_maybe_praise_player(sp);
1817                 }
1818         }
1819
1820         ship_generic_kill_stuff( ship_obj, percent_killed );
1821
1822         // mwa -- removed 2/25/98 -- why is this here?  ship_obj->flags &= ~(OF_PLAYER_SHIP);
1823         // if it is for observers, must deal with it a separate way!!!!
1824         if ( MULTIPLAYER_MASTER ) {
1825                 // check to see if this ship needs to be respawned
1826                 multi_respawn_check(ship_obj);          
1827                         
1828                 // send the kill packet to all players
1829                 // maybe send vaporize packet to all players
1830                 send_ship_kill_packet( ship_obj, other_obj, percent_killed, self_destruct );
1831         }       
1832
1833         // If ship from a player wing ship has died, then maybe play a scream
1834         if ( !(ship_obj->flags & OF_PLAYER_SHIP) && (sp->flags & SF_FROM_PLAYER_WING) ) {
1835                 ship_maybe_scream(sp);
1836         }
1837
1838         // If player is dying, have wingman lament (only in single player)
1839         if ( (Game_mode & GM_NORMAL) && (ship_obj == Player_obj) ) {
1840                 ship_maybe_lament();
1841         }
1842 }
1843
1844 // function to simply explode a ship where it is currently at
1845 void ship_self_destruct( object *objp )
1846 {       
1847         Assert ( objp->type == OBJ_SHIP );
1848
1849         // try and find a player
1850         if((Game_mode & GM_MULTIPLAYER) && (multi_find_player_by_object(objp) >= 0)){
1851                 int np_index = multi_find_player_by_object(objp);
1852                 if((np_index >= 0) && (np_index < MAX_PLAYERS) && (Net_players[np_index].player != NULL)){
1853                         mission_log_add_entry(LOG_SELF_DESTRUCT, Net_players[np_index].player->callsign, NULL );
1854                 } else {
1855                         mission_log_add_entry(LOG_SELF_DESTRUCT, Ships[objp->instance].ship_name, NULL );
1856                 }
1857         } else {
1858                 mission_log_add_entry(LOG_SELF_DESTRUCT, Ships[objp->instance].ship_name, NULL );
1859         }
1860         
1861         // check to see if this ship needs to be respawned
1862         if(MULTIPLAYER_MASTER){
1863                 // player ship?
1864                 int np_index = multi_find_player_by_object(objp);
1865                 if((np_index >= 0) && (np_index < MAX_PLAYERS) && MULTI_CONNECTED(Net_players[np_index]) && (Net_players[np_index].player != NULL)){
1866                         char msg[512] = "";
1867                         sprintf(msg, "%s %s", Net_players[np_index].player->callsign, XSTR("Self destructed", 1476));
1868
1869                         // send a message
1870                         send_game_chat_packet(Net_player, msg, MULTI_MSG_ALL, NULL, NULL, 2);
1871
1872                         // printf
1873                         if(!(Game_mode & GM_STANDALONE_SERVER)){
1874                                 HUD_printf(msg);
1875                         }
1876                 }
1877         }
1878
1879         // self destruct
1880         ship_hit_kill(objp, NULL, 1.0f, 1);     
1881 }
1882
1883 extern Homing_hits, Homing_misses;
1884
1885 // Call this instead of physics_apply_whack directly to 
1886 // deal with two ships docking properly.
1887 void ship_apply_whack(vector *force, vector *new_pos, object *objp)
1888 {
1889         if (objp->type == OBJ_SHIP)     {
1890                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_SUPPORT | SIF_CARGO)) {
1891                         int     docked_to_objnum;       
1892                         ai_info *aip;
1893
1894                         aip = &Ai_info[Ships[objp->instance].ai_index];
1895                 
1896                         if (aip->ai_flags & AIF_DOCKED) {
1897                                 docked_to_objnum = aip->dock_objnum;
1898                                 if (aip->dock_objnum != -1) {
1899                                         physics_apply_whack(force, new_pos, &Objects[docked_to_objnum].phys_info, &Objects[docked_to_objnum].orient, Objects[docked_to_objnum].phys_info.mass + objp->phys_info.mass);
1900                                         return;
1901                                 }
1902                         }
1903                 }
1904         }
1905         if (objp == Player_obj) {
1906                 nprintf(("Sandeep", "Playing stupid joystick effect\n"));
1907                 vector test;
1908                 vm_vec_unrotate(&test, force, &objp->orient);
1909
1910                 game_whack_apply( -test.x, -test.y );
1911         }
1912                                         
1913         physics_apply_whack(force, new_pos, &objp->phys_info, &objp->orient, objp->phys_info.mass);
1914 }
1915
1916 float Skill_level_player_damage_scale[NUM_SKILL_LEVELS] = {0.25f, 0.5f, 0.65f, 0.85f, 1.0f};
1917
1918
1919 // If a ship is dying and it gets hit, shorten its deathroll.
1920 //      But, if it's a player, don't decrease below MIN_PLAYER_DEATHROLL_TIME
1921 void shiphit_hit_after_death(object *ship_obj, float damage)
1922 {
1923         float   percent_killed;
1924         int     delta_time, time_remaining;
1925         ship    *shipp = &Ships[ship_obj->instance];
1926         ship_info       *sip = &Ship_info[shipp->ship_info_index];
1927
1928         // Since the explosion has two phases (final_death_time and really_final_death_time)
1929         // we should only shorten the deathroll time if that is the phase we're in.
1930         // And you can tell by seeing if the timestamp is valid, since it gets set to
1931         // invalid after it does the first large explosion.
1932         if ( !timestamp_valid(shipp->final_death_time) )        {
1933                 return;
1934         }
1935
1936         // Don't adjust vaporized ship
1937         if (shipp->flags & SF_VAPORIZE) {
1938                 return;
1939         }
1940
1941         //      Don't shorten deathroll on very large ships.
1942         if (ship_obj->radius > BIG_SHIP_MIN_RADIUS)
1943                 return;
1944
1945         percent_killed = damage/sip->initial_hull_strength;
1946         if (percent_killed > 1.0f)
1947                 percent_killed = 1.0f;
1948
1949         delta_time = (int) (4 * DEATHROLL_TIME * percent_killed);
1950         time_remaining = timestamp_until(shipp->final_death_time);
1951
1952         //nprintf(("AI", "Gametime = %7.3f, Time until %s dies = %7.3f, delta = %7.3f\n", f2fl(Missiontime), Ships[ship_obj->instance].ship_name, (float)time_remaining/1000.0f, delta_time));
1953         if (ship_obj->flags & OF_PLAYER_SHIP)
1954                 if (time_remaining < MIN_PLAYER_DEATHROLL_TIME)
1955                         return;
1956
1957         // nprintf(("AI", "Subtracting off %7.3f seconds from deathroll, reducing to %7.3f\n", (float) delta_time/1000.0f, (float) (time_remaining - delta_time)/1000.0f));
1958
1959         delta_time = time_remaining - delta_time;
1960         if (ship_obj->flags & OF_PLAYER_SHIP)
1961                 if (delta_time < MIN_PLAYER_DEATHROLL_TIME)
1962                         delta_time = MIN_PLAYER_DEATHROLL_TIME;
1963
1964         //      Prevent bogus timestamp.
1965         if (delta_time < 2)
1966                 delta_time = 2;
1967
1968         shipp->final_death_time = timestamp(delta_time);        // Adjust time until explosion.
1969 }
1970
1971 MONITOR( ShipHits );
1972 MONITOR( ShipNumDied );
1973
1974 int maybe_shockwave_damage_adjust(object *ship_obj, object *other_obj, float *damage)
1975 {
1976         ship_subsys *subsys;
1977         ship *shipp;
1978         float dist, nearest_dist = FLT_MAX;
1979         vector g_subobj_pos;
1980         float max_damage;
1981         shockwave *sw;
1982
1983         Assert(ship_obj->type == OBJ_SHIP);
1984         if (other_obj->type != OBJ_SHOCKWAVE) {
1985                 return 0;
1986         }
1987
1988         if (!(Ship_info[Ships[ship_obj->instance].ship_info_index].flags & SIF_HUGE_SHIP)) {
1989                 return 0;
1990         }
1991
1992         shipp = &Ships[ship_obj->instance];
1993         sw = &Shockwaves[other_obj->instance];
1994
1995         // find closest subsystem distance to shockwave origin
1996         for (subsys=GET_FIRST(&shipp->subsys_list); subsys != END_OF_LIST(&shipp->subsys_list); subsys = GET_NEXT(subsys) ) {
1997                 get_subsystem_world_pos(ship_obj, subsys, &g_subobj_pos);
1998                 dist = vm_vec_dist_quick(&g_subobj_pos, &other_obj->pos);
1999
2000                 if (dist < nearest_dist) {
2001                         nearest_dist = dist;
2002                 }
2003         }
2004
2005         // get max damage and adjust if needed to account for shockwave created from destroyed weapon
2006         max_damage = sw->damage;
2007         if (sw->flags & SW_WEAPON_KILL) {
2008                 max_damage *= 4.0f;
2009         }
2010
2011         // scale damage
2012         // floor of 25%, max if within inner_radius, linear between
2013         if (nearest_dist > sw->outer_radius) {
2014                 *damage = max_damage / 4.0f;
2015         } else if (nearest_dist < sw->inner_radius) {
2016                 *damage = max_damage;
2017         } else {
2018                 *damage = max_damage * (1.0f - 0.75f * (nearest_dist - sw->inner_radius) / (sw->outer_radius - sw->inner_radius));
2019         }
2020
2021         return 1;
2022 }
2023
2024 // ------------------------------------------------------------------------
2025 // ship_do_damage()
2026 //
2027 // Do damage assessment on a ship.    This should only be called
2028 // internally by ship_apply_global_damage and ship_apply_local_damage
2029 //
2030 // 
2031 //      input:  ship_obj                =>              object pointer for ship receiving damage
2032 //                              other_obj       =>              object pointer to object causing damage
2033 //                              hitpos          =>              impact world pos on the ship 
2034 //                              TODO:   get a better value for hitpos
2035 //                              damage          =>              damage to apply to the ship
2036 //                              shield_quadrant => which part of shield takes damage, -1 if not shield hit
2037 //                              wash_damage     =>              1 if damage is done by engine wash
2038 void ai_update_lethality(object *ship_obj, object *weapon_obj, float damage);
2039 static void ship_do_damage(object *ship_obj, object *other_obj, vector *hitpos, float damage, int shield_quadrant, int wash_damage=0)
2040 {
2041         ship *shipp;    
2042         float subsystem_damage = damage;                        // damage to be applied to subsystems
2043
2044         Assert(ship_obj->instance >= 0);
2045         Assert(ship_obj->type == OBJ_SHIP);
2046         shipp = &Ships[ship_obj->instance];
2047
2048         // maybe adjust damage done by shockwave for BIG|HUGE
2049         maybe_shockwave_damage_adjust(ship_obj, other_obj, &damage);
2050
2051         // update lethality of ship doing damage
2052         int update_lethality = FALSE;
2053         update_lethality = ((other_obj != NULL) && (other_obj->type == OBJ_WEAPON) && (other_obj->instance >= 0) && (other_obj->instance < MAX_WEAPONS));
2054         update_lethality = update_lethality || ((other_obj != NULL) && (other_obj->type == OBJ_SHOCKWAVE) && (other_obj->instance >= 0) && (other_obj->instance < MAX_SHOCKWAVES));
2055         if (update_lethality) {
2056                 ai_update_lethality(ship_obj, other_obj, damage);
2057         }
2058
2059         // if this is a weapon
2060         if((other_obj != NULL) && (other_obj->type == OBJ_WEAPON) && (other_obj->instance >= 0) && (other_obj->instance < MAX_WEAPONS)){
2061                 damage *= weapon_get_damage_scale(&Weapon_info[Weapons[other_obj->instance].weapon_info_index], other_obj, ship_obj);
2062         }
2063
2064         MONITOR_INC( ShipHits, 1 );
2065
2066         //      Don't damage player ship in the process of warping out.
2067         if ( Player->control_mode >= PCM_WARPOUT_STAGE2 )       {
2068                 if ( ship_obj == Player_obj ){
2069                         return;
2070                 }
2071         }
2072
2073         if ( (other_obj != NULL) && (other_obj->type == OBJ_WEAPON) ) {         
2074                 // for tvt and dogfight missions, don't scale damage
2075                 if( (Game_mode & GM_MULTIPLAYER) && ((Netgame.type_flags & NG_TYPE_TEAM) || (Netgame.type_flags & NG_TYPE_DOGFIGHT)) ){
2076                 } else {
2077                         // Do a little "skill" balancing for the player in single player and coop multiplayer
2078                         if (ship_obj->flags & OF_PLAYER_SHIP)   {
2079                                 damage *= Skill_level_player_damage_scale[Game_skill_level];
2080                                 subsystem_damage *= Skill_level_player_damage_scale[Game_skill_level];
2081                         }               
2082                 }
2083         }
2084
2085         // if this is not a laser, or i'm not a multiplayer client
2086         // apply pain to me
2087         if((other_obj != NULL) && ((Weapon_info[Weapons[other_obj->instance].weapon_info_index].subtype != WP_LASER) || !MULTIPLAYER_CLIENT) && (Player_obj != NULL) && (ship_obj == Player_obj)){
2088                 ship_hit_pain(damage);
2089         }       
2090
2091         // If the ship is invulnerable, do nothing
2092         if (ship_obj->flags & OF_INVULNERABLE)  {
2093                 return;
2094         }
2095
2096         //      if ship is already dying, shorten deathroll.
2097         if (shipp->flags & SF_DYING) {
2098                 shiphit_hit_after_death(ship_obj, damage);
2099                 return;
2100         }
2101         
2102         //      If we hit the shield, reduce it's strength and found
2103         // out how much damage is left over.
2104         if ( shield_quadrant > -1 && !(ship_obj->flags & OF_NO_SHIELDS) )       {
2105                 float shield_factor = -1.0f;
2106                 int     weapon_info_index;              
2107
2108                 weapon_info_index = shiphit_get_damage_weapon(other_obj);
2109                 if ( weapon_info_index >= 0 ) {
2110                         shield_factor = Weapon_info[weapon_info_index].shield_factor;
2111                 }
2112
2113                 if ( shield_factor >= 0 ) {
2114                         damage *= shield_factor;
2115                         subsystem_damage *= shield_factor;
2116                 }
2117
2118                 if ( damage > 0 ) {
2119                         float pre_shield = damage;
2120
2121                         damage = apply_damage_to_shield(ship_obj, shield_quadrant, damage);
2122
2123                         if(damage > 0.0f){
2124                                 subsystem_damage *= (damage / pre_shield);
2125                         } else {
2126                                 subsystem_damage = 0.0f;
2127                         }
2128                 }
2129
2130                 // if shield damage was increased, don't carry over leftover damage at scaled level
2131                 if ( shield_factor > 1 ) {
2132                         damage /= shield_factor;
2133
2134                         subsystem_damage /= shield_factor;
2135                 }
2136         }
2137                         
2138         // Apply leftover damage to the ship's subsystem and hull.
2139         if ( (damage > 0.0f) || (subsystem_damage > 0.0f) )     {
2140                 int     weapon_info_index;              
2141
2142                 float pre_subsys = subsystem_damage;
2143                 subsystem_damage = do_subobj_hit_stuff(ship_obj, other_obj, hitpos, subsystem_damage);
2144                 if(subsystem_damage > 0.0f){
2145                         damage *= (subsystem_damage / pre_subsys);
2146                 } else {
2147                         damage = 0.0f;
2148                 }
2149
2150                 // continue with damage?
2151                 if(damage > 0.0){
2152                         weapon_info_index = shiphit_get_damage_weapon(other_obj);
2153                         if ( weapon_info_index >= 0 ) {
2154                                 if (Weapon_info[weapon_info_index].wi_flags & WIF_PUNCTURE) {
2155                                         damage /= 4;
2156                                 }
2157
2158                                 damage *= Weapon_info[weapon_info_index].armor_factor;
2159                         }
2160
2161                         // if ship is flagged as can not die, don't let it die
2162                         if (ship_obj->flags & OF_GUARDIAN) {
2163                                 float min_hull_strength = 0.01f * Ship_info[Ships[ship_obj->instance].ship_info_index].initial_hull_strength;
2164                                 if ( (ship_obj->hull_strength - damage) < min_hull_strength ) {
2165                                         // find damage needed to take object to min hull strength
2166                                         damage = ship_obj->hull_strength - min_hull_strength;
2167
2168                                         // make sure damage is positive
2169                                         damage = max(0, damage);
2170                                 }
2171                         }
2172
2173                         // multiplayer clients don't do damage
2174                         if(((Game_mode & GM_MULTIPLAYER) && MULTIPLAYER_CLIENT) || (Game_mode & GM_DEMO_PLAYBACK)){
2175                         } else {
2176                                 ship_obj->hull_strength -= damage;              
2177                         }
2178
2179                         // let damage gauge know that player ship just took damage
2180                         if ( Player_obj == ship_obj ) {
2181                                 hud_gauge_popup_start(HUD_DAMAGE_GAUGE, 5000);
2182                         }
2183                 
2184                         // DB - removed 1/12/99 - scoring code properly bails if MULTIPLAYER_CLIENT
2185                         // in multiplayer, if I am not the host, get out of this function here!!
2186                         //if ( (Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER) ) {
2187                                 //return;
2188                         //}             
2189
2190                         switch (other_obj->type) {
2191                         case OBJ_SHOCKWAVE:
2192                                 scoring_add_damage(ship_obj,other_obj,damage);
2193                                 break;
2194                         case OBJ_ASTEROID:
2195                                 // don't call scoring for asteroids
2196                                 break;
2197                         case OBJ_WEAPON:
2198                                 if((other_obj->parent < 0) || (other_obj->parent >= MAX_OBJECTS)){
2199                                         scoring_add_damage(ship_obj, NULL, damage);
2200                                 } else {
2201                                         scoring_add_damage(ship_obj, &Objects[other_obj->parent], damage);
2202                                 }
2203                                 break;
2204                         default:
2205                                 break;
2206                         }
2207
2208                         if (ship_obj->hull_strength <= 0.0f) {
2209
2210                                 MONITOR_INC( ShipNumDied, 1 );
2211
2212                                 ship_info       *sip = &Ship_info[shipp->ship_info_index];
2213
2214                                 // If massive beam hitting small ship, vaporize  otherwise normal damage pipeline
2215                                 // Only vaporize once
2216                                 // multiplayer clients should skip this
2217                                 if(!MULTIPLAYER_CLIENT){
2218                                         if ( !(shipp->flags & SF_VAPORIZE) ) {
2219                                                 // Only small ships can be vaporized
2220                                                 if (sip->flags & (SIF_SMALL_SHIP)) {
2221                                                         if (other_obj->type == OBJ_BEAM) {
2222                                                                 int beam_weapon_info_index = beam_get_weapon_info_index(other_obj);
2223                                                                 if ( (beam_weapon_info_index > -1) && (Weapon_info[beam_weapon_info_index].wi_flags & (WIF_BEAM|WIF_HUGE)) ) {                                                          
2224                                                                         // Flag as vaporized
2225                                                                         shipp->flags |= SF_VAPORIZE;                                                            
2226                                                                 }
2227                                                         }
2228                                                 }
2229                                         }
2230                                 }
2231                                 
2232                                 // maybe engine wash death
2233                                 if (wash_damage) {
2234                                         shipp->wash_killed = 1;
2235                                 }
2236
2237                                 float percent_killed = -ship_obj->hull_strength/sip->initial_hull_strength;
2238                                 if (percent_killed > 1.0f){
2239                                         percent_killed = 1.0f;
2240                                 }
2241
2242                                 if ( !(shipp->flags & SF_DYING) && !MULTIPLAYER_CLIENT && !(Game_mode & GM_DEMO_PLAYBACK)){  // if not killed, then kill
2243                                         ship_hit_kill(ship_obj, other_obj, percent_killed, 0);
2244                                 }
2245                         }
2246                 }
2247         }
2248
2249         // if the hitting object is a weapon, maybe do some fun stuff here
2250         if(other_obj->type == OBJ_WEAPON){
2251                 weapon_info *wip;
2252                 Assert(other_obj->instance >= 0);
2253                 if(other_obj->instance < 0){
2254                         return;
2255                 }
2256                 Assert(Weapons[other_obj->instance].weapon_info_index >= 0);
2257                 if(Weapons[other_obj->instance].weapon_info_index < 0){
2258                         return;
2259                 }
2260                 wip = &Weapon_info[Weapons[other_obj->instance].weapon_info_index];
2261
2262                 // if its a leech weapon
2263                 if(wip->wi_flags & WIF_ENERGY_SUCK){
2264                         // reduce afterburner fuel
2265                         shipp->afterburner_fuel -= wip->afterburner_reduce;
2266                         shipp->afterburner_fuel = (shipp->afterburner_fuel < 0.0f) ? 0.0f : shipp->afterburner_fuel;
2267
2268                         // reduce weapon energy
2269                         shipp->weapon_energy -= wip->weapon_reduce;
2270                         shipp->weapon_energy = (shipp->weapon_energy < 0.0f) ? 0.0f : shipp->weapon_energy;
2271                 }
2272         }
2273 }
2274
2275 // This gets called to apply damage when something hits a particular point on a ship.
2276 // This assumes that whoever called this knows if the shield got hit or not.
2277 // hitpos is in world coordinates.
2278 // if shield_quadrant is not -1, then that part of the shield takes damage properly.
2279 void ship_apply_local_damage(object *ship_obj, object *other_obj, vector *hitpos, float damage, int shield_quadrant, bool create_spark, int submodel_num, vector *hit_normal)
2280 {
2281         ship *ship_p    = &Ships[ship_obj->instance];   
2282
2283         //      If got hit by a weapon, tell the AI so it can react.  Only do this line in single player,
2284         // or if I am the master in a multiplayer game
2285         if ( other_obj->type == OBJ_WEAPON && ( !(Game_mode & GM_MULTIPLAYER) || ((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_AM_MASTER)) )) {
2286                 weapon  *wp;
2287
2288                 wp = &Weapons[other_obj->instance];
2289                 //      If weapon hits ship on same team and that ship not targeted and parent of weapon not player,
2290                 //      don't do damage.
2291                 //      Ie, player can always do damage.  AI can only damage team if that ship is targeted.
2292                 if (wp->target_num != ship_obj-Objects) {
2293                         if ((ship_p->team == wp->team) && !(Objects[other_obj->parent].flags & OF_PLAYER_SHIP) ) {
2294                                 /*char  ship_name[64];
2295
2296                                 if (other_obj->parent_type == OBJ_SHIP) {
2297                                         strcpy(ship_name, Ships[Objects[other_obj->parent].instance].ship_name);
2298                                 } else
2299                                         strcpy(ship_name, XSTR("[not a ship]",-1));
2300                                 */
2301                                 // nprintf(("AI", "Ignoring hit on %s by weapon #%i, parent = %s\n", ship_p->ship_name, other_obj-Objects, ship_name));
2302                                 return;
2303                         }
2304                 }
2305         }
2306
2307         // only want to check the following in single player or if I am the multiplayer game server
2308         if ( !MULTIPLAYER_CLIENT && !(Game_mode & GM_DEMO_PLAYBACK) && ((other_obj->type == OBJ_SHIP) || (other_obj->type == OBJ_WEAPON)) ){
2309                 ai_ship_hit(ship_obj, other_obj, hitpos, shield_quadrant, hit_normal);
2310         }
2311
2312         //      Cut damage done on the player by 4x in training missions, but do full accredidation
2313         if ( The_mission.game_type & MISSION_TYPE_TRAINING ){
2314                 if (ship_obj == Player_obj){
2315                         damage /= 4.0f;
2316                 }
2317         }       
2318
2319         // send a packet in multiplayer -- but don't sent it if the ship is already dying.  Clients can
2320         // take care of dealing with ship hits after a ship is already dead.
2321         // if ( (MULTIPLAYER_MASTER) && !(ship_p->flags & SF_DYING) ){
2322                 // if this is a player ship which is not mine, send him a ship hit packet
2323                 // int np_index = multi_find_player_by_object(ship_obj);
2324                 // if((np_index > 0) && (np_index < MAX_PLAYERS) && (np_index != MY_NET_PLAYER_NUM) && MULTI_CONNECTED(Net_players[np_index])){
2325                         // send_ship_hit_packet( ship_obj, other_obj, hitpos, damage, shield_quadrant, submodel_num, &Net_players[np_index]);
2326                 // }
2327         // }
2328
2329         // maybe tag the ship
2330         if(!MULTIPLAYER_CLIENT && (other_obj->type == OBJ_WEAPON) && (Weapon_info[Weapons[other_obj->instance].weapon_info_index].wi_flags & WIF_TAG)) {
2331                 if (Weapon_info[Weapons[other_obj->instance].weapon_info_index].tag_level == 1) {
2332                         Ships[ship_obj->instance].tag_left = Weapon_info[Weapons[other_obj->instance].weapon_info_index].tag_time;
2333                         Ships[ship_obj->instance].tag_total = Ships[ship_obj->instance].tag_left;
2334                         if (Ships[ship_obj->instance].time_first_tagged == 0) {
2335                                 Ships[ship_obj->instance].time_first_tagged = Missiontime;
2336                         }
2337                         mprintf(("TAGGED %s for %f seconds\n", Ships[ship_obj->instance].ship_name, Ships[ship_obj->instance].tag_left));
2338                 } else if (Weapon_info[Weapons[other_obj->instance].weapon_info_index].tag_level == 2) {
2339                         Ships[ship_obj->instance].level2_tag_left = Weapon_info[Weapons[other_obj->instance].weapon_info_index].tag_time;
2340                         Ships[ship_obj->instance].level2_tag_total = Ships[ship_obj->instance].level2_tag_left;
2341                         if (Ships[ship_obj->instance].time_first_tagged == 0) {
2342                                 Ships[ship_obj->instance].time_first_tagged = Missiontime;
2343                         }
2344                         mprintf(("Level 2 TAGGED %s for %f seconds\n", Ships[ship_obj->instance].ship_name, Ships[ship_obj->instance].level2_tag_left));
2345                 } else {
2346                         Int3(); // unknown tag level
2347                 }
2348         }
2349
2350
2351 #ifndef NDEBUG
2352         if (other_obj->type == OBJ_WEAPON) {
2353                 weapon_info     *wip = &Weapon_info[Weapons[other_obj->instance].weapon_info_index];
2354                 if (wip->wi_flags & WIF_HOMING) {
2355                         Homing_hits++;
2356                         // nprintf(("AI", " Hit!  Hits = %i/%i\n", Homing_hits, (Homing_hits + Homing_misses)));
2357                 }
2358         }
2359 #endif
2360
2361         
2362         if ( Event_Music_battle_started == 0 )  {
2363                 ship_hit_music(ship_obj, other_obj);
2364         }
2365         
2366
2367         if (damage < 0.0f){
2368                 damage = 0.0f;
2369         }
2370
2371         // evaluate any possible player stats implications
2372         scoring_eval_hit(ship_obj,other_obj);
2373
2374         ship_do_damage(ship_obj, other_obj, hitpos, damage, shield_quadrant );
2375
2376         // DA 5/5/98: move ship_hit_create_sparks() after do_damage() since number of sparks depends on hull strength
2377         // doesn't hit shield and we want sparks
2378         if ((shield_quadrant == MISS_SHIELDS) && create_spark)  {
2379                 // check if subsys destroyed
2380                 if ( !is_subsys_destroyed(ship_p, submodel_num) ) {
2381                         ship_hit_create_sparks(ship_obj, hitpos, submodel_num);
2382                 }
2383                 //fireball_create( hitpos, FIREBALL_SHIP_EXPLODE1, OBJ_INDEX(ship_obj), 0.25f );
2384         }
2385 }
2386
2387
2388
2389 // This gets called to apply damage when a damaging force hits a ship, but at no 
2390 // point in particular.  Like from a shockwave.   This routine will see if the
2391 // shield got hit and if so, apply damage to it.
2392 // You can pass force_center==NULL if you the damage doesn't come from anywhere,
2393 // like for debug keys to damage an object or something.  It will 
2394 // assume damage is non-directional and will apply it correctly.   
2395 void ship_apply_global_damage(object *ship_obj, object *other_obj, vector *force_center, float damage )
2396 {                               
2397         vector tmp, world_hitpos;
2398
2399         if ( force_center )     {
2400                 int shield_quad;
2401                 vector local_hitpos;
2402
2403                 // find world hitpos
2404                 vm_vec_sub( &tmp, force_center, &ship_obj->pos );
2405                 vm_vec_normalize_safe( &tmp );
2406                 vm_vec_scale_add( &world_hitpos, &ship_obj->pos, &tmp, ship_obj->radius );
2407
2408                 // Rotate world_hitpos into local coordinates (local_hitpos)
2409                 vm_vec_sub(&tmp, &world_hitpos, &ship_obj->pos );
2410                 vm_vec_rotate( &local_hitpos, &tmp, &ship_obj->orient );
2411
2412                 // shield_quad = quadrant facing the force_center
2413                 shield_quad = get_quadrant(&local_hitpos);
2414
2415                 // world_hitpos use force_center for shockwave
2416                 if (other_obj->type == OBJ_SHOCKWAVE && Ship_info[Ships[ship_obj->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
2417                         world_hitpos = *force_center;
2418                 }
2419
2420                 // Do damage on local point             
2421                 ship_do_damage(ship_obj, other_obj, &world_hitpos, damage, shield_quad );
2422         } else {
2423                 // Since an force_center wasn't specified, this is probably just a debug key
2424                 // to kill an object.   So pick a shield quadrant and a point on the
2425                 // radius of the object.   
2426                 vm_vec_scale_add( &world_hitpos, &ship_obj->pos, &ship_obj->orient.fvec, ship_obj->radius );
2427
2428                 for (int i=0; i<MAX_SHIELD_SECTIONS; i++){
2429                         ship_do_damage(ship_obj, other_obj, &world_hitpos, damage/MAX_SHIELD_SECTIONS, i);
2430                 }
2431         }
2432
2433         // AL 3-30-98: Show flashing blast icon if player ship has taken blast damage
2434         if ( ship_obj == Player_obj ) {
2435                 // only show blast icon if playing on medium skill or lower
2436                 if ( Game_skill_level <= 2 ) {
2437                         hud_start_text_flash(XSTR("Blast", 1428), 2000);
2438                 }
2439         }
2440
2441         // evaluate any player stats scoring conditions (specifically, blasts from remotely detonated secondary weapons)
2442         scoring_eval_hit(ship_obj,other_obj,1); 
2443 }
2444
2445 void ship_apply_wash_damage(object *ship_obj, object *other_obj, float damage)
2446 {
2447         vector world_hitpos, direction_vec, rand_vec;
2448
2449         // Since an force_center wasn't specified, this is probably just a debug key
2450         // to kill an object.   So pick a shield quadrant and a point on the
2451         // radius of the object
2452         vm_vec_rand_vec_quick(&rand_vec);
2453         vm_vec_scale_add(&direction_vec, &ship_obj->orient.fvec, &rand_vec, 0.5f);
2454         vm_vec_normalize_quick(&direction_vec);
2455         vm_vec_scale_add( &world_hitpos, &ship_obj->pos, &direction_vec, ship_obj->radius );
2456
2457         // Do damage to hull and not to shields
2458         ship_do_damage(ship_obj, other_obj, &world_hitpos, damage, -1, 1);
2459
2460         // AL 3-30-98: Show flashing blast icon if player ship has taken blast damage
2461         if ( ship_obj == Player_obj ) {
2462                 // only show blast icon if playing on medium skill or lower
2463                 if ( Game_skill_level <= 2 ) {
2464                         hud_start_text_flash(XSTR("Engine Wash", 1429), 2000);
2465                 }
2466         }
2467
2468         // evaluate any player stats scoring conditions (specifically, blasts from remotely detonated secondary weapons)
2469         scoring_eval_hit(ship_obj,other_obj,1);
2470 }
2471
2472 // player pain
2473 void ship_hit_pain(float damage)
2474 {
2475         game_flash( damage/15.0f, -damage/30.0f, -damage/30.0f );
2476
2477         // kill any active popups when you get hit.
2478         if ( Game_mode & GM_MULTIPLAYER ){
2479                 popup_kill_any_active();
2480         }
2481 }