This commit was generated by cvs2svn to compensate for changes in r2,
[btb/d2x.git] / main / endlevel.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: endlevel.c,v 1.1.1.1 2001-01-19 03:30:01 bradleyb Exp $";
16 #endif
17
18 #include <conf.h>
19
20 //#define SLEW_ON 1
21
22 //#define _MARK_ON
23
24 #include <stdlib.h>
25
26
27 #include <stdio.h>
28 #include <string.h>
29
30 #include "fix.h"
31 #include "vecmat.h"
32 #include "gr.h"
33 #include "3d.h"
34 #include "error.h"
35 #include "palette.h"
36 #include "iff.h"
37 #include "mono.h"
38 #include "texmap.h"
39 #include "fvi.h"
40 #include "u_mem.h"
41 #include "sounds.h"
42
43 #include "inferno.h"
44 #include "endlevel.h"
45 #include "object.h"
46 #include "game.h"
47 #include "screens.h"
48 #include "gauges.h"
49 #include "wall.h"
50 #include "terrain.h"
51 #include "polyobj.h"
52 #include "bm.h"
53 #include "gameseq.h"
54 #include "newdemo.h"
55 #include "multi.h"
56 #include "vclip.h"
57 #include "fireball.h"
58 #include "network.h"
59 #include "text.h"
60 #include "digi.h"
61 #include "cfile.h"
62 #include "compbit.h"
63 #include "songs.h"
64 #include "movie.h"
65 #include "render.h"
66
67 typedef struct flythrough_data {
68         object          *obj;
69         vms_angvec      angles;                 //orientation in angles
70         vms_vector      step;                           //how far in a second
71         vms_vector      angstep;                        //rotation per second
72         fix                     speed;                  //how fast object is moving
73         vms_vector      headvec;                        //where we want to be pointing
74         int                     first_time;             //flag for if first time through
75         fix                     offset_frac;    //how far off-center as portion of way
76         fix                     offset_dist;    //how far currently off-center
77 } flythrough_data;
78
79 //endlevel sequence states
80
81 #define EL_OFF                          0               //not in endlevel
82 #define EL_FLYTHROUGH   1               //auto-flythrough in tunnel
83 #define EL_LOOKBACK             2               //looking back at player
84 #define EL_OUTSIDE              3               //flying outside for a while
85 #define EL_STOPPED              4               //stopped, watching explosion
86 #define EL_PANNING              5               //panning around, watching player
87 #define EL_CHASING              6               //chasing player to station
88
89 #define SHORT_SEQUENCE  1               //if defined, end sequnce when panning starts
90 //#define STATION_ENABLED       1               //if defined, load & use space station model
91
92 int Endlevel_sequence = 0;
93
94 extern fix player_speed;
95
96 int transition_segnum,exit_segnum;
97
98 object *endlevel_camera;
99
100 #define FLY_SPEED i2f(50)
101
102 void start_endlevel_flythrough(int n,object *obj,fix speed);
103
104 #ifdef D2_OEM
105 char movie_table[] =    {       'a','a','a','a','d','d','d','d' };
106 #else
107 char movie_table[] =    {       'a','b','c',
108                                                 #ifndef SHAREWARE
109                                                         'a',
110                                                         'd','f','d','f',
111                                                         'g','h','i','g',
112                                                         'j','k','l','j',
113                                                         'm','o','m','o',
114                                                         'p','q','p','q'
115                                                 #endif
116                                         };
117 #endif
118
119 #define N_MOVIES (sizeof(movie_table) / sizeof(*movie_table))
120
121 #ifndef SHAREWARE
122 #ifdef D2_OEM
123 char movie_table_secret[] = {'a','d'};
124 #else
125 char movie_table_secret[] = {'a','d','g','j','m','p'};
126 #endif
127 #define N_MOVIES_SECRET (sizeof(movie_table_secret) / sizeof(*movie_table_secret))
128 #else
129 #define N_MOVIES_SECRET 0
130 #endif
131
132
133 #define FLY_ACCEL i2f(5)
134
135 fix cur_fly_speed,desired_fly_speed;
136
137 extern int matt_find_connect_side(int seg0,int seg1);
138
139 grs_bitmap *satellite_bitmap,*station_bitmap,*terrain_bitmap;   //!!*exit_bitmap,
140 vms_vector satellite_pos,satellite_upvec;
141 //!!grs_bitmap **exit_bitmap_list[1];
142 int station_modelnum,exit_modelnum,destroyed_exit_modelnum;
143
144 vms_vector station_pos = {0xf8c4<<10,0x3c1c<<12,0x372<<10};
145
146 #ifdef STATION_ENABLED
147 grs_bitmap *station_bitmap;
148 grs_bitmap **station_bitmap_list[1];
149 int station_modelnum;
150 #endif
151
152 vms_vector mine_exit_point;
153 vms_vector mine_ground_exit_point;
154 vms_vector mine_side_exit_point;
155 vms_matrix mine_exit_orient;
156
157 int outside_mine;
158
159 void start_endlevel_flythrough(int n,object *obj,fix speed);
160
161 grs_bitmap terrain_bm_instance;
162 grs_bitmap satellite_bm_instance;
163
164 //find delta between two angles
165 fixang delta_ang(fixang a,fixang b)
166 {
167         fixang delta0,delta1;
168
169         return (abs(delta0 = a - b) < abs(delta1 = b - a)) ? delta0 : delta1;
170
171 }
172
173 //return though which side of seg0 is seg1
174 int matt_find_connect_side(int seg0,int seg1)
175 {
176         segment *Seg=&Segments[seg0];
177         int i;
178
179         for (i=MAX_SIDES_PER_SEGMENT;i--;) if (Seg->children[i]==seg1) return i;
180
181         return -1;
182 }
183
184 extern int Kmatrix_nomovie_message;
185
186 #if defined(D2_OEM) || defined(COMPILATION)
187 #define MOVIE_REQUIRED 0
188 #else
189 #define MOVIE_REQUIRED 1
190 #endif
191
192 //returns movie played status.  see movie.h
193 int start_endlevel_movie()
194 {
195         char movie_name[] = "esa.mve";
196    int r;
197         ubyte save_pal[768];
198
199         Assert(Current_mission_num == 0);               //only play movie for built-in mission
200
201         Assert(N_MOVIES >= Last_level);
202         Assert(N_MOVIES_SECRET >= -Last_secret_level);
203
204         #ifndef D2_OEM
205         if (Current_level_num == Last_level)
206                 return 1;       //don't play movie
207         #endif
208
209         if (Current_level_num > 0)
210                 movie_name[2] = movie_table[Current_level_num-1];
211         else {
212                 #ifndef SHAREWARE
213                         return 0;               //no escapes for secret level 
214                 #else
215                         Error("Invalid level number <%d>",Current_level_num);
216                 #endif
217         }
218
219         memcpy(save_pal,gr_palette,768);
220
221         #ifndef SHAREWARE
222                 r=PlayMovie(movie_name,(Game_mode & GM_MULTI)?0:MOVIE_REQUIRED);
223         #else
224                 return  0;      // movie not played for shareware
225         #endif
226
227         if (Newdemo_state == ND_STATE_PLAYBACK) {
228                 set_screen_mode(SCREEN_GAME);
229                 memcpy(gr_palette,save_pal,768);
230         }
231
232 #ifdef NETWORK
233    if (r==MOVIE_NOT_PLAYED && (Game_mode & GM_MULTI))
234           Kmatrix_nomovie_message=1;
235         else
236           Kmatrix_nomovie_message=0;
237 #endif
238         
239         return (r);
240
241 }
242
243 #ifdef SHAREWARE
244 void
245 free_endlevel_data()
246 {
247         if (terrain_bm_instance.bm_data)
248                 d_free(terrain_bm_instance.bm_data);
249
250         if (satellite_bm_instance.bm_data)
251                 d_free(satellite_bm_instance.bm_data);
252 }
253
254 init_endlevel()
255 {
256         //##satellite_bitmap = bm_load("earth.bbm");
257         //##terrain_bitmap = bm_load("moon.bbm");
258         //##
259         //##load_terrain("matt5b.bbm");         //load bitmap as height array
260         //##//load_terrain("ttest2.bbm");               //load bitmap as height array
261         
262         #ifdef STATION_ENABLED
263         station_bitmap = bm_load("steel3.bbm");
264         station_bitmap_list[0] = &station_bitmap;
265
266         station_modelnum = load_polygon_model("station.pof",1,station_bitmap_list,NULL);
267         #endif
268
269 //!!    exit_bitmap = bm_load("steel1.bbm");
270 //!!    exit_bitmap_list[0] = &exit_bitmap;
271
272 //!!    exit_modelnum = load_polygon_model("exit01.pof",1,exit_bitmap_list,NULL);
273 //!!    destroyed_exit_modelnum = load_polygon_model("exit01d.pof",1,exit_bitmap_list,NULL);
274
275         generate_starfield();
276
277         atexit(free_endlevel_data);
278
279         terrain_bm_instance.bm_data = satellite_bm_instance.bm_data = NULL;
280 }
281 #endif  //SHAREWARE
282
283 object external_explosion;
284 int ext_expl_playing,mine_destroyed;
285
286 extern fix flash_scale;
287
288 vms_angvec exit_angles={-0xa00,0,0};
289
290 vms_matrix surface_orient;
291
292 int endlevel_data_loaded=0;
293 extern char last_palette_loaded[];
294
295 void start_endlevel_sequence()
296 {
297         int     i;
298         int movie_played;
299         #if defined(MACINTOSH) && defined(SHAREWARE)
300         static int inited = 0;
301         
302         if (!inited) {
303                 load_exit_models();
304                 inited = 1;
305         }
306         #endif
307
308         if (Newdemo_state == ND_STATE_RECORDING)                // stop demo recording
309                 Newdemo_state = ND_STATE_PAUSED;
310
311         if (Newdemo_state == ND_STATE_PLAYBACK) {               // don't do this if in playback mode
312                 if (Current_mission_num == 0)           //only play movie for built-in mission
313                         start_endlevel_movie();
314                 strcpy(last_palette_loaded,"");         //force palette load next time
315                 return;
316         }
317
318         if (Player_is_dead || ConsoleObject->flags&OF_SHOULD_BE_DEAD)
319                 return;                         //don't start if dead!
320
321         //      Dematerialize Buddy!
322         for (i=0; i<=Highest_object_index; i++)
323                 if (Objects[i].type == OBJ_ROBOT)
324                         if (Robot_info[Objects[i].id].companion) {
325                                 object_create_explosion(Objects[i].segnum, &Objects[i].pos, F1_0*7/2, VCLIP_POWERUP_DISAPPEARANCE );
326                                 Objects[i].flags |= OF_SHOULD_BE_DEAD;
327                         }
328
329         Players[Player_num].homing_object_dist = -F1_0; // Turn off homing sound.
330
331         reset_rear_view();              //turn off rear view if set
332
333 #ifdef NETWORK
334         if (Game_mode & GM_MULTI) {
335                 multi_send_endlevel_start(0);
336                 network_do_frame(1, 1);
337         }
338 #endif
339
340         if (Current_mission_num == 0) {         //only play movie for built-in mission
341
342                 //try playing movie.  If it plays, great. if not, do rendered ending
343                 
344                 if (!(Game_mode & GM_MULTI))
345                         movie_played = start_endlevel_movie();
346                 
347                 #ifdef SHAREWARE
348                 if (movie_played == MOVIE_NOT_PLAYED) {         //don't have movie.  Do rendered sequence
349                 #ifndef WINDOWS
350                         start_rendered_endlevel_sequence();
351                 #endif
352                         return;
353                 }
354                 #endif
355
356         }
357         else
358                 gr_palette_fade_out(gr_palette, 32, 0);
359
360         PlayerFinishedLevel(0);         //done with level
361 }
362
363 #ifndef SHAREWARE
364
365 void do_endlevel_frame() {Int3();}
366 void stop_endlevel_sequence() {Int3();}
367 void render_endlevel_frame(fix eye_offset) {Int3();}
368
369 #else
370
371 static int cockpit_mode_save;
372
373 start_rendered_endlevel_sequence()
374 {
375         int last_segnum,exit_side,tunnel_length;
376
377         {
378                 int segnum,old_segnum,entry_side,i;
379
380                 //count segments in exit tunnel
381
382                 old_segnum = ConsoleObject->segnum;
383                 exit_side = find_exit_side(ConsoleObject);
384                 segnum = Segments[old_segnum].children[exit_side];
385                 tunnel_length = 0;
386                 do {
387                         entry_side = matt_find_connect_side(segnum,old_segnum);
388                         exit_side = Side_opposite[entry_side];
389                         old_segnum = segnum;
390                         segnum = Segments[segnum].children[exit_side];
391                         tunnel_length++;
392                 } while (segnum >= 0);
393
394                 if (segnum != -2) {
395                         PlayerFinishedLevel(0);         //don't do special sequence
396                         return;
397                 }
398
399                 last_segnum = old_segnum;
400
401                 //now pick transition segnum 1/3 of the way in
402
403                 old_segnum = ConsoleObject->segnum;
404                 exit_side = find_exit_side(ConsoleObject);
405                 segnum = Segments[old_segnum].children[exit_side];
406                 i=tunnel_length/3;
407                 while (i--) {
408
409                         entry_side = matt_find_connect_side(segnum,old_segnum);
410                         exit_side = Side_opposite[entry_side];
411                         old_segnum = segnum;
412                         segnum = Segments[segnum].children[exit_side];
413                 }
414                 transition_segnum = segnum;
415
416         }
417
418         cockpit_mode_save = Cockpit_mode;
419
420         #ifdef NETWORK
421         if (Game_mode & GM_MULTI) {
422                 multi_send_endlevel_start(0);
423                 network_do_frame(1, 1);
424         }
425         #endif
426
427         #ifdef SHAREWARE
428         Assert(last_segnum == exit_segnum);
429         //      songs_play_song( SONG_ENDLEVEL, 0 );    // JTS: Until we get an exit song, just don't worry
430         #endif
431
432         Endlevel_sequence = EL_FLYTHROUGH;
433
434         ConsoleObject->movement_type = MT_NONE;                 //movement handled by flythrough
435         ConsoleObject->control_type = CT_NONE;
436
437         Game_suspended |= SUSP_ROBOTS;          //robots don't move
438
439         cur_fly_speed = desired_fly_speed = FLY_SPEED;
440
441         start_endlevel_flythrough(0,ConsoleObject,cur_fly_speed);               //initialize
442
443         HUD_init_message( TXT_EXIT_SEQUENCE );
444
445         outside_mine = ext_expl_playing = 0;
446
447         flash_scale = f1_0;
448
449         //init_endlevel();
450
451         mine_destroyed=0;
452
453 }
454
455 extern flythrough_data fly_objects[];
456
457 extern object *slew_obj;
458
459 vms_angvec player_angles,player_dest_angles;
460 vms_angvec camera_desired_angles,camera_cur_angles;
461
462 #define CHASE_TURN_RATE (0x4000/4)              //max turn per second
463
464 //returns bitmask of which angles are at dest. bits 0,1,2 = p,b,h
465 int chase_angles(vms_angvec *cur_angles,vms_angvec *desired_angles)
466 {
467         vms_angvec delta_angs,alt_angles,alt_delta_angs;
468         fix total_delta,alt_total_delta;
469         fix frame_turn;
470         int mask=0;
471
472         delta_angs.p = desired_angles->p - cur_angles->p;
473         delta_angs.h = desired_angles->h - cur_angles->h;
474         delta_angs.b = desired_angles->b - cur_angles->b;
475 //delta_angs.b = 0;
476
477 //printf("chasing angles...desired = %x %x %x, cur = %x %x %x   ",desired_angles->p,desired_angles->b,desired_angles->h,cur_angles->p,cur_angles->b,cur_angles->h);
478
479         total_delta = abs(delta_angs.p) + abs(delta_angs.b) + abs(delta_angs.h);
480
481         alt_angles.p = f1_0/2 - cur_angles->p;
482         alt_angles.b = cur_angles->b + f1_0/2;
483         alt_angles.h = cur_angles->h + f1_0/2;
484
485         alt_delta_angs.p = desired_angles->p - alt_angles.p;
486         alt_delta_angs.h = desired_angles->h - alt_angles.h;
487         alt_delta_angs.b = desired_angles->b - alt_angles.b;
488 //alt_delta_angs.b = 0;
489
490         alt_total_delta = abs(alt_delta_angs.p) + abs(alt_delta_angs.b) + abs(alt_delta_angs.h);
491
492 //printf("Total delta = %x, alt total_delta = %x\n",total_delta,alt_total_delta);
493
494         if (alt_total_delta < total_delta) {
495                 //mprintf((0,"FLIPPING ANGLES!\n"));
496                 //printf("FLIPPING ANGLES!\n");
497                 *cur_angles = alt_angles;
498                 delta_angs = alt_delta_angs;
499         }
500
501         frame_turn = fixmul(FrameTime,CHASE_TURN_RATE);
502
503         if (abs(delta_angs.p) < frame_turn) {
504                 cur_angles->p = desired_angles->p;
505                 mask |= 1;
506         }
507         else
508                 if (delta_angs.p > 0)
509                         cur_angles->p += frame_turn;
510                 else
511                         cur_angles->p -= frame_turn;
512
513         if (abs(delta_angs.b) < frame_turn) {
514                 cur_angles->b = desired_angles->b;
515                 mask |= 2;
516         }
517         else
518                 if (delta_angs.b > 0)
519                         cur_angles->b += frame_turn;
520                 else
521                         cur_angles->b -= frame_turn;
522 //cur_angles->b = 0;
523
524         if (abs(delta_angs.h) < frame_turn) {
525                 cur_angles->h = desired_angles->h;
526                 mask |= 4;
527         }
528         else
529                 if (delta_angs.h > 0)
530                         cur_angles->h += frame_turn;
531                 else
532                         cur_angles->h -= frame_turn;
533
534         return mask;
535 }
536
537 stop_endlevel_sequence()
538 {
539         Interpolation_method = 0;
540
541         gr_palette_fade_out(gr_palette, 32, 0);
542
543         select_cockpit(cockpit_mode_save);
544
545         Endlevel_sequence = EL_OFF;
546
547         PlayerFinishedLevel(0);
548
549 }
550
551 #define VCLIP_BIG_PLAYER_EXPLOSION      58
552
553 //--unused-- vms_vector upvec = {0,f1_0,0};
554
555 //find the angle between the player's heading & the station
556 get_angs_to_object(vms_angvec *av,vms_vector *targ_pos,vms_vector *cur_pos)
557 {
558         vms_vector tv;
559
560         vm_vec_sub(&tv,targ_pos,cur_pos);
561
562         vm_extract_angles_vector(av,&tv);
563 }
564
565 do_endlevel_frame()
566 {
567         #ifdef SHAREWARE
568         static fix timer;
569         static fix bank_rate;
570         #endif
571         vms_vector save_last_pos;
572         static fix explosion_wait1=0;
573         static fix explosion_wait2=0;
574         static fix ext_expl_halflife;
575
576         save_last_pos = ConsoleObject->last_pos;        //don't let move code change this
577         object_move_all();
578         ConsoleObject->last_pos = save_last_pos;
579
580         if (ext_expl_playing) {
581
582                 external_explosion.lifeleft -= FrameTime;
583                 do_explosion_sequence(&external_explosion);
584
585                 if (external_explosion.lifeleft < ext_expl_halflife)
586                         mine_destroyed = 1;
587
588                 if (external_explosion.flags & OF_SHOULD_BE_DEAD)
589                         ext_expl_playing = 0;
590         }
591
592         if (cur_fly_speed != desired_fly_speed) {
593                 fix delta = desired_fly_speed - cur_fly_speed;
594                 fix frame_accel = fixmul(FrameTime,FLY_ACCEL);
595
596                 if (abs(delta) < frame_accel)
597                         cur_fly_speed = desired_fly_speed;
598                 else
599                         if (delta > 0)
600                                 cur_fly_speed += frame_accel;
601                         else
602                                 cur_fly_speed -= frame_accel;
603         }
604
605         //do big explosions
606         if (!outside_mine) {
607
608                 if (Endlevel_sequence==EL_OUTSIDE) {
609                         vms_vector tvec;
610
611                         vm_vec_sub(&tvec,&ConsoleObject->pos,&mine_side_exit_point);
612
613                         if (vm_vec_dot(&tvec,&mine_exit_orient.fvec) > 0) {
614                                 object *tobj;
615
616                                 outside_mine = 1;
617
618                                 tobj = object_create_explosion(exit_segnum,&mine_side_exit_point,i2f(50),VCLIP_BIG_PLAYER_EXPLOSION);
619
620                                 if (tobj) {
621                                         external_explosion = *tobj;
622
623                                         tobj->flags |= OF_SHOULD_BE_DEAD;
624
625                                         flash_scale = 0;        //kill lights in mine
626
627                                         ext_expl_halflife = tobj->lifeleft;
628
629                                         ext_expl_playing = 1;
630                                 }
631         
632                                 digi_link_sound_to_pos( SOUND_BIG_ENDLEVEL_EXPLOSION, exit_segnum, 0, &mine_side_exit_point, 0, i2f(3)/4 );
633                         }
634                 }
635
636                 //do explosions chasing player
637                 if ((explosion_wait1-=FrameTime) < 0) {
638                         vms_vector tpnt;
639                         int segnum;
640                         object *expl;
641                         static int sound_count;
642
643                         vm_vec_scale_add(&tpnt,&ConsoleObject->pos,&ConsoleObject->orient.fvec,-ConsoleObject->size*5);
644                         vm_vec_scale_add2(&tpnt,&ConsoleObject->orient.rvec,(d_rand()-RAND_MAX/2)*15);
645                         vm_vec_scale_add2(&tpnt,&ConsoleObject->orient.uvec,(d_rand()-RAND_MAX/2)*15);
646
647                         segnum = find_point_seg(&tpnt,ConsoleObject->segnum);
648
649                         if (segnum != -1) {
650                                 expl = object_create_explosion(segnum,&tpnt,i2f(20),VCLIP_BIG_PLAYER_EXPLOSION);
651                                 if (d_rand()<10000 || ++sound_count==7) {               //pseudo-random
652                                         digi_link_sound_to_pos( SOUND_TUNNEL_EXPLOSION, segnum, 0, &tpnt, 0, F1_0 );
653                                         sound_count=0;
654                                 }
655                         }
656
657                         explosion_wait1 = 0x2000 + d_rand()/4;
658
659                 }
660         }
661
662         //do little explosions on walls
663         if (Endlevel_sequence >= EL_FLYTHROUGH && Endlevel_sequence < EL_OUTSIDE)
664                 if ((explosion_wait2-=FrameTime) < 0) {
665                         vms_vector tpnt;
666                         fvi_query fq;
667                         fvi_info hit_data;
668
669                         //create little explosion on wall
670
671                         vm_vec_copy_scale(&tpnt,&ConsoleObject->orient.rvec,(d_rand()-RAND_MAX/2)*100);
672                         vm_vec_scale_add2(&tpnt,&ConsoleObject->orient.uvec,(d_rand()-RAND_MAX/2)*100);
673                         vm_vec_add2(&tpnt,&ConsoleObject->pos);
674
675                         if (Endlevel_sequence == EL_FLYTHROUGH)
676                                 vm_vec_scale_add2(&tpnt,&ConsoleObject->orient.fvec,d_rand()*200);
677                         else
678                                 vm_vec_scale_add2(&tpnt,&ConsoleObject->orient.fvec,d_rand()*60);
679
680                         //find hit point on wall
681
682                         fq.p0 = &ConsoleObject->pos;
683                         fq.p1 = &tpnt;
684                         fq.startseg = ConsoleObject->segnum;
685                         fq.rad = 0;
686                         fq.thisobjnum = 0;
687                         fq.ignore_obj_list = NULL;
688                         fq.flags = 0;
689
690                         find_vector_intersection(&fq,&hit_data);
691
692                         if (hit_data.hit_type==HIT_WALL && hit_data.hit_seg!=-1)
693                                 object_create_explosion(hit_data.hit_seg,&hit_data.hit_pnt,i2f(3)+d_rand()*6,VCLIP_SMALL_EXPLOSION);
694
695                         explosion_wait2 = (0xa00 + d_rand()/8)/2;
696                 }
697
698         switch (Endlevel_sequence) {
699
700                 case EL_OFF: return;
701
702                 case EL_FLYTHROUGH: {
703
704                         do_endlevel_flythrough(0);
705
706                         if (ConsoleObject->segnum == transition_segnum) {
707
708                                 #ifndef SHAREWARE
709                                         start_endlevel_movie();
710                                         stop_endlevel_sequence();
711                                 #else
712
713                                 int objnum;
714
715                                 //songs_play_song( SONG_ENDLEVEL, 0 );
716
717                                 Endlevel_sequence = EL_LOOKBACK;
718
719                                 objnum = obj_create(OBJ_CAMERA, 0, 
720                                         ConsoleObject->segnum,&ConsoleObject->pos,&ConsoleObject->orient,0,
721                                         CT_NONE,MT_NONE,RT_NONE);
722
723                                 if (objnum == -1) {                             //can't get object, so abort
724                                         mprintf((1, "Can't get object for endlevel sequence.  Aborting endlevel sequence.\n"));
725                                         stop_endlevel_sequence();
726                                         return;
727                                 }
728
729                                 Viewer = endlevel_camera = &Objects[objnum];
730
731                                 select_cockpit(CM_LETTERBOX);
732
733                                 fly_objects[1] = fly_objects[0];
734                                 fly_objects[1].obj = endlevel_camera;
735                                 fly_objects[1].speed = (5*cur_fly_speed)/4;
736                                 fly_objects[1].offset_frac = 0x4000;
737
738                                 vm_vec_scale_add2(&endlevel_camera->pos,&endlevel_camera->orient.fvec,i2f(7));
739
740                                 timer=0x20000;
741
742                                 #endif
743                         }
744
745                         break;
746                 }
747
748
749 #ifdef SHAREWARE
750                 case EL_LOOKBACK: {
751
752                         do_endlevel_flythrough(0);
753                         do_endlevel_flythrough(1);
754
755                         if (timer>0) {
756
757                                 timer -= FrameTime;
758
759                                 if (timer < 0)          //reduce speed
760                                         fly_objects[1].speed = fly_objects[0].speed;
761                         }
762
763                         if (endlevel_camera->segnum == exit_segnum) {
764                                 vms_angvec cam_angles,exit_seg_angles;
765
766                                 Endlevel_sequence = EL_OUTSIDE;
767
768                                 timer = i2f(2);
769
770                                 vm_vec_negate(&endlevel_camera->orient.fvec);
771                                 vm_vec_negate(&endlevel_camera->orient.rvec);
772
773                                 vm_extract_angles_matrix(&cam_angles,&endlevel_camera->orient);
774                                 vm_extract_angles_matrix(&exit_seg_angles,&mine_exit_orient);
775                                 bank_rate = (-exit_seg_angles.b - cam_angles.b)/2;
776
777                                 ConsoleObject->control_type = endlevel_camera->control_type = CT_NONE;
778
779 #ifdef SLEW_ON
780  slew_obj = endlevel_camera;
781 #endif
782                         }
783                                 
784                         break;
785                 }
786
787                 case EL_OUTSIDE: {
788                         #ifndef SLEW_ON
789                         vms_angvec cam_angles;
790                         #endif
791
792                         vm_vec_scale_add2(&ConsoleObject->pos,&ConsoleObject->orient.fvec,fixmul(FrameTime,cur_fly_speed));
793 #ifndef SLEW_ON
794                         vm_vec_scale_add2(&endlevel_camera->pos,&endlevel_camera->orient.fvec,fixmul(FrameTime,-2*cur_fly_speed));
795                         vm_vec_scale_add2(&endlevel_camera->pos,&endlevel_camera->orient.uvec,fixmul(FrameTime,-cur_fly_speed/10));
796
797                         vm_extract_angles_matrix(&cam_angles,&endlevel_camera->orient);
798                         cam_angles.b += fixmul(bank_rate,FrameTime);
799                         vm_angles_2_matrix(&endlevel_camera->orient,&cam_angles);
800 #endif
801
802                         timer -= FrameTime;
803
804                         if (timer < 0) {
805
806                                 Endlevel_sequence = EL_STOPPED;
807
808                                 vm_extract_angles_matrix(&player_angles,&ConsoleObject->orient);
809
810                                 timer = i2f(3);
811
812                         }
813
814                         break;
815                 }
816
817                 case EL_STOPPED: {
818
819                         get_angs_to_object(&player_dest_angles,&station_pos,&ConsoleObject->pos);
820                         chase_angles(&player_angles,&player_dest_angles);
821                         vm_angles_2_matrix(&ConsoleObject->orient,&player_angles);
822
823                         vm_vec_scale_add2(&ConsoleObject->pos,&ConsoleObject->orient.fvec,fixmul(FrameTime,cur_fly_speed));
824
825                         timer -= FrameTime;
826
827                         if (timer < 0) {
828
829                                 #ifdef SLEW_ON
830                                 slew_obj = endlevel_camera;
831                                 _do_slew_movement(endlevel_camera,1,1);
832                                 timer += FrameTime;             //make time stop
833                                 break;
834                                 #else
835
836                                 #ifdef SHORT_SEQUENCE
837
838                                 stop_endlevel_sequence();
839
840                                 #else
841                                 Endlevel_sequence = EL_PANNING;
842
843                                 vm_extract_angles_matrix(&camera_cur_angles,&endlevel_camera->orient);
844
845
846                                 timer = i2f(3);
847
848                                 if (Game_mode & GM_MULTI) { // try to skip part of the seq if multiplayer
849                                         stop_endlevel_sequence();
850                                         return;
851                                 }
852
853                                 //mprintf((0,"Switching to pan...\n"));
854                                 #endif          //SHORT_SEQUENCE
855                                 #endif          //SLEW_ON
856
857                         }
858                         break;
859                 }
860
861                 #ifndef SHORT_SEQUENCE
862                 case EL_PANNING: {
863                         #ifndef SLEW_ON
864                         int mask;
865                         #endif
866
867                         get_angs_to_object(&player_dest_angles,&station_pos,&ConsoleObject->pos);
868                         chase_angles(&player_angles,&player_dest_angles);
869                         vm_angles_2_matrix(&ConsoleObject->orient,&player_angles);
870                         vm_vec_scale_add2(&ConsoleObject->pos,&ConsoleObject->orient.fvec,fixmul(FrameTime,cur_fly_speed));
871
872                         #ifdef SLEW_ON
873                         _do_slew_movement(endlevel_camera,1,1);
874                         #else
875
876                         get_angs_to_object(&camera_desired_angles,&ConsoleObject->pos,&endlevel_camera->pos);
877                         mask = chase_angles(&camera_cur_angles,&camera_desired_angles);
878                         vm_angles_2_matrix(&endlevel_camera->orient,&camera_cur_angles);
879
880                         if ((mask&5) == 5) {
881
882                                 vms_vector tvec;
883
884                                 Endlevel_sequence = EL_CHASING;
885
886                                 vm_vec_normalized_dir_quick(&tvec,&station_pos,&ConsoleObject->pos);
887                                 vm_vector_2_matrix(&ConsoleObject->orient,&tvec,&surface_orient.uvec,NULL);
888
889                                 desired_fly_speed *= 2;
890
891                                 //mprintf((0,"Switching to chase...\n"));
892
893                         }
894                         #endif
895
896                         break;
897                 }
898
899                 case EL_CHASING: {
900                         fix d,speed_scale;
901
902                         #ifdef SLEW_ON
903                         _do_slew_movement(endlevel_camera,1,1);
904                         #endif
905
906                         get_angs_to_object(&camera_desired_angles,&ConsoleObject->pos,&endlevel_camera->pos);
907                         chase_angles(&camera_cur_angles,&camera_desired_angles);
908
909                         #ifndef SLEW_ON
910                         vm_angles_2_matrix(&endlevel_camera->orient,&camera_cur_angles);
911                         #endif
912
913                         d = vm_vec_dist_quick(&ConsoleObject->pos,&endlevel_camera->pos);
914
915                         speed_scale = fixdiv(d,i2f(0x20));
916                         if (d<f1_0) d=f1_0;
917
918                         get_angs_to_object(&player_dest_angles,&station_pos,&ConsoleObject->pos);
919                         chase_angles(&player_angles,&player_dest_angles);
920                         vm_angles_2_matrix(&ConsoleObject->orient,&player_angles);
921
922                         vm_vec_scale_add2(&ConsoleObject->pos,&ConsoleObject->orient.fvec,fixmul(FrameTime,cur_fly_speed));
923                         #ifndef SLEW_ON
924                         vm_vec_scale_add2(&endlevel_camera->pos,&endlevel_camera->orient.fvec,fixmul(FrameTime,fixmul(speed_scale,cur_fly_speed)));
925
926                         if (vm_vec_dist(&ConsoleObject->pos,&station_pos) < i2f(10))
927                                 stop_endlevel_sequence();
928                         #endif
929
930                         break;
931
932                 }
933                 #endif          //ifdef SHORT_SEQUENCE
934 #endif
935
936         }
937 }
938
939
940 #define MIN_D 0x100
941
942 //find which side to fly out of
943 find_exit_side(object *obj)
944 {
945         int i;
946         vms_vector prefvec,segcenter,sidevec;
947         fix best_val=-f2_0;
948         int best_side;
949         segment *pseg = &Segments[obj->segnum];
950
951         //find exit side
952
953         vm_vec_normalized_dir_quick(&prefvec,&obj->pos,&obj->last_pos);
954
955         compute_segment_center(&segcenter,pseg);
956
957         best_side=-1;
958         for (i=MAX_SIDES_PER_SEGMENT;--i >= 0;) {
959                 fix d;
960
961                 if (pseg->children[i]!=-1) {
962
963                         compute_center_point_on_side(&sidevec,pseg,i);
964                         vm_vec_normalized_dir_quick(&sidevec,&sidevec,&segcenter);
965                         d = vm_vec_dotprod(&sidevec,&prefvec);
966
967                         if (labs(d) < MIN_D) d=0;
968
969                         if (d > best_val) {best_val=d; best_side=i;}
970
971                 }
972         }
973
974         Assert(best_side!=-1);
975
976         return best_side;
977 }
978
979 extern fix Render_zoom;                                                 //the player's zoom factor
980
981 extern vms_vector Viewer_eye;   //valid during render
982
983 draw_exit_model()
984 {
985         vms_vector model_pos;
986         int f=15,u=0;   //21;
987
988         vm_vec_scale_add(&model_pos,&mine_exit_point,&mine_exit_orient.fvec,i2f(f));
989         vm_vec_scale_add2(&model_pos,&mine_exit_orient.uvec,i2f(u));
990
991         draw_polygon_model(&model_pos,&mine_exit_orient,NULL,(mine_destroyed)?destroyed_exit_modelnum:exit_modelnum,0,f1_0,NULL,NULL);
992
993 }
994
995 int exit_point_bmx,exit_point_bmy;
996
997 fix satellite_size = i2f(400);
998
999 #define SATELLITE_DIST          i2f(1024)
1000 #define SATELLITE_WIDTH         satellite_size
1001 #define SATELLITE_HEIGHT        ((satellite_size*9)/4)          //((satellite_size*5)/2)
1002
1003 render_external_scene(fix eye_offset)
1004 {
1005
1006         Viewer_eye = Viewer->pos;
1007
1008         if (eye_offset)
1009                 vm_vec_scale_add2(&Viewer_eye,&Viewer->orient.rvec,eye_offset);
1010
1011         g3_set_view_matrix(&Viewer->pos,&Viewer->orient,Render_zoom);
1012
1013         //g3_draw_horizon(BM_XRGB(0,0,0),BM_XRGB(16,16,16));            //,-1);
1014         gr_clear_canvas(BM_XRGB(0,0,0));
1015
1016         g3_start_instance_matrix(&vmd_zero_vector,&surface_orient);
1017         draw_stars();
1018         g3_done_instance();
1019
1020         {       //draw satellite
1021
1022                 vms_vector delta;
1023                 g3s_point p,top_pnt;
1024
1025                 g3_rotate_point(&p,&satellite_pos);
1026                 g3_rotate_delta_vec(&delta,&satellite_upvec);
1027
1028                 g3_add_delta_vec(&top_pnt,&p,&delta);
1029
1030                 if (! (p.p3_codes & CC_BEHIND)) {
1031                         int save_im = Interpolation_method;
1032                         //p.p3_flags &= ~PF_PROJECTED;
1033                         //g3_project_point(&p);
1034                         if (! (p.p3_flags & PF_OVERFLOW)) {
1035                                 Interpolation_method = 0;
1036                                 //gr_bitmapm(f2i(p.p3_sx)-32,f2i(p.p3_sy)-32,satellite_bitmap);
1037                                 g3_draw_rod_tmap(satellite_bitmap,&p,SATELLITE_WIDTH,&top_pnt,SATELLITE_WIDTH,f1_0);
1038                                 Interpolation_method = save_im;
1039                         }
1040                 }
1041         }
1042
1043         #ifdef STATION_ENABLED
1044         draw_polygon_model(&station_pos,&vmd_identity_matrix,NULL,station_modelnum,0,f1_0,NULL,NULL);
1045         #endif
1046
1047         render_terrain(&mine_ground_exit_point,exit_point_bmx,exit_point_bmy);
1048
1049         draw_exit_model();
1050         if (ext_expl_playing)
1051                 draw_fireball(&external_explosion);
1052
1053         Lighting_on=0;
1054         render_object(ConsoleObject);
1055         Lighting_on=1;
1056 }
1057
1058 #define MAX_STARS 500
1059
1060 vms_vector stars[MAX_STARS];
1061
1062 generate_starfield()
1063 {
1064         int i;
1065
1066         for (i=0;i<MAX_STARS;i++) {
1067
1068                 stars[i].x = (d_rand() - RAND_MAX/2) << 14;
1069                 stars[i].z = (d_rand() - RAND_MAX/2) << 14;
1070                 stars[i].y = (d_rand()/2) << 14;
1071
1072         }
1073 }
1074
1075 draw_stars()
1076 {
1077         int i;
1078         int intensity=31;
1079         g3s_point p;
1080
1081         for (i=0;i<MAX_STARS;i++) {
1082
1083                 if ((i&63) == 0) {
1084                         gr_setcolor(BM_XRGB(intensity,intensity,intensity));
1085                         intensity-=3;
1086                 }                       
1087
1088                 //g3_rotate_point(&p,&stars[i]);
1089                 g3_rotate_delta_vec(&p.p3_vec,&stars[i]);
1090                 g3_code_point(&p);
1091
1092                 if (p.p3_codes == 0) {
1093
1094                         p.p3_flags &= ~PF_PROJECTED;
1095
1096                         g3_project_point(&p);
1097
1098                         gr_pixel(f2i(p.p3_sx),f2i(p.p3_sy));
1099                 }
1100         }
1101
1102 //@@    {
1103 //@@            vms_vector delta;
1104 //@@            g3s_point top_pnt;
1105 //@@
1106 //@@            g3_rotate_point(&p,&satellite_pos);
1107 //@@            g3_rotate_delta_vec(&delta,&satellite_upvec);
1108 //@@
1109 //@@            g3_add_delta_vec(&top_pnt,&p,&delta);
1110 //@@
1111 //@@            if (! (p.p3_codes & CC_BEHIND)) {
1112 //@@                    int save_im = Interpolation_method;
1113 //@@                    Interpolation_method = 0;
1114 //@@                    //p.p3_flags &= ~PF_PROJECTED;
1115 //@@                    g3_project_point(&p);
1116 //@@                    if (! (p.p3_flags & PF_OVERFLOW))
1117 //@@                            //gr_bitmapm(f2i(p.p3_sx)-32,f2i(p.p3_sy)-32,satellite_bitmap);
1118 //@@                            g3_draw_rod_tmap(satellite_bitmap,&p,SATELLITE_WIDTH,&top_pnt,SATELLITE_WIDTH,f1_0);
1119 //@@                    Interpolation_method = save_im;
1120 //@@            }
1121 //@@    }
1122
1123 }
1124
1125 endlevel_render_mine(fix eye_offset)
1126 {
1127         int start_seg_num;
1128
1129         Viewer_eye = Viewer->pos;
1130
1131         if (Viewer->type == OBJ_PLAYER )
1132                 vm_vec_scale_add2(&Viewer_eye,&Viewer->orient.fvec,(Viewer->size*3)/4);
1133
1134         if (eye_offset)
1135                 vm_vec_scale_add2(&Viewer_eye,&Viewer->orient.rvec,eye_offset);
1136
1137         #ifdef EDITOR
1138         if (Function_mode==FMODE_EDITOR)
1139                 Viewer_eye = Viewer->pos;
1140         #endif
1141
1142         if (Endlevel_sequence >= EL_OUTSIDE) {
1143
1144                 start_seg_num = exit_segnum;
1145         }
1146         else {
1147                 start_seg_num = find_point_seg(&Viewer_eye,Viewer->segnum);
1148
1149                 if (start_seg_num==-1)
1150                         start_seg_num = Viewer->segnum;
1151         }
1152
1153         if (Endlevel_sequence == EL_LOOKBACK) {
1154                 vms_matrix headm,viewm;
1155                 vms_angvec angles = {0,0,0x7fff};
1156
1157                 vm_angles_2_matrix(&headm,&angles);
1158                 vm_matrix_x_matrix(&viewm,&Viewer->orient,&headm);
1159                 g3_set_view_matrix(&Viewer_eye,&viewm,Render_zoom);
1160         }
1161         else
1162                 g3_set_view_matrix(&Viewer_eye,&Viewer->orient,Render_zoom);
1163
1164         render_mine(start_seg_num,eye_offset, 0);
1165 }
1166
1167 void render_endlevel_frame(fix eye_offset)
1168 {
1169
1170         g3_start_frame();
1171
1172         if (Endlevel_sequence < EL_OUTSIDE)
1173                 endlevel_render_mine(eye_offset);
1174         #ifdef SHAREWARE
1175         else
1176                 render_external_scene(eye_offset);
1177         #endif
1178
1179         g3_end_frame();
1180
1181 }
1182
1183
1184 ///////////////////////// copy of flythrough code for endlevel
1185
1186
1187 #define MAX_FLY_OBJECTS 2
1188
1189 flythrough_data fly_objects[MAX_FLY_OBJECTS];
1190
1191 flythrough_data *flydata;
1192
1193 int matt_find_connect_side(int seg0,int seg1);
1194
1195 void compute_segment_center(vms_vector *vp,segment *sp);
1196
1197 fixang delta_ang(fixang a,fixang b);
1198 fixang interp_angle(fixang dest,fixang src,fixang step);
1199
1200 #define DEFAULT_SPEED i2f(16)
1201
1202 #define MIN_D 0x100
1203
1204 //if speed is zero, use default speed
1205 start_endlevel_flythrough(int n,object *obj,fix speed)
1206 {
1207         flydata = &fly_objects[n];
1208
1209         flydata->obj = obj;
1210
1211         flydata->first_time = 1;
1212
1213         flydata->speed = speed?speed:DEFAULT_SPEED;
1214
1215         flydata->offset_frac = 0;
1216 }
1217
1218 static vms_angvec *angvec_add2_scale(vms_angvec *dest,vms_vector *src,fix s)
1219 {
1220         dest->p += fixmul(src->x,s);
1221         dest->b  += fixmul(src->z,s);
1222         dest->h  += fixmul(src->y,s);
1223
1224         return dest;
1225 }
1226
1227 #define MAX_ANGSTEP     0x4000          //max turn per second
1228
1229 #define MAX_SLIDE_PER_SEGMENT 0x10000
1230
1231 do_endlevel_flythrough(int n)
1232 {
1233         object *obj;
1234         segment *pseg;
1235         int old_player_seg;
1236
1237         flydata = &fly_objects[n];
1238         obj = flydata->obj;
1239         
1240         old_player_seg = obj->segnum;
1241
1242         //move the player for this frame
1243
1244         if (!flydata->first_time) {
1245
1246                 vm_vec_scale_add2(&obj->pos,&flydata->step,FrameTime);
1247                 angvec_add2_scale(&flydata->angles,&flydata->angstep,FrameTime);
1248
1249                 vm_angles_2_matrix(&obj->orient,&flydata->angles);
1250         }
1251
1252         //check new player seg
1253
1254         update_object_seg(obj);
1255         pseg = &Segments[obj->segnum];
1256
1257         if (flydata->first_time || obj->segnum != old_player_seg) {             //moved into new seg
1258                 vms_vector curcenter,nextcenter;
1259                 fix step_size,seg_time;
1260                 short entry_side,exit_side;     //what sides we entry and leave through
1261                 vms_vector dest_point;          //where we are heading (center of exit_side)
1262                 vms_angvec dest_angles;         //where we want to be pointing
1263                 vms_matrix dest_orient;
1264                 int up_side;
1265
1266                 //find new exit side
1267
1268                 if (!flydata->first_time) {
1269
1270                         entry_side = matt_find_connect_side(obj->segnum,old_player_seg);
1271                         exit_side = Side_opposite[entry_side];
1272                 }
1273
1274                 if (flydata->first_time || entry_side==-1 || pseg->children[exit_side]==-1)
1275                         exit_side = find_exit_side(obj);
1276
1277                 {                                                                               //find closest side to align to
1278                         fix d,largest_d=-f1_0;
1279                         int i;
1280
1281                         for (i=0;i<6;i++) {
1282                                 #ifdef COMPACT_SEGS
1283                                 vms_vector v1;
1284                                 get_side_normal(pseg, i, 0, &v1 );
1285                                 d = vm_vec_dot(&v1,&flydata->obj->orient.uvec);
1286                                 #else
1287                                 d = vm_vec_dot(&pseg->sides[i].normals[0],&flydata->obj->orient.uvec);
1288                                 #endif
1289                                 if (d > largest_d) {largest_d = d; up_side=i;}
1290                         }
1291
1292                 }
1293
1294                 //update target point & angles
1295
1296                 compute_center_point_on_side(&dest_point,pseg,exit_side);
1297
1298                 //update target point and movement points
1299
1300                 //offset object sideways
1301                 if (flydata->offset_frac) {
1302                         int s0=-1,s1,i;
1303                         vms_vector s0p,s1p;
1304                         fix dist;
1305
1306                         for (i=0;i<6;i++)
1307                                 if (i!=entry_side && i!=exit_side && i!=up_side && i!=Side_opposite[up_side])
1308                                         if (s0==-1)
1309                                                 s0 = i;
1310                                         else
1311                                                 s1 = i;
1312
1313                         compute_center_point_on_side(&s0p,pseg,s0);
1314                         compute_center_point_on_side(&s1p,pseg,s1);
1315                         dist = fixmul(vm_vec_dist(&s0p,&s1p),flydata->offset_frac);
1316
1317                         if (dist-flydata->offset_dist > MAX_SLIDE_PER_SEGMENT)
1318                                 dist = flydata->offset_dist + MAX_SLIDE_PER_SEGMENT;
1319
1320                         flydata->offset_dist = dist;
1321
1322                         vm_vec_scale_add2(&dest_point,&obj->orient.rvec,dist);
1323
1324                 }
1325
1326                 vm_vec_sub(&flydata->step,&dest_point,&obj->pos);
1327                 step_size = vm_vec_normalize_quick(&flydata->step);
1328                 vm_vec_scale(&flydata->step,flydata->speed);
1329
1330                 compute_segment_center(&curcenter,pseg);
1331                 compute_segment_center(&nextcenter,&Segments[pseg->children[exit_side]]);
1332                 vm_vec_sub(&flydata->headvec,&nextcenter,&curcenter);
1333
1334                 #ifdef COMPACT_SEGS     
1335                 {
1336                         vms_vector _v1;
1337                         get_side_normal(pseg, up_side, 0, &_v1 );
1338                         vm_vector_2_matrix(&dest_orient,&flydata->headvec,&_v1,NULL);
1339                 }
1340                 #else
1341                 vm_vector_2_matrix(&dest_orient,&flydata->headvec,&pseg->sides[up_side].normals[0],NULL);
1342                 #endif
1343                 vm_extract_angles_matrix(&dest_angles,&dest_orient);
1344
1345                 if (flydata->first_time)
1346                         vm_extract_angles_matrix(&flydata->angles,&obj->orient);
1347
1348                 seg_time = fixdiv(step_size,flydata->speed);    //how long through seg
1349
1350                 if (seg_time) {
1351                         flydata->angstep.x = max(-MAX_ANGSTEP,min(MAX_ANGSTEP,fixdiv(delta_ang(flydata->angles.p,dest_angles.p),seg_time)));
1352                         flydata->angstep.z = max(-MAX_ANGSTEP,min(MAX_ANGSTEP,fixdiv(delta_ang(flydata->angles.b,dest_angles.b),seg_time)));
1353                         flydata->angstep.y = max(-MAX_ANGSTEP,min(MAX_ANGSTEP,fixdiv(delta_ang(flydata->angles.h,dest_angles.h),seg_time)));
1354
1355                 }
1356                 else {
1357                         flydata->angles = dest_angles;
1358                         flydata->angstep.x = flydata->angstep.y = flydata->angstep.z = 0;
1359                 }
1360         }
1361
1362         flydata->first_time=0;
1363 }
1364
1365 #define JOY_NULL 15
1366 #define ROT_SPEED 8             //rate of rotation while key held down
1367 #define VEL_SPEED (15)  //rate of acceleration while key held down
1368
1369 extern short old_joy_x,old_joy_y;       //position last time around
1370
1371 #include "key.h"
1372 #include "joy.h"
1373
1374 #ifdef SLEW_ON          //this is a special routine for slewing around external scene
1375 int _do_slew_movement(object *obj, int check_keys, int check_joy )
1376 {
1377         int moved = 0;
1378         vms_vector svel, movement;                              //scaled velocity (per this frame)
1379         vms_matrix rotmat,new_pm;
1380         int joy_x,joy_y,btns;
1381         int joyx_moved,joyy_moved;
1382         vms_angvec rotang;
1383
1384         if (keyd_pressed[KEY_PAD5])
1385                 vm_vec_zero(&obj->phys_info.velocity);
1386
1387         if (check_keys) {
1388                 obj->phys_info.velocity.x += VEL_SPEED * (key_down_time(KEY_PAD9) - key_down_time(KEY_PAD7));
1389                 obj->phys_info.velocity.y += VEL_SPEED * (key_down_time(KEY_PADMINUS) - key_down_time(KEY_PADPLUS));
1390                 obj->phys_info.velocity.z += VEL_SPEED * (key_down_time(KEY_PAD8) - key_down_time(KEY_PAD2));
1391
1392                 rotang.pitch =  (key_down_time(KEY_LBRACKET) - key_down_time(KEY_RBRACKET))/ROT_SPEED;
1393                 rotang.bank  = (key_down_time(KEY_PAD1) - key_down_time(KEY_PAD3))/ROT_SPEED;
1394                 rotang.head  = (key_down_time(KEY_PAD6) - key_down_time(KEY_PAD4))/ROT_SPEED;
1395         }
1396         else
1397                 rotang.pitch = rotang.bank  = rotang.head  = 0;
1398
1399         //check for joystick movement
1400
1401         if (check_joy && joy_present)   {
1402                 joy_get_pos(&joy_x,&joy_y);
1403                 btns=joy_get_btns();
1404         
1405                 joyx_moved = (abs(joy_x - old_joy_x)>JOY_NULL);
1406                 joyy_moved = (abs(joy_y - old_joy_y)>JOY_NULL);
1407         
1408                 if (abs(joy_x) < JOY_NULL) joy_x = 0;
1409                 if (abs(joy_y) < JOY_NULL) joy_y = 0;
1410         
1411                 if (btns)
1412                         if (!rotang.pitch) rotang.pitch = fixmul(-joy_y * 512,FrameTime); else;
1413                 else
1414                         if (joyy_moved) obj->phys_info.velocity.z = -joy_y * 8192;
1415         
1416                 if (!rotang.head) rotang.head = fixmul(joy_x * 512,FrameTime);
1417         
1418                 if (joyx_moved) old_joy_x = joy_x;
1419                 if (joyy_moved) old_joy_y = joy_y;
1420         }
1421
1422         moved = rotang.pitch | rotang.bank | rotang.head;
1423
1424         vm_angles_2_matrix(&rotmat,&rotang);
1425         vm_matrix_x_matrix(&new_pm,&obj->orient,&rotmat);
1426         obj->orient = new_pm;
1427         vm_transpose_matrix(&new_pm);           //make those columns rows
1428
1429         moved |= obj->phys_info.velocity.x | obj->phys_info.velocity.y | obj->phys_info.velocity.z;
1430
1431         svel = obj->phys_info.velocity;
1432         vm_vec_scale(&svel,FrameTime);          //movement in this frame
1433         vm_vec_rotate(&movement,&svel,&new_pm);
1434
1435         vm_vec_add2(&obj->pos,&movement);
1436
1437         moved |= (movement.x || movement.y || movement.z);
1438
1439         return moved;
1440 }
1441 #endif
1442
1443 #define LINE_LEN        80
1444 #define NUM_VARS        8
1445
1446 #define STATION_DIST    i2f(1024)
1447
1448 int convert_ext( char *dest, char *ext )
1449 {
1450         char *t;
1451
1452         t = strchr(dest,'.');
1453
1454         if (t && (t-dest <= 8)) {
1455                 t[1] = ext[0];                  
1456                 t[2] = ext[1];                  
1457                 t[3] = ext[2];  
1458                 return 1;
1459         }
1460         else
1461                 return 0;
1462 }
1463
1464 //called for each level to load & setup the exit sequence
1465 load_endlevel_data(int level_num)
1466 {
1467         char filename[13];
1468         char line[LINE_LEN],*p;
1469         CFILE *ifile;
1470         int var,segnum,sidenum;
1471         int exit_side, i;
1472         int have_binary = 0;
1473
1474         endlevel_data_loaded = 0;               //not loaded yet
1475
1476 try_again:
1477         ;
1478
1479         if (level_num<0)                //secret level
1480                 strcpy(filename,Secret_level_names[-level_num-1]);
1481         else                                    //normal level
1482                 strcpy(filename,Level_names[level_num-1]);
1483
1484         if (!convert_ext(filename,"END"))
1485                 Error("Error converting filename <%s> for endlevel data\n",filename);
1486
1487         ifile = cfopen(filename,"rb");
1488
1489         if (!ifile) {
1490
1491                 convert_ext(filename,"TXB");
1492
1493                 ifile = cfopen(filename,"rb");
1494
1495                 if (!ifile)
1496                         if (level_num==1) {
1497                                 Error("Cannot load file text of binary version of <%s>",filename);
1498                         }
1499                         else {
1500                                 level_num = 1;
1501                                 goto try_again;
1502                         }
1503
1504                 have_binary = 1;
1505         }
1506
1507         //ok...this parser is pretty simple.  It ignores comments, but
1508         //everything else must be in the right place
1509
1510         var = 0;
1511
1512         while (cfgets(line,LINE_LEN,ifile)) {
1513
1514                 if (have_binary) {
1515                         for (i = 0; i < strlen(line) - 1; i++) {
1516                                 encode_rotate_left(&(line[i]));
1517                                 line[i] = line[i] ^ BITMAP_TBL_XOR;
1518                                 encode_rotate_left(&(line[i]));
1519                         }
1520                         p = line;
1521                 }
1522
1523                 if ((p=strchr(line,';'))!=NULL)
1524                         *p = 0;         //cut off comment
1525
1526                 for (p=line+strlen(line)-1;p>line && isspace(*p);*p--=0);
1527                 for (p=line;isspace(*p);p++);
1528
1529                 if (!*p)                //empty line
1530                         continue;
1531
1532                 switch (var) {
1533
1534                         case 0: {                                               //ground terrain
1535                                 int iff_error, i;
1536                                 ubyte pal[768];
1537
1538                                 if (terrain_bm_instance.bm_data)
1539                                         d_free(terrain_bm_instance.bm_data);
1540
1541                                 Assert(terrain_bm_instance.bm_data == NULL);
1542                                 
1543                                 iff_error = iff_read_bitmap(p,&terrain_bm_instance,BM_LINEAR,pal);
1544                                 if (iff_error != IFF_NO_ERROR) {
1545                                         mprintf((1, "File %s - IFF error: %s",p,iff_errormsg(iff_error)));
1546                                         Error("File %s - IFF error: %s",p,iff_errormsg(iff_error));
1547                                 }
1548
1549                                 terrain_bitmap = &terrain_bm_instance;
1550
1551                                 gr_remap_bitmap_good( terrain_bitmap, pal, iff_transparent_color, -1);
1552                                 
1553                                 break;
1554                         }
1555
1556                         case 1:                                                 //height map
1557
1558                                 load_terrain(p);
1559                                 break;
1560
1561
1562                         case 2:
1563
1564                                 sscanf(p,"%d,%d",&exit_point_bmx,&exit_point_bmy);
1565                                 break;
1566
1567                         case 3:                                                 //exit heading
1568
1569                                 exit_angles.h = i2f(atoi(p))/360;
1570                                 break;
1571
1572                         case 4: {                                               //planet bitmap
1573                                 int iff_error;
1574                                 ubyte pal[768];
1575
1576                                 if (satellite_bm_instance.bm_data)
1577                                         d_free(satellite_bm_instance.bm_data);
1578
1579                                 iff_error = iff_read_bitmap(p,&satellite_bm_instance,BM_LINEAR,pal);
1580                                 if (iff_error != IFF_NO_ERROR) {
1581                                         mprintf((1, "File %s - IFF error: %s",p,iff_errormsg(iff_error)));
1582                                         Error("File %s - IFF error: %s",p,iff_errormsg(iff_error));
1583                                 }
1584
1585                                 satellite_bitmap = &satellite_bm_instance;
1586                                 gr_remap_bitmap_good( satellite_bitmap, pal, iff_transparent_color, -1);
1587
1588                                 break;
1589                         }
1590
1591                         case 5:                                                 //earth pos
1592                         case 7: {                                               //station pos
1593                                 vms_matrix tm;
1594                                 vms_angvec ta;
1595                                 int pitch,head;
1596
1597                                 sscanf(p,"%d,%d",&head,&pitch);
1598
1599                                 ta.h = i2f(head)/360;
1600                                 ta.p = -i2f(pitch)/360;
1601                                 ta.b = 0;
1602
1603                                 vm_angles_2_matrix(&tm,&ta);
1604
1605                                 if (var==5)
1606                                         satellite_pos = tm.fvec;
1607                                         //vm_vec_copy_scale(&satellite_pos,&tm.fvec,SATELLITE_DIST);
1608                                 else
1609                                         station_pos = tm.fvec;
1610
1611                                 break;
1612                         }
1613
1614                         case 6:                                         //planet size
1615                                 satellite_size = i2f(atoi(p));
1616                                 break;
1617                 }
1618
1619                 var++;
1620
1621         }
1622
1623         Assert(var == NUM_VARS);
1624
1625
1626         // OK, now the data is loaded.  Initialize everything
1627
1628         //find the exit sequence by searching all segments for a side with
1629         //children == -2
1630
1631         for (segnum=0,exit_segnum=-1;exit_segnum==-1 && segnum<=Highest_segment_index;segnum++)
1632                 for (sidenum=0;sidenum<6;sidenum++)
1633                         if (Segments[segnum].children[sidenum] == -2) {
1634                                 exit_segnum = segnum;
1635                                 exit_side = sidenum;
1636                                 break;
1637                         }
1638
1639         Assert(exit_segnum!=-1);
1640
1641         compute_segment_center(&mine_exit_point,&Segments[exit_segnum]);
1642         extract_orient_from_segment(&mine_exit_orient,&Segments[exit_segnum]);
1643         compute_center_point_on_side(&mine_side_exit_point,&Segments[exit_segnum],exit_side);
1644
1645         vm_vec_scale_add(&mine_ground_exit_point,&mine_exit_point,&mine_exit_orient.uvec,-i2f(20));
1646
1647         //compute orientation of surface
1648         {
1649                 vms_vector tv;
1650                 vms_matrix exit_orient,tm;
1651
1652                 vm_angles_2_matrix(&exit_orient,&exit_angles);
1653                 vm_transpose_matrix(&exit_orient);
1654                 vm_matrix_x_matrix(&surface_orient,&mine_exit_orient,&exit_orient);
1655
1656                 vm_copy_transpose_matrix(&tm,&surface_orient);
1657                 vm_vec_rotate(&tv,&station_pos,&tm);
1658                 vm_vec_scale_add(&station_pos,&mine_exit_point,&tv,STATION_DIST);
1659
1660 vm_vec_rotate(&tv,&satellite_pos,&tm);
1661 vm_vec_scale_add(&satellite_pos,&mine_exit_point,&tv,SATELLITE_DIST);
1662
1663 vm_vector_2_matrix(&tm,&tv,&surface_orient.uvec,NULL);
1664 vm_vec_copy_scale(&satellite_upvec,&tm.uvec,SATELLITE_HEIGHT);
1665
1666
1667         }
1668
1669         cfclose(ifile);
1670
1671         endlevel_data_loaded = 1;
1672
1673 }
1674
1675 #endif
1676