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