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