]> icculus.org git repositories - taylor/freespace2.git/blob - src/asteroid/asteroid.cpp
The Great Newline Fix
[taylor/freespace2.git] / src / asteroid / asteroid.cpp
1 /*
2  * $Logfile: /Freespace2/code/Asteroid/Asteroid.cpp $
3  * $Revision$
4  * $Date$
5  * $Author$
6  *
7  * C module for asteroid code
8  *
9  * $Log$
10  * Revision 1.2  2002/05/07 03:16:43  theoddone33
11  * The Great Newline Fix
12  *
13  * Revision 1.1.1.1  2002/05/03 03:28:11  root
14  * Initial import.
15  *
16  * 
17  * 31    9/08/99 10:52a Mikek
18  * Reduce the number of asteroids that can be thrown at a target at
19  * Medium+.
20  * 
21  * 30    9/06/99 12:46a Andsager
22  * Add weapon_explosion_ani LOD
23  * 
24  * 29    9/05/99 3:13p Mikek
25  * Slightly decrease number of asteroids thrown at escorted ships.
26  * 
27  * 28    8/26/99 8:51p Dave
28  * Gave multiplayer TvT messaging a heavy dose of sanity. Cheat codes.
29  * 
30  * 27    7/30/99 7:01p Dave
31  * Dogfight escort gauge. Fixed up laser rendering in Glide.
32  * 
33  * 26    7/19/99 8:58p Andsager
34  * Don't try to throw at objnum -1
35  * 
36  * 25    7/15/99 9:20a Andsager
37  * FS2_DEMO initial checkin
38  * 
39  * 24    7/09/99 5:54p Dave
40  * Seperated cruiser types into individual types. Added tons of new
41  * briefing icons. Campaign screen.
42  * 
43  * 23    6/10/99 11:06a Andsager
44  * Mission designed selection of asteroid types.
45  * 
46  * 22    6/09/99 2:55p Andsager
47  * Allow multiple asteroid subtypes (of large, medium, small) and follow
48  * family.
49  * 
50  * 21    6/08/99 7:19p Dave
51  * Fixed asteroid lighting. Was because on non-darkening textures in Glide
52  * only. Dumb.
53  * 
54  * 20    6/07/99 1:18p Andsager
55  * Make asteroids choose consistent texture from large to small.  Modify
56  * fireball radius of dying asteroids.
57  * 
58  * 19    5/03/99 10:50p Andsager
59  * Make Asteroid_obj_list.  Change get_nearest_turret_objnum() to use
60  * Asteroid_obj_list, Ship_obj_list and Missile_obj_list vs.
61  * obj_used_list.
62  * 
63  * 18    4/23/99 12:01p Johnson
64  * Added SIF_HUGE_SHIP
65  * 
66  * 17    4/21/99 6:15p Dave
67  * Did some serious housecleaning in the beam code. Made it ready to go
68  * for anti-fighter "pulse" weapons. Fixed collision pair creation. Added
69  * a handy macro for recalculating collision pairs for a given object.
70  * 
71  * 16    4/16/99 2:34p Andsager
72  * Second pass on debris fields
73  * 
74  * 15    4/15/99 5:27p Andsager
75  * Fix explosion sound for Ships debris
76  * 
77  * 14    4/15/99 5:00p Andsager
78  * Frist pass on Debris field
79  * 
80  * 13    2/07/99 8:51p Andsager
81  * Add inner bound to asteroid field.  Inner bound tries to stay astroid
82  * free.  Wrap when within and don't throw at ships inside.
83  * 
84  * 12    1/20/99 6:04p Dave
85  * Another bit of stuff for beam weapons. Ships will properly use them
86  * now, although they're really deadly.
87  * 
88  * 11    1/06/99 2:24p Dave
89  * Stubs and release build fixes.
90  * 
91  * 10    12/03/98 3:14p Andsager
92  * Check in code that checks rotating submodel actually has ship subsystem
93  * 
94  * 9     11/19/98 11:07p Andsager
95  * Check in of physics and collision detection of rotating submodels
96  * 
97  * 8     11/13/98 10:12a Andsager
98  * simplify collision code
99  * 
100  * 7     11/05/98 5:55p Dave
101  * Big pass at reducing #includes
102  * 
103  * 6     10/23/98 3:51p Dave
104  * Full support for tstrings.tbl and foreign languages. All that remains
105  * is to make it active in Fred.
106  * 
107  * 5     10/23/98 1:11p Andsager
108  * Make ship sparks emit correctly from rotating structures.
109  * 
110  * 4     10/16/98 1:22p Andsager
111  * clean up header files
112  * 
113  * 3     10/13/98 9:28a Dave
114  * Started neatening up freespace.h. Many variables renamed and
115  * reorganized. Added AlphaColors.[h,cpp]
116  * 
117  * 2     10/07/98 10:52a Dave
118  * Initial checkin.
119  * 
120  * 1     10/07/98 10:48a Dave
121  * 
122  * 80    7/14/98 3:30p Dave
123  * 
124  * 79    5/18/98 12:05p Mike
125  * Make sm1-06a a little harder.
126  * 
127  * 78    5/06/98 12:36p Lawrance
128  * disable ambient asteroid sound for now
129  * 
130  * 77    4/30/98 12:49a Allender
131  * deal with asteroid problems in multiplayer
132  * 
133  * 76    4/27/98 1:46p Mike
134  * Make asteroid_density have no meaning.
135  * 
136  * 75    4/24/98 11:59a Dan
137  * fix bug where a null vector would occur when death_hit_pos was assinged
138  * to asteroid_pos
139  * 
140  * 74    4/23/98 4:43p Andsager
141  * Don't call   asteroid_update_collide() on creating asteroids since it
142  * creates sets of collisions pairs.  Pairs are created when objects are
143  * merged in obj_merge_created_list()
144  * 
145  * 73    4/21/98 1:23a Mike
146  * Tone down difficulty in asteroid toss missions.
147  * 
148  * 72    4/16/98 11:57a John
149  * Removed debug and unused registry values.
150  * 
151  * 71    4/08/98 1:27a Lawrance
152  * Fix typo.
153  * 
154  * 70    4/08/98 1:17a Lawrance
155  * Fix bug with red and white brackets being drawn on top of one another.
156  * 
157  * 69    4/02/98 6:28p Lawrance
158  * remove asteroid code from demo
159  * 
160  * 68    4/02/98 5:11p Mike
161  * Quick out of asteroid code if none present.
162  * 
163  * 67    4/02/98 1:34p Mike
164  * Minor difficulty balance, made a bit easier.
165  * 
166  * 66    4/02/98 1:29p Andsager
167  * 
168  * 65    4/01/98 5:34p John
169  * Made only the used POFs page in for a level.   Reduced some interp
170  * arrays.    Made custom detail level work differently.
171  * 
172  * 64    3/31/98 5:11p John
173  * Removed demo/save/restore.  Made NDEBUG defined compile.  Removed a
174  * bunch of debug stuff out of player file.  Made model code be able to
175  * unload models and malloc out only however many models are needed.
176  * 
177  * 63    3/30/98 4:02p John
178  * Made machines with < 32 MB of RAM use every other frame of certain
179  * bitmaps.   Put in code to keep track of how much RAM we've malloc'd.
180  * 
181  * 62    3/30/98 2:38p Mike
182  * Add asteroid_density to detail level support.
183  * No force explosion damage in training missions.
184  * Make cargo deathrolls shorter.
185  * 
186  * 61    3/30/98 10:07a Lawrance
187  * Um, make asteroids work again.
188  * 
189  * 60    3/29/98 12:55a Lawrance
190  * Get demo build working with limited set of data.
191  * 
192  * 59    3/26/98 9:19a Lawrance
193  * Support multiple asteroid pofs
194  * 
195  * 58    3/25/98 3:44p Andsager
196  * Fixed bug in asteroid_sub_create, where last_pos field was invalid in
197  * its creation frame but needed for collision in that frame.
198  * 
199  * 57    3/25/98 2:03p Sandeep
200  * Remove "f" from top of file.
201  * 
202  * 56    3/25/98 1:50p Mike
203  * Asteroid destruction (sm1-06a) balancing.
204  * 
205  * 55    3/25/98 10:43a Andsager
206  * Hack for ship_asteroid collisions when erroneous relative_vel >150
207  * 
208  * 54    3/23/98 12:20p Andsager
209  * Enable collision from rotation in ship_debris and ship_debris
210  * collisions.
211  * 
212  * 53    3/22/98 4:09p Andsager
213  * Make moment of inertia based on model.
214  * 
215  * 52    3/21/98 3:33p Lawrance
216  * When asteroid collides with an escort ship, make the sound carry
217  * farther
218  * 
219  * 51    3/19/98 12:09p John
220  * Fixed a bug using 6 characters.   r_heavy was using local coordinates
221  * instead of world so all asteroid-ship and debris-ship hitpos's were in
222  * the wrong spot.  Ok, I rearreanged some code to make it clearer also.
223  * 
224  * 50    3/17/98 5:55p Lawrance
225  * Support object linked sounds for asteroids.
226  * 
227  * 49    3/17/98 3:44p Mike
228  * Make asteroids-thrown-at-target not only happen when an asteroid wraps.
229  * 
230  * 48    3/17/98 9:53a Lawrance
231  * Asteroid area effect only affect ships
232  * 
233  * 47    3/17/98 9:25a Allender
234  * some minor asteroid changes for multiplayer
235  * 
236  * 46    3/17/98 12:16a Allender
237  * asteroids in multiplayer -- minor problems with position being correct
238  * 
239  * 45    3/14/98 1:44p Mike
240  * Todolist items 3365..3368.  Make child asteroids collide properly.
241  * Make asteroid throwing less bunchy, toss asteroids earlier, make
242  * facing-ness not break mission balance.
243  * 
244  * 44    3/13/98 9:06a John
245  * Made missile thrusters use a different min dist for scaling.   Made
246  * missilies not use lighting.
247  * 
248  * 43    3/12/98 4:01p Lawrance
249  * Only show warning brackets for cruiser/capital ships on the same team
250  * 
251  * $NoKeywords: $
252  */
253
254 #include "asteroid.h"
255 #include "object.h"
256 #include "objcollide.h"
257 #include "freespace.h"
258 #include "timer.h"
259 #include "3d.h"
260 #include "fireballs.h"
261 #include "gamesnd.h"
262 #include "bmpman.h"
263 #include "particle.h"
264 #include "linklist.h"
265 #include "hudescort.h"
266 #include "shiphit.h"
267 #include "multiutil.h"
268 #include "staticrand.h"
269 #include "multimsgs.h"
270 #include "systemvars.h"
271 #include "localize.h"
272 #include "multi.h"
273
274 #ifndef FS2_DEMO
275
276 #define                 ASTEROID_OBJ_USED       (1<<0)                          // flag used in asteroid_obj struct
277 #define                 MAX_ASTEROID_OBJS       MAX_ASTEROIDS           // max number of asteroids tracked in asteroid list
278 asteroid_obj    Asteroid_objs[MAX_ASTEROID_OBJS];       // array used to store asteroid object indexes
279 asteroid_obj    Asteroid_obj_list;                                              // head of linked list of asteroid_obj structs
280
281 // Asteroid editor requires first set of entries to be "None" and then "Asteroid XXX"
282 // Any changes to this will require changes to the asteroid editor
283 debris_struct Field_debris_info[] = {
284         { -1,                                                   "None", },
285         { ASTEROID_TYPE_SMALL,          "Asteroid Small", },
286         { ASTEROID_TYPE_MEDIUM, "Asteroid Medium", },
287         { ASTEROID_TYPE_BIG,            "Asteroid Large", },
288
289         { DEBRIS_TERRAN_SMALL,          "Terran Small", },
290         { DEBRIS_TERRAN_MEDIUM, "Terran Medium", },
291         { DEBRIS_TERRAN_LARGE,          "Terran Large", },
292
293         { DEBRIS_VASUDAN_SMALL, "Vasudan Small", },
294         { DEBRIS_VASUDAN_MEDIUM,        "Vasudan Medium", },
295         { DEBRIS_VASUDAN_LARGE, "Vasudan Large", },
296
297         { DEBRIS_SHIVAN_SMALL,          "Shivan Small", },
298         { DEBRIS_SHIVAN_MEDIUM, "Shivan Medium", },
299         { DEBRIS_SHIVAN_LARGE,          "Shivan Large" },
300 };
301
302 // used for randomly generating debris type when there are multiple sizes.
303 #define SMALL_DEBRIS_WEIGHT     8
304 #define MEDIUM_DEBRIS_WEIGHT    4
305 #define LARGE_DEBRIS_WEIGHT     1
306
307 int     Asteroids_enabled = 1;
308 int     Num_asteroid_types;
309 int     Num_asteroids = 0;
310 int     Asteroid_throw_objnum = -1;             //      Object index of ship to throw asteroids at.
311 int     Next_asteroid_throw;
312
313 asteroid_info   Asteroid_info[MAX_DEBRIS_TYPES];
314 asteroid                        Asteroids[MAX_ASTEROIDS];
315 asteroid_field  Asteroid_field;
316
317 static int              Asteroid_impact_explosion_ani;
318 static float    Asteroid_impact_explosion_radius;
319
320 #define ASTEROID_CHECK_WRAP_TIMESTAMP                   2000    // how often an asteroid gets checked for wrapping
321 #define ASTEROID_UPDATE_COLLIDE_TIMESTAMP       2000    // how often asteroid is checked for impending collisions with escort ships
322 #define ASTEROID_MIN_COLLIDE_TIME                               24              // time in seconds to check for asteroid colliding
323
324 //      Force updating of pair stuff for asteroid *objp.
325 void asteroid_update_collide(object *objp)
326 {
327         // Asteroid has wrapped, update collide objnum and flags
328         Asteroids[objp->instance].collide_objnum = -1;
329         Asteroids[objp->instance].collide_objsig = -1;
330         OBJ_RECALC_PAIRS(objp); 
331 }
332
333 // Clear out the Asteroid_obj_list
334 //
335 void asteroid_obj_list_init()
336 {
337         int i;
338
339         list_init(&Asteroid_obj_list);
340         for ( i = 0; i < MAX_ASTEROID_OBJS; i++ ) {
341                 Asteroid_objs[i].flags = 0;
342         }
343 }
344
345 // ---------------------------------------------------
346 // asteroid_obj_list_add()
347 //
348 // Function to add a node from the Asteroid_obj_list.  Only
349 // called from weapon_create()
350 int asteroid_obj_list_add(int objnum)
351 {
352         int index;
353
354         asteroid *cur_asteroid = &Asteroids[Objects[objnum].instance];
355         index = cur_asteroid - Asteroids;
356
357         Assert(index >= 0 && index < MAX_ASTEROID_OBJS);
358         Assert(!Asteroid_objs[index].flags & ASTEROID_OBJ_USED);
359
360         Asteroid_objs[index].flags = 0;
361         Asteroid_objs[index].objnum = objnum;
362         list_append(&Asteroid_obj_list, &Asteroid_objs[index]);
363         Asteroid_objs[index].flags |= ASTEROID_OBJ_USED;
364
365         return index;
366 }
367
368 // ---------------------------------------------------
369 // missle_obj_list_remove()
370 //
371 // Function to remove a node from the Asteroid_obj_list.  Only
372 // called from weapon_delete()
373 void asteroid_obj_list_remove(object * obj)
374 {
375         int index = obj->instance;
376
377         Assert(index >= 0 && index < MAX_ASTEROID_OBJS);
378         Assert(Asteroid_objs[index].flags & ASTEROID_OBJ_USED);
379
380         list_remove(&Asteroid_obj_list, &Asteroid_objs[index]); 
381         Asteroid_objs[index].flags = 0;
382 }
383
384
385 //      Prevent speed from getting too huge so it's hard to catch up to an asteroid.
386 float asteroid_cap_speed(int asteroid_info_index, float speed)
387 {
388         float max, double_max;
389
390         max = Asteroid_info[asteroid_info_index].max_speed;
391         double_max = max * 2;
392
393         while (speed > double_max){
394                 speed *= 0.5f;
395         }
396         
397         if (speed > max){
398                 speed *= 0.75f;
399         }
400
401         return speed;
402 }
403
404 // Returns whether position is inside inner bounding volume
405 // sum together the following: 1 inside x, 2 inside y, 4 inside z
406 // inside only when sum = 7
407 int asteroid_in_inner_bound_with_axes(asteroid_field *asfieldp, vector *pos, float delta)
408 {
409         Assert(asfieldp->has_inner_bound);
410
411         int rval = 0;
412         if ( (pos->x > asfieldp->inner_min_bound.x - delta) && (pos->x < asfieldp->inner_max_bound.x + delta) ) {
413                 rval += 1;
414         }
415
416         if ( (pos->y > asfieldp->inner_min_bound.y - delta) && (pos->y < asfieldp->inner_max_bound.y + delta) ) {
417                 rval += 2;
418         }
419
420         if ( (pos->z > asfieldp->inner_min_bound.z - delta) && (pos->z < asfieldp->inner_max_bound.z + delta) ) {
421                 rval += 4;
422         }
423
424         return rval;
425 }
426
427 // check if asteroid is within inner bound
428 // return 0 if not inside or no inner bound, 1 if inside inner bound
429 int asteroid_in_inner_bound(asteroid_field *asfieldp, vector *pos, float delta) {
430
431         if (!asfieldp->has_inner_bound) {
432                 return 0;
433         }
434
435         return (asteroid_in_inner_bound_with_axes(asfieldp, pos, delta) == 7);
436 }
437
438 // repositions asteroid outside the inner box on all 3 axes
439 // moves to the other side of the inner box a distance delta from edge of box
440 void inner_bound_pos_fixup(asteroid_field *asfieldp, vector *pos)
441 {
442         if (!asteroid_in_inner_bound(asfieldp, pos, 0)) {
443                 return;
444         }
445
446         float dist1, dist2;
447         int axis;
448
449         for (axis=0; axis<3; axis++) {
450                 dist1 = pos->a1d[axis] - asfieldp->inner_min_bound.a1d[axis];
451                 dist2 = asfieldp->inner_max_bound.a1d[axis] - pos->a1d[axis];
452                 Assert(dist1 >= 0 && dist2 >= 0);
453
454                 if (dist1 < dist2) {
455                         pos->a1d[axis] = asfieldp->inner_max_bound.a1d[axis] + dist1;
456                 } else {
457                         pos->a1d[axis] = asfieldp->inner_min_bound.a1d[axis] - dist2;
458                 }
459         }
460 }
461
462
463 // Create a single asteroid 
464 object *asteroid_create(asteroid_field *asfieldp, int asteroid_type, int asteroid_subtype)
465 {
466         int                             n, objnum;
467         matrix                  orient;
468         object                  *objp;
469         asteroid                        *asp;
470         asteroid_info   *asip;
471         vector                  pos, delta_bound;
472         angles                  angs;
473         float                           radius;
474         ushort                  signature;
475         int                             rand_base;
476
477         // bogus
478         if(asfieldp == NULL){
479                 return NULL;
480         }
481
482         for (n=0; n<MAX_ASTEROIDS; n++ ) {
483                 if ( !(Asteroids[n].flags & AF_USED) ){
484                         break;
485                 }
486         }
487
488         if (n >= MAX_ASTEROIDS) {
489                 nprintf(("Warning","Could not create asteroid, no more slots left\n"));
490                 return NULL;
491         }
492
493         if((asteroid_type < 0) || (asteroid_type >= Num_asteroid_types)){
494                 return NULL;
495         }
496
497         // HACK: multiplayer asteroid subtype always 0 to keep subtype in sync
498         if ( Game_mode & GM_MULTIPLAYER) {
499                 asteroid_subtype = 0;
500         }       
501
502         if( (asteroid_subtype < 0) || (asteroid_subtype >= MAX_ASTEROID_POFS)){
503                 return NULL;
504         }
505
506         asip = &Asteroid_info[asteroid_type];
507
508         // bogus
509         if(asip->modelp[asteroid_subtype] == NULL){
510                 return NULL;
511         }       
512
513         asp = &Asteroids[n];
514         asp->type = asteroid_type;
515         asp->asteroid_subtype = asteroid_subtype;
516         asp->flags = 0;
517         asp->flags |= AF_USED;
518         asp->check_for_wrap = timestamp_rand(0, ASTEROID_CHECK_WRAP_TIMESTAMP);
519         asp->check_for_collide = timestamp_rand(0, ASTEROID_UPDATE_COLLIDE_TIMESTAMP);
520         asp->final_death_time = timestamp(-1);
521         asp->collide_objnum = -1;
522         asp->collide_objsig = -1;
523         asp->target_objnum = -1;
524
525         radius = model_get_radius(asip->model_num[asteroid_subtype]);
526
527         vm_vec_sub(&delta_bound, &asfieldp->max_bound, &asfieldp->min_bound);
528
529         // for multiplayer, we want to do a static_rand so that everything behaves the same on all machines
530         signature = 0;
531         rand_base = 0;
532         if ( Game_mode & GM_NORMAL ) {
533                 pos.x = asfieldp->min_bound.x + delta_bound.x * frand();
534                 pos.y = asfieldp->min_bound.y + delta_bound.y * frand();
535                 pos.z = asfieldp->min_bound.z + delta_bound.z * frand();
536
537                 inner_bound_pos_fixup(asfieldp, &pos);
538                 // vm_set_identity(&orient);
539                 angs.p = frand() * 2*PI;
540                 angs.b = frand() * 2*PI;
541                 angs.h = frand() * 2*PI;
542         } else {
543                 signature = multi_assign_network_signature( MULTI_SIG_ASTEROID );
544                 rand_base = signature;
545
546                 pos.x = asfieldp->min_bound.x + delta_bound.x * static_randf( rand_base++ );
547                 pos.y = asfieldp->min_bound.y + delta_bound.y * static_randf( rand_base++ );
548                 pos.z = asfieldp->min_bound.z + delta_bound.z * static_randf( rand_base++ );
549
550                 inner_bound_pos_fixup(asfieldp, &pos);
551                 // vm_set_identity(&orient);
552                 angs.p = static_randf( rand_base++ ) * 2*PI;
553                 angs.b = static_randf( rand_base++ ) * 2*PI;
554                 angs.h = static_randf( rand_base++ ) * 2*PI;
555         }
556
557         vm_angles_2_matrix(&orient, &angs);
558
559         objnum = obj_create( OBJ_ASTEROID, -1, n, &orient, &pos, radius, OF_RENDERS | OF_PHYSICS | OF_COLLIDES);
560         // mprintf(("Framecount: %d asteroid create: obj = %d\n", Framecount, objnum));
561         
562         if ( (objnum == -1) || (objnum >= MAX_OBJECTS) ) {
563                 mprintf(("Couldn't create asteroid -- out of object slots\n"));
564                 return NULL;
565         }
566
567         asp->objnum = objnum;
568
569         // Add to Asteroid_used_list
570         asteroid_obj_list_add(objnum);
571
572         objp = &Objects[objnum];
573
574         if ( Game_mode & GM_MULTIPLAYER ){
575                 objp->net_signature = signature;
576         }
577
578         Num_asteroids++;
579
580         if (radius < 1.0) {
581                 radius = 1.0f;
582         }
583
584         vector rotvel;
585         if ( Game_mode & GM_NORMAL ) {
586                 vm_vec_rand_vec_quick(&rotvel);
587                 vm_vec_scale(&rotvel, frand()/4.0f + 0.1f);
588                 objp->phys_info.rotvel = rotvel;
589                 vm_vec_rand_vec_quick(&objp->phys_info.vel);
590         } else {
591                 static_randvec( rand_base++, &rotvel );
592                 vm_vec_scale(&rotvel, static_randf(rand_base++)/4.0f + 0.1f);
593                 objp->phys_info.rotvel = rotvel;
594                 static_randvec( rand_base++, &objp->phys_info.vel );
595         }
596
597
598         float speed;
599
600         if ( Game_mode & GM_NORMAL ) {
601                 speed = asteroid_cap_speed(asteroid_type, asfieldp->speed*frand_range(0.5f + (float) Game_skill_level/NUM_SKILL_LEVELS, 2.0f + (float) (2*Game_skill_level)/NUM_SKILL_LEVELS));
602         } else {
603                 speed = asteroid_cap_speed(asteroid_type, asfieldp->speed*static_randf_range(rand_base++, 0.5f + (float) Game_skill_level/NUM_SKILL_LEVELS, 2.0f + (float) (2*Game_skill_level)/NUM_SKILL_LEVELS));
604         }
605         
606         vm_vec_scale(&objp->phys_info.vel, speed);
607         objp->phys_info.desired_vel = objp->phys_info.vel;
608
609         // blow out his reverse thrusters. Or drag, same thing.
610         objp->phys_info.rotdamp = 10000.0f;
611         objp->phys_info.side_slip_time_const = 10000.0f;
612         objp->phys_info.flags |= (PF_REDUCED_DAMP | PF_DEAD_DAMP);      // set damping equal for all axis and not changable
613
614         // Fill in the max_vel field, so the collision pair stuff knows
615         // how fast this can move maximum in order to throw out collisions.
616         // This is in local coordinates, so Z is forward velocity.
617         objp->phys_info.max_vel.x = 0.0f;
618         objp->phys_info.max_vel.y = 0.0f;
619         objp->phys_info.max_vel.z = vm_vec_mag(&objp->phys_info.desired_vel);
620         
621         objp->phys_info.mass = asip->modelp[asteroid_subtype]->rad * 700.0f;
622         objp->phys_info.I_body_inv.rvec.x = 1.0f / (objp->phys_info.mass*asip->modelp[asteroid_subtype]->rad);
623         objp->phys_info.I_body_inv.uvec.y = objp->phys_info.I_body_inv.rvec.x;
624         objp->phys_info.I_body_inv.fvec.z = objp->phys_info.I_body_inv.rvec.x;
625         objp->hull_strength = asip->initial_hull_strength * (0.8f + (float)Game_skill_level/NUM_SKILL_LEVELS)/2.0f;
626
627         // ensure vel is valid
628         Assert( !vm_is_vec_nan(&objp->phys_info.vel) ); 
629
630         // assign a persistant sound to the asteroid
631 //      obj_snd_assign(objnum, SND_ASTEROID);
632
633         return objp;
634 }
635
636 //      Create asteroids when parent_objp blows up.
637 void asteroid_sub_create(object *parent_objp, int asteroid_type, vector *relvec)
638 {
639         object  *new_objp;
640         float speed;
641
642         Assert(parent_objp->type == OBJ_ASTEROID);
643         int subtype = Asteroids[parent_objp->instance].asteroid_subtype;
644         new_objp = asteroid_create(&Asteroid_field, asteroid_type, subtype);
645
646         if (new_objp == NULL)
647                 return;
648
649         if ( MULTIPLAYER_MASTER ){
650                 send_asteroid_create( new_objp, parent_objp, asteroid_type, relvec );
651         }
652
653         //      Now, bash some values.
654         vm_vec_scale_add(&new_objp->pos, &parent_objp->pos, relvec, 0.5f * parent_objp->radius);
655         float parent_speed = vm_vec_mag_quick(&parent_objp->phys_info.vel);
656
657         if ( parent_speed < 0.1f ) {
658                 parent_speed = vm_vec_mag_quick(&Asteroid_field.vel);
659         }
660
661         new_objp->phys_info.vel = parent_objp->phys_info.vel;
662         if ( Game_mode & GM_NORMAL )
663                 speed = asteroid_cap_speed(asteroid_type, (frand() + 2.0f) * parent_speed);
664         else
665                 speed = asteroid_cap_speed(asteroid_type, (static_randf(new_objp->net_signature)+2.0f) * parent_speed);
666
667         vm_vec_scale_add2(&new_objp->phys_info.vel, relvec, speed);
668         if (vm_vec_mag_quick(&new_objp->phys_info.vel) > 80.0f)
669                 vm_vec_scale(&new_objp->phys_info.vel, 0.5f);
670
671         new_objp->phys_info.desired_vel = new_objp->phys_info.vel;
672         vm_vec_scale_add(&new_objp->last_pos, &new_objp->pos, &new_objp->phys_info.vel, -flFrametime);
673         // DA: 4/22/98  We get next line for free when new object (in obj_create_list) is merged.
674         // this line gives too many collision pairs.
675         //      asteroid_update_collide(new_objp);
676 }
677
678 // Load in an asteroid model
679 void asteroid_load(int asteroid_info_index, int asteroid_subtype)
680 {
681         asteroid_info   *asip;
682 //      int                             pof_index;
683
684         asip = &Asteroid_info[asteroid_info_index];
685
686         // pick one of MAX_ASTEROID_POFS models
687         // LOAD ALL TEXTURES USED
688 //      static int asteroid_pof_index = rand() % MAX_ASTEROID_POFS;
689 //      if (Asteroid_field.debris_genre == DG_ASTEROID) {
690 //              pof_index = asteroid_pof_index;
691 //      } else {
692 //              // only 1 pof for ship debris type
693 //              pof_index = 0;
694 //      }
695
696         asip->model_num[asteroid_subtype] = model_load( asip->pof_files[asteroid_subtype], 0, NULL );
697
698         if (asip->model_num[asteroid_subtype] > -1) {
699                 asip->modelp[asteroid_subtype] = model_get(asip->model_num[asteroid_subtype]);
700                 
701                 // Stuff detail level distances.
702                 for (int i = 0; i < asip->num_detail_levels; i++) {
703                         asip->modelp[asteroid_subtype]->detail_depth[i] = i2fl(asip->detail_distance[i]);
704                 }
705         }
706 }
707
708 // randomly choose a debris model within the current group
709 int get_debris_from_same_group(int index) {
710         int group_base, group_offset;
711
712         group_base = (index / 3) * 3;
713         group_offset = index - group_base;
714
715         // group base + offset
716         // offset is formed by adding 1 or 2 (since 3 in model group) and mapping back in the 0-2 range
717         return group_base + ((group_offset + rand()%2 + 1) % 3);
718 }
719
720 // returns a weight that depends on asteroid size.
721 // the weight is then used to determine the frequencty of different sizes of ship debris
722 int get_debris_weight(int ship_debris_index)
723 {
724         switch (ship_debris_index) {
725         case DEBRIS_TERRAN_SMALL:
726         case DEBRIS_VASUDAN_SMALL:
727         case DEBRIS_SHIVAN_SMALL:
728                 return SMALL_DEBRIS_WEIGHT;
729                 break;
730
731         case DEBRIS_TERRAN_MEDIUM:
732         case DEBRIS_VASUDAN_MEDIUM:
733         case DEBRIS_SHIVAN_MEDIUM:
734                 return MEDIUM_DEBRIS_WEIGHT;
735                 break;
736
737         case DEBRIS_TERRAN_LARGE:
738         case DEBRIS_VASUDAN_LARGE:
739         case DEBRIS_SHIVAN_LARGE:
740                 return LARGE_DEBRIS_WEIGHT;
741                 break;
742
743         default:
744                 Int3();
745                 return 1;
746                 break;
747         }
748 }
749
750 // Create all the asteroids for the mission, called from 
751 void asteroid_create_all()
752 {
753         int i, idx;
754
755         // ship_debris_odds_table keeps track of debris type of the next debris piece
756         // each different type (size) of debris piece has a diffenent weight, smaller weighted more heavily than larger.
757         // choose next type from table ship_debris_odds_table by rand()%max_weighted_range,
758         //  the first column in ship_debris_odds_table random number *below* which the debris type in the second column is selected.
759         int ship_debris_odds_table[3][2];
760         int max_weighted_range = 0;
761
762         if (!Asteroids_enabled)
763                 return;
764
765         if (Asteroid_field.num_initial_asteroids <= 0 ) {
766                 return;
767         }
768
769         int max_asteroids = Asteroid_field.num_initial_asteroids; // * (1.0f - 0.1f*(MAX_DETAIL_LEVEL-Detail.asteroid_density)));
770
771         int num_debris_types = 0;
772
773         // get number of ship debris types
774         if (Asteroid_field.debris_genre == DG_SHIP) {
775                 for (idx=0; idx<3; idx++) {
776                         if (Asteroid_field.field_debris_type[idx] != -1) {
777                                 num_debris_types++;
778                         }
779                 }
780
781                 // Calculate the odds table
782                 for (idx=0; idx<num_debris_types; idx++) {
783                         int debris_weight = get_debris_weight(Asteroid_field.field_debris_type[idx]);
784                         ship_debris_odds_table[idx][0] = max_weighted_range + debris_weight;
785                         ship_debris_odds_table[idx][1] = Asteroid_field.field_debris_type[idx];
786                         max_weighted_range += debris_weight;
787                 }
788         }
789
790         // Load Asteroid/ship models
791         if (Asteroid_field.debris_genre == DG_SHIP) {
792                 for (idx=0; idx<num_debris_types; idx++) {
793                         asteroid_load(Asteroid_field.field_debris_type[idx], 0);
794                 }
795         } else {
796                 if (Asteroid_field.field_debris_type[0] != -1) {
797                         asteroid_load(ASTEROID_TYPE_SMALL, 0);
798                         asteroid_load(ASTEROID_TYPE_MEDIUM, 0);
799                         asteroid_load(ASTEROID_TYPE_BIG, 0);
800                 }
801
802                 if (Asteroid_field.field_debris_type[1] != -1) {
803                         asteroid_load(ASTEROID_TYPE_SMALL, 1);
804                         asteroid_load(ASTEROID_TYPE_MEDIUM, 1);
805                         asteroid_load(ASTEROID_TYPE_BIG, 1);
806                 }
807
808                 if (Asteroid_field.field_debris_type[2] != -1) {
809                         asteroid_load(ASTEROID_TYPE_SMALL, 2);
810                         asteroid_load(ASTEROID_TYPE_MEDIUM, 2);
811                         asteroid_load(ASTEROID_TYPE_BIG, 2);
812                 }
813         }
814
815         // load all the asteroid/debris pieces
816         for (i=0; i<max_asteroids; i++) {
817                 if (Asteroid_field.debris_genre == DG_ASTEROID) {
818                         // For asteroid, load only large asteroids
819
820                         // get a valid subtype
821                         int subtype = rand() % 3;
822                         while (Asteroid_field.field_debris_type[subtype] == -1) {
823                                 subtype = (subtype + 1) % 3;
824                         }
825
826                         asteroid_create(&Asteroid_field, ASTEROID_TYPE_BIG, subtype);
827                 } else {
828                         Assert(num_debris_types > 0);
829
830                         int rand_choice = rand() % max_weighted_range;
831
832                         for (idx=0; idx<3; idx++) {
833                                 // for ship debris, choose type according to odds table
834                                 if (rand_choice < ship_debris_odds_table[idx][0]) {
835                                         asteroid_create(&Asteroid_field, ship_debris_odds_table[idx][1], 0);
836                                         break;
837                                 }
838                         }
839                 }
840         }
841 }
842
843 // Init asteriod system for the level, called from game_level_init()
844 void asteroid_level_init()
845 {
846         Asteroid_field.num_initial_asteroids=0;
847         Num_asteroids = 0;
848         Next_asteroid_throw = timestamp(1);
849         asteroid_obj_list_init();
850 }
851
852 // return !0 if asteroid should be wrapped, 0 otherwise.  Multiplayer clients will always return
853 // 0 from this function.  We will force a wrap on the clients when server tells us
854 int asteroid_should_wrap(object *objp, asteroid_field *asfieldp)
855 {
856         if ( MULTIPLAYER_CLIENT )
857                 return 0;
858
859         if (objp->pos.x < asfieldp->min_bound.x) {
860                 return 1;
861         }
862
863         if (objp->pos.y < asfieldp->min_bound.y) {
864                 return 1;
865         }
866
867         if (objp->pos.z < asfieldp->min_bound.z) {
868                 return 1;
869         }
870
871         if (objp->pos.x > asfieldp->max_bound.x) {
872                 return 1;
873         }
874
875         if (objp->pos.y > asfieldp->max_bound.y) {
876                 return 1;
877         }
878
879         if (objp->pos.z > asfieldp->max_bound.z) {
880                 return 1;
881         }
882
883         // check against inner bound
884         if (asfieldp->has_inner_bound) {
885                 if ( (objp->pos.x > asfieldp->inner_min_bound.x) && (objp->pos.x < asfieldp->inner_max_bound.x)
886                   && (objp->pos.y > asfieldp->inner_min_bound.y) && (objp->pos.y < asfieldp->inner_max_bound.y)
887                   && (objp->pos.z > asfieldp->inner_min_bound.z) && (objp->pos.z < asfieldp->inner_max_bound.z) ) {
888
889                         return 1;
890                 }
891         }
892
893         return 0;
894 }
895
896 // Wrap an asteroid from one end of the asteroid field to the other
897 void asteroid_wrap_pos(object *objp, asteroid_field *asfieldp)
898 {
899         if (objp->pos.x < asfieldp->min_bound.x) {
900                 objp->pos.x = asfieldp->max_bound.x + (objp->pos.x - asfieldp->min_bound.x);
901         }
902
903         if (objp->pos.y < asfieldp->min_bound.y) {
904                 objp->pos.y = asfieldp->max_bound.y + (objp->pos.y - asfieldp->min_bound.y);
905         }
906         
907         if (objp->pos.z < asfieldp->min_bound.z) {
908                 objp->pos.z = asfieldp->max_bound.z + (objp->pos.z - asfieldp->min_bound.z);
909         }
910
911         if (objp->pos.x > asfieldp->max_bound.x) {
912                 objp->pos.x = asfieldp->min_bound.x + (objp->pos.x - asfieldp->max_bound.x);
913         }
914
915         if (objp->pos.y > asfieldp->max_bound.y) {
916                 objp->pos.y = asfieldp->min_bound.y + (objp->pos.y - asfieldp->max_bound.y);
917         }
918
919         if (objp->pos.z > asfieldp->max_bound.z) {
920                 objp->pos.z = asfieldp->min_bound.z + (objp->pos.z - asfieldp->max_bound.z);
921         }
922
923         // wrap on inner bound, check all 3 axes as needed, use of rand ok for multiplayer with send_asteroid_throw()
924         inner_bound_pos_fixup(asfieldp, &objp->pos);
925
926 }
927
928
929 // return !0 if this asteroid is a target for any ship, otherwise return 0
930 int asteroid_is_targeted(object *objp)
931 {
932         ship_obj        *so;
933         object  *ship_objp;
934         int             asteroid_obj_index;
935
936         asteroid_obj_index=OBJ_INDEX(objp);
937
938         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
939                 ship_objp = &Objects[so->objnum];
940                 if ( Ai_info[Ships[ship_objp->instance].ai_index].target_objnum == asteroid_obj_index ) {
941                         return 1;
942                 }
943         }
944         
945         return 0;
946 }
947
948 //      Create an asteroid that will hit object *objp in delta_time seconds
949 void asteroid_aim_at_target(object *objp, object *asteroid_objp, float delta_time)
950 {
951         vector  predicted_center_pos;
952         vector  rand_vec;
953         float           speed;
954
955         vm_vec_scale_add(&predicted_center_pos, &objp->pos, &objp->phys_info.vel, delta_time);
956         vm_vec_rand_vec_quick(&rand_vec);
957         vm_vec_scale_add2(&predicted_center_pos, &rand_vec, objp->radius/2.0f);
958
959         vm_vec_add2(&rand_vec, &objp->orient.fvec);
960         if (vm_vec_mag_quick(&rand_vec) < 0.1f)
961                 vm_vec_add2(&rand_vec, &objp->orient.rvec);
962         vm_vec_normalize(&rand_vec);
963
964         speed = Asteroid_info[0].max_speed * (frand()/2.0f + 0.5f);
965         
966         vm_vec_copy_scale(&asteroid_objp->phys_info.vel, &rand_vec, -speed);
967         asteroid_objp->phys_info.desired_vel = asteroid_objp->phys_info.vel;
968         vm_vec_scale_add(&asteroid_objp->pos, &predicted_center_pos, &asteroid_objp->phys_info.vel, -delta_time);
969         vm_vec_scale_add(&asteroid_objp->last_pos, &asteroid_objp->pos, &asteroid_objp->phys_info.vel, -flFrametime);
970 }
971
972 int     Max_incoming_asteroids[NUM_SKILL_LEVELS] = {3, 4, 5, 7, 10};
973
974 //      Call once per frame to maybe throw an asteroid at a ship.
975 //      "count" asteroids already targeted on 
976 void maybe_throw_asteroid(int count)
977 {
978         if (!timestamp_elapsed(Next_asteroid_throw)) {
979                 return;
980         }
981
982         if (Asteroid_throw_objnum == -1) {
983                 return;
984         }
985
986         nprintf(("AI", "Incoming asteroids: %i\n", count));
987
988         if (count > Max_incoming_asteroids[Game_skill_level])
989                 return;
990
991         Next_asteroid_throw = timestamp(1000 + 1200 * count/(Game_skill_level+1));
992
993         ship_obj        *so;
994         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
995                 object *A = &Objects[so->objnum];
996                 if (so->objnum == Asteroid_throw_objnum) {
997                         int subtype = rand() % 3;
998                         while (Asteroid_field.field_debris_type[subtype] == -1) {
999                                 subtype = (subtype + 1) % 3;
1000                         }
1001                         object *objp = asteroid_create(&Asteroid_field, ASTEROID_TYPE_BIG, subtype);
1002                         if (objp != NULL) {
1003                                 asteroid_aim_at_target(A, objp, ASTEROID_MIN_COLLIDE_TIME + frand() * 20.0f);
1004
1005                                 // if asteroid is inside inner bound, kill it
1006                                 if (asteroid_in_inner_bound(&Asteroid_field, &objp->pos, 0.0f)) {
1007                                         objp->flags |= OF_SHOULD_BE_DEAD;
1008                                 } else {
1009                                         Asteroids[objp->instance].target_objnum = so->objnum;
1010                                         // DA: 4/22/98  We get next line for free when new object (in obj_create_list) is merged.
1011                                         // this line gives too many collision pairs.
1012                                         // asteroid_update_collide(objp);
1013
1014                                         if ( MULTIPLAYER_MASTER ) {
1015                                                 send_asteroid_throw( objp );
1016                                         }
1017                                 }
1018                         }
1019
1020                         return;
1021                 }
1022         }
1023
1024 }
1025
1026 void asteroid_delete( object * obj )
1027 {
1028         int             num;
1029         asteroid        *asp;
1030
1031         num = obj->instance;
1032         Assert( Asteroids[num].objnum == OBJ_INDEX(obj));
1033
1034         asp = &Asteroids[num];
1035
1036         Assert( Num_asteroids >= 0 );
1037
1038         asp->flags = 0;
1039         Num_asteroids--;
1040
1041         // Delete asteroid from Asteroid_used_list
1042         asteroid_obj_list_remove( obj );
1043 }
1044
1045 // See if we should reposition the asteroid.  Only reposition if oustide the bounding volume and
1046 // the player isn't looking towards the asteroid.
1047 void asteroid_maybe_reposition(object *objp, asteroid_field *asfieldp)
1048 {
1049         // passive field does not wrap
1050         if (asfieldp->field_type == FT_PASSIVE) {
1051                 return;
1052         }
1053
1054         if ( asteroid_should_wrap(objp, asfieldp) ) {
1055                 vector  vec_to_asteroid, old_asteroid_pos, old_vel;
1056                 float           dot, dist;
1057
1058                 old_asteroid_pos = objp->pos;
1059                 old_vel = objp->phys_info.vel;
1060
1061                 //nprintf(("AI", "Frame %i, reposition #%i\n", Framecount, objp-Objects));
1062
1063                 // don't wrap asteroid if it is a target of some ship
1064                 if ( !asteroid_is_targeted(objp) ) {
1065
1066                         // only wrap if player won't see asteroid disappear/reverse direction
1067                         dist = vm_vec_normalized_dir(&vec_to_asteroid, &objp->pos, &Eye_position);
1068                         dot = vm_vec_dot(&Eye_matrix.fvec, &vec_to_asteroid);
1069                         
1070                         if ((dot < 0.7f) || (dist > 3000.0f)) {
1071                                 if (Num_asteroids > MAX_ASTEROIDS-10) {
1072                                         objp->flags |= OF_SHOULD_BE_DEAD;
1073                                 } else {
1074                                         // check to ensure player won't see asteroid appear either
1075                                         asteroid_wrap_pos(objp, asfieldp);
1076                                         Asteroids[objp->instance].target_objnum = -1;
1077
1078                                         vm_vec_normalized_dir(&vec_to_asteroid, &objp->pos, &Eye_position);
1079                                         dot = vm_vec_dot(&Eye_matrix.fvec, &vec_to_asteroid);
1080                                         dist = vm_vec_dist_quick(&objp->pos, &Eye_position);
1081                                         
1082                                         if (( dot > 0.7f) && (dist < 3000.0f)) {
1083                                                 // player would see asteroid pop out other side, so reverse velocity instead of wrapping
1084                                                 objp->pos = old_asteroid_pos;           
1085                                                 vm_vec_copy_scale(&objp->phys_info.vel, &old_vel, -1.0f);
1086                                                 objp->phys_info.desired_vel = objp->phys_info.vel;
1087                                                 Asteroids[objp->instance].target_objnum = -1;
1088                                         }
1089
1090                                         // update last pos (after vel is known)
1091                                         vm_vec_scale_add(&objp->last_pos, &objp->pos, &objp->phys_info.vel, -flFrametime);
1092
1093                                         asteroid_update_collide(objp);
1094
1095                                         if ( MULTIPLAYER_MASTER )
1096                                                 send_asteroid_throw( objp );
1097                                 }
1098                         }
1099                 }
1100         }
1101 }
1102
1103 void lerp(float *goal, float f1, float f2, float scale)
1104 {
1105         *goal = (f2 - f1) * scale + f1;
1106 }
1107
1108 void asteroid_process_pre( object *objp, float frame_time)
1109 {
1110         if (Asteroids_enabled) {
1111                 vector  *v, *vv;
1112
1113                 v = &objp->phys_info.vel;
1114                 vv = &objp->phys_info.desired_vel;
1115
1116                 //nprintf(("AI", "Frm %i: Obj #%2i: Hull: %5.1f Vel: %5.1f %5.1f %5.1f Des: %5.1f %5.1f %5.1f\n", Framecount, objp-Objects, objp->hull_strength, v->x, v->y, v->z, vv->x, vv->y, vv->z));
1117
1118                 //      Make vel chase desired_vel
1119                 lerp(&objp->phys_info.vel.x, objp->phys_info.vel.x, objp->phys_info.desired_vel.x, flFrametime);
1120                 lerp(&objp->phys_info.vel.y, objp->phys_info.vel.y, objp->phys_info.desired_vel.y, flFrametime);
1121                 lerp(&objp->phys_info.vel.z, objp->phys_info.vel.z, objp->phys_info.desired_vel.z, flFrametime);
1122         }
1123 }
1124
1125 #ifndef PLAT_UNIX
1126 #pragma warning ( push )
1127 #pragma warning ( disable : 4701 )
1128 #endif
1129 int asteroid_check_collision(object *pasteroid, object *other_obj, vector *hitpos, collision_info_struct *asteroid_hit_info)
1130 {
1131         if (!Asteroids_enabled) {
1132                 return 0;
1133         }
1134
1135         mc_info mc;
1136         int             num, asteroid_subtype;
1137
1138         Assert( pasteroid->type == OBJ_ASTEROID );
1139
1140         num = pasteroid->instance;
1141         Assert( num >= 0 );
1142
1143         Assert( Asteroids[num].objnum == OBJ_INDEX(pasteroid));
1144         asteroid_subtype = Asteroids[num].asteroid_subtype;
1145
1146         // asteroid_hit_info NULL  --  asteroid-weapon collision
1147         if ( asteroid_hit_info == NULL ) {
1148                 // asteroid weapon collision
1149                 Assert( other_obj->type == OBJ_WEAPON );
1150                 mc.model_num = Asteroid_info[Asteroids[num].type].model_num[asteroid_subtype];  // Fill in the model to check
1151                 model_clear_instance( mc.model_num );
1152                 mc.orient = &pasteroid->orient;                                 // The object's orient
1153                 mc.pos = &pasteroid->pos;                                                       // The object's position
1154                 mc.p0 = &other_obj->last_pos;                           // Point 1 of ray to check
1155                 mc.p1 = &other_obj->pos;                                        // Point 2 of ray to check
1156                 mc.flags = (MC_CHECK_MODEL);
1157
1158                 if (model_collide(&mc))
1159                         *hitpos = mc.hit_point_world;
1160
1161                 return mc.num_hits;
1162         }
1163
1164         // asteroid ship collision -- use asteroid_hit_info to calculate physics
1165         object *ship_obj = other_obj;
1166         Assert( ship_obj->type == OBJ_SHIP );
1167
1168         object* heavy = asteroid_hit_info->heavy;
1169         object* light = asteroid_hit_info->light;
1170         object *heavy_obj = heavy;
1171         object *light_obj = light;
1172
1173         vector zero, p0, p1;
1174         vm_vec_zero( &zero );
1175         vm_vec_sub( &p0, &light->last_pos, &heavy->last_pos );
1176         vm_vec_sub( &p1, &light->pos, &heavy->pos );
1177
1178         mc.pos = &zero;                                                         // The object's position
1179         mc.p0 = &p0;                                                                    // Point 1 of ray to check
1180         mc.p1 = &p1;                                                                    // Point 2 of ray to check
1181
1182         // find the light object's position in the heavy object's reference frame at last frame and also in this frame.
1183         vector p0_temp, p0_rotated;
1184                 
1185         // Collision detection from rotation enabled if at rotaion is less than 30 degree in frame
1186         // This should account for all ships
1187         if ( (vm_vec_mag_squared( &heavy->phys_info.rotvel ) * flFrametime*flFrametime) < (PI*PI/36) ) {
1188                 // collide_rotate calculate (1) start position and (2) relative velocity
1189                 asteroid_hit_info->collide_rotate = 1;
1190                 vm_vec_rotate( &p0_temp, &p0, &heavy->last_orient );
1191                 vm_vec_unrotate( &p0_rotated, &p0_temp, &heavy->orient );
1192                 mc.p0 = &p0_rotated;                            // Point 1 of ray to check
1193                 vm_vec_sub( &asteroid_hit_info->light_rel_vel, &p1, &p0_rotated );
1194                 vm_vec_scale( &asteroid_hit_info->light_rel_vel, 1/flFrametime );
1195                 // HACK - this applies to big ships warping in/out of asteroid fields - not sure what it does
1196                 if (vm_vec_mag(&asteroid_hit_info->light_rel_vel) > 300) {
1197                         // nprintf(("Physics", "Asteroid type %d\n", Asteroids[asteroid_hit_info->light->instance].type));
1198                         asteroid_hit_info->collide_rotate = 0;
1199                         vm_vec_sub( &asteroid_hit_info->light_rel_vel, &light->phys_info.vel, &heavy->phys_info.vel );
1200                 }
1201         } else {
1202                 asteroid_hit_info->collide_rotate = 0;
1203                 vm_vec_sub( &asteroid_hit_info->light_rel_vel, &light->phys_info.vel, &heavy->phys_info.vel );
1204         }
1205
1206         int mc_ret_val = 0;
1207
1208         if ( asteroid_hit_info->heavy == ship_obj ) {   // ship is heavier, so asteroid is sphere. Check sphere collision against ship poly model
1209                 mc.model_num = Ships[ship_obj->instance].modelnum;              // Fill in the model to check
1210                 mc.orient = &ship_obj->orient;                                                          // The object's orient
1211                 mc.radius = pasteroid->radius;
1212                 mc.flags = (MC_CHECK_MODEL | MC_CHECK_SPHERELINE);
1213
1214                 // copy important data
1215                 int copy_flags = mc.flags;  // make a copy of start end positions of sphere in  big ship RF
1216                 vector copy_p0, copy_p1;
1217                 copy_p0 = *mc.p0;
1218                 copy_p1 = *mc.p1;
1219
1220                 // first test against the sphere - if this fails then don't do any submodel tests
1221                 mc.flags = MC_ONLY_SPHERE | MC_CHECK_SPHERELINE;
1222
1223                 int submodel_list[MAX_ROTATING_SUBMODELS];
1224                 int num_rotating_submodels = 0;
1225                 polymodel *pm;
1226
1227                 ship_model_start(ship_obj);
1228
1229                 if (model_collide(&mc)) {
1230
1231                         // Set earliest hit time
1232                         asteroid_hit_info->hit_time = FLT_MAX;
1233
1234                         // Do collision the cool new way
1235                         if ( asteroid_hit_info->collide_rotate ) {
1236                                 // We collide with the sphere, find the list of rotating submodels and test one at a time
1237                                 model_get_rotating_submodel_list(submodel_list, &num_rotating_submodels, heavy_obj);
1238
1239                                 // Get polymodel and turn off all rotating submodels, collide against only 1 at a time.
1240                                 pm = model_get(Ships[heavy_obj->instance].modelnum);
1241
1242                                 // turn off all rotating submodels and test for collision
1243                                 for (int i=0; i<num_rotating_submodels; i++) {
1244                                         pm->submodel[submodel_list[i]].blown_off = 1;
1245                                 }
1246
1247                                 // reset flags to check MC_CHECK_MODEL | MC_CHECK_SPHERELINE and maybe MC_CHECK_INVISIBLE_FACES and MC_SUBMODEL_INSTANCE
1248                                 mc.flags = copy_flags | MC_SUBMODEL_INSTANCE;
1249
1250
1251                                 // check each submodel in turn
1252                                 for (int i=0; i<num_rotating_submodels; i++) {
1253                                         // turn on submodel for collision test
1254                                         pm->submodel[submodel_list[i]].blown_off = 0;
1255
1256                                         // set angles for last frame (need to set to prev to get p0)
1257                                         angles copy_angles = pm->submodel[submodel_list[i]].angs;
1258
1259                                         // find the start and end positions of the sphere in submodel RF
1260                                         pm->submodel[submodel_list[i]].angs = pm->submodel[submodel_list[i]].sii->prev_angs;
1261                                         world_find_model_point(&p0, &light_obj->last_pos, pm, submodel_list[i], &heavy_obj->last_orient, &heavy_obj->last_pos);
1262
1263                                         pm->submodel[submodel_list[i]].angs = copy_angles;
1264                                         world_find_model_point(&p1, &light_obj->pos, pm, submodel_list[i], &heavy_obj->orient, &heavy_obj->pos);
1265
1266                                         mc.p0 = &p0;
1267                                         mc.p1 = &p1;
1268                                         // mc.pos = zero        // in submodel RF
1269
1270                                         mc.orient = &vmd_identity_matrix;
1271                                         mc.submodel_num = submodel_list[i];
1272
1273                                         if ( model_collide(&mc) ) {
1274                                                 if ( mc.hit_dist < asteroid_hit_info->hit_time ) {
1275                                                         mc_ret_val = 1;
1276
1277                                                         // set up asteroid_hit_info common
1278                                                         set_hit_struct_info(asteroid_hit_info, &mc, SUBMODEL_ROT_HIT);
1279
1280                                                         // set up asteroid_hit_info for rotating submodel
1281                                                         if (asteroid_hit_info->edge_hit == 0) {
1282                                                                 model_find_obj_dir(&asteroid_hit_info->collision_normal, &mc.hit_normal, heavy_obj, mc.hit_submodel);
1283                                                         }
1284
1285                                                         // find position in submodel RF of light object at collison
1286                                                         vector int_light_pos, diff;
1287                                                         vm_vec_sub(&diff, mc.p1, mc.p0);
1288                                                         vm_vec_scale_add(&int_light_pos, mc.p0, &diff, mc.hit_dist);
1289                                                         model_find_world_point(&asteroid_hit_info->light_collision_cm_pos, &int_light_pos, mc.model_num, mc.hit_submodel, &heavy_obj->orient, &zero);
1290                                                 }
1291                                         }
1292                                         // Don't look at this submodel again
1293                                         pm->submodel[submodel_list[i]].blown_off = 1;
1294                                 }
1295
1296                         }
1297
1298                         // Recover and do usual ship_ship collision, but without rotating submodels
1299                         mc.flags = copy_flags;
1300                         *mc.p0 = copy_p0;
1301                         *mc.p1 = copy_p1;
1302                         mc.orient = &heavy_obj->orient;
1303
1304                         // usual ship_ship collision test
1305                         if ( model_collide(&mc) )       {
1306                                 // check if this is the earliest hit
1307                                 if (mc.hit_dist < asteroid_hit_info->hit_time) {
1308                                         mc_ret_val = 1;
1309
1310                                         set_hit_struct_info(asteroid_hit_info, &mc, SUBMODEL_NO_ROT_HIT);
1311
1312                                         // get collision normal if not edge hit
1313                                         if (asteroid_hit_info->edge_hit == 0) {
1314                                                 model_find_obj_dir(&asteroid_hit_info->collision_normal, &mc.hit_normal, heavy_obj, mc.hit_submodel);
1315                                         }
1316
1317                                         // find position in submodel RF of light object at collison
1318                                         vector diff;
1319                                         vm_vec_sub(&diff, mc.p1, mc.p0);
1320                                         vm_vec_scale_add(&asteroid_hit_info->light_collision_cm_pos, mc.p0, &diff, mc.hit_dist);
1321
1322                                 }
1323                         }
1324
1325                         ship_model_stop( ship_obj );
1326                 }
1327
1328         } else {
1329                 // Asteroid is heavier obj
1330                 mc.model_num = Asteroid_info[Asteroids[num].type].model_num[asteroid_subtype];          // Fill in the model to check
1331                 model_clear_instance( mc.model_num );
1332                 mc.orient = &pasteroid->orient;                         // The object's orient
1333                 mc.radius = model_get_core_radius( Ships[ship_obj->instance].modelnum );
1334
1335                 // check for collision between asteroid model and ship sphere
1336                 mc.flags = (MC_CHECK_MODEL | MC_CHECK_SPHERELINE);
1337
1338                 mc_ret_val = model_collide(&mc);
1339
1340                 if (mc_ret_val) {
1341                         set_hit_struct_info(asteroid_hit_info, &mc, SUBMODEL_NO_ROT_HIT);
1342
1343                         // set normal if not edge hit
1344                         if ( !asteroid_hit_info->edge_hit ) {
1345                                 vm_vec_unrotate(&asteroid_hit_info->collision_normal, &mc.hit_normal, &heavy->orient);
1346                         }
1347
1348                         // find position in submodel RF of light object at collison
1349                         vector diff;
1350                         vm_vec_sub(&diff, mc.p1, mc.p0);
1351                         vm_vec_scale_add(&asteroid_hit_info->light_collision_cm_pos, mc.p0, &diff, mc.hit_dist);
1352
1353                 }
1354         }
1355         
1356
1357         if ( mc_ret_val )       {
1358
1359                 // SET PHYSICS PARAMETERS
1360                 // already have (hitpos - heavy) and light_cm_pos
1361                 // get heavy cm pos - already have light_cm_pos
1362                 asteroid_hit_info->heavy_collision_cm_pos = zero;
1363
1364                 // get r_heavy and r_light
1365                 asteroid_hit_info->r_heavy = asteroid_hit_info->hit_pos;
1366                 vm_vec_sub(&asteroid_hit_info->r_light, &asteroid_hit_info->hit_pos, &asteroid_hit_info->light_collision_cm_pos);
1367
1368                 // set normal for edge hit
1369                 if ( asteroid_hit_info->edge_hit ) {
1370                         vm_vec_copy_normalize(&asteroid_hit_info->collision_normal, &asteroid_hit_info->r_light);
1371                         vm_vec_negate(&asteroid_hit_info->collision_normal);
1372                 }
1373
1374                 // get world hitpos
1375                 vm_vec_add(hitpos, &asteroid_hit_info->heavy->pos, &asteroid_hit_info->r_heavy);
1376
1377                 return 1;
1378         } else {
1379                 // no hit
1380                 return 0;
1381         }
1382 }
1383 #ifndef PLAT_UNIX
1384 #pragma warning ( pop )
1385 #endif
1386
1387
1388 void asteroid_render(object * obj)
1389 {
1390         if (Asteroids_enabled) {
1391                 int                     num;
1392                 polymodel       *pm;
1393                 asteroid                *asp;
1394
1395                 pm = NULL;      
1396                 num = obj->instance;
1397
1398                 Assert((num >= 0) && (num < MAX_ASTEROIDS));
1399                 asp = &Asteroids[num];
1400
1401                 Assert( asp->flags & AF_USED );
1402
1403                 model_clear_instance( Asteroid_info[asp->type].model_num[asp->asteroid_subtype]);
1404                 model_render(Asteroid_info[asp->type].model_num[asp->asteroid_subtype], &obj->orient, &obj->pos, MR_NORMAL|MR_IS_ASTEROID, OBJ_INDEX(obj) );    //      Replace MR_NORMAL with 0x07 for big yellow blobs
1405         }
1406 }
1407
1408 //      Create a normalized vector generally in the direction from *hitpos to other_obj->pos
1409 void asc_get_relvec(vector *relvec, object *other_obj, vector *hitpos)
1410 {
1411         vector  tvec, rand_vec;
1412         int             count = 0;
1413
1414         vm_vec_normalized_dir(&tvec, &other_obj->pos, hitpos);
1415
1416         //      Try up to three times to get a good vector.
1417         while (count++ < 3) {
1418                 vm_vec_rand_vec_quick(&rand_vec);
1419                 vm_vec_add(relvec, &tvec, &rand_vec);
1420                 float mag = vm_vec_mag_quick(relvec);
1421                 if ((mag > 0.2f) && (mag < 1.7f))
1422                         break;
1423         }
1424
1425         vm_vec_normalize_quick(relvec);
1426 }
1427
1428 // return multiplier on asteroid radius for fireball
1429 float asteroid_get_fireball_scale_multiplier(int num)
1430 {
1431         if (Asteroids[num].flags & AF_USED) {
1432
1433                 switch(Asteroids[num].type) {
1434                 case ASTEROID_TYPE_BIG:
1435                         return 1.5f;
1436                         break;
1437
1438                 default:
1439                         return 1.0f;
1440                         break;
1441                 }
1442         }
1443
1444         Int3(); // this should not happen.  asteroid should be used.
1445         return 1.0f;
1446 }
1447
1448
1449 // create asteroid explosion
1450 // exit: expected time for explosion anim to last, in seconds
1451 float asteroid_create_explosion(object *objp)
1452 {
1453         int     fireball_objnum;
1454         float   explosion_life, fireball_scale_multiplier;
1455
1456         fireball_scale_multiplier = asteroid_get_fireball_scale_multiplier(objp->instance);
1457
1458         fireball_objnum = fireball_create( &objp->pos, FIREBALL_ASTEROID, OBJ_INDEX(objp), objp->radius*fireball_scale_multiplier, 0, &objp->phys_info.vel );
1459         if ( fireball_objnum > -1 )     {
1460                 explosion_life = fireball_lifeleft(&Objects[fireball_objnum]);
1461         } else {
1462                 explosion_life = 0.0f;
1463         }
1464
1465         return explosion_life;
1466 }
1467
1468 // play sound when asteroid explodes
1469 void asteriod_explode_sound(object *objp, int type, int play_loud)
1470 {
1471         int     sound_index = -1;
1472         float range_factor = 1.0f;              // how many times sound should traver farther than normal
1473
1474         switch (type) {
1475         case ASTEROID_TYPE_SMALL:
1476         case ASTEROID_TYPE_MEDIUM:
1477         case DEBRIS_TERRAN_SMALL:
1478         case DEBRIS_TERRAN_MEDIUM:
1479         case DEBRIS_VASUDAN_SMALL:
1480         case DEBRIS_VASUDAN_MEDIUM:
1481         case DEBRIS_SHIVAN_SMALL:
1482         case DEBRIS_SHIVAN_MEDIUM:
1483                 sound_index = SND_ASTEROID_EXPLODE_SMALL;
1484                 range_factor = 5.0f;
1485                 break;
1486
1487         case ASTEROID_TYPE_BIG:
1488         case DEBRIS_TERRAN_LARGE:
1489         case DEBRIS_VASUDAN_LARGE:
1490         case DEBRIS_SHIVAN_LARGE:
1491                 sound_index = SND_ASTEROID_EXPLODE_BIG;
1492                 range_factor = 10.0f;
1493                 break;
1494
1495         default:
1496                 Int3();
1497                 return;
1498         }
1499
1500         Assert(sound_index != -1);
1501
1502         if ( !play_loud ) {
1503                 range_factor = 1.0f;
1504         }
1505
1506         snd_play_3d( &Snds[sound_index], &objp->pos, &Eye_position, objp->radius, NULL, 0, 1.0f, SND_PRIORITY_MUST_PLAY, NULL, range_factor );
1507 }
1508
1509 //      asteroid_do_area_effect()
1510 //
1511 // Do the area effect for an asteroid exploding
1512 //
1513 // input:       asteroid_objp   =>              object pointer to asteriod causing explosion
1514 void asteroid_do_area_effect(object *asteroid_objp)
1515 {
1516         object                  *ship_objp;
1517         float                           damage, blast;
1518         ship_obj                        *so;
1519         asteroid                        *asp;
1520         asteroid_info   *asip;
1521
1522         asp = &Asteroids[asteroid_objp->instance];
1523         asip = &Asteroid_info[asp->type];
1524
1525         if ( asip->damage <= 0 ) {              // do a quick out if there is no damage to apply
1526                 return;
1527         }
1528
1529         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
1530                 ship_objp = &Objects[so->objnum];
1531         
1532                 // don't blast navbuoys
1533                 if ( ship_get_SIF(ship_objp->instance) & SIF_NAVBUOY ) {
1534                         continue;
1535                 }
1536
1537                 if ( weapon_area_calc_damage(ship_objp, &asteroid_objp->pos, asip->inner_rad, asip->outer_rad, asip->blast, asip->damage, &blast, &damage, asip->outer_rad) == -1 )
1538                         continue;
1539
1540                 ship_apply_global_damage(ship_objp, asteroid_objp, &asteroid_objp->pos, damage );
1541                 weapon_area_apply_blast(NULL, ship_objp, &asteroid_objp->pos, blast, 0);
1542         }       // end for
1543 }
1544
1545 //      Asteroid asteroid_obj was hit.
1546 //      Apply damage.  Maybe make it break into smaller asteroids.
1547 // input:       asteroid_obj    =>              pointer to asteroid object getting hit
1548 //                              other_obj               =>              object that hit asteroid, can be NULL if asteroid hit by area effect
1549 //                              hitpos                  =>              world position asteroid was hit, can be NULL if hit by area effect
1550 //                              damage                  =>              amount of damage to apply to asteroid
1551 void asteroid_hit( object * asteroid_obj, object * other_obj, vector * hitpos, float damage )
1552 {
1553         float           explosion_life;
1554         asteroid        *asp;
1555
1556         asp = &Asteroids[asteroid_obj->instance];
1557
1558         if (asteroid_obj->flags & OF_SHOULD_BE_DEAD){
1559                 return;
1560         }
1561
1562         if ( MULTIPLAYER_MASTER ){
1563                 send_asteroid_hit( asteroid_obj, other_obj, hitpos, damage );
1564         }
1565
1566         asteroid_obj->hull_strength -= damage;
1567
1568         //nprintf(("AI", "Asteroid collided with %s, hull = %.2f\n", Object_type_names[other_obj->type], asteroid_obj->hull_strength));
1569
1570         if (asteroid_obj->hull_strength < 0.0f) {
1571                 if ( asp->final_death_time <= 0 ) {
1572                         int play_loud_collision = 0;
1573
1574                         explosion_life = asteroid_create_explosion(asteroid_obj);
1575                         if ( asp->collide_objnum == OBJ_INDEX(other_obj) ) {
1576 //                              play_loud_collision = 1;
1577                         }
1578                         asteriod_explode_sound(asteroid_obj, asp->type, play_loud_collision);
1579                         asteroid_do_area_effect(asteroid_obj);
1580
1581                         asp->final_death_time = timestamp( fl2i(explosion_life*1000.0f)/5 );    // Wait till 30% of vclip time before breaking the asteroid up.
1582                         if ( hitpos ) {
1583                                 asp->death_hit_pos = *hitpos;
1584                         } else {
1585                                 asp->death_hit_pos = asteroid_obj->pos;
1586                                 // randomize hit pos a bit, otherwise we will get a NULL vector when trying to find direction to toss child asteroids
1587                                 vector rand_vec;
1588                                 vm_vec_rand_vec_quick(&rand_vec);
1589                                 vm_vec_add2(&asp->death_hit_pos, &rand_vec);
1590                         }
1591                 }
1592         } else if ( other_obj ) {
1593                 if ( other_obj->type == OBJ_WEAPON ) {
1594                         weapon_info *wip;
1595                         wip = &Weapon_info[Weapons[other_obj->instance].weapon_info_index];
1596                         // If the weapon didn't play any impact animation, play custom asteroid impact animation
1597                         if ( wip->impact_weapon_expl_index < 0 ) {
1598                                 particle_create( hitpos, &vmd_zero_vector, 0.0f, Asteroid_impact_explosion_radius, PARTICLE_BITMAP, Asteroid_impact_explosion_ani );
1599                         }
1600                 }
1601         }
1602
1603         // evaluate any relevant player scoring implications
1604         scoring_eval_hit(asteroid_obj,other_obj);
1605 }
1606
1607 // De-init asteroids, called from game_level_close()
1608 void asteroid_level_close()
1609 {
1610         int     i;
1611
1612         for (i=0; i<MAX_ASTEROIDS; i++) {
1613                 if (Asteroids[i].flags & AF_USED) {
1614                         Asteroids[i].flags &= ~AF_USED;
1615                         Assert(Asteroids[i].objnum >=0 && Asteroids[i].objnum < MAX_OBJECTS);
1616                         Objects[Asteroids[i].objnum].flags |= OF_SHOULD_BE_DEAD;
1617                 }
1618         }
1619
1620         Asteroid_field.num_initial_asteroids=0;
1621 }
1622
1623 DCF(asteroids,"Turns asteroids on/off")
1624 {       
1625         if ( Dc_command )       {       
1626                 dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE);                
1627                 if ( Dc_arg_type & ARG_TRUE )   
1628                         Asteroids_enabled = 1;  
1629                 else if ( Dc_arg_type & ARG_FALSE ) 
1630                         Asteroids_enabled = 0;  
1631                 else if ( Dc_arg_type & ARG_NONE ) 
1632                         Asteroids_enabled ^= 1; 
1633         }       
1634         if ( Dc_help )  
1635                 dc_printf( "Usage: asteroids [bool]\nTurns asteroid system on/off.  If nothing passed, then toggles it.\n" );   
1636         
1637         if ( Dc_status )        
1638                 dc_printf( "asteroids are %s\n", (Asteroids_enabled?"ON":"OFF") );      
1639
1640 /*
1641         if ((old_asteroids_enabled == 0) && (Asteroids_enabled == 1)) {
1642                 asteroid_init();
1643         } else if ((old_asteroids_enabled == 1) && (Asteroids_enabled == 0)) {
1644                 asteroid_uninit();
1645         }
1646 */
1647 }
1648
1649 void hud_target_asteroid()
1650 {
1651         int     i;
1652         int     start_index = 0, end_index = MAX_ASTEROIDS;
1653
1654         if (Player_ai->target_objnum != -1) {
1655                 if (Objects[Player_ai->target_objnum].type == OBJ_ASTEROID) {
1656                         start_index = Objects[Player_ai->target_objnum].instance+1;
1657                         end_index = start_index-1;
1658                         if (end_index < 0)
1659                                 end_index = MAX_ASTEROIDS;
1660                 }
1661         }
1662
1663         i = start_index;
1664         while (i != end_index) {
1665                 if (i == MAX_ASTEROIDS)
1666                         i = 0;
1667
1668                 if (Asteroids[i].flags & AF_USED) {
1669                         Assert(Objects[Asteroids[i].objnum].type == OBJ_ASTEROID);
1670                         set_target_objnum( Player_ai, Asteroids[i].objnum);
1671                         break;
1672                 }
1673
1674                 i++;
1675         }
1676 }
1677
1678 // Return the number of active asteroids
1679 int asteroid_count()
1680 {
1681         return Num_asteroids;
1682 }
1683
1684 // See if asteroid should split up.  We delay splitting up to allow the explosion animation
1685 // to play for a bit.
1686 void asteroid_maybe_break_up(object *asteroid_obj)
1687 {
1688         asteroid *asp;
1689
1690         asp = &Asteroids[asteroid_obj->instance];
1691
1692         if ( timestamp_elapsed(asp->final_death_time) ) {
1693                 vector  relvec, vfh, tvec;
1694
1695                 asteroid_obj->flags |= OF_SHOULD_BE_DEAD;
1696
1697                 // multiplayer clients won't go through the following code.  asteroid_sub_create will send
1698                 // a create packet to the client in the above named function
1699                 if ( !MULTIPLAYER_CLIENT ) {
1700
1701                         switch (asp->type) {
1702                         case ASTEROID_TYPE_SMALL:
1703                                 break;
1704                         case ASTEROID_TYPE_MEDIUM:
1705                                 asc_get_relvec(&relvec, asteroid_obj, &asp->death_hit_pos);
1706                                 asteroid_sub_create(asteroid_obj, ASTEROID_TYPE_SMALL, &relvec);
1707                         
1708                                 vm_vec_normalized_dir(&vfh, &asteroid_obj->pos, &asp->death_hit_pos);
1709                                 vm_vec_copy_scale(&tvec, &vfh, 2.0f);
1710                                 vm_vec_sub2(&tvec, &relvec);
1711                                 asteroid_sub_create(asteroid_obj, ASTEROID_TYPE_SMALL, &tvec);
1712                                 
1713                                 break;
1714                         case ASTEROID_TYPE_BIG:
1715                                 asc_get_relvec(&relvec, asteroid_obj, &asp->death_hit_pos);
1716                                 asteroid_sub_create(asteroid_obj, ASTEROID_TYPE_MEDIUM, &relvec);
1717                         
1718                                 vm_vec_normalized_dir(&vfh, &asteroid_obj->pos, &asp->death_hit_pos);
1719                                 vm_vec_copy_scale(&tvec, &vfh, 2.0f);
1720                                 vm_vec_sub2(&tvec, &relvec);
1721                                 asteroid_sub_create(asteroid_obj, ASTEROID_TYPE_MEDIUM, &tvec);
1722
1723                                 while (frand() > 0.6f) {
1724                                         vector  rvec, tvec2;
1725                                         vm_vec_rand_vec_quick(&rvec);
1726                                         vm_vec_scale_add(&tvec2, &vfh, &rvec, 0.75f);
1727                                         asteroid_sub_create(asteroid_obj, ASTEROID_TYPE_SMALL, &tvec2);
1728                                 }
1729
1730                                 break;
1731
1732                         // ship debris does not break up
1733                         case    DEBRIS_TERRAN_SMALL:
1734                         case    DEBRIS_TERRAN_MEDIUM:
1735                         case    DEBRIS_TERRAN_LARGE:
1736                         case    DEBRIS_VASUDAN_SMALL:
1737                         case    DEBRIS_VASUDAN_MEDIUM:
1738                         case    DEBRIS_VASUDAN_LARGE:
1739                         case    DEBRIS_SHIVAN_SMALL:
1740                         case    DEBRIS_SHIVAN_MEDIUM:
1741                         case    DEBRIS_SHIVAN_LARGE:
1742                                 break;
1743
1744                         default:
1745                                 Int3();
1746                         }
1747                 }
1748
1749                 asp->final_death_time = timestamp(-1);
1750         }
1751 }
1752
1753 int asteroid_get_random_in_cone(vector *pos, vector *dir, float ang, int danger)
1754 {
1755         int idx;
1756         vector asteroid_dir;
1757
1758         // just pick the first asteroid which satisfies our condition
1759         for(idx=0; idx<Num_asteroids; idx++){
1760                 vm_vec_sub(&asteroid_dir, &Objects[Asteroids[idx].objnum].pos, pos);
1761                 vm_vec_normalize_quick(&asteroid_dir);
1762
1763                 // if it satisfies the condition
1764                 if(vm_vec_dot(dir, &asteroid_dir) >= ang){
1765                         return idx;
1766                 }
1767         }
1768
1769         return -1;
1770 }
1771
1772 void asteroid_test_collide(object *asteroid_obj, object *ship_obj, mc_info *mc)
1773 {
1774         float           asteroid_ray_dist;
1775         vector  asteroid_fvec, terminus;
1776
1777         // See if ray from asteroid intersects bounding box of escort ship
1778         asteroid_ray_dist = vm_vec_mag_quick(&asteroid_obj->phys_info.desired_vel) * ASTEROID_MIN_COLLIDE_TIME;
1779         asteroid_fvec = asteroid_obj->phys_info.desired_vel;    
1780
1781         if(IS_VEC_NULL(&asteroid_fvec)){
1782                 terminus = asteroid_obj->pos;
1783         } else {
1784                 vm_vec_normalize(&asteroid_fvec);
1785                 vm_vec_scale_add(&terminus, &asteroid_obj->pos, &asteroid_fvec, asteroid_ray_dist);
1786         }
1787
1788         Assert(ship_obj->type == OBJ_SHIP);
1789
1790         ship_model_start(ship_obj);
1791
1792         mc->model_num = Ships[ship_obj->instance].modelnum;                     // Fill in the model to check
1793         mc->orient = &ship_obj->orient;                                                                         // The object's orientation
1794         mc->pos = &ship_obj->pos;                                                                                               // The object's position
1795         mc->p0 = &asteroid_obj->pos;                                                                                    // Point 1 of ray to check
1796         mc->p1 = &terminus;                                                                                                             // Point 2 of ray to check
1797 //      mc->flags = MC_CHECK_MODEL | MC_ONLY_BOUND_BOX; 
1798         mc->flags = MC_CHECK_MODEL | MC_CHECK_SPHERELINE;       
1799         mc->radius = asteroid_obj->radius;
1800
1801         model_collide(mc);
1802
1803         ship_model_stop(ship_obj);
1804 }
1805
1806 // Return !0 is the asteroid will collide with the escort ship within ASTEROID_MIN_COLLIDE_TIME
1807 // seconds
1808 int asteroid_will_collide(object *asteroid_obj, object *escort_objp)
1809 {
1810         mc_info mc;
1811
1812         asteroid_test_collide(asteroid_obj, escort_objp, &mc);
1813
1814         if ( !mc.num_hits ) {
1815                 return 0;
1816         }       
1817
1818         return 1;
1819 }
1820
1821 // return !0 if we should warn about asteroid hitting ship, otherwise return 0
1822 int asteroid_valid_ship_to_warn_collide(ship *shipp)
1823 {
1824         if ( !(Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) ) {
1825                 return 0;
1826         }
1827
1828         if ( shipp->flags & (SF_DYING|SF_DEPART_WARP) ) {
1829                 return 0;
1830         }
1831
1832         if ( (shipp->team != Player_ship->team) || (Player_ship->team == TEAM_TRAITOR) ) {
1833                 return 0;
1834         }
1835
1836         return 1;
1837 }
1838
1839 // See if asteroid will collide with a large ship on the escort list in the next
1840 // ASTEROID_MIN_COLLIDE_TIME seconds.
1841 void asteroid_update_collide_flag(object *asteroid_objp)
1842 {
1843         int             i, num_escorts, escort_objnum, will_collide=0;
1844         ship            *escort_shipp;
1845         asteroid        *asp;
1846
1847         asp = &Asteroids[asteroid_objp->instance];
1848         asp->collide_objnum = -1;
1849         asp->collide_objsig = -1;
1850
1851         // multiplayer dogfight
1852         if((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_DOGFIGHT)){
1853                 return;
1854         }
1855
1856         num_escorts = hud_escort_num_ships_on_list();
1857
1858         if ( num_escorts <= 0 ) {
1859                 return;
1860         }
1861
1862         for ( i = 0; i < num_escorts; i++ ) {
1863                 escort_objnum = hud_escort_return_objnum(i);
1864                 if ( escort_objnum >= 0 ) {
1865                         escort_shipp = &Ships[Objects[escort_objnum].instance];
1866                         if ( asteroid_valid_ship_to_warn_collide(escort_shipp) ) {
1867                                 will_collide = asteroid_will_collide(asteroid_objp, &Objects[escort_objnum]);
1868                                 if ( will_collide ) {
1869                                         asp->collide_objnum = escort_objnum;
1870                                         asp->collide_objsig = Objects[escort_objnum].signature;
1871                                 }
1872                         }
1873                 }
1874         }
1875 }
1876
1877 // ensure that the collide objnum for the asteroid is still valid
1878 void asteroid_verify_collide_objnum(asteroid *asp)
1879 {
1880         if ( asp->collide_objnum >= 0 ) {
1881                 if ( Objects[asp->collide_objnum].signature != asp->collide_objsig ) {
1882                         asp->collide_objnum = -1;
1883                         asp->collide_objsig = -1;
1884                 }
1885         }
1886 }
1887
1888 void asteroid_process_post(object * obj, float frame_time)
1889 {
1890         if (Asteroids_enabled) {
1891                 int num;
1892                 num = obj->instance;
1893                 
1894                 //Assert( Asteroids[num].objnum == objnum );
1895                 asteroid        *asp = &Asteroids[num];
1896
1897                 // Only wrap if active field
1898                 if (Asteroid_field.field_type == FT_ACTIVE) {
1899                         if ( timestamp_elapsed(asp->check_for_wrap) ) {
1900                                 asteroid_maybe_reposition(obj, &Asteroid_field);
1901                                 asp->check_for_wrap = timestamp(ASTEROID_CHECK_WRAP_TIMESTAMP);
1902                         }
1903                 }
1904
1905                 asteroid_verify_collide_objnum(asp);
1906
1907                 if ( timestamp_elapsed(asp->check_for_collide) ) {
1908                         asteroid_update_collide_flag(obj);
1909                         asp->check_for_collide = timestamp(ASTEROID_UPDATE_COLLIDE_TIMESTAMP);
1910                 }
1911
1912                 asteroid_maybe_break_up(obj);
1913         }
1914 }
1915
1916 // return the object number that the asteroid is about to impact
1917 int asteroid_collide_objnum(object *asteroid_objp)
1918 {
1919         return Asteroids[asteroid_objp->instance].collide_objnum;
1920 }
1921
1922 // return the time until the asteroid will impact its collide_objnum
1923 float asteroid_time_to_impact(object *asteroid_objp)
1924 {
1925         float           time=-1.0f, total_dist, speed;
1926         asteroid        *asp;
1927         mc_info mc;
1928
1929         asp = &Asteroids[asteroid_objp->instance];
1930
1931         if ( asp->collide_objnum < 0 ) {
1932                 return time;
1933         }
1934         
1935         asteroid_test_collide(asteroid_objp, &Objects[asp->collide_objnum], &mc);
1936
1937         if ( mc.num_hits ) {
1938                 total_dist = vm_vec_dist(&mc.hit_point_world, &asteroid_objp->pos) - asteroid_objp->radius;
1939                 if ( total_dist < 0 ) {
1940                         total_dist = 0.0f;
1941                 }
1942                 speed = vm_vec_mag(&asteroid_objp->phys_info.vel);
1943                 time = total_dist/speed;
1944         }       
1945
1946         return time;
1947 }
1948
1949 // read in a single asteroid section from asteroid.tbl
1950 void asteroid_parse_section()
1951 {
1952         asteroid_info   *asip;
1953         
1954         asip = &Asteroid_info[Num_asteroid_types];
1955
1956         required_string("$Name:");
1957         stuff_string(asip->name, F_NAME, NULL);
1958
1959         required_string( "$POF file1:" );
1960         stuff_string_white( asip->pof_files[0] );
1961
1962         required_string( "$POF file2:" );
1963         stuff_string_white( asip->pof_files[1] );
1964
1965         if ( (strstr(asip->name,"Asteroid") != NULL) || (strstr(asip->name, "asteroid") != NULL) ) {
1966                 required_string( "$POF file3:" );
1967                 stuff_string_white( asip->pof_files[2] );
1968         }
1969
1970         asip->num_detail_levels = 0;
1971
1972         required_string("$Detail distance:");
1973         asip->num_detail_levels = stuff_int_list(asip->detail_distance, MAX_SHIP_DETAIL_LEVELS, RAW_INTEGER_TYPE);
1974
1975         required_string("$Max Speed:");
1976         stuff_float(&asip->max_speed);
1977
1978         required_string("$Expl inner rad:");
1979         stuff_float(&asip->inner_rad);
1980
1981         required_string("$Expl outer rad:");
1982         stuff_float(&asip->outer_rad);
1983
1984         required_string("$Expl damage:");
1985         stuff_float(&asip->damage);
1986
1987         required_string("$Expl blast:");
1988         stuff_float(&asip->blast);
1989
1990         required_string("$Hitpoints:");
1991         stuff_float(&asip->initial_hull_strength);
1992 }
1993
1994 // read in data from asteroid.tbl into Asteroid_info[] array
1995 void asteroid_parse_tbl()
1996 {
1997         char impact_ani_file[FILESPEC_LENGTH];
1998
1999         Num_asteroid_types = 0;
2000
2001         // open localization
2002         lcl_ext_open();
2003
2004         read_file_text("asteroid.tbl");
2005         reset_parse();
2006
2007         required_string("#Asteroid Types");
2008
2009         while (required_string_either("#End","$Name:")) {
2010                 Assert( Num_asteroid_types < MAX_DEBRIS_TYPES );
2011                 asteroid_parse_section();
2012                 Num_asteroid_types++;
2013         }
2014
2015         required_string("#End");
2016
2017         // check all read in
2018         Assert(Num_asteroid_types == MAX_DEBRIS_TYPES);
2019
2020         Asteroid_impact_explosion_ani = -1;
2021         required_string("$Impact Explosion:");
2022         stuff_string(impact_ani_file, F_NAME, NULL);
2023         if ( stricmp(impact_ani_file,NOX("none")))      {
2024                 int num_frames;
2025                 Asteroid_impact_explosion_ani = bm_load_animation( impact_ani_file, &num_frames, NULL, 1);
2026         }
2027
2028         required_string("$Impact Explosion Radius:");
2029         stuff_float(&Asteroid_impact_explosion_radius);
2030
2031         // close localization
2032         lcl_ext_close();
2033 }
2034
2035 //      Return number of asteroids expected to collide with a ship.
2036 int count_incident_asteroids()
2037 {
2038         object  *asteroid_objp;
2039         int             count;
2040
2041         count = 0;
2042
2043         for ( asteroid_objp = GET_FIRST(&obj_used_list); asteroid_objp !=END_OF_LIST(&obj_used_list); asteroid_objp = GET_NEXT(asteroid_objp) ) {
2044                 if (asteroid_objp->type == OBJ_ASTEROID ) {
2045                         asteroid *asp = &Asteroids[asteroid_objp->instance];
2046
2047                         if ( asp->target_objnum >= 0 ) {
2048                                 count++;
2049                         }
2050                 }
2051         }
2052
2053         return count;
2054 }
2055
2056 //      Pick object to throw asteroids at.
2057 //      Pick any capital or big ship inside the bounds of the asteroid field.
2058 int set_asteroid_throw_objnum()
2059 {
2060         if (Asteroid_field.num_initial_asteroids < 1)
2061                 return -1;
2062
2063         ship_obj        *so;
2064         object  *ship_objp;
2065
2066         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2067                 ship_objp = &Objects[so->objnum];
2068                 float           radius = ship_objp->radius*2.0f;
2069
2070                 if (Ship_info[Ships[ship_objp->instance].ship_info_index].flags & (SIF_HUGE_SHIP | SIF_BIG_SHIP)) {
2071                         if (ship_objp->pos.x + radius > Asteroid_field.min_bound.x)
2072                                 if (ship_objp->pos.y + radius > Asteroid_field.min_bound.y)
2073                                 if (ship_objp->pos.z + radius > Asteroid_field.min_bound.z)
2074                                 if (ship_objp->pos.x - radius < Asteroid_field.max_bound.x)
2075                                 if (ship_objp->pos.y - radius < Asteroid_field.max_bound.y)
2076                                 if (ship_objp->pos.z - radius < Asteroid_field.max_bound.z)
2077                                 if (!asteroid_in_inner_bound(&Asteroid_field, &ship_objp->pos, radius))
2078                                         return so->objnum;
2079                 }
2080         }
2081         return -1;
2082
2083 }
2084
2085 void asteroid_frame()
2086 {
2087         if (Num_asteroids < 1)
2088                 return;
2089
2090         // Only throw if active field
2091         if (Asteroid_field.field_type == FT_PASSIVE) {
2092                 return;
2093         }
2094
2095         Asteroid_throw_objnum = set_asteroid_throw_objnum();
2096
2097         maybe_throw_asteroid(count_incident_asteroids());
2098 }
2099
2100 // Called once, at game start.  Do any one-time initializations here
2101 void asteroid_init()
2102 {
2103         asteroid_parse_tbl();
2104 }
2105
2106 // Draw brackets around on-screen asteroids that are about to collide, otherwise draw an offscreen indicator
2107 void asteroid_show_brackets()
2108 {
2109         vertex  asteroid_vertex;
2110         object  *asteroid_objp, *player_target;
2111         asteroid        *asp;
2112
2113         // get pointer to player target, so we don't need to take OBJ_INDEX() of asteroid_objp to compare to target_objnum
2114         if ( Player_ai->target_objnum >= 0 ) {
2115                 player_target = &Objects[Player_ai->target_objnum];
2116         } else {
2117                 player_target = NULL;
2118         }
2119
2120         for ( asteroid_objp = GET_FIRST(&obj_used_list); asteroid_objp !=END_OF_LIST(&obj_used_list); asteroid_objp = GET_NEXT(asteroid_objp) ) {
2121                 if (asteroid_objp->type != OBJ_ASTEROID ) {
2122                         continue;
2123                 }
2124
2125                 asp = &Asteroids[asteroid_objp->instance];
2126
2127                 if ( asp->collide_objnum < 0 ) {
2128                         continue;
2129                 }
2130
2131                 if ( asteroid_objp == player_target ) {
2132                         continue;
2133                 }
2134
2135                 g3_rotate_vertex(&asteroid_vertex,&asteroid_objp->pos);
2136                 g3_project_vertex(&asteroid_vertex);
2137
2138                 if (!(asteroid_vertex.flags & PF_OVERFLOW)) {
2139                         gr_set_color_fast(&IFF_colors[IFF_COLOR_SELECTION][1]);
2140                         hud_show_brackets(asteroid_objp, &asteroid_vertex);
2141                 }
2142
2143                 // if asteroid is not on screen, draw an offscreen indicator
2144                 if ( hud_gauge_active(HUD_OFFSCREEN_INDICATOR) ) {
2145                         if (asteroid_vertex.codes != 0) {
2146                                 float dist;
2147 //                              dist = vm_vec_dist_quick(&Player_obj->pos, &asteroid_objp->pos);
2148                                 dist = hud_find_target_distance( asteroid_objp, Player_obj );
2149                                 gr_set_color_fast(&IFF_colors[IFF_COLOR_SELECTION][1]);
2150                                 hud_draw_offscreen_indicator(&asteroid_vertex, &asteroid_objp->pos, dist);
2151                         }
2152                 }
2153         }
2154 }
2155
2156 // target the closest danger asteroid to the player
2157 void asteroid_target_closest_danger()
2158 {
2159         object  *asteroid_objp, *closest_asteroid_objp = NULL;
2160         asteroid        *asp;
2161         float           dist, closest_dist = 999999.0f;
2162
2163         for ( asteroid_objp = GET_FIRST(&obj_used_list); asteroid_objp !=END_OF_LIST(&obj_used_list); asteroid_objp = GET_NEXT(asteroid_objp) ) {
2164                 if (asteroid_objp->type != OBJ_ASTEROID ) {
2165                         continue;
2166                 }
2167
2168                 asp = &Asteroids[asteroid_objp->instance];
2169
2170                 if ( asp->collide_objnum < 0 ) {
2171                         continue;
2172                 }
2173
2174                 dist = vm_vec_dist_quick(&Player_obj->pos, &asteroid_objp->pos);
2175
2176                 if ( dist < closest_dist ) {
2177                         closest_dist = dist;
2178                         closest_asteroid_objp = asteroid_objp;
2179                 }
2180         }
2181
2182         if ( closest_asteroid_objp ) {
2183                 set_target_objnum( Player_ai, OBJ_INDEX(closest_asteroid_objp) );
2184         }
2185 }
2186
2187 void asteroid_page_in()
2188 {
2189         if (Asteroid_field.num_initial_asteroids > 0 ) {
2190                 int i, j, k;
2191
2192                 nprintf(( "Paging", "Paging in asteroids\n" ));
2193
2194
2195                 // max of 3 possible debris field models
2196                 for (i=0; i<3; i++) {
2197                         asteroid_info   *asip;
2198
2199                         if (Asteroid_field.debris_genre == DG_ASTEROID) {
2200                                 // asteroid
2201                                 asip = &Asteroid_info[i];
2202                         } else {
2203                                 // ship debris - always full until empty
2204                                 if (Asteroid_field.field_debris_type[i] != -1) {
2205                                         asip = &Asteroid_info[Asteroid_field.field_debris_type[i]];
2206                                 } else {
2207                                         break;
2208                                 }
2209                         }
2210
2211
2212                         for (k=0; k<3; k++) {
2213
2214                                 // SHIP DEBRIS - use subtype 0
2215                                 if (Asteroid_field.debris_genre == DG_SHIP) {
2216                                         if (k > 0) {
2217                                                 break;
2218                                         }
2219                                 } else {
2220                                         // ASTEROID DEBRIS - use subtype (Asteroid_field.field_debris_type[] != -1)
2221                                         if (Asteroid_field.field_debris_type[k] == -1) {
2222                                                 continue;
2223                                         }
2224                                 }
2225                                 
2226                                 asip->modelp[k] = model_get(asip->model_num[k]);
2227
2228                                 // Page in textures
2229                                 for (j=0; j<asip->modelp[k]->n_textures; j++ )  {
2230                                         int bitmap_num = asip->modelp[k]->original_textures[j];
2231
2232
2233                                         // if we're in Glide (and maybe later with D3D), use nondarkening textures
2234                                         if ( bitmap_num > -1 )  {
2235                                                 if(gr_screen.mode == GR_GLIDE){
2236                                                         bm_page_in_nondarkening_texture( bitmap_num );
2237                                                 } else {
2238                                                         bm_page_in_texture( bitmap_num );
2239                                                 }                               
2240                                         }                                       
2241                                 }
2242
2243                         }
2244                 } 
2245         }
2246 }
2247
2248 #else
2249
2250 // stubbed out functions not used in the demo
2251 void    asteroid_init() {}
2252 void    asteroid_level_init() {}
2253 void    asteroid_level_close() {}
2254 void    asteroid_create_all() {}
2255 void    asteroid_render( object *asteroid_objp ) {}
2256 void    asteroid_delete( object *asteroid_objp ) {}
2257 void    asteroid_process_pre( object *asteroid_objp, float frame_time) {}
2258 void    asteroid_process_post( object *asteroid_objp, float frame_time) {}
2259 int     asteroid_check_collision( object *asteroid_objp, object * other_obj, vector * hitpos, collision_info_struct *asteroid_hit_info ) {return 0;}
2260 void    asteroid_hit( object *asteroid_objp, object *other_objp, vector *hitpos, float damage ) {}
2261 void    asteroid_save_restore(CFILE *fp) {}
2262 int     asteroid_count() {return 0;}
2263 int     asteroid_collide_objnum(object *asteroid_objp) {return 0;}
2264 float asteroid_time_to_impact(object *asteroid_objp) {return 0.0f;}
2265 void    asteroid_show_brackets() {}
2266 void    asteroid_target_closest_danger() {}
2267 void    asteroid_page_in() {}
2268 void    asteroid_sub_create(object *parent_objp, int asteroid_type, vector *relvec) {}
2269 void    asteroid_frame() {}
2270
2271
2272 #endif
2273