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