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