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