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