remove explicit uses of mission list
[btb/d2x.git] / main / state.c
1 /* $Id: state.c,v 1.16 2004-10-23 19:39:35 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  * Functions to save/restore game state.
18  *
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include <conf.h>
23 #endif
24
25 #ifdef WINDOWS
26 #include "desw.h"
27 #endif
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <math.h>
32 #include <string.h>
33 #if !defined(_MSC_VER) && !defined(macintosh)
34 #include <unistd.h>
35 #endif
36 #ifndef _WIN32_WCE
37 #include <errno.h>
38 #endif
39 #ifdef MACINTOSH
40 #include <Files.h>
41 #endif
42
43 #ifdef OGL
44 # ifdef _MSC_VER
45 #  include <windows.h>
46 # endif
47 #if defined(__APPLE__) && defined(__MACH__)
48 #include <OpenGL/gl.h>
49 #else
50 #include <GL/gl.h>
51 #endif
52 #endif
53
54 #include "pstypes.h"
55 #include "pa_enabl.h"                   //$$POLY_ACC
56 #include "mono.h"
57 #include "inferno.h"
58 #include "segment.h"
59 #include "textures.h"
60 #include "wall.h"
61 #include "object.h"
62 #include "digi.h"
63 #include "gamemine.h"
64 #include "error.h"
65 #include "gameseg.h"
66 #include "menu.h"
67 #include "switch.h"
68 #include "game.h"
69 #include "screens.h"
70 #include "newmenu.h"
71 #include "cfile.h"
72 #include "fuelcen.h"
73 #include "hash.h"
74 #include "key.h"
75 #include "piggy.h"
76 #include "player.h"
77 #include "cntrlcen.h"
78 #include "morph.h"
79 #include "weapon.h"
80 #include "render.h"
81 #include "gameseq.h"
82 #include "gauges.h"
83 #include "newdemo.h"
84 #include "automap.h"
85 #include "piggy.h"
86 #include "paging.h"
87 #include "titles.h"
88 #include "text.h"
89 #include "mission.h"
90 #include "pcx.h"
91 #include "u_mem.h"
92 #ifdef NETWORK
93 #include "network.h"
94 #endif
95 #include "args.h"
96 #include "ai.h"
97 #include "fireball.h"
98 #include "controls.h"
99 #include "laser.h"
100 #include "multibot.h"
101 #include "state.h"
102
103 #if defined(POLY_ACC)
104 #include "poly_acc.h"
105 #endif
106
107 #ifdef OGL
108 #include "gr.h"
109 #endif
110
111 #define STATE_VERSION 22
112 #define STATE_COMPATIBLE_VERSION 20
113 // 0 - Put DGSS (Descent Game State Save) id at tof.
114 // 1 - Added Difficulty level save
115 // 2 - Added Cheats_enabled flag
116 // 3 - Added between levels save.
117 // 4 - Added mission support
118 // 5 - Mike changed ai and object structure.
119 // 6 - Added buggin' cheat save
120 // 7 - Added other cheat saves and game_id.
121 // 8 - Added AI stuff for escort and thief.
122 // 9 - Save palette with screen shot
123 // 12- Saved last_was_super array
124 // 13- Saved palette flash stuff
125 // 14- Save cloaking wall stuff
126 // 15- Save additional ai info
127 // 16- Save Light_subtracted
128 // 17- New marker save
129 // 18- Took out saving of old cheat status
130 // 19- Saved cheats_enabled flag
131 // 20- First_secret_visit
132 // 22- Omega_charge
133
134 #define NUM_SAVES 9
135 #define THUMBNAIL_W 100
136 #define THUMBNAIL_H 50
137 #define DESC_LENGTH 20
138
139 extern void multi_initiate_save_game();
140 extern void multi_initiate_restore_game();
141 extern void apply_all_changed_light(void);
142
143 extern int Do_appearance_effect;
144 extern fix Fusion_next_sound_time;
145
146 extern int Laser_rapid_fire;
147 extern int Physics_cheat_flag;
148 extern int Lunacy;
149 extern void do_lunacy_on(void);
150 extern void do_lunacy_off(void);
151 extern int First_secret_visit;
152
153 int sc_last_item= 0;
154 grs_bitmap *sc_bmp[NUM_SAVES+1];
155
156 char dgss_id[4] = "DGSS";
157
158 int state_default_item = 0;
159
160 uint state_game_id;
161
162 extern int robot_controlled[MAX_ROBOTS_CONTROLLED];
163 extern int robot_agitation[MAX_ROBOTS_CONTROLLED];
164 extern fix robot_controlled_time[MAX_ROBOTS_CONTROLLED];
165 extern fix robot_last_send_time[MAX_ROBOTS_CONTROLLED];
166 extern fix robot_last_message_time[MAX_ROBOTS_CONTROLLED];
167 extern int robot_send_pending[MAX_ROBOTS_CONTROLLED];
168 extern int robot_fired[MAX_ROBOTS_CONTROLLED];
169 extern sbyte robot_fire_buf[MAX_ROBOTS_CONTROLLED][18+3];
170
171
172 #if defined(WINDOWS) || defined(MACINTOSH)
173 extern ubyte Hack_DblClick_MenuMode;
174 #endif
175
176 void compute_all_static_light(void);
177
178 //-------------------------------------------------------------------
179 void state_callback(int nitems,newmenu_item * items, int * last_key, int citem)
180 {
181         nitems = nitems;
182         last_key = last_key;
183         
184 //      if ( sc_last_item != citem )    {
185 //              sc_last_item = citem;
186                 if ( citem > 0 )        {
187                         if ( sc_bmp[citem-1] )  {
188                                 if (MenuHires) {
189                                 WINDOS(
190                                         dd_grs_canvas *save_canv = dd_grd_curcanv,
191                                         grs_canvas *save_canv = grd_curcanv
192                                 );
193                                         grs_canvas *temp_canv = gr_create_canvas(THUMBNAIL_W*2,(THUMBNAIL_H*24/10));
194                                         grs_point vertbuf[3] = {{0,0}, {0,0}, {i2f(THUMBNAIL_W*2),i2f(THUMBNAIL_H*24/10)} };
195                                         gr_set_current_canvas(temp_canv);
196                                         scale_bitmap(sc_bmp[citem-1], vertbuf, 0 );
197                                 WINDOS(
198                                         dd_gr_set_current_canvas(save_canv),
199                                         gr_set_current_canvas( save_canv )
200                                 );
201                                 WIN(DDGRLOCK(dd_grd_curcanv));
202                                         gr_bitmap( (grd_curcanv->cv_bitmap.bm_w-THUMBNAIL_W*2)/2,items[0].y-10, &temp_canv->cv_bitmap);
203                                 WIN(DDGRUNLOCK(dd_grd_curcanv));
204                                         gr_free_canvas(temp_canv);
205                                 }
206                                 else    {
207                                 #ifdef WINDOWS
208                                         Int3();
209                                 #else
210                                         gr_bitmap( (grd_curcanv->cv_bitmap.bm_w-THUMBNAIL_W)/2,items[0].y-5, sc_bmp[citem-1] );
211                                 #endif
212                                 }
213                         }
214                 }
215 //      }       
216 }
217
218 void rpad_string( char * string, int max_chars )
219 {
220         int i, end_found;
221
222         end_found = 0;
223         for( i=0; i<max_chars; i++ )    {
224                 if ( *string == 0 )
225                         end_found = 1;
226                 if ( end_found )
227                         *string = ' ';
228                 string++;
229         }
230         *string = 0;            // NULL terminate
231 }
232
233 int state_get_save_file(char * fname, char * dsc, int multi )
234 {
235         CFILE *fp;
236         int i, choice, version;
237         newmenu_item m[NUM_SAVES+2];
238         char filename[NUM_SAVES+1][30];
239         char desc[NUM_SAVES+1][DESC_LENGTH+16];
240         char id[5];
241         int valid=0;
242         
243         for (i=0;i<NUM_SAVES; i++ )     {
244                 sc_bmp[i] = NULL;
245                 if ( !multi )
246                         #ifndef MACINTOSH
247                         sprintf( filename[i], "%s.sg%x", Players[Player_num].callsign, i );
248                         #else
249                         sprintf( filename[i], ":Players:%s.sg%x", Players[Player_num].callsign, i );
250                         #endif
251                 else
252                         #ifndef MACINTOSH
253                         sprintf( filename[i], "%s.mg%x", Players[Player_num].callsign, i );
254                         #else
255                         sprintf( filename[i], ":Players:%s.mg%x", Players[Player_num].callsign, i );
256                         #endif
257                 valid = 0;
258                 fp = cfopen(filename[i], "rb");
259                 if ( fp ) {
260                         //Read id
261                         cfread(id, sizeof(char)*4, 1, fp);
262                         if ( !memcmp( id, dgss_id, 4 )) {
263                                 //Read version
264                                 cfread(&version, sizeof(int), 1, fp);
265                                 if (version >= STATE_COMPATIBLE_VERSION)        {
266                                         // Read description
267                                         cfread(desc[i], sizeof(char)*DESC_LENGTH, 1, fp);
268                                         //rpad_string( desc[i], DESC_LENGTH-1 );
269                                         // Read thumbnail
270                                         //sc_bmp[i] = gr_create_bitmap(THUMBNAIL_W,THUMBNAIL_H );
271                                         //cfread(sc_bmp[i]->bm_data, THUMBNAIL_W * THUMBNAIL_H, 1, fp);
272                                         valid = 1;
273                                 }
274                         }
275                         cfclose(fp);
276                 }
277                 if (!valid) {
278                         strcpy( desc[i], TXT_EMPTY );
279                         //rpad_string( desc[i], DESC_LENGTH-1 );
280                 }
281                 m[i].type = NM_TYPE_INPUT_MENU; m[i].text = desc[i]; m[i].text_len = DESC_LENGTH-1;
282         }
283
284         sc_last_item = -1;
285         choice = newmenu_do1( NULL, "Save Game", NUM_SAVES, m, NULL, state_default_item );
286
287         for (i=0; i<NUM_SAVES; i++ )    {
288                 if ( sc_bmp[i] )
289                         gr_free_bitmap( sc_bmp[i] );
290         }
291
292         if (choice > -1) {
293                 strcpy( fname, filename[choice] );
294                 strcpy( dsc, desc[choice] );
295                 state_default_item = choice;
296                 return choice+1;
297         }
298         return 0;
299 }
300
301 int RestoringMenu=0;
302 extern int Current_display_mode;
303
304 int state_get_restore_file(char * fname, int multi)
305 {
306         CFILE *fp;
307         int i, choice, version, nsaves;
308         newmenu_item m[NUM_SAVES+2];
309         char filename[NUM_SAVES+1][30];
310         char desc[NUM_SAVES+1][DESC_LENGTH + 16];
311         char id[5];
312         int valid;
313
314         nsaves=0;
315         m[0].type = NM_TYPE_TEXT; m[0].text = "\n\n\n\n";       
316         for (i=0;i<NUM_SAVES+1; i++ )   {
317                 sc_bmp[i] = NULL;
318                 if (!multi)
319                         #ifndef MACINTOSH
320                         sprintf( filename[i], "%s.sg%x", Players[Player_num].callsign, i );
321                         #else
322                         sprintf( filename[i], ":Players:%s.sg%x", Players[Player_num].callsign, i );
323                         #endif
324                 else
325                         #ifndef MACINTOSH
326                         sprintf( filename[i], "%s.mg%x", Players[Player_num].callsign, i );
327                         #else
328                         sprintf( filename[i], ":Players:%s.mg%x", Players[Player_num].callsign, i );
329                         #endif
330                 valid = 0;
331                 fp = cfopen(filename[i], "rb");
332                 if ( fp ) {
333                         //Read id
334                         cfread(id, sizeof(char)*4, 1, fp);
335                         if ( !memcmp( id, dgss_id, 4 )) {
336                                 //Read version
337                                 cfread(&version, sizeof(int), 1, fp);
338                                 if (version >= STATE_COMPATIBLE_VERSION)        {
339                                         // Read description
340                                         cfread(desc[i], sizeof(char)*DESC_LENGTH, 1, fp);
341                                         //rpad_string( desc[i], DESC_LENGTH-1 );
342                                         m[i+1].type = NM_TYPE_MENU; m[i+1].text = desc[i];
343                                         // Read thumbnail
344                                         sc_bmp[i] = gr_create_bitmap(THUMBNAIL_W,THUMBNAIL_H );
345                                         cfread(sc_bmp[i]->bm_data, THUMBNAIL_W * THUMBNAIL_H, 1, fp);
346                                         if (version >= 9) {
347                                                 ubyte pal[256*3];
348                                                 cfread(pal, 3, 256, fp);
349                                                 gr_remap_bitmap_good( sc_bmp[i], pal, -1, -1 );
350                                         }
351                                         nsaves++;
352                                         valid = 1;
353                                 }
354                         }
355                         cfclose(fp);
356                 }
357                 if (!valid) {
358                         strcpy( desc[i], TXT_EMPTY );
359                         //rpad_string( desc[i], DESC_LENGTH-1 );
360                         m[i+1].type = NM_TYPE_TEXT; m[i+1].text = desc[i];
361                 }
362         }
363
364         if ( nsaves < 1 )       {
365                 nm_messagebox( NULL, 1, "Ok", "No saved games were found!" );
366                 return 0;
367         }
368
369         if (Current_display_mode == 3)  //restore menu won't fit on 640x400
370                 VR_screen_flags ^= VRF_COMPATIBLE_MENUS;
371
372         sc_last_item = -1;
373
374 #if defined(WINDOWS) || defined(MACINTOSH)
375         Hack_DblClick_MenuMode = 1;
376 #endif
377
378    RestoringMenu=1;
379         choice = newmenu_do3( NULL, "Select Game to Restore", NUM_SAVES+2, m, state_callback, state_default_item+1, NULL, 190, -1 );
380    RestoringMenu=0;
381
382 #if defined(WINDOWS) || defined(MACINTOSH)
383         Hack_DblClick_MenuMode = 0;
384 #endif
385
386         if (Current_display_mode == 3)  //set flag back
387                 VR_screen_flags ^= VRF_COMPATIBLE_MENUS;
388
389
390         for (i=0; i<NUM_SAVES+1; i++ )  {
391                 if ( sc_bmp[i] )
392                         gr_free_bitmap( sc_bmp[i] );
393         }
394
395         if (choice > 0) {
396                 strcpy( fname, filename[choice-1] );
397                 if (choice != NUM_SAVES+1)              //no new default when restore from autosave
398                         state_default_item = choice - 1;
399                 return choice;
400         }
401         return 0;
402 }
403
404 #define DESC_OFFSET     8
405
406 #define CF_BUF_SIZE     1024
407
408 #ifdef _WIN32_WCE
409 # define errno -1
410 # define strerror(x) "Unknown Error"
411 #endif
412
413
414 //      -----------------------------------------------------------------------------------
415 //      Imagine if C had a function to copy a file...
416 int copy_file(char *old_file, char *new_file)
417 {
418         sbyte   buf[CF_BUF_SIZE];
419         CFILE   *in_file, *out_file;
420
421         out_file = cfopen(new_file, "wb");
422
423         if (out_file == NULL)
424                 return -1;
425
426         in_file = cfopen(old_file, "rb");
427
428         if (in_file == NULL)
429                 return -2;
430
431         while (!cfeof(in_file))
432         {
433                 int bytes_read;
434
435                 bytes_read = cfread(buf, 1, CF_BUF_SIZE, in_file);
436                 if (cferror(in_file))
437                         Error("Cannot read from file <%s>: %s", old_file, strerror(errno));
438
439                 Assert(bytes_read == CF_BUF_SIZE || cfeof(in_file));
440
441                 cfwrite(buf, 1, bytes_read, out_file);
442
443                 if (cferror(out_file))
444                         Error("Cannot write to file <%s>: %s", new_file, strerror(errno));
445         }
446
447         if (cfclose(in_file)) {
448                 cfclose(out_file);
449                 return -3;
450         }
451
452         if (cfclose(out_file))
453                 return -4;
454
455         return 0;
456 }
457
458 #ifndef MACINTOSH
459 #define SECRETB_FILENAME        "secret.sgb"
460 #define SECRETC_FILENAME        "secret.sgc"
461 #else
462 #define SECRETB_FILENAME        ":Players:secret.sgb"
463 #define SECRETC_FILENAME        ":Players:secret.sgc"
464 #endif
465
466 extern int Final_boss_is_dead;
467
468 //      -----------------------------------------------------------------------------------
469 //      blind_save means don't prompt user for any info.
470 int state_save_all(int between_levels, int secret_save, char *filename_override)
471 {
472         int     rval, filenum = -1;
473
474         char    filename[128], desc[DESC_LENGTH+1];
475
476         Assert(between_levels == 0);    //between levels save ripped out
477
478 #ifdef NETWORK
479         if ( Game_mode & GM_MULTI )     {
480                         multi_initiate_save_game();
481                 return 0;
482         }
483 #endif
484
485         if ((Current_level_num < 0) && (secret_save == 0)) {
486                 HUD_init_message( "Can't save in secret level!" );
487                 return 0;
488         }
489
490         if (Final_boss_is_dead)         //don't allow save while final boss is dying
491                 return 0;
492
493         mprintf(( 0, "CL=%d, NL=%d\n", Current_level_num, Next_level_num ));
494         
495         //      If this is a secret save and the control center has been destroyed, don't allow
496         //      return to the base level.
497         if (secret_save && (Control_center_destroyed)) {
498                 mprintf((0, "Deleting secret.sgb so player can't return to base level.\n"));
499                 cfile_delete(SECRETB_FILENAME);
500                 return 0;
501         }
502
503         stop_time();
504
505         if (secret_save == 1) {
506                 filename_override = filename;
507                 sprintf(filename_override, SECRETB_FILENAME);
508         } else if (secret_save == 2) {
509                 filename_override = filename;
510                 sprintf(filename_override, SECRETC_FILENAME);
511         } else {
512                 if (filename_override) {
513                         strcpy( filename, filename_override);
514                         sprintf(desc, "[autosave backup]");
515                 } else if (!(filenum = state_get_save_file(filename,desc,0))) {
516                         start_time();
517                         return 0;
518                 }
519         }
520                 
521         //      MK, 1/1/96
522         //      If not in multiplayer, do special secret level stuff.
523         //      If secret.sgc exists, then copy it to Nsecret.sgc (where N = filenum).
524         //      If it doesn't exist, then delete Nsecret.sgc
525         if (!secret_save && !(Game_mode & GM_MULTI)) {
526                 int     rval;
527                 char    temp_fname[32], fc;
528
529                 if (filenum != -1) {
530
531                         if (filenum >= 10)
532                                 fc = (filenum-10) + 'a';
533                         else
534                                 fc = '0' + filenum;
535
536                         #ifndef MACINTOSH
537                         sprintf(temp_fname, "%csecret.sgc", fc);
538                         #else
539                         sprintf(temp_fname, ":Players:%csecret.sgc", fc);
540                         #endif
541
542                         mprintf((0, "Trying to copy secret.sgc to %s.\n", temp_fname));
543
544                         if (cfexist(temp_fname))
545                         {
546                                 mprintf((0, "Deleting file %s\n", temp_fname));
547                                 rval = cfile_delete(temp_fname);
548                                 Assert(rval == 0);      //      Oops, error deleting file in temp_fname.
549                         }
550
551                         if (cfexist(SECRETC_FILENAME))
552                         {
553                                 mprintf((0, "Copying secret.sgc to %s.\n", temp_fname));
554                                 rval = copy_file(SECRETC_FILENAME, temp_fname);
555                                 Assert(rval == 0);      //      Oops, error copying temp_fname to secret.sgc!
556                         }
557                 }
558         }
559
560         //      Save file we're going to save over in last slot and call "[autosave backup]"
561         if (!filename_override) {
562                 CFILE *tfp;
563         
564                 tfp = cfopen(filename, "rb");
565
566                 if ( tfp ) {
567                         char    newname[128];
568
569                         #ifndef MACINTOSH
570                         sprintf( newname, "%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
571                         #else
572                         sprintf( newname, ":Players:%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
573                         #endif
574                         
575                         cfseek(tfp, DESC_OFFSET, SEEK_SET);
576                         cfwrite("[autosave backup]", sizeof(char)*DESC_LENGTH, 1, tfp);
577                         cfclose(tfp);
578                         cfile_delete(newname);
579                         cfile_rename(filename, newname);
580                 }
581         }
582         
583         rval = state_save_all_sub(filename, desc, between_levels);
584
585         return rval;
586 }
587
588 extern  fix     Flash_effect, Time_flash_last_played;
589
590
591 int state_save_all_sub(char *filename, char *desc, int between_levels)
592 {
593         int i,j;
594         CFILE *fp;
595         grs_canvas * cnv;
596         #ifdef POLY_ACC
597         grs_canvas cnv2,*save_cnv2;
598         #endif
599         ubyte *pal;
600
601         Assert(between_levels == 0);    //between levels save ripped out
602
603 /*      if ( Game_mode & GM_MULTI )     {
604                 {
605                 start_time();
606                 return 0;
607                 }
608         }*/
609
610         #if defined(MACINTOSH) && !defined(NDEBUG)
611         if ( strncmp(filename, ":Players:", 9) )
612                 Int3();
613         #endif
614
615         fp = cfopen(filename, "wb");
616         if ( !fp ) {
617                 if ( !(Game_mode & GM_MULTI) )
618                         nm_messagebox(NULL, 1, TXT_OK, "Error writing savegame.\nPossibly out of disk\nspace.");
619                 start_time();
620                 return 0;
621         }
622
623 //Save id
624         cfwrite(dgss_id, sizeof(char)*4, 1, fp);
625
626 //Save version
627         i = STATE_VERSION;
628         cfwrite(&i, sizeof(int), 1, fp);
629
630 //Save description
631         cfwrite(desc, sizeof(char) * DESC_LENGTH, 1, fp);
632         
633 // Save the current screen shot...
634
635         cnv = gr_create_canvas( THUMBNAIL_W, THUMBNAIL_H );
636         if ( cnv )
637         {
638 #ifdef OGL
639                 ubyte *buf;
640                 int k;
641 #endif
642                 #ifdef WINDOWS
643                         dd_grs_canvas *cnv_save;
644                         cnv_save = dd_grd_curcanv;
645                 #else
646                         grs_canvas * cnv_save;
647                         cnv_save = grd_curcanv;
648                 #endif
649
650                 #ifndef MACINTOSH
651                 
652                         #if defined(POLY_ACC)
653                         
654                                         PA_DFX (pa_fool_to_backbuffer());
655                         
656                                         //for poly_acc, we render the frame to the normal render buffer
657                                         //so that this doesn't show, we create yet another canvas to save
658                                         //and restore what's on the render buffer
659                                         PA_DFX (pa_alpha_always());     
660                                         PA_DFX (pa_set_front_to_read());
661                                         gr_init_sub_canvas( &cnv2, &VR_render_buffer[0], 0, 0, THUMBNAIL_W, THUMBNAIL_H );
662                                         save_cnv2 = gr_create_canvas2(THUMBNAIL_W, THUMBNAIL_H, cnv2.cv_bitmap.bm_type);
663                                         gr_set_current_canvas( save_cnv2 );
664                                         PA_DFX (pa_set_front_to_read());
665                                         gr_bitmap(0,0,&cnv2.cv_bitmap);
666                                         gr_set_current_canvas( &cnv2 );
667                         #else
668                                         gr_set_current_canvas( cnv );
669                         #endif
670                         
671                                         PA_DFX (pa_set_backbuffer_current());
672                                         render_frame(0, 0);
673                                         PA_DFX (pa_alpha_always());
674                         
675 #if defined(POLY_ACC)
676                                         #ifndef MACINTOSH
677                                         screen_shot_pa(cnv,&cnv2);
678                                         #else
679                                         if ( PAEnabled )
680                                                 screen_shot_pa(cnv,&cnv2);
681                                         #endif
682 #elif defined(OGL)
683 # if 1
684                 buf = d_malloc(THUMBNAIL_W * THUMBNAIL_H * 3);
685                 glReadBuffer(GL_FRONT);
686                 glReadPixels(0, SHEIGHT - THUMBNAIL_H, THUMBNAIL_W, THUMBNAIL_H, GL_RGB, GL_UNSIGNED_BYTE, buf);
687                 k = THUMBNAIL_H;
688                 for (i = 0; i < THUMBNAIL_W * THUMBNAIL_H; i++) {
689                         if (!(j = i % THUMBNAIL_W))
690                                 k--;
691                         cnv->cv_bitmap.bm_data[THUMBNAIL_W * k + j] =
692                                 gr_find_closest_color(buf[3*i]/4, buf[3*i+1]/4, buf[3*i+2]/4);
693                 }
694                 d_free(buf);
695 # else // simpler d1x method, not tested yet
696                 ogl_ubitblt_tolinear(grd_curcanv->cv_bitmap.bm_w, grd_curcanv->cv_bitmap.bm_h, 0, 0, 0, 0, &grd_curscreen->sc_canvas.cv_bitmap, &grd_curcanv->cv_bitmap);
697 # endif
698 #endif
699
700                                         pal = gr_palette;
701
702                                         cfwrite(cnv->cv_bitmap.bm_data, THUMBNAIL_W * THUMBNAIL_H, 1, fp);
703
704                         #if defined(POLY_ACC)
705                                         PA_DFX (pa_alpha_always());     
706                                         PA_DFX (pa_set_frontbuffer_current());
707                                         PA_DFX(gr_bitmap(0,0,&save_cnv2->cv_bitmap));
708                                         PA_DFX (pa_set_backbuffer_current());
709                                         gr_bitmap(0,0,&save_cnv2->cv_bitmap);
710                                         gr_free_canvas(save_cnv2);
711                                         PA_DFX (pa_fool_to_offscreen());
712                         
713                         #endif
714                 
715                 #else   // macintosh stuff below
716                 {
717                         #if defined(POLY_ACC)
718                                 int     savePAEnabled = PAEnabled;
719                                 PAEnabled = false;
720                         #endif
721
722                         gr_set_current_canvas( cnv );
723                         render_frame(0, 0);
724                         pal = gr_palette;
725                         cfwrite(cnv->cv_bitmap.bm_data, THUMBNAIL_W * THUMBNAIL_H, 1, fp);
726                         
727                         #if defined(POLY_ACC)
728                                 PAEnabled = savePAEnabled;
729                         #endif
730                 }       
731                 #endif  // end of ifndef macintosh
732                 
733                 
734                 WINDOS(
735                         dd_gr_set_current_canvas(cnv_save),
736                         gr_set_current_canvas(cnv_save)
737                 );
738                 gr_free_canvas( cnv );
739                 cfwrite(pal, 3, 256, fp);
740         }
741         else
742         {
743                 ubyte color = 0;
744                 for ( i=0; i<THUMBNAIL_W*THUMBNAIL_H; i++ )
745                         cfwrite(&color, sizeof(ubyte), 1, fp);
746         }
747
748 // Save the Between levels flag...
749         cfwrite(&between_levels, sizeof(int), 1, fp);
750
751 // Save the mission info...
752         mprintf ((0, "HEY! Mission name is %s\n", Current_mission_filename));
753         cfwrite(Current_mission_filename, sizeof(char), 9, fp);
754
755 //Save level info
756         cfwrite(&Current_level_num, sizeof(int), 1, fp);
757         cfwrite(&Next_level_num, sizeof(int), 1, fp);
758
759 //Save GameTime
760         cfwrite(&GameTime, sizeof(fix), 1, fp);
761
762 // If coop save, save all
763 #ifdef NETWORK
764    if (Game_mode & GM_MULTI_COOP)
765          {
766                 cfwrite(&state_game_id, sizeof(int), 1, fp);
767                 cfwrite(&Netgame, sizeof(netgame_info), 1, fp);
768                 cfwrite(&NetPlayers, sizeof(AllNetPlayers_info), 1, fp);
769                 cfwrite(&N_players, sizeof(int), 1, fp);
770                 cfwrite(&Player_num, sizeof(int), 1, fp);
771                 for (i=0;i<N_players;i++)
772                         cfwrite(&Players[i], sizeof(player), 1, fp);
773
774 #ifdef RISKY_PROPOSITION
775                 cfwrite(&robot_controlled[0], 4, MAX_ROBOTS_CONTROLLED, fp);
776                 cfwrite(&robot_agitation[0], 4, MAX_ROBOTS_CONTROLLED, fp);
777                 cfwrite(&robot_controlled_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
778                 cfwrite(&robot_last_send_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
779                 cfwrite(&robot_last_message_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
780                 cfwrite(&robot_send_pending[0], 4, MAX_ROBOTS_CONTROLLED, fp);
781                 cfwrite(&robot_fired[0], 4, MAX_ROBOTS_CONTROLLED, fp);
782
783       for (i=0;i<MAX_ROBOTS_CONTROLLED;i++)
784                         cfwrite(robot_fire_buf[i][0], 18 + 3, 1, fp);
785 #endif
786
787          }
788 #endif
789
790 //Save player info
791         cfwrite(&Players[Player_num], sizeof(player), 1, fp);
792
793 // Save the current weapon info
794         cfwrite(&Primary_weapon, sizeof(sbyte), 1, fp);
795         cfwrite(&Secondary_weapon, sizeof(sbyte), 1, fp);
796
797 // Save the difficulty level
798         cfwrite(&Difficulty_level, sizeof(int), 1, fp);
799 // Save cheats enabled
800         cfwrite(&Cheats_enabled, sizeof(int), 1, fp);
801
802         if ( !between_levels )  {
803
804         //Finish all morph objects
805                 for (i=0; i<=Highest_object_index; i++ )        {
806                         if ( (Objects[i].type != OBJ_NONE) && (Objects[i].render_type==RT_MORPH))       {
807                                 morph_data *md;
808                                 md = find_morph_data(&Objects[i]);
809                                 if (md) {                                       
810                                         md->obj->control_type = md->morph_save_control_type;
811                                         md->obj->movement_type = md->morph_save_movement_type;
812                                         md->obj->render_type = RT_POLYOBJ;
813                                         md->obj->mtype.phys_info = md->morph_save_phys_info;
814                                         md->obj = NULL;
815                                 } else {                                                //maybe loaded half-morphed from disk
816                                         Objects[i].flags |= OF_SHOULD_BE_DEAD;
817                                         Objects[i].render_type = RT_POLYOBJ;
818                                         Objects[i].control_type = CT_NONE;
819                                         Objects[i].movement_type = MT_NONE;
820                                 }
821                         }
822                 }
823         
824         //Save object info
825                 i = Highest_object_index+1;
826                 cfwrite(&i, sizeof(int), 1, fp);
827                 cfwrite(Objects, sizeof(object), i, fp);
828                 
829         //Save wall info
830                 i = Num_walls;
831                 cfwrite(&i, sizeof(int), 1, fp);
832                 cfwrite(Walls, sizeof(wall), i, fp);
833
834         //Save exploding wall info
835                 i = MAX_EXPLODING_WALLS;
836                 cfwrite(&i, sizeof(int), 1, fp);
837                 cfwrite(expl_wall_list, sizeof(*expl_wall_list), i, fp);
838         
839         //Save door info
840                 i = Num_open_doors;
841                 cfwrite(&i, sizeof(int), 1, fp );
842                 cfwrite(ActiveDoors, sizeof(active_door), i, fp);
843         
844         //Save cloaking wall info
845                 i = Num_cloaking_walls;
846                 cfwrite(&i, sizeof(int), 1, fp );
847                 cfwrite(CloakingWalls, sizeof(cloaking_wall), i, fp);
848         
849         //Save trigger info
850                 cfwrite(&Num_triggers, sizeof(int), 1, fp);
851                 cfwrite(Triggers, sizeof(trigger), Num_triggers, fp);
852         
853         //Save tmap info
854                 for (i=0; i<=Highest_segment_index; i++ )       {
855                         for (j=0; j<6; j++ )    {
856                                 cfwrite(&Segments[i].sides[j].wall_num, sizeof(short), 1, fp);
857                                 cfwrite(&Segments[i].sides[j].tmap_num, sizeof(short), 1, fp);
858                                 cfwrite(&Segments[i].sides[j].tmap_num2, sizeof(short), 1, fp);
859                         }
860                 }
861         
862         // Save the fuelcen info
863                 cfwrite(&Control_center_destroyed, sizeof(int), 1, fp);
864                 cfwrite(&Countdown_timer, sizeof(int), 1, fp);
865                 cfwrite(&Num_robot_centers, sizeof(int), 1, fp);
866                 cfwrite(RobotCenters, sizeof(matcen_info), Num_robot_centers, fp);
867                 cfwrite(&ControlCenterTriggers, sizeof(control_center_triggers), 1, fp);
868                 cfwrite(&Num_fuelcenters, sizeof(int), 1, fp);
869                 cfwrite(Station, sizeof(FuelCenter), Num_fuelcenters, fp);
870         
871         // Save the control cen info
872                 cfwrite(&Control_center_been_hit, sizeof(int), 1, fp);
873                 cfwrite(&Control_center_player_been_seen, sizeof(int), 1, fp);
874                 cfwrite(&Control_center_next_fire_time, sizeof(int), 1, fp);
875                 cfwrite(&Control_center_present, sizeof(int), 1, fp);
876                 cfwrite(&Dead_controlcen_object_num, sizeof(int), 1, fp);
877         
878         // Save the AI state
879                 ai_save_state( fp );
880         
881         // Save the automap visited info
882                 cfwrite(Automap_visited, sizeof(ubyte) * MAX_SEGMENTS, 1, fp);
883
884         }
885         cfwrite(&state_game_id, sizeof(uint), 1, fp);
886         cfwrite(&Laser_rapid_fire, sizeof(int), 1, fp);
887         cfwrite(&Lunacy, sizeof(int), 1, fp);           //      Yes, writing this twice.  Removed the Ugly robot system, but didn't want to change savegame format.
888         cfwrite(&Lunacy, sizeof(int), 1, fp);
889
890         // Save automap marker info
891
892         cfwrite(MarkerObject, sizeof(MarkerObject), 1, fp);
893         cfwrite(MarkerOwner, sizeof(MarkerOwner), 1, fp);
894         cfwrite(MarkerMessage, sizeof(MarkerMessage), 1, fp);
895
896         cfwrite(&Afterburner_charge, sizeof(fix), 1, fp);
897
898         //save last was super information
899         cfwrite(&Primary_last_was_super, sizeof(Primary_last_was_super), 1, fp);
900         cfwrite(&Secondary_last_was_super, sizeof(Secondary_last_was_super), 1, fp);
901
902         //      Save flash effect stuff
903         cfwrite(&Flash_effect, sizeof(int), 1, fp);
904         cfwrite(&Time_flash_last_played, sizeof(int), 1, fp);
905         cfwrite(&PaletteRedAdd, sizeof(int), 1, fp);
906         cfwrite(&PaletteGreenAdd, sizeof(int), 1, fp);
907         cfwrite(&PaletteBlueAdd, sizeof(int), 1, fp);
908
909         cfwrite(Light_subtracted, sizeof(Light_subtracted[0]), MAX_SEGMENTS, fp);
910
911         cfwrite(&First_secret_visit, sizeof(First_secret_visit), 1, fp);
912
913         cfwrite(&Omega_charge, sizeof(Omega_charge), 1, fp);
914         
915         if (cferror(fp))
916         {
917                 if ( !(Game_mode & GM_MULTI) ) {
918                         nm_messagebox(NULL, 1, TXT_OK, "Error writing savegame.\nPossibly out of disk\nspace.");
919                         cfclose(fp);
920                         cfile_delete(filename);
921                 }
922         } else  {
923                 cfclose(fp);
924
925                 #ifdef MACINTOSH                // set the type and creator of the saved game file
926                 {
927                         FInfo finfo;
928                         OSErr err;
929                         Str255 pfilename;
930         
931                         strcpy(pfilename, filename);
932                         c2pstr(pfilename);
933                         err = HGetFInfo(0, 0, pfilename, &finfo);
934                         finfo.fdType = 'SVGM';
935                         finfo.fdCreator = 'DCT2';
936                         err = HSetFInfo(0, 0, pfilename, &finfo);
937                 }
938                 #endif
939         }
940         
941         start_time();
942
943         return 1;
944 }
945
946 //      -----------------------------------------------------------------------------------
947 //      Set the player's position from the globals Secret_return_segment and Secret_return_orient.
948 void set_pos_from_return_segment(void)
949 {
950         int     plobjnum = Players[Player_num].objnum;
951
952         compute_segment_center(&Objects[plobjnum].pos, &Segments[Secret_return_segment]);
953         obj_relink(plobjnum, Secret_return_segment);
954         reset_player_object();
955         Objects[plobjnum].orient = Secret_return_orient;
956 }
957
958 //      -----------------------------------------------------------------------------------
959 int state_restore_all(int in_game, int secret_restore, char *filename_override)
960 {
961         char filename[128];
962         int     filenum = -1;
963
964 #ifdef NETWORK
965         if ( Game_mode & GM_MULTI )     {
966 #ifdef MULTI_SAVE
967                         multi_initiate_restore_game();
968 #endif
969                 return 0;
970         }
971 #endif
972
973         if (in_game && (Current_level_num < 0) && (secret_restore == 0)) {
974                 HUD_init_message( "Can't restore in secret level!" );
975                 return 0;
976         }
977
978         if ( Newdemo_state == ND_STATE_RECORDING )
979                 newdemo_stop_recording();
980
981         if ( Newdemo_state != ND_STATE_NORMAL )
982                 return 0;
983
984         stop_time();
985
986         if (filename_override) {
987                 strcpy(filename, filename_override);
988                 filenum = NUM_SAVES+1;          //      So we don't trigger autosave
989         } else if (!(filenum = state_get_restore_file(filename, 0)))    {
990                 start_time();
991                 return 0;
992         }
993         
994         //      MK, 1/1/96
995         //      If not in multiplayer, do special secret level stuff.
996         //      If Nsecret.sgc (where N = filenum) exists, then copy it to secret.sgc.
997         //      If it doesn't exist, then delete secret.sgc
998         if (!secret_restore && !(Game_mode & GM_MULTI)) {
999                 int     rval;
1000                 char    temp_fname[32], fc;
1001
1002                 if (filenum != -1) {
1003                         if (filenum >= 10)
1004                                 fc = (filenum-10) + 'a';
1005                         else
1006                                 fc = '0' + filenum;
1007                         
1008                         #ifndef MACINTOSH
1009                         sprintf(temp_fname, "%csecret.sgc", fc);
1010                         #else
1011                         sprintf(temp_fname, ":Players:%csecret.sgc", fc);
1012                         #endif
1013
1014                         mprintf((0, "Trying to copy %s to secret.sgc.\n", temp_fname));
1015
1016                         if (cfexist(temp_fname))
1017                         {
1018                                 mprintf((0, "Copying %s to secret.sgc\n", temp_fname));
1019                                 rval = copy_file(temp_fname, SECRETC_FILENAME);
1020                                 Assert(rval == 0);      //      Oops, error copying temp_fname to secret.sgc!
1021                         } else
1022                                 cfile_delete(SECRETC_FILENAME);
1023                 }
1024         }
1025
1026         //      Changed, 11/15/95, MK, don't to autosave if restoring from main menu.
1027         if ((filenum != (NUM_SAVES+1)) && in_game) {
1028                 char    temp_filename[128];
1029                 mprintf((0, "Doing autosave, filenum = %i, != %i!\n", filenum, NUM_SAVES+1));
1030                 #ifndef MACINTOSH
1031                 sprintf( temp_filename, "%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
1032                 #else
1033                 sprintf( temp_filename, ":Players:%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
1034                 #endif          
1035                 state_save_all(!in_game, secret_restore, temp_filename);
1036         }
1037
1038         if ( !secret_restore && in_game ) {
1039                 int choice;
1040                 choice =  nm_messagebox( NULL, 2, "Yes", "No", "Restore Game?" );
1041                 if ( choice != 0 )      {
1042                         start_time();
1043                         return 0;
1044                 }
1045         }
1046
1047         start_time();
1048
1049         return state_restore_all_sub(filename, 0, secret_restore);
1050 }
1051
1052 extern void init_player_stats_new_ship(void);
1053
1054 void ShowLevelIntro(int level_num);
1055
1056 extern void do_cloak_invul_secret_stuff(fix old_gametime);
1057 extern void copy_defaults_to_robot(object *objp);
1058
1059 int state_restore_all_sub(char *filename, int multi, int secret_restore)
1060 {
1061         int ObjectStartLocation;
1062         int version,i, j, segnum;
1063         object * obj;
1064         CFILE *fp;
1065         int current_level, next_level;
1066         int between_levels;
1067         char mission[16];
1068         char desc[DESC_LENGTH+1];
1069         char id[5];
1070         char org_callsign[CALLSIGN_LEN+16];
1071 #ifdef NETWORK
1072         int found;
1073         int nplayers;   //,playid[12],mynum;
1074         player restore_players[MAX_PLAYERS];
1075 #endif
1076         fix     old_gametime = GameTime;
1077
1078         #if defined(MACINTOSH) && !defined(NDEBUG)
1079         if ( strncmp(filename, ":Players:", 9) )
1080                 Int3();
1081         #endif
1082
1083         fp = cfopen(filename, "rb");
1084         if ( !fp ) return 0;
1085
1086 //Read id
1087         cfread(id, sizeof(char)*4, 1, fp);
1088         if ( memcmp( id, dgss_id, 4 )) {
1089                 cfclose(fp);
1090                 return 0;
1091         }
1092
1093 //Read version
1094         cfread(&version, sizeof(int), 1, fp);
1095         if (version < STATE_COMPATIBLE_VERSION) {
1096                 cfclose(fp);
1097                 return 0;
1098         }
1099
1100 // Read description
1101         cfread(desc, sizeof(char) * DESC_LENGTH, 1, fp);
1102
1103 // Skip the current screen shot...
1104         cfseek(fp, THUMBNAIL_W*THUMBNAIL_H, SEEK_CUR);
1105
1106 // And now...skip the goddamn palette stuff that somebody forgot to add
1107         cfseek(fp, 768, SEEK_CUR);
1108
1109 // Read the Between levels flag...
1110         cfread(&between_levels, sizeof(int), 1, fp);
1111
1112         Assert(between_levels == 0);    //between levels save ripped out
1113
1114 // Read the mission info...
1115         cfread(mission, sizeof(char), 9, fp);
1116         mprintf ((0,"Missionname to load = %s\n",mission));
1117
1118         if (!load_mission_by_name( mission ))   {
1119                 nm_messagebox( NULL, 1, "Ok", "Error!\nUnable to load mission\n'%s'\n", mission );
1120                 cfclose(fp);
1121                 return 0;
1122         }
1123
1124 //Read level info
1125         cfread(&current_level, sizeof(int), 1, fp);
1126         cfread(&next_level, sizeof(int), 1, fp);
1127
1128 //Restore GameTime
1129         cfread(&GameTime, sizeof(fix), 1, fp);
1130
1131 // Start new game....
1132         if (!multi)     {
1133                 Game_mode = GM_NORMAL;
1134                 Function_mode = FMODE_GAME;
1135 #ifdef NETWORK
1136                 change_playernum_to(0);
1137 #endif
1138                 strcpy( org_callsign, Players[0].callsign );
1139                 N_players = 1;
1140                 if (!secret_restore) {
1141                         InitPlayerObject();                             //make sure player's object set up
1142                         init_player_stats_game();               //clear all stats
1143                 }
1144         } else {
1145                 strcpy( org_callsign, Players[Player_num].callsign );
1146         }
1147
1148 #ifdef NETWORK
1149    if (Game_mode & GM_MULTI)
1150          {
1151                 cfread(&state_game_id,sizeof(int), 1, fp);
1152                 cfread(&Netgame,sizeof(netgame_info), 1, fp);
1153                 cfread(&NetPlayers,sizeof(AllNetPlayers_info), 1, fp);
1154                 cfread(&nplayers,sizeof(N_players), 1, fp);
1155                 cfread(&Player_num,sizeof(Player_num), 1, fp);
1156                 for (i=0;i<nplayers;i++)
1157                         cfread(&restore_players[i], sizeof(player), 1, fp);
1158 #ifdef RISKY_PROPOSITION
1159                 cfread(&robot_controlled[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1160                 cfread(&robot_agitation[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1161                 cfread(&robot_controlled_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1162                 cfread(&robot_last_send_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1163                 cfread(&robot_last_message_time[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1164                 cfread(&robot_send_pending[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1165                 cfread(&robot_fired[0], 4, MAX_ROBOTS_CONTROLLED, fp);
1166
1167       for (i=0;i<MAX_ROBOTS_CONTROLLED;i++)
1168                         cfread(&robot_fire_buf[i][0], 21, 1, fp);
1169 #endif
1170
1171            for (i=0;i<nplayers;i++)
1172                  {
1173                   found=0;
1174                   for (j=0;j<nplayers;j++)
1175                          {
1176            if ((!strcmp (restore_players[i].callsign,Players[j].callsign)) && Players[j].connected==1)
1177                                  found=1;
1178                          }
1179                   restore_players[i].connected=found;
1180             }
1181                 memcpy (&Players,&restore_players,sizeof(player)*nplayers);
1182                 N_players=nplayers;
1183
1184       if (network_i_am_master())
1185                  {
1186                   for (i=0;i<N_players;i++)
1187                         {
1188                          if (i==Player_num)
1189                                 continue;
1190                  Players[i].connected=0;
1191                         }
1192                  }
1193
1194                 //Viewer = ConsoleObject = &Objects[Players[Player_num].objnum];
1195          }
1196
1197 #endif
1198
1199 //Read player info
1200
1201         {
1202                 StartNewLevelSub(current_level, 1, secret_restore);
1203
1204                 if (secret_restore) {
1205                         player  dummy_player;
1206
1207                         cfread(&dummy_player, sizeof(player), 1, fp);
1208                         if (secret_restore == 1) {              //      This means he didn't die, so he keeps what he got in the secret level.
1209                                 Players[Player_num].level = dummy_player.level;
1210                                 Players[Player_num].last_score = dummy_player.last_score;
1211                                 Players[Player_num].time_level = dummy_player.time_level;
1212
1213                                 Players[Player_num].num_robots_level = dummy_player.num_robots_level;
1214                                 Players[Player_num].num_robots_total = dummy_player.num_robots_total;
1215                                 Players[Player_num].hostages_rescued_total = dummy_player.hostages_rescued_total;
1216                                 Players[Player_num].hostages_total = dummy_player.hostages_total;
1217                                 Players[Player_num].hostages_on_board = dummy_player.hostages_on_board;
1218                                 Players[Player_num].hostages_level = dummy_player.hostages_level;
1219                                 Players[Player_num].homing_object_dist = dummy_player.homing_object_dist;
1220                                 Players[Player_num].hours_level = dummy_player.hours_level;
1221                                 Players[Player_num].hours_total = dummy_player.hours_total;
1222                                 do_cloak_invul_secret_stuff(old_gametime);
1223                         } else {
1224                                 Players[Player_num] = dummy_player;
1225                         }
1226                 } else {
1227                         cfread(&Players[Player_num], sizeof(player), 1, fp);
1228                 }
1229         }
1230         strcpy( Players[Player_num].callsign, org_callsign );
1231
1232 // Set the right level
1233         if ( between_levels )
1234                 Players[Player_num].level = next_level;
1235
1236 // Restore the weapon states
1237         cfread(&Primary_weapon, sizeof(sbyte), 1, fp);
1238         cfread(&Secondary_weapon, sizeof(sbyte), 1, fp);
1239
1240         select_weapon(Primary_weapon, 0, 0, 0);
1241         select_weapon(Secondary_weapon, 1, 0, 0);
1242
1243 // Restore the difficulty level
1244         cfread(&Difficulty_level, sizeof(int), 1, fp);
1245
1246 // Restore the cheats enabled flag
1247
1248         cfread(&Cheats_enabled, sizeof(int), 1, fp);
1249
1250         if ( !between_levels )  {
1251                 Do_appearance_effect = 0;                       // Don't do this for middle o' game stuff.
1252
1253                 ObjectStartLocation = cftell(fp);
1254                 //Clear out all the objects from the lvl file
1255                 for (segnum=0; segnum <= Highest_segment_index; segnum++)
1256                         Segments[segnum].objects = -1;
1257                 reset_objects(1);
1258         
1259                 //Read objects, and pop 'em into their respective segments.
1260                 cfread(&i, sizeof(int), 1, fp);
1261                 Highest_object_index = i-1;
1262                 cfread(Objects, sizeof(object), i, fp);
1263         
1264                 Object_next_signature = 0;
1265                 for (i=0; i<=Highest_object_index; i++ )        {
1266                         obj = &Objects[i];
1267                         obj->rtype.pobj_info.alt_textures = -1;
1268                         segnum = obj->segnum;
1269                         obj->next = obj->prev = obj->segnum = -1;
1270                         if ( obj->type != OBJ_NONE )    {
1271                                 obj_link(i,segnum);
1272                                 if ( obj->signature > Object_next_signature )
1273                                         Object_next_signature = obj->signature;
1274                         }
1275
1276                         //look for, and fix, boss with bogus shields
1277                         if (obj->type == OBJ_ROBOT && Robot_info[obj->id].boss_flag) {
1278                                 fix save_shields = obj->shields;
1279
1280                                 copy_defaults_to_robot(obj);            //calculate starting shields
1281
1282                                 //if in valid range, use loaded shield value
1283                                 if (save_shields > 0 && save_shields <= obj->shields)
1284                                         obj->shields = save_shields;
1285                                 else
1286                                         obj->shields /= 2;  //give player a break
1287                         }
1288
1289                 }       
1290                 special_reset_objects();
1291                 Object_next_signature++;
1292         
1293                 //      1 = Didn't die on secret level.
1294                 //      2 = Died on secret level.
1295                 if (secret_restore && (Current_level_num >= 0)) {
1296                         set_pos_from_return_segment();
1297                         if (secret_restore == 2)
1298                                 init_player_stats_new_ship();
1299                 }
1300
1301                 //Restore wall info
1302                 cfread(&i, sizeof(int), 1, fp);
1303                 Num_walls = i;
1304                 cfread(Walls, sizeof(wall), Num_walls, fp);
1305
1306                 //now that we have the walls, check if any sounds are linked to
1307                 //walls that are now open
1308                 for (i=0;i<Num_walls;i++) {
1309                         if (Walls[i].type == WALL_OPEN)
1310                                 digi_kill_sound_linked_to_segment(Walls[i].segnum,Walls[i].sidenum,-1); //-1 means kill any sound
1311                 }
1312
1313                 //Restore exploding wall info
1314                 if (version >= 10) {
1315                         cfread(&i, sizeof(int), 1, fp);
1316                         cfread(expl_wall_list, sizeof(*expl_wall_list), i, fp);
1317                 }
1318
1319                 //Restore door info
1320                 cfread(&i, sizeof(int), 1, fp);
1321                 Num_open_doors = i;
1322                 cfread(ActiveDoors, sizeof(active_door), Num_open_doors, fp);
1323         
1324                 if (version >= 14) {            //Restore cloaking wall info
1325                         cfread(&i, sizeof(int), 1, fp);
1326                         Num_cloaking_walls = i;
1327                         cfread(CloakingWalls, sizeof(cloaking_wall), Num_cloaking_walls, fp);
1328                 }
1329         
1330                 //Restore trigger info
1331                 cfread(&Num_triggers, sizeof(int), 1, fp);
1332                 cfread(Triggers, sizeof(trigger), Num_triggers, fp);
1333         
1334                 //Restore tmap info
1335                 for (i=0; i<=Highest_segment_index; i++ )       {
1336                         for (j=0; j<6; j++ )    {
1337                                 cfread(&Segments[i].sides[j].wall_num, sizeof(short), 1, fp);
1338                                 cfread(&Segments[i].sides[j].tmap_num, sizeof(short), 1, fp);
1339                                 cfread(&Segments[i].sides[j].tmap_num2, sizeof(short), 1, fp);
1340                         }
1341                 }
1342         
1343                 //Restore the fuelcen info
1344                 cfread(&Control_center_destroyed, sizeof(int), 1, fp);
1345                 cfread(&Countdown_timer, sizeof(int), 1, fp);
1346                 cfread(&Num_robot_centers, sizeof(int), 1, fp);
1347                 cfread(RobotCenters, sizeof(matcen_info), Num_robot_centers, fp);
1348                 cfread(&ControlCenterTriggers, sizeof(control_center_triggers), 1, fp);
1349                 cfread(&Num_fuelcenters, sizeof(int), 1, fp);
1350                 cfread(Station, sizeof(FuelCenter), Num_fuelcenters, fp);
1351         
1352                 // Restore the control cen info
1353                 cfread(&Control_center_been_hit, sizeof(int), 1, fp);
1354                 cfread(&Control_center_player_been_seen, sizeof(int), 1, fp);
1355                 cfread(&Control_center_next_fire_time, sizeof(int), 1, fp);
1356                 cfread(&Control_center_present, sizeof(int), 1, fp);
1357                 cfread(&Dead_controlcen_object_num, sizeof(int), 1, fp);
1358         
1359                 // Restore the AI state
1360                 ai_restore_state( fp, version );
1361         
1362                 // Restore the automap visited info
1363                 cfread( Automap_visited, sizeof(ubyte), MAX_SEGMENTS, fp);
1364
1365                 //      Restore hacked up weapon system stuff.
1366                 Fusion_next_sound_time = GameTime;
1367                 Auto_fire_fusion_cannon_time = 0;
1368                 Next_laser_fire_time = GameTime;
1369                 Next_missile_fire_time = GameTime;
1370                 Last_laser_fired_time = GameTime;
1371
1372         }
1373         state_game_id = 0;
1374
1375         if ( version >= 7 )     {
1376                 cfread(&state_game_id, sizeof(uint), 1, fp);
1377                 cfread(&Laser_rapid_fire, sizeof(int), 1, fp);
1378                 cfread(&Lunacy, sizeof(int), 1, fp);            //      Yes, writing this twice.  Removed the Ugly robot system, but didn't want to change savegame format.
1379                 cfread(&Lunacy, sizeof(int), 1, fp);
1380                 if ( Lunacy )
1381                         do_lunacy_on();
1382         }
1383
1384         if (version >= 17) {
1385                 cfread(MarkerObject, sizeof(MarkerObject), 1, fp);
1386                 cfread(MarkerOwner, sizeof(MarkerOwner), 1, fp);
1387                 cfread(MarkerMessage, sizeof(MarkerMessage), 1, fp);
1388         }
1389         else {
1390                 int num,dummy;
1391
1392                 // skip dummy info
1393
1394                 cfread(&num, sizeof(int), 1, fp);       //was NumOfMarkers
1395                 cfread(&dummy, sizeof(int), 1, fp);     //was CurMarker
1396
1397                 cfseek(fp, num * (sizeof(vms_vector) + 40), SEEK_CUR);
1398
1399                 for (num=0;num<NUM_MARKERS;num++)
1400                         MarkerObject[num] = -1;
1401         }
1402
1403         if (version>=11) {
1404                 if (secret_restore != 1)
1405                         cfread(&Afterburner_charge, sizeof(fix), 1, fp);
1406                 else {
1407                         fix     dummy_fix;
1408                         cfread(&dummy_fix,sizeof(fix), 1, fp);
1409                 }
1410         }
1411         if (version>=12) {
1412                 //read last was super information
1413                 cfread(&Primary_last_was_super, sizeof(Primary_last_was_super), 1, fp);
1414                 cfread(&Secondary_last_was_super, sizeof(Secondary_last_was_super), 1, fp);
1415         }
1416
1417         if (version >= 12) {
1418                 cfread(&Flash_effect, sizeof(int), 1, fp);
1419                 cfread(&Time_flash_last_played, sizeof(int), 1, fp);
1420                 cfread(&PaletteRedAdd, sizeof(int), 1, fp);
1421                 cfread(&PaletteGreenAdd, sizeof(int), 1, fp);
1422                 cfread(&PaletteBlueAdd, sizeof(int), 1, fp);
1423         } else {
1424                 Flash_effect = 0;
1425                 Time_flash_last_played = 0;
1426                 PaletteRedAdd = 0;
1427                 PaletteGreenAdd = 0;
1428                 PaletteBlueAdd = 0;
1429         }
1430
1431         //      Load Light_subtracted
1432         if (version >= 16) {
1433                 cfread(Light_subtracted, sizeof(Light_subtracted[0]), MAX_SEGMENTS, fp);
1434                 apply_all_changed_light();
1435                 compute_all_static_light();     //      set static_light field in segment struct.  See note at that function.
1436         } else {
1437                 int     i;
1438                 for (i=0; i<=Highest_segment_index; i++)
1439                         Light_subtracted[i] = 0;
1440         }
1441
1442         if (!secret_restore) {
1443                 if (version >= 20) {
1444                         cfread(&First_secret_visit, sizeof(First_secret_visit), 1, fp);
1445                         mprintf((0, "File: [%s] Read First_secret_visit: New value = %i\n", filename, First_secret_visit));
1446                 } else
1447                         First_secret_visit = 1;
1448         } else
1449                 First_secret_visit = 0;
1450
1451         if (version >= 22)
1452         {
1453                 if (secret_restore != 1)
1454                         cfread(&Omega_charge,sizeof(fix), 1, fp);
1455                 else {
1456                         fix     dummy_fix;
1457                         cfread(&dummy_fix,sizeof(fix), 1, fp);
1458                 }
1459         }
1460
1461         cfclose(fp);
1462
1463 #ifdef NETWORK
1464    if (Game_mode & GM_MULTI)   // Get rid of ships that aren't
1465          {                                                                       // connected in the restored game
1466                 for (i=0;i<nplayers;i++)
1467                  {
1468                   mprintf ((0,"Testing %s = %d\n",Players[i].callsign,Players[i].connected));
1469                   if (Players[i].connected!=1)
1470                    {
1471                     network_disconnect_player (i);
1472                create_player_appearance_effect(&Objects[Players[i].objnum]);
1473                          mprintf ((0,"Killing player ship %s!\n",Players[i].callsign));
1474               }
1475                  }
1476                         
1477          }
1478 #endif
1479
1480 // Load in bitmaps, etc..
1481 //!!    piggy_load_level_data();        //already done by StartNewLevelSub()
1482
1483         return 1;
1484 }
1485
1486 //      When loading a saved game, segp->static_light is bogus.
1487 //      This is because apply_all_changed_light, which is supposed to properly update this value,
1488 //      cannot do so because it needs the original light cast from a light which is no longer there.
1489 //      That is, a light has been blown out, so the texture remaining casts 0 light, but the static light
1490 //      which is present in the static_light field contains the light cast from that light.
1491 void compute_all_static_light(void)
1492 {
1493         int     i, j, k;
1494
1495         for (i=0; i<=Highest_segment_index; i++) {
1496                 fix     total_light;
1497                 segment *segp;
1498
1499                 segp = &Segments[i];
1500                 total_light = 0;
1501
1502                 for (j=0; j<MAX_SIDES_PER_SEGMENT; j++) {
1503                         side    *sidep;
1504
1505                         sidep = &segp->sides[j];
1506
1507                         for (k=0; k<4; k++)
1508                                 total_light += sidep->uvls[k].l;
1509                 }
1510
1511                 Segment2s[i].static_light = total_light/(MAX_SIDES_PER_SEGMENT*4);
1512         }
1513
1514 }
1515
1516
1517 int state_get_game_id(char *filename)
1518 {
1519         int version;
1520         CFILE *fp;
1521         int between_levels;
1522         char mission[16];
1523         char desc[DESC_LENGTH+1];
1524         char id[5];
1525         int dumbint;
1526
1527 mprintf((0, "Restoring multigame from [%s]\n", filename));
1528
1529         fp = cfopen(filename, "rb");
1530         if ( !fp ) return 0;
1531
1532 //Read id
1533         cfread(id, sizeof(char)*4, 1, fp);
1534         if ( memcmp( id, dgss_id, 4 )) {
1535                 cfclose(fp);
1536                 return 0;
1537         }
1538
1539 //Read version
1540         cfread(&version, sizeof(int), 1, fp);
1541         if (version < STATE_COMPATIBLE_VERSION) {
1542                 cfclose(fp);
1543                 return 0;
1544         }
1545
1546 // Read description
1547         cfread(desc, sizeof(char)*DESC_LENGTH, 1, fp);
1548
1549 // Skip the current screen shot...
1550         cfseek(fp, THUMBNAIL_W*THUMBNAIL_H, SEEK_CUR);
1551
1552 // And now...skip the palette stuff that somebody forgot to add
1553         cfseek(fp, 768, SEEK_CUR);
1554
1555 // Read the Between levels flag...
1556         cfread(&between_levels, sizeof(int), 1, fp);
1557
1558         Assert(between_levels == 0);    //between levels save ripped out
1559
1560 // Read the mission info...
1561         cfread(mission, sizeof(char), 9, fp);
1562 //Read level info
1563         cfread(&dumbint, sizeof(int), 1, fp);
1564         cfread(&dumbint, sizeof(int), 1, fp);
1565
1566 //Restore GameTime
1567         cfread(&dumbint, sizeof(fix), 1, fp);
1568
1569         cfread(&state_game_id, sizeof(int), 1, fp);
1570
1571         return (state_game_id);
1572  }
1573
1574 #if defined(POLY_ACC)
1575 //void screen_shot_pa(ubyte *dst,ushort *src)
1576 //{
1577 //    //ushort *src = pa_get_buffer_address(0),
1578 //    ushort *s;
1579 //    fix u, v, du, dv;
1580 //    int ui, w, h;
1581 //
1582 //    pa_flush();
1583 //
1584 //    du = (640.0 / (float)THUMBNAIL_W) * 65536.0;
1585 //    dv = (480.0 / (float)THUMBNAIL_H) * 65536.0;
1586 //
1587 //    for(v = h = 0; h != THUMBNAIL_H; ++h)
1588 //    {
1589 //        s = src + f2i(v) * 640;
1590 //        v += dv;
1591 //        for(u = w = 0; w != THUMBNAIL_W; ++w)
1592 //        {
1593 //            ui = f2i(u);
1594 //            *dst++ = gr_find_closest_color((s[ui] >> 9) & 0x3e, (s[ui] >> 4) & 0x3e, (s[ui] << 1) & 0x3e);
1595 //            u += du;
1596 //        }
1597 //    }
1598 //}
1599
1600 void screen_shot_pa(grs_canvas *dcanv,grs_canvas *scanv)
1601 {
1602 #if !defined(MACINTOSH)
1603         ubyte *dst;
1604         ushort *src;
1605         int x,y;
1606
1607         Assert(scanv->cv_w == dcanv->cv_w && scanv->cv_h == dcanv->cv_h);
1608
1609         pa_flush();
1610
1611         src = (ushort *) scanv->cv_bitmap.bm_data;
1612         dst = dcanv->cv_bitmap.bm_data;
1613
1614         #ifdef PA_3DFX_VOODOO
1615    src=(ushort *)pa_set_back_to_read();
1616         #endif
1617
1618         for (y=0; y<scanv->cv_h; y++) {
1619                 for (x=0; x<scanv->cv_w; x++) {
1620                         #ifdef PA_3DFX_VOODOO
1621                         *dst++ = gr_find_closest_color((*src >> 10) & 0x3e, (*src >> 5) & 0x3f, (*src << 1) & 0x3e);
1622                         #else
1623                         *dst++ = gr_find_closest_color((*src >> 9) & 0x3e, (*src >> 4) & 0x3e, (*src << 1) & 0x3e);
1624                         #endif
1625
1626                         src++;
1627                 }
1628                 src = (ushort *) (((ubyte *) src) + (scanv->cv_bitmap.bm_rowsize - (scanv->cv_bitmap.bm_w*PA_BPP)));
1629                 dst += dcanv->cv_bitmap.bm_rowsize - dcanv->cv_bitmap.bm_w;
1630         }
1631         #ifdef PA_3DFX_VOODOO
1632         pa_set_front_to_read();
1633         #endif
1634 #endif
1635 }
1636 #endif
1637