]> icculus.org git repositories - taylor/freespace2.git/blob - src/physics/physics.cpp
Initial revision
[taylor/freespace2.git] / src / physics / physics.cpp
1 /*
2  * $Logfile: /Freespace2/code/Physics/Physics.cpp $
3  * $Revision$
4  * $Date$
5  * $Author$
6  *
7  * Physics stuff
8  *
9  * $Log$
10  * Revision 1.1  2002/05/03 03:28:10  root
11  * Initial revision
12  *
13  * 
14  * 5     8/13/99 10:49a Andsager
15  * Knossos and HUGE ship warp out.  HUGE ship warp in.  Stealth search
16  * modes dont collide big ships.
17  * 
18  * 4     7/03/99 5:50p Dave
19  * Make rotated bitmaps draw properly in padlock views.
20  * 
21  * 3     5/11/99 10:16p Andsager
22  * First pass on engine wash effect.  Rotation (control input), damage,
23  * shake.  
24  * 
25  * 2     10/07/98 10:53a Dave
26  * Initial checkin.
27  * 
28  * 1     10/07/98 10:50a Dave
29  * 
30  * 125   8/26/98 4:00p Johnson
31  * Removed max velocity assert so the new huge cap ship can warp in
32  * safely.
33  * 
34  * 124   5/18/98 5:01p Comet
35  * don't do displacement checks in multiplayer
36  * 
37  * 123   4/06/98 2:38p Duncan
38  * AL: Fix potential negative sqrt due to numerical inaccuracy
39  * 
40  * 122   3/25/98 1:30p Andsager
41  * comment out physics assert
42  * 
43  * 121   3/23/98 9:48a Andsager
44  * comment out printf
45  * 
46  * 120   3/22/98 4:11p Andsager
47  * Remove global Freespace_running
48  * 
49  * 119   3/20/98 5:15p Andsager
50  * Revised calculation of rotation, shake, and velocity in response to
51  * shockwave since capital ships were seen  to shake.
52  * 
53  * 118   3/19/98 1:06p Andsager
54  * Fix bug checking excessive velocity with accelerated time.
55  * 
56  * 117   3/17/98 5:43p Andsager
57  * Modify physics checks for very slow frame rates.
58  * 
59  * 116   3/17/98 9:54a Andsager
60  * Temporary take out Int3()s in velocity checks
61  * 
62  * 115   3/17/98 9:51a Allender
63  * temporarily commented out Int3 that was causing pain
64  * 
65  * 114   3/16/98 6:07p Johnson
66  * DA:  check that ship velocity does not get too high from collisons
67  * 
68  * 113   3/16/98 4:39p Adam
69  * change Dave's asserts so that displacement checks don't get used when
70  * not "in mission"
71  * 
72  * 112   3/16/98 1:11p Andsager
73  * Turn on velocity, displacement limit checks
74  * 
75  * 111   3/12/98 5:21p Andsager
76  * Optimize physics for lasers and dumbfire missiles
77  * 
78  * 110   3/09/98 2:10p Andsager
79  * Put in checks for debris (other) with excessive velocity.
80  * 
81  * 109   3/09/98 12:59p Mike
82  * Put error checking in physics code to detect NANs.
83  * 
84  * 108   3/09/98 12:13a Andsager
85  * Add code to help find jumps in position.
86  * 
87  * 107   3/03/98 10:39a Andsager
88  * Fixed erroneous mprintf for log term in physics_apply_shock
89  * 
90  * 106   2/11/98 4:52p Mike
91  * Better attacking by ships.
92  * Fix stupidity in AI classes, which were in backward order!
93  * 
94  * 105   2/03/98 6:01p Andsager
95  * Fix excessive rotvel in debris_create.  Check using physics function
96  * check_rotvel_limit.
97  * 
98  * 104   2/03/98 10:45a Mike
99  * Comment out mprintf that could occur very often.
100  * 
101  * 103   1/29/98 2:38p Andsager
102  * Fix bug in physics_apply_shock so that large ships have a smaller
103  * effect from shockwaves.
104  * 
105  * 102   1/23/98 11:31a Andsager
106  * Added I_body_inv to phys_init.  Needed for shockwaves hitting ships in
107  * descent style physics.
108  * 
109  * 101   1/23/98 9:02a John
110  * Took out Dave's debugging Int3 since they aren't finding what he
111  * thought they would and they broke Testcode and pofview.
112  * 
113  * 100   1/22/98 5:10p Mike
114  * Fix bug with player's damp getting stuck off.
115  * 
116  * 99    1/20/98 3:13p Allender
117  * check for Player_obj being valid before doing some other andsager
118  * sanity check in physics_sim_vel
119  * 
120  * 98    1/20/98 10:08a Andsager
121  * Remove uninitialized viariable warnings.
122  * 
123  * 97    1/19/98 3:46p Allender
124  * fixed problem where a previous changed caused optimized builds to
125  * break.  Don't do a quick out on velcoity_ramp() anymore
126  * 
127  * 96    1/19/98 12:00p Dave
128  * DA:  Revise instantaneous velocity debug check to work with
129  * multiplayer.
130  * 
131  * 95    1/16/98 3:03p Andsager
132  * Fix debug info from int3() on player death.
133  * 
134  * 94    1/16/98 2:54p Andsager
135  * Fix debug info.
136  * 
137  * 93    1/16/98 2:34p Andsager
138  * Added debug code to find instantaneous acceleration.
139  * 
140  * 92    1/16/98 12:14p Andsager
141  * Add error checking for the current brief stage
142  * 
143  * 91    12/29/97 5:10p Allender
144  * fixed problems with speed not being reported properly in multiplayer
145  * games.  Made read_flying_controls take frametime as a parameter.  More
146  * ship/weapon select stuff
147  * 
148  * 90    12/29/97 12:58p Johnson
149  * don't debug rotational velocity when Fred is running
150  * 
151  * 89    12/08/97 10:29a Andsager
152  * Remove shockwave physics parameters from weapon_area_apply_blast and
153  * move into physics
154  * 
155  * 88    12/05/97 3:31p Andsager
156  * Added view shake if hit by a weapon or collisoin.
157  * 
158  * 87    12/03/97 5:47p Andsager
159  * Changed reduced damping following collision or weapon to run off time
160  * stamp. 
161  * 
162  * 86    11/24/97 1:54p Dan
163  * Mike: Comment out Assert() in physics, debug_rotvel().
164  * 
165  * 85    11/24/97 8:46a Andsager
166  * Added rotational velocity caps and debug info.
167  * 
168  * 84    11/20/97 4:01p Mike
169  * Prevent divide overflow.
170  * 
171  * 83    11/20/97 12:34a Mike
172  * Make ships coast to a stop when their engines have been destroyed.
173  * Tricky because code doesn't use damp in forward dimension.
174  * 
175  * 82    11/19/97 5:57p Mike
176  * Hmm, undid all my changes, except for the crucial removal of a blank
177  * between "physics_sim" and the open paren.
178  * 
179  * 81    11/19/97 1:26a Andsager
180  * Made shockwaves work again, including shake.
181  * 
182  * 80    11/17/97 5:15p Andsager
183  * 
184  * 79    11/13/97 6:01p Andsager
185  * Improve comment in physic_collide_whack
186  * 
187  * 78    11/13/97 5:41p Andsager
188  * Decreased the rotational whack after getting hit by lasers and
189  * missiles.
190  * 
191  * 77    10/29/97 5:01p Andsager
192  * fixed bug in collision physics (physics_collide_whack)
193  * 
194  * 76    9/16/97 5:28p Andsager
195  * calculate velocity in physics_sim_vel
196  * 
197  * 75    9/11/97 5:25p Mike
198  * Fix ! vs. & precedence bug in physics_sim_vel().
199  * 
200  * 74    9/09/97 10:14p Andsager
201  * 
202  * 73    9/04/97 5:09p Andsager
203  * implement physics using moment of inertia and mass (from BSPgen).
204  * Added to phys_info struct.  Updated ship_info, polymodel structs.
205  * Updated weapon ($Mass and $Force) and ship ($Mass -> $Density) tables
206  * 
207  * 72    9/03/97 5:43p Andsager
208  * fixed bug calculating ramp velocity after getting whacked
209  * 
210  * 71    9/02/97 4:19p Mike
211  * Comment out code at end of physics_apply_whack() that made ships nearly
212  * stop.
213  * 
214  * 70    8/29/97 10:13a Allender
215  * work on server/client prediction code -- doesn't work too well.  Made
216  * all clients simulate their own orientation with the server giving
217  * corrections every so often.
218  * 
219  * 69    8/25/97 2:41p Andsager
220  * collision code also changes ramp velocity to take account of collison.
221  * some optimization of collision physics.
222  * 
223  * 68    8/19/97 9:56a John
224  * new thruster effect fairly functional
225  * 
226  * 67    8/18/97 6:26p Andsager
227  * preliminary version of collision physics
228  * 
229  * 66    8/17/97 9:19p Andsager
230  * improvement to collision physics
231  * 
232  * 65    8/13/97 12:16p Andsager
233  * intermediate level checkin for use with collision with extended objects
234  * 
235  * 64    8/05/97 3:13p Andsager
236  * improved comments to apply_whack
237  * 
238  * 63    8/05/97 10:18a Lawrance
239  * my_rand() being used temporarily instead of rand()
240  * 
241  * 62    7/31/97 12:44p Andsager
242  * 
243  * 61    7/25/97 5:05p John
244  * fixed a potential bug in ramp_velocity when delta dist becomes 0, a
245  * bunch of sideways 8 thingys appear :-)
246  * 
247  * 
248  * 60    7/25/97 1:04p Andsager
249  * Modified physics flag PF_REDUCED_DAMP for damping when object is hit.
250  * Flag is now set in physics_apply_whack/shock and turned off in
251  * physics_sim_vel.  Weapons should not directly set this flag.
252  * 
253  * 59    7/25/97 9:07a Andsager
254  * modified apply_whack
255  * 
256  * 58    7/23/97 5:10p Andsager
257  * Enhanced shockwave effect with shake based on blast force.  
258  * 
259  * 57    7/22/97 2:40p Andsager
260  * shockwaves now cause proper rotation of ships
261  * 
262  * 56    7/21/97 4:12p Mike
263  * Two ships move as one while docked, including physics whacks.  Spin of
264  * objects when killed based on speed.
265  * 
266  * 55    7/21/97 2:19p John
267  * made descent-style physics work for testcode. fixed bug in the
268  * velocity_ramp code with t==0.0f
269  * 
270  * 54    7/17/97 8:02p Lawrance
271  * improve comments to physics_apply_whack()
272  * 
273  * 53    7/16/97 4:42p Mike
274  * Make afterburner shake viewer, not ship.
275  * Shake for limited time.
276  * Add timestamp_until() function to timer library.
277  * 
278  * 52    7/16/97 11:53a Andsager
279  * 
280  * 51    7/16/97 11:06a Andsager
281  * Allow damping on z to support shockwaves
282  * 
283  * 50    7/15/97 12:28p Andsager
284  * commented out some debug code.
285  * 
286  * 49    7/15/97 12:25p Andsager
287  * More integration with new physics.
288  * 
289  * 48    7/15/97 12:03p Andsager
290  * New physics stuff
291  * 
292  * 47    7/11/97 11:54a John
293  * added rotated 3d bitmaps.
294  * 
295  * 46    6/25/97 12:22p Mike
296  * Diminish bashing into of objects.  Make ships flying waypoints fly in
297  * formation.
298  * 
299  * 45    6/17/97 10:59p Mike
300  * Comment out irritating mprintf().
301  * 
302  * 44    6/11/97 4:27p Mike
303  * Balance the whack ships take when they get hit.
304  * 
305  * 43    4/17/97 10:02a Lawrance
306  * allow ship shaking for ABURN_DECAY_TIME after afterburners cut out
307  * 
308  * 42    4/16/97 10:48p Mike
309  * Afterburner shake.
310  * Made afterburner engagement a bit in physics flags, removed from ship
311  * flags, removed a parameter to physics_read_flying_controls().
312  * 
313  * 41    4/11/97 3:17p Mike
314  * Modify physics_sim() to use non quick version of vm_vec_mag().  Quick
315  * version was causing cumulative errors in velocity of homing missiles.
316  * 
317  * 40    4/10/97 3:20p Mike
318  * Change hull damage to be like shields.
319  * 
320  * 39    4/04/97 11:08a Adam
321  * played with banking values
322  * 
323  * 38    4/04/97 12:19a Mike
324  * Make ships bank when they turn.
325  * 
326  * 37    3/04/97 3:10p Mike
327  * Intermediate checkin: Had to resolve some build errors.  Working on two
328  * docked ships moving as one.
329  * 
330  * 36    2/25/97 7:39p Lawrance
331  * added afterburner_on flag to physics_read_flying_controls() to account
332  * for afterburner effects
333  * 
334  * 35    2/05/97 6:02p Hoffoss
335  * Added heading rotation around universal Y axis to Fred when controlling
336  * the camera.
337  * 
338  * 34    2/05/97 9:15a Mike
339  * Partial implementation of new docking system, integrated so I could
340  * update on John's new turret code.
341  * 
342  * 33    1/20/97 7:58p John
343  * Fixed some link errors with testcode.
344  * 
345  * $NoKeywords: $
346  */
347
348 #include <stdio.h>
349 #include <stdlib.h>
350 #include <string.h>
351 #include <math.h>
352
353 #include "physics.h"
354 #include "floating.h"
355 #include "player.h"
356 #include "freespace.h"
357 #include "linklist.h"
358 #include "timer.h"
359 #include "key.h"
360
361 // defines for physics functions
362 #define MAX_TURN_LIMIT  0.2618f         // about 15 degrees
363
364 #define ROT_DEBUG
365 #define ROTVEL_TOL              0.1                     // Amount of rotvel is decreased if over cap
366 #define ROTVEL_CAP              14.0                    // Rotational velocity cap for live objects
367 #define DEAD_ROTVEL_CAP 16.3                    // Rotational velocity cap for dead objects
368
369 #define MAX_SHIP_SPEED          300             // Maximum speed allowed after whack or shockwave
370 #define RESET_SHIP_SPEED        240             // Speed that a ship is reset to after exceeding MAX_SHIP_SPEED
371
372 #define SW_ROT_FACTOR                   5               // increase in rotational time constant in shockwave
373 #define SW_BLAST_DURATION               2000    // maximum duration of shockwave
374 #define REDUCED_DAMP_FACTOR     10              // increase in side_slip and acceleration time constants (scaled according to reduced damp time)
375 #define REDUCED_DAMP_VEL                30              // change in velocity at which reduced_damp_time is 2000 ms
376 #define REDUCED_DAMP_TIME               2000    // ms (2.0 sec)
377 #define WEAPON_SHAKE_TIME               500     //      ms (0.5 sec)    viewer shake time after hit by weapon (implemented via afterburner shake)
378 #define SPECIAL_WARP_T_CONST    0.651   // special warp time constant (loose 99 % of excess speed in 3 sec)
379
380 #define PHYS_DEBUG                                              // check if (vel > 500) or (displacement in one frame > 350)
381
382 void update_reduced_damp_timestamp( physics_info *pi, float impulse );
383
384 void physics_init( physics_info * pi )
385 {
386         memset( pi, 0, sizeof(physics_info) );
387
388         pi->mass = 10.0f;                                       // This ship weighs 10 units
389         pi->side_slip_time_const = 0.05f;                                       
390         pi->rotdamp = 0.1f;
391
392         pi->max_vel.x = 100.0f;         //sideways
393         pi->max_vel.y = 100.0f;         //up/down
394         pi->max_vel.z = 100.0f;         //forward
395         pi->max_rear_vel = 100.0f;      //backward -- controlled seperately
396
397         pi->max_rotvel.x = 2.0f;                //pitch 
398         pi->max_rotvel.y = 1.0f;                //heading
399         pi->max_rotvel.z = 2.0f;                //bank
400
401         pi->prev_ramp_vel.x = 0.0f;
402         pi->prev_ramp_vel.y = 0.0f;
403         pi->prev_ramp_vel.z = 0.0f;
404
405         pi->desired_vel.x = 0.0f;
406         pi->desired_vel.y = 0.0f;
407         pi->desired_vel.z = 0.0f;
408
409         pi->slide_accel_time_const=pi->side_slip_time_const;    // slide using max_vel.x & .y
410         pi->slide_decel_time_const=pi->side_slip_time_const;    // slide using max_vel.x & .y
411
412         pi->afterburner_decay = 1;      
413         pi->forward_thrust = 0.0f;
414
415         pi->flags = 0;
416
417         // default values for moment of inetaia
418         vm_vec_make( &pi->I_body_inv.rvec, 1e-5f, 0.0f, 0.0f );
419         vm_vec_make( &pi->I_body_inv.uvec, 0.0f, 1e-5f, 0.0f );
420         vm_vec_make( &pi->I_body_inv.fvec, 0.0f, 0.0f, 1e-5f );
421
422 }
423
424
425 //==========================================================================
426 // apply_physics - This does correct physics independent of frame rate.
427 //
428 // Given:
429 //    damping = damping factor.  Setting this to zero make the object instantly
430 //              go to the target velocity.  Increasing it makes the object ramp
431 //              up or down to the target velocity.
432 //    desired_vel = the target velocity
433 //    initial_vel = velocity at last call
434 //    t = elapsed time since last call
435 //
436 // Returns:
437 //    new_vel = current velocity
438 //    delta_pos = delta position (framevec)
439 // You can extend this to 3d by calling it 3 times, once for each x,y,z component.
440
441 void apply_physics( float damping, float desired_vel, float initial_vel, float t, float * new_vel, float * delta_pos )
442 {
443         if ( damping < 0.0001f )        {
444                 if ( delta_pos )
445                         *delta_pos = desired_vel*t;
446                 if ( new_vel )
447                         *new_vel = desired_vel;
448         } else {
449                 float dv, e;
450                 dv = initial_vel - desired_vel;
451                 e = (float)exp( -t/damping );
452                 if ( delta_pos )
453                         *delta_pos = (1.0f - e)*dv*damping + desired_vel*t;
454                 if ( new_vel )
455                         *new_vel = dv*e + desired_vel;
456         }
457 }
458
459
460
461 float Physics_viewer_bank = 0.0f;
462 int Physics_viewer_direction = PHYSICS_VIEWER_FRONT;
463 static physics_info * Viewer_physics_info = NULL;
464
465 // If you would like Physics_viewer_bank to be tracked (Which is needed
466 // for rotating 3d bitmaps) call this and pass it a pointer to the
467 // viewer's physics info.
468 void physics_set_viewer( physics_info * p, int dir )
469 {
470         if ( (Viewer_physics_info != p) || (Physics_viewer_direction != dir) )  {
471                 Viewer_physics_info = p;
472                 Physics_viewer_bank = 0.0f;
473                 Physics_viewer_direction = dir;
474         }
475 }
476
477
478
479 //      -----------------------------------------------------------------------------------------------------------
480 // add rotational velocity & acceleration
481
482
483
484 void physics_sim_rot(matrix * orient, physics_info * pi, float sim_time )
485 {
486         angles  tangles;
487         vector  new_vel;
488         matrix  tmp;
489         float           shock_amplitude;
490         float           rotdamp;
491         float           shock_fraction_time_left;
492
493         Assert(is_valid_matrix(orient));
494         Assert(is_valid_vec(&pi->rotvel));
495         Assert(is_valid_vec(&pi->desired_rotvel));
496
497         // Handle special case of shockwave
498         shock_amplitude = 0.0f;
499         if ( pi->flags & PF_IN_SHOCKWAVE ) {
500                 if ( timestamp_elapsed(pi->shockwave_decay) ) {
501                         pi->flags &= ~PF_IN_SHOCKWAVE;
502                         rotdamp = pi->rotdamp;
503                 } else {
504                         shock_fraction_time_left = timestamp_until( pi->shockwave_decay ) / (float) SW_BLAST_DURATION;
505                         rotdamp = pi->rotdamp + pi->rotdamp * (SW_ROT_FACTOR - 1) * shock_fraction_time_left;
506                         shock_amplitude = pi->shockwave_shake_amp * shock_fraction_time_left;
507                 }
508         } else {
509                 rotdamp = pi->rotdamp;
510         }
511
512         // Do rotational physics with given damping
513         apply_physics( rotdamp, pi->desired_rotvel.x, pi->rotvel.x, sim_time, &new_vel.x, NULL );
514         apply_physics( rotdamp, pi->desired_rotvel.y, pi->rotvel.y, sim_time, &new_vel.y, NULL );
515         apply_physics( rotdamp, pi->desired_rotvel.z, pi->rotvel.z, sim_time, &new_vel.z, NULL );
516
517         /*
518 #ifdef ROT_DEBUG
519         if (check_rotvel_limit( pi )) {
520                 nprintf(("Physics", "rotvel reset in physics_sim_rot\n"));
521         }
522 #endif
523 */
524         Assert(is_valid_vec(&new_vel));
525
526         pi->rotvel = new_vel;
527
528         tangles.p = pi->rotvel.x*sim_time;
529         tangles.h = pi->rotvel.y*sim_time;
530         tangles.b = pi->rotvel.z*sim_time;
531
532         // If this is the viewer_object, keep track of the
533         // changes in banking so that rotated bitmaps look correct.
534         // This is used by the g3_draw_rotated_bitmap function.
535         if ( pi == Viewer_physics_info )        {
536                 switch(Physics_viewer_direction){
537                 case PHYSICS_VIEWER_FRONT:                              
538                         Physics_viewer_bank -= tangles.b;
539                         break;
540
541                 case PHYSICS_VIEWER_UP:
542                         Physics_viewer_bank -= tangles.h;
543                         break;
544
545                 case PHYSICS_VIEWER_REAR:
546                         Physics_viewer_bank += tangles.b;
547                         break;
548
549                 case PHYSICS_VIEWER_LEFT:
550                         Physics_viewer_bank += tangles.p;
551                         break;
552
553                 case PHYSICS_VIEWER_RIGHT:
554                         Physics_viewer_bank -= tangles.p;
555                         break;
556
557                 default:
558                         Physics_viewer_bank -= tangles.b;
559                         break;
560                 }
561
562                 if ( Physics_viewer_bank < 0.0f ){
563                         Physics_viewer_bank += 2.0f * PI;
564                 }
565
566                 if ( Physics_viewer_bank > 2.0f * PI ){
567                         Physics_viewer_bank -= 2.0f * PI;
568                 }
569         }
570
571 /*      //      Make ship shake due to afterburner.
572         if (pi->flags & PF_AFTERBURNER_ON || !timestamp_elapsed(pi->afterburner_decay) ) {
573                 float   max_speed;
574
575                 max_speed = vm_vec_mag_quick(&pi->max_vel);
576                 tangles.p += (float) (rand()-RAND_MAX/2)/RAND_MAX * pi->speed/max_speed/64.0f;
577                 tangles.h += (float) (rand()-RAND_MAX/2)/RAND_MAX * pi->speed/max_speed/64.0f;
578                 if ( pi->flags & PF_AFTERBURNER_ON ) {
579                         pi->afterburner_decay = timestamp(ABURN_DECAY_TIME);
580                 }
581         }
582 */
583
584         // Make ship shake due to shockwave, decreasing in amplitude at the end of the shockwave
585         if ( pi->flags & PF_IN_SHOCKWAVE ) {
586                 tangles.p += (float) (myrand()-RAND_MAX/2)/RAND_MAX * shock_amplitude;
587                 tangles.h += (float) (myrand()-RAND_MAX/2)/RAND_MAX * shock_amplitude;
588         }
589
590
591         vm_angles_2_matrix(&pi->last_rotmat, &tangles );
592         vm_matrix_x_matrix( &tmp, orient, &pi->last_rotmat );
593         *orient = tmp;
594
595         vm_orthogonalize_matrix(orient);
596                 
597 }
598
599 //      -----------------------------------------------------------------------------------------------------------
600 // add rotational velocity & acceleration
601
602 void physics_sim_rot_editor(matrix * orient, physics_info * pi, float sim_time)
603 {
604         angles  tangles;
605         vector  new_vel;
606         matrix  tmp;
607         angles  t1, t2;
608
609         apply_physics( pi->rotdamp, pi->desired_rotvel.x, pi->rotvel.x, sim_time, 
610                                                                  &new_vel.x, NULL );
611
612         apply_physics( pi->rotdamp, pi->desired_rotvel.y, pi->rotvel.y, sim_time, 
613                                                                  &new_vel.y, NULL );
614
615         apply_physics( pi->rotdamp, pi->desired_rotvel.z, pi->rotvel.z, sim_time, 
616                                                                  &new_vel.z, NULL );
617         
618         pi->rotvel = new_vel;
619
620         tangles.p = pi->rotvel.x*sim_time;
621         tangles.h = pi->rotvel.y*sim_time;
622         tangles.b = pi->rotvel.z*sim_time;
623
624         t1 = t2 = tangles;
625         t1.h = 0.0f;  t1.b = 0.0f;
626         t2.p = 0.0f; t2.b = 0.0f;
627
628         // put in p & b like normal
629         vm_angles_2_matrix(&pi->last_rotmat, &t1 );
630         vm_matrix_x_matrix( &tmp, orient, &pi->last_rotmat );
631         
632         // Put in heading separately
633         vm_angles_2_matrix(&pi->last_rotmat, &t2 );
634         vm_matrix_x_matrix( orient, &pi->last_rotmat, &tmp );
635
636         vm_orthogonalize_matrix(orient);
637                 
638 }
639
640 // Adds velocity to position
641 // finds velocity and displacement in local coords
642 void physics_sim_vel(vector * position, physics_info * pi, float sim_time, matrix *orient)
643 {
644         vector local_disp;              // displacement in this frame
645         vector local_v_in;              // velocity in local coords at the start of this frame
646         vector local_desired_vel;       // desired velocity in local coords
647         vector local_v_out;             // velocity in local coords following this frame
648         vector damp;
649
650         //      Maybe clear the reduced_damp flag.
651         //      This fixes the problem of the player getting near-instantaneous acceleration under unknown circumstances.
652         //      The larger problem is probably that PF_USE_VEL is getting stuck set.
653         if ((pi->flags & PF_REDUCED_DAMP) && (timestamp_elapsed(pi->reduced_damp_decay))) {
654                 pi->flags &= ~PF_REDUCED_DAMP;
655         }
656
657         // Set up damping constants based on special conditions
658         // ie. shockwave, collision, weapon, dead
659         if (pi->flags & PF_DEAD_DAMP) {
660                 // side_slip_time_const is already quite large and now needs to be applied in all directions
661                 vm_vec_make( &damp, pi->side_slip_time_const, pi->side_slip_time_const, pi->side_slip_time_const );
662
663         } else if (pi->flags & PF_REDUCED_DAMP) {
664                 // case of shock, weapon, collide, etc.
665                 if ( timestamp_elapsed(pi->reduced_damp_decay) ) {
666                         vm_vec_make( &damp, pi->side_slip_time_const, pi->side_slip_time_const, 0.0f );
667                 } else {
668                         // damp is multiplied by fraction and not fraction^2, gives better collision separation
669                         float reduced_damp_fraction_time_left = timestamp_until( pi->reduced_damp_decay ) / (float) REDUCED_DAMP_TIME;
670                         damp.x = pi->side_slip_time_const * ( 1 + (REDUCED_DAMP_FACTOR-1) * reduced_damp_fraction_time_left );
671                         damp.y = pi->side_slip_time_const * ( 1 + (REDUCED_DAMP_FACTOR-1) * reduced_damp_fraction_time_left );
672                         damp.z = pi->side_slip_time_const * reduced_damp_fraction_time_left * REDUCED_DAMP_FACTOR;
673                 }
674         } else {
675                 // regular damping
676                 vm_vec_make( &damp, pi->side_slip_time_const, pi->side_slip_time_const, 0.0f );
677         }
678
679         // Note: CANNOT maintain a *local velocity* since a rotation can occur in this frame. 
680         // thus the local velocity of in the next frame can be different (this would require rotate to change local vel
681         // and this is not desired
682
683         // get local components of current velocity
684         vm_vec_rotate (&local_v_in, &pi->vel, orient);
685
686         // get local components of desired velocity
687         vm_vec_rotate (&local_desired_vel, &pi->desired_vel, orient);
688
689         // find updated LOCAL velocity and position in the local x direction
690         apply_physics (damp.x, local_desired_vel.x, local_v_in.x, sim_time, &local_v_out.x, &local_disp.x);
691
692         // find updated LOCAL velocity and position in the local y direction
693         apply_physics (damp.y, local_desired_vel.y, local_v_in.y, sim_time, &local_v_out.y, &local_disp.y);
694
695         // find updated LOCAL velocity and position in the local z direction
696         // for player ship, damp should normally be zero, but may be altered in a shockwave
697         //  in death, shockwave,etc. we want damping time const large for all 3 axes
698         // warp in test - make excessive speed drop exponentially from max allowed
699         // become (0.01x in 3 sec)
700
701         int special_warp_in = FALSE;
702         float excess = local_v_in.z - pi->max_vel.z;
703         if (excess > 5 && (pi->flags & PF_SPECIAL_WARP_IN)) {
704                 special_warp_in = TRUE;
705                 float exp_factor = float(exp(-sim_time / SPECIAL_WARP_T_CONST));
706                 local_v_out.z = pi->max_vel.z + excess * exp_factor;
707                 local_disp.z = (pi->max_vel.z * sim_time) + excess * (float(SPECIAL_WARP_T_CONST) * (1.0f - exp_factor));
708         } else if (pi->flags & PF_SPECIAL_WARP_OUT) {
709                 float exp_factor = float(exp(-sim_time / SPECIAL_WARP_T_CONST));
710                 vector temp;
711                 vm_vec_rotate(&temp, &pi->prev_ramp_vel, orient);
712                 float deficeit = temp.z - local_v_in.z;
713                 local_v_out.z = local_v_in.z + deficeit * (1.0f - exp_factor);
714                 local_disp.z = (local_v_in.z * sim_time) + deficeit * (sim_time - (float(SPECIAL_WARP_T_CONST) * (1.0f - exp_factor)));
715         } else {
716                 apply_physics (damp.z, local_desired_vel.z, local_v_in.z, sim_time, &local_v_out.z, &local_disp.z);
717         }
718
719         // maybe turn off special warp in flag
720         if ((pi->flags & PF_SPECIAL_WARP_IN) && (excess < 5)) {
721                 pi->flags &= ~(PF_SPECIAL_WARP_IN);
722         }
723
724         // update world position from local to world coords using orient
725         vector world_disp;
726         vm_vec_unrotate (&world_disp, &local_disp, orient);
727 #ifdef PHYS_DEBUG
728         // check for  excess velocity or translation
729         // GET DaveA.
730         if ( (Game_mode & GM_IN_MISSION) && (Game_mode & GM_NORMAL) ) {
731                 // Assert( (sim_time > 0.5f) || (vm_vec_mag_squared(&pi->vel) < 500*500) );
732                 // Assert( (sim_time > 0.5f) || (vm_vec_mag_squared(&world_disp) < 350*350) );
733         }
734 #endif
735         vm_vec_add2 (position, &world_disp);
736
737         // update world velocity
738         vm_vec_unrotate(&pi->vel, &local_v_out, orient);
739
740         if (special_warp_in) {
741                 vm_vec_rotate(&pi->prev_ramp_vel, &pi->vel, orient);
742         }
743 }
744
745 //      -----------------------------------------------------------------------------------------------------------
746 // Simulate a physics object for this frame
747 void physics_sim(vector* position, matrix* orient, physics_info* pi, float sim_time)
748 {
749         // check flag which tells us whether or not to do velocity translation
750         if (pi->flags & PF_CONST_VEL) {
751                 vm_vec_scale_add2(position, &pi->vel, sim_time);
752         } else {
753                 physics_sim_vel(position, pi, sim_time, orient);
754
755                 physics_sim_rot(orient, pi, sim_time);
756
757                 pi->speed = vm_vec_mag(&pi->vel);                                                       //      Note, cannot use quick version, causes cumulative error, increasing speed.
758                 pi->fspeed = vm_vec_dot(&orient->fvec, &pi->vel);               // instead of vector magnitude -- use only forward vector since we are only interested in forward velocity
759         }
760
761 }
762
763 //      -----------------------------------------------------------------------------------------------------------
764 // Simulate a physics object for this frame.  Used by the editor.  The difference between
765 // this function and physics_sim() is that this one uses a heading change to rotate around
766 // the universal Y axis, rather than the local orientation's Y axis.  Banking is also ignored.
767 void physics_sim_editor(vector *position, matrix * orient, physics_info * pi, float sim_time )
768 {
769         physics_sim_vel(position, pi, sim_time, orient);
770         physics_sim_rot_editor(orient, pi, sim_time);
771         pi->speed = vm_vec_mag_quick(&pi->vel);
772         pi->fspeed = vm_vec_dot(&orient->fvec, &pi->vel);               // instead of vector magnitude -- use only forward vector since we are only interested in forward velocity
773 }
774
775 // function to predict an object's position given the delta time and an objects physics info
776 void physics_predict_pos(physics_info *pi, float delta_time, vector *predicted_pos)
777 {
778         apply_physics( pi->side_slip_time_const, pi->desired_vel.x, pi->vel.x, delta_time, 
779                                                                  NULL, &predicted_pos->x );
780
781         apply_physics( pi->side_slip_time_const, pi->desired_vel.y, pi->vel.y, delta_time, 
782                                                                  NULL, &predicted_pos->y );
783
784         apply_physics( pi->side_slip_time_const, pi->desired_vel.z, pi->vel.z, delta_time, 
785                                                                  NULL, &predicted_pos->z );
786 }
787
788 // function to predict an object's velocity given the parameters
789 void physics_predict_vel(physics_info *pi, float delta_time, vector *predicted_vel)
790 {
791         if (pi->flags & PF_CONST_VEL) {
792                 predicted_vel = &pi->vel;
793         } else {
794                 apply_physics( pi->side_slip_time_const, pi->desired_vel.x, pi->vel.x, delta_time, 
795                                                                          &predicted_vel->x, NULL );
796
797                 apply_physics( pi->side_slip_time_const, pi->desired_vel.y, pi->vel.y, delta_time, 
798                                                                          &predicted_vel->y, NULL );
799
800                 apply_physics( pi->side_slip_time_const, pi->desired_vel.z, pi->vel.z, delta_time, 
801                                                                          &predicted_vel->z, NULL );
802         }
803 }
804
805 // function to predict position and velocity of an object
806 void physics_predict_pos_and_vel(physics_info *pi, float delta_time, vector *predicted_vel, vector *predicted_pos)
807 {
808
809         apply_physics( pi->side_slip_time_const, pi->desired_vel.x, pi->vel.x, delta_time, 
810                               &predicted_vel->x, &predicted_pos->x );
811
812         apply_physics( pi->side_slip_time_const, pi->desired_vel.y, pi->vel.y, delta_time, 
813                               &predicted_vel->y, &predicted_pos->y );
814
815         apply_physics( pi->side_slip_time_const, pi->desired_vel.z, pi->vel.z, delta_time, 
816                               &predicted_vel->z, &predicted_pos->z );
817 }
818
819 // physics_read_flying_controls() 
820 //
821 // parmeters:  *orient  ==>
822 //                                      *pi             ==>
823 //                                      *ci             ==> 
824 //      Adam: Uncomment-out this define to enable banking while turning.
825 #define BANK_WHEN_TURN
826
827
828
829 // function looks at the flying controls and the current velocity to determine a goal velocity
830 // function determines velocity in object's reference frame and goal velocity in object's reference frame
831 void physics_read_flying_controls( matrix * orient, physics_info * pi, control_info * ci, float sim_time, vector *wash_rot)
832 {
833         vector goal_vel;                // goal velocity in local coords, *not* accounting for ramping of velcity
834         float ramp_time_const;          // time constant for velocity ramping
835
836         float velocity_ramp (float v_in, float v_goal, float time_const, float t);
837
838 //      if ( keyd_pressed[KEY_LSHIFT] ) {
839 //              keyd_pressed[KEY_LSHIFT] = 0;
840 //              Int3();
841 //      }
842
843         ci->forward += (ci->forward_cruise_percent / 100.0f);
844
845 //      mprintf(("ci->forward == %7.3f\n", ci->forward));
846
847         // give control imput to cause rotation in engine wash
848         extern int Wash_on;
849         if ( wash_rot && Wash_on ) {
850                 ci->pitch += wash_rot->x;
851                 ci->bank += wash_rot->z;
852                 ci->heading += wash_rot->y;
853         }
854
855         if (ci->pitch > 1.0f ) ci->pitch = 1.0f;
856         else if (ci->pitch < -1.0f ) ci->pitch = -1.0f;
857
858         if (ci->vertical > 1.0f ) ci->vertical = 1.0f;
859         else if (ci->vertical < -1.0f ) ci->vertical = -1.0f;
860
861         if (ci->heading > 1.0f ) ci->heading = 1.0f;
862         else if (ci->heading < -1.0f ) ci->heading = -1.0f;
863
864         if (ci->sideways > 1.0f  ) ci->sideways = 1.0f;
865         else if (ci->sideways < -1.0f  ) ci->sideways = -1.0f;
866
867         if (ci->bank > 1.0f ) ci->bank = 1.0f;
868         else if (ci->bank < -1.0f ) ci->bank = -1.0f;
869
870         if ( pi->flags & PF_AFTERBURNER_ON )
871                 ci->forward = 1.0f;
872
873         if (ci->forward > 1.0f ) ci->forward = 1.0f;
874         else if (ci->forward < -1.0f ) ci->forward = -1.0f;
875
876         pi->desired_rotvel.x = ci->pitch * pi->max_rotvel.x;
877         pi->desired_rotvel.y = ci->heading * pi->max_rotvel.y;
878
879         float   delta_bank;
880
881 #ifdef BANK_WHEN_TURN
882         //      To change direction of bank, negate the whole expression.
883         //      To increase magnitude of banking, decrease denominator.
884         //      Adam: The following statement is all the math for banking while turning.
885         delta_bank = - (ci->heading * pi->max_rotvel.y)/2.0f;
886 #else
887         delta_bank = 0.0f;
888 #endif
889
890         pi->desired_rotvel.z = ci->bank * pi->max_rotvel.z + delta_bank;
891         pi->forward_thrust = ci->forward;
892
893         if ( pi->flags & PF_AFTERBURNER_ON ) {
894                 goal_vel.x = ci->sideways*pi->afterburner_max_vel.x;
895                 goal_vel.y = ci->vertical*pi->afterburner_max_vel.y;
896                 goal_vel.z = ci->forward* pi->afterburner_max_vel.z;
897         }
898         else {
899                 goal_vel.x = ci->sideways*pi->max_vel.x;
900                 goal_vel.y = ci->vertical*pi->max_vel.y;
901                 goal_vel.z = ci->forward* pi->max_vel.z;
902         }
903
904         if ( goal_vel.z < -pi->max_rear_vel ) 
905                 goal_vel.z = -pi->max_rear_vel;
906
907
908         if ( pi->flags & PF_ACCELERATES )       {
909                 //
910                 // Determine *resultant* DESIRED VELOCITY (desired_vel) accounting for RAMPING of velocity
911                 // Use LOCAL coordinates
912                 // if slide_enabled, ramp velocity for x and y, otherwise set goal (0)
913                 //    always ramp velocity for z
914                 // 
915
916                 // If reduced damp in effect, then adjust ramp_velocity and desired_velocity can not change as fast.
917                 // Scale according to reduced_damp_time_expansion.
918                 float reduced_damp_ramp_time_expansion;
919                 if ( pi->flags & PF_REDUCED_DAMP ) {
920                         float reduced_damp_fraction_time_left = timestamp_until( pi->reduced_damp_decay ) / (float) REDUCED_DAMP_TIME;
921                         reduced_damp_ramp_time_expansion = 1.0f + (REDUCED_DAMP_FACTOR-1) * reduced_damp_fraction_time_left;
922                 } else {
923                         reduced_damp_ramp_time_expansion = 1.0f;
924                 }
925
926 //      if ( !use_descent && (Player_obj->phys_info.forward_accel_time_const < 0.1) && !(Ships[Player_obj->instance].flags & SF_DYING) && (Player_obj->type != OBJ_OBSERVER) )
927 //                      Int3(); // Get dave A
928
929                 if (pi->flags & PF_SLIDE_ENABLED)  {
930                         // determine the local velocity
931                         // deterimine whether accelerating or decleration toward goal for x
932                         if ( goal_vel.x > 0.0f )  {
933                                 if ( goal_vel.x >= pi->prev_ramp_vel.x ) 
934                                         ramp_time_const = pi->slide_accel_time_const;
935                                 else
936                                         ramp_time_const = pi->slide_decel_time_const;
937                         } else  {  // goal_vel.x <= 0.0
938                                 if ( goal_vel.x <= pi->prev_ramp_vel.x )
939                                         ramp_time_const = pi->slide_accel_time_const;
940                                 else
941                                         ramp_time_const = pi->slide_decel_time_const;
942                         }
943                         // If reduced damp in effect, then adjust ramp_velocity and desired_velocity can not change as fast
944                         if ( pi->flags & PF_REDUCED_DAMP ) {
945                                 ramp_time_const *= reduced_damp_ramp_time_expansion;
946                         }
947                         pi->prev_ramp_vel.x = velocity_ramp(pi->prev_ramp_vel.x, goal_vel.x, ramp_time_const, sim_time);
948
949                         // deterimine whether accelerating or decleration toward goal for y
950                         if ( goal_vel.y > 0.0f )  {
951                                 if ( goal_vel.y >= pi->prev_ramp_vel.y ) 
952                                         ramp_time_const = pi->slide_accel_time_const;
953                                 else
954                                         ramp_time_const = pi->slide_decel_time_const;
955                         } else  {  // goal_vel.y <= 0.0
956                                 if ( goal_vel.y <= pi->prev_ramp_vel.y )
957                                         ramp_time_const = pi->slide_accel_time_const;
958                                 else
959                                         ramp_time_const = pi->slide_decel_time_const;
960                         }
961                         // If reduced damp in effect, then adjust ramp_velocity and desired_velocity can not change as fast
962                         if ( pi->flags & PF_REDUCED_DAMP ) {
963                                 ramp_time_const *= reduced_damp_ramp_time_expansion;
964                         }
965                         pi->prev_ramp_vel.y = velocity_ramp( pi->prev_ramp_vel.y, goal_vel.y, ramp_time_const, sim_time);
966                 } else  {
967                         // slide not enabled
968                         pi->prev_ramp_vel.x = 0.0f;
969                         pi->prev_ramp_vel.y = 0.0f;
970                 }
971
972                 // find ramp velocity in the forward direction
973                 if ( goal_vel.z >= pi->prev_ramp_vel.z )  {
974                         if ( pi->flags & PF_AFTERBURNER_ON )
975                                 ramp_time_const = pi->afterburner_forward_accel_time_const;
976                         else
977                                 ramp_time_const = pi->forward_accel_time_const;
978                 } else
979                         ramp_time_const = pi->forward_decel_time_const;
980
981                 // If reduced damp in effect, then adjust ramp_velocity and desired_velocity can not change as fast
982                 if ( pi->flags & PF_REDUCED_DAMP ) {
983                         ramp_time_const *= reduced_damp_ramp_time_expansion;
984                 }
985                 pi->prev_ramp_vel.z = velocity_ramp( pi->prev_ramp_vel.z, goal_vel.z, ramp_time_const, sim_time);
986
987
988                 // this translates local desired velocities to world velocities
989
990                 vm_vec_zero(&pi->desired_vel);
991                 vm_vec_scale_add2( &pi->desired_vel, &orient->rvec, pi->prev_ramp_vel.x );
992                 vm_vec_scale_add2( &pi->desired_vel, &orient->uvec, pi->prev_ramp_vel.y );
993                 vm_vec_scale_add2( &pi->desired_vel, &orient->fvec, pi->prev_ramp_vel.z );
994         } else  // object does not accelerate  (PF_ACCELERATES not set)
995                 pi->desired_vel = pi->vel;
996 }
997
998
999
1000 //      ----------------------------------------------------------------
1001 //      Do *dest = *delta unless:
1002 //                              *delta is pretty small
1003 //              and     they are of different signs.
1004 void physics_set_rotvel_and_saturate(float *dest, float delta)
1005 {
1006         /*
1007         if ((delta ^ *dest) < 0) {
1008                 if (abs(delta) < F1_0/8) {
1009                         // mprintf((0, "D"));
1010                         *dest = delta/4;
1011                 } else
1012                         // mprintf((0, "d"));
1013                         *dest = delta;
1014         } else {
1015                 // mprintf((0, "!"));
1016                 *dest = delta;
1017         }
1018         */
1019         *dest = delta;
1020 }
1021
1022
1023 // ----------------------------------------------------------------------------
1024 // physics_apply_whack applies an instaneous whack on an object changing
1025 // both the objects velocity and the rotational velocity based on the impulse
1026 // being applied.  
1027 //
1028 //      input:  impulse         =>              impulse vector ( force*time = impulse = change in momentum (mv) )
1029 //                              pos                     =>              vector from center of mass to location of where the force acts
1030 //                              pi                              =>              pointer to phys_info struct of object getting whacked
1031 //                              orient          =>              orientation matrix (needed to set rotational impulse in body coords)
1032 //                              mass                    =>              mass of the object (may be different from pi.mass if docked)
1033 //
1034 #define WHACK_LIMIT     0.001f
1035 #define ROTVEL_WHACK_CONST 0.12
1036 void physics_apply_whack(vector *impulse, vector *pos, physics_info *pi, matrix *orient, float mass)
1037 {
1038         vector  local_torque, torque;
1039 //      vector  npos;
1040
1041         //      Detect null vector.
1042         if ((fl_abs(impulse->x) <= WHACK_LIMIT) && (fl_abs(impulse->y) <= WHACK_LIMIT) && (fl_abs(impulse->z) <= WHACK_LIMIT))
1043                 return;
1044
1045         // first do the rotational velocity
1046         // calculate the torque on the body based on the point on the
1047         // object that was hit and the momentum being applied to the object
1048
1049         vm_vec_crossprod(&torque, pos, impulse);
1050         vm_vec_rotate ( &local_torque, &torque, orient );
1051
1052         vector delta_rotvel;
1053         vm_vec_rotate( &delta_rotvel, &local_torque, &pi->I_body_inv );
1054         vm_vec_scale ( &delta_rotvel, (float) ROTVEL_WHACK_CONST );
1055         vm_vec_add2( &pi->rotvel, &delta_rotvel );
1056
1057 #ifdef ROT_DEBUG
1058         if (check_rotvel_limit( pi )) {
1059                 nprintf(("Physics", "rotvel reset in physics_apply_whack\n"));
1060         }
1061 #endif
1062
1063         //mprintf(("Whack: %7.3f %7.3f %7.3f\n", pi->rotvel.x, pi->rotvel.y, pi->rotvel.z));
1064
1065         // instant whack on the velocity
1066         // reduce damping on all axes
1067         pi->flags |= PF_REDUCED_DAMP;
1068         update_reduced_damp_timestamp( pi, vm_vec_mag(impulse) );
1069
1070         // find time for shake from weapon to end
1071         int dtime = timestamp_until(pi->afterburner_decay);
1072         if (dtime < WEAPON_SHAKE_TIME) {
1073                 pi->afterburner_decay = timestamp( WEAPON_SHAKE_TIME );
1074         }
1075
1076         vm_vec_scale_add2( &pi->vel, impulse, 1.0f / pi->mass );
1077         if (!(pi->flags & PF_USE_VEL) && (vm_vec_mag_squared(&pi->vel) > MAX_SHIP_SPEED*MAX_SHIP_SPEED)) {
1078                 // Get DaveA
1079                 nprintf(("Physics", "speed reset in physics_apply_whack [speed: %f]\n", vm_vec_mag(&pi->vel)));
1080 //              Int3();
1081                 vm_vec_normalize(&pi->vel);
1082                 vm_vec_scale(&pi->vel, (float)RESET_SHIP_SPEED);
1083         }
1084         vm_vec_rotate( &pi->prev_ramp_vel, &pi->vel, orient );          // set so velocity will ramp starting from current speed
1085                                                                                                                                                                         // ramped velocity is now affected by collision
1086 }
1087
1088 // function generates a velocity ramp with a given time constant independent of frame rate
1089 // uses an exponential approach to desired velocity and a cheat when close to improve closure speed
1090 float velocity_ramp (float v_in, float v_goal, float ramp_time_const, float t)
1091 {
1092         float delta_v;
1093         float decay_factor;
1094         float dist;
1095
1096         // JAS: If no time elapsed, change nothing
1097         if ( t==0.0f )
1098                 return v_in;
1099
1100         delta_v = v_goal - v_in;
1101         dist = (float)fl_abs(delta_v);
1102
1103         // hack to speed up closure when close to goal
1104         if (dist < ramp_time_const/3)
1105                 ramp_time_const = dist / 3;
1106
1107         // Rather than get a divide by zero, just go to the goal
1108         if ( ramp_time_const < 0.0001f )        {
1109                 return v_goal;
1110         }
1111
1112         // determine decay factor  (ranges from 0 for short times to 1 for long times)
1113         // when decay factor is near 0, the velocity in nearly unchanged
1114         // when decay factor in near 1, the velocity approaches goal
1115         decay_factor = (float)exp(- t / ramp_time_const);
1116
1117         return (v_in + delta_v * (1.0f - decay_factor) );
1118 }
1119
1120
1121 // ----------------------------------------------------------------------------
1122 // physics_apply_shock applies applies a shockwave to an object.  This causes a velocity impulse and 
1123 // and a rotational impulse.  This is different than physics_apply_whack since a shock wave is a pressure
1124 // wave which acts over the *surface* of the object, not a point.
1125 //
1126 // inputs:      direction_vec           =>              a position vector whose direction is from the center of the shock wave to the object
1127 //                              pressure                                =>              the pressure of the shock wave at the object
1128 //                              pi                                              =>              physics_info structure
1129 //                              orient                          =>              matrix orientation of the object
1130 //                              min                                     =>              vector of minimum values of the bounding box
1131 //                              max                                     =>              vector of maximum values of the bounding box
1132 //                              radius                          =>              bounding box radius of the object, used for scaling rotation
1133 //
1134 // outputs:     makes changes to physics_info structure rotvel and vel variables
1135 //                              
1136 #define STD_PRESSURE            1000            // amplitude of standard shockwave blasts
1137 #define MIN_RADIUS                      10                      // radius within which full rotvel and shake applied
1138 #define MAX_RADIUS                      50                      // radius at which no rotvel or shake applied
1139 #define MAX_ROTVEL                      0.4             // max rotational velocity
1140 #define MAX_SHAKE                       0.1             // max rotational amplitude of shake
1141 #define MAX_VEL                         8                       // max vel from shockwave 
1142 void physics_apply_shock(vector *direction_vec, float pressure, physics_info *pi, matrix *orient, vector *min, vector *max, float radius)
1143 {
1144         vector normal;
1145         vector local_torque, temp_torque, torque;
1146         vector impact_vec;
1147         vector area;
1148         vector sin;
1149
1150         if (radius > MAX_RADIUS) {
1151                 return;
1152         }
1153
1154         vm_vec_normalize_safe ( direction_vec );
1155
1156         area.x = (max->y - min->z) * (max->z - min->z);
1157         area.y = (max->x - min->x) * (max->z - min->z);
1158         area.z = (max->x - min->x) * (max->y - min->y);
1159
1160         normal.x = vm_vec_dotprod( direction_vec, &orient->rvec );
1161         normal.y = vm_vec_dotprod( direction_vec, &orient->uvec );
1162         normal.z = vm_vec_dotprod( direction_vec, &orient->fvec );
1163
1164         sin.x = fl_sqrt( fl_abs(1.0f - normal.x*normal.x) );
1165         sin.y = fl_sqrt( fl_abs(1.0f - normal.y*normal.y) );
1166         sin.z = fl_sqrt( fl_abs(1.0f - normal.z*normal.z) );    
1167
1168         vm_vec_make( &torque, 0.0f, 0.0f, 0.0f );
1169
1170         // find the torque exerted due to the shockwave hitting each face
1171         //  model the effect of the shockwave as if the shockwave were a plane of projectiles,
1172         //  all moving in the direction direction_vec.  then find the torque as the cross prod
1173         //  of the force (pressure * area * normal * sin * scale * mass)
1174         //  normal takes account the fraction of the surface exposed to the shockwave
1175         //  the sin term is not technically needed but "feels" better
1176         //  scale factors out the increase in area with larger objects
1177         //  more massive objects get less rotation
1178
1179         // find torque due to forces on the right/left face
1180         if ( normal.x < 0.0f )          // normal < 0, hits the right face
1181                 vm_vec_copy_scale( &impact_vec, &orient->rvec, max->x * pressure * area.x *  normal.x * sin.x / pi->mass );
1182         else                                                            // normal > 0, hits the left face
1183                 vm_vec_copy_scale( &impact_vec, &orient->rvec, min->x * pressure * area.x * -normal.x * sin.x / pi->mass );
1184
1185         vm_vec_crossprod( &temp_torque, &impact_vec, direction_vec );
1186         vm_vec_add2( &torque, &temp_torque );
1187
1188         // find torque due to forces on the up/down face
1189         if ( normal.y < 0.0f )
1190                 vm_vec_copy_scale( &impact_vec, &orient->uvec, max->y * pressure * area.y *  normal.y * sin.y / pi->mass );
1191         else
1192                 vm_vec_copy_scale( &impact_vec, &orient->uvec, min->y * pressure * area.y * -normal.y * sin.y / pi->mass );
1193
1194         vm_vec_crossprod( &temp_torque, &impact_vec, direction_vec );
1195         vm_vec_add2( &torque, &temp_torque );
1196
1197         // find torque due to forces on the forward/backward face
1198         if ( normal.z < 0.0f )
1199                 vm_vec_copy_scale( &impact_vec, &orient->fvec, max->z * pressure * area.z *  normal.z * sin.z / pi->mass );
1200         else
1201                 vm_vec_copy_scale( &impact_vec, &orient->fvec, min->z * pressure * area.z * -normal.z * sin.z / pi->mass );
1202
1203         vm_vec_crossprod( &temp_torque, &impact_vec, direction_vec );
1204         vm_vec_add2( &torque, &temp_torque );
1205
1206         // compute delta rotvel, scale according to blast and radius
1207         float scale;
1208         vector delta_rotvel;
1209         vm_vec_rotate( &local_torque, &torque, orient );
1210         vm_vec_copy_normalize(&delta_rotvel, &local_torque);
1211         if (radius < MIN_RADIUS) {
1212                 scale = 1.0f;
1213         } else {
1214                 scale = (MAX_RADIUS - radius)/(MAX_RADIUS-MIN_RADIUS);
1215         }
1216         vm_vec_scale(&delta_rotvel, (float)(MAX_ROTVEL*(pressure/STD_PRESSURE)*scale));
1217         // nprintf(("Physics", "rotvel scale %f\n", (MAX_ROTVEL*(pressure/STD_PRESSURE)*scale)));
1218         vm_vec_add2(&pi->rotvel, &delta_rotvel);
1219
1220         // set shockwave shake amplitude, duration, flag
1221         pi->shockwave_shake_amp = (float)(MAX_SHAKE*(pressure/STD_PRESSURE)*scale);
1222         pi->shockwave_decay = timestamp( SW_BLAST_DURATION );
1223         pi->flags |= PF_IN_SHOCKWAVE;
1224
1225         // set reduced translational damping, set flags
1226         float velocity_scale = (float)MAX_VEL*scale;
1227         pi->flags |= PF_REDUCED_DAMP;
1228         update_reduced_damp_timestamp( pi, velocity_scale*pi->mass );
1229         vm_vec_scale_add2( &pi->vel, direction_vec, velocity_scale );
1230         vm_vec_rotate(&pi->prev_ramp_vel, &pi->vel, orient);    // set so velocity will ramp starting from current speed
1231
1232         // check that kick from shockwave is not too large
1233         if (!(pi->flags & PF_USE_VEL) && (vm_vec_mag_squared(&pi->vel) > MAX_SHIP_SPEED*MAX_SHIP_SPEED)) {
1234                 // Get DaveA
1235                 nprintf(("Physics", "speed reset in physics_apply_shock [speed: %f]\n", vm_vec_mag(&pi->vel)));
1236 //              Int3();
1237                 vm_vec_normalize(&pi->vel);
1238                 vm_vec_scale(&pi->vel, (float)RESET_SHIP_SPEED);
1239         }
1240
1241 #ifdef ROT_DEBUG
1242         if (check_rotvel_limit( pi )) {
1243                 nprintf(("Physics", "rotvel reset in physics_apply_shock\n"));
1244         }
1245 #endif
1246
1247                                                                                                                                                                 // ramped velocity is now affected by collision
1248 }
1249
1250 // ----------------------------------------------------------------------------
1251 // physics_collide_whack applies an instaneous whack on an object changing
1252 // both the objects velocity and the rotational velocity based on the impulse
1253 // being applied.  
1254 //
1255 //      input:  impulse                                 =>              impulse vector ( force*time = impulse = change in momentum (mv) )
1256 //                              world_delta_rotvel      =>              change in rotational velocity (already calculated)
1257 //                              pi                                                      =>              pointer to phys_info struct of object getting whacked
1258 //                              orient                                  =>              orientation matrix (needed to set rotational impulse in body coords)
1259 //
1260
1261 // Warning:  Do not change ROTVEL_COLLIDE_WHACK_CONST.  This will mess up collision physics.
1262 // If you need to change the rotation, change  COLLISION_ROTATION_FACTOR in collide_ship_ship.
1263 #define ROTVEL_COLLIDE_WHACK_CONST 1.0
1264 void physics_collide_whack( vector *impulse, vector *world_delta_rotvel, physics_info *pi, matrix *orient )
1265 {
1266         vector  body_delta_rotvel;
1267
1268         //      Detect null vector.
1269         if ((fl_abs(impulse->x) <= WHACK_LIMIT) && (fl_abs(impulse->y) <= WHACK_LIMIT) && (fl_abs(impulse->z) <= WHACK_LIMIT))
1270                 return;
1271
1272         vm_vec_rotate( &body_delta_rotvel, world_delta_rotvel, orient );
1273 //      vm_vec_scale( &body_delta_rotvel, (float)       ROTVEL_COLLIDE_WHACK_CONST );
1274         vm_vec_add2( &pi->rotvel, &body_delta_rotvel );
1275
1276 #ifdef ROT_DEBUG
1277         if (check_rotvel_limit( pi )) {
1278                 nprintf(("Physics", "rotvel reset in physics_collide_whack\n"));
1279         }
1280 #endif
1281
1282         update_reduced_damp_timestamp( pi, vm_vec_mag(impulse) );
1283
1284         // find time for shake from weapon to end
1285         int dtime = timestamp_until(pi->afterburner_decay);
1286         if (dtime < WEAPON_SHAKE_TIME) {
1287                 pi->afterburner_decay = timestamp( WEAPON_SHAKE_TIME );
1288         }
1289
1290         pi->flags |= PF_REDUCED_DAMP;
1291         vm_vec_scale_add2( &pi->vel, impulse, 1.0f / pi->mass );
1292         // check that collision does not give ship too much speed
1293         // reset if too high
1294         if (!(pi->flags & PF_USE_VEL) && (vm_vec_mag_squared(&pi->vel) > MAX_SHIP_SPEED*MAX_SHIP_SPEED)) {
1295                 // Get DaveA
1296                 nprintf(("Physics", "speed reset in physics_collide_whack [speed: %f]\n", vm_vec_mag(&pi->vel)));
1297 //              Int3();
1298                 vm_vec_normalize(&pi->vel);
1299                 vm_vec_scale(&pi->vel, (float)RESET_SHIP_SPEED);
1300         }
1301         vm_vec_rotate( &pi->prev_ramp_vel, &pi->vel, orient );          // set so velocity will ramp starting from current speed
1302                                                                                                                                                                         // ramped velocity is now affected by collision
1303         // rotate previous ramp velocity (in model coord) to be same as vel (in world coords)
1304 }
1305
1306
1307 int check_rotvel_limit( physics_info *pi )
1308 {
1309         if ( 0 == pi->flags )           // weapon
1310                 return 0;
1311
1312         if ( Fred_running )
1313                 return 0;
1314
1315         int change_made = 0;
1316         if ( !(pi->flags & PF_DEAD_DAMP) ) {
1317                 // case of normal, live ship
1318                 // -- Commented out by MK: Assert( vm_vec_mag_squared(&pi->max_rotvel) > ROTVEL_TOL );
1319                 // Assert( (pi->max_rotvel.x <= ROTVEL_CAP) && (pi->max_rotvel.y <= ROTVEL_CAP) && (pi->max_rotvel.z <= ROTVEL_CAP) );
1320                 //              Warning(LOCATION,"Excessive rotvel (wx: %f, wy: %f, wz:%f)\n", pi->rotvel.x, pi->rotvel.y, pi->rotvel.z);
1321                 if ( fl_abs(pi->rotvel.x) > pi->max_rotvel.x ) {
1322                         pi->rotvel.x = (pi->rotvel.x / fl_abs(pi->rotvel.x)) * (pi->max_rotvel.x - (float) ROTVEL_TOL);
1323                         change_made = 1;
1324                 }
1325                 if ( fl_abs(pi->rotvel.y) > pi->max_rotvel.y ) {
1326                         pi->rotvel.y = (pi->rotvel.y / fl_abs(pi->rotvel.y)) * (pi->max_rotvel.y - (float) ROTVEL_TOL);
1327                         change_made = 1;
1328                 }
1329                 if ( fl_abs(pi->rotvel.z) > pi->max_rotvel.z ) {
1330                         pi->rotvel.z = (pi->rotvel.z / fl_abs(pi->rotvel.z)) * (pi->max_rotvel.z - (float) ROTVEL_TOL);
1331                         change_made = 1;
1332                 }
1333         } else { 
1334                 // case of dead ship
1335                 if ( fl_abs(pi->rotvel.x) > DEAD_ROTVEL_CAP ) {
1336                         pi->rotvel.x = (pi->rotvel.x / fl_abs(pi->rotvel.x)) * (float) (DEAD_ROTVEL_CAP - ROTVEL_TOL);
1337                         change_made = 1;
1338                 }
1339                 if ( fl_abs(pi->rotvel.y) > DEAD_ROTVEL_CAP ) {
1340                         pi->rotvel.y = (pi->rotvel.y / fl_abs(pi->rotvel.y)) * (float) (DEAD_ROTVEL_CAP - ROTVEL_TOL);
1341                         change_made = 1;
1342                 }
1343                 if ( fl_abs(pi->rotvel.z) > DEAD_ROTVEL_CAP ) {
1344                         pi->rotvel.z = (pi->rotvel.z / fl_abs(pi->rotvel.z)) * (float) (DEAD_ROTVEL_CAP - ROTVEL_TOL);
1345                         change_made = 1;
1346                 }
1347         }
1348         return change_made;
1349 }
1350
1351 // ----------------------------------------------------------------------------
1352 // update_reduced_damp_timestamp()
1353 //
1354 void update_reduced_damp_timestamp( physics_info *pi, float impulse )
1355 {
1356
1357         // Compute duration of reduced damp from present
1358         // Compare with current value and increase if greater, otherwise ignore
1359         int reduced_damp_decay_time;
1360         reduced_damp_decay_time = (int) (REDUCED_DAMP_TIME * impulse / (REDUCED_DAMP_VEL * pi->mass));
1361         if ( reduced_damp_decay_time > REDUCED_DAMP_TIME )
1362                 reduced_damp_decay_time = REDUCED_DAMP_TIME;
1363
1364         // Reset timestamp if larger than current (if any)
1365         if ( timestamp_valid( pi->reduced_damp_decay ) ) {
1366                 int time_left = timestamp_until( pi->reduced_damp_decay );
1367                 if ( time_left > 0 ) {
1368                         // increment old time, but apply cap
1369                         int new_time = reduced_damp_decay_time + time_left;
1370                         if ( new_time < REDUCED_DAMP_TIME ) {
1371                                 pi->reduced_damp_decay = timestamp( new_time );
1372                         }
1373                 } else {
1374                         pi->reduced_damp_decay = timestamp( reduced_damp_decay_time );
1375                 }
1376         } else {
1377                 // set if not valid
1378                 pi->reduced_damp_decay = timestamp( reduced_damp_decay_time );
1379         }
1380
1381 }