attempt to support mac d1 descent.pig
[btb/d2x.git] / main / gameseq.c
1 /* $Id: gameseq.c,v 1.22 2003-03-22 02:41:42 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.22 2003-03-22 02:41:42 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 extern void change_filename_extension( char *dest, char *src, char *new_ext );
822 extern char last_palette_loaded_pig[];
823
824 ubyte *Bitmap_replacement_data=NULL;
825
826 void free_bitmap_replacements()
827 {
828         if (Bitmap_replacement_data) {
829                 d_free(Bitmap_replacement_data);
830                 Bitmap_replacement_data = NULL;
831         }
832 }
833
834 void load_bitmap_replacements(char *level_name)
835 {
836         char ifile_name[FILENAME_LEN];
837         CFILE *ifile;
838         int i;
839
840         //first, free up data allocated for old bitmaps
841         free_bitmap_replacements();
842
843         change_filename_extension(ifile_name, level_name, ".POG" );
844         
845         ifile = cfopen(ifile_name,"rb");
846
847         if (ifile) {
848                 int id,version,n_bitmaps;
849                 int bitmap_data_size;
850                 ushort *indices;
851  
852                 id = cfile_read_int(ifile);
853                 version = cfile_read_int(ifile);
854
855                 if (id != MAKE_SIG('G','O','P','D') || version != 1) {
856                         cfclose(ifile);
857                         return;
858                 }
859
860                 n_bitmaps = cfile_read_int(ifile);
861
862                 MALLOC( indices, ushort, n_bitmaps );
863                 
864                 for (i = 0; i < n_bitmaps; i++)
865                         indices[i] = cfile_read_short(ifile);
866
867                 bitmap_data_size = cfilelength(ifile) - cftell(ifile) - DISKBITMAPHEADER_SIZE * n_bitmaps;
868                 MALLOC( Bitmap_replacement_data, ubyte, bitmap_data_size );
869
870                 for (i=0;i<n_bitmaps;i++) {
871                         DiskBitmapHeader bmh;
872                         grs_bitmap temp_bitmap;
873
874                         DiskBitmapHeader_read(&bmh, ifile);
875
876                         memset( &temp_bitmap, 0, sizeof(grs_bitmap) );
877         
878                         temp_bitmap.bm_w = temp_bitmap.bm_rowsize = bmh.width + ((short) (bmh.wh_extra&0x0f)<<8);
879                         temp_bitmap.bm_h = bmh.height + ((short) (bmh.wh_extra&0xf0)<<4);
880                         temp_bitmap.avg_color = bmh.avg_color;
881                         temp_bitmap.bm_data = Bitmap_replacement_data + bmh.offset;
882         
883                         if ( bmh.flags & BM_FLAG_TRANSPARENT ) temp_bitmap.bm_flags |= BM_FLAG_TRANSPARENT;
884                         if ( bmh.flags & BM_FLAG_SUPER_TRANSPARENT ) temp_bitmap.bm_flags |= BM_FLAG_SUPER_TRANSPARENT;
885                         if ( bmh.flags & BM_FLAG_NO_LIGHTING ) temp_bitmap.bm_flags |= BM_FLAG_NO_LIGHTING;
886                         if ( bmh.flags & BM_FLAG_RLE ) temp_bitmap.bm_flags |= BM_FLAG_RLE;
887                         if ( bmh.flags & BM_FLAG_RLE_BIG ) temp_bitmap.bm_flags |= BM_FLAG_RLE_BIG;
888
889                         GameBitmaps[indices[i]] = temp_bitmap;
890                 }
891
892                 cfread(Bitmap_replacement_data,1,bitmap_data_size,ifile);
893
894                 d_free(indices);
895
896                 cfclose(ifile);
897
898                 last_palette_loaded_pig[0]= 0;  //force pig re-load
899
900                 texmerge_flush();               //for re-merging with new textures
901         }
902
903         atexit(free_bitmap_replacements);
904 }
905
906 #define FIRST_D1_TEXTURE 722
907 #define LAST_D1_STATIC_TEXTURE 1042//1342 //afterwards, we have door frames and stuff
908 #define FIRST_D2_TEXTURE 1243
909
910 void load_d1_bitmap_replacements()
911 {
912         CFILE * d1_Piggy_fp;
913         grs_bitmap temp_bitmap;
914         DiskBitmapHeader bmh;
915         int pig_data_start, bitmap_header_start, bitmap_data_start;
916         int N_bitmaps, zsize;
917         int d1_index, d2_index;
918         ubyte colormap[256];
919         ubyte *next_bitmap; // to which address we write the next bitmap
920
921 #ifndef MACINTOSH
922         d1_Piggy_fp = cfopen( "descent.pig", "rb" );
923 #else
924         d1_Piggy_fp = cfopen( "Data:Descent.pig", "rb" );
925 #endif  // end of ifndef/else MACINTOSH
926
927         if (!d1_Piggy_fp)
928                 return; // use d2 bitmaps instead...
929
930         //first, free up data allocated for old bitmaps
931         free_bitmap_replacements();
932
933         // read d1 palette, build colormap
934         {
935                 int freq[256];
936                 ubyte d1_palette[256*3];
937                 CFILE * palette_file = cfopen( "palette.256", "rb" );
938                 Assert( palette_file );
939                 Assert( cfilelength( palette_file ) == 9472 );
940                 cfread( d1_palette, 256, 3, palette_file);
941                 cfclose( palette_file );
942                 build_colormap_good( d1_palette, colormap, freq );
943                 // don't change transparencies:
944                 colormap[254] = 254;
945                 colormap[255] = 255;
946         }
947
948
949         if (0) //TODO: put here cfilelength(d1_Piggy_fp) == D1_PIG_SHARE
950                 pig_data_start = 0;
951         else {
952                 //int i;
953                 pig_data_start = cfile_read_int(d1_Piggy_fp );
954                 bm_read_all_d1( d1_Piggy_fp );
955                 //for (i = 0; i < 1800; i++) GameBitmapXlat[i] = cfile_read_short(d1_Piggy_fp);
956         }
957         cfseek( d1_Piggy_fp, pig_data_start, SEEK_SET );
958         N_bitmaps = cfile_read_int(d1_Piggy_fp);
959         {
960                 int N_sounds = cfile_read_int(d1_Piggy_fp);
961                 int header_size = N_bitmaps * DISKBITMAPHEADER_D1_SIZE
962                                 + N_sounds * DISKSOUNDHEADER_SIZE;
963                 bitmap_header_start = pig_data_start + 2 * sizeof(int);
964                 bitmap_data_start = bitmap_header_start + header_size;
965         }
966
967         MALLOC( Bitmap_replacement_data, ubyte, cfilelength(d1_Piggy_fp) - bitmap_data_start ); // too much
968         //TODO: handle case where b_r_d == 0! (have to convert textures, return, not bm_read_all_d1)
969
970         next_bitmap = Bitmap_replacement_data;
971
972         for (d1_index=1; d1_index<=N_bitmaps; d1_index++ ) {
973                 // only change wall texture bitmaps
974                 if (d1_index >= FIRST_D1_TEXTURE && d1_index <= LAST_D1_STATIC_TEXTURE) {
975                         d2_index = d1_index + FIRST_D2_TEXTURE - FIRST_D1_TEXTURE;
976
977                         cfseek(d1_Piggy_fp, bitmap_header_start + (d1_index-1) * DISKBITMAPHEADER_D1_SIZE, SEEK_SET);
978                         DiskBitmapHeader_d1_read(&bmh, d1_Piggy_fp);
979
980                         memset( &temp_bitmap, 0, sizeof(grs_bitmap) );
981
982                         temp_bitmap.bm_w = temp_bitmap.bm_rowsize = bmh.width + ((short) (bmh.wh_extra&0x0f)<<8);
983                         temp_bitmap.bm_h = bmh.height + ((short) (bmh.wh_extra&0xf0)<<4);
984                         temp_bitmap.avg_color = bmh.avg_color;
985
986                         //GameBitmapFlags[convert_d1_bitmap_num(d1_index)] = 0;
987
988                         if ( bmh.flags & BM_FLAG_TRANSPARENT )
989                                 temp_bitmap.bm_flags |= BM_FLAG_TRANSPARENT;
990                         if ( bmh.flags & BM_FLAG_SUPER_TRANSPARENT )
991                                 temp_bitmap.bm_flags |= BM_FLAG_SUPER_TRANSPARENT;
992                         if ( bmh.flags & BM_FLAG_NO_LIGHTING )
993                                 temp_bitmap.bm_flags |= BM_FLAG_NO_LIGHTING;
994                         if ( bmh.flags & BM_FLAG_RLE )
995                                 temp_bitmap.bm_flags |= BM_FLAG_RLE;
996                         if ( bmh.flags & BM_FLAG_RLE_BIG )
997                                 temp_bitmap.bm_flags |= BM_FLAG_RLE_BIG;
998
999                         temp_bitmap.bm_data = next_bitmap;
1000
1001                         cfseek(d1_Piggy_fp, bitmap_data_start + bmh.offset, SEEK_SET);
1002                         zsize = cfile_read_int(d1_Piggy_fp);
1003                         cfseek(d1_Piggy_fp, bitmap_data_start + bmh.offset, SEEK_SET);
1004                         cfread(next_bitmap, 1, zsize, d1_Piggy_fp);
1005
1006                         switch(cfilelength(d1_Piggy_fp)) {
1007                         case D1_MAC_PIGSIZE:
1008                         case D1_MAC_SHARE_PIGSIZE:
1009                                 rle_swap_0_255(&temp_bitmap);
1010                         }
1011                         rle_remap(&temp_bitmap, colormap);
1012
1013                         GameBitmaps[d2_index] = temp_bitmap;
1014
1015                         memcpy(&zsize, temp_bitmap.bm_data, 4);
1016                         next_bitmap += zsize;
1017                 }
1018         }
1019
1020         cfclose(d1_Piggy_fp);
1021
1022         last_palette_loaded_pig[0]= 0;  //force pig re-load
1023
1024         texmerge_flush();               //for re-merging with new textures
1025
1026         atexit(free_bitmap_replacements);
1027 }
1028
1029
1030 void load_robot_replacements(char *level_name);
1031 int read_hamfile();
1032 extern int Robot_replacements_loaded;
1033
1034 //load a level off disk. level numbers start at 1.  Secret levels are -1,-2,-3
1035 void LoadLevel(int level_num,int page_in_textures)
1036 {
1037         char *level_name;
1038         player save_player;
1039         int load_ret;
1040
1041         save_player = Players[Player_num];      
1042
1043         Assert(level_num <= Last_level  && level_num >= Last_secret_level  && level_num != 0);
1044
1045         if (level_num<0)                //secret level
1046                 level_name = Secret_level_names[-level_num-1];
1047         else                                    //normal level
1048                 level_name = Level_names[level_num-1];
1049
1050         undo_bm_read_all_d1();
1051         d1_pig_loaded = cfexist("descent.pig");
1052
1053         #ifdef WINDOWS
1054                 dd_gr_set_current_canvas(NULL);
1055                 dd_gr_clear_canvas(BM_XRGB(0,0,0));
1056         #else
1057                 gr_set_current_canvas(NULL);
1058                 gr_clear_canvas(BM_XRGB(0, 0, 0));              //so palette switching is less obvious
1059         #endif
1060
1061         Last_msg_ycrd = -1;             //so we don't restore backgound under msg
1062
1063 //      WIN(LoadCursorWin(MOUSE_WAIT_CURSOR));
1064 //      WIN(ShowCursorW());
1065
1066 #if 1 //defined(POLY_ACC) || defined(OGL)
1067     gr_palette_load(gr_palette);
1068     show_boxed_message(TXT_LOADING);
1069 #else
1070         show_boxed_message(TXT_LOADING);
1071         gr_palette_load(gr_palette);
1072 #endif
1073
1074         load_ret = load_level(level_name);              //actually load the data from disk!
1075
1076         if (load_ret)
1077                 Error("Couldn't load level file <%s>, error = %d",level_name,load_ret);
1078
1079         Current_level_num=level_num;
1080
1081 //      load_palette_pig(Current_level_palette);                //load just the pig
1082
1083         load_palette(Current_level_palette,1,1);                //don't change screen
1084
1085         load_endlevel_data(level_num);
1086
1087         if ( page_in_textures )
1088                 piggy_load_level_data();
1089
1090         if (Mission_list[Current_mission_num].descent_version == 1)
1091                 load_d1_bitmap_replacements();
1092         else
1093                 load_bitmap_replacements(level_name);
1094
1095         if (Robot_replacements_loaded) {
1096                 read_hamfile();         //load original data
1097                 Robot_replacements_loaded = 0;
1098         }
1099         load_robot_replacements(level_name);
1100
1101 #ifdef NETWORK
1102         my_segments_checksum = netmisc_calc_checksum(Segments, sizeof(segment)*(Highest_segment_index+1));
1103
1104         reset_network_objects();
1105 #endif
1106
1107         Players[Player_num] = save_player;
1108
1109         set_sound_sources();
1110
1111         songs_play_level_song( Current_level_num );
1112
1113         clear_boxed_message();          //remove message before new palette loaded
1114
1115         gr_palette_load(gr_palette);            //actually load the palette
1116
1117 //      WIN(HideCursorW());
1118 }
1119
1120 //sets up Player_num & ConsoleObject  
1121 void InitPlayerObject()
1122 {
1123         Assert(Player_num>=0 && Player_num<MAX_PLAYERS);
1124
1125         if (Player_num != 0 )   {
1126                 Players[0] = Players[Player_num];
1127                 Player_num = 0;
1128         }
1129
1130         Players[Player_num].objnum = 0;
1131
1132         ConsoleObject = &Objects[Players[Player_num].objnum];
1133
1134         ConsoleObject->type                             = OBJ_PLAYER;
1135         ConsoleObject->id                                       = Player_num;
1136         ConsoleObject->control_type     = CT_FLYING;
1137         ConsoleObject->movement_type    = MT_PHYSICS;
1138 }
1139
1140 extern void game_disable_cheats();
1141 extern void turn_cheats_off();
1142 extern void init_seismic_disturbances(void);
1143
1144 //starts a new game on the given level
1145 void StartNewGame(int start_level)
1146 {
1147         Game_mode = GM_NORMAL;
1148         Function_mode = FMODE_GAME;
1149         
1150         Next_level_num = 0;
1151
1152         InitPlayerObject();                             //make sure player's object set up
1153
1154         init_player_stats_game();               //clear all stats
1155
1156         N_players = 1;
1157 #ifdef NETWORK
1158         Network_new_game = 0;
1159 #endif
1160
1161         if (start_level < 0)
1162                 StartNewLevelSecret(start_level, 0);
1163         else
1164                 StartNewLevel(start_level, 0);
1165
1166         Players[Player_num].starting_level = start_level;               // Mark where they started
1167
1168         game_disable_cheats();
1169
1170         init_seismic_disturbances();
1171 }
1172
1173 //@@//starts a resumed game loaded from disk
1174 //@@void ResumeSavedGame(int start_level)
1175 //@@{
1176 //@@    Game_mode = GM_NORMAL;
1177 //@@    Function_mode = FMODE_GAME;
1178 //@@
1179 //@@    N_players = 1;
1180 //@@    Network_new_game = 0;
1181 //@@
1182 //@@    InitPlayerObject();                             //make sure player's object set up
1183 //@@
1184 //@@    StartNewLevel(start_level, 0);
1185 //@@
1186 //@@    game_disable_cheats();
1187 //@@}
1188
1189 #ifndef _NETWORK_H
1190 extern int network_endlevel_poll2( int nitems, newmenu_item * menus, int * key, int citem ); // network.c
1191 #endif
1192
1193 extern int N_secret_levels;
1194
1195 #define STARS_BACKGROUND ((MenuHires && cfexist("starsb.pcx"))?"starsb.pcx":"stars.pcx")
1196
1197 //      -----------------------------------------------------------------------------
1198 //      Does the bonus scoring.
1199 //      Call with dead_flag = 1 if player died, but deserves some portion of bonus (only skill points), anyway.
1200 void DoEndLevelScoreGlitz(int network)
1201 {
1202         int level_points, skill_points, energy_points, shield_points, hostage_points;
1203         int     all_hostage_points;
1204         int     endgame_points;
1205         char    all_hostage_text[64];
1206         char    endgame_text[64];
1207         #define N_GLITZITEMS 11
1208         char                            m_str[N_GLITZITEMS][30];
1209         newmenu_item    m[N_GLITZITEMS+1];
1210         int                             i,c;
1211         char                            title[128];
1212         int                             is_last_level;
1213         int                             mine_level;
1214
1215         set_screen_mode(SCREEN_MENU);           //go into menu mode
1216
1217    #ifdef TACTILE
1218                 if (TactileStick)
1219                   ClearForces();
1220         #endif
1221
1222         mprintf((0,"DoEndLevelScoreGlitz\n"));
1223
1224         //      Compute level player is on, deal with secret levels (negative numbers)
1225         mine_level = Players[Player_num].level;
1226         if (mine_level < 0)
1227                 mine_level *= -(Last_level/N_secret_levels);
1228
1229         level_points = Players[Player_num].score-Players[Player_num].last_score;
1230
1231         if (!Cheats_enabled) {
1232                 if (Difficulty_level > 1) {
1233                         skill_points = level_points*(Difficulty_level)/4;
1234                         skill_points -= skill_points % 100;
1235                 } else
1236                         skill_points = 0;
1237
1238                 shield_points = f2i(Players[Player_num].shields) * 5 * mine_level;
1239                 energy_points = f2i(Players[Player_num].energy) * 2 * mine_level;
1240                 hostage_points = Players[Player_num].hostages_on_board * 500 * (Difficulty_level+1);
1241
1242                 shield_points -= shield_points % 50;
1243                 energy_points -= energy_points % 50;
1244         } else {
1245                 skill_points = 0;
1246                 shield_points = 0;
1247                 energy_points = 0;
1248                 hostage_points = 0;
1249         }
1250
1251         all_hostage_text[0] = 0;
1252         endgame_text[0] = 0;
1253
1254         if (!Cheats_enabled && (Players[Player_num].hostages_on_board == Players[Player_num].hostages_level)) {
1255                 all_hostage_points = Players[Player_num].hostages_on_board * 1000 * (Difficulty_level+1);
1256                 sprintf(all_hostage_text, "%s%i\n", TXT_FULL_RESCUE_BONUS, all_hostage_points);
1257         } else
1258                 all_hostage_points = 0;
1259
1260         if (!Cheats_enabled && !(Game_mode & GM_MULTI) && (Players[Player_num].lives) && (Current_level_num == Last_level)) {           //player has finished the game!
1261                 endgame_points = Players[Player_num].lives * 10000;
1262                 sprintf(endgame_text, "%s%i\n", TXT_SHIP_BONUS, endgame_points);
1263                 is_last_level=1;
1264         } else
1265                 endgame_points = is_last_level = 0;
1266
1267         mprintf((0,"adding bonus points\n"));
1268         add_bonus_points_to_score(skill_points + energy_points + shield_points + hostage_points + all_hostage_points + endgame_points);
1269
1270         c = 0;
1271         sprintf(m_str[c++], "%s%i", TXT_SHIELD_BONUS, shield_points);           // Return at start to lower menu...
1272         sprintf(m_str[c++], "%s%i", TXT_ENERGY_BONUS, energy_points);
1273         sprintf(m_str[c++], "%s%i", TXT_HOSTAGE_BONUS, hostage_points);
1274         sprintf(m_str[c++], "%s%i", TXT_SKILL_BONUS, skill_points);
1275
1276         sprintf(m_str[c++], "%s", all_hostage_text);
1277         if (!(Game_mode & GM_MULTI) && (Players[Player_num].lives) && (Current_level_num == Last_level))
1278                 sprintf(m_str[c++], "%s", endgame_text);
1279
1280         sprintf(m_str[c++], "%s%i\n", TXT_TOTAL_BONUS, shield_points+energy_points+hostage_points+skill_points+all_hostage_points+endgame_points);
1281         sprintf(m_str[c++], "%s%i", TXT_TOTAL_SCORE, Players[Player_num].score);
1282
1283         #ifdef WINDOWS
1284         sprintf(m_str[c++], "");
1285         sprintf(m_str[c++], "         Done");
1286         #endif
1287
1288         for (i=0; i<c; i++) {
1289                 m[i].type = NM_TYPE_TEXT;
1290                 m[i].text = m_str[i];
1291         }
1292
1293         #ifdef WINDOWS
1294         m[c-1].type = NM_TYPE_MENU;
1295         #endif
1296
1297         // m[c].type = NM_TYPE_MENU;    m[c++].text = "Ok";
1298
1299         if (Current_level_num < 0)
1300                 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);
1301         else
1302                 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);
1303
1304         Assert(c <= N_GLITZITEMS);
1305
1306         gr_palette_fade_out(gr_palette, 32, 0);
1307
1308         mprintf((0,"doing menu\n"));
1309
1310    PA_DFX (pa_alpha_always());
1311
1312 #ifdef NETWORK
1313         if ( network && (Game_mode & GM_NETWORK) )
1314                 newmenu_do2(NULL, title, c, m, (void (*))network_endlevel_poll2, 0, STARS_BACKGROUND);
1315         else
1316 #endif
1317                 // NOTE LINK TO ABOVE!!!
1318                 newmenu_do2(NULL, title, c, m, NULL, 0, STARS_BACKGROUND);
1319
1320         mprintf((0,"done DoEndLevelScoreGlitz\n"));
1321 }
1322
1323 //give the player the opportunity to save his game
1324 void DoEndlevelMenu()
1325 {
1326 //No between level saves......!!!       state_save_all(1);
1327 }
1328
1329 //      -----------------------------------------------------------------------------------------------------
1330 //called when the player is starting a level (new game or new ship)
1331 void StartSecretLevel()
1332 {
1333         Assert(!Player_is_dead);
1334
1335         InitPlayerPosition(0);
1336
1337         verify_console_object();
1338
1339         ConsoleObject->control_type     = CT_FLYING;
1340         ConsoleObject->movement_type    = MT_PHYSICS;
1341
1342         // -- WHY? -- disable_matcens();
1343         clear_transient_objects(0);             //0 means leave proximity bombs
1344
1345         // create_player_appearance_effect(ConsoleObject);
1346         Do_appearance_effect = 1;
1347
1348         ai_reset_all_paths();
1349         // -- NO? -- reset_time();
1350
1351         reset_rear_view();
1352         Auto_fire_fusion_cannon_time = 0;
1353         Fusion_charge = 0;
1354
1355         Robot_firing_enabled = 1;
1356 }
1357
1358 extern void set_pos_from_return_segment(void);
1359
1360 //      Returns true if secret level has been destroyed.
1361 int p_secret_level_destroyed(void)
1362 {
1363         if (First_secret_visit) {
1364                 return 0;               //      Never been there, can't have been destroyed.
1365         } else {
1366                 FILE    *fp;
1367                 if ((fp = fopen(SECRETC_FILENAME, "rb")) != NULL) {
1368                         fclose(fp);
1369                         return 0;
1370                 } else {
1371                         return 1;
1372                 }
1373         }
1374 }
1375
1376 //      -----------------------------------------------------------------------------------------------------
1377 void do_secret_message(char *msg)
1378 {
1379         int     old_fmode;
1380
1381         load_stars();
1382
1383 #if defined(POLY_ACC)
1384         pa_save_clut();
1385         pa_update_clut(gr_palette, 0, 256, 0);
1386 #endif
1387
1388         old_fmode = Function_mode;
1389         Function_mode = FMODE_MENU;
1390         nm_messagebox(NULL, 1, TXT_OK, msg);
1391         Function_mode = old_fmode;
1392
1393 #if defined(POLY_ACC)
1394         pa_restore_clut();
1395 #endif
1396         
1397         WIN(DEFINE_SCREEN(NULL));
1398 }
1399
1400 //      -----------------------------------------------------------------------------------------------------
1401 // called when the player is starting a new level for normal game mode and restore state
1402 //      Need to deal with whether this is the first time coming to this level or not.  If not the
1403 //      first time, instead of initializing various things, need to do a game restore for all the
1404 //      robots, powerups, walls, doors, etc.
1405 void StartNewLevelSecret(int level_num, int page_in_textures)
1406 {
1407         newmenu_item    m[1];
1408         //int i;
1409
1410         ThisLevelTime=0;
1411          
1412         m[0].type = NM_TYPE_TEXT;
1413         m[0].text = " ";
1414
1415         last_drawn_cockpit[0] = -1;
1416         last_drawn_cockpit[1] = -1;
1417
1418         if (Newdemo_state == ND_STATE_PAUSED)
1419                 Newdemo_state = ND_STATE_RECORDING;
1420
1421         if (Newdemo_state == ND_STATE_RECORDING) {
1422                 newdemo_set_new_level(level_num);
1423                 newdemo_record_start_frame(FrameCount, FrameTime );
1424         } else if (Newdemo_state != ND_STATE_PLAYBACK) {
1425
1426                 gr_palette_fade_out(gr_palette, 32, 0);
1427
1428                 set_screen_mode(SCREEN_MENU);           //go into menu mode
1429
1430                 if (First_secret_visit) {
1431                         do_secret_message(TXT_SECRET_EXIT);
1432                 } else {
1433                         FILE    *fp;
1434                         if ((fp = fopen(SECRETC_FILENAME, "rb")) != NULL) {
1435                                 fclose(fp);
1436                                 do_secret_message(TXT_SECRET_EXIT);
1437                         } else {
1438                                 char    text_str[128];
1439
1440                                 sprintf(text_str, "Secret level already destroyed.\nAdvancing to level %i.", Current_level_num+1);
1441                                 do_secret_message(text_str);
1442                         }
1443                 }
1444         }
1445
1446         LoadLevel(level_num,page_in_textures);
1447
1448         Assert(Current_level_num == level_num); //make sure level set right
1449
1450         Assert(Function_mode == FMODE_GAME);
1451
1452         gameseq_init_network_players(); // Initialize the Players array for 
1453                                                                                           // this level
1454
1455         HUD_clear_messages();
1456
1457         automap_clear_visited();
1458
1459         // --   init_player_stats_level();
1460
1461         Viewer = &Objects[Players[Player_num].objnum];
1462
1463         gameseq_remove_unused_players();
1464
1465         Game_suspended = 0;
1466
1467         Control_center_destroyed = 0;
1468
1469         init_cockpit();
1470         reset_palette_add();
1471
1472         if (First_secret_visit || (Newdemo_state == ND_STATE_PLAYBACK)) {
1473                 init_robots_for_level();
1474                 init_ai_objects();
1475                 init_smega_detonates();
1476                 init_morphs();
1477                 init_all_matcens();
1478                 reset_special_effects();
1479                 StartSecretLevel();
1480         } else {
1481                 FILE    *fp;
1482                 if ((fp = fopen(SECRETC_FILENAME, "rb")) != NULL) {
1483                         int     pw_save, sw_save;
1484
1485                         fclose(fp);
1486
1487                         pw_save = Primary_weapon;
1488                         sw_save = Secondary_weapon;
1489                         state_restore_all(1, 1, SECRETC_FILENAME);
1490                         Primary_weapon = pw_save;
1491                         Secondary_weapon = sw_save;
1492                         reset_special_effects();
1493                         StartSecretLevel();
1494                         // -- No: This is only for returning to base level: set_pos_from_return_segment();
1495                 } else {
1496                         char    text_str[128];
1497
1498                         sprintf(text_str, "Secret level already destroyed.\nAdvancing to level %i.", Current_level_num+1);
1499                         do_secret_message(text_str);
1500                         return;
1501
1502                         // -- //        If file doesn't exist, it's because reactor was destroyed.
1503                         // -- mprintf((0, "secret.sgc doesn't exist.  Advancing to next level.\n"));
1504                         // -- // -- StartNewLevel(Secret_level_table[-Current_level_num-1]+1, 0);
1505                         // -- StartNewLevel(Secret_level_table[-Current_level_num-1]+1, 0);
1506                         // -- return;
1507                 }
1508         }
1509
1510         if (First_secret_visit) {
1511                 copy_defaults_to_robot_all();
1512         }
1513
1514         turn_cheats_off();
1515
1516         init_controlcen_for_level();
1517
1518         //      Say player can use FLASH cheat to mark path to exit.
1519         Last_level_path_created = -1;
1520
1521         First_secret_visit = 0;
1522 }
1523
1524 int     Entered_from_level;
1525
1526 // ---------------------------------------------------------------------------------------------------------------
1527 //      Called from switch.c when player is on a secret level and hits exit to return to base level.
1528 void ExitSecretLevel(void)
1529 {
1530         FILE    *fp;
1531
1532         if (Newdemo_state == ND_STATE_PLAYBACK)
1533                 return;
1534
1535         if (!Control_center_destroyed) {
1536                 state_save_all(0, 2, SECRETC_FILENAME);
1537         }
1538
1539         if ((fp = fopen(SECRETB_FILENAME, "rb")) != NULL) {
1540                 int     pw_save, sw_save;
1541
1542                 returning_to_level_message();
1543                 fclose(fp);
1544                 pw_save = Primary_weapon;
1545                 sw_save = Secondary_weapon;
1546                 state_restore_all(1, 1, SECRETB_FILENAME);
1547                 Primary_weapon = pw_save;
1548                 Secondary_weapon = sw_save;
1549         } else {
1550                 // File doesn't exist, so can't return to base level.  Advance to next one.
1551                 if (Entered_from_level == Last_level)
1552                         DoEndGame();
1553                 else {
1554                         advancing_to_level_message();
1555                         StartNewLevel(Entered_from_level+1, 0);
1556                 }
1557         }
1558 }
1559
1560 // ---------------------------------------------------------------------------------------------------------------
1561 //      Set invulnerable_time and cloak_time in player struct to preserve amount of time left to
1562 //      be invulnerable or cloaked.
1563 void do_cloak_invul_secret_stuff(fix old_gametime)
1564 {
1565         if (Players[Player_num].flags & PLAYER_FLAGS_INVULNERABLE) {
1566                 fix     time_used;
1567
1568                 time_used = old_gametime - Players[Player_num].invulnerable_time;
1569                 Players[Player_num].invulnerable_time = GameTime - time_used;
1570         }
1571
1572         if (Players[Player_num].flags & PLAYER_FLAGS_CLOAKED) {
1573                 fix     time_used;
1574
1575                 time_used = old_gametime - Players[Player_num].cloak_time;
1576                 Players[Player_num].cloak_time = GameTime - time_used;
1577         }
1578 }
1579
1580 // ---------------------------------------------------------------------------------------------------------------
1581 //      Called from switch.c when player passes through secret exit.  That means he was on a non-secret level and he
1582 //      is passing to the secret level.
1583 //      Do a savegame.
1584 void EnterSecretLevel(void)
1585 {
1586         fix     old_gametime;
1587         int     i;
1588
1589         Assert(! (Game_mode & GM_MULTI) );
1590
1591         Entered_from_level = Current_level_num;
1592
1593         if (Control_center_destroyed)
1594                 DoEndLevelScoreGlitz(0);
1595
1596         if (Newdemo_state != ND_STATE_PLAYBACK)
1597                 state_save_all(0, 1, NULL);     //      Not between levels (ie, save all), IS a secret level, NO filename override
1598
1599         //      Find secret level number to go to, stuff in Next_level_num.
1600         for (i=0; i<-Last_secret_level; i++)
1601                 if (Secret_level_table[i]==Current_level_num) {
1602                         Next_level_num = -(i+1);
1603                         break;
1604                 } else if (Secret_level_table[i] > Current_level_num) { //      Allows multiple exits in same group.
1605                         Next_level_num = -i;
1606                         break;
1607                 }
1608
1609         if (! (i<-Last_secret_level))           //didn't find level, so must be last
1610                 Next_level_num = Last_secret_level;
1611
1612         old_gametime = GameTime;
1613
1614         StartNewLevelSecret(Next_level_num, 1);
1615         
1616         // do_cloak_invul_stuff();
1617 }
1618
1619 //called when the player has finished a level
1620 void PlayerFinishedLevel(int secret_flag)
1621 {
1622         Assert(!secret_flag);
1623
1624         //credit the player for hostages
1625         Players[Player_num].hostages_rescued_total += Players[Player_num].hostages_on_board;
1626
1627         if (Game_mode & GM_NETWORK)
1628                 Players[Player_num].connected = 2; // Finished but did not die
1629
1630         last_drawn_cockpit[0] = -1;
1631         last_drawn_cockpit[1] = -1;
1632
1633         AdvanceLevel(secret_flag);                              //now go on to the next one (if one)
1634 }
1635
1636 #if defined(D2_OEM) || defined(COMPILATION)
1637 #define MOVIE_REQUIRED 0
1638 #else
1639 #define MOVIE_REQUIRED 1
1640 #endif
1641
1642 #ifdef D2_OEM
1643 #define ENDMOVIE "endo"
1644 #else
1645 #define ENDMOVIE "end"
1646 #endif
1647
1648 void show_order_form();
1649 extern void com_hangup(void);
1650
1651 //called when the player has finished the last level
1652 void DoEndGame(void)
1653 {
1654         mprintf((0,"DoEndGame\n"));
1655
1656         Function_mode = FMODE_MENU;
1657         if ((Newdemo_state == ND_STATE_RECORDING) || (Newdemo_state == ND_STATE_PAUSED))
1658                 newdemo_stop_recording();
1659
1660         set_screen_mode( SCREEN_MENU );
1661
1662         WINDOS(
1663                 dd_gr_set_current_canvas(NULL),
1664                 gr_set_current_canvas(NULL)
1665         );
1666
1667         key_flush();
1668
1669         if (Current_mission_num == Builtin_mission_num && !(Game_mode & GM_MULTI)) { //only built-in mission, & not multi
1670 #ifndef SHAREWARE
1671                 int played=MOVIE_NOT_PLAYED;    //default is not played
1672 #endif
1673
1674                 init_subtitles(ENDMOVIE ".tex");        //ingore errors
1675                 played = PlayMovie(ENDMOVIE,MOVIE_REQUIRED);
1676                 close_subtitles();
1677                 if (!played) {
1678                         if (cfexist("end2oem.txb") || cfexist("end2oem.tex")) { // #ifdef D2_OEM
1679                                 songs_play_song( SONG_TITLE, 0 );
1680                                 do_briefing_screens("end2oem.tex",1);
1681                         } else {
1682                                 songs_play_song( SONG_ENDGAME, 0 );
1683                                 mprintf((0,"doing briefing\n"));
1684                                 do_briefing_screens("ending2.tex",1);
1685                                 mprintf((0,"briefing done\n"));
1686                         }
1687                 }
1688    } else if (!(Game_mode & GM_MULTI)) {    //not multi
1689                 char tname[FILENAME_LEN];
1690                 sprintf(tname,"%s.tex",Current_mission_filename);
1691                 do_briefing_screens (tname,Last_level+1);   //level past last is endgame breifing
1692
1693                 //try doing special credits
1694                 sprintf(tname,"%s.ctb",Current_mission_filename);
1695                 credits_show(tname);
1696         }
1697
1698         key_flush();
1699
1700 #ifdef SHAREWARE
1701                 show_order_form();
1702 #endif
1703
1704 #ifdef NETWORK
1705         if (Game_mode & GM_MULTI)
1706                 multi_endlevel_score();
1707         else
1708 #endif
1709                 // NOTE LINK TO ABOVE
1710                 DoEndLevelScoreGlitz(0);
1711
1712         if (Current_mission_num == Builtin_mission_num && !((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP))) {
1713                 WINDOS(
1714                         dd_gr_set_current_canvas(NULL),
1715                         gr_set_current_canvas( NULL )
1716                 );
1717                 WINDOS(
1718                         dd_gr_clear_canvas(BM_XRGB(0,0,0)),
1719                         gr_clear_canvas(BM_XRGB(0,0,0))
1720                 );
1721                 gr_palette_clear();
1722                 load_palette(DEFAULT_PALETTE,0,1);
1723                 scores_maybe_add_player(0);
1724         }
1725
1726         Function_mode = FMODE_MENU;
1727
1728         if ((Game_mode & GM_SERIAL) || (Game_mode & GM_MODEM))
1729                 Game_mode |= GM_GAME_OVER;              //preserve modem setting so go back into modem menu
1730         else
1731                 Game_mode = GM_GAME_OVER;
1732
1733
1734         longjmp( LeaveGame, 0 );                // Exit out of game loop
1735 }
1736
1737 //from which level each do you get to each secret level 
1738 int Secret_level_table[MAX_SECRET_LEVELS_PER_MISSION];
1739
1740 //called to go to the next level (if there is one)
1741 //if secret_flag is true, advance to secret level, else next normal one
1742 //      Return true if game over.
1743 void AdvanceLevel(int secret_flag)
1744 {
1745 #ifdef NETWORK
1746         int result;
1747 #endif
1748
1749         mprintf((0,"AdvanceLevel\n"));
1750
1751         Assert(!secret_flag);
1752
1753         if (Current_level_num != Last_level) {
1754 #ifdef NETWORK
1755                 if (Game_mode & GM_MULTI)
1756                         multi_endlevel_score();         
1757                 else 
1758 #endif
1759                         // NOTE LINK TO ABOVE!!!
1760                         DoEndLevelScoreGlitz(0);                //give bonuses
1761         }
1762
1763         Control_center_destroyed = 0;
1764
1765         #ifdef EDITOR
1766         if (Current_level_num == 0)
1767                 return;         //not a real level
1768         #endif
1769
1770 #ifdef NETWORK
1771         if (Game_mode & GM_MULTI)       {
1772                 result = multi_endlevel(&secret_flag); // Wait for other players to reach this point
1773                 if (result) // failed to sync
1774                 {
1775                         if (Current_level_num == Last_level)            //player has finished the game!
1776                                 longjmp( LeaveGame, 0 );                // Exit out of game loop
1777                         else
1778                                 return;
1779                 }
1780         }
1781 #endif
1782
1783         if (Current_level_num == Last_level) {          //player has finished the game!
1784                 
1785                 mprintf((0,"Finished last level!\n"));
1786
1787                 DoEndGame();
1788
1789         } else {
1790
1791                 Next_level_num = Current_level_num+1;           //assume go to next normal level
1792
1793                 if (!(Game_mode & GM_MULTI))
1794                         DoEndlevelMenu(); // Let use save their game
1795
1796                 StartNewLevel(Next_level_num, 0);
1797
1798         }
1799 }
1800
1801 #ifdef MACINTOSH                // horrible hack of a routine to load just the palette from the stars.pcx file
1802
1803 extern char last_palette_loaded[];
1804
1805 void load_stars_palette()
1806 {
1807         int pcx_error;
1808         ubyte pal[256*3];
1809
1810         pcx_error = pcx_read_bitmap_palette(STARS_BACKGROUND,pal);
1811         Assert(pcx_error == PCX_ERROR_NONE);
1812
1813         //@@gr_remap_bitmap_good( bmp, pal, -1, -1 );
1814
1815
1816         {       //remap stuff. this code is kindof a hack
1817
1818                 //now, before we bring up the menu, we need to 
1819                 //do some stuff to make sure the palette is ok.  First, we need to
1820                 //get our current palette into the 2d's array, so the remapping will
1821                 //work.  Second, we need to remap the fonts.  Third, we need to fill 
1822                 //in part of the fade tables so the darkening of the menu edges works
1823
1824                 gr_copy_palette(gr_palette, pal, sizeof(gr_palette));
1825                 remap_fonts_and_menus(1);
1826
1827         }
1828
1829         strcpy(last_palette_loaded,"");         //force palette load next time
1830 }
1831 #endif
1832
1833 void nm_draw_background1(char * filename);
1834
1835 void load_stars()
1836 {
1837 //@@    int pcx_error;
1838 //@@    ubyte pal[256*3];
1839 //@@
1840 //@@    pcx_error = pcx_read_bitmap("STARS.PCX",&grd_curcanv->cv_bitmap,grd_curcanv->cv_bitmap.bm_type,pal);
1841 //@@    Assert(pcx_error == PCX_ERROR_NONE);
1842 //@@
1843 //@@    gr_remap_bitmap_good( &grd_curcanv->cv_bitmap, pal, -1, -1 );
1844
1845         WIN(DEFINE_SCREEN(STARS_BACKGROUND));
1846
1847         nm_draw_background1(STARS_BACKGROUND);
1848
1849 }
1850
1851
1852 void
1853 died_in_mine_message(void)
1854 {
1855         // Tell the player he died in the mine, explain why
1856         int old_fmode;
1857
1858         if (Game_mode & GM_MULTI)
1859                 return;
1860
1861         gr_palette_fade_out(gr_palette, 32, 0);
1862
1863         set_screen_mode(SCREEN_MENU);           //go into menu mode
1864
1865         WINDOS(
1866                 dd_gr_set_current_canvas(NULL),
1867                 gr_set_current_canvas(NULL)
1868         );
1869
1870         load_stars();
1871
1872 #if defined(POLY_ACC)
1873         pa_save_clut();
1874         pa_update_clut(gr_palette, 0, 256, 0);
1875 #endif
1876
1877         old_fmode = Function_mode;
1878         Function_mode = FMODE_MENU;
1879         nm_messagebox(NULL, 1, TXT_OK, TXT_DIED_IN_MINE);
1880         Function_mode = old_fmode;
1881
1882 #if defined(POLY_ACC)
1883         pa_restore_clut();
1884 #endif
1885
1886         WIN(DEFINE_SCREEN(NULL));
1887 }
1888
1889 //      Called when player dies on secret level.
1890 void returning_to_level_message(void)
1891 {
1892         char    msg[128];
1893
1894         int old_fmode;
1895
1896         if (Game_mode & GM_MULTI)
1897                 return;
1898
1899         gr_palette_fade_out(gr_palette, 32, 0);
1900
1901         set_screen_mode(SCREEN_MENU);           //go into menu mode
1902
1903         gr_set_current_canvas(NULL);
1904
1905         load_stars();
1906
1907 #if defined(POLY_ACC)
1908         pa_save_clut();
1909         pa_update_clut(gr_palette, 0, 256, 0);
1910 #endif
1911
1912         old_fmode = Function_mode;
1913         Function_mode = FMODE_MENU;
1914         sprintf(msg, "Returning to level %i", Entered_from_level);
1915         nm_messagebox(NULL, 1, TXT_OK, msg);
1916         Function_mode = old_fmode;
1917
1918 #if defined(POLY_ACC)
1919         pa_restore_clut();
1920 #endif
1921
1922         WIN(DEFINE_SCREEN(NULL));
1923 }
1924
1925 //      Called when player dies on secret level.
1926 void advancing_to_level_message(void)
1927 {
1928         char    msg[128];
1929
1930         int old_fmode;
1931
1932         //      Only supposed to come here from a secret level.
1933         Assert(Current_level_num < 0);
1934
1935         if (Game_mode & GM_MULTI)
1936                 return;
1937
1938         gr_palette_fade_out(gr_palette, 32, 0);
1939
1940         set_screen_mode(SCREEN_MENU);           //go into menu mode
1941
1942         gr_set_current_canvas(NULL);
1943         
1944         load_stars();
1945
1946 #if defined(POLY_ACC)
1947         pa_save_clut();
1948         pa_update_clut(gr_palette, 0, 256, 0);
1949 #endif
1950
1951         old_fmode = Function_mode;
1952         Function_mode = FMODE_MENU;
1953         sprintf(msg, "Base level destroyed.\nAdvancing to level %i", Entered_from_level+1);
1954         nm_messagebox(NULL, 1, TXT_OK, msg);
1955         Function_mode = old_fmode;
1956
1957 #if defined(POLY_ACC)
1958         pa_restore_clut();
1959 #endif
1960
1961         WIN(DEFINE_SCREEN(NULL));
1962 }
1963
1964 void digi_stop_digi_sounds();
1965
1966 void DoPlayerDead()
1967 {
1968         reset_palette_add();
1969
1970         gr_palette_load (gr_palette);
1971
1972 //      digi_pause_digi_sounds();               //kill any continuing sounds (eg. forcefield hum)
1973         digi_stop_digi_sounds();                //kill any continuing sounds (eg. forcefield hum)
1974
1975         dead_player_end();              //terminate death sequence (if playing)
1976
1977         #ifdef EDITOR
1978         if (Game_mode == GM_EDITOR) {                   //test mine, not real level
1979                 object * playerobj = &Objects[Players[Player_num].objnum];
1980                 //nm_messagebox( "You're Dead!", 1, "Continue", "Not a real game, though." );
1981                 load_level("gamesave.lvl");
1982                 init_player_stats_new_ship();
1983                 playerobj->flags &= ~OF_SHOULD_BE_DEAD;
1984                 StartLevel(0);
1985                 return;
1986         }
1987         #endif
1988
1989 #ifdef NETWORK
1990         if ( Game_mode&GM_MULTI )
1991         {
1992                 multi_do_death(Players[Player_num].objnum);
1993         }
1994         else 
1995 #endif
1996         {                               //Note link to above else!
1997                 Players[Player_num].lives--;
1998                 if (Players[Player_num].lives == 0)
1999                 {       
2000                         DoGameOver();
2001                         return;
2002                 }
2003         }
2004                                 
2005         if ( Control_center_destroyed ) {
2006
2007                 //clear out stuff so no bonus
2008                 Players[Player_num].hostages_on_board = 0;
2009                 Players[Player_num].energy = 0;
2010                 Players[Player_num].shields = 0;
2011                 Players[Player_num].connected = 3;
2012
2013                 died_in_mine_message(); // Give them some indication of what happened
2014
2015                 if (Current_level_num < 0) {
2016                         FILE    *fp;
2017
2018                         if ((fp = fopen(SECRETB_FILENAME, "rb")) != NULL) {
2019                                 fclose(fp);
2020                                 returning_to_level_message();
2021                                 state_restore_all(1, 2, SECRETB_FILENAME);                      //      2 means you died
2022                                 set_pos_from_return_segment();
2023                                 Players[Player_num].lives--;                                            //      re-lose the life, Players[Player_num].lives got written over in restore.
2024                         } else {
2025                                 advancing_to_level_message();
2026                                 StartNewLevel(Entered_from_level+1, 0);
2027                                 init_player_stats_new_ship();   //      New, MK, 05/29/96!, fix bug with dying in secret level, advance to next level, keep powerups!
2028                         }
2029                 } else {
2030
2031                         AdvanceLevel(0);                        //if finished, go on to next level
2032
2033                         init_player_stats_new_ship();
2034                         last_drawn_cockpit[0] = -1;
2035                         last_drawn_cockpit[1] = -1;
2036                 }
2037
2038         } else if (Current_level_num < 0) {
2039                 FILE    *fp;
2040                 if ((fp = fopen(SECRETB_FILENAME, "rb")) != NULL) {
2041                         fclose(fp);
2042                         returning_to_level_message();
2043                         if (!Control_center_destroyed)
2044                                 state_save_all(0, 2, SECRETC_FILENAME);
2045                         state_restore_all(1, 2, SECRETB_FILENAME);
2046                         set_pos_from_return_segment();
2047                         Players[Player_num].lives--;                                            //      re-lose the life, Players[Player_num].lives got written over in restore.
2048                 } else {
2049                         died_in_mine_message(); // Give them some indication of what happened
2050                         advancing_to_level_message();
2051                         StartNewLevel(Entered_from_level+1, 0);
2052                         init_player_stats_new_ship();
2053                 }
2054         } else {
2055                 init_player_stats_new_ship();
2056                 StartLevel(1);
2057         }
2058
2059         digi_sync_sounds();
2060 }
2061
2062 extern int BigWindowSwitch;
2063
2064 //called when the player is starting a new level for normal game mode and restore state
2065 //      secret_flag set if came from a secret level
2066 void StartNewLevelSub(int level_num, int page_in_textures, int secret_flag)
2067 {
2068         if (!(Game_mode & GM_MULTI)) {
2069                 last_drawn_cockpit[0] = -1;
2070                 last_drawn_cockpit[1] = -1;
2071         }
2072    BigWindowSwitch=0;
2073
2074
2075         if (Newdemo_state == ND_STATE_PAUSED)
2076                 Newdemo_state = ND_STATE_RECORDING;
2077
2078         if (Newdemo_state == ND_STATE_RECORDING) {
2079                 newdemo_set_new_level(level_num);
2080                 newdemo_record_start_frame(FrameCount, FrameTime );
2081         }
2082
2083         if (Game_mode & GM_MULTI)
2084                 Function_mode = FMODE_MENU; // Cheap fix to prevent problems with errror dialogs in loadlevel.
2085
2086         LoadLevel(level_num,page_in_textures);
2087
2088         Assert(Current_level_num == level_num); //make sure level set right
2089
2090         gameseq_init_network_players(); // Initialize the Players array for 
2091                                                                                           // this level
2092
2093         Viewer = &Objects[Players[Player_num].objnum];
2094
2095         Assert(N_players <= NumNetPlayerPositions);
2096                 //If this assert fails, there's not enough start positions
2097
2098 #ifdef NETWORK
2099         if (Game_mode & GM_NETWORK)
2100         {
2101                 if(network_level_sync()) // After calling this, Player_num is set
2102                         return;
2103         }
2104         if ((Game_mode & GM_SERIAL) || (Game_mode & GM_MODEM))
2105         {
2106                 if(com_level_sync())
2107                         return;
2108         }
2109 #endif
2110
2111         Assert(Function_mode == FMODE_GAME);
2112
2113         #ifndef NDEBUG
2114         //-- mprintf((0, "Player_num = %d, N_players = %d.\n", Player_num, N_players)); // DEBUG
2115         #endif
2116
2117         HUD_clear_messages();
2118
2119         automap_clear_visited();
2120
2121 #ifdef NETWORK
2122         if (Network_new_game == 1)
2123         {
2124                 Network_new_game = 0;
2125                 init_player_stats_new_ship();
2126         }
2127 #endif
2128         init_player_stats_level(secret_flag);
2129
2130 #ifdef NETWORK
2131         if ((Game_mode & GM_MULTI_COOP) && Network_rejoined)
2132         {
2133                 int i;
2134                 for (i = 0; i < N_players; i++)
2135                         Players[i].flags |= Netgame.player_flags[i];
2136         }
2137
2138         if (Game_mode & GM_MULTI)
2139         {
2140                 multi_prep_level(); // Removes robots from level if necessary
2141         }
2142 #endif
2143
2144         gameseq_remove_unused_players();
2145
2146         Game_suspended = 0;
2147
2148         Control_center_destroyed = 0;
2149
2150         set_screen_mode(SCREEN_GAME);
2151         init_cockpit();
2152         init_robots_for_level();
2153         init_ai_objects();
2154         init_smega_detonates();
2155         init_morphs();
2156         init_all_matcens();
2157         reset_palette_add();
2158         init_thief_for_level();
2159         init_stuck_objects();
2160         game_flush_inputs();            // clear out the keyboard
2161         if (!(Game_mode & GM_MULTI))
2162                 filter_objects_from_level();
2163
2164         turn_cheats_off();
2165
2166         if (!(Game_mode & GM_MULTI) && !Cheats_enabled)
2167                 set_highest_level(Current_level_num);
2168         else
2169                 read_player_file();             //get window sizes
2170
2171         reset_special_effects();
2172
2173 #ifdef OGL
2174         ogl_cache_level_textures();
2175 #endif
2176
2177
2178 #ifdef NETWORK
2179         if (Network_rejoined == 1)
2180         {
2181                 #ifndef NDEBUG
2182                 mprintf((0, "Restarting - joining in random location.\n"));
2183                 #endif
2184                 Network_rejoined = 0;
2185                 StartLevel(1);
2186         }
2187         else
2188 #endif
2189                 StartLevel(0);          // Note link to above if!
2190
2191         copy_defaults_to_robot_all();
2192         init_controlcen_for_level();
2193
2194         //      Say player can use FLASH cheat to mark path to exit.
2195         Last_level_path_created = -1;
2196 }
2197
2198 #ifdef NETWORK
2199 extern char PowerupsInMine[MAX_POWERUP_TYPES], MaxPowerupsAllowed[MAX_POWERUP_TYPES];
2200 #endif
2201 void bash_to_shield (int i,char *s)
2202 {
2203 #ifdef NETWORK
2204         int type=Objects[i].id;
2205 #endif
2206
2207         mprintf((0, "Bashing %s object #%i to shield.\n",s, i));
2208
2209 #ifdef NETWORK
2210         PowerupsInMine[type]=MaxPowerupsAllowed[type]=0;
2211 #endif
2212
2213         Objects[i].id = POW_SHIELD_BOOST;
2214         Objects[i].rtype.vclip_info.vclip_num = Powerup_info[Objects[i].id].vclip_num;
2215         Objects[i].rtype.vclip_info.frametime = Vclip[Objects[i].rtype.vclip_info.vclip_num].frame_time;
2216 }
2217
2218
2219 void filter_objects_from_level()
2220  {
2221   int i;
2222   
2223   mprintf ((0,"Highest object index=%d\n",Highest_object_index));
2224  
2225   for (i=0;i<=Highest_object_index;i++) 
2226         {
2227          if (Objects[i].type==OBJ_POWERUP)
2228      if (Objects[i].id==POW_FLAG_RED || Objects[i].id==POW_FLAG_BLUE)
2229            bash_to_shield (i,"Flag!!!!");
2230    } 
2231
2232  }
2233
2234 struct {
2235         int     level_num;
2236         char    movie_name[FILENAME_LEN];
2237 } intro_movie[] = {     { 1,"pla"},
2238                                                         { 5,"plb"},
2239                                                         { 9,"plc"},
2240                                                         {13,"pld"},
2241                                                         {17,"ple"},
2242                                                         {21,"plf"},
2243                                                         {24,"plg"}};
2244
2245 #define NUM_INTRO_MOVIES (sizeof(intro_movie) / sizeof(*intro_movie))
2246
2247 extern int MenuHiresAvailable;
2248 extern int robot_movies;        //0 means none, 1 means lowres, 2 means hires
2249 extern int intro_played;        //true if big intro movie played
2250
2251 void ShowLevelIntro(int level_num)
2252 {
2253         //if shareware, show a briefing?
2254
2255         if (!(Game_mode & GM_MULTI)) {
2256                 int i;
2257
2258                 ubyte save_pal[sizeof(gr_palette)];
2259
2260                 memcpy(save_pal,gr_palette,sizeof(gr_palette));
2261
2262                 if (Current_mission_num == Builtin_mission_num) {
2263                         int movie=0;
2264
2265                         if (cfexist("brief2.txb") || cfexist("brief2.tex")) { // SHAREWARE
2266                                 if (level_num==1)
2267                                         do_briefing_screens ("brief2.tex", 1);
2268                         } else if (cfexist("brief2o.txb") || cfexist("brief2o.tex")) { // OEM
2269                                 if (level_num == 1 && !intro_played)
2270                                         do_briefing_screens("brief2o.tex", 1);
2271                         } else { // full version
2272                                 for (i=0;i<NUM_INTRO_MOVIES;i++)
2273                                 {
2274                                         if (intro_movie[i].level_num == level_num)
2275                                         {
2276                                                 Screen_mode = -1;
2277                                                 PlayMovie(intro_movie[i].movie_name,MOVIE_REQUIRED);
2278                                                 movie=1;
2279                                                 break;
2280                                         }
2281                                 }
2282
2283 #ifdef WINDOWS
2284                                 if (!movie) {                                   //must go before briefing
2285                                         dd_gr_init_screen();
2286                                         Screen_mode = -1;
2287                                 }
2288 #endif
2289
2290                                 if (robot_movies)
2291                                 {
2292                                         int hires_save=MenuHiresAvailable;
2293
2294                                         if (robot_movies == 1)          //lowres only
2295                                         {
2296                                                 MenuHiresAvailable = 0;         //pretend we can't do highres
2297
2298                                                 if (hires_save != MenuHiresAvailable)
2299                                                         Screen_mode = -1;               //force reset
2300
2301                                         }
2302                                         do_briefing_screens ("robot.tex",level_num);
2303                                         MenuHiresAvailable = hires_save;
2304                                 }
2305
2306                         }
2307                 }
2308                 else {  //not the built-in mission.  check for add-on briefing
2309                         if (Mission_list[Current_mission_num].descent_version == 1)
2310                                 do_briefing_screens(Briefing_text_filename, level_num);
2311                         else {
2312                                 char tname[FILENAME_LEN];
2313                                 sprintf(tname, "%s.tex", Current_mission_filename);
2314                                 do_briefing_screens(tname, level_num);
2315                         }
2316                 }
2317
2318
2319                 memcpy(gr_palette,save_pal,sizeof(gr_palette));
2320         }
2321 }
2322
2323 //      ---------------------------------------------------------------------------
2324 //      If starting a level which appears in the Secret_level_table, then set First_secret_visit.
2325 //      Reason: On this level, if player goes to a secret level, he will be going to a different
2326 //      secret level than he's ever been to before.
2327 //      Sets the global First_secret_visit if necessary.  Otherwise leaves it unchanged.
2328 void maybe_set_first_secret_visit(int level_num)
2329 {
2330         int     i;
2331
2332         for (i=0; i<N_secret_levels; i++) {
2333                 if (Secret_level_table[i] == level_num) {
2334                         First_secret_visit = 1;
2335                         mprintf((0, "Bashing First_secret_visit to 1 because entering level %i.\n", level_num));
2336                 }
2337         }
2338 }
2339
2340 //called when the player is starting a new level for normal game model
2341 //      secret_flag if came from a secret level
2342 void StartNewLevel(int level_num, int secret_flag)
2343 {
2344         ThisLevelTime=0;
2345
2346         if ((level_num > 0) && (!secret_flag)) {
2347                 maybe_set_first_secret_visit(level_num);
2348         }
2349
2350         ShowLevelIntro(level_num);
2351
2352         WIN(DEFINE_SCREEN(NULL));               // ALT-TAB: no restore of background.
2353         
2354         StartNewLevelSub(level_num, 1, secret_flag );
2355
2356 }
2357
2358 //initialize the player object position & orientation (at start of game, or new ship)
2359 void InitPlayerPosition(int random_flag)
2360 {
2361         int NewPlayer=0;
2362
2363 #ifdef NETWORK
2364         if (! ((Game_mode & GM_MULTI) && !(Game_mode&GM_MULTI_COOP)) ) // If not deathmatch
2365 #endif
2366                 NewPlayer = Player_num;
2367 #ifdef NETWORK
2368         else if (random_flag == 1)
2369         {
2370                 int i, closest = -1, trys=0;
2371                 fix closest_dist = 0x7ffffff, dist;
2372
2373                 d_srand(clock());
2374
2375 #ifndef NDEBUG
2376                 if (NumNetPlayerPositions != MAX_NUM_NET_PLAYERS)
2377                 {
2378                         mprintf((1, "WARNING: There are only %d start positions!\n"));
2379                         //Int3();
2380                 }
2381 #endif
2382
2383                 do {
2384                         if (trys > 0)   
2385                         {
2386                                 mprintf((0, "Can't start in location %d because its too close to player %d\n", NewPlayer, closest ));
2387                         }
2388                         trys++;
2389
2390                         NewPlayer = d_rand() % NumNetPlayerPositions;
2391
2392                         closest = -1;
2393                         closest_dist = 0x7fffffff;
2394         
2395                         for (i=0; i<N_players; i++ )    {
2396                                 if ( (i!=Player_num) && (Objects[Players[i].objnum].type == OBJ_PLAYER) )       {
2397                                         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
2398                                         // -- mprintf((0, "Distance from start location %d to player %d is %f.\n", NewPlayer, i, f2fl(dist)));
2399                                         if ( (dist < closest_dist) && (dist >= 0) )     {
2400                                                 closest_dist = dist;
2401                                                 closest = i;
2402                                         }
2403                                 }
2404                         }
2405
2406                         // -- mprintf((0, "Closest from pos %d is %f to plr %d.\n", NewPlayer, f2fl(closest_dist), closest));
2407                 } while ( (closest_dist<i2f(15*20)) && (trys<MAX_NUM_NET_PLAYERS*2) );
2408         } 
2409         else {
2410                 mprintf((0, "Starting position is not being changed.\n"));
2411                 goto done; // If deathmatch and not random, positions were already determined by sync packet
2412         }
2413         Assert(NewPlayer >= 0);
2414         Assert(NewPlayer < NumNetPlayerPositions);
2415 #endif
2416
2417         ConsoleObject->pos = Player_init[NewPlayer].pos;
2418         ConsoleObject->orient = Player_init[NewPlayer].orient;
2419 // -- mprintf((0, "Pos set to %8x %8x %8x\n", ConsoleObject->pos.x, ConsoleObject->pos.y, ConsoleObject->pos.z));
2420
2421         // -- mprintf((0, "Re-starting in location %d of %d.\n", NewPlayer+1, NumNetPlayerPositions));
2422
2423         obj_relink(ConsoleObject-Objects,Player_init[NewPlayer].segnum);
2424
2425 #ifdef NETWORK
2426 done:
2427 #endif
2428         reset_player_object();
2429         reset_cruise();
2430 }
2431
2432 //      -----------------------------------------------------------------------------------------------------
2433 //      Initialize default parameters for one robot, copying from Robot_info to *objp.
2434 //      What about setting size!?  Where does that come from?
2435 void copy_defaults_to_robot(object *objp)
2436 {
2437         robot_info      *robptr;
2438         int                     objid;
2439
2440         Assert(objp->type == OBJ_ROBOT);
2441         objid = objp->id;
2442         Assert(objid < N_robot_types);
2443
2444         robptr = &Robot_info[objid];
2445
2446         //      Boost shield for Thief and Buddy based on level.
2447         objp->shields = robptr->strength;
2448
2449         if ((robptr->thief) || (robptr->companion)) {
2450                 objp->shields = (objp->shields * (abs(Current_level_num)+7))/8;
2451
2452                 if (robptr->companion) {
2453                         //      Now, scale guide-bot hits by skill level
2454                         switch (Difficulty_level) {
2455                                 case 0: objp->shields = i2f(20000);     break;          //      Trainee, basically unkillable
2456                                 case 1: objp->shields *= 3;                             break;          //      Rookie, pretty dang hard
2457                                 case 2: objp->shields *= 2;                             break;          //      Hotshot, a bit tough
2458                                 default:        break;
2459                         }
2460                 }
2461         } else if (robptr->boss_flag)   //      MK, 01/16/95, make boss shields lower on lower diff levels.
2462                 objp->shields = objp->shields/(NDL+3) * (Difficulty_level+4);
2463
2464         //      Additional wimpification of bosses at Trainee
2465         if ((robptr->boss_flag) && (Difficulty_level == 0))
2466                 objp->shields /= 2;
2467 }
2468
2469 //      -----------------------------------------------------------------------------------------------------
2470 //      Copy all values from the robot info structure to all instances of robots.
2471 //      This allows us to change bitmaps.tbl and have these changes manifested in existing robots.
2472 //      This function should be called at level load time.
2473 void copy_defaults_to_robot_all()
2474 {
2475         int     i;
2476
2477         for (i=0; i<=Highest_object_index; i++)
2478                 if (Objects[i].type == OBJ_ROBOT)
2479                         copy_defaults_to_robot(&Objects[i]);
2480
2481 }
2482
2483 extern void clear_stuck_objects(void);
2484
2485 //      -----------------------------------------------------------------------------------------------------
2486 //called when the player is starting a level (new game or new ship)
2487 void StartLevel(int random_flag)
2488 {
2489         Assert(!Player_is_dead);
2490
2491         InitPlayerPosition(random_flag);
2492
2493         verify_console_object();
2494
2495         ConsoleObject->control_type     = CT_FLYING;
2496         ConsoleObject->movement_type    = MT_PHYSICS;
2497
2498         disable_matcens();
2499
2500         clear_transient_objects(0);             //0 means leave proximity bombs
2501
2502         // create_player_appearance_effect(ConsoleObject);
2503         Do_appearance_effect = 1;
2504
2505 #ifdef NETWORK
2506         if (Game_mode & GM_MULTI)
2507         {
2508                 if (Game_mode & GM_MULTI_COOP)
2509                         multi_send_score();
2510                 multi_send_position(Players[Player_num].objnum);
2511                 multi_send_reappear();
2512         }               
2513
2514         if (Game_mode & GM_NETWORK)
2515                 network_do_frame(1, 1);
2516 #endif
2517
2518         ai_reset_all_paths();
2519         ai_init_boss_for_ship();
2520         clear_stuck_objects();
2521
2522         #ifdef EDITOR
2523         //      Note, this is only done if editor builtin.  Calling this from here
2524         //      will cause it to be called after the player dies, resetting the
2525         //      hits for the buddy and thief.  This is ok, since it will work ok
2526         //      in a shipped version.
2527         init_ai_objects();
2528         #endif
2529
2530         reset_time();
2531
2532         reset_rear_view();
2533         Auto_fire_fusion_cannon_time = 0;
2534         Fusion_charge = 0;
2535
2536         Robot_firing_enabled = 1;
2537 }