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