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