]> icculus.org git repositories - taylor/freespace2.git/blob - src/debris/debris.cpp
implemented two assembly stubs.
[taylor/freespace2.git] / src / debris / debris.cpp
1 /*
2  * $Logfile: /Freespace2/code/Debris/Debris.cpp $
3  * $Revision$
4  * $Date$
5  * $Author$
6  *
7  * Code for the pieces of exploding object debris.
8  *
9  * $Log$
10  * Revision 1.2  2002/05/28 08:52:03  relnev
11  * implemented two assembly stubs.
12  *
13  * cleaned up a few warnings.
14  *
15  * added a little demo hackery to make it progress a little farther.
16  *
17  * Revision 1.1.1.1  2002/05/03 03:28:08  root
18  * Initial import.
19  *
20  * 
21  * 16    8/01/99 1:13p Dave
22  * Fixed objsnd problem with hull debris pieces.
23  * 
24  * 15    7/01/99 4:23p Dave
25  * Full support for multiple linked ambient engine sounds. Added "big
26  * damage" flag.
27  * 
28  * 14    7/01/99 11:44a Dave
29  * Updated object sound system to allow multiple obj sounds per ship.
30  * Added hit-by-beam sound. Added killed by beam sound.
31  * 
32  * 13    5/18/99 11:50a Andsager
33  * Remove unused object type OBJ_GHOST_SAVE
34  * 
35  * 12    5/14/99 11:50a Andsager
36  * Added vaporize for SMALL ships hit by HUGE beams.  Modified dying
37  * frame.  Enlarged debris shards and range at which visible.
38  * 
39  * 11    4/23/99 12:01p Johnson
40  * Added SIF_HUGE_SHIP
41  * 
42  * 10    2/26/99 4:14p Dave
43  * Put in the ability to have multiple shockwaves for ships.
44  * 
45  * 9     1/20/99 6:04p Dave
46  * Another bit of stuff for beam weapons. Ships will properly use them
47  * now, although they're really deadly.
48  * 
49  * 8     12/03/98 3:14p Andsager
50  * Check in code that checks rotating submodel actually has ship subsystem
51  * 
52  * 7     11/19/98 11:07p Andsager
53  * Check in of physics and collision detection of rotating submodels
54  * 
55  * 6     11/13/98 10:13a Andsager
56  * simplify collision code
57  * 
58  * 5     11/05/98 5:55p Dave
59  * Big pass at reducing #includes
60  * 
61  * 4     10/23/98 1:11p Andsager
62  * Make ship sparks emit correctly from rotating structures.
63  * 
64  * 3     10/16/98 1:22p Andsager
65  * clean up header files
66  * 
67  * 2     10/07/98 10:52a Dave
68  * Initial checkin.
69  * 
70  * 1     10/07/98 10:48a Dave
71  * 
72  * 119   8/28/98 3:28p Dave
73  * EMP effect done. AI effects may need some tweaking as required.
74  * 
75  * 118   5/03/98 5:41p Mike
76  * Add Framecount to nprintf.
77  * 
78  * 117   4/15/98 10:00p Allender
79  * make debris have own signature set.
80  * 
81  * 116   4/15/98 9:42a Adam
82  * added 2 more explosion types (1, actually, but placeholder for 2)
83  * 
84  * 115   4/13/98 4:52p Allender
85  * remove AI_frametime and us flFrametime instead.  Make lock warning work
86  * in multiplayer for aspect seeking missiles.  Debris fixups
87  * 
88  * 114   4/10/98 12:16p Allender
89  * fix ship hit kill and debris packets
90  * 
91  * 113   4/09/98 5:43p Allender
92  * multiplayer network object fixes.  debris and self destructed ships
93  * should all sync up.  Fix problem where debris pieces (hull pieces) were
94  * not getting a net signature
95  * 
96  * 112   4/01/98 5:34p John
97  * Made only the used POFs page in for a level.   Reduced some interp
98  * arrays.    Made custom detail level work differently.
99  * 
100  * 111   3/31/98 5:11p John
101  * Removed demo/save/restore.  Made NDEBUG defined compile.  Removed a
102  * bunch of debug stuff out of player file.  Made model code be able to
103  * unload models and malloc out only however many models are needed.
104  * 
105  * 110   3/26/98 5:21p John
106  * Added new code to preload all bitmaps at the start of a level.
107  * Commented it out, though.
108  * 
109  * 109   3/23/98 12:20p Andsager
110  * Enable collision from rotation in ship_debris and ship_debris
111  * collisions.
112  * 
113  * 108   3/19/98 12:09p John
114  * Fixed a bug using 6 characters.   r_heavy was using local coordinates
115  * instead of world so all asteroid-ship and debris-ship hitpos's were in
116  * the wrong spot.  Ok, I rearreanged some code to make it clearer also.
117  * 
118  * 
119  * 107   3/12/98 6:47p John
120  * MAde arcs on debris further than objrad*50 not render.
121  * 
122  * 106   3/09/98 2:10p Andsager
123  * Put in checks for debris (other) with excessive velocity.
124  * 
125  * 105   2/26/98 10:07p Hoffoss
126  * Rewrote state saving and restoring to fix bugs and simplify the code.
127  * 
128  * 104   2/22/98 12:19p John
129  * Externalized some strings
130  * 
131  * 103   2/20/98 8:31p Lawrance
132  * Add radius parm to sound_play_3d()
133  * 
134  * 102   2/10/98 6:43p Lawrance
135  * Moved asteroid code to a separate lib.
136  * 
137  * 101   2/07/98 2:14p Mike
138  * Improve asteroid splitting.  Add ship:asteroid collisions.  Timestamp
139  * ship:debris collisions.
140  * 
141  * 100   2/06/98 7:45p John
142  * Reversed order of asteroid models so blown up ones are smaller.  
143  * 
144  * 99    2/06/98 7:28p John
145  * Made debris and particles not get created if > 200 m from eye.   Added
146  * max_velocity to asteroid's physics info for aiding in throwing out
147  * collision pairs.
148  * 
149  * 98    2/06/98 3:08p Mike
150  * More asteroid stuff, including resolving conflicts between the two
151  * asteroid_field structs!
152  * 
153  * 97    2/06/98 12:25a Mike
154  * More asteroid stuff.
155  * 
156  * 96    2/05/98 9:41p Mike
157  * Asteroid work, intermediate checkin to resolve compile errors.
158  * 
159  * 95    2/05/98 9:21p John
160  * Some new Direct3D code.   Added code to monitor a ton of stuff in the
161  * game.
162  * 
163  * 94    2/05/98 12:51a Mike
164  * Early asteroid stuff.
165  * 
166  * 93    2/03/98 6:01p Andsager
167  * Fix excessive rotvel in debris_create.  Check using physics function
168  * check_rotvel_limit.
169  * 
170  * 92    2/03/98 11:14a Andsager
171  * Temp check in to stop debris being created with excess rotvel
172  * 
173  * 91    2/02/98 4:45p Mike
174  * Increase translational and rotational velocity imparted to debris
175  * pieces at request of Adam.
176  * 
177  * 90    1/30/98 2:56p John
178  * Made debris arcs jump around.  Made only 2/3 of the chunks have arcing
179  * 
180  * 89    1/30/98 11:48a John
181  * Made debris arcs cast light.  Added sound effects for them.
182  * 
183  * 88    1/29/98 5:50p John
184  * Made electrical arcing on debris pieces be persistent from frame to
185  * frame
186  * 
187  * 87    1/29/98 8:39a Andsager
188  * Changed mass and moment of intertia based area vs. volume
189  * 
190  * 86    1/27/98 11:02a John
191  * Added first rev of sparks.   Made all code that calls model_render call
192  * clear_instance first.   Made debris pieces not render by default when
193  * clear_instance is called.
194  * 
195  * 85    1/24/98 4:49p Lawrance
196  * Only delete hull piece if you can find an old one that isn't already
197  * about to die.
198  * 
199  * 84    1/23/98 5:06p John
200  * Took L out of vertex structure used B (blue) instead.   Took all small
201  * fireballs out of fireball types and used particles instead.  Fixed some
202  * debris explosion things.  Restructured fireball code.   Restructured
203  * some lighting code.   Made dynamic lighting on by default. Made groups
204  * of lasers only cast one light.  Made fireballs not cast light.
205  * 
206  * $NoKeywords: $
207  */
208
209 #include "3d.h"
210 #include "bmpman.h"
211 #include "object.h"
212 #include "debris.h"
213 #include "fireballs.h"
214 #include "radar.h"
215 #include "missionparse.h"               // For MAX_SPECIES_NAMES
216 #include "gamesnd.h"
217 #include "objectsnd.h"
218 #include "linklist.h"
219 #include "systemvars.h"
220 #include "multi.h"
221 #include "multimsgs.h"
222 #include "particle.h"
223 #include "freespace.h"
224 #include "multiutil.h"
225 #include "objcollide.h"
226 #include "timer.h"
227
228 #define MAX_LIFE                                                                        10.0f
229 #define MIN_RADIUS_FOR_PERSISTANT_DEBRIS        50              // ship radius at which debris from it becomes persistant
230 #define DEBRIS_SOUND_DELAY                                              2000    // time to start debris sound after created
231
232 // limit the number of hull debris chunks that can exist.  
233 #define MAX_HULL_PIECES         10
234 int             Num_hull_pieces;                // number of hull pieces in existance
235 debris  Hull_debris_list;               // head of linked list for hull debris chunks, for quick search
236
237 debris Debris[MAX_DEBRIS_PIECES];
238
239 int Num_debris_pieces = 0;
240 int Debris_inited = 0;
241
242 int Debris_model = -1;
243 int Debris_vaporize_model = -1;
244 int Debris_num_submodels = 0;
245 char * Debris_texture_files[MAX_SPECIES_NAMES] = { 
246         NOX("debris01a"),       // Terran
247         NOX("debris01b"),       // Species B
248         NOX("debris01c"),       // Shivan
249         };
250
251 int Debris_textures[MAX_SPECIES_NAMES];
252
253 #define MAX_DEBRIS_DIST                                 10000.0f                        //      Debris goes away if it's this far away.
254 #define DEBRIS_DISTANCE_CHECK_TIME              (10*1000)               //      Check every 10 seconds.
255 #define DEBRIS_INDEX(dp) (dp-Debris)
256
257 #define MAX_SPEED_SMALL_DEBRIS          200                                     // maximum velocity of small debris piece
258 #define MAX_SPEED_BIG_DEBRIS                    150                                     // maximum velocity of big debris piece
259 #define MAX_SPEED_CAPITAL_DEBRIS        100                                     // maximum velocity of capital debris piece
260 #define DEBRIS_SPEED_DEBUG
261
262 // ---------------------------------------------------------------------------------------
263 // debris_start_death_roll()
264 //
265 //      Start the sequence of a piece of debris writhing in unholy agony!!!
266 //
267 static void debris_start_death_roll(object *debris_obj, debris *debris_p)
268 {
269         if (debris_p->is_hull)  {
270                 // tell everyone else to blow up the piece of debris
271                 if( MULTIPLAYER_MASTER )
272                         send_debris_update_packet(debris_obj,DEBRIS_UPDATE_NUKE);
273
274                 int fireball_type = FIREBALL_EXPLOSION_LARGE1 + rand()%FIREBALL_NUM_LARGE_EXPLOSIONS;
275                 fireball_create( &debris_obj->pos, fireball_type, OBJ_INDEX(debris_obj), debris_obj->radius*1.75f);
276
277                 // only play debris destroy sound if hull piece and it has been around for at least 2 seconds
278                 if ( Missiontime > debris_p->time_started + 2*F1_0 ) {
279                         snd_play_3d( &Snds[SND_MISSILE_IMPACT1], &debris_obj->pos, &View_position, debris_obj->radius );
280                         
281                 }
282         }
283
284         debris_obj->flags |= OF_SHOULD_BE_DEAD;
285 //      demo_do_flag_dead(OBJ_INDEX(debris_obj));
286 }
287
288 // ---------------------------------------------------------------------------------------
289 // debris_init()
290 //
291 // This will get called at the start of each level.
292 //
293 void debris_init()
294 {
295         int i;
296
297         if ( !Debris_inited ) {
298                 Debris_inited = 1;
299         }
300
301         Debris_model = -1;
302         Debris_vaporize_model = -1;
303         Debris_num_submodels = 0;
304                 
305         // Reset everything between levels
306         Num_debris_pieces = 0;
307         for (i=0; i<MAX_DEBRIS_PIECES; i++ )    {
308                 Debris[i].flags = 0;
309                 Debris[i].sound_delay = 0;
310         }
311                 
312         Num_hull_pieces = 0;
313         list_init(&Hull_debris_list);
314 }
315
316 // Page in debris bitmaps at level load
317 void debris_page_in()
318 {
319         int i;
320
321         Debris_model = model_load( NOX("debris01.pof"), 0, NULL );
322         if (Debris_model>-1)    {
323                 polymodel * pm;
324                 pm = model_get(Debris_model);
325                 Debris_num_submodels = pm->n_models;
326         }
327
328         Debris_vaporize_model = model_load( NOX("debris02.pof"), 0, NULL );
329
330         for (i=0; i<MAX_SPECIES_NAMES; i++ )    {
331                 nprintf(( "Paging", "Paging in debris texture '%s'\n", Debris_texture_files[i] ));
332                 Debris_textures[i] = bm_load( Debris_texture_files[i] );
333                 if ( Debris_textures[i] < 0 ) { 
334                         Warning( LOCATION, "Couldn't load species %d debris\ntexture, '%s'\n", i, Debris_texture_files[i] );
335                 }
336                 bm_page_in_texture( Debris_textures[i] );
337         }
338         
339 }
340
341 MONITOR(NumSmallDebrisRend);
342 MONITOR(NumHullDebrisRend);
343
344 // ---------------------------------------------------------------------------------------
345 // debris_render()
346 //
347 //
348 void debris_render(object * obj)
349 {
350         int                     i, num, swapped;
351         polymodel       *pm;
352         debris          *db;
353
354
355         swapped = -1;
356         pm = NULL;      
357         num = obj->instance;
358
359         Assert(num >= 0 && num < MAX_DEBRIS_PIECES );
360         db = &Debris[num];
361
362         Assert( db->flags & DEBRIS_USED );
363
364         // Swap in a different texture depending on the species
365         if ( (db->species > -1) && (db->species < MAX_SPECIES_NAMES) )  {
366
367                 pm = model_get( db->model_num );
368
369                 if ( pm && (pm->n_textures == 1) ) {
370                         swapped = pm->textures[0];
371                         pm->textures[0] = Debris_textures[db->species];
372                 }
373         }
374
375         model_clear_instance( db->model_num );
376
377         // Only render electrical arcs if within 500m of the eye (for a 10m piece)
378         if ( vm_vec_dist_quick( &obj->pos, &Eye_position ) < obj->radius*50.0f )        {
379                 for (i=0; i<MAX_DEBRIS_ARCS; i++ )      {
380                         if ( timestamp_valid( db->arc_timestamp[i] ) )  {
381                                 model_add_arc( db->model_num, db->submodel_num, &db->arc_pts[i][0], &db->arc_pts[i][1], MARC_TYPE_NORMAL );
382                         }
383                 }
384         }
385
386         if ( db->is_hull )      {
387                 MONITOR_INC(NumHullDebrisRend,1);
388                 submodel_render( db->model_num, db->submodel_num, &obj->orient, &obj->pos );
389         } else {
390                 MONITOR_INC(NumSmallDebrisRend,1);
391                 submodel_render( db->model_num, db->submodel_num, &obj->orient, &obj->pos, MR_NO_LIGHTING );
392         }
393
394         if ((swapped!=-1) && pm)        {
395                 pm->textures[0] = swapped;
396         }
397 }
398
399 // Removed the DEBRIS_EXPIRE flag, and remove item from Hull_debris_list
400 void debris_clear_expired_flag(debris *db)
401 {
402         if ( db->flags & DEBRIS_EXPIRE ) {
403                 db->flags &= ~DEBRIS_EXPIRE;
404                 if ( db->is_hull ) {
405                         Num_hull_pieces--;
406                         list_remove(Hull_debris_list, db);
407                         Assert( Num_hull_pieces >= 0 );
408                 }
409         }
410 }
411
412 // ---------------------------------------------------------------------------------------
413 // debris_delete()
414 //
415 // Delete the debris object.  This is only ever called via obj_delete().  Do not call directly.
416 // Use debris_start_death_roll() if you want to force a debris piece to die.
417 //
418 void debris_delete( object * obj )
419 {
420         int             num;
421         debris  *db;
422
423         num = obj->instance;
424         Assert( Debris[num].objnum == OBJ_INDEX(obj));
425
426         db = &Debris[num];
427
428         Assert( Num_debris_pieces >= 0 );
429         if ( db->is_hull && (db->flags & DEBRIS_EXPIRE) ) {
430                 debris_clear_expired_flag(db);
431         }
432
433         db->flags = 0;
434         Num_debris_pieces--;
435 }
436
437 //      If debris piece *db is far away from all players, make it go away very soon.
438 //      In single player game, delete if MAX_DEBRIS_DIST from player.
439 //      In multiplayer game, delete if MAX_DEBRIS_DIST from all players.
440 void maybe_delete_debris(debris *db)
441 {
442         object  *objp;
443
444         if (timestamp_elapsed(db->next_distance_check)) {
445                 if (!(Game_mode & GM_MULTIPLAYER)) {            //      In single player game, just check against player.
446                         if (vm_vec_dist_quick(&Player_obj->pos, &Objects[db->objnum].pos) > MAX_DEBRIS_DIST)
447                                 db->lifeleft = 0.1f;
448                         else
449                                 db->next_distance_check = timestamp(DEBRIS_DISTANCE_CHECK_TIME);
450                 } else {
451                         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
452                                 if (objp->flags & OF_PLAYER_SHIP) {
453                                         if (vm_vec_dist_quick(&objp->pos, &Objects[db->objnum].pos) < MAX_DEBRIS_DIST) {
454                                                 db->next_distance_check = timestamp(DEBRIS_DISTANCE_CHECK_TIME);
455                                                 return;
456                                         }
457                                 }
458                         }
459                         db->lifeleft = 0.1f;
460                 }
461         }
462 }
463
464 // broke debris_move into debris_process_pre and debris_process_post as was done with all
465 // *_move functions on 8/13 by MK and MA.
466 void debris_process_pre( object *objp, float frame_time)
467 {
468 }
469
470 MONITOR(NumSmallDebris);
471 MONITOR(NumHullDebris);
472
473 // ---------------------------------------------------------------------------------------
474 // debris_process_post()
475 //
476 // Do various updates to debris:  check if time to die, start fireballs
477 //
478 // parameters:          obj                     =>              pointer to debris object
479 //                                              frame_time      =>              time elapsed since last debris_move() called
480 //
481 //      Maybe delete debris if it's very far away from player.
482 void debris_process_post(object * obj, float frame_time)
483 {
484         int i, num;
485         num = obj->instance;
486
487         int objnum = OBJ_INDEX(obj);
488         Assert( Debris[num].objnum == objnum );
489         debris *db = &Debris[num];
490
491         if ( db->is_hull ) {
492                 MONITOR_INC(NumHullDebris,1);
493                 radar_plot_object( obj );
494
495                 if ( timestamp_elapsed(db->sound_delay) ) {
496                         obj_snd_assign(objnum, SND_DEBRIS, &vmd_zero_vector, 0);
497                         db->sound_delay = 0;
498                 }
499         } else {
500                 MONITOR_INC(NumSmallDebris,1);
501         }
502
503         if ( db->lifeleft >= 0.0f) {
504                 db->lifeleft -= frame_time;
505                 if ( db->lifeleft < 0.0f )      {
506                         debris_start_death_roll(obj, db);
507                 }
508         }
509
510         maybe_delete_debris(db);        //      Make this debris go away if it's very far away.
511
512         // ================== DO THE ELECTRIC ARCING STUFF =====================
513         if ( db->arc_frequency <= 0 )   {
514                 return;                 // If arc_frequency <= 0, this piece has no arcs on it
515         }
516
517         if ( !timestamp_elapsed(db->fire_timeout) && timestamp_elapsed(db->next_fireball))      {
518
519                 // start the next fireball up in the next 50 - 100 ms
520                 //db->next_fireball = timestamp_rand(60,80);            
521
522                 db->next_fireball = timestamp_rand(db->arc_frequency,db->arc_frequency*2 );
523                 db->arc_frequency += 100;       
524
525                 if (db->is_hull)        {
526
527                         int n, n_arcs = ((rand()>>5) % 3)+1;            // Create 1-3 sparks
528
529                         vector v1, v2, v3, v4;
530                         submodel_get_two_random_points( db->model_num, db->submodel_num, &v1, &v2 );
531                         submodel_get_two_random_points( db->model_num, db->submodel_num, &v3, &v4 );
532
533                         n = 0;
534
535                         int a = 100, b = 1000;
536                         int lifetime = (myrand()%((b)-(a)+1))+(a);
537
538                         // Create the spark effects
539                         for (i=0; i<MAX_DEBRIS_ARCS; i++ )      {
540                                 if ( !timestamp_valid( db->arc_timestamp[i] ) ) {
541                                         //db->arc_timestamp[i] = timestamp_rand(400,1000);      // live up to a second
542                                         db->arc_timestamp[i] = timestamp(lifetime);     // live up to a second
543
544                                         switch( n )     {
545                                         case 0:
546                                                 db->arc_pts[i][0] = v1;
547                                                 db->arc_pts[i][1] = v2;
548                                                 break;
549                                         case 1:
550                                                 db->arc_pts[i][0] = v2;
551                                                 db->arc_pts[i][1] = v3;
552                                                 break;
553
554                                         case 2:
555                                                 db->arc_pts[i][0] = v2;
556                                                 db->arc_pts[i][1] = v4;
557                                                 break;
558
559                                         default:
560                                                 Int3();
561                                         }
562                                                 
563                                         n++;
564                                         if ( n == n_arcs )
565                                                 break;  // Don't need to create anymore
566                                 }
567                         }
568
569         
570                         // rotate v2 out of local coordinates into world.
571                         // Use v2 since it is used in every bolt.  See above switch().
572                         vector snd_pos;
573                         vm_vec_unrotate(&snd_pos, &v2, &obj->orient);
574                         vm_vec_add2(&snd_pos, &obj->pos );
575
576                         //Play a sound effect
577                         if ( lifetime > 750 )   {
578                                 // 1.00 second effect
579                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_05], &snd_pos, &View_position, obj->radius );
580                         } else if ( lifetime >  500 )   {
581                                 // 0.75 second effect
582                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_04], &snd_pos, &View_position, obj->radius );
583                         } else if ( lifetime >  250 )   {
584                                 // 0.50 second effect
585                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_03], &snd_pos, &View_position, obj->radius );
586                         } else if ( lifetime >  100 )   {
587                                 // 0.25 second effect
588                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_02], &snd_pos, &View_position, obj->radius );
589                         } else {
590                                 // 0.10 second effect
591                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_01], &snd_pos, &View_position, obj->radius );
592                         }
593
594                 }
595
596
597
598         }
599
600         for (i=0; i<MAX_DEBRIS_ARCS; i++ )      {
601                 if ( timestamp_valid( db->arc_timestamp[i] ) )  {
602                         if ( timestamp_elapsed( db->arc_timestamp[i] ) )        {
603                                 // Kill off the spark
604                                 db->arc_timestamp[i] = timestamp(-1);
605                         } else {
606                                 // Maybe move a vertex....  20% of the time maybe?
607                                 int mr = myrand();
608                                 if ( mr < RAND_MAX/5 )  {
609                                         vector v1, v2;
610                                         submodel_get_two_random_points( db->model_num, db->submodel_num, &v1, &v2 );
611                                         db->arc_pts[i][mr % 2] = v1;
612                                 }
613                         }
614                 }
615         }
616
617 }
618
619 // ---------------------------------------------------------------------------------------
620 // debris_find_oldest()
621 //
622 // Locate the oldest hull debris chunk.  Search through the Hull_debris_list, which is a list
623 // of all the hull debris chunks.
624 //
625 int debris_find_oldest()
626 {
627         int             oldest_index;
628         fix             oldest_time;
629         debris  *db;
630
631         oldest_index = -1;
632         oldest_time = 0x7fffffff;
633
634         for ( db = GET_FIRST(&Hull_debris_list); db != END_OF_LIST(&Hull_debris_list); db = GET_NEXT(db) ) {
635                 if ( (db->time_started < oldest_time) && !(Objects[db->objnum].flags & OF_SHOULD_BE_DEAD) ) {
636                         oldest_index = DEBRIS_INDEX(db);
637                         oldest_time = db->time_started;
638                 }
639         }
640
641         return oldest_index;
642 }
643
644 #define DEBRIS_ROTVEL_SCALE     5.0f
645 void calc_debris_physics_properties( physics_info *pi, vector *min, vector *max );
646 // ---------------------------------------------------------------------------------------
647 // debris_create()
648 //
649 // Create debris from an object
650 //
651 //      exp_force:      Explosion force, used to assign velocity to pieces.
652 //                                      1.0f assigns velocity like before.  2.0f assigns twice as much to non-inherited part of velocity
653 object *debris_create(object *source_obj, int model_num, int submodel_num, vector *pos, vector *exp_center, int hull_flag, float exp_force)
654 {
655         int             i, n, objnum, parent_objnum;
656         object  *obj;
657         ship            *shipp;
658         debris  *db;    
659         polymodel *pm;
660         int vaporize;
661
662         parent_objnum = OBJ_INDEX(source_obj);
663
664         Assert( (source_obj->type == OBJ_SHIP ) || (source_obj->type == OBJ_GHOST));
665         Assert( source_obj->instance >= 0 && source_obj->instance < MAX_SHIPS );        
666         shipp = &Ships[source_obj->instance];
667         vaporize = (shipp->flags &SF_VAPORIZE);
668
669         if ( !hull_flag )       {
670                 // Make vaporize debris seen from farther away
671                 float dist = vm_vec_dist_quick( pos, &Eye_position );
672                 if (vaporize) {
673                         dist /= 2.0f;
674                 }
675                 if ( dist > 200.0f ) {
676                         //mprintf(( "Not creating debris that is %.1f m away\n", dist ));
677                         return NULL;
678                 }
679         }
680
681         if ( hull_flag && (Num_hull_pieces >= MAX_HULL_PIECES ) ) {
682                 // cause oldest hull debris chunk to blow up
683                 n = debris_find_oldest();
684                 if ( n >= 0 ) {
685                         debris_start_death_roll(&Objects[Debris[n].objnum], &Debris[n] );
686                 }
687         }
688
689         for (n=0; n<MAX_DEBRIS_PIECES; n++ ) {
690                 if ( !(Debris[n].flags & DEBRIS_USED) )
691                         break;
692         }
693
694         if ( n == MAX_DEBRIS_PIECES ) {
695                 nprintf(("Warning","Frame %i: Could not create debris, no more slots left\n", Framecount));
696                 return NULL;
697         }
698
699         db = &Debris[n];
700
701         // Create Debris piece n!
702         if ( hull_flag ) {
703                 if (rand() < RAND_MAX/6)        // Make some pieces blow up shortly after explosion.
704                         db->lifeleft = 2.0f * ((float) myrand()/(float) RAND_MAX) + 0.5f;
705                 else
706                         db->lifeleft = -1.0f;           // large hull pieces stay around forever
707         }       else {
708                 db->lifeleft = (i2fl(myrand())/i2fl(RAND_MAX))*2.0f+0.1f;
709         }
710
711         // increase lifetime for vaporized debris
712         if (vaporize) {
713                 db->lifeleft *= 3.0f;
714         }
715         db->flags |= DEBRIS_USED;
716         db->is_hull = hull_flag;
717         db->source_objnum = parent_objnum;
718         db->source_sig = source_obj->signature;
719         db->ship_info_index = shipp->ship_info_index;
720         db->team = shipp->team;
721         db->fire_timeout = 0;   // if not changed, timestamp_elapsed() will return false
722         db->time_started = Missiontime;
723         db->species = Ship_info[shipp->ship_info_index].species;
724         db->next_distance_check = (myrand() % 2000) + 4*DEBRIS_DISTANCE_CHECK_TIME;
725
726         for (i=0; i<MAX_DEBRIS_ARCS; i++ )      {
727                 db->arc_timestamp[i] = timestamp(-1);
728                 //      vector  arc_pts[MAX_DEBRIS_ARCS][2];            // The endpoints of each arc
729         }
730
731         if ( db->is_hull )      {
732                 // Only make 1/2 of the pieces have arcs
733                 if ( myrand() < RAND_MAX*2/3 )  {
734                         db->arc_frequency = 1000;
735                 } else {
736                         db->arc_frequency = 0;
737                 }
738         } else {
739                 db->arc_frequency = 0;
740         }
741
742         if ( model_num < 0 )    {
743                 if (vaporize) {
744                         db->model_num = Debris_vaporize_model;
745                 } else {
746                         db->model_num = Debris_model;
747                 }
748                 db->submodel_num = (myrand()>>4) % Debris_num_submodels;
749         } else {
750                 db->model_num = model_num;
751                 db->submodel_num = submodel_num;
752         }
753         float radius = submodel_get_radius( db->model_num, db->submodel_num );
754
755         db->next_fireball = timestamp_rand(500,2000);   //start one 1/2 - 2 secs later
756
757         if ( pos == NULL )
758                 pos = &source_obj->pos;
759
760         uint flags = OF_RENDERS | OF_PHYSICS;
761         if ( hull_flag )        
762                 flags |= OF_COLLIDES;
763         objnum = obj_create( OBJ_DEBRIS, parent_objnum, n, &source_obj->orient, pos, radius, flags );
764         if ( objnum == -1 ) {
765                 mprintf(("Couldn't create debris object -- out of object slots\n"));
766                 return NULL;
767         }
768
769         db->objnum = objnum;
770         
771         obj = &Objects[objnum];
772
773         // assign the network signature.  The signature will be 0 for non-hull pieces, but since that
774         // is our invalid signature, it should be okay.
775         obj->net_signature = 0;
776         if ( (Game_mode & GM_MULTIPLAYER) && hull_flag ) {
777                 obj->net_signature = multi_get_next_network_signature( MULTI_SIG_DEBRIS );
778         }
779
780         // -- No long need shield: bset_shield_strength(obj, 100.0f);           //      Hey!  Set to some meaningful value!
781
782         if (source_obj->type == OBJ_SHIP) {
783                 obj->hull_strength = Ship_info[Ships[source_obj->instance].ship_info_index].initial_hull_strength/8.0f;
784         } else
785                 obj->hull_strength = 10.0f;
786
787         Num_debris_pieces++;
788
789         vector rotvel, radial_vel, to_center;
790
791         if ( exp_center )
792                 vm_vec_sub( &to_center,pos, exp_center );
793         else
794                 vm_vec_zero(&to_center);
795
796         float scale;
797
798         if ( hull_flag )        {
799                 float t;
800                 scale = exp_force * i2fl((myrand()%20) + 10);   // for radial_vel away from location of blast center
801                 db->sound_delay = timestamp(DEBRIS_SOUND_DELAY);
802
803                 // set up physics mass and I_inv for hull debris pieces
804                 pm = model_get(model_num);
805                 vector *min, *max;
806                 min = &pm->submodel[submodel_num].min;
807                 max = &pm->submodel[submodel_num].max;
808                 calc_debris_physics_properties( &obj->phys_info, min, max );
809
810                 // limit the amount of time that fireballs appear
811                 // let fireball length be linked to radius of ship.  Range is .33 radius => 3.33 radius seconds.
812                 t = 1000*Objects[db->source_objnum].radius/3 + myrand()%(fl2i(1000*3*Objects[db->source_objnum].radius));
813                 db->fire_timeout = timestamp(fl2i(t));          // fireballs last from 5 - 30 seconds
814                 
815                 if ( Objects[db->source_objnum].radius < MIN_RADIUS_FOR_PERSISTANT_DEBRIS ) {
816                         db->flags |= DEBRIS_EXPIRE;     // debris can expire
817                         Num_hull_pieces++;
818                         list_append(&Hull_debris_list, db);
819                 } else {
820                         nprintf(("Alan","A forever chunk of debris was created from ship with radius %f\n",Objects[db->source_objnum].radius));
821                 }
822         }
823         else {
824                 scale = exp_force * i2fl((myrand()%20) + 10);   // for radial_vel away from blast center (non-hull)
825         }
826
827         if ( vm_vec_mag_squared( &to_center ) < 0.1f )  {
828                 vm_vec_rand_vec_quick(&radial_vel);
829                 vm_vec_scale(&radial_vel, scale );
830         }
831         else {
832                 vm_vec_normalize(&to_center);
833                 vm_vec_copy_scale(&radial_vel, &to_center, scale );
834         }
835
836         //      MK: This next line causes debris pieces to get between 50% and 100% of the parent ship's
837         //      velocity.  What would be very cool is if the rotational velocity of the parent would become 
838         // translational velocity of the debris piece.  This would be based on the location of the debris
839         //      piece in the parent object.
840
841         // DA: here we need to vel_from_rot = w x to_center, where w is world is unrotated to world coords and offset is the 
842         // displacement fromt the center of the parent object to the center of the debris piece
843
844         vector world_rotvel, vel_from_rotvel;
845         vm_vec_unrotate ( &world_rotvel, &source_obj->phys_info.rotvel, &source_obj->orient );
846         vm_vec_crossprod ( &vel_from_rotvel, &world_rotvel, &to_center );
847         vm_vec_scale ( &vel_from_rotvel, DEBRIS_ROTVEL_SCALE);
848
849         vm_vec_add (&obj->phys_info.vel, &radial_vel, &source_obj->phys_info.vel);
850         vm_vec_add2(&obj->phys_info.vel, &vel_from_rotvel);
851
852 #ifdef DEBRIS_SPEED_DEBUG
853         // check that debris is not created with too high a velocity
854         if (hull_flag) {
855                 int ship_info_flag = Ship_info[Ships[source_obj->instance].ship_info_index].flags;
856                 if (ship_info_flag & (SIF_SMALL_SHIP | SIF_NOT_FLYABLE | SIF_HARMLESS)) {
857                         if (vm_vec_mag_squared(&obj->phys_info.vel) > MAX_SPEED_SMALL_DEBRIS*MAX_SPEED_SMALL_DEBRIS) {
858                                 float scale = MAX_SPEED_SMALL_DEBRIS / vm_vec_mag(&obj->phys_info.vel);
859                                 vm_vec_scale(&obj->phys_info.vel, scale);
860                         }
861                 } else if (ship_info_flag & SIF_BIG_SHIP) {
862                         if (vm_vec_mag_squared(&obj->phys_info.vel) > MAX_SPEED_BIG_DEBRIS*MAX_SPEED_BIG_DEBRIS) {
863                                 float scale = MAX_SPEED_BIG_DEBRIS / vm_vec_mag(&obj->phys_info.vel);
864                                 vm_vec_scale(&obj->phys_info.vel, scale);
865                         }
866                 } else if (ship_info_flag & SIF_HUGE_SHIP) {
867                         if (vm_vec_mag_squared(&obj->phys_info.vel) > MAX_SPEED_CAPITAL_DEBRIS*MAX_SPEED_CAPITAL_DEBRIS) {
868                                 float scale = MAX_SPEED_CAPITAL_DEBRIS / vm_vec_mag(&obj->phys_info.vel);
869                                 vm_vec_scale(&obj->phys_info.vel, scale);
870                         }
871                 } else {
872                         Warning(LOCATION, "Ship has info flag that is not among the following:  SMALL, NOT_FLYABLE, HARMLESS, BIG, CAPITAL, SUPERCAP");
873                 }
874         }
875 #endif
876
877 //      vm_vec_scale_add(&obj->phys_info.vel, &radial_vel, &source_obj->phys_info.vel, frand()/2.0f + 0.5f);
878 //      nprintf(("Andsager","object vel from rotvel: %0.2f, %0.2f, %0.2f\n",vel_from_rotvel.x, vel_from_rotvel.y, vel_from_rotvel.z));
879
880 // make sure rotational velocity does not get too high
881         if (radius < 1.0) {
882                 radius = 1.0f;
883         }
884
885         scale = ( 6.0f + i2fl(myrand()%4) ) / radius;
886
887         vm_vec_rand_vec_quick(&rotvel);
888         vm_vec_scale(&rotvel, scale);
889
890         obj->phys_info.flags |= PF_DEAD_DAMP;
891         obj->phys_info.rotvel = rotvel;
892         check_rotvel_limit( &obj->phys_info );
893
894
895         // blow out his reverse thrusters. Or drag, same thing.
896         obj->phys_info.rotdamp = 10000.0f;
897         obj->phys_info.side_slip_time_const = 10000.0f;
898         obj->phys_info.flags |= (PF_REDUCED_DAMP | PF_DEAD_DAMP);       // set damping equal for all axis and not changable
899
900         vm_vec_zero(&obj->phys_info.max_vel);           // make so he can't turn on his own VOLITION anymore.
901         vm_vec_zero(&obj->phys_info.max_rotvel);        // make so he can't change speed on his own VOLITION anymore.
902
903
904         // ensure vel is valid
905         Assert( !vm_is_vec_nan(&obj->phys_info.vel) );
906
907 //      if ( hull_flag )        {
908 //              vm_vec_zero(&obj->phys_info.vel);
909 //              vm_vec_zero(&obj->phys_info.rotvel);
910 //      }
911
912         return obj;
913 }
914
915 // ---------------------------------------------------------------------------------------
916 // debris_hit()
917 //
918 //      Alas, poor debris_obj got whacked.  Fortunately, we know who did it, where and how hard, so we
919 //      can do something about it.
920 //
921 void debris_hit(object *debris_obj, object *other_obj, vector *hitpos, float damage)
922 {
923         debris  *debris_p = &Debris[debris_obj->instance];
924
925
926         // Do a little particle spark shower to show we hit
927         {
928                 particle_emitter        pe;
929
930                 pe.pos = *hitpos;                                                               // Where the particles emit from
931                 pe.vel = debris_obj->phys_info.vel;             // Initial velocity of all the particles
932
933                 vector tmp_norm;
934                 vm_vec_sub( &tmp_norm, hitpos, &debris_obj->pos );
935                 vm_vec_normalize_safe(&tmp_norm);
936                         
937                 pe.normal = tmp_norm;                   // What normal the particle emit around
938                 pe.normal_variance = 0.3f;              //      How close they stick to that normal 0=good, 1=360 degree
939                 pe.min_rad = 0.20f;                             // Min radius
940                 pe.max_rad = 0.40f;                             // Max radius
941
942                 // Sparks for first time at this spot
943                 pe.num_low = 10;                                // Lowest number of particles to create
944                 pe.num_high = 10;                       // Highest number of particles to create
945                 pe.normal_variance = 0.3f;              //      How close they stick to that normal 0=good, 1=360 degree
946                 pe.min_vel = 0.0f;                              // How fast the slowest particle can move
947                 pe.max_vel = 10.0f;                             // How fast the fastest particle can move
948                 pe.min_life = 0.25f;                    // How long the particles live
949                 pe.max_life = 0.75f;                    // How long the particles live
950                 particle_emit( &pe, PARTICLE_FIRE, 0 );
951         }
952
953         // multiplayer clients bail here
954         if(MULTIPLAYER_CLIENT){
955                 return;
956         }
957
958         if ( damage < 0.0f ) {
959                 damage = 0.0f;
960         }
961
962         debris_obj->hull_strength -= damage;
963
964         if (debris_obj->hull_strength < 0.0f) {
965                 debris_start_death_roll(debris_obj, debris_p );
966         } else {
967                 // otherwise, give all the other players an update on the debris
968                 if(MULTIPLAYER_MASTER){
969                         send_debris_update_packet(debris_obj,DEBRIS_UPDATE_UPDATE);
970                 }
971         }
972 }
973
974 // ---------------------------------------------------------------------------------------
975 // debris_check_collision()
976 //
977 //      See if poor debris object *obj got whacked by evil *other_obj at point *hitpos.
978 // NOTE: debris_hit_info pointer NULL for debris:weapon collision, otherwise debris:ship collision.
979 //      Return true if hit, else return false.
980 //
981 #ifndef PLAT_UNIX
982 #pragma warning ( push )
983 #pragma warning ( disable : 4701 )
984 #endif
985 int debris_check_collision(object *pdebris, object *other_obj, vector *hitpos, collision_info_struct *debris_hit_info)
986 {
987         mc_info mc;
988         int             num;
989
990         Assert( pdebris->type == OBJ_DEBRIS );
991
992         num = pdebris->instance;
993         Assert( num >= 0 );
994
995         Assert( Debris[num].objnum == OBJ_INDEX(pdebris));      
996
997         // debris_hit_info NULL - so debris-weapon collision
998         if ( debris_hit_info == NULL ) {
999                 // debris weapon collision
1000                 Assert( other_obj->type == OBJ_WEAPON );
1001                 mc.model_num = Debris[num].model_num;   // Fill in the model to check
1002                 mc.submodel_num = Debris[num].submodel_num;
1003                 model_clear_instance( mc.model_num );
1004                 mc.orient = &pdebris->orient;                                   // The object's orient
1005                 mc.pos = &pdebris->pos;                                                 // The object's position
1006                 mc.p0 = &other_obj->last_pos;                           // Point 1 of ray to check
1007                 mc.p1 = &other_obj->pos;                                        // Point 2 of ray to check
1008                 mc.flags = (MC_CHECK_MODEL | MC_SUBMODEL);
1009
1010                 if (model_collide(&mc)) {
1011                         *hitpos = mc.hit_point_world;
1012                 }
1013
1014                 return mc.num_hits;
1015         }
1016         
1017         // debris ship collision -- use debris_hit_info to calculate physics
1018         object *ship_obj = other_obj;
1019         Assert( ship_obj->type == OBJ_SHIP );
1020
1021         object *heavy = debris_hit_info->heavy;
1022         object *light = debris_hit_info->light;
1023         object *heavy_obj = heavy;
1024         object *light_obj = light;
1025
1026         vector zero, p0, p1;
1027         vm_vec_zero(&zero);
1028         vm_vec_sub(&p0, &light->last_pos, &heavy->last_pos);
1029         vm_vec_sub(&p1, &light->pos, &heavy->pos);
1030
1031         mc.pos = &zero;                                                         // The object's position
1032         mc.p0 = &p0;                                                                    // Point 1 of ray to check
1033         mc.p1 = &p1;                                                                    // Point 2 of ray to check
1034
1035         // find the light object's position in the heavy object's reference frame at last frame and also in this frame.
1036         vector p0_temp, p0_rotated;
1037                 
1038         // Collision detection from rotation enabled if at rotaion is less than 30 degree in frame
1039         // This should account for all ships
1040         if ( (vm_vec_mag_squared(&heavy->phys_info.rotvel) * flFrametime*flFrametime) < (PI*PI/36) ) {
1041                 // collide_rotate calculate (1) start position and (2) relative velocity
1042                 debris_hit_info->collide_rotate = 1;
1043                 vm_vec_rotate(&p0_temp, &p0, &heavy->last_orient);
1044                 vm_vec_unrotate(&p0_rotated, &p0_temp, &heavy->orient);
1045                 mc.p0 = &p0_rotated;                            // Point 1 of ray to check
1046                 vm_vec_sub(&debris_hit_info->light_rel_vel, &p1, &p0_rotated);
1047                 vm_vec_scale(&debris_hit_info->light_rel_vel, 1/flFrametime);
1048         } else {
1049                 debris_hit_info->collide_rotate = 0;
1050                 vm_vec_sub(&debris_hit_info->light_rel_vel, &light->phys_info.vel, &heavy->phys_info.vel);
1051         }
1052
1053         int mc_ret_val = 0;
1054
1055         if ( debris_hit_info->heavy == ship_obj ) {     // ship is heavier, so debris is sphere. Check sphere collision against ship poly model
1056                 mc.model_num = Ships[ship_obj->instance].modelnum;              // Fill in the model to check
1057                 mc.orient = &ship_obj->orient;                                                          // The object's orient
1058                 mc.radius = pdebris->radius;
1059                 mc.flags = (MC_CHECK_MODEL | MC_CHECK_SPHERELINE);
1060
1061                 // copy important data
1062                 int copy_flags = mc.flags;  // make a copy of start end positions of sphere in  big ship RF
1063                 vector copy_p0, copy_p1;
1064                 copy_p0 = *mc.p0;
1065                 copy_p1 = *mc.p1;
1066
1067                 // first test against the sphere - if this fails then don't do any submodel tests
1068                 mc.flags = MC_ONLY_SPHERE | MC_CHECK_SPHERELINE;
1069
1070                 int submodel_list[MAX_ROTATING_SUBMODELS];
1071                 int num_rotating_submodels = 0;
1072                 polymodel *pm;
1073
1074                 ship_model_start(ship_obj);
1075
1076                 if (model_collide(&mc)) {
1077
1078                         // Set earliest hit time
1079                         debris_hit_info->hit_time = FLT_MAX;
1080
1081                         // Do collision the cool new way
1082                         if ( debris_hit_info->collide_rotate ) {
1083                                 // We collide with the sphere, find the list of rotating submodels and test one at a time
1084                                 model_get_rotating_submodel_list(submodel_list, &num_rotating_submodels, heavy_obj);
1085
1086                                 // Get polymodel and turn off all rotating submodels, collide against only 1 at a time.
1087                                 pm = model_get(Ships[heavy_obj->instance].modelnum);
1088
1089                                 // turn off all rotating submodels and test for collision
1090                                 for (int i=0; i<num_rotating_submodels; i++) {
1091                                         pm->submodel[submodel_list[i]].blown_off = 1;
1092                                 }
1093
1094                                 // reset flags to check MC_CHECK_MODEL | MC_CHECK_SPHERELINE and maybe MC_CHECK_INVISIBLE_FACES and MC_SUBMODEL_INSTANCE
1095                                 mc.flags = copy_flags | MC_SUBMODEL_INSTANCE;
1096
1097                                 // check each submodel in turn
1098                                 for (int i=0; i<num_rotating_submodels; i++) {
1099                                         // turn on submodel for collision test
1100                                         pm->submodel[submodel_list[i]].blown_off = 0;
1101
1102                                         // set angles for last frame (need to set to prev to get p0)
1103                                         angles copy_angles = pm->submodel[submodel_list[i]].angs;
1104
1105                                         // find the start and end positions of the sphere in submodel RF
1106                                         pm->submodel[submodel_list[i]].angs = pm->submodel[submodel_list[i]].sii->prev_angs;
1107                                         world_find_model_point(&p0, &light_obj->last_pos, pm, submodel_list[i], &heavy_obj->last_orient, &heavy_obj->last_pos);
1108
1109                                         pm->submodel[submodel_list[i]].angs = copy_angles;
1110                                         world_find_model_point(&p1, &light_obj->pos, pm, submodel_list[i], &heavy_obj->orient, &heavy_obj->pos);
1111
1112                                         mc.p0 = &p0;
1113                                         mc.p1 = &p1;
1114                                         // mc.pos = zero        // in submodel RF
1115
1116                                         mc.orient = &vmd_identity_matrix;
1117                                         mc.submodel_num = submodel_list[i];
1118
1119                                         if ( model_collide(&mc) ) {
1120                                                 if ( mc.hit_dist < debris_hit_info->hit_time ) {
1121                                                         mc_ret_val = 1;
1122
1123                                                         // set up debris_hit_info common
1124                                                         set_hit_struct_info(debris_hit_info, &mc, SUBMODEL_ROT_HIT);
1125                                                         model_find_world_point(&debris_hit_info->hit_pos, &mc.hit_point, mc.model_num, mc.hit_submodel, &heavy_obj->orient, &zero);
1126
1127                                                         // set up debris_hit_info for rotating submodel
1128                                                         if (debris_hit_info->edge_hit == 0) {
1129                                                                 model_find_obj_dir(&debris_hit_info->collision_normal, &mc.hit_normal, heavy_obj, mc.hit_submodel);
1130                                                         }
1131
1132                                                         // find position in submodel RF of light object at collison
1133                                                         vector int_light_pos, diff;
1134                                                         vm_vec_sub(&diff, mc.p1, mc.p0);
1135                                                         vm_vec_scale_add(&int_light_pos, mc.p0, &diff, mc.hit_dist);
1136                                                         model_find_world_point(&debris_hit_info->light_collision_cm_pos, &int_light_pos, mc.model_num, mc.hit_submodel, &heavy_obj->orient, &zero);
1137                                                 }
1138                                         }
1139                                         // Don't look at this submodel again
1140                                         pm->submodel[submodel_list[i]].blown_off = 1;
1141                                 }
1142
1143                         }
1144
1145                         // Recover and do usual ship_ship collision, but without rotating submodels
1146                         mc.flags = copy_flags;
1147                         *mc.p0 = copy_p0;
1148                         *mc.p1 = copy_p1;
1149                         mc.orient = &heavy_obj->orient;
1150
1151                         // usual ship_ship collision test
1152                         if ( model_collide(&mc) )       {
1153                                 // check if this is the earliest hit
1154                                 if (mc.hit_dist < debris_hit_info->hit_time) {
1155                                         mc_ret_val = 1;
1156
1157                                         set_hit_struct_info(debris_hit_info, &mc, SUBMODEL_NO_ROT_HIT);
1158
1159                                         // get collision normal if not edge hit
1160                                         if (debris_hit_info->edge_hit == 0) {
1161                                                 model_find_obj_dir(&debris_hit_info->collision_normal, &mc.hit_normal, heavy_obj, mc.hit_submodel);
1162                                         }
1163
1164                                         // find position in submodel RF of light object at collison
1165                                         vector diff;
1166                                         vm_vec_sub(&diff, mc.p1, mc.p0);
1167                                         vm_vec_scale_add(&debris_hit_info->light_collision_cm_pos, mc.p0, &diff, mc.hit_dist);
1168
1169                                 }
1170                         }
1171
1172                         ship_model_stop( ship_obj );
1173                 }
1174
1175         } else {
1176                 // Debris is heavier obj
1177                 mc.model_num = Debris[num].model_num;           // Fill in the model to check
1178                 mc.submodel_num = Debris[num].submodel_num;
1179                 model_clear_instance( mc.model_num );
1180                 mc.orient = &pdebris->orient;                           // The object's orient
1181                 mc.radius = model_get_core_radius( Ships[ship_obj->instance].modelnum );
1182
1183                 // check for collision between debris model and ship sphere
1184                 mc.flags = (MC_CHECK_MODEL | MC_SUBMODEL | MC_CHECK_SPHERELINE);
1185
1186                 mc_ret_val = model_collide(&mc);
1187
1188                 if (mc_ret_val) {
1189                         set_hit_struct_info(debris_hit_info, &mc, SUBMODEL_NO_ROT_HIT);
1190
1191                         // set normal if not edge hit
1192                         if ( !debris_hit_info->edge_hit ) {
1193                                 vm_vec_unrotate(&debris_hit_info->collision_normal, &mc.hit_normal, &heavy->orient);
1194                         }
1195
1196                         // find position in submodel RF of light object at collison
1197                         vector diff;
1198                         vm_vec_sub(&diff, mc.p1, mc.p0);
1199                         vm_vec_scale_add(&debris_hit_info->light_collision_cm_pos, mc.p0, &diff, mc.hit_dist);
1200
1201                 }
1202         }
1203
1204
1205         if ( mc_ret_val )       {
1206
1207                 // SET PHYSICS PARAMETERS
1208                 // already have (hitpos - heavy) and light_cm_pos
1209                 // get heavy cm pos - already have light_cm_pos
1210                 debris_hit_info->heavy_collision_cm_pos = zero;
1211
1212                 // get r_heavy and r_light
1213                 debris_hit_info->r_heavy = debris_hit_info->hit_pos;
1214                 vm_vec_sub(&debris_hit_info->r_light, &debris_hit_info->hit_pos, &debris_hit_info->light_collision_cm_pos);
1215
1216                 // set normal for edge hit
1217                 if ( debris_hit_info->edge_hit ) {
1218                         vm_vec_copy_normalize(&debris_hit_info->collision_normal, &debris_hit_info->r_light);
1219                         vm_vec_negate(&debris_hit_info->collision_normal);
1220                 }
1221
1222                 // get world hitpos
1223                 vm_vec_add(hitpos, &debris_hit_info->heavy->pos, &debris_hit_info->r_heavy);
1224
1225                 return 1;
1226         } else {
1227                 // no hit
1228                 return 0;
1229         }
1230 }
1231 #ifndef PLAT_UNIX
1232 #pragma warning ( pop )
1233 #endif
1234
1235 // ---------------------------------------------------------------------------------------
1236 // debris_get_team()
1237 //
1238 //      Return the team field for a debris object
1239 //
1240 int debris_get_team(object *objp)
1241 {
1242         Assert( objp->type == OBJ_DEBRIS );
1243         Assert( objp->instance >= 0 && objp->instance < MAX_DEBRIS_PIECES );
1244         return Debris[objp->instance].team;
1245 }
1246
1247 // fills in debris physics properties when created, specifically mass and moment of inertia
1248 void calc_debris_physics_properties( physics_info *pi, vector *mins, vector *maxs )
1249 {
1250         float dx, dy, dz, mass;
1251         dx = maxs->x - mins->x;
1252         dy = maxs->y - mins->y;
1253         dz = maxs->z - mins->z;
1254
1255         // John, with new bspgen, just set pi->mass = mass
1256         mass = 0.12f * dx * dy * dz;
1257         pi->mass = (float) pow(mass, 0.6666667f) * 4.65f;
1258
1259         pi->I_body_inv.rvec.x = 12.0f / (pi->mass *  (dy*dy + dz*dz));
1260         pi->I_body_inv.rvec.y = 0.0f;
1261         pi->I_body_inv.rvec.z = 0.0f;
1262
1263         pi->I_body_inv.uvec.x = 0.0f;
1264         pi->I_body_inv.uvec.y = 12.0f / (pi->mass *  (dx*dx + dz*dz));
1265         pi->I_body_inv.uvec.z = 0.0f;
1266
1267         pi->I_body_inv.fvec.x = 0.0f;
1268         pi->I_body_inv.fvec.y = 0.0f;
1269         pi->I_body_inv.fvec.z = 12.0f / (pi->mass *  (dx*dx + dy*dy));
1270 }
1271
1272