configuration fixes
[btb/d2x.git] / main / physics.c
1 /*
2 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
3 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
4 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
5 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
6 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
7 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
8 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
9 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
10 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.  
11 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
12 */
13
14 #ifdef RCS
15 static char rcsid[] = "$Id: physics.c,v 1.2 2001-01-20 13:49:17 bradleyb Exp $";
16 #endif
17
18 #include <conf.h>
19
20 #include <stdio.h>
21 #include <stdlib.h>
22
23 #include "joy.h"
24 #include "mono.h"
25 #include "error.h"
26
27 #include "inferno.h"
28 #include "segment.h"
29 #include "object.h"
30 #include "physics.h"
31 #include "key.h"
32 #include "game.h"
33 #include "collide.h"
34 #include "fvi.h"
35 #include "newdemo.h"
36 #include "timer.h"
37 #include "ai.h"
38 #include "wall.h"
39 #include "laser.h"
40 #include "bm.h"
41 #include "player.h"
42
43 #ifdef TACTILE
44 #include "tactile.h"
45 #endif
46
47 //Global variables for physics system
48
49 #define ROLL_RATE               0x2000
50 #define DAMP_ANG                        0x400                  //min angle to bank
51
52 #define TURNROLL_SCALE  (0x4ec4/2)
53
54 #define MAX_OBJECT_VEL i2f(100)
55
56 #define BUMP_HACK       1               //if defined, bump player when he gets stuck
57
58 //--unused-- int mike_mode=0;
59
60 //check point against each side of segment. return bitmask, where bit
61 //set means behind that side
62
63 int Physics_cheat_flag = 0;
64 extern char BounceCheat;
65
66 //##//returns the distance of a point (checkp) from a plane (defined by norm & planep) 
67 //##fix dist_to_plane(vms_vector *checkp,vms_vector *norm,vms_vector *planep)
68 //##{
69 //##    vms_vector deltap;
70 //##
71 //##    vm_vec_sub(&deltap,checkp,planep);
72 //##
73 //##    return vm_vec_dot(&deltap,norm);
74 //##}
75  
76 //--unused-- int dpjm_old_joy_x, dpjm_old_joy_y;
77
78 int floor_levelling=0;
79
80 //--unused-- level_with_floor()
81 //--unused-- {
82 //--unused--    floor_levelling=1;
83 //--unused-- }
84
85 //make sure matrix is orthogonal
86 void check_and_fix_matrix(vms_matrix *m)
87 {
88         vms_matrix tempm;
89
90         vm_vector_2_matrix(&tempm,&m->fvec,&m->uvec,NULL);
91         *m  = tempm;
92 }
93
94
95 void do_physics_align_object( object * obj )
96 {
97         vms_vector desired_upvec;
98         fixang delta_ang,roll_ang;
99         //vms_vector forvec = {0,0,f1_0};
100         vms_matrix temp_matrix;
101         fix d,largest_d=-f1_0;
102         int i,best_side;
103
104         best_side=0;
105         // bank player according to segment orientation
106
107         //find side of segment that player is most alligned with
108
109         for (i=0;i<6;i++) {
110                 #ifdef COMPACT_SEGS
111                         vms_vector _tv1;
112                         get_side_normal( &Segments[obj->segnum], i, 0, &_tv1 );
113                         d = vm_vec_dot(&_tv1,&obj->orient.uvec);
114                 #else                                   
115                         d = vm_vec_dot(&Segments[obj->segnum].sides[i].normals[0],&obj->orient.uvec);
116                 #endif
117
118                 if (d > largest_d) {largest_d = d; best_side=i;}
119         }
120
121         if (floor_levelling) {
122
123                 // old way: used floor's normal as upvec
124                 #ifdef COMPACT_SEGS
125                         get_side_normal(&Segments[obj->segnum], 3, 0, &desired_upvec );                 
126                 #else
127                         desired_upvec = Segments[obj->segnum].sides[3].normals[0];
128                 #endif
129
130         }
131         else  // new player leveling code: use normal of side closest to our up vec
132                 if (get_num_faces(&Segments[obj->segnum].sides[best_side])==2) {
133                         #ifdef COMPACT_SEGS
134                                 vms_vector normals[2];
135                                 get_side_normals(&Segments[obj->segnum], best_side, &normals[0], &normals[1] );                 
136
137                                 desired_upvec.x = (normals[0].x + normals[1].x) / 2;
138                                 desired_upvec.y = (normals[0].y + normals[1].y) / 2;
139                                 desired_upvec.z = (normals[0].z + normals[1].z) / 2;
140
141                                 vm_vec_normalize(&desired_upvec);
142                         #else
143                                 side *s = &Segments[obj->segnum].sides[best_side];
144                                 desired_upvec.x = (s->normals[0].x + s->normals[1].x) / 2;
145                                 desired_upvec.y = (s->normals[0].y + s->normals[1].y) / 2;
146                                 desired_upvec.z = (s->normals[0].z + s->normals[1].z) / 2;
147                 
148                                 vm_vec_normalize(&desired_upvec);
149                         #endif
150                 }
151                 else
152                         #ifdef COMPACT_SEGS
153                                 get_side_normal(&Segments[obj->segnum], best_side, 0, &desired_upvec );                 
154                         #else
155                                 desired_upvec = Segments[obj->segnum].sides[best_side].normals[0];
156                         #endif
157
158         if (labs(vm_vec_dot(&desired_upvec,&obj->orient.fvec)) < f1_0/2) {
159                 fixang save_delta_ang;
160                 vms_angvec tangles;
161                 
162                 vm_vector_2_matrix(&temp_matrix,&obj->orient.fvec,&desired_upvec,NULL);
163
164                 save_delta_ang = delta_ang = vm_vec_delta_ang(&obj->orient.uvec,&temp_matrix.uvec,&obj->orient.fvec);
165
166                 delta_ang += obj->mtype.phys_info.turnroll;
167
168                 if (abs(delta_ang) > DAMP_ANG) {
169                         vms_matrix rotmat, new_pm;
170
171                         roll_ang = fixmul(FrameTime,ROLL_RATE);
172
173                         if (abs(delta_ang) < roll_ang) roll_ang = delta_ang;
174                         else if (delta_ang<0) roll_ang = -roll_ang;
175
176                         tangles.p = tangles.h = 0;  tangles.b = roll_ang;
177                         vm_angles_2_matrix(&rotmat,&tangles);
178
179                         vm_matrix_x_matrix(&new_pm,&obj->orient,&rotmat);
180                         obj->orient = new_pm;
181                 }
182                 else floor_levelling=0;
183         }
184
185 }
186
187 void set_object_turnroll(object *obj)
188 {
189         fixang desired_bank;
190
191         desired_bank = -fixmul(obj->mtype.phys_info.rotvel.y,TURNROLL_SCALE);
192
193         if (obj->mtype.phys_info.turnroll != desired_bank) {
194                 fixang delta_ang,max_roll;
195
196                 max_roll = fixmul(ROLL_RATE,FrameTime);
197
198                 delta_ang = desired_bank - obj->mtype.phys_info.turnroll;
199
200                 if (labs(delta_ang) < max_roll)
201                         max_roll = delta_ang;
202                 else
203                         if (delta_ang < 0)
204                                 max_roll = -max_roll;
205
206                 obj->mtype.phys_info.turnroll += max_roll;
207         }
208
209 }
210
211 //list of segments went through
212 int phys_seglist[MAX_FVI_SEGS],n_phys_segs;
213
214
215 #define MAX_IGNORE_OBJS 100
216
217 #ifndef NDEBUG
218 #define EXTRA_DEBUG 1           //no extra debug when NDEBUG is on
219 #endif
220
221 #ifdef EXTRA_DEBUG
222 object *debug_obj=NULL;
223 #endif
224
225 #define XYZ(v) (v)->x,(v)->y,(v)->z
226
227
228 #ifndef NDEBUG
229 int     Total_retries=0, Total_sims=0;
230 int     Dont_move_ai_objects=0;
231 #endif
232
233 #define FT (f1_0/64)
234
235 extern int disable_new_fvi_stuff;
236 //      -----------------------------------------------------------------------------------------------------------
237 // add rotational velocity & acceleration
238 void do_physics_sim_rot(object *obj)
239 {
240         vms_angvec      tangles;
241         vms_matrix      rotmat,new_orient;
242         //fix                   rotdrag_scale;
243         physics_info *pi;
244
245         Assert(FrameTime > 0);  //Get MATT if hit this!
246
247         pi = &obj->mtype.phys_info;
248
249         if (!(pi->rotvel.x || pi->rotvel.y || pi->rotvel.z || pi->rotthrust.x || pi->rotthrust.y || pi->rotthrust.z))
250                 return;
251
252         if (obj->mtype.phys_info.drag) {
253                 int count;
254                 vms_vector accel;
255                 fix drag,r,k;
256
257                 count = FrameTime / FT;
258                 r = FrameTime % FT;
259                 k = fixdiv(r,FT);
260
261                 drag = (obj->mtype.phys_info.drag*5)/2;
262
263                 if (obj->mtype.phys_info.flags & PF_USES_THRUST) {
264
265                         vm_vec_copy_scale(&accel,&obj->mtype.phys_info.rotthrust,fixdiv(f1_0,obj->mtype.phys_info.mass));
266
267                         while (count--) {
268
269                                 vm_vec_add2(&obj->mtype.phys_info.rotvel,&accel);
270
271                                 vm_vec_scale(&obj->mtype.phys_info.rotvel,f1_0-drag);
272                         }
273
274                         //do linear scale on remaining bit of time
275
276                         vm_vec_scale_add2(&obj->mtype.phys_info.rotvel,&accel,k);
277                         vm_vec_scale(&obj->mtype.phys_info.rotvel,f1_0-fixmul(k,drag));
278                 }
279                 else if (! (obj->mtype.phys_info.flags & PF_FREE_SPINNING)) {
280                         fix total_drag=f1_0;
281
282                         while (count--)
283                                 total_drag = fixmul(total_drag,f1_0-drag);
284
285                         //do linear scale on remaining bit of time
286
287                         total_drag = fixmul(total_drag,f1_0-fixmul(k,drag));
288
289                         vm_vec_scale(&obj->mtype.phys_info.rotvel,total_drag);
290                 }
291
292         }
293
294         //mprintf( (0, "Rot vel = %.3f,%.3f,%.3f\n", f2fl(obj->mtype.phys_info.rotvel.x),f2fl(obj->mtype.phys_info.rotvel.y), f2fl(obj->mtype.phys_info.rotvel.z) ));
295
296         //now rotate object 
297
298         //unrotate object for bank caused by turn
299         if (obj->mtype.phys_info.turnroll) {
300                 vms_matrix new_pm;
301
302                 tangles.p = tangles.h = 0;
303                 tangles.b = -obj->mtype.phys_info.turnroll;
304                 vm_angles_2_matrix(&rotmat,&tangles);
305                 vm_matrix_x_matrix(&new_pm,&obj->orient,&rotmat);
306                 obj->orient = new_pm;
307         }
308   
309         tangles.p = fixmul(obj->mtype.phys_info.rotvel.x,FrameTime);
310         tangles.h = fixmul(obj->mtype.phys_info.rotvel.y,FrameTime);
311         tangles.b  = fixmul(obj->mtype.phys_info.rotvel.z,FrameTime);
312
313         vm_angles_2_matrix(&rotmat,&tangles);
314         vm_matrix_x_matrix(&new_orient,&obj->orient,&rotmat);
315         obj->orient = new_orient;
316
317         if (obj->mtype.phys_info.flags & PF_TURNROLL)
318                 set_object_turnroll(obj);
319
320         //re-rotate object for bank caused by turn
321         if (obj->mtype.phys_info.turnroll) {
322                 vms_matrix new_pm;
323
324                 tangles.p = tangles.h = 0;
325                 tangles.b = obj->mtype.phys_info.turnroll;
326                 vm_angles_2_matrix(&rotmat,&tangles);
327                 vm_matrix_x_matrix(&new_pm,&obj->orient,&rotmat);
328                 obj->orient = new_pm;
329         }
330
331         check_and_fix_matrix(&obj->orient);
332 }
333
334 //      -----------------------------------------------------------------------------------------------------------
335 //Simulate a physics object for this frame
336 void do_physics_sim(object *obj)
337 {
338         int ignore_obj_list[MAX_IGNORE_OBJS],n_ignore_objs;
339         int iseg;
340         int try_again;
341         int fate;
342         vms_vector frame_vec;                   //movement in this frame
343         vms_vector new_pos,ipos;                //position after this frame
344         int count=0;
345         int objnum;
346         int WallHitSeg, WallHitSide;
347         fvi_info hit_info;
348         fvi_query fq;
349         vms_vector save_pos;
350         int save_seg;
351         fix drag;
352         fix sim_time,old_sim_time;
353         vms_vector start_pos;
354         int obj_stopped=0;
355         fix moved_time;                 //how long objected moved before hit something
356         vms_vector save_p0,save_p1;
357         physics_info *pi;
358         int orig_segnum = obj->segnum;
359         int bounced=0;
360
361         Assert(obj->type != OBJ_NONE);
362         Assert(obj->movement_type == MT_PHYSICS);
363
364 #ifndef NDEBUG
365 if (Dont_move_ai_objects)
366         if (obj->control_type == CT_AI)
367                 return;
368 #endif
369
370         pi = &obj->mtype.phys_info;
371
372         do_physics_sim_rot(obj);
373
374         if (!(pi->velocity.x || pi->velocity.y || pi->velocity.z || pi->thrust.x || pi->thrust.y || pi->thrust.z))
375                 return;
376
377         objnum = obj-Objects;
378
379         n_phys_segs = 0;
380
381         disable_new_fvi_stuff = (obj->type != OBJ_PLAYER);
382
383         sim_time = FrameTime;
384
385 //debug_obj = obj;
386
387         #ifdef EXTRA_DEBUG
388         if (obj == debug_obj) {
389                 printf("object %d:\n  start pos = %x %x %x\n",objnum,XYZ(&obj->pos));
390                 printf("  thrust = %x %x %x\n",XYZ(&obj->mtype.phys_info.thrust));
391                 printf("  sim_time = %x\n",sim_time);
392         }
393
394         //check for correct object segment 
395         if(!get_seg_masks(&obj->pos,obj->segnum,0).centermask==0) {
396                 #ifndef NDEBUG
397                 mprintf((0,"Warning: object %d not in given seg!\n",objnum));
398                 #endif
399                 //Int3();  Removed by Rob 10/5/94
400                 if (!update_object_seg(obj)) {
401                         #ifndef NDEBUG
402                         mprintf((0,"Warning: can't find seg for object %d - moving\n",objnum));
403                         #endif
404                         if (!(Game_mode & GM_MULTI))
405                                 Int3();
406                         compute_segment_center(&obj->pos,&Segments[obj->segnum]);
407                         obj->pos.x += objnum;
408                 }
409         }
410         #endif
411
412         start_pos = obj->pos;
413
414         n_ignore_objs = 0;
415
416         Assert(obj->mtype.phys_info.brakes==0);         //brakes not used anymore?
417
418                 //if uses thrust, cannot have zero drag
419         Assert(!(obj->mtype.phys_info.flags&PF_USES_THRUST) || obj->mtype.phys_info.drag!=0);
420
421 //mprintf((0,"thrust=%x  speed=%x\n",vm_vec_mag(&obj->mtype.phys_info.thrust),vm_vec_mag(&obj->mtype.phys_info.velocity)));
422
423         //do thrust & drag
424         
425         if ((drag = obj->mtype.phys_info.drag) != 0) {
426
427                 int count;
428                 vms_vector accel;
429                 fix r,k;
430
431                 count = sim_time / FT;
432                 r = sim_time % FT;
433                 k = fixdiv(r,FT);
434
435                 if (obj->mtype.phys_info.flags & PF_USES_THRUST) {
436
437                         vm_vec_copy_scale(&accel,&obj->mtype.phys_info.thrust,fixdiv(f1_0,obj->mtype.phys_info.mass));
438
439                         while (count--) {
440
441                                 vm_vec_add2(&obj->mtype.phys_info.velocity,&accel);
442
443                                 vm_vec_scale(&obj->mtype.phys_info.velocity,f1_0-drag);
444                         }
445
446                         //do linear scale on remaining bit of time
447
448                         vm_vec_scale_add2(&obj->mtype.phys_info.velocity,&accel,k);
449
450                         vm_vec_scale(&obj->mtype.phys_info.velocity,f1_0-fixmul(k,drag));
451                 }
452                 else {
453                         fix total_drag=f1_0;
454
455                         while (count--)
456                                 total_drag = fixmul(total_drag,f1_0-drag);
457
458                         //do linear scale on remaining bit of time
459
460                         total_drag = fixmul(total_drag,f1_0-fixmul(k,drag));
461
462                         vm_vec_scale(&obj->mtype.phys_info.velocity,total_drag);
463                 }
464         }
465
466         #ifdef EXTRA_DEBUG
467         if (obj == debug_obj)
468                 printf("  velocity = %x %x %x\n",XYZ(&obj->mtype.phys_info.velocity));
469         #endif
470
471         do {
472                 try_again = 0;
473
474                 //Move the object
475                 vm_vec_copy_scale(&frame_vec, &obj->mtype.phys_info.velocity, sim_time);
476
477                 #ifdef EXTRA_DEBUG
478                 if (obj == debug_obj)
479                         printf("  pass %d, frame_vec = %x %x %x\n",count,XYZ(&frame_vec));
480                 #endif
481
482                 if ( (frame_vec.x==0) && (frame_vec.y==0) && (frame_vec.z==0) ) 
483                         break;
484
485                 count++;
486
487                 //      If retry count is getting large, then we are trying to do something stupid.
488                 if ( count > 3)         {
489                         if (obj->type == OBJ_PLAYER) {
490                                 if (count > 8)
491                                         break;
492                         } else
493                                 break;
494                 }
495
496                 vm_vec_add(&new_pos,&obj->pos,&frame_vec);
497
498                 #ifdef EXTRA_DEBUG
499                 if (obj == debug_obj)
500                         printf("   desired_pos  = %x %x %x\n",XYZ(&new_pos));
501                 #endif
502
503                 ignore_obj_list[n_ignore_objs] = -1;
504
505                 #ifdef EXTRA_DEBUG
506                 if (obj == debug_obj) {
507                         printf("   FVI parms: p0 = %8x %8x %8x, segnum=%x, size=%x\n",XYZ(&obj->pos),obj->segnum,obj->size);
508                         printf("              p1 = %8x %8x %8x\n",XYZ(&new_pos));
509                 }
510                 #endif
511
512                 fq.p0                                           = &obj->pos;
513                 fq.startseg                             = obj->segnum;
514                 fq.p1                                           = &new_pos;
515                 fq.rad                                  = obj->size;
516                 fq.thisobjnum                   = objnum;
517                 fq.ignore_obj_list      = ignore_obj_list;
518                 fq.flags                                        = FQ_CHECK_OBJS;
519
520                 if (obj->type == OBJ_WEAPON)
521                         fq.flags |= FQ_TRANSPOINT;
522
523                 if (obj->type == OBJ_PLAYER)
524                         fq.flags |= FQ_GET_SEGLIST;
525
526 //@@                    if (get_seg_masks(&obj->pos,obj->segnum,0).centermask!=0)
527 //@@                            Int3();
528
529 save_p0 = *fq.p0;
530 save_p1 = *fq.p1;
531
532
533                 fate = find_vector_intersection(&fq,&hit_info);
534                 //      Matt: Mike's hack.
535                 if (fate == HIT_OBJECT) {
536                         object  *objp = &Objects[hit_info.hit_object];
537
538                         if ((objp->type == OBJ_WEAPON) && ((objp->id == PROXIMITY_ID) || (objp->id == SUPERPROX_ID)))
539                                 count--;
540                 }
541
542                 #ifndef NDEBUG
543                 if (fate == HIT_BAD_P0) {
544                         mprintf((0,"Warning: Bad p0 in physics!  Object = %i, type = %i [%s]\n", obj-Objects, obj->type, Object_type_names[obj->type]));
545                         Int3();
546                 }
547                 #endif
548
549                 if (obj->type == OBJ_PLAYER) {
550                         int i;
551
552                         if (n_phys_segs && phys_seglist[n_phys_segs-1]==hit_info.seglist[0])
553                                 n_phys_segs--;
554
555                         for (i=0;(i<hit_info.n_segs) && (n_phys_segs<MAX_FVI_SEGS-1);  )
556                                 phys_seglist[n_phys_segs++] = hit_info.seglist[i++];
557                 }
558
559                 #ifdef EXTRA_DEBUG
560                 if (obj == debug_obj)
561                         printf("   fate  = %d, hit_pnt = %8x %8x %8x\n",fate,XYZ(&hit_info.hit_pnt));;
562                 #endif
563
564                 ipos = hit_info.hit_pnt;
565                 iseg = hit_info.hit_seg;
566                 WallHitSide = hit_info.hit_side;
567                 WallHitSeg = hit_info.hit_side_seg;
568
569                 if (iseg==-1) {         //some sort of horrible error
570                         #ifndef NDEBUG
571                         mprintf((1,"iseg==-1 in physics!  Object = %i, type = %i (%s)\n", obj-Objects, obj->type, Object_type_names[obj->type]));
572                         #endif
573                         //Int3();
574                         //compute_segment_center(&ipos,&Segments[obj->segnum]);
575                         //ipos.x += objnum;
576                         //iseg = obj->segnum;
577                         //fate = HIT_NONE;
578                         if (obj->type == OBJ_WEAPON)
579                                 obj->flags |= OF_SHOULD_BE_DEAD;
580                         break;
581                 }
582
583                 Assert(!((fate==HIT_WALL) && ((WallHitSeg == -1) || (WallHitSeg > Highest_segment_index))));
584
585                 //if(!get_seg_masks(&hit_info.hit_pnt,hit_info.hit_seg,0).centermask==0)
586                 //      Int3();
587
588                 save_pos = obj->pos;                    //save the object's position
589                 save_seg = obj->segnum;
590
591                 // update object's position and segment number
592                 obj->pos = ipos;
593
594                 #ifdef EXTRA_DEBUG
595                 if (obj == debug_obj)
596                         printf("   new pos = %x %x %x\n",XYZ(&obj->pos));
597                 #endif
598
599                 if ( iseg != obj->segnum )
600                         obj_relink(objnum, iseg );
601
602                 //if start point not in segment, move object to center of segment
603                 if (get_seg_masks(&obj->pos,obj->segnum,0).centermask!=0) {
604                         int n;
605
606                         if ((n=find_object_seg(obj))==-1) {
607                                 //Int3();
608                                 if (obj->type==OBJ_PLAYER && (n=find_point_seg(&obj->last_pos,obj->segnum))!=-1) {
609                                         obj->pos = obj->last_pos;
610                                         obj_relink(objnum, n );
611                                 }
612                                 else {
613                                         compute_segment_center(&obj->pos,&Segments[obj->segnum]);
614                                         obj->pos.x += objnum;
615                                 }
616                                 if (obj->type == OBJ_WEAPON)
617                                         obj->flags |= OF_SHOULD_BE_DEAD;
618                         }
619                         return;
620                 }
621
622                 //calulate new sim time
623                 {
624                         //vms_vector moved_vec;
625                         vms_vector moved_vec_n;
626                         fix attempted_dist,actual_dist;
627
628                         old_sim_time = sim_time;
629
630                         actual_dist = vm_vec_normalized_dir(&moved_vec_n,&obj->pos,&save_pos);
631
632                         if (fate==HIT_WALL && vm_vec_dot(&moved_vec_n,&frame_vec) < 0) {                //moved backwards
633
634                                 //don't change position or sim_time
635
636 //*******                                       mprintf((0,"Obj %d moved backwards\n",obj-Objects));
637
638                                 #ifdef EXTRA_DEBUG
639                                 if (obj == debug_obj)
640                                         printf("   Warning: moved backwards!\n");
641                                 #endif
642
643                                 obj->pos = save_pos;
644                 
645                                 //iseg = obj->segnum;           //don't change segment
646
647                                 obj_relink(objnum, save_seg );
648
649                                 moved_time = 0;
650                         }
651                         else {
652
653                                 //if (obj == debug_obj)
654                                 //      printf("   moved_vec = %x %x %x\n",XYZ(&moved_vec));
655                         
656                                 attempted_dist = vm_vec_mag(&frame_vec);
657
658                                 sim_time = fixmuldiv(sim_time,attempted_dist-actual_dist,attempted_dist);
659
660                                 moved_time = old_sim_time - sim_time;
661
662                                 if (sim_time < 0 || sim_time>old_sim_time) {
663                                         #ifndef NDEBUG
664                                         mprintf((0,"Bogus sim_time = %x, old = %x\n",sim_time,old_sim_time));
665                                         if (obj == debug_obj)
666                                                 printf("   Bogus sim_time = %x, old = %x, attempted_dist = %x, actual_dist = %x\n",sim_time,old_sim_time,attempted_dist,actual_dist);
667                                         //Int3(); Removed by Rob
668                                         #endif
669                                         sim_time = old_sim_time;
670                                         //WHY DOES THIS HAPPEN??
671
672                                         moved_time = 0;
673                                 }
674                         }
675
676                         #ifdef EXTRA_DEBUG
677                         if (obj == debug_obj)
678                                 printf("   new sim_time = %x\n",sim_time);
679                         #endif
680
681                 }
682
683
684                 switch( fate )          {
685
686                         case HIT_WALL:          {
687                                 vms_vector moved_v;
688                                 //@@fix total_d,moved_d;
689                                 fix hit_speed,wall_part;
690         
691                                 // Find hit speed       
692
693                                 vm_vec_sub(&moved_v,&obj->pos,&save_pos);
694
695                                 wall_part = vm_vec_dot(&moved_v,&hit_info.hit_wallnorm);
696
697                                 if (wall_part != 0 && moved_time>0 && (hit_speed=-fixdiv(wall_part,moved_time))>0)
698                                         collide_object_with_wall( obj, hit_speed, WallHitSeg, WallHitSide, &hit_info.hit_pnt );
699                                 else
700                                         scrape_object_on_wall(obj, WallHitSeg, WallHitSide, &hit_info.hit_pnt );
701
702                                 Assert( WallHitSeg > -1 );
703                                 Assert( WallHitSide > -1 );
704
705                                 if ( !(obj->flags&OF_SHOULD_BE_DEAD) )  {
706                                         int forcefield_bounce;          //bounce off a forcefield
707
708                                         Assert(BounceCheat || !(obj->mtype.phys_info.flags & PF_STICK && obj->mtype.phys_info.flags & PF_BOUNCE));      //can't be bounce and stick
709
710                                         forcefield_bounce = (TmapInfo[Segments[WallHitSeg].sides[WallHitSide].tmap_num].flags & TMI_FORCE_FIELD);
711
712                                         if (!forcefield_bounce && (obj->mtype.phys_info.flags & PF_STICK)) {            //stop moving
713
714                                                 // mprintf((0, "Object %i stuck at %i:%i\n", obj-Objects, WallHitSeg, WallHitSide));
715                                                 add_stuck_object(obj, WallHitSeg, WallHitSide);
716
717                                                 vm_vec_zero(&obj->mtype.phys_info.velocity);
718                                                 obj_stopped = 1;
719                                                 try_again = 0;
720                                         }
721                                         else {                                  // Slide object along wall
722                                                 int check_vel=0;
723
724                                                 //We're constrained by wall, so subtract wall part from 
725                                                 //velocity vector
726
727                                                 wall_part = vm_vec_dot(&hit_info.hit_wallnorm,&obj->mtype.phys_info.velocity);
728
729 //                                              mprintf((0, "%d", f2i(vm_vec_mag(&hit_info.hit_wallnorm)) ));
730
731                                                 if (forcefield_bounce || (obj->mtype.phys_info.flags & PF_BOUNCE)) {            //bounce off wall
732                                                         wall_part *= 2; //Subtract out wall part twice to achieve bounce
733
734                                                         if (forcefield_bounce) {
735                                                                 check_vel = 1;                          //check for max velocity
736                                                                 if (obj->type == OBJ_PLAYER)
737                                                                         wall_part *= 2;         //player bounce twice as much
738                                                         }
739
740                                                         if ( obj->mtype.phys_info.flags & PF_BOUNCES_TWICE) {
741                                                                 Assert(obj->mtype.phys_info.flags & PF_BOUNCE);
742                                                                 if (obj->mtype.phys_info.flags & PF_BOUNCED_ONCE)
743                                                                         obj->mtype.phys_info.flags &= ~(PF_BOUNCE+PF_BOUNCED_ONCE+PF_BOUNCES_TWICE);
744                                                                 else
745                                                                         obj->mtype.phys_info.flags |= PF_BOUNCED_ONCE;
746                                                         }
747
748                                                         bounced = 1;            //this object bounced
749                                                 }
750
751                                                 vm_vec_scale_add2(&obj->mtype.phys_info.velocity,&hit_info.hit_wallnorm,-wall_part);
752
753 //                                              mprintf((0, "Velocity at bounce time = %d\n", f2i(vm_vec_mag(&obj->mtype.phys_info.velocity))));
754
755 //if (obj==ConsoleObject)
756 //      mprintf((0,"player vel = %x\n",vm_vec_mag_quick(&obj->mtype.phys_info.velocity)));
757
758                                                 if (check_vel) {
759                                                         fix vel = vm_vec_mag_quick(&obj->mtype.phys_info.velocity);
760
761                                                         if (vel > MAX_OBJECT_VEL)
762                                                                 vm_vec_scale(&obj->mtype.phys_info.velocity,fixdiv(MAX_OBJECT_VEL,vel));
763                                                 }
764
765                                                 if (bounced && obj->type == OBJ_WEAPON)
766                                                         vm_vector_2_matrix(&obj->orient,&obj->mtype.phys_info.velocity,&obj->orient.uvec,NULL);
767
768                                                 #ifdef EXTRA_DEBUG
769                                                 if (obj == debug_obj) {
770                                                         printf("   sliding - wall_norm %x %x %x %x\n",wall_part,XYZ(&hit_info.hit_wallnorm));
771                                                         printf("   wall_part %x, new velocity = %x %x %x\n",wall_part,XYZ(&obj->mtype.phys_info.velocity));
772                                                 }
773                                                 #endif
774
775                                                 try_again = 1;
776                                         }
777                                 }
778                                 break;
779                         }
780
781                         case HIT_OBJECT:                {
782                                 vms_vector old_vel;
783
784                                 // Mark the hit object so that on a retry the fvi code
785                                 // ignores this object.
786
787                                 Assert(hit_info.hit_object != -1);
788
789                                 //      Calculcate the hit point between the two objects.
790                                 {       vms_vector      *ppos0, *ppos1, pos_hit;
791                                         fix                     size0, size1;
792                                         ppos0 = &Objects[hit_info.hit_object].pos;
793                                         ppos1 = &obj->pos;
794                                         size0 = Objects[hit_info.hit_object].size;
795                                         size1 = obj->size;
796                                         Assert(size0+size1 != 0);       // Error, both sizes are 0, so how did they collide, anyway?!?
797                                         //vm_vec_scale(vm_vec_sub(&pos_hit, ppos1, ppos0), fixdiv(size0, size0 + size1));
798                                         //vm_vec_add2(&pos_hit, ppos0);
799                                         vm_vec_sub(&pos_hit, ppos1, ppos0);
800                                         vm_vec_scale_add(&pos_hit,ppos0,&pos_hit,fixdiv(size0, size0 + size1));
801
802                                         old_vel = obj->mtype.phys_info.velocity;
803
804                                         collide_two_objects( obj, &Objects[hit_info.hit_object], &pos_hit);
805
806                                 }
807
808                                 // Let object continue its movement
809                                 if ( !(obj->flags&OF_SHOULD_BE_DEAD)  ) {
810                                         //obj->pos = save_pos;
811
812                                         if (obj->mtype.phys_info.flags&PF_PERSISTENT || (old_vel.x == obj->mtype.phys_info.velocity.x && old_vel.y == obj->mtype.phys_info.velocity.y && old_vel.z == obj->mtype.phys_info.velocity.z)) {
813                                                 //if (Objects[hit_info.hit_object].type == OBJ_POWERUP)
814                                                         ignore_obj_list[n_ignore_objs++] = hit_info.hit_object;
815                                                 try_again = 1;
816                                         }
817                                 }
818
819                                 break;
820                         }       
821                         case HIT_NONE:          
822                         #ifdef TACTILE
823                                 if (TactileStick && obj==ConsoleObject && !(FrameCount & 15))
824                                  Tactile_Xvibrate_clear ();
825                         #endif
826                                 break;
827
828                         #ifndef NDEBUG
829                         case HIT_BAD_P0:
830                                 Int3();         // Unexpected collision type: start point not in specified segment.
831                                 mprintf((0,"Warning: Bad p0 in physics!!!\n"));
832                                 break;
833                         default:
834                                 // Unknown collision type returned from find_vector_intersection!!
835                                 Int3();
836                                 break;
837                         #endif
838                 }
839
840         } while ( try_again );
841
842         //      Pass retry count info to AI.
843         if (obj->control_type == CT_AI) {
844                 if (count > 0) {
845                         Ai_local_info[objnum].retry_count = count-1;
846                         #ifndef NDEBUG
847                         Total_retries += count-1;
848                         Total_sims++;
849                         #endif
850                 }
851         }
852
853         //I'm not sure why we do this.  I wish there were a comment that
854         //explained it.  I think maybe it only needs to be done if the object
855         //is sliding, but I don't know
856         if (!obj_stopped && !bounced)   {       //Set velocity from actual movement
857                 vms_vector moved_vec;
858
859                 vm_vec_sub(&moved_vec,&obj->pos,&start_pos);
860                 vm_vec_copy_scale(&obj->mtype.phys_info.velocity,&moved_vec,fixdiv(f1_0,FrameTime));
861
862                 #ifdef BUMP_HACK
863                 if (obj==ConsoleObject && (obj->mtype.phys_info.velocity.x==0 && obj->mtype.phys_info.velocity.y==0 && obj->mtype.phys_info.velocity.z==0) &&
864                           !(obj->mtype.phys_info.thrust.x==0 && obj->mtype.phys_info.thrust.y==0 && obj->mtype.phys_info.thrust.z==0)) {
865                         vms_vector center,bump_vec;
866
867                         //bump player a little towards center of segment to unstick
868
869                         compute_segment_center(&center,&Segments[obj->segnum]);
870                         vm_vec_normalized_dir_quick(&bump_vec,&center,&obj->pos);
871
872                         //don't bump player toward center of reactor segment
873                         if (Segment2s[obj->segnum].special == SEGMENT_IS_CONTROLCEN)
874                                 vm_vec_negate(&bump_vec);
875
876                         vm_vec_scale_add2(&obj->pos,&bump_vec,obj->size/5);
877
878                         //if moving away from seg, might move out of seg, so update
879                         if (Segment2s[obj->segnum].special == SEGMENT_IS_CONTROLCEN)
880                                 update_object_seg(obj);
881                 }
882                 #endif
883         }
884
885         //Assert(check_point_in_seg(&obj->pos,obj->segnum,0).centermask==0);
886
887         //if (obj->control_type == CT_FLYING)
888         if (obj->mtype.phys_info.flags & PF_LEVELLING)
889                 do_physics_align_object( obj );
890
891
892         //hack to keep player from going through closed doors
893         if (obj->type==OBJ_PLAYER && obj->segnum!=orig_segnum && (Physics_cheat_flag!=0xBADA55) ) {
894                 int sidenum;
895
896                 sidenum = find_connect_side(&Segments[obj->segnum],&Segments[orig_segnum]);
897
898                 if (sidenum != -1) {
899
900                         if (! (WALL_IS_DOORWAY(&Segments[orig_segnum],sidenum) & WID_FLY_FLAG)) {
901                                 side *s;
902                                 int vertnum,num_faces,i;
903                                 fix dist;
904                                 int vertex_list[6];
905
906                                 //bump object back
907
908                                 s = &Segments[orig_segnum].sides[sidenum];
909
910                                 if (orig_segnum==-1)
911                                         Error("orig_segnum == -1 in physics");
912
913                                 create_abs_vertex_lists( &num_faces, vertex_list, orig_segnum, sidenum);
914
915                                 //let's pretend this wall is not triangulated
916                                 vertnum = vertex_list[0];
917                                 for (i=1;i<4;i++)
918                                         if (vertex_list[i] < vertnum)
919                                                 vertnum = vertex_list[i];
920
921                                 #ifdef COMPACT_SEGS
922                                         {
923                                         vms_vector _vn;
924                                         get_side_normal(&Segments[orig_segnum], sidenum, 0, &_vn );
925                                         dist = vm_dist_to_plane(&start_pos, &_vn, &Vertices[vertnum]);
926                                         vm_vec_scale_add(&obj->pos,&start_pos,&_vn,obj->size-dist);
927                                         }
928                                 #else
929                                         dist = vm_dist_to_plane(&start_pos, &s->normals[0], &Vertices[vertnum]);
930                                         vm_vec_scale_add(&obj->pos,&start_pos,&s->normals[0],obj->size-dist);
931                                 #endif
932                                 update_object_seg(obj);
933
934                         }
935                 }
936         }
937
938 //--WE ALWYS WANT THIS IN, MATT AND MIKE DECISION ON 12/10/94, TWO MONTHS AFTER FINAL   #ifndef NDEBUG
939         //if end point not in segment, move object to last pos, or segment center
940         if (get_seg_masks(&obj->pos,obj->segnum,0).centermask!=0) {
941                 if (find_object_seg(obj)==-1) {
942                         int n;
943
944                         //Int3();
945                         if (obj->type==OBJ_PLAYER && (n=find_point_seg(&obj->last_pos,obj->segnum))!=-1) {
946                                 obj->pos = obj->last_pos;
947                                 obj_relink(objnum, n );
948                         }
949                         else {
950                                 compute_segment_center(&obj->pos,&Segments[obj->segnum]);
951                                 obj->pos.x += objnum;
952                         }
953                         if (obj->type == OBJ_WEAPON)
954                                 obj->flags |= OF_SHOULD_BE_DEAD;
955                 }
956         }
957 //--WE ALWYS WANT THIS IN, MATT AND MIKE DECISION ON 12/10/94, TWO MONTHS AFTER FINAL   #endif
958
959
960 }
961
962 //--unused-- //tell us what the given object will do (as far as hiting walls) in
963 //--unused-- //the given time (in seconds) t.  Igores acceleration (sorry) 
964 //--unused-- //if check_objects is set, check with objects, else just with walls
965 //--unused-- //returns fate, fills in hit time.  If fate==HIT_NONE, hit_time undefined
966 //--unused-- int physics_lookahead(object *obj,fix t,int fvi_flags,fix *hit_time, fvi_info *hit_info)
967 //--unused-- {
968 //--unused--    vms_vector new_pos;
969 //--unused--    int objnum,fate;
970 //--unused--    fvi_query fq;
971 //--unused-- 
972 //--unused--    Assert(obj->movement_type == MT_PHYSICS);
973 //--unused-- 
974 //--unused--    objnum = obj-Objects;
975 //--unused-- 
976 //--unused--    vm_vec_scale_add(&new_pos, &obj->pos, &obj->mtype.phys_info.velocity, t);
977 //--unused-- 
978 //--unused--    fq.p0                                           = &obj->pos;
979 //--unused--    fq.startseg                             = obj->segnum;
980 //--unused--    fq.p1                                           = &new_pos;
981 //--unused--    fq.rad                                  = obj->size;
982 //--unused--    fq.thisobjnum                   = objnum;
983 //--unused--    fq.ignore_obj_list      = NULL;
984 //--unused--    fq.flags                                        = fvi_flags;
985 //--unused-- 
986 //--unused--    fate = find_vector_intersection(&fq,hit_info);
987 //--unused-- 
988 //--unused--    if (fate != HIT_NONE) {
989 //--unused--            fix dist,speed;
990 //--unused-- 
991 //--unused--            dist = vm_vec_dist(&obj->pos, &hit_info->hit_pnt);
992 //--unused-- 
993 //--unused--            speed = vm_vec_mag(&obj->mtype.phys_info.velocity);
994 //--unused-- 
995 //--unused--            *hit_time = fixdiv(dist,speed);
996 //--unused-- 
997 //--unused--    }
998 //--unused-- 
999 //--unused--    return fate;
1000 //--unused-- 
1001 //--unused-- }
1002
1003 //Applies an instantaneous force on an object, resulting in an instantaneous
1004 //change in velocity.
1005 void phys_apply_force(object *obj,vms_vector *force_vec)
1006 {
1007
1008         //      Put in by MK on 2/13/96 for force getting applied to Omega blobs, which have 0 mass,
1009         //      in collision with crazy reactor robot thing on d2levf-s.
1010         if (obj->mtype.phys_info.mass == 0)
1011                 return;
1012
1013         if (obj->movement_type != MT_PHYSICS)
1014                 return;
1015
1016 #ifdef TACTILE
1017    if (TactileStick && obj==&Objects[Players[Player_num].objnum])
1018                 Tactile_apply_force (force_vec,&obj->orient);
1019 #endif
1020  
1021         //Add in acceleration due to force
1022         vm_vec_scale_add2(&obj->mtype.phys_info.velocity,force_vec,fixdiv(f1_0,obj->mtype.phys_info.mass));
1023
1024
1025 }
1026
1027 //      ----------------------------------------------------------------
1028 //      Do *dest = *delta unless:
1029 //                              *delta is pretty small
1030 //              and     they are of different signs.
1031 void physics_set_rotvel_and_saturate(fix *dest, fix delta)
1032 {
1033         if ((delta ^ *dest) < 0) {
1034                 if (abs(delta) < F1_0/8) {
1035                         // mprintf((0, "D"));
1036                         *dest = delta/4;
1037                 } else
1038                         // mprintf((0, "d"));
1039                         *dest = delta;
1040         } else {
1041                 // mprintf((0, "!"));
1042                 *dest = delta;
1043         }
1044 }
1045
1046 //      ------------------------------------------------------------------------------------------------------
1047 //      Note: This is the old ai_turn_towards_vector code.
1048 //      phys_apply_rot used to call ai_turn_towards_vector until I fixed it, which broke phys_apply_rot.
1049 void physics_turn_towards_vector(vms_vector *goal_vector, object *obj, fix rate)
1050 {
1051         vms_angvec      dest_angles, cur_angles;
1052         fix                     delta_p, delta_h;
1053         vms_vector      *rotvel_ptr = &obj->mtype.phys_info.rotvel;
1054
1055         // Make this object turn towards the goal_vector.  Changes orientation, doesn't change direction of movement.
1056         // If no one moves, will be facing goal_vector in 1 second.
1057
1058         //      Detect null vector.
1059         if ((goal_vector->x == 0) && (goal_vector->y == 0) && (goal_vector->z == 0))
1060                 return;
1061
1062         //      Make morph objects turn more slowly.
1063         if (obj->control_type == CT_MORPH)
1064                 rate *= 2;
1065
1066         vm_extract_angles_vector(&dest_angles, goal_vector);
1067         vm_extract_angles_vector(&cur_angles, &obj->orient.fvec);
1068
1069         delta_p = (dest_angles.p - cur_angles.p);
1070         delta_h = (dest_angles.h - cur_angles.h);
1071
1072         if (delta_p > F1_0/2) delta_p = dest_angles.p - cur_angles.p - F1_0;
1073         if (delta_p < -F1_0/2) delta_p = dest_angles.p - cur_angles.p + F1_0;
1074         if (delta_h > F1_0/2) delta_h = dest_angles.h - cur_angles.h - F1_0;
1075         if (delta_h < -F1_0/2) delta_h = dest_angles.h - cur_angles.h + F1_0;
1076
1077         delta_p = fixdiv(delta_p, rate);
1078         delta_h = fixdiv(delta_h, rate);
1079
1080         if (abs(delta_p) < F1_0/16) delta_p *= 4;
1081         if (abs(delta_h) < F1_0/16) delta_h *= 4;
1082
1083         physics_set_rotvel_and_saturate(&rotvel_ptr->x, delta_p);
1084         physics_set_rotvel_and_saturate(&rotvel_ptr->y, delta_h);
1085         rotvel_ptr->z = 0;
1086 }
1087
1088 //      -----------------------------------------------------------------------------
1089 //      Applies an instantaneous whack on an object, resulting in an instantaneous
1090 //      change in orientation.
1091 void phys_apply_rot(object *obj,vms_vector *force_vec)
1092 {
1093         fix     rate, vecmag;
1094
1095         if (obj->movement_type != MT_PHYSICS)
1096                 return;
1097
1098         vecmag = vm_vec_mag(force_vec)/8;
1099         if (vecmag < F1_0/256)
1100                 rate = 4*F1_0;
1101         else if (vecmag < obj->mtype.phys_info.mass >> 14)
1102                 rate = 4*F1_0;
1103         else {
1104                 rate = fixdiv(obj->mtype.phys_info.mass, vecmag);
1105                 if (obj->type == OBJ_ROBOT) {
1106                         if (rate < F1_0/4)
1107                                 rate = F1_0/4;
1108                         //      Changed by mk, 10/24/95, claw guys should not slow down when attacking!
1109                         if (!Robot_info[obj->id].thief && !Robot_info[obj->id].attack_type) {
1110                                 if (obj->ctype.ai_info.SKIP_AI_COUNT * FrameTime < 3*F1_0/4) {
1111                                         fix     tval = fixdiv(F1_0, 8*FrameTime);
1112                                         int     addval;
1113
1114                                         addval = f2i(tval);
1115
1116                                         if ( (d_rand() * 2) < (tval & 0xffff))
1117                                                 addval++;
1118                                         obj->ctype.ai_info.SKIP_AI_COUNT += addval;
1119                                         // -- mk: too much stuff making hard to see my debug messages...mprintf((0, "FrameTime = %7.3f, addval = %i\n", f2fl(FrameTime), addval));
1120                                 }
1121                         }
1122                 } else {
1123                         if (rate < F1_0/2)
1124                                 rate = F1_0/2;
1125                 }
1126         }
1127
1128         //      Turn amount inversely proportional to mass.  Third parameter is seconds to do 360 turn.
1129         physics_turn_towards_vector(force_vec, obj, rate);
1130
1131
1132 }
1133
1134
1135 //this routine will set the thrust for an object to a value that will
1136 //(hopefully) maintain the object's current velocity
1137 void set_thrust_from_velocity(object *obj)
1138 {
1139         fix k;
1140
1141         Assert(obj->movement_type == MT_PHYSICS);
1142
1143         k = fixmuldiv(obj->mtype.phys_info.mass,obj->mtype.phys_info.drag,(f1_0-obj->mtype.phys_info.drag));
1144
1145         vm_vec_copy_scale(&obj->mtype.phys_info.thrust,&obj->mtype.phys_info.velocity,k);
1146
1147 }
1148
1149