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