]> icculus.org git repositories - taylor/freespace2.git/blob - src/ship/shipfx.cpp
changes to screen backup/mouse drawing code. removed a few warnings.
[taylor/freespace2.git] / src / ship / shipfx.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Ship/ShipFX.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Routines for ship effects (as in special)
16  *
17  * $Log$
18  * Revision 1.5  2002/09/04 01:12:11  relnev
19  * changes to screen backup/mouse drawing code.  removed a few warnings.
20  *
21  * Revision 1.4  2002/06/17 06:33:11  relnev
22  * ryan's struct patch for gcc 2.95
23  *
24  * Revision 1.3  2002/06/09 04:41:26  relnev
25  * added copyright header
26  *
27  * Revision 1.2  2002/05/07 03:16:52  theoddone33
28  * The Great Newline Fix
29  *
30  * Revision 1.1.1.1  2002/05/03 03:28:10  root
31  * Initial import.
32  *
33  * 
34  * 51    9/13/99 4:53p Andsager
35  * 
36  * 50    9/13/99 10:09a Andsager
37  * Add debug console commands to lower model render detail and fireball
38  * LOD for big ship explosiosns.
39  * 
40  * 49    9/08/99 10:44p Andsager
41  * Make HUGE ships not die when warping out, after warp effect started.
42  * 
43  * 48    9/06/99 10:16p Andsager
44  * Modify big ship explosions.  Less frequent fireballs, fewer particles,
45  * larger fireballs
46  * 
47  * 47    9/05/99 11:10a Andsager
48  * Fix up which split ship get debris pieces.  Dont render debris pieces
49  * for split ships until they are near clip plane.
50  * 
51  * 46    9/02/99 12:55a Mikek
52  * Scale engine wash by speed.
53  * 
54  * 45    9/01/99 10:15a Dave
55  * 
56  * 44    8/31/99 10:13p Andsager
57  * Add Knossos warp effect fireball
58  * 
59  * 43    8/23/99 11:09a Andsager
60  * Round 2 of Knossos explosion
61  * 
62  * 42    8/20/99 2:16p Andsager
63  * Make only supercaps slow down extra fast after warping in.
64  * 
65  * 41    8/20/99 1:42p Andsager
66  * Frist pass on Knossos explosion.
67  * 
68  * 40    8/19/99 4:36p Andsager
69  * Cleaned up special_warpout
70  * 
71  * 39    8/16/99 10:04p Andsager
72  * Add special-warp-dist and special-warpout-name sexp for Knossos device
73  * warpout.
74  * 
75  * 38    8/16/99 2:01p Andsager
76  * Knossos warp-in warp-out.
77  * 
78  * 37    8/13/99 10:49a Andsager
79  * Knossos and HUGE ship warp out.  HUGE ship warp in.  Stealth search
80  * modes dont collide big ships.
81  * 
82  * 36    8/05/99 2:06a Dave
83  * Whee.
84  * 
85  * 35    7/18/99 12:32p Dave
86  * Randomly oriented shockwaves.
87  * 
88  * 34    7/09/99 12:52a Andsager
89  * Modify engine wash (1) less damage (2) only at a closer range (3) no
90  * damage when engine is disabled
91  * 
92  * 33    7/06/99 10:45a Andsager
93  * Modify engine wash to work on any ship that is not small.  Add AWACS
94  * ask for help.
95  * 
96  * 32    7/02/99 9:55p Dave
97  * Player engine wash sound.
98  * 
99  * 31    7/02/99 4:31p Dave
100  * Much more sophisticated lightning support.
101  * 
102  * 30    7/01/99 4:23p Dave
103  * Full support for multiple linked ambient engine sounds. Added "big
104  * damage" flag.
105  * 
106  * 29    7/01/99 11:44a Dave
107  * Updated object sound system to allow multiple obj sounds per ship.
108  * Added hit-by-beam sound. Added killed by beam sound.
109  * 
110  * 28    6/17/99 12:06p Andsager
111  * Add a fireball for each live debris piece.
112  * 
113  * 27    6/14/99 3:21p Andsager
114  * Allow collisions between ship and its debris.  Fix up collision pairs
115  * when large ship is warping out.
116  * 
117  * 26    5/27/99 12:14p Andsager
118  * Some fixes for live debris when more than one subsys on ship with live
119  * debris.  Set subsys strength (when 0) blows off subsystem.
120  * sexp_hits_left_subsystem works for SUBSYSTEM_UNKNOWN.
121  * 
122  * 25    5/26/99 11:46a Dave
123  * Added ship-blasting lighting and made the randomization of lighting
124  * much more customizable.
125  * 
126  * 24    5/25/99 10:05a Andsager
127  * Fix assert with wing warping out with no warp effect.
128  * 
129  * 23    5/24/99 5:45p Dave
130  * Added detail levels to the nebula, with a decent speedup. Split nebula
131  * lightning into its own section.
132  * 
133  * 22    5/21/99 5:03p Andsager
134  * Add code to display engine wash death.  Modify ship_kill_packet
135  * 
136  * 21    5/19/99 11:09a Andsager
137  * Turn on engine wash.  Check every 1/4 sec.
138  * 
139  * 20    5/18/99 1:30p Dave
140  * Added muzzle flash table stuff.
141  * 
142  * 19    5/17/99 10:33a Dave
143  * Fixed warning.
144  * 
145  * 18    5/11/99 10:16p Andsager
146  * First pass on engine wash effect.  Rotation (control input), damage,
147  * shake.  
148  * 
149  * 17    5/09/99 6:00p Dave
150  * Lots of cool new effects. E3 build tweaks.
151  * 
152  * 16    4/28/99 11:13p Dave
153  * Temporary checkin of artillery code.
154  * 
155  * 15    3/29/99 6:17p Dave
156  * More work on demo system. Got just about everything in except for
157  * blowing ships up, secondary weapons and player death/warpout.
158  * 
159  * 14    3/28/99 5:58p Dave
160  * Added early demo code. Make objects move. Nice and framerate
161  * independant, but not much else. Don't use yet unless you're me :)
162  * 
163  * 13    3/23/99 2:29p Andsager
164  * Fix shockwaves for kamikazi and Fred defined.  Collect together
165  * shockwave_create_info struct.
166  * 
167  * 12    3/20/99 3:03p Andsager
168  * Fix get_model_cross_section_at_z() from getting invalid index .
169  * 
170  * 11    3/19/99 9:51a Dave
171  * Checkin to repair massive source safe crash. Also added support for
172  * pof-style nebulae, and some new weapons code.
173  * 
174  * 10    2/26/99 4:14p Dave
175  * Put in the ability to have multiple shockwaves for ships.
176  * 
177  * 9     1/29/99 12:47a Dave
178  * Put in sounds for beam weapon. A bunch of interface screens (tech
179  * database stuff).
180  * 
181  * 8     1/28/99 9:10a Andsager
182  * Particles increased in width, life, number.  Max particles increased
183  * 
184  * 7     1/27/99 9:56a Dave
185  * Temporary checkin of beam weapons for Dan to make cool sounds.
186  * 
187  * 6     1/11/99 12:42p Andsager
188  * Add live debris - debris which is created from a destroyed subsystem,
189  * when the ship is still alive
190  * 
191  * 5     11/18/98 10:29a Johnson
192  * fix assert in shipfx_remove_submodel_ship_sparks.  submodel may not
193  * have spark and be destroyed.
194  * 
195  * 4     11/17/98 4:27p Andsager
196  * Stop sparks from emitting from destroyed subobjects
197  * 
198  * 3     10/20/98 1:39p Andsager
199  * Make so sparks follow animated ship submodels.  Modify
200  * ship_weapon_do_hit_stuff() and ship_apply_local_damage() to add
201  * submodel_num.  Add submodel_num to multiplayer hit packet.
202  * 
203  * 2     10/07/98 10:53a Dave
204  * Initial checkin.
205  * 
206  * 1     10/07/98 10:51a Dave
207  * 
208  *
209  * $NoKeywords: $
210  */
211
212 #include "pstypes.h"
213 #include "systemvars.h"
214 #include "ship.h"
215 #include "fireballs.h"
216 #include "debris.h"
217 #include "hudtarget.h"
218 #include "shipfx.h"
219 #include "multi.h"
220 #include "gamesnd.h"
221 #include "timer.h"
222 #include "3d.h"                 // needed for View_position, which is used when playing a 3D sound
223 #include "multi.h"
224 #include "multiutil.h"
225 #include "hud.h"
226 #include "fvi.h"
227 #include "gamesequence.h"
228 #include "lighting.h"
229 #include "linklist.h"
230 #include "particle.h"
231 #include "multimsgs.h"
232 #include "multiutil.h"
233 #include "bmpman.h"
234 #include "freespace.h"
235 #include "muzzleflash.h"
236 #include "demo.h"
237 #include "shiphit.h"
238 #include "neblightning.h"
239 #include "objectsnd.h"
240
241 #ifndef NDEBUG
242 extern float flFrametime;
243 extern int Framecount;
244 #endif
245
246 #define SHIP_CANNON_BITMAP                      "argh"
247 int Ship_cannon_bitmap = -1;
248
249 int Player_engine_wash_loop = -1;
250
251 void shipfx_remove_submodel_ship_sparks(ship *shipp, int submodel_num)
252 {
253         Assert(submodel_num != -1);
254
255         // maybe no active sparks on submodel
256         if (shipp->num_hits == 0) {
257                 return;
258         }
259         
260         for (int spark_num=0; spark_num<shipp->num_hits; spark_num++) {
261                 if (shipp->sparks[spark_num].submodel_num == submodel_num) {
262                         shipp->sparks[spark_num].end_time = timestamp(1);
263                 }
264         }
265 }
266
267 // Check if subsystem has live debris and create
268 // DKA: 5/26/99 make velocity of debris scale according to size of debris subobject (at least for large subobjects)
269 void shipfx_subsystem_mabye_create_live_debris(object *ship_obj, ship *ship_p, ship_subsys *subsys, vector *exp_center, float exp_mag)
270 {
271         // initializations
272         polymodel *pm = model_get(ship_p->modelnum);
273         int submodel_num = subsys->system_info->subobj_num;
274         submodel_instance_info *sii = &subsys->submodel_info_1;
275
276         object *live_debris_obj;
277         int i, num_live_debris, live_debris_submodel;
278
279         // get number of live debris objects to create
280         num_live_debris = pm->submodel[submodel_num].num_live_debris;
281         if (num_live_debris <= 0) {
282                 return;
283         }
284
285         ship_model_start(ship_obj);
286
287         // copy angles
288         angles copy_angs = pm->submodel[submodel_num].angs;
289         angles zero_angs = {0.0f, 0.0f, 0.0f};
290
291         // make sure the axis point is set
292         if ( !sii->axis_set ) {
293                 model_init_submodel_axis_pt(sii, ship_p->modelnum, submodel_num);
294         }
295
296         // get the rotvel
297         vector model_axis, world_axis, rotvel, world_axis_pt;
298         void model_get_rotating_submodel_axis(vector *model_axis, vector *world_axis, int modelnum, int submodel_num, object *obj);
299         model_get_rotating_submodel_axis(&model_axis, &world_axis, ship_p->modelnum, submodel_num, ship_obj);
300         vm_vec_copy_scale(&rotvel, &world_axis, sii->cur_turn_rate);
301
302         model_find_world_point(&world_axis_pt, &sii->pt_on_axis, ship_p->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
303
304         matrix m_rot;   // rotation for debris orient about axis
305         vm_quaternion_rotate(&m_rot, vm_vec_mag((vector*)&sii->angs), &model_axis);
306
307
308         // create live debris pieces
309         for (i=0; i<num_live_debris; i++) {
310                 live_debris_submodel = pm->submodel[submodel_num].live_debris[i];
311                 vector start_world_pos, start_model_pos, end_world_pos;
312
313                 // get start world pos
314                 vm_vec_zero(&start_world_pos);
315                 model_find_world_point(&start_world_pos, &pm->submodel[live_debris_submodel].offset, ship_p->modelnum, live_debris_submodel, &ship_obj->orient, &ship_obj->pos );
316
317                 // convert to model coord of underlying submodel
318                 // set angle to zero
319                 pm->submodel[submodel_num].angs = zero_angs;
320                 world_find_model_point(&start_model_pos, &start_world_pos, pm, submodel_num, &ship_obj->orient, &ship_obj->pos);
321
322                 // rotate from submodel coord to world coords
323                 // reset angle to current angle
324                 pm->submodel[submodel_num].angs = copy_angs;
325                 model_find_world_point(&end_world_pos, &start_model_pos, ship_p->modelnum, submodel_num, &ship_obj->orient, &ship_obj->pos);
326
327                 // create fireball here.
328                 fireball_create(&end_world_pos, FIREBALL_EXPLOSION_MEDIUM, OBJ_INDEX(ship_obj), pm->submodel[live_debris_submodel].rad);
329
330                 // create debris
331                 live_debris_obj = debris_create(ship_obj, ship_p->modelnum, live_debris_submodel, &end_world_pos, exp_center, 1, exp_mag);
332
333                 // only do if debris is created
334                 if (live_debris_obj) {
335                         // get radial velocity of debris
336                         vector delta_x, radial_vel;
337                         vm_vec_sub(&delta_x, &end_world_pos, &world_axis_pt);
338                         vm_vec_crossprod(&radial_vel, &rotvel, &delta_x);
339
340                         if (Ship_info[ship_p->ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
341                                 // set velocity to cross center of knossos device
342                                 vector rand_vec, vec_to_center;
343
344                                 float vel_mag = vm_vec_mag_quick(&radial_vel) * 1.3f * (0.9f + 0.2f*frand());
345                                 vm_vec_normalized_dir(&vec_to_center, &world_axis_pt, &end_world_pos);
346                                 vm_vec_rand_vec_quick(&rand_vec);
347                                 vm_vec_scale_add2(&vec_to_center, &rand_vec, 0.2f);
348                                 vm_vec_scale_add2(&live_debris_obj->phys_info.vel, &vec_to_center, vel_mag);
349
350                         } else {
351                                 // Get rotation of debris object
352                                 matrix copy = live_debris_obj->orient;
353                                 vm_matrix_x_matrix(&live_debris_obj->orient, &copy, &m_rot);
354
355                                 // Add radial velocity (at least as large as exp velocity)
356                                 vector temp_vel;        // explosion velocity with ship_obj velocity removed
357                                 vm_vec_sub(&temp_vel, &live_debris_obj->phys_info.vel, &ship_obj->phys_info.vel);
358
359                                 // find magnitudes of radial and temp velocity
360                                 float vel_mag = vm_vec_mag(&temp_vel);
361                                 float rotvel_mag = vm_vec_mag(&radial_vel);
362
363                                 if (rotvel_mag > 0.1) {
364                                         float scale = (1.2f + 0.2f * frand()) * vel_mag / rotvel_mag;
365                                         // always add *at least* rotvel
366                                         if (scale < 1) {
367                                                 scale = 1.0f;
368                                         }
369
370                                         if (exp_mag > 1) {      // whole ship going down
371                                                 scale = exp_mag;
372                                         }
373
374                                         if (Ship_info[ship_p->ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
375                                                 scale = 1.0f;
376                                         }
377
378                                         vm_vec_scale_add2(&live_debris_obj->phys_info.vel, &radial_vel, scale);
379                                 }
380
381                                 // scale up speed of debris if ship_obj > 125, but not for knossos
382                                 if (ship_obj->radius > 250 && !(Ship_info[ship_p->ship_info_index].flags & SIF_KNOSSOS_DEVICE)) {
383                                         vm_vec_scale(&live_debris_obj->phys_info.vel, ship_obj->radius/250.0f);
384                                 }
385                         }
386                 }
387         }
388
389         ship_model_stop(ship_obj);
390 }
391
392 void set_ship_submodel_as_blown_off(ship *shipp, char *name)
393 {
394         int found =     FALSE;
395
396         // go through list of ship subsystems and find name
397         ship_subsys     *pss = NULL;
398         for (pss=GET_FIRST(&shipp->subsys_list); pss!=END_OF_LIST(&shipp->subsys_list); pss=GET_NEXT(pss)) {
399                 if ( stricmp(pss->system_info->name, name) == 0) {
400                         found = TRUE;
401                         break;
402                 }
403         }
404
405         // set its blown off flag to TRUE
406         Assert(found);
407         if (found) {
408                 pss->submodel_info_1.blown_off = 1;
409         }
410 }
411
412
413 // Create debris for ship submodel which has live debris (at ship death)
414 // when ship submodel has not already been blown off (and hence liberated live debris)
415 void shipfx_maybe_create_live_debris_at_ship_death( object *ship_obj )
416 {
417         // if ship has live debris, detonate that subsystem now
418         // search for any live debris
419
420         ship *shipp = &Ships[ship_obj->instance];
421         polymodel *pm = model_get(shipp->modelnum);
422
423         int live_debris_submodel = -1;
424         for (int idx=0; idx<pm->num_debris_objects; idx++) {
425                 if (pm->submodel[pm->debris_objects[idx]].is_live_debris) {
426                         live_debris_submodel = pm->debris_objects[idx];
427
428                         // get submodel that produces live debris
429                         int model_get_parent_submodel_for_live_debris( int model_num, int live_debris_model_num );
430                         int parent = model_get_parent_submodel_for_live_debris( shipp->modelnum, live_debris_submodel);
431                         Assert(parent != -1);
432
433                         // set model values only once (esp blown off)
434                         ship_model_start(ship_obj);
435
436                         // check if already blown off  (ship model set)
437                         if ( !pm->submodel[parent].blown_off ) {
438                 
439                                 // get ship_subsys for live_debris
440                                 // Go through all subsystems and look for submodel the subsystems with "parent" submodel.
441                                 ship_subsys     *pss = NULL;
442                                 for ( pss = GET_FIRST(&shipp->subsys_list); pss != END_OF_LIST(&shipp->subsys_list); pss = GET_NEXT(pss) ) {
443                                         if (pss->system_info->subobj_num == parent) {
444                                                 break;
445                                         }
446                                 }
447
448                                 Assert (pss != NULL);
449                                 if (pss != NULL) {
450                                         vector exp_center, tmp = {0.0f, 0.0f, 0.0f};
451                                         model_find_world_point(&exp_center, &tmp, shipp->modelnum, parent, &ship_obj->orient, &ship_obj->pos );
452
453                                         // if not blown off, blow it off
454                                         shipfx_subsystem_mabye_create_live_debris(ship_obj, shipp, pss, &exp_center, 3.0f);
455
456                                         // now set subsystem as blown off, so we only get one copy
457                                         pm->submodel[parent].blown_off = 1;
458                                         set_ship_submodel_as_blown_off(&Ships[ship_obj->instance], pss->system_info->name);
459                                 }
460                         }
461                 }
462         }
463
464         // clean up
465         ship_model_stop(ship_obj);
466
467 }
468
469 void shipfx_blow_off_subsystem(object *ship_obj,ship *ship_p,ship_subsys *subsys, vector *exp_center)
470 {
471         vector subobj_pos;
472
473         model_subsystem *psub = subsys->system_info;
474
475         get_subsystem_world_pos(ship_obj, subsys, &subobj_pos);
476
477 /*
478         if ( psub->turret_gun_sobj > -1 )
479                 debris_create( ship_obj, ship_p->modelnum, psub->turret_gun_sobj, &subobj_pos, exp_center, 0, 1.0f );
480
481         if ( psub->subobj_num > -1 )
482                 debris_create( ship_obj, ship_p->modelnum, psub->subobj_num, &subobj_pos, exp_center, 0, 1.0f );
483 */
484         // get rid of sparks on submodel that is destroyed
485         shipfx_remove_submodel_ship_sparks(ship_p, psub->subobj_num);
486
487         // create debris shards
488         shipfx_blow_up_model(ship_obj, ship_p->modelnum, psub->subobj_num, 50, &subobj_pos );
489
490         // create live debris objects, if any
491         // TODO:  some MULITPLAYER implcations here!!
492         shipfx_subsystem_mabye_create_live_debris(ship_obj, ship_p, subsys, exp_center, 1.0f);
493
494         // create first fireball
495         fireball_create( &subobj_pos, FIREBALL_EXPLOSION_MEDIUM, OBJ_INDEX(ship_obj), psub->radius );
496 }
497
498
499 void shipfx_blow_up_hull(object *obj, int model, vector *exp_center)
500 {
501         int i;
502         polymodel * pm;
503         ushort sig_save;
504
505
506         pm = model_get(model);
507         if (!pm) return;
508
509         // in multiplayer, send a debris_hull_create packet.  Save/restore the debris signature
510         // when in misison only (since we can create debris pieces before mission starts)
511         sig_save = 0;
512         if ( (Game_mode & GM_MULTIPLAYER) && (Game_mode & GM_IN_MISSION) ) {
513                 sig_save = multi_get_next_network_signature( MULTI_SIG_DEBRIS );
514                 multi_set_network_signature( (ushort)(Ships[obj->instance].arrival_distance), MULTI_SIG_DEBRIS );
515         }
516
517         bool try_live_debris = true;
518         for (i=0; i<pm->num_debris_objects; i++ )       {
519                 if (! pm->submodel[pm->debris_objects[i]].is_live_debris) {
520                         vector tmp = {0.0f, 0.0f, 0.0f };               
521                         model_find_world_point(&tmp, &pm->submodel[pm->debris_objects[i]].offset, model, 0, &obj->orient, &obj->pos );
522                         debris_create( obj, model, pm->debris_objects[i], &tmp, exp_center, 1, 3.0f );
523                 } else {
524                         if ( try_live_debris ) {
525                                 // only create live debris once
526                                 // this creates *all* the live debris for *all* the currently live subsystems.
527                                 try_live_debris = false;
528                                 shipfx_maybe_create_live_debris_at_ship_death(obj);
529                         }
530                 }
531         }
532
533         // restore the ship signature to it's original value.
534         if ( (Game_mode & GM_MULTIPLAYER) && (Game_mode & GM_IN_MISSION) ) {
535                 multi_set_network_signature( sig_save, MULTI_SIG_DEBRIS );
536         }
537 }
538
539
540 // Creates "ndebris" pieces of debris on random verts of the the "submodel" in the 
541 // ship's model.
542 void shipfx_blow_up_model(object *obj,int model, int submodel, int ndebris, vector *exp_center )
543 {
544         int i;
545
546         // if in a multiplayer game -- seed the random number generator with a value that will be the same
547         // on all clients in the game -- the net_signature of the object works nicely -- since doing so should
548         // ensure that all pieces of debris will get scattered in same direction on all machines
549         if ( Game_mode & GM_MULTIPLAYER )
550                 srand( obj->net_signature );
551
552         // made a change to allow anyone but multiplayer client to blow up hull.  Clients will do it when
553         // they get the create packet
554         if ( submodel == 0 ) {
555                 shipfx_blow_up_hull(obj,model, exp_center );
556         }
557
558         for (i=0; i<ndebris; i++ )      {
559                 vector pnt1, pnt2;
560
561                 // Gets two random points on the surface of a submodel
562                 submodel_get_two_random_points(model, submodel, &pnt1, &pnt2 );
563
564                 vector tmp, outpnt;
565
566                 vm_vec_avg( &tmp, &pnt1, &pnt2 );
567                 model_find_world_point(&outpnt, &tmp, model,submodel, &obj->orient, &obj->pos );
568
569                 debris_create( obj, -1, -1, &outpnt, exp_center, 0, 1.0f );
570         }
571 }
572
573
574 // =================================================
575 //          SHIP WARP IN EFFECT CODE
576 // =================================================
577
578
579 // Given an ship, find the radius of it as viewed from the front.
580 static float shipfx_calculate_effect_radius( object *objp )
581 {
582         float w,h,rad;
583         ship *shipp = &Ships[objp->instance];
584
585         polymodel *pm = model_get( shipp->modelnum );
586
587         w = pm->maxs.xyz.x - pm->mins.xyz.x;
588         h = pm->maxs.xyz.y - pm->mins.xyz.y;
589         
590         if ( w > h )    {
591                 rad = w / 2.0f;
592         } else {
593                 rad = h / 2.0f;
594         }
595
596         object *docked_objp = ai_find_docked_object( objp );
597
598         //      If ship is docked then center wormhold about their center and make radius large enough.
599         if ( docked_objp ) {
600                 ship *docked_shipp = &Ships[docked_objp->instance];
601                 
602                 pm = model_get( docked_shipp->modelnum );
603                 
604                 w = pm->maxs.xyz.x - pm->mins.xyz.x;
605                 h = pm->maxs.xyz.y - pm->mins.xyz.y;
606                 
607                 if ( w > h )    {
608                         rad += w / 2.0f;
609                 } else {
610                         rad += h / 2.0f;
611                 }
612         }
613         return rad*3.0f;
614 }
615
616 // How long the stage 1 & stage 2 of warp in effect lasts.
617 // There are different times for small, medium, and large ships.
618 // The appropriate values are picked depending on the ship's
619 // radius.
620 #define SHIPFX_WARP_DELAY       (2.0f)          // time for warp effect to ramp up before ship moves into it.
621
622 // Give object objp, calculate how long it should take the
623 // ship to go through the warp effect and how fast the ship
624 // should go.   For reference,  capital ship of 2780m 
625 // should take 7 seconds to fly through.   Fighters of 30, 
626 // should take 1.5 seconds to fly through.
627
628 #define LARGEST_RAD 1390.0f 
629 #define LARGEST_RAD_TIME 7.0f
630
631 #define SMALLEST_RAD 15.0f
632 #define SMALLEST_RAD_TIME 1.5f
633
634
635 static float shipfx_calculate_warp_time( object * objp )
636 {
637         // Find rad_percent from 0 to 1, 0 being smallest ship, 1 being largest
638         float rad_percent = (objp->radius-SMALLEST_RAD) / (LARGEST_RAD-SMALLEST_RAD);
639         if ( rad_percent < 0.0f ) {
640                 rad_percent = 0.0f;
641         } else if ( rad_percent > 1.0f )        {
642                 rad_percent = 1.0f;
643         }
644         float rad_time = rad_percent*(LARGEST_RAD_TIME-SMALLEST_RAD_TIME) + SMALLEST_RAD_TIME;
645
646         return rad_time;
647 }
648
649 // calculate warp speed
650 float shipfx_calculate_warp_speed(object *objp)
651 {
652         float length;
653
654         Assert(objp->type == OBJ_SHIP);
655         if (objp->type != OBJ_SHIP) {
656                 length = 2.0f * objp->radius;
657         } else {
658                 length = ship_get_length(&Ships[objp->instance]);
659         }
660         return length / shipfx_calculate_warp_time(objp);
661 }
662
663
664 // This is called to actually warp this object in
665 // after all the flashy fx are done, or if the flashy 
666 // fx don't work for some reason.
667 void shipfx_actually_warpin(    ship *shipp, object *objp )
668 {
669         shipp->flags &= (~SF_ARRIVING_STAGE_1);
670         shipp->flags &= (~SF_ARRIVING_STAGE_2);
671
672         // let physics in on it too.
673         objp->phys_info.flags &= (~PF_WARP_IN);
674 }
675
676 // JAS - code to start the ship doing the warp in effect
677 // This also starts the animating 3d effect playing.
678 // There are two modes, stage 1 and stage 2.   Stage 1 is
679 // when the ship just invisibly waits for a certain time
680 // period after the effect starts, and then stage 2 begins,
681 // where the ships flies through the effect at a set
682 // velocity so it gets through in a certain amount of
683 // time.
684 void shipfx_warpin_start( object *objp )
685 {
686         ship *shipp;
687         float effect_time, effect_radius;
688         
689         shipp = &Ships[objp->instance];
690
691         if ( shipp->flags & SF_ARRIVING )       {
692                 mprintf(( "Ship is already arriving!\n" ));
693                 return;
694         }
695
696         // post a warpin event
697         if(Game_mode & GM_DEMO_RECORD){
698                 demo_POST_warpin(objp->signature, shipp->flags);
699         }
700
701         // if there is no arrival warp, then skip the whole thing
702         if ( shipp->flags & SF_NO_ARRIVAL_WARP )        {
703                 shipfx_actually_warpin(shipp,objp);
704                 return;
705         }
706         
707         // VALIDATE special_warp_objnum
708         if (shipp->special_warp_objnum >= 0) {
709                         
710                 int ref_objnum = shipp->special_warp_objnum;
711                 int valid_reference_ship = FALSE;
712
713                 // Validate reference_objnum
714                 if ((ref_objnum >= 0) && (ref_objnum < MAX_OBJECTS)) {
715                         object *sp_objp = &Objects[ref_objnum];
716                         if (sp_objp->type == OBJ_SHIP) {
717                                 if (Ship_info[Ships[sp_objp->instance].ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
718                                         valid_reference_ship = TRUE;
719                                 }
720                         }
721                 }
722
723                 if (valid_reference_ship != TRUE) {
724                         shipp->special_warp_objnum = -1;
725                 }
726         }
727
728         // only move warp effect pos if not special warp in.
729         if (shipp->special_warp_objnum >= 0) {
730                 Assert(!(Game_mode & GM_MULTIPLAYER));
731                 polymodel *pm;
732                 pm = model_get(shipp->modelnum);
733                 vm_vec_scale_add(&shipp->warp_effect_pos, &objp->pos, &objp->orient.v.fvec, -pm->mins.xyz.z);
734         } else {
735                 vm_vec_scale_add( &shipp->warp_effect_pos, &objp->pos, &objp->orient.v.fvec, objp->radius );
736         }
737         
738         // The ending zero mean this is a warp-in effect
739         if ( !(shipp->flags & SF_INITIALLY_DOCKED) ) {
740                 int warp_objnum;
741
742                 // Effect time is 'SHIPFX_WARP_DELAY' (1.5 secs) seconds to start, 'shipfx_calculate_warp_time' 
743                 // for ship to go thru, and 'SHIPFX_WARP_DELAY' (1.5 secs) to go away.
744                 effect_time = shipfx_calculate_warp_time(objp) + SHIPFX_WARP_DELAY + SHIPFX_WARP_DELAY;
745                 effect_radius = shipfx_calculate_effect_radius(objp);
746
747                 // maybe special warpin
748                 if (shipp->special_warp_objnum >= 0) {
749                         // cap radius to size of knossos
750                         effect_radius = min(effect_radius, 0.8f*Objects[shipp->special_warp_objnum].radius);
751                         warp_objnum = fireball_create(&shipp->warp_effect_pos, FIREBALL_KNOSSOS_EFFECT, shipp->special_warp_objnum, effect_radius, 0, NULL, effect_time, shipp->ship_info_index);
752                 } else {
753                         warp_objnum = fireball_create(&shipp->warp_effect_pos, FIREBALL_WARP_EFFECT, OBJ_INDEX(objp), effect_radius, 0, NULL, effect_time, shipp->ship_info_index);
754                 }
755                 if (warp_objnum < 0 )   {       // JAS: This must always be created, if not, just warp the ship in
756                         shipfx_actually_warpin(shipp,objp);
757                         return;
758                 }
759
760                 shipp->warp_effect_fvec = Objects[warp_objnum].orient.v.fvec;
761                 // maybe negate if special warp effect
762                 if (shipp->special_warp_objnum >= 0) {
763                         if (vm_vec_dotprod(&shipp->warp_effect_fvec, &objp->orient.v.fvec) < 0) {
764                                 vm_vec_negate(&shipp->warp_effect_fvec);
765                         }
766                 }
767
768
769                 shipp->final_warp_time = timestamp(fl2i(SHIPFX_WARP_DELAY*1000.0f));
770                 shipp->flags |= SF_ARRIVING_STAGE_1;
771
772                 // see if this ship is docked with anything, and if so, make docked ship be "arriving"
773                 /*
774                 if ( Ai_info[shipp->ai_index].dock_objnum != -1 ) {
775                         Ships[Ai_info[shipp->ai_index].dock_objnum].final_warp_time = timestamp(fl2i(warp_time*1000.0f));
776                         Ships[Ai_info[shipp->ai_index].dock_objnum].flags |= SF_ARRIVING_STAGE_1;
777                 }
778                 */
779         }
780 }
781
782 void shipfx_warpin_frame( object *objp, float frametime )
783 {
784         ship *shipp;
785
786         shipp = &Ships[objp->instance];
787
788         if ( shipp->flags & SF_DYING ) return;
789
790         if ( shipp->flags & SF_ARRIVING_STAGE_1 )       {
791                 if ( timestamp_elapsed(shipp->final_warp_time) ) {
792
793                         // let physics know the ship is going to warp in.
794                         objp->phys_info.flags |= PF_WARP_IN;
795
796                         // done doing stage 1 of warp, so go on to stage 2
797                         shipp->flags &= (~SF_ARRIVING_STAGE_1);
798                         shipp->flags |= SF_ARRIVING_STAGE_2;
799
800                         float warp_time = shipfx_calculate_warp_time(objp);
801                         float speed = shipfx_calculate_warp_speed(objp);                        // How long it takes to move through warp effect
802
803                         // Make ship move at velocity so that it moves two radius's in warp_time seconds.
804                         vector vel;
805                         vel = objp->orient.v.fvec;
806                         vm_vec_scale( &vel, speed );
807                         objp->phys_info.vel = vel;
808                         objp->phys_info.desired_vel = vel;
809                         objp->phys_info.prev_ramp_vel.xyz.x = 0.0f;
810                         objp->phys_info.prev_ramp_vel.xyz.y = 0.0f;
811                         objp->phys_info.prev_ramp_vel.xyz.z = speed;
812                         objp->phys_info.forward_thrust = 0.0f;          // How much the forward thruster is applied.  0-1.
813
814                         shipp->final_warp_time = timestamp(fl2i(warp_time*1000.0f));
815
816                         /*
817                         // see if this ship is docked with anything, and if so, make docked ship be "arriving"
818                         if ( Ai_info[shipp->ai_index].dock_objnum != -1 ) {
819                                 Ships[Ai_info[shipp->ai_index].dock_objnum].flags &= (~SF_ARRIVING_STAGE_1);
820                                 Ships[Ai_info[shipp->ai_index].dock_objnum].flags |= SF_ARRIVING_STAGE_2;
821                                 Ships[Ai_info[shipp->ai_index].dock_objnum].final_warp_time = timestamp(fl2i(warp_time*1000.0f));
822                         }
823                         */
824                 } 
825         } else if ( shipp->flags & SF_ARRIVING_STAGE_2 )        {
826                 if ( timestamp_elapsed(shipp->final_warp_time) ) {
827                         // done doing stage 2 of warp, so turn off arriving flag
828                         shipfx_actually_warpin(shipp,objp);
829
830                         // notify physics to slow down
831                         if (Ship_info[shipp->ship_info_index].flags & SIF_SUPERCAP) {
832                                 // let physics know this is a special warp in
833                                 objp->phys_info.flags |= PF_SPECIAL_WARP_IN;
834                         }
835                 }
836         }
837
838 }
839  
840 // This is called to actually warp this object out
841 // after all the flashy fx are done, or if the flashy 
842 // fx don't work for some reason.  OR to skip the flashy
843 // fx.
844 void shipfx_actually_warpout( ship *shipp, object *objp )
845 {
846         // Once we get through effect, make the ship go away
847
848         if ( objp == Player_obj )       {
849                 // Normally, this will never get called for the player. If it
850                 // does, it is because some error (like the warpout effect
851                 // couldn't start) so go ahead an warp the player out.
852                 // All this does is set the event to go to debriefing, the
853                 // same thing that happens after the player warp out effect
854                 // ends.
855                 gameseq_post_event( GS_EVENT_DEBRIEF ); // proceed to debriefing
856         } else {
857                 object *docked_objp;
858                 
859                 // Code for objects except player ship warping out
860                 objp->flags |= OF_SHOULD_BE_DEAD;
861                 // check to see if departing ship is docked with anything and if so, mark that object
862                 // gone as well
863                 docked_objp = ai_find_docked_object( objp );
864                 if ( docked_objp ) {
865                         docked_objp->flags |= OF_SHOULD_BE_DEAD;
866                 }
867
868                 ship_departed( objp->instance );
869                 if ( docked_objp ){
870                         ship_departed( docked_objp->instance );
871                 }
872         }
873 }
874
875 // compute_special_warpout_stuff();
876 int compute_special_warpout_stuff(object *objp, float *speed, float *warp_time, vector *warp_pos)
877 {
878         object  *sp_objp = NULL;
879         ship            *shipp;
880         int             valid_refenence_ship = FALSE, ref_objnum;
881         vector  facing_normal, vec_to_knossos;
882         float           dist_to_plane;
883
884         // knossos warpout only valid in single player
885         if (Game_mode & GM_MULTIPLAYER) {
886                 mprintf(("special warpout only for single player\n"));
887                 return -1;
888         }
889
890         // find special warp ship reference
891         valid_refenence_ship = FALSE;
892         ref_objnum = Ships[objp->instance].special_warp_objnum;
893
894         // Validate reference_objnum
895         if ((ref_objnum >= 0) && (ref_objnum < MAX_OBJECTS)) {
896                 sp_objp = &Objects[ref_objnum];
897                 if (sp_objp->type == OBJ_SHIP) {
898                         shipp = &Ships[sp_objp->instance];
899                         if (Ship_info[shipp->ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
900                                 valid_refenence_ship = TRUE;
901                         }
902                 }
903         }
904         
905         if (!valid_refenence_ship) {
906                 Int3();
907                 mprintf(("special warpout reference ship not found\n"));
908                 return -1;
909         }
910
911         // get facing normal from knossos
912         vm_vec_sub(&vec_to_knossos, &sp_objp->pos, &objp->pos);
913         facing_normal = sp_objp->orient.v.fvec;
914         if (vm_vec_dotprod(&vec_to_knossos, &sp_objp->orient.v.fvec) > 0) {
915                 vm_vec_negate(&facing_normal);
916         }
917
918         // find position to play the warp ani..
919         dist_to_plane = fvi_ray_plane(warp_pos, &sp_objp->pos, &facing_normal, &objp->pos, &objp->orient.v.fvec, 0.0f);
920
921         // calculate distance to warpout point.
922         polymodel *pm = model_get(Ships[objp->instance].modelnum);
923         dist_to_plane += pm->mins.xyz.z;
924
925         if (dist_to_plane < 0) {
926                 mprintf(("warpout started too late\n"));
927                 return -1;
928         }
929
930         // validate angle
931         float max_warpout_angle = 0.707f;       // 45 degree half-angle cone for small ships
932         if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
933                 max_warpout_angle = 0.866f;     // 30 degree half-angle cone for BIG or HUGE
934         }
935
936         if (-vm_vec_dotprod(&objp->orient.v.fvec, &facing_normal) < max_warpout_angle) {        // within allowed angle
937                 Int3();
938                 mprintf(("special warpout angle exceeded\n"));
939                 return -1;
940         }
941
942         // Calculate speed needed to get 
943         *speed = shipfx_calculate_warp_speed(objp);
944         
945         // Calculate how long to fly through the effect.  Not to get to the effect, just through it.
946         *warp_time = shipfx_calculate_warp_time(objp);
947         *warp_time += dist_to_plane / *speed;
948
949         return 0;
950 }
951
952
953 void compute_warpout_stuff(object *objp, float *speed, float *warp_time, vector *warp_pos)
954 {
955         // If we're warping through the knossos, do something different.
956         if (Ships[objp->instance].special_warp_objnum >= 0) {
957                 if (compute_special_warpout_stuff(objp, speed, warp_time, warp_pos) != -1) {
958                         return;
959                 } else {
960                         mprintf(("Invalid special warp\n"));
961                 }
962         }
963
964         object  *docked_objp = ai_find_docked_object( objp );
965         vector  center_pos = objp->pos;
966         float           radius, ship_move_dist, warp_dist;
967
968         radius = objp->radius;
969
970         //      If ship is docked then center wormhold about their center and make radius large enough.
971         if ( docked_objp ) {
972                 vm_vec_avg(&center_pos, &objp->pos, &docked_objp->pos);
973                 radius += docked_objp->radius;
974         }
975
976         // Calculate how long to fly through the effect.  Not to get to the effect, just through it.
977         *warp_time = shipfx_calculate_warp_time(objp);
978
979         // Pick some speed at which we want to go through the warp effect.  
980         // This is determined by shipfx_calculate_warp_time specifying how long
981         // it should take to go through the effect, or 2R.
982         *speed = shipfx_calculate_warp_speed(objp);
983
984         if ( objp == Player_obj )       {
985                 *speed = 0.8f*objp->phys_info.max_vel.xyz.z;
986         }
987
988         // Now we know our speed. Figure out how far the warp effect will be from here.  
989         ship_move_dist = (*speed * SHIPFX_WARP_DELAY) + radius*1.5f;            // We want to get to 1.5R away from effect
990         if ( ship_move_dist < radius*1.5f ) {
991                 ship_move_dist = radius*1.5f;
992         }
993
994         // If this is a huge ship, set the distance to the length of the ship
995         if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
996                 ship_move_dist = 0.5f * ship_get_length(&Ships[objp->instance]);
997         }
998
999         // Acount for time to get to warp effect, before we actually go through it.
1000         *warp_time += ship_move_dist / *speed;
1001
1002         warp_dist = ship_move_dist;
1003         // allow for off center
1004         if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
1005                 polymodel *pm = model_get(Ships[objp->instance].modelnum);
1006                 warp_dist -= pm->mins.xyz.z;
1007         }
1008
1009         vm_vec_scale_add( warp_pos, &center_pos, &objp->orient.v.fvec, warp_dist );
1010 }
1011
1012 // JAS - code to start the ship doing the warp out effect
1013 // This puts the ship into a mode specified by SF_DEPARTING
1014 // where it flies forward for a set time period at a set
1015 // velocity, then disappears when that time is reached.  This
1016 // also starts the animating 3d effect playing.
1017 void shipfx_warpout_start( object *objp )
1018 {
1019         float warp_time;
1020         ship *shipp;
1021         shipp = &Ships[objp->instance];
1022
1023         if (    shipp->flags & SF_DEPART_WARP ) {
1024                 mprintf(( "Ship is already departing!\n" ));
1025                 return;
1026         }
1027
1028         // if we're dying return
1029         if ( shipp->flags & SF_DYING ) {
1030                 return;
1031         }
1032
1033         // if we're HUGE, keep alive - set guardian
1034         if (Ship_info[shipp->ship_info_index].flags & SIF_HUGE_SHIP) {
1035                 objp->flags |= OF_GUARDIAN;
1036         }
1037
1038         // post a warpin event
1039         if(Game_mode & GM_DEMO_RECORD){
1040                 demo_POST_warpout(objp->signature, shipp->flags);
1041         }
1042
1043         // don't send ship depart packets for player ships
1044         if ( (MULTIPLAYER_MASTER) && !(objp->flags & OF_PLAYER_SHIP) ){
1045                 send_ship_depart_packet( objp );
1046         }
1047
1048         // don't do departure wormhole if ship flag is set which indicates no effect
1049         if ( shipp->flags & SF_NO_DEPARTURE_WARP ) {
1050                 // DKA 5/25/99 If he's going to warpout, set it.  
1051                 // Next line fixes assert in wing cleanup code when no warp effect.
1052                 shipp->flags |= SF_DEPART_WARP;
1053
1054                 shipfx_actually_warpout(shipp, objp);
1055                 return;
1056         }
1057
1058         if ( objp == Player_obj )       {
1059                 HUD_printf(XSTR( "Subspace node activated", 498) );
1060         }
1061
1062         float   speed, effect_time, effect_radius;
1063         vector  warp_pos;
1064         // warp time from compute warpout stuff includes time to get up to warp_pos
1065         compute_warpout_stuff(objp, &speed, &warp_time, &warp_pos);
1066         shipp->warp_effect_pos = warp_pos;
1067
1068         // The ending one means this is a warp-out effect
1069         int warp_objnum;
1070         // Effect time is 'SHIPFX_WARP_DELAY' (1.5 secs) seconds to start, 'shipfx_calculate_warp_time' 
1071         // for ship to go thru, and 'SHIPFX_WARP_DELAY' (1.5 secs) to go away.
1072         // effect_time = shipfx_calculate_warp_time(objp) + SHIPFX_WARP_DELAY + SHIPFX_WARP_DELAY;
1073         effect_time = warp_time + SHIPFX_WARP_DELAY;
1074         effect_radius = shipfx_calculate_effect_radius(objp);
1075
1076         // maybe special warpout
1077         if (shipp->special_warp_objnum >= 0) {
1078                 // cap radius to size of knossos
1079                 effect_radius = min(effect_radius, 0.8f*Objects[shipp->special_warp_objnum].radius);
1080                 warp_objnum = fireball_create(&shipp->warp_effect_pos, FIREBALL_KNOSSOS_EFFECT, shipp->special_warp_objnum, effect_radius, 1, NULL, effect_time, shipp->ship_info_index);
1081         } else {
1082                 warp_objnum = fireball_create(&shipp->warp_effect_pos, FIREBALL_WARP_EFFECT, OBJ_INDEX(objp), effect_radius, 1, NULL, effect_time, shipp->ship_info_index);
1083         }
1084         if (warp_objnum < 0 )   {       // JAS: This must always be created, if not, just warp the ship in
1085                 shipfx_actually_warpout(shipp,objp);
1086                 return;
1087         }
1088
1089         shipp->warp_effect_fvec = Objects[warp_objnum].orient.v.fvec;
1090         // maybe negate if special warp effect
1091         if (shipp->special_warp_objnum >= 0) {
1092                 if (vm_vec_dotprod(&shipp->warp_effect_fvec, &objp->orient.v.fvec) > 0) {
1093                         vm_vec_negate(&shipp->warp_effect_fvec);
1094                 }
1095         }
1096
1097         // Make the warp effect stage 1 last SHIP_WARP_TIME1 seconds.
1098         if ( objp == Player_obj )       {
1099                 warp_time = fireball_lifeleft(&Objects[warp_objnum]);
1100                 shipp->final_warp_time = timestamp(fl2i(warp_time*1000.0f));
1101         } else {
1102                 shipp->final_warp_time = timestamp(fl2i(warp_time*2.0f*1000.0f));
1103         }
1104         shipp->flags |= SF_DEPART_WARP;
1105
1106 //      mprintf(( "Warp time = %.4f , effect time = %.4f ms\n", warp_time*1000.0f, effect_time ));
1107
1108         // This is a hack to make the ship go at the right speed to go from it's current position to the warp_effect_pos;
1109         
1110         // Set ship's velocity to 'speed'
1111         // This should actually be an AI that flies from the current
1112         // position through 'shipp->warp_effect_pos' in 'warp_time'
1113         // and keeps going 
1114         if ( objp != Player_obj )       {
1115                 vector vel;
1116                 vel = objp->orient.v.fvec;
1117                 vm_vec_scale( &vel, speed );
1118                 objp->phys_info.vel = vel;
1119                 objp->phys_info.desired_vel = vel;
1120                 objp->phys_info.prev_ramp_vel.xyz.x = 0.0f;
1121                 objp->phys_info.prev_ramp_vel.xyz.y = 0.0f;
1122                 objp->phys_info.prev_ramp_vel.xyz.z = speed;
1123                 objp->phys_info.forward_thrust = 1.0f;          // How much the forward thruster is applied.  0-1.
1124
1125                 // special case for HUGE ships
1126                 if (Ship_info[shipp->ship_info_index].flags & SIF_HUGE_SHIP) {
1127 //                      objp->phys_info.flags |= PF_SPECIAL_WARP_OUT;
1128                 }
1129         }
1130
1131 }
1132
1133 void shipfx_warpout_frame( object *objp, float frametime )
1134 {
1135         ship *shipp;
1136         shipp = &Ships[objp->instance];
1137
1138         if ( shipp->flags & SF_DYING ) return;
1139
1140         vector tempv;
1141         float warp_pos; // position of warp effect in object's frame of reference
1142
1143         vm_vec_sub( &tempv, &objp->pos, &shipp->warp_effect_pos );
1144         warp_pos = -vm_vec_dot( &tempv, &shipp->warp_effect_fvec );
1145
1146
1147         // Find the closest point on line from center of wormhole
1148         vector pos;
1149         float dist;
1150
1151         fvi_ray_plane(&pos,&objp->pos,&shipp->warp_effect_fvec,&shipp->warp_effect_pos, &shipp->warp_effect_fvec, 0.0f );
1152         dist = vm_vec_dist( &pos, &objp->pos );
1153
1154 //      mprintf(( "Warp pos = %.1f, rad=%.1f, center dist = %.1f\n", warp_pos, objp->radius, dist ));
1155
1156         if ( objp == Player_obj )       {
1157                 // Code for player warpout frame
1158
1159                 if ( (Player->control_mode==PCM_WARPOUT_STAGE2) && (warp_pos > objp->radius) )  {
1160                         gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_DONE_STAGE2 );
1161                 }
1162
1163                 if ( timestamp_elapsed(shipp->final_warp_time) ) {
1164
1165                         // Something went wrong... oh well, warp him out anyway.
1166                         if ( Player->control_mode != PCM_WARPOUT_STAGE3 )       {
1167                                 mprintf(( "Hmmm... player ship warpout time elapsed, but he wasn't in warp stage 3.\n" ));
1168                         }
1169
1170                         gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_DONE );
1171                         ship_departed( objp->instance );                                                                // mark log entry for the player
1172                 }
1173
1174         } else {
1175                 // Code for all non-player ships warpout frame
1176
1177                 int timed_out = timestamp_elapsed(shipp->final_warp_time);
1178                 if ( timed_out )        {
1179 //                      mprintf(("Frame %i: Ship %s missed departue cue.\n", Framecount, shipp->ship_name ));
1180                         int     delta_ms = timestamp_until(shipp->final_warp_time);
1181                         if (delta_ms > 1000.0f * frametime ) {
1182                                 nprintf(("AI", "Frame %i: Ship %s missed departue cue by %7.3f seconds.\n", Framecount, shipp->ship_name, - (float) delta_ms/1000.0f));
1183                         }
1184                 }
1185
1186                 // MWA 10/21/97 -- added shipp->flags & SF_NO_DEPARTURE_WARP part of next if statement.  For ships
1187                 // that don't get a wormhole effect, I wanted to drop into this code immediately.
1188                 if ( (warp_pos > objp->radius)  || (shipp->flags & SF_NO_DEPARTURE_WARP) || timed_out ) {
1189                         shipfx_actually_warpout( shipp, objp );
1190                 } 
1191         }
1192 }
1193
1194
1195 //==================================================
1196 // Stuff for keeping track of which ships are in
1197 // whose shadows.
1198
1199
1200 // Given point p0, in object's frame of reference, find if 
1201 // it can see the sun.
1202 int shipfx_point_in_shadow( vector *p0, matrix *src_orient, vector *src_pos, float radius )
1203 {
1204         mc_info mc;
1205         object *objp;
1206         ship_obj *so;
1207         ship *shipp;
1208         int n_lights;
1209         int idx;
1210
1211         vector rp0, rp1;
1212
1213         vector light_dir;
1214
1215         // Move rp0 into world coordinates      
1216         vm_vec_unrotate(&rp0, p0, src_orient);
1217         vm_vec_add2(&rp0, src_pos);
1218
1219         // get the # of global lights
1220         n_lights = light_get_global_count();
1221         
1222         for(idx=0; idx<n_lights; idx++){
1223                 // get the light dir for this light
1224                 light_get_global_dir(&light_dir, idx);
1225
1226                 // Find rp1
1227                 vm_vec_scale_add( &rp1, &rp0, &light_dir, 10000.0f );
1228
1229                 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) )    {
1230                         objp = &Objects[so->objnum];
1231                         shipp = &Ships[objp->instance];
1232
1233                         mc.model_num = shipp->modelnum;
1234                         mc.orient = &objp->orient;
1235                         mc.pos = &objp->pos;
1236                         mc.p0 = &rp0;
1237                         mc.p1 = &rp1;
1238                         mc.flags = MC_CHECK_MODEL;      
1239
1240                         if ( model_collide(&mc) ){
1241                                 return 1;
1242                         }
1243                 }
1244         }
1245
1246         // not in shadow
1247         return 0;
1248 }
1249
1250
1251 // Given an ship see if it is in a shadow.
1252 int shipfx_in_shadow( object * src_obj )
1253 {
1254         mc_info mc;
1255         object *objp;
1256         ship_obj *so;
1257         ship *shipp;
1258         int n_lights;
1259         int idx;
1260
1261         vector rp0, rp1;
1262         vector light_dir;
1263
1264         rp0 = src_obj->pos;
1265         
1266         // get the # of global lights
1267         n_lights = light_get_global_count();
1268
1269         for(idx=0; idx<n_lights; idx++){
1270                 // get the direction for this light
1271                 light_get_global_dir(&light_dir, idx);
1272
1273                 // Find rp1
1274                 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) )    {
1275                         objp = &Objects[so->objnum];
1276
1277                         if ( src_obj != objp )  {
1278                                 shipp = &Ships[objp->instance];
1279
1280                                 vm_vec_scale_add( &rp1, &rp0, &light_dir, objp->radius*10.0f );
1281
1282                                 mc.model_num = shipp->modelnum;
1283                                 mc.orient = &objp->orient;
1284                                 mc.pos = &objp->pos;
1285                                 mc.p0 = &rp0;
1286                                 mc.p1 = &rp1;
1287                                 mc.flags = MC_CHECK_MODEL;      
1288
1289         //                      mc.flags |= MC_CHECK_SPHERELINE;
1290         //                      mc.radius = src_obj->radius;
1291
1292                                 if ( model_collide(&mc) )       {
1293                                         return 1;
1294                                 }
1295                         }
1296                 }
1297         }
1298
1299         // not in shadow
1300         return 0;
1301 }
1302
1303 // Given world point see if it is in a shadow.
1304 int shipfx_eye_in_shadow( vector *eye_pos, object * src_obj, int sun_n )
1305 {
1306         mc_info mc;
1307         object *objp;
1308         ship_obj *so;
1309         ship *shipp;    
1310
1311         vector rp0, rp1;
1312         vector light_dir;
1313
1314         rp0 = *eye_pos; 
1315         
1316         // get the light dir
1317         if(!light_get_global_dir(&light_dir, sun_n)){
1318                 return 0;
1319         }
1320
1321         // Find rp1
1322         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) )    {
1323                 objp = &Objects[so->objnum];
1324
1325                 if ( src_obj != objp )  {
1326                         shipp = &Ships[objp->instance];
1327
1328                         vm_vec_scale_add( &rp1, &rp0, &light_dir, objp->radius*10.0f );
1329
1330                         ship_model_start(objp);
1331
1332                         mc.model_num = shipp->modelnum;
1333                         mc.orient = &objp->orient;
1334                         mc.pos = &objp->pos;
1335                         mc.p0 = &rp0;
1336                         mc.p1 = &rp1;
1337                         mc.flags = MC_CHECK_MODEL;      
1338
1339         //                      mc.flags |= MC_CHECK_SPHERELINE;
1340         //                      mc.radius = src_obj->radius;
1341
1342                         int hit = model_collide(&mc);
1343
1344                         ship_model_stop(objp);
1345
1346                         if (hit) {
1347                                 return 1;
1348                         }
1349                 }
1350         }
1351
1352         // Check all the big hull debris pieces.
1353         debris  *db = Debris;
1354
1355         int i;
1356         for ( i = 0; i < MAX_DEBRIS_PIECES; i++, db++ ) {
1357                 if ( !(db->flags & DEBRIS_USED) || !db->is_hull ){
1358                         continue;
1359                 }
1360
1361                 objp = &Objects[db->objnum];
1362
1363                 vm_vec_scale_add( &rp1, &rp0, &light_dir, objp->radius*10.0f );
1364
1365                 mc.model_num = db->model_num;   // Fill in the model to check
1366                 mc.submodel_num = db->submodel_num;
1367                 model_clear_instance( mc.model_num );
1368                 mc.orient = &objp->orient;                                      // The object's orient
1369                 mc.pos = &objp->pos;                                                    // The object's position
1370                 mc.p0 = &rp0;                           // Point 1 of ray to check
1371                 mc.p1 = &rp1;                                   // Point 2 of ray to check
1372                 mc.flags = (MC_CHECK_MODEL | MC_SUBMODEL);
1373
1374                 if (model_collide(&mc)) {
1375                         return 1;
1376                 }
1377         }       
1378
1379         // not in shadow
1380         return 0;
1381 }
1382
1383 //=====================================================================================
1384 // STUFF FOR DOING SHIP GUN FLASHES
1385 //=====================================================================================
1386
1387 #define MAX_FLASHES     128                     // How many flashes total
1388 #define FLASH_LIFE_PRIMARY              0.25f                   // How long flash lives
1389 #define FLASH_LIFE_SECONDARY    0.50f                   // How long flash lives
1390
1391
1392 typedef struct ship_flash {
1393         int     objnum;                                 // object number of parent ship
1394         int     obj_signature;                  // signature of that object
1395         int     light_num;                              // which light in the model this uses
1396         float   life;                                           // how long this should be around
1397         float max_life;                         // how long this has been around.
1398 } ship_flash;
1399
1400 int Ship_flash_inited = 0;
1401 int Ship_flash_highest = -1;
1402 ship_flash Ship_flash[MAX_FLASHES];
1403
1404 // Resets the ship flash stuff. Call before each level.
1405 void shipfx_flash_init()
1406 {
1407         int i;
1408         
1409         for (i=0; i<MAX_FLASHES; i++ )  {
1410                 Ship_flash[i].objnum = -1;                      // mark as unused
1411         }
1412         Ship_flash_highest = -1;
1413         Ship_flash_inited = 1;  
1414 }
1415
1416
1417 // Given that a ship fired a weapon, light up the model
1418 // accordingly.
1419 void shipfx_flash_create(object *objp, ship * shipp, vector *gun_pos, vector *gun_dir, int is_primary, int weapon_info_index)
1420 {
1421         int i;
1422         int objnum = OBJ_INDEX(objp);
1423
1424         Assert(Ship_flash_inited);
1425
1426         polymodel *pm = model_get( shipp->modelnum );
1427         int closest_light = -1;
1428         float d, closest_dist = 0.0f;
1429
1430         // ALWAYS do this - since this is called once per firing
1431         // if this is a cannon type weapon, create a muzzle flash
1432         // HACK - let the flak guns do this on their own since they fire so quickly
1433         if((Weapon_info[weapon_info_index].wi_flags & WIF_MFLASH) && !(Weapon_info[weapon_info_index].wi_flags & WIF_FLAK)){
1434                 // spiffy new flash stuff
1435                 mflash_create(gun_pos, gun_dir, Weapon_info[weapon_info_index].muzzle_flash);           
1436         }
1437
1438         if ( pm->num_lights < 1 ) return;
1439
1440         for (i=0; i<pm->num_lights; i++ )       {
1441                 d = vm_vec_dist( &pm->lights[i].pos, gun_pos );
1442         
1443                 if ( pm->lights[i].type == BSP_LIGHT_TYPE_WEAPON ) {
1444                         if ( (closest_light==-1) || (d<closest_dist) )  {
1445                                 closest_light = i;
1446                                 closest_dist = d;
1447                         }
1448                 }
1449         }
1450
1451         if ( closest_light == -1 ) return;
1452
1453         int first_slot = -1;
1454
1455         for (i=0; i<=Ship_flash_highest; i++ )  {
1456                 if ( (first_slot==-1) && (Ship_flash[i].objnum < 0) )   {
1457                         first_slot = i;
1458                 }
1459
1460                 if ( (Ship_flash[i].objnum == objnum) && (Ship_flash[i].obj_signature==objp->signature) )       {
1461                         if ( Ship_flash[i].light_num == closest_light ) {
1462                                 // This is already flashing!
1463                                 Ship_flash[i].life = 0.0f;
1464                                 if ( is_primary )       {
1465                                         Ship_flash[i].max_life = FLASH_LIFE_PRIMARY;
1466                                 } else {
1467                                         Ship_flash[i].max_life = FLASH_LIFE_SECONDARY;
1468                                 }
1469                                 return;
1470                         }
1471                 }
1472         }
1473
1474         if ( first_slot == -1 ) {
1475                 if ( Ship_flash_highest < MAX_FLASHES-1 )       {
1476                         Ship_flash_highest++;
1477                         first_slot = Ship_flash_highest;
1478                 } else {
1479                         //mprintf(( "SHIP_FLASH: Out of flash spots!\n" ));
1480                         return;         // out of flash slots
1481                 }
1482         }
1483
1484         Assert( Ship_flash[first_slot].objnum == -1 );
1485
1486         Ship_flash[first_slot].objnum = objnum;
1487         Ship_flash[first_slot].obj_signature = objp->signature;
1488         Ship_flash[first_slot].life = 0.0f;             // Start it up
1489         if ( is_primary )       {
1490                 Ship_flash[first_slot].max_life = FLASH_LIFE_PRIMARY;
1491         } else {
1492                 Ship_flash[first_slot].max_life = FLASH_LIFE_SECONDARY;
1493         }
1494         Ship_flash[first_slot].light_num = closest_light;               
1495 }
1496
1497 // Sets the flash lights in the model used by this
1498 // ship to the appropriate values.  There might not
1499 // be any flashes linked to this ship in which
1500 // case this function does nothing.
1501 void shipfx_flash_light_model( object *objp, ship * shipp )
1502 {
1503         int i, objnum = OBJ_INDEX(objp);
1504         polymodel *pm = model_get( shipp->modelnum );
1505
1506         for (i=0; i<=Ship_flash_highest; i++ )  {
1507                 if ( (Ship_flash[i].objnum == objnum) && (Ship_flash[i].obj_signature==objp->signature) )       {
1508                         float v = (Ship_flash[i].max_life - Ship_flash[i].life)/Ship_flash[i].max_life;
1509
1510                         pm->lights[Ship_flash[i].light_num].value += v / 255.0f;
1511                 }
1512         }
1513
1514 }
1515
1516 // Does whatever processing needs to be done each frame.
1517 void shipfx_flash_do_frame(float frametime)
1518 {
1519         ship_flash *sf;
1520         int kill_it = 0;
1521         int i;
1522
1523         for (i=0, sf = &Ship_flash[0]; i<=Ship_flash_highest; i++, sf++ )       {
1524                 if ( sf->objnum > -1 )  {
1525                         if ( Objects[sf->objnum].signature != sf->obj_signature )       {
1526                                 kill_it = 1;
1527                         }
1528                         sf->life += frametime;
1529                         if ( sf->life >= sf->max_life ) kill_it = 1;
1530
1531                         if (kill_it) {
1532                                 sf->objnum = -1;
1533                                 if ( i == Ship_flash_highest )  {
1534                                         while( (Ship_flash_highest>0) && (Ship_flash[Ship_flash_highest].objnum == -1) )        {
1535                                                 Ship_flash_highest--;
1536                                         }
1537                                 }
1538                         }       
1539                 }
1540         }       
1541
1542 }
1543
1544 float Particle_width = 1.2f;
1545 DCF(particle_width, "Multiplier for angular width of the particle spew")
1546 {
1547         if ( Dc_command ) {
1548                 dc_get_arg(ARG_FLOAT);
1549                 if ( (Dc_arg_float >= 0 ) && (Dc_arg_float <= 5) ) {
1550                         Particle_width = Dc_arg_float;
1551                 } else {
1552                         dc_printf( "Illegal value for particle width. (Must be from 0-5) \n\n");
1553                 }
1554         }
1555 }
1556
1557 float Particle_number = 1.2f;
1558 DCF(particle_num, "Multiplier for the number of particles created")
1559 {
1560         if ( Dc_command ) {
1561                 dc_get_arg(ARG_FLOAT);
1562                 if ( (Dc_arg_float >= 0 ) && (Dc_arg_float <= 5) ) {
1563                         Particle_number = Dc_arg_float;
1564                 } else {
1565                         dc_printf( "Illegal value for particle num. (Must be from 0-5) \n\n");
1566                 }
1567         }
1568 }
1569
1570 float Particle_life = 1.2f;
1571 DCF(particle_life, "Multiplier for the lifetime of particles created")
1572 {
1573         if ( Dc_command ) {
1574                 dc_get_arg(ARG_FLOAT);
1575                 if ( (Dc_arg_float >= 0 ) && (Dc_arg_float <= 5) ) {
1576                         Particle_life = Dc_arg_float;
1577                 } else {
1578                         dc_printf( "Illegal value for particle life. (Must be from 0-5) \n\n");
1579                 }
1580         }
1581 }
1582
1583 // Make sparks fly off of ship n.
1584 // sn = spark number to spark, corrosponding to element in
1585 //      ship->hitpos array.  If this isn't -1, it is a just
1586 //      got hit by weapon spark, otherwise pick one randomally.
1587 void shipfx_emit_spark( int n, int sn )
1588 {
1589         int create_spark = 1;
1590         object * obj;
1591         vector outpnt;
1592         ship *shipp = &Ships[n];
1593         float ship_radius, spark_scale_factor;
1594         
1595         if ( shipp->num_hits <= 0 )
1596                 return;
1597
1598         // get radius of ship
1599         ship_radius = model_get_radius(Ship_info[shipp->ship_info_index].modelnum);
1600
1601         // get spark_scale_factor -- how much to increase ship sparks, based on radius
1602         if (ship_radius > 40) {
1603                 spark_scale_factor = 1.0f;
1604         } else if (ship_radius > 20) {
1605                 spark_scale_factor = (ship_radius - 20.0f) / 20.0f;
1606         } else {
1607                 spark_scale_factor = 0.0f;
1608         }
1609
1610         float spark_time_scale  = 1.0f + spark_scale_factor * (Particle_life   - 1.0f);
1611         float spark_width_scale = 1.0f + spark_scale_factor * (Particle_width  - 1.0f);
1612         float spark_num_scale   = 1.0f + spark_scale_factor * (Particle_number - 1.0f);
1613
1614         obj = &Objects[shipp->objnum];
1615         ship_info* si = &Ship_info[shipp->ship_info_index];
1616
1617         float hull_percent = obj->hull_strength / si->initial_hull_strength;
1618         if (hull_percent < 0.001) {
1619                 hull_percent = 0.001f;
1620         }
1621         float fraction = 0.1f * obj->radius / hull_percent;
1622         if (fraction > 1.0f) {
1623                 fraction = 1.0f;
1624         }
1625
1626         int spark_num;
1627         if ( sn == -1 ) {
1628                 spark_num = myrand() % shipp->num_hits;
1629         } else {
1630                 spark_num = sn;
1631         }
1632
1633         // don't display sparks that have expired
1634         if ( timestamp_elapsed(shipp->sparks[spark_num].end_time) ) {
1635                 return;
1636         }
1637
1638         // get spark position
1639         if (shipp->sparks[spark_num].submodel_num != -1) {
1640                 ship_model_start(obj);
1641                 model_find_world_point(&outpnt, &shipp->sparks[spark_num].pos, shipp->modelnum, shipp->sparks[spark_num].submodel_num, &obj->orient, &obj->pos);
1642                 ship_model_stop(obj);
1643         } else {
1644                 // rotate sparks correctly with current ship orient
1645                 vm_vec_unrotate(&outpnt, &shipp->sparks[spark_num].pos, &obj->orient);
1646                 vm_vec_add2(&outpnt,&obj->pos);
1647         }
1648
1649         if ( shipp->flags & (SF_ARRIVING|SF_DEPART_WARP) ) {
1650                 vector tmp;
1651                 vm_vec_sub( &tmp, &outpnt, &shipp->warp_effect_pos );
1652                 if ( vm_vec_dot( &tmp, &shipp->warp_effect_fvec ) < 0.0f )      {
1653                         // if in front of warp plane, don't create.
1654                         create_spark = 0;
1655                 }
1656         }
1657
1658         if ( create_spark )     {
1659
1660                 particle_emitter        pe;
1661
1662                 pe.pos = outpnt;                                // Where the particles emit from
1663
1664                 if ( shipp->flags & (SF_ARRIVING|SF_DEPART_WARP) ) {
1665                         // No velocity if going through warp.
1666                         pe.vel = vmd_zero_vector;
1667                 } else {
1668                         // Initial velocity of all the particles.
1669                         // 0.0f = 0% of parent's.
1670                         // 1.0f = 100% of parent's.
1671                         vm_vec_copy_scale( &pe.vel, &obj->phys_info.vel, 0.7f );
1672                 }
1673
1674                 // TODO: add velocity from rotation if submodel is rotating
1675                 // v_rot = w x r
1676
1677                 // r = outpnt - model_find_world_point(0)
1678
1679                 // w = model_find_world_dir(
1680                 // model_find_world_dir(&out_dir, &in_dir, model_num, submodel_num, &objorient, &objpos);
1681
1682                 vector tmp_norm, tmp_vel;
1683                 vm_vec_sub( &tmp_norm, &outpnt, &obj->pos );
1684                 vm_vec_normalize_safe(&tmp_norm);
1685
1686                 tmp_vel = obj->phys_info.vel;
1687                 if ( vm_vec_normalize_safe(&tmp_vel) > 1.0f )   {
1688                         vm_vec_scale_add2(&tmp_norm,&tmp_vel, -2.0f);
1689                         vm_vec_normalize_safe(&tmp_norm);
1690                 }
1691                                 
1692                 pe.normal = tmp_norm;                   // What normal the particle emit around
1693                 pe.normal_variance = 0.3f;              //      How close they stick to that normal 0=good, 1=360 degree
1694                 pe.min_rad = 0.20f;                             // Min radius
1695                 pe.max_rad = 0.50f;                             // Max radius
1696
1697                 // first time through - set up end time and make heavier initially
1698                 if ( sn > -1 )  {
1699                         // Sparks for first time at this spot
1700                         if (si->flags & SIF_FIGHTER) {
1701                                 if (hull_percent > 0.6f) {
1702                                         // sparks only once when hull > 60%
1703                                         float spark_duration = (float)pow(2.0f, -5.0f*(hull_percent-1.3f)) * (1.0f + 0.6f*(frand()-0.5f));      // +- 30%
1704                                         shipp->sparks[spark_num].end_time = timestamp( (int) (1000.0f * spark_duration) );
1705                                 } else {
1706                                         // spark never ends when hull < 60% (~277 hr)
1707                                         shipp->sparks[spark_num].end_time = timestamp( 100000000 );
1708                                 }
1709                         }
1710
1711                         if ( D3D_enabled ) {
1712                                 pe.num_low  = 25;                               // Lowest number of particles to create (hardware)
1713                                 pe.num_high = 30;                               // Highest number of particles to create (hardware)
1714                         } else {
1715                                 pe.num_low  = 5;                                // Lowest number of particles to create (software)
1716                                 pe.num_high = 7;                                // Highest number of particles to create (software)
1717                         }
1718                         pe.normal_variance = 1.0f;      //      How close they stick to that normal 0=good, 1=360 degree
1719                         pe.min_vel = 2.0f;                              // How fast the slowest particle can move
1720                         pe.max_vel = 12.0f;                             // How fast the fastest particle can move
1721                         pe.min_life = 0.05f;                            // How long the particles live
1722                         pe.max_life = 0.55f;                            // How long the particles live
1723
1724                         particle_emit( &pe, PARTICLE_FIRE, 0 );
1725                 } else {
1726
1727                         pe.min_rad = 0.7f;                              // Min radius
1728                         pe.max_rad = 1.3f;                              // Max radius
1729                         if ( D3D_enabled ) {
1730                                 pe.num_low  = int (20 * spark_num_scale);               // Lowest number of particles to create (hardware)
1731                                 pe.num_high = int (50 * spark_num_scale);               // Highest number of particles to create (hardware)
1732                         } else {
1733                                 pe.num_low  = 2;                        // Lowest number of particles to create (software)
1734                                 pe.num_high = 8;                // Highest number of particles to create (software)
1735                         }
1736                         pe.normal_variance = 0.2f * spark_width_scale;          //      How close they stick to that normal 0=good, 1=360 degree
1737                         pe.min_vel = 3.0f;                              // How fast the slowest particle can move
1738                         pe.max_vel = 12.0f;                             // How fast the fastest particle can move
1739                         pe.min_life = 0.35f*2.0f * spark_time_scale;            // How long the particles live
1740                         pe.max_life = 0.75f*2.0f * spark_time_scale;            // How long the particles live
1741                         
1742                         particle_emit( &pe, PARTICLE_SMOKE, 0 );
1743                 }
1744         }
1745
1746         // Select time to do next spark
1747 //      Ships[n].next_hit_spark = timestamp_rand(100,500);
1748         shipp->next_hit_spark = timestamp_rand(50,100);
1749 }
1750
1751
1752
1753 //=====================================================================================
1754 // STUFF FOR DOING LARGE SHIP EXPLOSIONS
1755 //=====================================================================================
1756
1757 int     Bs_exp_fire_low = 1;
1758 float   Bs_exp_fire_time_mult = 1.0f;
1759
1760 DCF_BOOL(bs_exp_fire_low, Bs_exp_fire_low)
1761 DCF(bs_exp_fire_time_mult, "Multiplier time between fireball in big ship explosion")
1762 {
1763         if ( Dc_command ) {
1764                 dc_get_arg(ARG_FLOAT);
1765                 if ( (Dc_arg_float >= 0.1 ) && (Dc_arg_float <= 5) ) {
1766                         Bs_exp_fire_time_mult = Dc_arg_float;
1767                 } else {
1768                         dc_printf( "Illegal value for bs_exp_fire_time_mult. (Must be from 0.1-5) \n\n");
1769                 }
1770         }
1771 }
1772
1773 #define MAX_SPLIT_SHIPS         3               // How many can explode at once.  Each one is about 1K.
1774
1775 #define DEBRIS_NONE                     0
1776 #define DEBRIS_DRAW                     1
1777 #define DEBRIS_FREE                     2
1778
1779 typedef struct clip_ship {
1780         object*                 parent_obj;
1781         float                   length_left;    // uncomsumed length
1782         matrix                  orient;
1783         physics_info    phys_info;
1784         vector                  local_pivot;                                                            // world center of mass position of half ship
1785         vector                  model_center_disp_to_orig_center;       // displacement from half ship center to original model center
1786         vector                  clip_plane_norm;                                                        // clip plane normal (local [0,0,1] or [0,0,-1])
1787         float                           cur_clip_plane_pt;                                              // displacement from half ship clip plane to original model center
1788         float                           explosion_vel;
1789         ubyte                           draw_debris[MAX_DEBRIS_OBJECTS];
1790         int                             next_fireball;
1791 } clip_ship;
1792
1793 typedef struct split_ship {
1794         int                             used;                                   // 0 if not used, 1 if used
1795         clip_ship               front_ship;
1796         clip_ship               back_ship;
1797         int                             explosion_flash_timestamp;
1798         int                             explosion_flash_started;
1799         int                             sound_handle[NUM_SUB_EXPL_HANDLES];
1800 } split_ship;
1801
1802
1803 static split_ship Split_ships[MAX_SPLIT_SHIPS];
1804 static int Split_ships_inited = 0;
1805
1806 static void split_ship_init_system()
1807 {
1808         int i;
1809         for (i=0; i<MAX_SPLIT_SHIPS; i++ )      {
1810                 Split_ships[i].used = 0;
1811         }
1812         Split_ships_inited = 1;
1813 }
1814
1815 static void maybe_fireball_wipe(clip_ship* half_ship, int* sound_handle);
1816 static void split_ship_init( ship* shipp, split_ship* split_ship )
1817 {
1818         object* parent_ship_obj = &Objects[shipp->objnum];
1819         matrix* orient = &parent_ship_obj->orient;
1820         for (int ii=0; ii<NUM_SUB_EXPL_HANDLES; ii++) {
1821                 split_ship->sound_handle[ii] = shipp->sub_expl_sound_handle[ii];
1822         }
1823
1824         // play 3d sound for shockwave explosion
1825         snd_play_3d( &Snds[SND_SHOCKWAVE_EXPLODE], &parent_ship_obj->pos, &View_position, 0.0f, NULL, 0, 1.0f, SND_PRIORITY_SINGLE_INSTANCE, NULL, 3.0f );
1826
1827         // initialize both ships
1828         split_ship->front_ship.parent_obj = parent_ship_obj;
1829         split_ship->back_ship.parent_obj  = parent_ship_obj;
1830         split_ship->explosion_flash_timestamp = timestamp((int)(0.00075f*parent_ship_obj->radius));
1831         split_ship->explosion_flash_started = 0;
1832         split_ship->front_ship.orient = *orient;
1833         split_ship->back_ship.orient  = *orient;
1834         split_ship->front_ship.next_fireball = timestamp_rand(0, 100);
1835         split_ship->back_ship.next_fireball  = timestamp_rand(0, 100);
1836
1837         split_ship->front_ship.clip_plane_norm = vmd_z_vector;
1838         vm_vec_copy_scale(&split_ship->back_ship.clip_plane_norm, &vmd_z_vector, -1.0f);
1839
1840         // find the point at which the ship splits (relative to its pivot)
1841         polymodel* pm = model_get(shipp->modelnum);
1842         float init_clip_plane_dist;
1843         if (pm->num_split_plane > 0) {
1844                 int index = rand()%pm->num_split_plane;
1845                 init_clip_plane_dist = pm->split_plane[index];
1846         } else {
1847                 init_clip_plane_dist = 0.5f * (0.5f - frand())*pm->core_radius;
1848         }
1849
1850         split_ship->back_ship.cur_clip_plane_pt =  init_clip_plane_dist;
1851         split_ship->front_ship.cur_clip_plane_pt = init_clip_plane_dist;
1852
1853         float dist;
1854         dist = (split_ship->front_ship.cur_clip_plane_pt+pm->maxs.xyz.z)/2.0f;
1855         vm_vec_copy_scale(&split_ship->front_ship.local_pivot, &orient->v.fvec, dist);
1856         (void) vm_vec_make(&split_ship->front_ship.model_center_disp_to_orig_center, 0.0f, 0.0f, -dist);
1857         dist = (split_ship->back_ship.cur_clip_plane_pt +pm->mins.xyz.z)/2.0f;
1858         vm_vec_copy_scale(&split_ship->back_ship.local_pivot, &orient->v.fvec, dist);
1859         (void) vm_vec_make(&split_ship->back_ship.model_center_disp_to_orig_center, 0.0f, 0.0f, -dist);
1860         vm_vec_add2(&split_ship->front_ship.local_pivot, &parent_ship_obj->pos );
1861         vm_vec_add2(&split_ship->back_ship.local_pivot,  &parent_ship_obj->pos );
1862         
1863         // find which debris pieces are in the front and back split ships
1864         for (int i=0; i<pm->num_debris_objects; i++ )   {
1865                 vector temp_pos = {0.0f, 0.0f, 0.0f};
1866                 vector tmp = {0.0f, 0.0f, 0.0f };               
1867                 vector tmp1 = pm->submodel[pm->debris_objects[i]].offset;
1868                 // tmp is world position,  temp_pos is world_pivot,  tmp1 is offset from world_pivot (in ship local coord)
1869                 model_find_world_point(&tmp, &tmp1, shipp->modelnum, -1, &vmd_identity_matrix, &temp_pos );
1870                 if (tmp.xyz.z > init_clip_plane_dist) {
1871                         split_ship->front_ship.draw_debris[i] = DEBRIS_DRAW;
1872                         split_ship->back_ship.draw_debris[i]  = DEBRIS_NONE;
1873                 } else {
1874                         split_ship->front_ship.draw_debris[i] = DEBRIS_NONE;
1875                         split_ship->back_ship.draw_debris[i]  = DEBRIS_DRAW;
1876                 }
1877         }
1878
1879         /*
1880         // set the remaining debris slots to not draw
1881         for (i=pm->num_debris_objects; i<MAX_DEBRIS_OBJECTS; i++) {
1882                 split_ship->front_ship.draw_debris[i] = DEBRIS_NONE;
1883                 split_ship->back_ship.draw_debris[i]  = DEBRIS_NONE;
1884         } */
1885
1886         // set up physics 
1887         physics_init( &split_ship->front_ship.phys_info );
1888         physics_init( &split_ship->back_ship.phys_info );
1889         split_ship->front_ship.phys_info.flags  |= (PF_ACCELERATES | PF_DEAD_DAMP);
1890         split_ship->back_ship.phys_info.flags |= (PF_ACCELERATES | PF_DEAD_DAMP);
1891         split_ship->front_ship.phys_info.side_slip_time_const = 10000.0f;
1892         split_ship->back_ship.phys_info.side_slip_time_const =  10000.0f;
1893         split_ship->front_ship.phys_info.rotdamp = 10000.0f;
1894         split_ship->back_ship.phys_info.rotdamp =  10000.0f;
1895
1896         // set up explosion vel and relative velocities (assuming mass depends on length)
1897         float front_length = pm->maxs.xyz.z - split_ship->front_ship.cur_clip_plane_pt;
1898         float back_length  = split_ship->back_ship.cur_clip_plane_pt - pm->mins.xyz.z;
1899         float ship_length = front_length + back_length;
1900         split_ship->front_ship.length_left = front_length;
1901         split_ship->back_ship.length_left  = back_length;
1902
1903         float expl_length_scale = (ship_length - 200.0f) / 2000.0f;
1904         // s_r_f effects speed of "wipe" and rotvel
1905         float speed_reduction_factor = (1.0f + 0.001f*parent_ship_obj->radius);
1906         float explosion_time = (3.0f + expl_length_scale + (frand()-0.5f)) * speed_reduction_factor;
1907         float long_length = max(front_length, back_length);
1908         float expl_vel = long_length / explosion_time;
1909         split_ship->front_ship.explosion_vel = expl_vel;
1910         split_ship->back_ship.explosion_vel  = -expl_vel;
1911
1912         float rel_vel = (0.6f + 0.2f*frand()) * expl_vel * speed_reduction_factor;
1913         float front_vel = rel_vel * back_length / ship_length;
1914         float back_vel = -rel_vel * front_length / ship_length;
1915         // mprintf(("rel_vel %.1f, expl_vel %.1f\n", rel_vel, expl_vel));
1916
1917         // set up rotational vel
1918         vector rotvel;
1919         vm_vec_rand_vec_quick(&rotvel);
1920         rotvel.xyz.z = 0.0f;
1921         vm_vec_normalize(&rotvel);
1922         vm_vec_scale(&rotvel, 0.15f / speed_reduction_factor);
1923         split_ship->front_ship.phys_info.rotvel = rotvel;
1924         vm_vec_copy_scale(&split_ship->back_ship.phys_info.rotvel, &rotvel, -(front_length*front_length)/(back_length*back_length));
1925         split_ship->front_ship.phys_info.rotvel.xyz.z = parent_ship_obj->phys_info.rotvel.xyz.z;
1926         split_ship->back_ship.phys_info.rotvel.xyz.z  = parent_ship_obj->phys_info.rotvel.xyz.z;
1927
1928
1929         // modify vel of each split ship based on rotvel of parent ship obj
1930         vector temp_rotvel = parent_ship_obj->phys_info.rotvel;
1931         temp_rotvel.xyz.z = 0.0f;
1932         vector vel_from_rotvel;
1933         vm_vec_crossprod(&vel_from_rotvel, &temp_rotvel, &split_ship->front_ship.local_pivot);
1934         //      vm_vec_scale_add2(&split_ship->front_ship.phys_info.vel, &vel_from_rotvel, 0.5f);
1935         vm_vec_crossprod(&vel_from_rotvel, &temp_rotvel, &split_ship->back_ship.local_pivot);
1936         //      vm_vec_scale_add2(&split_ship->back_ship.phys_info.vel, &vel_from_rotvel, 0.5f);
1937
1938         // set up velocity and make initial fireballs and particles
1939         split_ship->front_ship.phys_info.vel = parent_ship_obj->phys_info.vel;
1940         split_ship->back_ship.phys_info.vel  = parent_ship_obj->phys_info.vel;
1941         maybe_fireball_wipe(&split_ship->front_ship, (int*)&split_ship->sound_handle);
1942         maybe_fireball_wipe(&split_ship->back_ship,  (int*)&split_ship->sound_handle);
1943         vm_vec_scale_add2(&split_ship->front_ship.phys_info.vel, &orient->v.fvec, front_vel);
1944         vm_vec_scale_add2(&split_ship->back_ship.phys_info.vel,  &orient->v.fvec, back_vel);
1945
1946         // HANDLE LIVE DEBRIS - blow off if not already gone
1947         shipfx_maybe_create_live_debris_at_ship_death( parent_ship_obj );
1948 }
1949
1950
1951 static void half_ship_render_ship_and_debris(clip_ship* half_ship,ship *shipp)
1952 {
1953         Assert( Split_ships_inited );
1954
1955         polymodel *pm = model_get(shipp->modelnum);
1956
1957         // get rotated clip plane normal and world coord of original ship center
1958         vector orig_ship_world_center, clip_plane_norm, model_clip_plane_pt, debris_clip_plane_pt;
1959         vm_vec_unrotate(&clip_plane_norm, &half_ship->clip_plane_norm, &half_ship->orient);
1960         vm_vec_unrotate(&orig_ship_world_center, &half_ship->model_center_disp_to_orig_center, &half_ship->orient);
1961         vm_vec_add2(&orig_ship_world_center, &half_ship->local_pivot);
1962
1963         // *out_pivot = orig_ship_world_center;
1964
1965         // get debris clip plane pt and draw debris
1966         vm_vec_unrotate(&debris_clip_plane_pt, &half_ship->model_center_disp_to_orig_center, &half_ship->orient);
1967         vm_vec_add2(&debris_clip_plane_pt, &half_ship->local_pivot);
1968         g3_start_user_clip_plane( &debris_clip_plane_pt, &clip_plane_norm);
1969
1970         // set up render flags
1971         uint render_flags = MR_NORMAL;
1972
1973         for (int i=0; i<pm->num_debris_objects; i++ )   {
1974                 // draw DEBRIS_FREE in test only
1975                 if (half_ship->draw_debris[i] == DEBRIS_DRAW) {
1976                         vector temp_pos = orig_ship_world_center;
1977                         vector tmp = {0.0f, 0.0f, 0.0f};
1978                         vector tmp1 = pm->submodel[pm->debris_objects[i]].offset;
1979
1980                         // determine if explosion front has past debris piece
1981                         // 67 ~ dist expl moves in 2 frames -- maybe fraction works better
1982                         int is_live_debris = pm->submodel[pm->debris_objects[i]].is_live_debris;
1983                         int create_debris = 0;
1984                         // front ship
1985                         if (half_ship->explosion_vel > 0) {
1986                                 if (half_ship->cur_clip_plane_pt > tmp1.xyz.z + pm->submodel[pm->debris_objects[i]].max.xyz.z - 0.1f*half_ship->explosion_vel) {
1987                                         create_debris = 1;
1988                                 }
1989                                 // is the debris visible
1990 //                              if (half_ship->cur_clip_plane_pt > tmp1.xyz.z + pm->submodel[pm->debris_objects[i]].min.xyz.z - 0.5f*half_ship->explosion_vel) {
1991 //                                      render_debris = 1;
1992 //                              }
1993                         // back ship
1994                         } else {
1995                                 if (half_ship->cur_clip_plane_pt < tmp1.xyz.z + pm->submodel[pm->debris_objects[i]].min.xyz.z - 0.1f*half_ship->explosion_vel) {
1996                                         create_debris = 1;
1997                                 }
1998                                 // is the debris visible
1999 //                              if (half_ship->cur_clip_plane_pt < tmp1.xyz.z + pm->submodel[pm->debris_objects[i]].max.xyz.z - 0.5f*half_ship->explosion_vel) {
2000 //                                      render_debris = 1;
2001 //                              }
2002                         }
2003
2004                         // Draw debris, but not live debris
2005                         if ( !is_live_debris ) {
2006                                 model_find_world_point(&tmp, &tmp1, shipp->modelnum, -1, &half_ship->orient, &temp_pos);
2007                                 submodel_render(shipp->modelnum, pm->debris_objects[i], &half_ship->orient, &tmp, render_flags);
2008                         }
2009
2010                         // make free piece of debris
2011                         if ( create_debris ) {
2012                                 half_ship->draw_debris[i] = DEBRIS_FREE;                // mark debris to not render with model
2013                                 vector center_to_debris, debris_vel, radial_vel;
2014                                 // check if last debris piece, ie, debris_count == 0
2015                                 int debris_count = 0;
2016                                 for (int j=0; j<pm->num_debris_objects; j++ ) {
2017                                         if (half_ship->draw_debris[j] == DEBRIS_DRAW) {
2018                                                 debris_count++;
2019                                         }
2020                                 } 
2021                                 // do debris create here, but not for live debris
2022                                 // debris vel (1) split ship vel (2) split ship rotvel (3) random
2023                                 if ( !is_live_debris ) {
2024                                         object* debris_obj;
2025                                         debris_obj = debris_create(half_ship->parent_obj, shipp->modelnum, pm->debris_objects[i], &tmp, &half_ship->local_pivot, 1, 1.0f);
2026                                         // AL: make sure debris_obj isn't NULL!
2027                                         if ( debris_obj ) {
2028                                                 vm_vec_scale(&debris_obj->phys_info.rotvel, 4.0f);
2029                                                 debris_obj->orient = half_ship->orient;
2030                                                 // if (debris_count > 0) {
2031                                                         //mprintf(( "base rotvel %.1f, debris rotvel mag %.2f\n", vm_vec_mag(&half_ship->phys_info.rotvel), vm_vec_mag(&debris_obj->phys_info.rotvel) ));
2032                                                         vm_vec_sub(&center_to_debris, &tmp, &half_ship->local_pivot);
2033                                                         vm_vec_crossprod(&debris_vel, &center_to_debris, &half_ship->phys_info.rotvel);
2034                                                         vm_vec_add2(&debris_vel, &half_ship->phys_info.vel);
2035                                                         vm_vec_copy_normalize(&radial_vel, &center_to_debris);
2036                                                         float radial_mag = 10.0f + 30.0f*frand();
2037                                                         vm_vec_scale_add2(&debris_vel, &radial_vel, radial_mag);
2038                                                         debris_obj->phys_info.vel = debris_vel;
2039                                                 /* } else {
2040                                                         debris_obj->phys_info.vel = half_ship->phys_info.vel;
2041                                                         debris_obj->phys_info.rotvel = half_ship->phys_info.rotvel;
2042                                                 } */
2043                                         }
2044                                 }
2045                         }
2046                 }
2047         }
2048
2049         // get model clip plane pt and draw model
2050         vector temp;
2051         (void) vm_vec_make(&temp, 0.0f, 0.0f, half_ship->cur_clip_plane_pt);
2052         vm_vec_unrotate(&model_clip_plane_pt, &temp, &half_ship->orient);
2053         vm_vec_add2(&model_clip_plane_pt, &orig_ship_world_center);
2054         g3_start_user_clip_plane( &model_clip_plane_pt, &clip_plane_norm );
2055         model_render(shipp->modelnum, &half_ship->orient, &orig_ship_world_center, render_flags);
2056 }
2057
2058 void shipfx_large_blowup_level_init()
2059 {
2060         split_ship_init_system();
2061
2062         if(Ship_cannon_bitmap != -1){
2063                 bm_unload(Ship_cannon_bitmap);
2064                 Ship_cannon_bitmap = bm_load(SHIP_CANNON_BITMAP);
2065         }
2066 }
2067
2068 // Returns 0 if couldn't init
2069 int shipfx_large_blowup_init(ship *shipp)
2070 {
2071
2072         if ( !Split_ships_inited )      {
2073                 split_ship_init_system();
2074         }
2075
2076         int i;
2077         for (i=0; i<MAX_SPLIT_SHIPS; i++ )      {
2078                 if ( Split_ships[i].used == 0 ) {
2079                         break;
2080                 }
2081         }
2082
2083         if ( i >= MAX_SPLIT_SHIPS )     {
2084                 mprintf(( "Not enough split ship slots!! See John!\n" ));
2085                 Int3();
2086                 return 0;
2087         }
2088
2089         Split_ships[i].used = 1;
2090         shipp->large_ship_blowup_index = i;
2091
2092         split_ship_init(shipp, &Split_ships[i] );
2093         
2094         return 1;
2095 }
2096
2097 // ----------------------------------------------------------------------------
2098 // uses list of model z values with constant increment to find the radius of the 
2099 // cross section at the current model z value
2100 float get_model_cross_section_at_z(float z, polymodel* pm)
2101 {
2102         if (pm->num_xc < 2) {
2103                 return 0.0f;
2104         }
2105
2106         float index, increment;
2107         increment = (pm->xc[pm->num_xc-1].z - pm->xc[0].z) / (float)(pm->num_xc - 1);
2108         index = (z - pm->xc[0].z) / increment;
2109
2110         if (index < 0.5f) {
2111                 return pm->xc[0].radius;
2112         } else if (index > (pm->num_xc - 1.0f - 0.5f)) {
2113                 return pm->xc[pm->num_xc-1].radius;
2114         } else {
2115                 int floor_index = (int)floor(index);
2116                 int ceil_index  = (int)ceil(index);
2117                 return max(pm->xc[ceil_index].radius, pm->xc[floor_index].radius);
2118         }
2119 }
2120
2121 // returns how long sound has been playing
2122 int get_sound_time_played(int snd_id, int handle)
2123 {
2124         if (handle == -1) {
2125                 return 100000;
2126         }
2127
2128         int bits_per_sample, frequency;
2129         snd_get_format(snd_id, &bits_per_sample, &frequency);
2130         int time_left = snd_time_remaining(handle, bits_per_sample, frequency);
2131         int duration = snd_get_duration(snd_id);
2132         
2133         return (duration - time_left);
2134 }
2135
2136 // sound manager for big ship sub explosions sounds.
2137 // forces playing of sub-explosion sounds.  keeps track of active sounds, plays them for >= 750 ms
2138 // when sound has played >= 750, sound is stopped and new instance is started 
2139 void do_sub_expl_sound(float radius, vector* sound_pos, int* sound_handle)
2140 {
2141         int sound_index, handle;
2142         // multiplier for range (near and far distances) to apply attenuation
2143         float sound_range = 1.0f + 0.0043f*radius;
2144
2145         int handle_index = rand()%NUM_SUB_EXPL_HANDLES;
2146         //mprintf(("handle_index %d\n", *handle_index));
2147
2148         // sound_index = get_sub_explosion_sound_index(handle_index);
2149         sound_index = SND_SHIP_EXPLODE_1;
2150         handle = sound_handle[handle_index];
2151
2152
2153         // mprintf(("dist to sound %.1f snd_indx: %d, h1: %d, h2: %d\n", vm_vec_dist(&Player_obj->pos, sound_pos), next_sound_index, sound_handle[0], sound_handle[1]));
2154
2155         if (handle == -1) {
2156                 // if no handle, get one
2157                 sound_handle[handle_index] = snd_play_3d( &Snds[sound_index], sound_pos, &View_position, 0.0f, NULL, 0, 0.6f, SND_PRIORITY_MUST_PLAY, NULL, sound_range );
2158         } else if (!snd_is_playing(handle)) {
2159                 // if sound not playing and old, get new one
2160                 // I don't think will happen with SND_PRIORITY_MUST_PLAY
2161                 if (get_sound_time_played(Snds[sound_index].id, handle) > 400) {
2162                         //mprintf(("sound not playing %d, time_played %d, stopped\n", handle, get_sound_time_played(Snds[sound_index].id, handle)));
2163                         snd_stop(sound_handle[handle_index]);
2164                         sound_handle[handle_index] = snd_play_3d( &Snds[sound_index], sound_pos, &View_position, 0.0f, NULL, 0, 0.6f, SND_PRIORITY_MUST_PLAY, NULL, sound_range );
2165                 }
2166         } else if (get_sound_time_played(Snds[sound_index].id, handle) > 750) {
2167                 //mprintf(("time %f, cur sound %d time_played %d num sounds %d\n", f2fl(Missiontime), handle_index, get_sound_time_played(Snds[sound_index].id, handle), snd_num_playing() ));
2168                 sound_handle[handle_index] = snd_play_3d( &Snds[sound_index], sound_pos, &View_position, 0.0f, NULL, 0, 0.6f, SND_PRIORITY_MUST_PLAY, NULL, sound_range );
2169         }
2170 }
2171
2172 // maybe create a fireball along model clip plane
2173 // also maybe plays explosion sound
2174 static void maybe_fireball_wipe(clip_ship* half_ship, int* sound_handle)
2175 {
2176         // maybe make fireball to cover wipe.
2177         if ( timestamp_elapsed(half_ship->next_fireball) ) {
2178                 if ( half_ship->length_left > 0.2f*fl_abs(half_ship->explosion_vel) )   {
2179
2180                         polymodel* pm = model_get(Ships[half_ship->parent_obj->instance].modelnum);
2181
2182                         vector model_clip_plane_pt, orig_ship_world_center, temp;
2183
2184                         vm_vec_unrotate(&orig_ship_world_center, &half_ship->model_center_disp_to_orig_center, &half_ship->orient);
2185                         vm_vec_add2(&orig_ship_world_center, &half_ship->local_pivot);
2186
2187                         (void) vm_vec_make(&temp, 0.0f, 0.0f, half_ship->cur_clip_plane_pt);
2188                         vm_vec_unrotate(&model_clip_plane_pt, &temp, &half_ship->orient);
2189                         vm_vec_add2(&model_clip_plane_pt, &orig_ship_world_center);
2190                         vm_vec_rand_vec_quick(&temp);
2191                         vm_vec_scale(&temp, 0.1f*frand());
2192                         vm_vec_add2(&model_clip_plane_pt, &temp);
2193
2194                         float rad = get_model_cross_section_at_z(half_ship->cur_clip_plane_pt, pm);
2195                         if (rad < 1) {
2196                                 rad = half_ship->parent_obj->radius * frand_range(0.4f, 0.6f);
2197                         } else {
2198                                 // make fireball radius (1.5 +/- .1) * model_cross_section value
2199                                 rad *= frand_range(1.4f, 1.6f);
2200                         }
2201
2202                         rad *= 1.5f;
2203                         rad = min(rad, half_ship->parent_obj->radius);
2204
2205                         // mprintf(("xc %.1f model %.1f\n", rad, half_ship->parent_obj->radius*0.25));
2206                         int fireball_type = FIREBALL_EXPLOSION_LARGE1 + rand()%FIREBALL_NUM_LARGE_EXPLOSIONS;
2207                         int low_res_fireballs = Bs_exp_fire_low;
2208                         fireball_create(&model_clip_plane_pt, fireball_type, OBJ_INDEX(half_ship->parent_obj), rad, 0, &half_ship->parent_obj->phys_info.vel, 0.0f, -1, NULL, low_res_fireballs);
2209
2210                         // start the next fireball up (3-4 per frame) + 30%
2211                         int time_low, time_high;
2212                         time_low = int(650 * Bs_exp_fire_time_mult);
2213                         time_high = int(900 * Bs_exp_fire_time_mult);
2214                         half_ship->next_fireball = timestamp_rand(time_low, time_high);
2215
2216                         // do sound
2217                         do_sub_expl_sound(half_ship->parent_obj->radius, &model_clip_plane_pt, sound_handle);
2218
2219                         // do particles
2220                         particle_emitter        pe;
2221
2222                         pe.num_low = 40;                                        // Lowest number of particles to create
2223                         pe.num_high = 80;                               // Highest number of particles to create
2224                         pe.pos = model_clip_plane_pt;   // Where the particles emit from
2225                         pe.vel = half_ship->phys_info.vel;              // Initial velocity of all the particles
2226
2227 #ifdef FS2_DEMO
2228                         float range = 1.0f + 0.002f*half_ship->parent_obj->radius * 5.0f;
2229 #else 
2230                         float range = 1.0f + 0.002f*half_ship->parent_obj->radius;
2231 #endif
2232
2233 #ifdef FS2_DEMO
2234                         pe.min_life = 2.0f*range;                               // How long the particles live
2235                         pe.max_life = 10.0f*range;                              // How long the particles live
2236 #else
2237                         pe.min_life = 0.5f*range;                               // How long the particles live
2238                         pe.max_life = 6.0f*range;                               // How long the particles live
2239 #endif
2240                         pe.normal = vmd_x_vector;               // What normal the particle emit around
2241                         pe.normal_variance = 2.0f;              //      How close they stick to that normal 0=on normal, 1=180, 2=360 degree
2242                         pe.min_vel = 0.0f;                              // How fast the slowest particle can move
2243                         pe.max_vel = half_ship->explosion_vel;                          // How fast the fastest particle can move
2244
2245 #ifdef FS2_DEMO
2246                         float scale = half_ship->parent_obj->radius * 0.02f;
2247 #else
2248                         float scale = half_ship->parent_obj->radius * 0.01f;
2249 #endif
2250                         pe.min_rad = 0.5f*scale;                                // Min radius
2251                         pe.max_rad = 1.5f*scale;                                // Max radius
2252
2253                         particle_emit( &pe, PARTICLE_SMOKE2, 0, range );
2254
2255                 } else {
2256                         // time out forever
2257                         half_ship->next_fireball = timestamp(-1);
2258                 }
2259         }
2260 }
2261
2262
2263 // Returns 1 when explosion is done
2264 int shipfx_large_blowup_do_frame(ship *shipp, float frametime)
2265 {
2266         // DAVE:  I made this not do any movement just to try to get things working...
2267         // return 0;
2268
2269         Assert( Split_ships_inited );
2270         Assert( shipp->large_ship_blowup_index > -1 );
2271
2272         split_ship *the_split_ship = &Split_ships[shipp->large_ship_blowup_index];
2273         Assert( the_split_ship->used );         // Get John
2274
2275         // Do fireballs, particles, shockwave here
2276         // Note parent ship is still valid, vel and pos updated in obj_move_all
2277
2278         if ( timestamp_elapsed(the_split_ship->explosion_flash_timestamp) ) {
2279                 if ( !the_split_ship->explosion_flash_started ) {
2280                         object* objp = &Objects[shipp->objnum];
2281                         if (objp->flags & OF_WAS_RENDERED) {
2282                                 float excess_dist = vm_vec_dist(&Player_obj->pos, &objp->pos) - 2.0f*objp->radius - Player_obj->radius;
2283                                 float intensity = 1.0f - 0.1f*excess_dist / objp->radius;
2284
2285                                 if (intensity > 1) {
2286                                         intensity = 1.0f;
2287                                 }
2288
2289                                 if (intensity > 0.1f) {
2290                                         // big_explosion_flash(intensity);
2291                                 }
2292                         }
2293                         the_split_ship->explosion_flash_started = 1;
2294                 }
2295         }
2296
2297         physics_sim(&the_split_ship->front_ship.local_pivot, &the_split_ship->front_ship.orient, &the_split_ship->front_ship.phys_info, frametime);
2298         physics_sim(&the_split_ship->back_ship.local_pivot,  &the_split_ship->back_ship.orient,  &the_split_ship->back_ship.phys_info,  frametime);
2299         the_split_ship->front_ship.length_left -= the_split_ship->front_ship.explosion_vel*frametime;
2300         the_split_ship->back_ship.length_left  += the_split_ship->back_ship.explosion_vel *frametime;
2301         the_split_ship->front_ship.cur_clip_plane_pt += the_split_ship->front_ship.explosion_vel*frametime;
2302         the_split_ship->back_ship.cur_clip_plane_pt  += the_split_ship->back_ship.explosion_vel *frametime;
2303
2304         float length_left = max( the_split_ship->front_ship.length_left, the_split_ship->back_ship.length_left );
2305
2306         //      mprintf(( "Blowup frame, dist = %.1f \n", length_left ));
2307
2308         if ( length_left < 0 )  {
2309                 the_split_ship->used = 0;
2310                 return 1;
2311         }
2312
2313         maybe_fireball_wipe(&the_split_ship->front_ship, (int*)&the_split_ship->sound_handle);
2314         maybe_fireball_wipe(&the_split_ship->back_ship,  (int*)&the_split_ship->sound_handle);
2315         return 0;
2316 }
2317
2318 void shipfx_large_blowup_render(ship* shipp)
2319 {
2320 // This actually renders the original model like it should render.
2321 //      object *objp = &Objects[shipp->objnum];
2322 //      model_render( shipp->modelnum, &objp->orient, &objp->pos, MR_NORMAL );
2323 //      return;
2324
2325         Assert( Split_ships_inited );
2326         Assert( shipp->large_ship_blowup_index > -1 );
2327
2328         split_ship *the_split_ship = &Split_ships[shipp->large_ship_blowup_index];
2329         Assert( the_split_ship->used );         // Get John
2330
2331         // vector front_global_pivot, back_global_pivot;
2332
2333         if (the_split_ship->front_ship.length_left > 0) {
2334                 half_ship_render_ship_and_debris(&the_split_ship->front_ship,shipp);
2335         }
2336
2337         if (the_split_ship->back_ship.length_left > 0) {
2338                 half_ship_render_ship_and_debris(&the_split_ship->back_ship,shipp);
2339         }
2340
2341         g3_stop_user_clip_plane();                      
2342 }
2343
2344
2345 // ================== DO THE ELECTRIC ARCING STUFF =====================
2346 // Creates any new ones, moves old ones.
2347
2348 #define MAX_ARC_LENGTH_PERCENTAGE 0.25f
2349
2350 #define MAX_EMP_ARC_TIMESTAMP            (150.0f)
2351
2352 void shipfx_do_damaged_arcs_frame( ship *shipp )
2353 {
2354         int i;
2355         int should_arc;
2356         object *obj = &Objects[shipp->objnum];
2357         ship_info * sip = &Ship_info[shipp->ship_info_index];
2358
2359         should_arc = 1;
2360
2361         float damage = obj->hull_strength / sip->initial_hull_strength; 
2362
2363         if (damage < 0) {
2364                 damage = 0.0f;
2365         }
2366
2367         // don't draw an arc based on damage
2368         if ( damage > 0.30f )   {
2369                 // Don't do spark.
2370                 should_arc = 0;
2371         }
2372
2373         // we should draw an arc
2374         if( shipp->emp_intensity > 0.0f){
2375                 should_arc = 1;
2376         }
2377
2378         // Kill off old sparks
2379         for(i=0; i<MAX_SHIP_ARCS; i++){
2380                 if(timestamp_valid(shipp->arc_timestamp[i]) && timestamp_elapsed(shipp->arc_timestamp[i])){                     
2381                         shipp->arc_timestamp[i] = timestamp(-1);
2382                 }
2383         }
2384
2385         // if we shouldn't draw an arc, return
2386         if(!should_arc){
2387                 return;
2388         }
2389
2390         if (!timestamp_valid(shipp->arc_next_time))     {
2391                 // start the next fireball up in the next 10 seconds or so... 
2392                 int freq;
2393                 
2394                 // if the emp effect is active
2395                 if(shipp->emp_intensity > 0.0f){
2396                         freq = fl2i(MAX_EMP_ARC_TIMESTAMP);
2397                 }
2398                 // otherwise if we're arcing based upon damage
2399                 else {
2400                         freq = fl2i((damage+0.1f)*5000.0f);
2401                 }
2402
2403                 // set the next arc time
2404                 shipp->arc_next_time = timestamp_rand(freq*2,freq*4);
2405         }
2406
2407         if ( timestamp_elapsed(shipp->arc_next_time) )  {
2408
2409                 shipp->arc_next_time = timestamp(-1);           // invalid, so it gets restarted next frame
2410
2411                 //mprintf(( "Creating new ship arc!\n" ));
2412
2413                 int n, n_arcs = ((rand()>>5) % 3)+1;            // Create 1-3 sparks
2414
2415                 vector v1, v2, v3, v4;
2416                 submodel_get_two_random_points( shipp->modelnum, -1, &v1, &v2 );
2417                 submodel_get_two_random_points( shipp->modelnum, -1, &v3, &v4 );
2418
2419                 // For large ships, cap the length to be 25% of max radius
2420                 if ( obj->radius > 200.0f )     {
2421                         float max_dist = obj->radius * MAX_ARC_LENGTH_PERCENTAGE;
2422                         
2423                         vector tmp;
2424                         float d;
2425
2426                         // Cap arc 2->1
2427                         vm_vec_sub( &tmp, &v1, &v2 );
2428                         d = vm_vec_mag_quick( &tmp );
2429                         if ( d > max_dist )     {
2430                                 vm_vec_scale_add( &v1, &v2, &tmp, max_dist / d );
2431                         }
2432
2433                         // Cap arc 2->3
2434                         vm_vec_sub( &tmp, &v3, &v2 );
2435                         d = vm_vec_mag_quick( &tmp );
2436                         if ( d > max_dist )     {
2437                                 vm_vec_scale_add( &v3, &v2, &tmp, max_dist / d );
2438                         }
2439
2440
2441                         // Cap arc 2->4
2442                         vm_vec_sub( &tmp, &v4, &v2 );
2443                         d = vm_vec_mag_quick( &tmp );
2444                         if ( d > max_dist )     {
2445                                 vm_vec_scale_add( &v4, &v2, &tmp, max_dist / d );
2446                         }
2447                         
2448                 }
2449                 
2450                 n = 0;
2451
2452 //              int a = 100, b = 1000;
2453                 float factor = 1.0f + 0.0025f*obj->radius;
2454                 int a = (int) (factor*100.0f);
2455                 int b = (int) (factor*1000.0f);
2456                 int lifetime = (myrand()%((b)-(a)+1))+(a);
2457
2458                 // Create the arc effects
2459                 for (i=0; i<MAX_SHIP_ARCS; i++ )        {
2460                         if ( !timestamp_valid( shipp->arc_timestamp[i] ) )      {
2461                                 //shipp->arc_timestamp[i] = timestamp_rand(400,1000);   // live up to a second
2462                                 shipp->arc_timestamp[i] = timestamp(lifetime);  // live up to a second
2463
2464                                 switch( n )     {
2465                                 case 0:
2466                                         shipp->arc_pts[i][0] = v1;
2467                                         shipp->arc_pts[i][1] = v2;
2468                                         break;
2469                                 case 1:
2470                                         shipp->arc_pts[i][0] = v2;
2471                                         shipp->arc_pts[i][1] = v3;
2472                                         break;
2473
2474                                 case 2:
2475                                         shipp->arc_pts[i][0] = v2;
2476                                         shipp->arc_pts[i][1] = v4;
2477                                         break;
2478
2479                                 default:
2480                                         Int3();
2481                                 }
2482
2483                                 // determine what kind of arc to create
2484                                 if(shipp->emp_intensity > 0.0f){
2485                                         shipp->arc_type[i] = MARC_TYPE_EMP;
2486                                 } else {
2487                                         shipp->arc_type[i] = MARC_TYPE_NORMAL;
2488                                 }
2489                                         
2490                                 n++;
2491                                 if ( n == n_arcs )
2492                                         break;  // Don't need to create anymore
2493                         }
2494         
2495                         // rotate v2 out of local coordinates into world.
2496                         // Use v2 since it is used in every bolt.  See above switch().
2497                         vector snd_pos;
2498                         vm_vec_unrotate(&snd_pos, &v2, &obj->orient);
2499                         vm_vec_add2(&snd_pos, &obj->pos );
2500
2501                         //Play a sound effect
2502                         if ( lifetime > 750 )   {
2503                                 // 1.00 second effect
2504                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_05], &snd_pos, &View_position, obj->radius );
2505                         } else if ( lifetime >  500 )   {
2506                                 // 0.75 second effect
2507                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_04], &snd_pos, &View_position, obj->radius );
2508                         } else if ( lifetime >  250 )   {
2509                                 // 0.50 second effect
2510                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_03], &snd_pos, &View_position, obj->radius );
2511                         } else if ( lifetime >  100 )   {
2512                                 // 0.25 second effect
2513                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_02], &snd_pos, &View_position, obj->radius );
2514                         } else {
2515                                 // 0.10 second effect
2516                                 snd_play_3d( &Snds[SND_DEBRIS_ARC_01], &snd_pos, &View_position, obj->radius );
2517                         }
2518                 }
2519         }
2520
2521         // maybe move arc points around
2522         for (i=0; i<MAX_SHIP_ARCS; i++ )        {
2523                 if ( timestamp_valid( shipp->arc_timestamp[i] ) )       {
2524                         if ( !timestamp_elapsed( shipp->arc_timestamp[i] ) )    {                                                       
2525                                 // Maybe move a vertex....  20% of the time maybe?
2526                                 int mr = myrand();
2527                                 if ( mr < RAND_MAX/5 )  {
2528                                         vector v1, v2;
2529                                         submodel_get_two_random_points( shipp->modelnum, -1, &v1, &v2 );
2530
2531                                         vector static_one;
2532
2533                                         if ( mr % 2 )   {
2534                                                 static_one = shipp->arc_pts[i][0];
2535                                         } else {
2536                                                 static_one = shipp->arc_pts[i][1];
2537                                         }
2538
2539                                         // For large ships, cap the length to be 25% of max radius
2540                                         if ( obj->radius > 200.0f )     {
2541                                                 float max_dist = obj->radius * MAX_ARC_LENGTH_PERCENTAGE;
2542                                                 
2543                                                 vector tmp;
2544                                                 float d;
2545
2546                                                 // Cap arc 2->1
2547                                                 vm_vec_sub( &tmp, &v1, &static_one );
2548                                                 d = vm_vec_mag_quick( &tmp );
2549                                                 if ( d > max_dist )     {
2550                                                         vm_vec_scale_add( &v1, &static_one, &tmp, max_dist / d );
2551                                                 }
2552                                         }
2553
2554                                         shipp->arc_pts[i][mr % 2] = v1;
2555                                 }
2556                         }
2557                 }
2558         }
2559 }
2560
2561 int l_cruiser_count = 1;
2562 int l_big_count = 2;
2563 int l_huge_count = 3;
2564 float l_max_radius = 3000.0f;
2565 void shipfx_do_lightning_frame( ship *shipp )
2566 {
2567         /*
2568         ship_info *sip;
2569         object *objp;
2570         int stamp, count;
2571         vector v1, v2, n1, n2, temp, temp2;
2572         bolt_info binfo;
2573
2574         // sanity checks
2575         Assert(shipp != NULL);
2576         if(shipp == NULL){
2577                 return;
2578         } 
2579         Assert(shipp->ship_info_index >= 0);
2580         if(shipp->ship_info_index < 0){
2581                 return;
2582         }       
2583         Assert(shipp->objnum >= 0);
2584         if(shipp->objnum < 0){
2585                 return;
2586         }       
2587
2588         // get some pointers
2589         sip = &Ship_info[shipp->ship_info_index];
2590         objp = &Objects[shipp->objnum]; 
2591
2592         // if this is not a nebula mission, don't do anything
2593         if(!(The_mission.flags & MISSION_FLAG_FULLNEB)){
2594                 shipp->lightning_stamp = -1;
2595                 return;
2596         }
2597         
2598         // if this not a cruiser or big ship
2599         if(!((sip->flags & SIF_CRUISER) || (sip->flags & SIF_BIG_SHIP) || (sip->flags & SIF_HUGE_SHIP))){
2600                 shipp->lightning_stamp = -1;
2601                 return;
2602         }
2603
2604         // determine stamp and count values
2605         if(sip->flags & SIF_CRUISER){
2606                 stamp = (int)((float)(Nebl_cruiser_min + ((Nebl_cruiser_max - Nebl_cruiser_min) * Nebl_intensity)) * frand_range(0.8f, 1.1f));
2607                 count = l_cruiser_count;
2608         } 
2609         else {
2610                 if(sip->flags & SIF_HUGE_SHIP){
2611                         stamp = (int)((float)(Nebl_supercap_min + ((Nebl_supercap_max - Nebl_supercap_min) * Nebl_intensity)) * frand_range(0.8f, 1.1f));
2612                         count = l_huge_count;
2613                 } else {
2614                         stamp = (int)((float)(Nebl_cap_min + ((Nebl_cap_max - Nebl_cap_min) * Nebl_intensity)) * frand_range(0.8f, 1.1f));
2615                         count = l_big_count;
2616                 }
2617         }
2618
2619         // if his timestamp is unset
2620         if(shipp->lightning_stamp == -1){
2621                 shipp->lightning_stamp = timestamp(stamp);
2622                 return;
2623         }
2624         // if his timestamp is currently unelapsed
2625         if(!timestamp_elapsed(shipp->lightning_stamp)){
2626                 return;
2627         }
2628
2629         mprintf(("SHIP BOLT\n"));
2630
2631         // restamp him first
2632         shipp->lightning_stamp = timestamp(stamp);
2633
2634         // ah, now we can create some lightning bolts
2635         count = (int)frand_range(0.0f, (float)count);
2636         while(count > 0){
2637                 // get 2 points on the hull of the ship
2638                 submodel_get_two_random_points(shipp->modelnum, 0, &v1, &v2, &n1, &n2);         
2639
2640                 // make up to 2 bolts
2641                 if(objp->radius > l_max_radius){
2642                         vm_vec_scale_add(&temp2, &v1, &n1, l_max_radius);
2643                 } else {
2644                         vm_vec_scale_add(&temp2, &v1, &n1, objp->radius);
2645                 }
2646                 vm_vec_unrotate(&temp, &temp2, &objp->orient);
2647                 vm_vec_add2(&temp, &objp->pos);
2648                 vm_vec_unrotate(&temp2, &v1, &objp->orient);
2649                 vm_vec_add2(&temp2, &objp->pos);
2650
2651                 // create the bolt
2652                 binfo.start = temp;
2653                 binfo.strike = temp2;
2654                 binfo.num_strikes = 3;
2655                 binfo.noise = 0.045f;
2656                 binfo.life = 375;
2657                 binfo.delay = (int)frand_range(0.0f, 1600.0f);
2658                 nebl_bolt(&binfo);
2659                 count--;
2660         
2661                 // done
2662                 if(count <= 0){
2663                         break;
2664                 }
2665
2666                 // one more             
2667                 if(objp->radius > l_max_radius){
2668                         vm_vec_scale_add(&temp2, &v2, &n2, l_max_radius);
2669                 } else {
2670                         vm_vec_scale_add(&temp2, &v2, &n2, objp->radius);
2671                 }
2672                 vm_vec_unrotate(&temp, &temp2, &objp->orient);
2673                 vm_vec_add2(&temp, &objp->pos);
2674                 vm_vec_unrotate(&temp2, &v2, &objp->orient);
2675                 vm_vec_add2(&temp2, &objp->pos);
2676
2677                 // create the bolt
2678                 binfo.start = temp;
2679                 binfo.strike = temp2;
2680                 binfo.num_strikes = 3;
2681                 binfo.noise = 0.045f;
2682                 binfo.life = 375;
2683                 binfo.delay = (int)frand_range(0.0f, 1600.0f);
2684                 nebl_bolt(&binfo);              
2685                 count--;
2686         }
2687         */
2688 }
2689
2690 // do all shockwaves for a ship blowing up
2691 void shipfx_do_shockwave_stuff(ship *shipp, shockwave_create_info *sci)
2692 {
2693         ship_info *sip;
2694         object *objp;
2695         polymodel *pm;
2696         vector temp, dir, shockwave_pos;
2697         vector head = vmd_zero_vector;
2698         vector tail = vmd_zero_vector;  
2699         float len, step, cur;
2700         int idx;
2701
2702         // sanity checks
2703         Assert(shipp != NULL);
2704         if(shipp == NULL){
2705                 return;
2706         } 
2707         Assert(shipp->ship_info_index >= 0);
2708         if(shipp->ship_info_index < 0){
2709                 return;
2710         }       
2711         Assert(shipp->objnum >= 0);
2712         if(shipp->objnum < 0){
2713                 return;
2714         }
2715         Assert(sci != NULL);
2716         if (sci == NULL) {
2717                 return;
2718         }
2719
2720         // get some pointers
2721         sip = &Ship_info[shipp->ship_info_index];
2722         objp = &Objects[shipp->objnum]; 
2723
2724         Assert(sip->shockwave_count > 0);
2725         if(sip->shockwave_count <= 0){
2726                 return;
2727         }
2728
2729         // get vectors at the head and tail of the object, dead center          
2730         pm = model_get(shipp->modelnum);
2731         if(pm == NULL){
2732                 return;
2733         }
2734         head.xyz.x = pm->submodel[0].offset.xyz.x;
2735         head.xyz.y = pm->submodel[0].offset.xyz.y;
2736         head.xyz.z = pm->maxs.xyz.z;
2737
2738         tail.xyz.x = pm->submodel[0].offset.xyz.x;
2739         tail.xyz.y = pm->submodel[0].offset.xyz.y;
2740         tail.xyz.z = pm->mins.xyz.z;
2741
2742         // transform the vectors into world coords
2743         vm_vec_unrotate(&temp, &head, &objp->orient);
2744         vm_vec_add(&head, &temp, &objp->pos);
2745         vm_vec_unrotate(&temp, &tail, &objp->orient);
2746         vm_vec_add(&tail, &temp, &objp->pos);
2747
2748         // now create as many shockwaves as needed
2749         vm_vec_sub(&dir, &head, &tail);
2750         len = vm_vec_mag(&dir);
2751         step = 1.0f / ((float)sip->shockwave_count + 1.0f);
2752         cur = step;
2753         for(idx=0; idx<sip->shockwave_count; idx++){
2754                 // get the shockwave position           
2755                 temp = dir;
2756                 vm_vec_scale(&temp, cur);
2757                 vm_vec_add(&shockwave_pos, &tail, &temp);
2758
2759                 // if knossos device, make shockwave in center
2760                 if (Ship_info[shipp->ship_info_index].flags & SIF_KNOSSOS_DEVICE) {
2761                         shockwave_pos = Objects[shipp->objnum].pos;
2762                 }
2763
2764                 // create the shockwave
2765                 shockwave_create_info sci2;
2766                 sci2.blast = (sci->blast / (float)sip->shockwave_count) * frand_range(0.75f, 1.25f);
2767                 sci2.damage = (sci->damage / (float)sip->shockwave_count) * frand_range(0.75f, 1.25f);
2768                 sci2.inner_rad = sci->inner_rad;
2769                 sci2.outer_rad = sci->outer_rad;
2770                 sci2.speed = sci->speed * frand_range(0.75f, 1.25f);
2771                 sci2.rot_angle = frand_range(0.0f, 359.0f);
2772
2773                 shockwave_create(shipp->objnum, &shockwave_pos, &sci2, SW_SHIP_DEATH, (int)frand_range(0.0f, 350.0f));
2774                 // shockwave_create(shipp->objnum, &objp->pos, sip->shockwave_speed, sip->inner_rad, sip->outer_rad, sip->damage, sip->blast, SW_SHIP_DEATH);
2775
2776                 // next shockwave
2777                 cur += step;
2778         }
2779 }
2780
2781 int Wash_on = 1;
2782 DCF_BOOL(engine_wash, Wash_on);
2783 #define ENGINE_WASH_CHECK_INTERVAL              250     // (4x sec)
2784 // Do engine wash effect for ship
2785 // Assumes length of engine wash is greater than radius of engine wash hemisphere
2786 void engine_wash_ship_process(ship *shipp)
2787 {
2788         int idx, j;             
2789         object *objp, *ship_objp, *max_ship_intensity_objp;
2790         int started_with_no_wash = shipp->wash_intensity <= 0 ? 1 : 0;
2791
2792         if (!Wash_on) {
2793                 return;
2794         }
2795
2796         Assert(shipp != NULL);
2797         Assert(shipp->objnum >= 0);
2798         objp = &Objects[shipp->objnum];
2799         ship_obj *so;
2800         ship_objp = NULL;
2801
2802         vector world_thruster_pos, world_thruster_norm, apex, thruster_to_ship, apex_to_ship, temp;
2803         float dist_sqr, inset_depth, dot_to_ship, max_ship_intensity;
2804         polymodel *pm;
2805
2806         float max_wash_dist, half_angle, radius_mult;
2807
2808         // if this is not a fighter or bomber, we don't care
2809         if ((objp->type != OBJ_SHIP) || !(Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER|SIF_BOMBER)) ) {
2810                 return;
2811         }
2812
2813         // is it time to check for engine wash 
2814         int time_to_next_hit = timestamp_until(shipp->wash_timestamp);
2815         if (time_to_next_hit < 0) {
2816                 if (time_to_next_hit < -ENGINE_WASH_CHECK_INTERVAL) {
2817                         time_to_next_hit = 0;
2818                 }
2819
2820                 // keep interval constant independent of framerate
2821                 shipp->wash_timestamp = timestamp(ENGINE_WASH_CHECK_INTERVAL + time_to_next_hit);
2822
2823                 // initialize wash params
2824                 shipp->wash_intensity = 0.0f;
2825                 vm_vec_zero(&shipp->wash_rot_axis);
2826                 max_ship_intensity_objp = NULL;
2827                 max_ship_intensity = 0;
2828         } else {
2829                 return;
2830         }
2831
2832         // only do damage if we're within half of the max wash distance
2833         int do_damage = 0;
2834
2835         // go thru Ship_used_list and check if we're in wash from CAP or SUPERCAP (SIF_HUGE)
2836         for (so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so)) {
2837                 ship_objp = &Objects[so->objnum];
2838
2839                 // don't do small ships
2840                 if ( (Ship_info[Ships[ship_objp->instance].ship_info_index].flags & SIF_SMALL_SHIP) ) {
2841                         continue;
2842                 }
2843
2844                 pm = model_get(Ships[ship_objp->instance].modelnum);
2845                 float ship_intensity = 0;
2846
2847                 // if engines disabled, no engine wash
2848                 if (ship_get_subsystem_strength(&Ships[ship_objp->instance], SUBSYSTEM_ENGINE) < 0.01) {
2849                         continue;
2850                 }
2851
2852                 float   speed_scale;
2853                 if (ship_objp->phys_info.speed > 20.0f)
2854                         speed_scale = 1.0f;
2855                 else
2856                         speed_scale = ship_objp->phys_info.speed/20.0f;
2857
2858                 for (idx = 0; idx < pm->n_thrusters; idx++) {
2859                         thruster_bank *bank = &pm->thrusters[idx];
2860
2861                         // check if thruster bank has engine wash
2862                         if (bank->wash_info_index < 0) {
2863                                 // if huge, give default engine wash
2864                                 if (Ship_info[Ships[ship_objp->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
2865                                         bank->wash_info_index = 0;
2866                                         nprintf(("wash", "Adding default engine wash to ship %s", Ship_info[Ships[ship_objp->instance].ship_info_index].name));
2867                                 } else {
2868                                         continue;
2869                                 }
2870                         }
2871
2872                         engine_wash_info *ewp = &Engine_wash_info[bank->wash_info_index];
2873                         half_angle = ewp->angle;
2874                         radius_mult = ewp->radius_mult;
2875
2876                         for (j=0; j<bank->num_slots; j++) {
2877                                 // get world pos of thruster
2878                                 vm_vec_unrotate(&world_thruster_pos, &bank->pnt[j], &ship_objp->orient);
2879                                 vm_vec_add2(&world_thruster_pos, &ship_objp->pos);
2880                                 
2881                                 // get world norm of thruster;
2882                                 vm_vec_unrotate(&world_thruster_norm, &bank->norm[j], &ship_objp->orient);
2883
2884                                 // get vector from thruster to ship
2885                                 vm_vec_sub(&thruster_to_ship, &objp->pos, &world_thruster_pos);
2886
2887                                 // check if on back side of thruster
2888                                 dot_to_ship = vm_vec_dotprod(&thruster_to_ship, &world_thruster_norm);
2889                                 if (dot_to_ship > 0) {
2890
2891                                         // get max wash distance
2892                                         max_wash_dist = max(ewp->length, bank->radius[j]*ewp->radius_mult);
2893
2894                                         // check if within dist range
2895                                         dist_sqr = vm_vec_mag_squared(&thruster_to_ship);
2896                                         if (dist_sqr < max_wash_dist*max_wash_dist) {
2897
2898                                                 // check if inside the sphere
2899                                                 if (dist_sqr < radius_mult*radius_mult*bank->radius[j]*bank->radius[j]) {
2900                                                         vm_vec_crossprod(&temp, &world_thruster_norm, &thruster_to_ship);
2901                                                         vm_vec_scale_add2(&shipp->wash_rot_axis, &temp, dot_to_ship / dist_sqr);
2902 //                                                      shipp->wash_intensity += (1.0f - dist_sqr / (max_wash_dist*max_wash_dist));
2903                                                         ship_intensity += (1.0f - dist_sqr / (max_wash_dist*max_wash_dist));
2904                                                         if (!do_damage) {
2905                                                                 if (dist_sqr < 0.25 * max_wash_dist * max_wash_dist) {
2906                                                                         do_damage = 1;
2907                                                                 }
2908                                                         }
2909                                                 } else {
2910                                                         // check if inside cone - first fine apex of cone
2911                                                         inset_depth = float(bank->radius[j] / tan(half_angle));
2912                                                         vm_vec_scale_add(&apex, &world_thruster_pos, &world_thruster_norm, -inset_depth);
2913                                                         vm_vec_sub(&apex_to_ship, &objp->pos, &apex);
2914                                                         vm_vec_normalize(&apex_to_ship);
2915
2916                                                         // check if inside cone angle
2917                                                         if (vm_vec_dotprod(&apex_to_ship, &world_thruster_norm) > cos(half_angle)) {
2918                                                                 vm_vec_crossprod(&temp, &world_thruster_norm, &thruster_to_ship);
2919                                                                 vm_vec_scale_add2(&shipp->wash_rot_axis, &temp, dot_to_ship / dist_sqr);
2920 //                                                              shipp->wash_intensity += (1.0f - dist_sqr / (max_wash_dist*max_wash_dist));
2921                                                                 ship_intensity += (1.0f - dist_sqr / (max_wash_dist*max_wash_dist));
2922                                                                 if (!do_damage) {
2923                                                                         if (dist_sqr < 0.25 * max_wash_dist * max_wash_dist) {
2924                                                                                 do_damage = 1;
2925                                                                         }
2926                                                                 }
2927                                                         }
2928                                                 }
2929                                         }
2930                                 }
2931                         }
2932                 }
2933                 shipp->wash_intensity += ship_intensity * speed_scale;
2934                 if (ship_intensity > max_ship_intensity) {
2935                         max_ship_intensity = ship_intensity;
2936                         max_ship_intensity_objp = ship_objp;
2937                 }
2938         }
2939
2940         // apply damage at rate of 1%/sec
2941         if (shipp->wash_intensity > 0) {
2942                 Assert(max_ship_intensity_objp != NULL);
2943
2944                 nprintf(("wash", "Wash intensity %.2f\n", shipp->wash_intensity));
2945
2946                 float damage;
2947                 if (!do_damage) {
2948                         damage = 0;
2949                 } else {
2950                         damage = (0.001f * 0.003f * ENGINE_WASH_CHECK_INTERVAL * Ship_info[shipp->ship_info_index].initial_hull_strength * shipp->wash_intensity);
2951                 }
2952
2953                 ship_apply_wash_damage(&Objects[shipp->objnum], max_ship_intensity_objp, damage);
2954
2955                 // if we had no wash before now, add the wash object sound
2956                 if(started_with_no_wash){
2957                         if(shipp != Player_ship){
2958                                 obj_snd_assign(shipp->objnum, SND_ENGINE_WASH, &vmd_zero_vector, 1);
2959                         } else {                                
2960                                 Player_engine_wash_loop = snd_play_looping( &Snds[SND_ENGINE_WASH], 0.0f , -1, -1, 1.0f);
2961                         }
2962                 }
2963         } 
2964         // if we've got no wash, kill any wash object sounds from this guy
2965         else {
2966                 if(shipp != Player_ship){
2967                         obj_snd_delete(shipp->objnum, SND_ENGINE_WASH);
2968                 } else {
2969                         snd_stop(Player_engine_wash_loop);
2970                         Player_engine_wash_loop = -1;
2971                 }
2972         }
2973 }
2974
2975 // engine wash level init
2976 void shipfx_engine_wash_level_init()
2977 {
2978         Player_engine_wash_loop = -1;
2979 }
2980
2981 // pause engine wash sounds
2982 void shipfx_stop_engine_wash_sound()
2983 {
2984         if(Player_engine_wash_loop != -1){
2985                 snd_stop(Player_engine_wash_loop);
2986                 Player_engine_wash_loop = -1;
2987         }
2988 }