move bitmap replacement functions to piggy.c
[btb/d2x.git] / main / gameseq.c
1 /* $Id: gameseq.c,v 1.23 2003-03-22 03:14:30 btb Exp $ */
2 /*
3 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
4 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
5 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
6 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
7 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
8 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
9 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
10 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
11 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
12 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
13 */
14
15 #ifdef HAVE_CONFIG_H
16 #include <conf.h>
17 #endif
18
19 #ifdef RCS
20 char gameseq_rcsid[] = "$Id: gameseq.c,v 1.23 2003-03-22 03:14:30 btb Exp $";
21 #endif
22
23 #ifdef WINDOWS
24 #include "desw.h"
25 #endif
26
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <time.h>
33
34 #ifdef OGL
35 #include "ogl_init.h"
36 #endif
37
38 #include "pa_enabl.h"                   //$$POLY_ACC
39 #include "inferno.h"
40 #include "game.h"
41 #include "player.h"
42 #include "key.h"
43 #include "object.h"
44 #include "physics.h"
45 #include "error.h"
46 #include "joy.h"
47 #include "mono.h"
48 #include "iff.h"
49 #include "pcx.h"
50 #include "timer.h"
51 #include "render.h"
52 #include "laser.h"
53 #include "screens.h"
54 #include "textures.h"
55 #include "slew.h"
56 #include "gauges.h"
57 #include "texmap.h"
58 #include "3d.h"
59 #include "effects.h"
60 #include "menu.h"
61 #include "gameseg.h"
62 #include "wall.h"
63 #include "ai.h"
64 #include "fuelcen.h"
65 #include "switch.h"
66 #include "digi.h"
67 #include "gamesave.h"
68 #include "scores.h"
69 #include "ibitblt.h"
70 #include "u_mem.h"
71 #include "palette.h"
72 #include "morph.h"
73 #include "lighting.h"
74 #include "newdemo.h"
75 #include "titles.h"
76 #include "collide.h"
77 #include "weapon.h"
78 #include "sounds.h"
79 #include "args.h"
80 #include "gameseq.h"
81 #include "gamefont.h"
82 #include "newmenu.h"
83 #include "endlevel.h"
84 #ifdef NETWORK
85 #include "network.h"
86 #endif
87 #include "playsave.h"
88 #include "ctype.h"
89 #include "multi.h"
90 #include "fireball.h"
91 #include "kconfig.h"
92 #include "config.h"
93 #include "robot.h"
94 #include "automap.h"
95 #include "cntrlcen.h"
96 #include "powerup.h"
97 #include "modem.h"
98 #include "text.h"
99 #include "cfile.h"
100 #include "piggy.h"
101 #include "texmerge.h"
102 #include "paging.h"
103 #include "mission.h"
104 #include "state.h"
105 #include "songs.h"
106 #ifdef NETWORK
107 #include "netmisc.h"
108 #endif
109 #include "gamepal.h"
110 #include "movie.h"
111 #include "controls.h"
112 #include "credits.h"
113 #include "gamemine.h"
114
115 #if defined(POLY_ACC)
116 #include "poly_acc.h"
117 #endif
118 #if defined (TACTILE)
119  #include "tactile.h"
120 #endif
121
122 #ifdef EDITOR
123 #include "editor/editor.h"
124 #endif
125
126 #include "makesig.h"
127 #include "strutil.h"
128 #include "rle.h"
129
130 void StartNewLevelSecret(int level_num, int page_in_textures);
131 void InitPlayerPosition(int random_flag);
132 void load_stars();
133 void returning_to_level_message(void);
134 void advancing_to_level_message(void);
135 void DoEndGame(void);
136 void AdvanceLevel(int secret_flag);
137 void filter_objects_from_level();
138
139 // From allender -- you'll find these defines in state.c and cntrlcen.c
140 // since I couldn't think of a good place to put them and i wanted to
141 // fix this stuff fast!  Sorry about that...
142
143 #ifndef MACINTOSH
144 #define SECRETB_FILENAME        "secret.sgb"
145 #define SECRETC_FILENAME        "secret.sgc"
146 #else
147 #define SECRETB_FILENAME        ":Players:secret.sgb"
148 #define SECRETC_FILENAME        ":Players:secret.sgc"
149 #endif
150
151 //Current_level_num starts at 1 for the first level
152 //-1,-2,-3 are secret levels
153 //0 means not a real level loaded
154 int     Current_level_num=0,Next_level_num;
155 char    Current_level_name[LEVEL_NAME_LEN];
156
157 #if !defined(SHAREWARE) && !defined(D2_OEM)
158 int Last_level,Last_secret_level;
159 #endif
160
161 // Global variables describing the player
162 int                             N_players=1;                                            // Number of players ( >1 means a net game, eh?)
163 int                             Player_num=0;                                           // The player number who is on the console.
164 player                  Players[MAX_PLAYERS+4];                   // Misc player info
165 obj_position    Player_init[MAX_PLAYERS];
166
167 // Global variables telling what sort of game we have
168 int MaxNumNetPlayers = -1;
169 int NumNetPlayerPositions = -1;
170
171 extern fix ThisLevelTime;
172
173 // Extern from game.c to fix a bug in the cockpit!
174
175 extern int last_drawn_cockpit[2];
176 extern int Last_level_path_created;
177
178 //      HUD_clear_messages external, declared in gauges.h
179 #ifndef _GAUGES_H
180 extern void HUD_clear_messages(); // From hud.c
181 #endif
182
183 //      Extra prototypes declared for the sake of LINT
184 void init_player_stats_new_ship(void);
185 void copy_defaults_to_robot_all(void);
186
187 int     Do_appearance_effect=0;
188
189 extern int Rear_view;
190
191 int     First_secret_visit = 1;
192
193 extern int descent_critical_error;
194
195 extern int Last_msg_ycrd;
196
197 //--------------------------------------------------------------------
198 void verify_console_object()
199 {
200         Assert( Player_num > -1 );
201         Assert( Players[Player_num].objnum > -1 );
202         ConsoleObject = &Objects[Players[Player_num].objnum];
203         Assert( ConsoleObject->type==OBJ_PLAYER );
204         Assert( ConsoleObject->id==Player_num );
205 }
206
207 int count_number_of_robots() 
208 {
209         int robot_count;
210         int i;
211
212         robot_count = 0;
213         for (i=0;i<=Highest_object_index;i++) {
214                 if (Objects[i].type == OBJ_ROBOT)
215                         robot_count++;
216         }
217
218         return robot_count;
219 }
220
221
222 int count_number_of_hostages() 
223 {
224         int count;
225         int i;
226
227         count = 0;
228         for (i=0;i<=Highest_object_index;i++) {
229                 if (Objects[i].type == OBJ_HOSTAGE)
230                         count++;
231         }
232
233         return count;
234 }
235
236 //added 10/12/95: delete buddy bot if coop game.  Probably doesn't really belong here. -MT
237 void
238 gameseq_init_network_players()
239 {
240         int i,k,j;
241
242         // Initialize network player start locations and object numbers
243
244         ConsoleObject = &Objects[0];
245         k = 0;
246         j = 0;
247         for (i=0;i<=Highest_object_index;i++) {
248
249                 if (( Objects[i].type==OBJ_PLAYER )     || (Objects[i].type == OBJ_GHOST) || (Objects[i].type == OBJ_COOP))
250                 {
251                         if ( (!(Game_mode & GM_MULTI_COOP) && ((Objects[i].type == OBJ_PLAYER)||(Objects[i].type==OBJ_GHOST))) ||
252                    ((Game_mode & GM_MULTI_COOP) && ((j == 0) || ( Objects[i].type==OBJ_COOP ))) )
253                         {
254                                 // -- mprintf((0, "Created Cooperative multiplayer object\n"));
255                                 Objects[i].type=OBJ_PLAYER;
256                                 // -- mprintf((0, "Player init %d is ship %d.\n", k, j));
257                                 Player_init[k].pos = Objects[i].pos;
258                                 Player_init[k].orient = Objects[i].orient;
259                                 Player_init[k].segnum = Objects[i].segnum;
260                                 Players[k].objnum = i;
261                                 Objects[i].id = k;
262                                 k++;
263                         }
264                         else
265                                 obj_delete(i);
266                         j++;
267                 }
268
269                 if ((Objects[i].type==OBJ_ROBOT) && (Robot_info[Objects[i].id].companion) && (Game_mode & GM_MULTI))
270                         obj_delete(i);          //kill the buddy in netgames
271
272         }
273         NumNetPlayerPositions = k;
274
275 #ifndef NDEBUG
276         if ( ((Game_mode & GM_MULTI_COOP) && (NumNetPlayerPositions != 4)) ||
277                   (!(Game_mode & GM_MULTI_COOP) && (NumNetPlayerPositions != 8)) )
278         {
279                 mprintf((1, "--NOT ENOUGH MULTIPLAYER POSITIONS IN THIS MINE!--\n"));
280                 //Int3(); // Not enough positions!!
281         }
282 #endif
283 #if defined (D2_OEM)
284
285         if ((Game_mode & GM_MULTI) && Current_mission_num == Builtin_mission_num && Current_level_num==8)
286          {
287           for (i=0;i<N_players;i++)
288                  if (Players[i].connected && !(NetPlayers.players[i].version_minor & 0xF0))
289                         {
290                nm_messagebox ("Warning!",1,TXT_OK,"This special version of Descent II\nwill disconnect after this level.\nPlease purchase the full version\nto experience all the levels!");    
291                          return;
292                         }
293          }
294 #endif
295 }
296
297 void gameseq_remove_unused_players()
298 {
299         int i;
300
301         // 'Remove' the unused players
302
303 #ifdef NETWORK
304         if (Game_mode & GM_MULTI)
305         {
306                 for (i=0; i < NumNetPlayerPositions; i++)
307                 {
308                         if ((!Players[i].connected) || (i >= N_players))
309                         {
310                                 #ifndef NDEBUG
311 //                              mprintf((0, "Ghosting player ship %d.\n", i+1));
312                                 #endif
313                                 multi_make_player_ghost(i);
314                         }
315                 }
316         }
317         else
318 #endif
319         {               // Note link to above if!!!
320                 #ifndef NDEBUG
321                 // -- mprintf((0, "Removing player objects numbered %d-%d.\n", 1, NumNetPlayerPositions));
322                 #endif
323                 for (i=1; i < NumNetPlayerPositions; i++)
324                 {
325                         obj_delete(Players[i].objnum);
326                 }
327         }
328 }
329
330 fix StartingShields=INITIAL_SHIELDS;
331
332 // Setup player for new game
333 void init_player_stats_game()
334 {
335         Players[Player_num].score = 0;
336         Players[Player_num].last_score = 0;
337         Players[Player_num].lives = INITIAL_LIVES;
338         Players[Player_num].level = 1;
339
340         Players[Player_num].time_level = 0;
341         Players[Player_num].time_total = 0;
342         Players[Player_num].hours_level = 0;
343         Players[Player_num].hours_total = 0;
344
345         Players[Player_num].energy = INITIAL_ENERGY;
346         Players[Player_num].shields = StartingShields;
347         Players[Player_num].killer_objnum = -1;
348
349         Players[Player_num].net_killed_total = 0;
350         Players[Player_num].net_kills_total = 0;
351
352         Players[Player_num].num_kills_level = 0;
353         Players[Player_num].num_kills_total = 0;
354         Players[Player_num].num_robots_level = 0;
355         Players[Player_num].num_robots_total = 0;
356         Players[Player_num].KillGoalCount = 0;
357         
358         Players[Player_num].hostages_rescued_total = 0;
359         Players[Player_num].hostages_level = 0;
360         Players[Player_num].hostages_total = 0;
361
362         Players[Player_num].laser_level = 0;
363         Players[Player_num].flags = 0;
364
365         init_player_stats_new_ship();
366
367         First_secret_visit = 1;
368 }
369
370 void init_ammo_and_energy(void)
371 {
372         if (Players[Player_num].energy < INITIAL_ENERGY)
373                 Players[Player_num].energy = INITIAL_ENERGY;
374         if (Players[Player_num].shields < StartingShields)
375                 Players[Player_num].shields = StartingShields;
376
377 //      for (i=0; i<MAX_PRIMARY_WEAPONS; i++)
378 //              if (Players[Player_num].primary_ammo[i] < Default_primary_ammo_level[i])
379 //                      Players[Player_num].primary_ammo[i] = Default_primary_ammo_level[i];
380
381 //      for (i=0; i<MAX_SECONDARY_WEAPONS; i++)
382 //              if (Players[Player_num].secondary_ammo[i] < Default_secondary_ammo_level[i])
383 //                      Players[Player_num].secondary_ammo[i] = Default_secondary_ammo_level[i];
384         if (Players[Player_num].secondary_ammo[0] < 2 + NDL - Difficulty_level)
385                 Players[Player_num].secondary_ammo[0] = 2 + NDL - Difficulty_level;
386 }
387
388 extern  ubyte   Last_afterburner_state;
389
390 // Setup player for new level (After completion of previous level)
391 void init_player_stats_level(int secret_flag)
392 {
393         // int  i;
394
395         Players[Player_num].last_score = Players[Player_num].score;
396
397         Players[Player_num].level = Current_level_num;
398
399 #ifdef NETWORK
400         if (!Network_rejoined) {
401 #endif
402                 Players[Player_num].time_level = 0;
403                 Players[Player_num].hours_level = 0;
404 #ifdef NETWORK
405         }
406 #endif
407
408         Players[Player_num].killer_objnum = -1;
409
410         Players[Player_num].num_kills_level = 0;
411         Players[Player_num].num_robots_level = count_number_of_robots();
412         Players[Player_num].num_robots_total += Players[Player_num].num_robots_level;
413
414         Players[Player_num].hostages_level = count_number_of_hostages();
415         Players[Player_num].hostages_total += Players[Player_num].hostages_level;
416         Players[Player_num].hostages_on_board = 0;
417
418         if (!secret_flag) {
419                 init_ammo_and_energy();
420
421                 Players[Player_num].flags &= (~KEY_BLUE);
422                 Players[Player_num].flags &= (~KEY_RED);
423                 Players[Player_num].flags &= (~KEY_GOLD);
424
425                 Players[Player_num].flags &=   ~(PLAYER_FLAGS_INVULNERABLE |
426                                                                                                         PLAYER_FLAGS_CLOAKED |
427                                                                                                         PLAYER_FLAGS_MAP_ALL);
428
429                 Players[Player_num].cloak_time = 0;
430                 Players[Player_num].invulnerable_time = 0;
431
432                 if ((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP))
433                         Players[Player_num].flags |= (KEY_BLUE | KEY_RED | KEY_GOLD);
434         }
435
436         Player_is_dead = 0; // Added by RH
437         Players[Player_num].homing_object_dist = -F1_0; // Added by RH
438
439         Last_laser_fired_time = Next_laser_fire_time = GameTime; // added by RH, solved demo playback bug
440
441         Controls.afterburner_state = 0;
442         Last_afterburner_state = 0;
443
444         digi_kill_sound_linked_to_object(Players[Player_num].objnum);
445
446         init_gauges();
447
448    #ifdef TACTILE
449                 if (TactileStick)
450                   tactile_set_button_jolt();
451         #endif
452
453         Missile_viewer = NULL;
454 }
455
456 extern  void init_ai_for_ship(void);
457
458 // Setup player for a brand-new ship
459 void init_player_stats_new_ship()
460 {
461         int     i;
462
463         if (Newdemo_state == ND_STATE_RECORDING) {
464                 newdemo_record_laser_level(Players[Player_num].laser_level, 0);
465                 newdemo_record_player_weapon(0, 0);
466                 newdemo_record_player_weapon(1, 0);
467         }
468
469         Players[Player_num].energy = INITIAL_ENERGY;
470         Players[Player_num].shields = StartingShields;
471         Players[Player_num].laser_level = 0;
472         Players[Player_num].killer_objnum = -1;
473         Players[Player_num].hostages_on_board = 0;
474
475         Afterburner_charge = 0;
476
477         for (i=0; i<MAX_PRIMARY_WEAPONS; i++) {
478                 Players[Player_num].primary_ammo[i] = 0;
479                 Primary_last_was_super[i] = 0;
480         }
481
482         for (i=1; i<MAX_SECONDARY_WEAPONS; i++) {
483                 Players[Player_num].secondary_ammo[i] = 0;
484                 Secondary_last_was_super[i] = 0;
485         }
486         Players[Player_num].secondary_ammo[0] = 2 + NDL - Difficulty_level;
487
488         Players[Player_num].primary_weapon_flags = HAS_LASER_FLAG;
489         Players[Player_num].secondary_weapon_flags = HAS_CONCUSSION_FLAG;
490
491         Primary_weapon = 0;
492         Secondary_weapon = 0;
493
494         Players[Player_num].flags &= ~( PLAYER_FLAGS_QUAD_LASERS | 
495                                                                                                 PLAYER_FLAGS_AFTERBURNER | 
496                                                                                                 PLAYER_FLAGS_CLOAKED | 
497                                                                                                 PLAYER_FLAGS_INVULNERABLE | 
498                                                                                                 PLAYER_FLAGS_MAP_ALL |
499                                                                                                 PLAYER_FLAGS_CONVERTER |
500                                                                                                 PLAYER_FLAGS_AMMO_RACK |
501                                                                                                 PLAYER_FLAGS_HEADLIGHT |
502                                                                                                 PLAYER_FLAGS_HEADLIGHT_ON |
503                                                                                                 PLAYER_FLAGS_FLAG);
504
505         Players[Player_num].cloak_time = 0;
506         Players[Player_num].invulnerable_time = 0;
507
508         Player_is_dead = 0;             //player no longer dead
509
510         Players[Player_num].homing_object_dist = -F1_0; // Added by RH
511
512         Controls.afterburner_state = 0;
513         Last_afterburner_state = 0;
514
515         digi_kill_sound_linked_to_object(Players[Player_num].objnum);
516
517         Missile_viewer=NULL;            ///reset missile camera if out there
518
519    #ifdef TACTILE
520                 if (TactileStick)
521                  {
522                   tactile_set_button_jolt();
523                  }
524         #endif
525
526
527         init_ai_for_ship();
528 }
529
530 #ifdef NETWORK
531 void reset_network_objects()
532 {
533         memset(local_to_remote, -1, MAX_OBJECTS*sizeof(short));
534         memset(remote_to_local, -1, MAX_NUM_NET_PLAYERS*MAX_OBJECTS*sizeof(short));
535         memset(object_owner, -1, MAX_OBJECTS);
536 }
537 #endif
538
539 extern void init_stuck_objects(void);
540
541 #ifdef EDITOR
542
543 extern int Slide_segs_computed;
544
545 //reset stuff so game is semi-normal when playing from editor
546 void editor_reset_stuff_on_level()
547 {
548         gameseq_init_network_players();
549         init_player_stats_level(0);
550         Viewer = ConsoleObject;
551         ConsoleObject = Viewer = &Objects[Players[Player_num].objnum];
552         ConsoleObject->id=Player_num;
553         ConsoleObject->control_type = CT_FLYING;
554         ConsoleObject->movement_type = MT_PHYSICS;
555         Game_suspended = 0;
556         verify_console_object();
557         Control_center_destroyed = 0;
558         if (Newdemo_state != ND_STATE_PLAYBACK)
559                 gameseq_remove_unused_players();
560         init_cockpit();
561         init_robots_for_level();
562         init_ai_objects();
563         init_morphs();
564         init_all_matcens();
565         init_player_stats_new_ship();
566         init_controlcen_for_level();
567         automap_clear_visited();
568         init_stuck_objects();
569         init_thief_for_level();
570
571         Slide_segs_computed = 0;
572 }
573 #endif
574
575 //do whatever needs to be done when a player dies in multiplayer
576
577 void DoGameOver()
578 {
579 //      nm_messagebox( TXT_GAME_OVER, 1, TXT_OK, "" );
580
581         if (Current_mission_num == Builtin_mission_num)
582                 scores_maybe_add_player(0);
583
584         Function_mode = FMODE_MENU;
585         Game_mode = GM_GAME_OVER;
586         longjmp( LeaveGame, 0 );                // Exit out of game loop
587
588 }
589
590 extern void do_save_game_menu();
591
592 //update various information about the player
593 void update_player_stats()
594 {
595                 Players[Player_num].time_level += FrameTime;    //the never-ending march of time...
596                 if ( Players[Player_num].time_level > i2f(3600) )       {
597                         Players[Player_num].time_level -= i2f(3600);
598                         Players[Player_num].hours_level++;
599                 }
600
601                 Players[Player_num].time_total += FrameTime;    //the never-ending march of time...
602                 if ( Players[Player_num].time_total > i2f(3600) )       {
603                         Players[Player_num].time_total -= i2f(3600);
604                         Players[Player_num].hours_total++;
605                 }
606 }
607
608 //hack to not start object when loading level
609 extern int Dont_start_sound_objects;
610
611 //go through this level and start any eclip sounds
612 void set_sound_sources()
613 {
614         int segnum,sidenum;
615         segment *seg;
616
617         digi_init_sounds();             //clear old sounds
618
619         Dont_start_sound_objects = 1;
620
621         for (seg=&Segments[0],segnum=0;segnum<=Highest_segment_index;seg++,segnum++)
622                 for (sidenum=0;sidenum<MAX_SIDES_PER_SEGMENT;sidenum++) {
623                         int tm,ec,sn;
624
625                         if (WALL_IS_DOORWAY(seg,sidenum) & WID_RENDER_FLAG)
626                                 if ((((tm=seg->sides[sidenum].tmap_num2) != 0) && ((ec=TmapInfo[tm&0x3fff].eclip_num)!=-1)) || ((ec=TmapInfo[seg->sides[sidenum].tmap_num].eclip_num)!=-1))
627                                         if ((sn=Effects[ec].sound_num)!=-1) {
628                                                 vms_vector pnt;
629                                                 int csegnum = seg->children[sidenum];
630
631                                                 //check for sound on other side of wall.  Don't add on
632                                                 //both walls if sound travels through wall.  If sound
633                                                 //does travel through wall, add sound for lower-numbered
634                                                 //segment.
635
636                                                 if (IS_CHILD(csegnum) && csegnum < segnum) {
637                                                         if (WALL_IS_DOORWAY(seg, sidenum) & (WID_FLY_FLAG+WID_RENDPAST_FLAG)) {
638                                                                 segment *csegp;
639                                                                 int csidenum;
640
641                                                                 csegp = &Segments[seg->children[sidenum]];
642                                                                 csidenum = find_connect_side(seg, csegp);
643
644                                                                 if (csegp->sides[csidenum].tmap_num2 == seg->sides[sidenum].tmap_num2)
645                                                                         continue;               //skip this one
646                                                         }
647                                                 }
648
649                                                 compute_center_point_on_side(&pnt,seg,sidenum);
650                                                 digi_link_sound_to_pos(sn,segnum,sidenum,&pnt,1, F1_0/2);
651                                         }
652                 }
653
654         Dont_start_sound_objects = 0;
655
656 }
657
658
659 //fix flash_dist=i2f(1);
660 fix flash_dist=fl2f(.9);
661
662 //create flash for player appearance
663 void create_player_appearance_effect(object *player_obj)
664 {
665         vms_vector pos;
666         object *effect_obj;
667
668 #ifndef NDEBUG
669         {
670                 int objnum = player_obj-Objects;
671                 if ( (objnum < 0) || (objnum > Highest_object_index) )
672                         Int3(); // See Rob, trying to track down weird network bug
673         }
674 #endif
675
676         if (player_obj == Viewer)
677                 vm_vec_scale_add(&pos, &player_obj->pos, &player_obj->orient.fvec, fixmul(player_obj->size,flash_dist));
678         else
679                 pos = player_obj->pos;
680
681         effect_obj = object_create_explosion(player_obj->segnum, &pos, player_obj->size, VCLIP_PLAYER_APPEARANCE );
682
683         if (effect_obj) {
684                 effect_obj->orient = player_obj->orient;
685
686                 if ( Vclip[VCLIP_PLAYER_APPEARANCE].sound_num > -1 )
687                         digi_link_sound_to_object( Vclip[VCLIP_PLAYER_APPEARANCE].sound_num, effect_obj-Objects, 0, F1_0);
688         }
689 }
690
691 //
692 // New Game sequencing functions
693 //
694
695 //pairs of chars describing ranges
696 char playername_allowed_chars[] = "azAZ09__--";
697
698 int MakeNewPlayerFile(int allow_abort)
699 {
700         int x;
701         char filename[14];
702         newmenu_item m;
703         char text[CALLSIGN_LEN+1]="";
704         FILE *fp;
705
706         strncpy(text, Players[Player_num].callsign,CALLSIGN_LEN);
707
708 try_again:
709         m.type=NM_TYPE_INPUT; m.text_len = 8; m.text = text;
710
711         Newmenu_allowed_chars = playername_allowed_chars;
712         x = newmenu_do( NULL, TXT_ENTER_PILOT_NAME, 1, &m, NULL );
713         Newmenu_allowed_chars = NULL;
714
715         if ( x < 0 ) {
716                 if ( allow_abort ) return 0;
717                 goto try_again;
718         }
719
720         if (text[0]==0) //null string
721                 goto try_again;
722
723         sprintf( filename, "%s.plr", text );
724
725         fp = fopen( filename, "rb" );
726
727 #ifndef MACINTOSH
728         //if the callsign is the name of a tty device, prepend a char
729         if (fp && isatty(fileno(fp))) {
730                 fclose(fp);
731                 sprintf(filename,"$%.7s.plr",text);
732                 fp = fopen(filename,"rb");
733         }
734 #endif
735         
736         if ( fp )       {
737                 nm_messagebox(NULL, 1, TXT_OK, "%s '%s' %s", TXT_PLAYER, text, TXT_ALREADY_EXISTS );
738                 fclose(fp);
739                 goto try_again;
740         }
741
742         if ( !new_player_config() )
743                 goto try_again;                 // They hit Esc during New player config
744
745         strncpy(Players[Player_num].callsign, text, CALLSIGN_LEN);
746
747         write_player_file();
748
749         return 1;
750 }
751
752 #ifdef WINDOWS
753 #undef TXT_SELECT_PILOT
754 #define TXT_SELECT_PILOT "Select pilot\n<Ctrl-D> or Right-click\nto delete"
755 #endif
756
757 //Inputs the player's name, without putting up the background screen
758 int RegisterPlayer()
759 {
760         int i,j;
761         char filename[14];
762         int allow_abort_flag = 1;
763
764         if ( Players[Player_num].callsign[0] == 0 )     {
765                 //---------------------------------------------------------------------
766                 // Set default config options in case there is no config file
767                 // kc_keyboard, kc_joystick, kc_mouse are statically defined.
768                 Config_joystick_sensitivity = 8;
769                 Config_control_type =CONTROL_NONE;
770                 for (i=0; i<CONTROL_MAX_TYPES; i++ )
771                         for (j=0; j<MAX_CONTROLS; j++ )
772                                 kconfig_settings[i][j] = default_kconfig_settings[i][j];
773                 kc_set_controls();
774                 //----------------------------------------------------------------
775
776                 // Read the last player's name from config file, not lastplr.txt
777                 strncpy( Players[Player_num].callsign, config_last_player, CALLSIGN_LEN );
778
779                 if (config_last_player[0]==0)
780                         allow_abort_flag = 0;
781         }
782
783 do_menu_again:
784         ;
785
786 #ifndef MACINTOSH
787         if (!newmenu_get_filename( TXT_SELECT_PILOT, "*.plr", filename, allow_abort_flag ))     {
788                 goto do_menu_again; //return 0;         // They hit Esc in file selector
789         }
790 #else
791         #ifndef APPLE_DEMO
792         if (!newmenu_get_filename( TXT_SELECT_PILOT, ".\\Players\\*.plr", filename, allow_abort_flag )) {
793                 goto do_menu_again;             // They hit Esc in file selector
794         }
795         #else
796         newmenu_get_filename( "Select Pilot", ".\\Players\\*.plr", filename, 0 );               // no abort allowed ever -- and change title of menubox
797         #endif
798 #endif
799
800         if ( filename[0] == '<' )       {
801                 // They selected 'create new pilot'
802                 if (!MakeNewPlayerFile(allow_abort_flag))
803                         //return 0;             // They hit Esc during enter name stage
804                         goto do_menu_again;
805         } else {
806                 strncpy(Players[Player_num].callsign,filename, CALLSIGN_LEN);
807         }
808
809         if (read_player_file() != EZERO)
810                 goto do_menu_again;
811
812         Auto_leveling_on = Default_leveling_on;
813
814         set_display_mode(Default_display_mode);
815
816         WriteConfigFile();              // Update lastplr
817
818         return 1;
819 }
820
821
822 void load_robot_replacements(char *level_name);
823 int read_hamfile();
824 extern int Robot_replacements_loaded;
825
826 //load a level off disk. level numbers start at 1.  Secret levels are -1,-2,-3
827 void LoadLevel(int level_num,int page_in_textures)
828 {
829         char *level_name;
830         player save_player;
831         int load_ret;
832
833         save_player = Players[Player_num];      
834
835         Assert(level_num <= Last_level  && level_num >= Last_secret_level  && level_num != 0);
836
837         if (level_num<0)                //secret level
838                 level_name = Secret_level_names[-level_num-1];
839         else                                    //normal level
840                 level_name = Level_names[level_num-1];
841
842         undo_bm_read_all_d1();
843         d1_pig_loaded = cfexist("descent.pig");
844
845         #ifdef WINDOWS
846                 dd_gr_set_current_canvas(NULL);
847                 dd_gr_clear_canvas(BM_XRGB(0,0,0));
848         #else
849                 gr_set_current_canvas(NULL);
850                 gr_clear_canvas(BM_XRGB(0, 0, 0));              //so palette switching is less obvious
851         #endif
852
853         Last_msg_ycrd = -1;             //so we don't restore backgound under msg
854
855 //      WIN(LoadCursorWin(MOUSE_WAIT_CURSOR));
856 //      WIN(ShowCursorW());
857
858 #if 1 //defined(POLY_ACC) || defined(OGL)
859     gr_palette_load(gr_palette);
860     show_boxed_message(TXT_LOADING);
861 #else
862         show_boxed_message(TXT_LOADING);
863         gr_palette_load(gr_palette);
864 #endif
865
866         load_ret = load_level(level_name);              //actually load the data from disk!
867
868         if (load_ret)
869                 Error("Couldn't load level file <%s>, error = %d",level_name,load_ret);
870
871         Current_level_num=level_num;
872
873 //      load_palette_pig(Current_level_palette);                //load just the pig
874
875         load_palette(Current_level_palette,1,1);                //don't change screen
876
877         load_endlevel_data(level_num);
878
879         if ( page_in_textures )
880                 piggy_load_level_data();
881
882         if (Mission_list[Current_mission_num].descent_version == 1)
883                 load_d1_bitmap_replacements();
884         else
885                 load_bitmap_replacements(level_name);
886
887         if (Robot_replacements_loaded) {
888                 read_hamfile();         //load original data
889                 Robot_replacements_loaded = 0;
890         }
891         load_robot_replacements(level_name);
892
893 #ifdef NETWORK
894         my_segments_checksum = netmisc_calc_checksum(Segments, sizeof(segment)*(Highest_segment_index+1));
895
896         reset_network_objects();
897 #endif
898
899         Players[Player_num] = save_player;
900
901         set_sound_sources();
902
903         songs_play_level_song( Current_level_num );
904
905         clear_boxed_message();          //remove message before new palette loaded
906
907         gr_palette_load(gr_palette);            //actually load the palette
908
909 //      WIN(HideCursorW());
910 }
911
912 //sets up Player_num & ConsoleObject  
913 void InitPlayerObject()
914 {
915         Assert(Player_num>=0 && Player_num<MAX_PLAYERS);
916
917         if (Player_num != 0 )   {
918                 Players[0] = Players[Player_num];
919                 Player_num = 0;
920         }
921
922         Players[Player_num].objnum = 0;
923
924         ConsoleObject = &Objects[Players[Player_num].objnum];
925
926         ConsoleObject->type                             = OBJ_PLAYER;
927         ConsoleObject->id                                       = Player_num;
928         ConsoleObject->control_type     = CT_FLYING;
929         ConsoleObject->movement_type    = MT_PHYSICS;
930 }
931
932 extern void game_disable_cheats();
933 extern void turn_cheats_off();
934 extern void init_seismic_disturbances(void);
935
936 //starts a new game on the given level
937 void StartNewGame(int start_level)
938 {
939         Game_mode = GM_NORMAL;
940         Function_mode = FMODE_GAME;
941         
942         Next_level_num = 0;
943
944         InitPlayerObject();                             //make sure player's object set up
945
946         init_player_stats_game();               //clear all stats
947
948         N_players = 1;
949 #ifdef NETWORK
950         Network_new_game = 0;
951 #endif
952
953         if (start_level < 0)
954                 StartNewLevelSecret(start_level, 0);
955         else
956                 StartNewLevel(start_level, 0);
957
958         Players[Player_num].starting_level = start_level;               // Mark where they started
959
960         game_disable_cheats();
961
962         init_seismic_disturbances();
963 }
964
965 //@@//starts a resumed game loaded from disk
966 //@@void ResumeSavedGame(int start_level)
967 //@@{
968 //@@    Game_mode = GM_NORMAL;
969 //@@    Function_mode = FMODE_GAME;
970 //@@
971 //@@    N_players = 1;
972 //@@    Network_new_game = 0;
973 //@@
974 //@@    InitPlayerObject();                             //make sure player's object set up
975 //@@
976 //@@    StartNewLevel(start_level, 0);
977 //@@
978 //@@    game_disable_cheats();
979 //@@}
980
981 #ifndef _NETWORK_H
982 extern int network_endlevel_poll2( int nitems, newmenu_item * menus, int * key, int citem ); // network.c
983 #endif
984
985 extern int N_secret_levels;
986
987 #define STARS_BACKGROUND ((MenuHires && cfexist("starsb.pcx"))?"starsb.pcx":"stars.pcx")
988
989 //      -----------------------------------------------------------------------------
990 //      Does the bonus scoring.
991 //      Call with dead_flag = 1 if player died, but deserves some portion of bonus (only skill points), anyway.
992 void DoEndLevelScoreGlitz(int network)
993 {
994         int level_points, skill_points, energy_points, shield_points, hostage_points;
995         int     all_hostage_points;
996         int     endgame_points;
997         char    all_hostage_text[64];
998         char    endgame_text[64];
999         #define N_GLITZITEMS 11
1000         char                            m_str[N_GLITZITEMS][30];
1001         newmenu_item    m[N_GLITZITEMS+1];
1002         int                             i,c;
1003         char                            title[128];
1004         int                             is_last_level;
1005         int                             mine_level;
1006
1007         set_screen_mode(SCREEN_MENU);           //go into menu mode
1008
1009    #ifdef TACTILE
1010                 if (TactileStick)
1011                   ClearForces();
1012         #endif
1013
1014         mprintf((0,"DoEndLevelScoreGlitz\n"));
1015
1016         //      Compute level player is on, deal with secret levels (negative numbers)
1017         mine_level = Players[Player_num].level;
1018         if (mine_level < 0)
1019                 mine_level *= -(Last_level/N_secret_levels);
1020
1021         level_points = Players[Player_num].score-Players[Player_num].last_score;
1022
1023         if (!Cheats_enabled) {
1024                 if (Difficulty_level > 1) {
1025                         skill_points = level_points*(Difficulty_level)/4;
1026                         skill_points -= skill_points % 100;
1027                 } else
1028                         skill_points = 0;
1029
1030                 shield_points = f2i(Players[Player_num].shields) * 5 * mine_level;
1031                 energy_points = f2i(Players[Player_num].energy) * 2 * mine_level;
1032                 hostage_points = Players[Player_num].hostages_on_board * 500 * (Difficulty_level+1);
1033
1034                 shield_points -= shield_points % 50;
1035                 energy_points -= energy_points % 50;
1036         } else {
1037                 skill_points = 0;
1038                 shield_points = 0;
1039                 energy_points = 0;
1040                 hostage_points = 0;
1041         }
1042
1043         all_hostage_text[0] = 0;
1044         endgame_text[0] = 0;
1045
1046         if (!Cheats_enabled && (Players[Player_num].hostages_on_board == Players[Player_num].hostages_level)) {
1047                 all_hostage_points = Players[Player_num].hostages_on_board * 1000 * (Difficulty_level+1);
1048                 sprintf(all_hostage_text, "%s%i\n", TXT_FULL_RESCUE_BONUS, all_hostage_points);
1049         } else
1050                 all_hostage_points = 0;
1051
1052         if (!Cheats_enabled && !(Game_mode & GM_MULTI) && (Players[Player_num].lives) && (Current_level_num == Last_level)) {           //player has finished the game!
1053                 endgame_points = Players[Player_num].lives * 10000;
1054                 sprintf(endgame_text, "%s%i\n", TXT_SHIP_BONUS, endgame_points);
1055                 is_last_level=1;
1056         } else
1057                 endgame_points = is_last_level = 0;
1058
1059         mprintf((0,"adding bonus points\n"));
1060         add_bonus_points_to_score(skill_points + energy_points + shield_points + hostage_points + all_hostage_points + endgame_points);
1061
1062         c = 0;
1063         sprintf(m_str[c++], "%s%i", TXT_SHIELD_BONUS, shield_points);           // Return at start to lower menu...
1064         sprintf(m_str[c++], "%s%i", TXT_ENERGY_BONUS, energy_points);
1065         sprintf(m_str[c++], "%s%i", TXT_HOSTAGE_BONUS, hostage_points);
1066         sprintf(m_str[c++], "%s%i", TXT_SKILL_BONUS, skill_points);
1067
1068         sprintf(m_str[c++], "%s", all_hostage_text);
1069         if (!(Game_mode & GM_MULTI) && (Players[Player_num].lives) && (Current_level_num == Last_level))
1070                 sprintf(m_str[c++], "%s", endgame_text);
1071
1072         sprintf(m_str[c++], "%s%i\n", TXT_TOTAL_BONUS, shield_points+energy_points+hostage_points+skill_points+all_hostage_points+endgame_points);
1073         sprintf(m_str[c++], "%s%i", TXT_TOTAL_SCORE, Players[Player_num].score);
1074
1075         #ifdef WINDOWS
1076         sprintf(m_str[c++], "");
1077         sprintf(m_str[c++], "         Done");
1078         #endif
1079
1080         for (i=0; i<c; i++) {
1081                 m[i].type = NM_TYPE_TEXT;
1082                 m[i].text = m_str[i];
1083         }
1084
1085         #ifdef WINDOWS
1086         m[c-1].type = NM_TYPE_MENU;
1087         #endif
1088
1089         // m[c].type = NM_TYPE_MENU;    m[c++].text = "Ok";
1090
1091         if (Current_level_num < 0)
1092                 sprintf(title,"%s%s %d %s\n %s %s",is_last_level?"\n\n\n":"\n",TXT_SECRET_LEVEL, -Current_level_num, TXT_COMPLETE, Current_level_name, TXT_DESTROYED);
1093         else
1094                 sprintf(title,"%s%s %d %s\n%s %s",is_last_level?"\n\n\n":"\n",TXT_LEVEL, Current_level_num, TXT_COMPLETE, Current_level_name, TXT_DESTROYED);
1095
1096         Assert(c <= N_GLITZITEMS);
1097
1098         gr_palette_fade_out(gr_palette, 32, 0);
1099
1100         mprintf((0,"doing menu\n"));
1101
1102    PA_DFX (pa_alpha_always());
1103
1104 #ifdef NETWORK
1105         if ( network && (Game_mode & GM_NETWORK) )
1106                 newmenu_do2(NULL, title, c, m, (void (*))network_endlevel_poll2, 0, STARS_BACKGROUND);
1107         else
1108 #endif
1109                 // NOTE LINK TO ABOVE!!!
1110                 newmenu_do2(NULL, title, c, m, NULL, 0, STARS_BACKGROUND);
1111
1112         mprintf((0,"done DoEndLevelScoreGlitz\n"));
1113 }
1114
1115 //give the player the opportunity to save his game
1116 void DoEndlevelMenu()
1117 {
1118 //No between level saves......!!!       state_save_all(1);
1119 }
1120
1121 //      -----------------------------------------------------------------------------------------------------
1122 //called when the player is starting a level (new game or new ship)
1123 void StartSecretLevel()
1124 {
1125         Assert(!Player_is_dead);
1126
1127         InitPlayerPosition(0);
1128
1129         verify_console_object();
1130
1131         ConsoleObject->control_type     = CT_FLYING;
1132         ConsoleObject->movement_type    = MT_PHYSICS;
1133
1134         // -- WHY? -- disable_matcens();
1135         clear_transient_objects(0);             //0 means leave proximity bombs
1136
1137         // create_player_appearance_effect(ConsoleObject);
1138         Do_appearance_effect = 1;
1139
1140         ai_reset_all_paths();
1141         // -- NO? -- reset_time();
1142
1143         reset_rear_view();
1144         Auto_fire_fusion_cannon_time = 0;
1145         Fusion_charge = 0;
1146
1147         Robot_firing_enabled = 1;
1148 }
1149
1150 extern void set_pos_from_return_segment(void);
1151
1152 //      Returns true if secret level has been destroyed.
1153 int p_secret_level_destroyed(void)
1154 {
1155         if (First_secret_visit) {
1156                 return 0;               //      Never been there, can't have been destroyed.
1157         } else {
1158                 FILE    *fp;
1159                 if ((fp = fopen(SECRETC_FILENAME, "rb")) != NULL) {
1160                         fclose(fp);
1161                         return 0;
1162                 } else {
1163                         return 1;
1164                 }
1165         }
1166 }
1167
1168 //      -----------------------------------------------------------------------------------------------------
1169 void do_secret_message(char *msg)
1170 {
1171         int     old_fmode;
1172
1173         load_stars();
1174
1175 #if defined(POLY_ACC)
1176         pa_save_clut();
1177         pa_update_clut(gr_palette, 0, 256, 0);
1178 #endif
1179
1180         old_fmode = Function_mode;
1181         Function_mode = FMODE_MENU;
1182         nm_messagebox(NULL, 1, TXT_OK, msg);
1183         Function_mode = old_fmode;
1184
1185 #if defined(POLY_ACC)
1186         pa_restore_clut();
1187 #endif
1188         
1189         WIN(DEFINE_SCREEN(NULL));
1190 }
1191
1192 //      -----------------------------------------------------------------------------------------------------
1193 // called when the player is starting a new level for normal game mode and restore state
1194 //      Need to deal with whether this is the first time coming to this level or not.  If not the
1195 //      first time, instead of initializing various things, need to do a game restore for all the
1196 //      robots, powerups, walls, doors, etc.
1197 void StartNewLevelSecret(int level_num, int page_in_textures)
1198 {
1199         newmenu_item    m[1];
1200         //int i;
1201
1202         ThisLevelTime=0;
1203          
1204         m[0].type = NM_TYPE_TEXT;
1205         m[0].text = " ";
1206
1207         last_drawn_cockpit[0] = -1;
1208         last_drawn_cockpit[1] = -1;
1209
1210         if (Newdemo_state == ND_STATE_PAUSED)
1211                 Newdemo_state = ND_STATE_RECORDING;
1212
1213         if (Newdemo_state == ND_STATE_RECORDING) {
1214                 newdemo_set_new_level(level_num);
1215                 newdemo_record_start_frame(FrameCount, FrameTime );
1216         } else if (Newdemo_state != ND_STATE_PLAYBACK) {
1217
1218                 gr_palette_fade_out(gr_palette, 32, 0);
1219
1220                 set_screen_mode(SCREEN_MENU);           //go into menu mode
1221
1222                 if (First_secret_visit) {
1223                         do_secret_message(TXT_SECRET_EXIT);
1224                 } else {
1225                         FILE    *fp;
1226                         if ((fp = fopen(SECRETC_FILENAME, "rb")) != NULL) {
1227                                 fclose(fp);
1228                                 do_secret_message(TXT_SECRET_EXIT);
1229                         } else {
1230                                 char    text_str[128];
1231
1232                                 sprintf(text_str, "Secret level already destroyed.\nAdvancing to level %i.", Current_level_num+1);
1233                                 do_secret_message(text_str);
1234                         }
1235                 }
1236         }
1237
1238         LoadLevel(level_num,page_in_textures);
1239
1240         Assert(Current_level_num == level_num); //make sure level set right
1241
1242         Assert(Function_mode == FMODE_GAME);
1243
1244         gameseq_init_network_players(); // Initialize the Players array for 
1245                                                                                           // this level
1246
1247         HUD_clear_messages();
1248
1249         automap_clear_visited();
1250
1251         // --   init_player_stats_level();
1252
1253         Viewer = &Objects[Players[Player_num].objnum];
1254
1255         gameseq_remove_unused_players();
1256
1257         Game_suspended = 0;
1258
1259         Control_center_destroyed = 0;
1260
1261         init_cockpit();
1262         reset_palette_add();
1263
1264         if (First_secret_visit || (Newdemo_state == ND_STATE_PLAYBACK)) {
1265                 init_robots_for_level();
1266                 init_ai_objects();
1267                 init_smega_detonates();
1268                 init_morphs();
1269                 init_all_matcens();
1270                 reset_special_effects();
1271                 StartSecretLevel();
1272         } else {
1273                 FILE    *fp;
1274                 if ((fp = fopen(SECRETC_FILENAME, "rb")) != NULL) {
1275                         int     pw_save, sw_save;
1276
1277                         fclose(fp);
1278
1279                         pw_save = Primary_weapon;
1280                         sw_save = Secondary_weapon;
1281                         state_restore_all(1, 1, SECRETC_FILENAME);
1282                         Primary_weapon = pw_save;
1283                         Secondary_weapon = sw_save;
1284                         reset_special_effects();
1285                         StartSecretLevel();
1286                         // -- No: This is only for returning to base level: set_pos_from_return_segment();
1287                 } else {
1288                         char    text_str[128];
1289
1290                         sprintf(text_str, "Secret level already destroyed.\nAdvancing to level %i.", Current_level_num+1);
1291                         do_secret_message(text_str);
1292                         return;
1293
1294                         // -- //        If file doesn't exist, it's because reactor was destroyed.
1295                         // -- mprintf((0, "secret.sgc doesn't exist.  Advancing to next level.\n"));
1296                         // -- // -- StartNewLevel(Secret_level_table[-Current_level_num-1]+1, 0);
1297                         // -- StartNewLevel(Secret_level_table[-Current_level_num-1]+1, 0);
1298                         // -- return;
1299                 }
1300         }
1301
1302         if (First_secret_visit) {
1303                 copy_defaults_to_robot_all();
1304         }
1305
1306         turn_cheats_off();
1307
1308         init_controlcen_for_level();
1309
1310         //      Say player can use FLASH cheat to mark path to exit.
1311         Last_level_path_created = -1;
1312
1313         First_secret_visit = 0;
1314 }
1315
1316 int     Entered_from_level;
1317
1318 // ---------------------------------------------------------------------------------------------------------------
1319 //      Called from switch.c when player is on a secret level and hits exit to return to base level.
1320 void ExitSecretLevel(void)
1321 {
1322         FILE    *fp;
1323
1324         if (Newdemo_state == ND_STATE_PLAYBACK)
1325                 return;
1326
1327         if (!Control_center_destroyed) {
1328                 state_save_all(0, 2, SECRETC_FILENAME);
1329         }
1330
1331         if ((fp = fopen(SECRETB_FILENAME, "rb")) != NULL) {
1332                 int     pw_save, sw_save;
1333
1334                 returning_to_level_message();
1335                 fclose(fp);
1336                 pw_save = Primary_weapon;
1337                 sw_save = Secondary_weapon;
1338                 state_restore_all(1, 1, SECRETB_FILENAME);
1339                 Primary_weapon = pw_save;
1340                 Secondary_weapon = sw_save;
1341         } else {
1342                 // File doesn't exist, so can't return to base level.  Advance to next one.
1343                 if (Entered_from_level == Last_level)
1344                         DoEndGame();
1345                 else {
1346                         advancing_to_level_message();
1347                         StartNewLevel(Entered_from_level+1, 0);
1348                 }
1349         }
1350 }
1351
1352 // ---------------------------------------------------------------------------------------------------------------
1353 //      Set invulnerable_time and cloak_time in player struct to preserve amount of time left to
1354 //      be invulnerable or cloaked.
1355 void do_cloak_invul_secret_stuff(fix old_gametime)
1356 {
1357         if (Players[Player_num].flags & PLAYER_FLAGS_INVULNERABLE) {
1358                 fix     time_used;
1359
1360                 time_used = old_gametime - Players[Player_num].invulnerable_time;
1361                 Players[Player_num].invulnerable_time = GameTime - time_used;
1362         }
1363
1364         if (Players[Player_num].flags & PLAYER_FLAGS_CLOAKED) {
1365                 fix     time_used;
1366
1367                 time_used = old_gametime - Players[Player_num].cloak_time;
1368                 Players[Player_num].cloak_time = GameTime - time_used;
1369         }
1370 }
1371
1372 // ---------------------------------------------------------------------------------------------------------------
1373 //      Called from switch.c when player passes through secret exit.  That means he was on a non-secret level and he
1374 //      is passing to the secret level.
1375 //      Do a savegame.
1376 void EnterSecretLevel(void)
1377 {
1378         fix     old_gametime;
1379         int     i;
1380
1381         Assert(! (Game_mode & GM_MULTI) );
1382
1383         Entered_from_level = Current_level_num;
1384
1385         if (Control_center_destroyed)
1386                 DoEndLevelScoreGlitz(0);
1387
1388         if (Newdemo_state != ND_STATE_PLAYBACK)
1389                 state_save_all(0, 1, NULL);     //      Not between levels (ie, save all), IS a secret level, NO filename override
1390
1391         //      Find secret level number to go to, stuff in Next_level_num.
1392         for (i=0; i<-Last_secret_level; i++)
1393                 if (Secret_level_table[i]==Current_level_num) {
1394                         Next_level_num = -(i+1);
1395                         break;
1396                 } else if (Secret_level_table[i] > Current_level_num) { //      Allows multiple exits in same group.
1397                         Next_level_num = -i;
1398                         break;
1399                 }
1400
1401         if (! (i<-Last_secret_level))           //didn't find level, so must be last
1402                 Next_level_num = Last_secret_level;
1403
1404         old_gametime = GameTime;
1405
1406         StartNewLevelSecret(Next_level_num, 1);
1407         
1408         // do_cloak_invul_stuff();
1409 }
1410
1411 //called when the player has finished a level
1412 void PlayerFinishedLevel(int secret_flag)
1413 {
1414         Assert(!secret_flag);
1415
1416         //credit the player for hostages
1417         Players[Player_num].hostages_rescued_total += Players[Player_num].hostages_on_board;
1418
1419         if (Game_mode & GM_NETWORK)
1420                 Players[Player_num].connected = 2; // Finished but did not die
1421
1422         last_drawn_cockpit[0] = -1;
1423         last_drawn_cockpit[1] = -1;
1424
1425         AdvanceLevel(secret_flag);                              //now go on to the next one (if one)
1426 }
1427
1428 #if defined(D2_OEM) || defined(COMPILATION)
1429 #define MOVIE_REQUIRED 0
1430 #else
1431 #define MOVIE_REQUIRED 1
1432 #endif
1433
1434 #ifdef D2_OEM
1435 #define ENDMOVIE "endo"
1436 #else
1437 #define ENDMOVIE "end"
1438 #endif
1439
1440 void show_order_form();
1441 extern void com_hangup(void);
1442
1443 //called when the player has finished the last level
1444 void DoEndGame(void)
1445 {
1446         mprintf((0,"DoEndGame\n"));
1447
1448         Function_mode = FMODE_MENU;
1449         if ((Newdemo_state == ND_STATE_RECORDING) || (Newdemo_state == ND_STATE_PAUSED))
1450                 newdemo_stop_recording();
1451
1452         set_screen_mode( SCREEN_MENU );
1453
1454         WINDOS(
1455                 dd_gr_set_current_canvas(NULL),
1456                 gr_set_current_canvas(NULL)
1457         );
1458
1459         key_flush();
1460
1461         if (Current_mission_num == Builtin_mission_num && !(Game_mode & GM_MULTI)) { //only built-in mission, & not multi
1462 #ifndef SHAREWARE
1463                 int played=MOVIE_NOT_PLAYED;    //default is not played
1464 #endif
1465
1466                 init_subtitles(ENDMOVIE ".tex");        //ingore errors
1467                 played = PlayMovie(ENDMOVIE,MOVIE_REQUIRED);
1468                 close_subtitles();
1469                 if (!played) {
1470                         if (cfexist("end2oem.txb") || cfexist("end2oem.tex")) { // #ifdef D2_OEM
1471                                 songs_play_song( SONG_TITLE, 0 );
1472                                 do_briefing_screens("end2oem.tex",1);
1473                         } else {
1474                                 songs_play_song( SONG_ENDGAME, 0 );
1475                                 mprintf((0,"doing briefing\n"));
1476                                 do_briefing_screens("ending2.tex",1);
1477                                 mprintf((0,"briefing done\n"));
1478                         }
1479                 }
1480    } else if (!(Game_mode & GM_MULTI)) {    //not multi
1481                 char tname[FILENAME_LEN];
1482                 sprintf(tname,"%s.tex",Current_mission_filename);
1483                 do_briefing_screens (tname,Last_level+1);   //level past last is endgame breifing
1484
1485                 //try doing special credits
1486                 sprintf(tname,"%s.ctb",Current_mission_filename);
1487                 credits_show(tname);
1488         }
1489
1490         key_flush();
1491
1492 #ifdef SHAREWARE
1493                 show_order_form();
1494 #endif
1495
1496 #ifdef NETWORK
1497         if (Game_mode & GM_MULTI)
1498                 multi_endlevel_score();
1499         else
1500 #endif
1501                 // NOTE LINK TO ABOVE
1502                 DoEndLevelScoreGlitz(0);
1503
1504         if (Current_mission_num == Builtin_mission_num && !((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP))) {
1505                 WINDOS(
1506                         dd_gr_set_current_canvas(NULL),
1507                         gr_set_current_canvas( NULL )
1508                 );
1509                 WINDOS(
1510                         dd_gr_clear_canvas(BM_XRGB(0,0,0)),
1511                         gr_clear_canvas(BM_XRGB(0,0,0))
1512                 );
1513                 gr_palette_clear();
1514                 load_palette(DEFAULT_PALETTE,0,1);
1515                 scores_maybe_add_player(0);
1516         }
1517
1518         Function_mode = FMODE_MENU;
1519
1520         if ((Game_mode & GM_SERIAL) || (Game_mode & GM_MODEM))
1521                 Game_mode |= GM_GAME_OVER;              //preserve modem setting so go back into modem menu
1522         else
1523                 Game_mode = GM_GAME_OVER;
1524
1525
1526         longjmp( LeaveGame, 0 );                // Exit out of game loop
1527 }
1528
1529 //from which level each do you get to each secret level 
1530 int Secret_level_table[MAX_SECRET_LEVELS_PER_MISSION];
1531
1532 //called to go to the next level (if there is one)
1533 //if secret_flag is true, advance to secret level, else next normal one
1534 //      Return true if game over.
1535 void AdvanceLevel(int secret_flag)
1536 {
1537 #ifdef NETWORK
1538         int result;
1539 #endif
1540
1541         mprintf((0,"AdvanceLevel\n"));
1542
1543         Assert(!secret_flag);
1544
1545         if (Current_level_num != Last_level) {
1546 #ifdef NETWORK
1547                 if (Game_mode & GM_MULTI)
1548                         multi_endlevel_score();         
1549                 else 
1550 #endif
1551                         // NOTE LINK TO ABOVE!!!
1552                         DoEndLevelScoreGlitz(0);                //give bonuses
1553         }
1554
1555         Control_center_destroyed = 0;
1556
1557         #ifdef EDITOR
1558         if (Current_level_num == 0)
1559                 return;         //not a real level
1560         #endif
1561
1562 #ifdef NETWORK
1563         if (Game_mode & GM_MULTI)       {
1564                 result = multi_endlevel(&secret_flag); // Wait for other players to reach this point
1565                 if (result) // failed to sync
1566                 {
1567                         if (Current_level_num == Last_level)            //player has finished the game!
1568                                 longjmp( LeaveGame, 0 );                // Exit out of game loop
1569                         else
1570                                 return;
1571                 }
1572         }
1573 #endif
1574
1575         if (Current_level_num == Last_level) {          //player has finished the game!
1576                 
1577                 mprintf((0,"Finished last level!\n"));
1578
1579                 DoEndGame();
1580
1581         } else {
1582
1583                 Next_level_num = Current_level_num+1;           //assume go to next normal level
1584
1585                 if (!(Game_mode & GM_MULTI))
1586                         DoEndlevelMenu(); // Let use save their game
1587
1588                 StartNewLevel(Next_level_num, 0);
1589
1590         }
1591 }
1592
1593 #ifdef MACINTOSH                // horrible hack of a routine to load just the palette from the stars.pcx file
1594
1595 extern char last_palette_loaded[];
1596
1597 void load_stars_palette()
1598 {
1599         int pcx_error;
1600         ubyte pal[256*3];
1601
1602         pcx_error = pcx_read_bitmap_palette(STARS_BACKGROUND,pal);
1603         Assert(pcx_error == PCX_ERROR_NONE);
1604
1605         //@@gr_remap_bitmap_good( bmp, pal, -1, -1 );
1606
1607
1608         {       //remap stuff. this code is kindof a hack
1609
1610                 //now, before we bring up the menu, we need to 
1611                 //do some stuff to make sure the palette is ok.  First, we need to
1612                 //get our current palette into the 2d's array, so the remapping will
1613                 //work.  Second, we need to remap the fonts.  Third, we need to fill 
1614                 //in part of the fade tables so the darkening of the menu edges works
1615
1616                 gr_copy_palette(gr_palette, pal, sizeof(gr_palette));
1617                 remap_fonts_and_menus(1);
1618
1619         }
1620
1621         strcpy(last_palette_loaded,"");         //force palette load next time
1622 }
1623 #endif
1624
1625 void nm_draw_background1(char * filename);
1626
1627 void load_stars()
1628 {
1629 //@@    int pcx_error;
1630 //@@    ubyte pal[256*3];
1631 //@@
1632 //@@    pcx_error = pcx_read_bitmap("STARS.PCX",&grd_curcanv->cv_bitmap,grd_curcanv->cv_bitmap.bm_type,pal);
1633 //@@    Assert(pcx_error == PCX_ERROR_NONE);
1634 //@@
1635 //@@    gr_remap_bitmap_good( &grd_curcanv->cv_bitmap, pal, -1, -1 );
1636
1637         WIN(DEFINE_SCREEN(STARS_BACKGROUND));
1638
1639         nm_draw_background1(STARS_BACKGROUND);
1640
1641 }
1642
1643
1644 void
1645 died_in_mine_message(void)
1646 {
1647         // Tell the player he died in the mine, explain why
1648         int old_fmode;
1649
1650         if (Game_mode & GM_MULTI)
1651                 return;
1652
1653         gr_palette_fade_out(gr_palette, 32, 0);
1654
1655         set_screen_mode(SCREEN_MENU);           //go into menu mode
1656
1657         WINDOS(
1658                 dd_gr_set_current_canvas(NULL),
1659                 gr_set_current_canvas(NULL)
1660         );
1661
1662         load_stars();
1663
1664 #if defined(POLY_ACC)
1665         pa_save_clut();
1666         pa_update_clut(gr_palette, 0, 256, 0);
1667 #endif
1668
1669         old_fmode = Function_mode;
1670         Function_mode = FMODE_MENU;
1671         nm_messagebox(NULL, 1, TXT_OK, TXT_DIED_IN_MINE);
1672         Function_mode = old_fmode;
1673
1674 #if defined(POLY_ACC)
1675         pa_restore_clut();
1676 #endif
1677
1678         WIN(DEFINE_SCREEN(NULL));
1679 }
1680
1681 //      Called when player dies on secret level.
1682 void returning_to_level_message(void)
1683 {
1684         char    msg[128];
1685
1686         int old_fmode;
1687
1688         if (Game_mode & GM_MULTI)
1689                 return;
1690
1691         gr_palette_fade_out(gr_palette, 32, 0);
1692
1693         set_screen_mode(SCREEN_MENU);           //go into menu mode
1694
1695         gr_set_current_canvas(NULL);
1696
1697         load_stars();
1698
1699 #if defined(POLY_ACC)
1700         pa_save_clut();
1701         pa_update_clut(gr_palette, 0, 256, 0);
1702 #endif
1703
1704         old_fmode = Function_mode;
1705         Function_mode = FMODE_MENU;
1706         sprintf(msg, "Returning to level %i", Entered_from_level);
1707         nm_messagebox(NULL, 1, TXT_OK, msg);
1708         Function_mode = old_fmode;
1709
1710 #if defined(POLY_ACC)
1711         pa_restore_clut();
1712 #endif
1713
1714         WIN(DEFINE_SCREEN(NULL));
1715 }
1716
1717 //      Called when player dies on secret level.
1718 void advancing_to_level_message(void)
1719 {
1720         char    msg[128];
1721
1722         int old_fmode;
1723
1724         //      Only supposed to come here from a secret level.
1725         Assert(Current_level_num < 0);
1726
1727         if (Game_mode & GM_MULTI)
1728                 return;
1729
1730         gr_palette_fade_out(gr_palette, 32, 0);
1731
1732         set_screen_mode(SCREEN_MENU);           //go into menu mode
1733
1734         gr_set_current_canvas(NULL);
1735         
1736         load_stars();
1737
1738 #if defined(POLY_ACC)
1739         pa_save_clut();
1740         pa_update_clut(gr_palette, 0, 256, 0);
1741 #endif
1742
1743         old_fmode = Function_mode;
1744         Function_mode = FMODE_MENU;
1745         sprintf(msg, "Base level destroyed.\nAdvancing to level %i", Entered_from_level+1);
1746         nm_messagebox(NULL, 1, TXT_OK, msg);
1747         Function_mode = old_fmode;
1748
1749 #if defined(POLY_ACC)
1750         pa_restore_clut();
1751 #endif
1752
1753         WIN(DEFINE_SCREEN(NULL));
1754 }
1755
1756 void digi_stop_digi_sounds();
1757
1758 void DoPlayerDead()
1759 {
1760         reset_palette_add();
1761
1762         gr_palette_load (gr_palette);
1763
1764 //      digi_pause_digi_sounds();               //kill any continuing sounds (eg. forcefield hum)
1765         digi_stop_digi_sounds();                //kill any continuing sounds (eg. forcefield hum)
1766
1767         dead_player_end();              //terminate death sequence (if playing)
1768
1769         #ifdef EDITOR
1770         if (Game_mode == GM_EDITOR) {                   //test mine, not real level
1771                 object * playerobj = &Objects[Players[Player_num].objnum];
1772                 //nm_messagebox( "You're Dead!", 1, "Continue", "Not a real game, though." );
1773                 load_level("gamesave.lvl");
1774                 init_player_stats_new_ship();
1775                 playerobj->flags &= ~OF_SHOULD_BE_DEAD;
1776                 StartLevel(0);
1777                 return;
1778         }
1779         #endif
1780
1781 #ifdef NETWORK
1782         if ( Game_mode&GM_MULTI )
1783         {
1784                 multi_do_death(Players[Player_num].objnum);
1785         }
1786         else 
1787 #endif
1788         {                               //Note link to above else!
1789                 Players[Player_num].lives--;
1790                 if (Players[Player_num].lives == 0)
1791                 {       
1792                         DoGameOver();
1793                         return;
1794                 }
1795         }
1796                                 
1797         if ( Control_center_destroyed ) {
1798
1799                 //clear out stuff so no bonus
1800                 Players[Player_num].hostages_on_board = 0;
1801                 Players[Player_num].energy = 0;
1802                 Players[Player_num].shields = 0;
1803                 Players[Player_num].connected = 3;
1804
1805                 died_in_mine_message(); // Give them some indication of what happened
1806
1807                 if (Current_level_num < 0) {
1808                         FILE    *fp;
1809
1810                         if ((fp = fopen(SECRETB_FILENAME, "rb")) != NULL) {
1811                                 fclose(fp);
1812                                 returning_to_level_message();
1813                                 state_restore_all(1, 2, SECRETB_FILENAME);                      //      2 means you died
1814                                 set_pos_from_return_segment();
1815                                 Players[Player_num].lives--;                                            //      re-lose the life, Players[Player_num].lives got written over in restore.
1816                         } else {
1817                                 advancing_to_level_message();
1818                                 StartNewLevel(Entered_from_level+1, 0);
1819                                 init_player_stats_new_ship();   //      New, MK, 05/29/96!, fix bug with dying in secret level, advance to next level, keep powerups!
1820                         }
1821                 } else {
1822
1823                         AdvanceLevel(0);                        //if finished, go on to next level
1824
1825                         init_player_stats_new_ship();
1826                         last_drawn_cockpit[0] = -1;
1827                         last_drawn_cockpit[1] = -1;
1828                 }
1829
1830         } else if (Current_level_num < 0) {
1831                 FILE    *fp;
1832                 if ((fp = fopen(SECRETB_FILENAME, "rb")) != NULL) {
1833                         fclose(fp);
1834                         returning_to_level_message();
1835                         if (!Control_center_destroyed)
1836                                 state_save_all(0, 2, SECRETC_FILENAME);
1837                         state_restore_all(1, 2, SECRETB_FILENAME);
1838                         set_pos_from_return_segment();
1839                         Players[Player_num].lives--;                                            //      re-lose the life, Players[Player_num].lives got written over in restore.
1840                 } else {
1841                         died_in_mine_message(); // Give them some indication of what happened
1842                         advancing_to_level_message();
1843                         StartNewLevel(Entered_from_level+1, 0);
1844                         init_player_stats_new_ship();
1845                 }
1846         } else {
1847                 init_player_stats_new_ship();
1848                 StartLevel(1);
1849         }
1850
1851         digi_sync_sounds();
1852 }
1853
1854 extern int BigWindowSwitch;
1855
1856 //called when the player is starting a new level for normal game mode and restore state
1857 //      secret_flag set if came from a secret level
1858 void StartNewLevelSub(int level_num, int page_in_textures, int secret_flag)
1859 {
1860         if (!(Game_mode & GM_MULTI)) {
1861                 last_drawn_cockpit[0] = -1;
1862                 last_drawn_cockpit[1] = -1;
1863         }
1864    BigWindowSwitch=0;
1865
1866
1867         if (Newdemo_state == ND_STATE_PAUSED)
1868                 Newdemo_state = ND_STATE_RECORDING;
1869
1870         if (Newdemo_state == ND_STATE_RECORDING) {
1871                 newdemo_set_new_level(level_num);
1872                 newdemo_record_start_frame(FrameCount, FrameTime );
1873         }
1874
1875         if (Game_mode & GM_MULTI)
1876                 Function_mode = FMODE_MENU; // Cheap fix to prevent problems with errror dialogs in loadlevel.
1877
1878         LoadLevel(level_num,page_in_textures);
1879
1880         Assert(Current_level_num == level_num); //make sure level set right
1881
1882         gameseq_init_network_players(); // Initialize the Players array for 
1883                                                                                           // this level
1884
1885         Viewer = &Objects[Players[Player_num].objnum];
1886
1887         Assert(N_players <= NumNetPlayerPositions);
1888                 //If this assert fails, there's not enough start positions
1889
1890 #ifdef NETWORK
1891         if (Game_mode & GM_NETWORK)
1892         {
1893                 if(network_level_sync()) // After calling this, Player_num is set
1894                         return;
1895         }
1896         if ((Game_mode & GM_SERIAL) || (Game_mode & GM_MODEM))
1897         {
1898                 if(com_level_sync())
1899                         return;
1900         }
1901 #endif
1902
1903         Assert(Function_mode == FMODE_GAME);
1904
1905         #ifndef NDEBUG
1906         //-- mprintf((0, "Player_num = %d, N_players = %d.\n", Player_num, N_players)); // DEBUG
1907         #endif
1908
1909         HUD_clear_messages();
1910
1911         automap_clear_visited();
1912
1913 #ifdef NETWORK
1914         if (Network_new_game == 1)
1915         {
1916                 Network_new_game = 0;
1917                 init_player_stats_new_ship();
1918         }
1919 #endif
1920         init_player_stats_level(secret_flag);
1921
1922 #ifdef NETWORK
1923         if ((Game_mode & GM_MULTI_COOP) && Network_rejoined)
1924         {
1925                 int i;
1926                 for (i = 0; i < N_players; i++)
1927                         Players[i].flags |= Netgame.player_flags[i];
1928         }
1929
1930         if (Game_mode & GM_MULTI)
1931         {
1932                 multi_prep_level(); // Removes robots from level if necessary
1933         }
1934 #endif
1935
1936         gameseq_remove_unused_players();
1937
1938         Game_suspended = 0;
1939
1940         Control_center_destroyed = 0;
1941
1942         set_screen_mode(SCREEN_GAME);
1943         init_cockpit();
1944         init_robots_for_level();
1945         init_ai_objects();
1946         init_smega_detonates();
1947         init_morphs();
1948         init_all_matcens();
1949         reset_palette_add();
1950         init_thief_for_level();
1951         init_stuck_objects();
1952         game_flush_inputs();            // clear out the keyboard
1953         if (!(Game_mode & GM_MULTI))
1954                 filter_objects_from_level();
1955
1956         turn_cheats_off();
1957
1958         if (!(Game_mode & GM_MULTI) && !Cheats_enabled)
1959                 set_highest_level(Current_level_num);
1960         else
1961                 read_player_file();             //get window sizes
1962
1963         reset_special_effects();
1964
1965 #ifdef OGL
1966         ogl_cache_level_textures();
1967 #endif
1968
1969
1970 #ifdef NETWORK
1971         if (Network_rejoined == 1)
1972         {
1973                 #ifndef NDEBUG
1974                 mprintf((0, "Restarting - joining in random location.\n"));
1975                 #endif
1976                 Network_rejoined = 0;
1977                 StartLevel(1);
1978         }
1979         else
1980 #endif
1981                 StartLevel(0);          // Note link to above if!
1982
1983         copy_defaults_to_robot_all();
1984         init_controlcen_for_level();
1985
1986         //      Say player can use FLASH cheat to mark path to exit.
1987         Last_level_path_created = -1;
1988 }
1989
1990 #ifdef NETWORK
1991 extern char PowerupsInMine[MAX_POWERUP_TYPES], MaxPowerupsAllowed[MAX_POWERUP_TYPES];
1992 #endif
1993 void bash_to_shield (int i,char *s)
1994 {
1995 #ifdef NETWORK
1996         int type=Objects[i].id;
1997 #endif
1998
1999         mprintf((0, "Bashing %s object #%i to shield.\n",s, i));
2000
2001 #ifdef NETWORK
2002         PowerupsInMine[type]=MaxPowerupsAllowed[type]=0;
2003 #endif
2004
2005         Objects[i].id = POW_SHIELD_BOOST;
2006         Objects[i].rtype.vclip_info.vclip_num = Powerup_info[Objects[i].id].vclip_num;
2007         Objects[i].rtype.vclip_info.frametime = Vclip[Objects[i].rtype.vclip_info.vclip_num].frame_time;
2008 }
2009
2010
2011 void filter_objects_from_level()
2012  {
2013   int i;
2014   
2015   mprintf ((0,"Highest object index=%d\n",Highest_object_index));
2016  
2017   for (i=0;i<=Highest_object_index;i++) 
2018         {
2019          if (Objects[i].type==OBJ_POWERUP)
2020      if (Objects[i].id==POW_FLAG_RED || Objects[i].id==POW_FLAG_BLUE)
2021            bash_to_shield (i,"Flag!!!!");
2022    } 
2023
2024  }
2025
2026 struct {
2027         int     level_num;
2028         char    movie_name[FILENAME_LEN];
2029 } intro_movie[] = {     { 1,"pla"},
2030                                                         { 5,"plb"},
2031                                                         { 9,"plc"},
2032                                                         {13,"pld"},
2033                                                         {17,"ple"},
2034                                                         {21,"plf"},
2035                                                         {24,"plg"}};
2036
2037 #define NUM_INTRO_MOVIES (sizeof(intro_movie) / sizeof(*intro_movie))
2038
2039 extern int MenuHiresAvailable;
2040 extern int robot_movies;        //0 means none, 1 means lowres, 2 means hires
2041 extern int intro_played;        //true if big intro movie played
2042
2043 void ShowLevelIntro(int level_num)
2044 {
2045         //if shareware, show a briefing?
2046
2047         if (!(Game_mode & GM_MULTI)) {
2048                 int i;
2049
2050                 ubyte save_pal[sizeof(gr_palette)];
2051
2052                 memcpy(save_pal,gr_palette,sizeof(gr_palette));
2053
2054                 if (Current_mission_num == Builtin_mission_num) {
2055                         int movie=0;
2056
2057                         if (cfexist("brief2.txb") || cfexist("brief2.tex")) { // SHAREWARE
2058                                 if (level_num==1)
2059                                         do_briefing_screens ("brief2.tex", 1);
2060                         } else if (cfexist("brief2o.txb") || cfexist("brief2o.tex")) { // OEM
2061                                 if (level_num == 1 && !intro_played)
2062                                         do_briefing_screens("brief2o.tex", 1);
2063                         } else { // full version
2064                                 for (i=0;i<NUM_INTRO_MOVIES;i++)
2065                                 {
2066                                         if (intro_movie[i].level_num == level_num)
2067                                         {
2068                                                 Screen_mode = -1;
2069                                                 PlayMovie(intro_movie[i].movie_name,MOVIE_REQUIRED);
2070                                                 movie=1;
2071                                                 break;
2072                                         }
2073                                 }
2074
2075 #ifdef WINDOWS
2076                                 if (!movie) {                                   //must go before briefing
2077                                         dd_gr_init_screen();
2078                                         Screen_mode = -1;
2079                                 }
2080 #endif
2081
2082                                 if (robot_movies)
2083                                 {
2084                                         int hires_save=MenuHiresAvailable;
2085
2086                                         if (robot_movies == 1)          //lowres only
2087                                         {
2088                                                 MenuHiresAvailable = 0;         //pretend we can't do highres
2089
2090                                                 if (hires_save != MenuHiresAvailable)
2091                                                         Screen_mode = -1;               //force reset
2092
2093                                         }
2094                                         do_briefing_screens ("robot.tex",level_num);
2095                                         MenuHiresAvailable = hires_save;
2096                                 }
2097
2098                         }
2099                 }
2100                 else {  //not the built-in mission.  check for add-on briefing
2101                         if (Mission_list[Current_mission_num].descent_version == 1)
2102                                 do_briefing_screens(Briefing_text_filename, level_num);
2103                         else {
2104                                 char tname[FILENAME_LEN];
2105                                 sprintf(tname, "%s.tex", Current_mission_filename);
2106                                 do_briefing_screens(tname, level_num);
2107                         }
2108                 }
2109
2110
2111                 memcpy(gr_palette,save_pal,sizeof(gr_palette));
2112         }
2113 }
2114
2115 //      ---------------------------------------------------------------------------
2116 //      If starting a level which appears in the Secret_level_table, then set First_secret_visit.
2117 //      Reason: On this level, if player goes to a secret level, he will be going to a different
2118 //      secret level than he's ever been to before.
2119 //      Sets the global First_secret_visit if necessary.  Otherwise leaves it unchanged.
2120 void maybe_set_first_secret_visit(int level_num)
2121 {
2122         int     i;
2123
2124         for (i=0; i<N_secret_levels; i++) {
2125                 if (Secret_level_table[i] == level_num) {
2126                         First_secret_visit = 1;
2127                         mprintf((0, "Bashing First_secret_visit to 1 because entering level %i.\n", level_num));
2128                 }
2129         }
2130 }
2131
2132 //called when the player is starting a new level for normal game model
2133 //      secret_flag if came from a secret level
2134 void StartNewLevel(int level_num, int secret_flag)
2135 {
2136         ThisLevelTime=0;
2137
2138         if ((level_num > 0) && (!secret_flag)) {
2139                 maybe_set_first_secret_visit(level_num);
2140         }
2141
2142         ShowLevelIntro(level_num);
2143
2144         WIN(DEFINE_SCREEN(NULL));               // ALT-TAB: no restore of background.
2145         
2146         StartNewLevelSub(level_num, 1, secret_flag );
2147
2148 }
2149
2150 //initialize the player object position & orientation (at start of game, or new ship)
2151 void InitPlayerPosition(int random_flag)
2152 {
2153         int NewPlayer=0;
2154
2155 #ifdef NETWORK
2156         if (! ((Game_mode & GM_MULTI) && !(Game_mode&GM_MULTI_COOP)) ) // If not deathmatch
2157 #endif
2158                 NewPlayer = Player_num;
2159 #ifdef NETWORK
2160         else if (random_flag == 1)
2161         {
2162                 int i, closest = -1, trys=0;
2163                 fix closest_dist = 0x7ffffff, dist;
2164
2165                 d_srand(clock());
2166
2167 #ifndef NDEBUG
2168                 if (NumNetPlayerPositions != MAX_NUM_NET_PLAYERS)
2169                 {
2170                         mprintf((1, "WARNING: There are only %d start positions!\n"));
2171                         //Int3();
2172                 }
2173 #endif
2174
2175                 do {
2176                         if (trys > 0)   
2177                         {
2178                                 mprintf((0, "Can't start in location %d because its too close to player %d\n", NewPlayer, closest ));
2179                         }
2180                         trys++;
2181
2182                         NewPlayer = d_rand() % NumNetPlayerPositions;
2183
2184                         closest = -1;
2185                         closest_dist = 0x7fffffff;
2186         
2187                         for (i=0; i<N_players; i++ )    {
2188                                 if ( (i!=Player_num) && (Objects[Players[i].objnum].type == OBJ_PLAYER) )       {
2189                                         dist = find_connected_distance(&Objects[Players[i].objnum].pos, Objects[Players[i].objnum].segnum, &Player_init[NewPlayer].pos, Player_init[NewPlayer].segnum, 10, WID_FLY_FLAG );      //      Used to be 5, search up to 10 segments
2190                                         // -- mprintf((0, "Distance from start location %d to player %d is %f.\n", NewPlayer, i, f2fl(dist)));
2191                                         if ( (dist < closest_dist) && (dist >= 0) )     {
2192                                                 closest_dist = dist;
2193                                                 closest = i;
2194                                         }
2195                                 }
2196                         }
2197
2198                         // -- mprintf((0, "Closest from pos %d is %f to plr %d.\n", NewPlayer, f2fl(closest_dist), closest));
2199                 } while ( (closest_dist<i2f(15*20)) && (trys<MAX_NUM_NET_PLAYERS*2) );
2200         } 
2201         else {
2202                 mprintf((0, "Starting position is not being changed.\n"));
2203                 goto done; // If deathmatch and not random, positions were already determined by sync packet
2204         }
2205         Assert(NewPlayer >= 0);
2206         Assert(NewPlayer < NumNetPlayerPositions);
2207 #endif
2208
2209         ConsoleObject->pos = Player_init[NewPlayer].pos;
2210         ConsoleObject->orient = Player_init[NewPlayer].orient;
2211 // -- mprintf((0, "Pos set to %8x %8x %8x\n", ConsoleObject->pos.x, ConsoleObject->pos.y, ConsoleObject->pos.z));
2212
2213         // -- mprintf((0, "Re-starting in location %d of %d.\n", NewPlayer+1, NumNetPlayerPositions));
2214
2215         obj_relink(ConsoleObject-Objects,Player_init[NewPlayer].segnum);
2216
2217 #ifdef NETWORK
2218 done:
2219 #endif
2220         reset_player_object();
2221         reset_cruise();
2222 }
2223
2224 //      -----------------------------------------------------------------------------------------------------
2225 //      Initialize default parameters for one robot, copying from Robot_info to *objp.
2226 //      What about setting size!?  Where does that come from?
2227 void copy_defaults_to_robot(object *objp)
2228 {
2229         robot_info      *robptr;
2230         int                     objid;
2231
2232         Assert(objp->type == OBJ_ROBOT);
2233         objid = objp->id;
2234         Assert(objid < N_robot_types);
2235
2236         robptr = &Robot_info[objid];
2237
2238         //      Boost shield for Thief and Buddy based on level.
2239         objp->shields = robptr->strength;
2240
2241         if ((robptr->thief) || (robptr->companion)) {
2242                 objp->shields = (objp->shields * (abs(Current_level_num)+7))/8;
2243
2244                 if (robptr->companion) {
2245                         //      Now, scale guide-bot hits by skill level
2246                         switch (Difficulty_level) {
2247                                 case 0: objp->shields = i2f(20000);     break;          //      Trainee, basically unkillable
2248                                 case 1: objp->shields *= 3;                             break;          //      Rookie, pretty dang hard
2249                                 case 2: objp->shields *= 2;                             break;          //      Hotshot, a bit tough
2250                                 default:        break;
2251                         }
2252                 }
2253         } else if (robptr->boss_flag)   //      MK, 01/16/95, make boss shields lower on lower diff levels.
2254                 objp->shields = objp->shields/(NDL+3) * (Difficulty_level+4);
2255
2256         //      Additional wimpification of bosses at Trainee
2257         if ((robptr->boss_flag) && (Difficulty_level == 0))
2258                 objp->shields /= 2;
2259 }
2260
2261 //      -----------------------------------------------------------------------------------------------------
2262 //      Copy all values from the robot info structure to all instances of robots.
2263 //      This allows us to change bitmaps.tbl and have these changes manifested in existing robots.
2264 //      This function should be called at level load time.
2265 void copy_defaults_to_robot_all()
2266 {
2267         int     i;
2268
2269         for (i=0; i<=Highest_object_index; i++)
2270                 if (Objects[i].type == OBJ_ROBOT)
2271                         copy_defaults_to_robot(&Objects[i]);
2272
2273 }
2274
2275 extern void clear_stuck_objects(void);
2276
2277 //      -----------------------------------------------------------------------------------------------------
2278 //called when the player is starting a level (new game or new ship)
2279 void StartLevel(int random_flag)
2280 {
2281         Assert(!Player_is_dead);
2282
2283         InitPlayerPosition(random_flag);
2284
2285         verify_console_object();
2286
2287         ConsoleObject->control_type     = CT_FLYING;
2288         ConsoleObject->movement_type    = MT_PHYSICS;
2289
2290         disable_matcens();
2291
2292         clear_transient_objects(0);             //0 means leave proximity bombs
2293
2294         // create_player_appearance_effect(ConsoleObject);
2295         Do_appearance_effect = 1;
2296
2297 #ifdef NETWORK
2298         if (Game_mode & GM_MULTI)
2299         {
2300                 if (Game_mode & GM_MULTI_COOP)
2301                         multi_send_score();
2302                 multi_send_position(Players[Player_num].objnum);
2303                 multi_send_reappear();
2304         }               
2305
2306         if (Game_mode & GM_NETWORK)
2307                 network_do_frame(1, 1);
2308 #endif
2309
2310         ai_reset_all_paths();
2311         ai_init_boss_for_ship();
2312         clear_stuck_objects();
2313
2314         #ifdef EDITOR
2315         //      Note, this is only done if editor builtin.  Calling this from here
2316         //      will cause it to be called after the player dies, resetting the
2317         //      hits for the buddy and thief.  This is ok, since it will work ok
2318         //      in a shipped version.
2319         init_ai_objects();
2320         #endif
2321
2322         reset_time();
2323
2324         reset_rear_view();
2325         Auto_fire_fusion_cannon_time = 0;
2326         Fusion_charge = 0;
2327
2328         Robot_firing_enabled = 1;
2329 }