]> icculus.org git repositories - btb/d2x.git/blob - main/state.c
prevent overflow of line buffer
[btb/d2x.git] / main / state.c
1 /* $Id: state.c,v 1.27 2006-07-24 08:20:39 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 //-------------------------------------------------------------------
173 void state_callback(int nitems,newmenu_item * items, int * last_key, int citem)
174 {
175         nitems = nitems;
176         last_key = last_key;
177         
178 //      if ( sc_last_item != citem )    {
179 //              sc_last_item = citem;
180                 if ( citem > 0 )        {
181                         if ( sc_bmp[citem-1] )  {
182                                 if (MenuHires) {
183                                         grs_canvas *save_canv = grd_curcanv;
184                                         grs_canvas *temp_canv = gr_create_canvas(THUMBNAIL_W*2,(THUMBNAIL_H*24/10));
185                                         grs_point vertbuf[3] = {{0,0}, {0,0}, {i2f(THUMBNAIL_W*2),i2f(THUMBNAIL_H*24/10)} };
186                                         gr_set_current_canvas(temp_canv);
187                                         scale_bitmap(sc_bmp[citem-1], vertbuf, 0 );
188                                         gr_set_current_canvas( save_canv );
189                                         gr_bitmap( (grd_curcanv->cv_bitmap.bm_w-THUMBNAIL_W*2)/2,items[0].y-10, &temp_canv->cv_bitmap);
190                                         gr_free_canvas(temp_canv);
191                                 }
192                                 else    {
193                                         gr_bitmap( (grd_curcanv->cv_bitmap.bm_w-THUMBNAIL_W)/2,items[0].y-5, sc_bmp[citem-1] );
194                                 }
195                         }
196                 }
197 //      }       
198 }
199
200 void rpad_string( char * string, int max_chars )
201 {
202         int i, end_found;
203
204         end_found = 0;
205         for( i=0; i<max_chars; i++ )    {
206                 if ( *string == 0 )
207                         end_found = 1;
208                 if ( end_found )
209                         *string = ' ';
210                 string++;
211         }
212         *string = 0;            // NULL terminate
213 }
214
215 int state_get_save_file(char * fname, char * dsc, int multi, int blind_save)
216 {
217         PHYSFS_file *fp;
218         int i, choice, version;
219         newmenu_item m[NUM_SAVES+2];
220         char filename[NUM_SAVES+1][30];
221         char desc[NUM_SAVES+1][DESC_LENGTH+16];
222         char id[5];
223         int valid=0;
224         
225         for (i=0;i<NUM_SAVES; i++ )     {
226                 sc_bmp[i] = NULL;
227                 if ( !multi )
228                         #ifndef MACINTOSH
229                         sprintf( filename[i], "%s.sg%x", Players[Player_num].callsign, i );
230                         #else
231                         sprintf( filename[i], ":Players:%s.sg%x", Players[Player_num].callsign, i );
232                         #endif
233                 else
234                         #ifndef MACINTOSH
235                         sprintf( filename[i], "%s.mg%x", Players[Player_num].callsign, i );
236                         #else
237                         sprintf( filename[i], ":Players:%s.mg%x", Players[Player_num].callsign, i );
238                         #endif
239                 valid = 0;
240                 fp = PHYSFSX_openReadBuffered(filename[i]);
241                 if ( fp ) {
242                         //Read id
243                         //FIXME: check for swapped file, react accordingly...
244                         PHYSFS_read(fp, id, sizeof(char) * 4, 1);
245                         if ( !memcmp( id, dgss_id, 4 )) {
246                                 //Read version
247                                 PHYSFS_read(fp, &version, sizeof(int), 1);
248                                 if (version >= STATE_COMPATIBLE_VERSION)        {
249                                         // Read description
250                                         PHYSFS_read(fp, desc[i], sizeof(char) * DESC_LENGTH, 1);
251                                         //rpad_string( desc[i], DESC_LENGTH-1 );
252                                         // Read thumbnail
253                                         //sc_bmp[i] = gr_create_bitmap(THUMBNAIL_W,THUMBNAIL_H );
254                                         //PHYSFS_read(fp, sc_bmp[i]->bm_data, THUMBNAIL_W * THUMBNAIL_H, 1);
255                                         valid = 1;
256                                 }
257                         } 
258                         PHYSFS_close(fp);
259                 }
260                 if (!valid) {
261                         strcpy( desc[i], TXT_EMPTY );
262                         //rpad_string( desc[i], DESC_LENGTH-1 );
263                 }
264                 m[i].type = NM_TYPE_INPUT_MENU; m[i].text = desc[i]; m[i].text_len = DESC_LENGTH-1;
265         }
266
267         sc_last_item = -1;
268         if (blind_save && state_default_item >= 0)
269                 choice = state_default_item;
270         else
271                 choice = newmenu_do1(NULL, "Save Game", NUM_SAVES, m, NULL, state_default_item);
272
273         for (i=0; i<NUM_SAVES; i++ )    {
274                 if ( sc_bmp[i] )
275                         gr_free_bitmap( sc_bmp[i] );
276         }
277
278         if (choice > -1) {
279                 strcpy( fname, filename[choice] );
280                 strcpy( dsc, desc[choice] );
281                 state_default_item = choice;
282                 return choice+1;
283         }
284         return 0;
285 }
286
287 int RestoringMenu=0;
288 extern int Current_display_mode;
289
290 int state_get_restore_file(char * fname, int multi)
291 {
292         PHYSFS_file *fp;
293         int i, choice, version, nsaves;
294         newmenu_item m[NUM_SAVES+2];
295         char filename[NUM_SAVES+1][30];
296         char desc[NUM_SAVES+1][DESC_LENGTH + 16];
297         char id[5];
298         int valid;
299
300         nsaves=0;
301         m[0].type = NM_TYPE_TEXT; m[0].text = "\n\n\n\n";       
302         for (i=0;i<NUM_SAVES+1; i++ )   {
303                 sc_bmp[i] = NULL;
304                 if (!multi)
305                         #ifndef MACINTOSH
306                         sprintf( filename[i], "%s.sg%x", Players[Player_num].callsign, i );
307                         #else
308                         sprintf( filename[i], ":Players:%s.sg%x", Players[Player_num].callsign, i );
309                         #endif
310                 else
311                         #ifndef MACINTOSH
312                         sprintf( filename[i], "%s.mg%x", Players[Player_num].callsign, i );
313                         #else
314                         sprintf( filename[i], ":Players:%s.mg%x", Players[Player_num].callsign, i );
315                         #endif
316                 valid = 0;
317                 fp = PHYSFSX_openReadBuffered(filename[i]);
318                 if ( fp ) {
319                         //Read id
320                         //FIXME: check for swapped file, react accordingly...
321                         PHYSFS_read(fp, id, sizeof(char) * 4, 1);
322                         if ( !memcmp( id, dgss_id, 4 )) {
323                                 //Read version
324                                 PHYSFS_read(fp, &version, sizeof(int), 1);
325                                 if (version >= STATE_COMPATIBLE_VERSION)        {
326                                         // Read description
327                                         PHYSFS_read(fp, desc[i], sizeof(char) * DESC_LENGTH, 1);
328                                         //rpad_string( desc[i], DESC_LENGTH-1 );
329                                         m[i+1].type = NM_TYPE_MENU; m[i+1].text = desc[i];
330                                         // Read thumbnail
331                                         sc_bmp[i] = gr_create_bitmap(THUMBNAIL_W,THUMBNAIL_H );
332                                         PHYSFS_read(fp, sc_bmp[i]->bm_data, THUMBNAIL_W * THUMBNAIL_H, 1);
333                                         if (version >= 9) {
334                                                 ubyte pal[256*3];
335                                                 PHYSFS_read(fp, pal, 3, 256);
336                                                 gr_remap_bitmap_good( sc_bmp[i], pal, -1, -1 );
337                                         }
338                                         nsaves++;
339                                         valid = 1;
340                                 }
341                         }
342                         PHYSFS_close(fp);
343                 }
344                 if (!valid) {
345                         strcpy( desc[i], TXT_EMPTY );
346                         //rpad_string( desc[i], DESC_LENGTH-1 );
347                         m[i+1].type = NM_TYPE_TEXT; m[i+1].text = desc[i];
348                 }
349         }
350
351         if ( nsaves < 1 )       {
352                 nm_messagebox( NULL, 1, "Ok", "No saved games were found!" );
353                 return 0;
354         }
355
356         if (Current_display_mode == 3)  //restore menu won't fit on 640x400
357                 VR_screen_flags ^= VRF_COMPATIBLE_MENUS;
358
359         sc_last_item = -1;
360
361 #if defined(WINDOWS) || defined(MACINTOSH)
362         Hack_DblClick_MenuMode = 1;
363 #endif
364
365    RestoringMenu=1;
366         choice = newmenu_do3( NULL, "Select Game to Restore", NUM_SAVES+2, m, state_callback, state_default_item+1, NULL, 190, -1 );
367    RestoringMenu=0;
368
369 #if defined(WINDOWS) || defined(MACINTOSH)
370         Hack_DblClick_MenuMode = 0;
371 #endif
372
373         if (Current_display_mode == 3)  //set flag back
374                 VR_screen_flags ^= VRF_COMPATIBLE_MENUS;
375
376
377         for (i=0; i<NUM_SAVES+1; i++ )  {
378                 if ( sc_bmp[i] )
379                         gr_free_bitmap( sc_bmp[i] );
380         }
381
382         if (choice > 0) {
383                 strcpy( fname, filename[choice-1] );
384                 if (choice != NUM_SAVES+1)              //no new default when restore from autosave
385                         state_default_item = choice - 1;
386                 return choice;
387         }
388         return 0;
389 }
390
391 #define DESC_OFFSET     8
392
393 //      -----------------------------------------------------------------------------------
394 //      Imagine if C had a function to copy a file...
395 int copy_file(char *old_file, char *new_file)
396 {
397         sbyte   *buf;
398         int             buf_size;
399         PHYSFS_file *in_file, *out_file;
400
401         out_file = PHYSFS_openWrite(new_file);
402
403         if (out_file == NULL)
404                 return -1;
405
406         in_file = PHYSFS_openRead(old_file);
407
408         if (in_file == NULL)
409                 return -2;
410
411         buf_size = PHYSFS_fileLength(in_file);
412         while (buf_size && !(buf = d_malloc(buf_size)))
413                 buf_size /= 2;
414         if (buf_size == 0)
415                 return -5;      // likely to be an empty file
416
417         while (!PHYSFS_eof(in_file))
418         {
419                 int bytes_read;
420
421                 bytes_read = PHYSFS_read(in_file, buf, 1, buf_size);
422                 if (bytes_read < 0)
423                         Error("Cannot read from file <%s>: %s", old_file, PHYSFS_getLastError());
424
425                 Assert(bytes_read == buf_size || PHYSFS_eof(in_file));
426
427                 if (PHYSFS_write(out_file, buf, 1, bytes_read) < bytes_read)
428                         Error("Cannot write to file <%s>: %s", new_file, PHYSFS_getLastError());
429         }
430
431         d_free(buf);
432
433         if (!PHYSFS_close(in_file))
434         {
435                 PHYSFS_close(out_file);
436                 return -3;
437         }
438
439         if (!PHYSFS_close(out_file))
440                 return -4;
441
442         return 0;
443 }
444
445 #ifndef MACINTOSH
446 #define SECRETB_FILENAME        "secret.sgb"
447 #define SECRETC_FILENAME        "secret.sgc"
448 #else
449 #define SECRETB_FILENAME        ":Players:secret.sgb"
450 #define SECRETC_FILENAME        ":Players:secret.sgc"
451 #endif
452
453 extern int Final_boss_is_dead;
454
455 //      -----------------------------------------------------------------------------------
456 //      blind_save means don't prompt user for any info.
457 int state_save_all(int between_levels, int secret_save, char *filename_override, int blind_save)
458 {
459         int     rval, filenum = -1;
460
461         char    filename[128], desc[DESC_LENGTH+1];
462
463         Assert(between_levels == 0);    //between levels save ripped out
464
465 #ifdef NETWORK
466         if ( Game_mode & GM_MULTI )     {
467                         multi_initiate_save_game();
468                 return 0;
469         }
470 #endif
471
472         if ((Current_level_num < 0) && (secret_save == 0)) {
473                 HUD_init_message( "Can't save in secret level!" );
474                 return 0;
475         }
476
477         if (Final_boss_is_dead)         //don't allow save while final boss is dying
478                 return 0;
479
480         mprintf(( 0, "CL=%d, NL=%d\n", Current_level_num, Next_level_num ));
481         
482         //      If this is a secret save and the control center has been destroyed, don't allow
483         //      return to the base level.
484         if (secret_save && (Control_center_destroyed)) {
485                 mprintf((0, "Deleting secret.sgb so player can't return to base level.\n"));
486                 PHYSFS_delete(SECRETB_FILENAME);
487                 return 0;
488         }
489
490         stop_time();
491
492         if (secret_save == 1) {
493                 filename_override = filename;
494                 sprintf(filename_override, SECRETB_FILENAME);
495         } else if (secret_save == 2) {
496                 filename_override = filename;
497                 sprintf(filename_override, SECRETC_FILENAME);
498         } else {
499                 if (filename_override) {
500                         strcpy( filename, filename_override);
501                         sprintf(desc, "[autosave backup]");
502                 }
503                 else if (!(filenum = state_get_save_file(filename, desc, 0, blind_save)))
504                 {
505                         start_time();
506                         return 0;
507                 }
508         }
509                 
510         //      MK, 1/1/96
511         //      If not in multiplayer, do special secret level stuff.
512         //      If secret.sgc exists, then copy it to Nsecret.sgc (where N = filenum).
513         //      If it doesn't exist, then delete Nsecret.sgc
514         if (!secret_save && !(Game_mode & GM_MULTI)) {
515                 int     rval;
516                 char    temp_fname[32], fc;
517
518                 if (filenum != -1) {
519
520                         if (filenum >= 10)
521                                 fc = (filenum-10) + 'a';
522                         else
523                                 fc = '0' + filenum;
524
525                         #ifndef MACINTOSH
526                         sprintf(temp_fname, "%csecret.sgc", fc);
527                         #else
528                         sprintf(temp_fname, ":Players:%csecret.sgc", fc);
529                         #endif
530
531                         mprintf((0, "Trying to copy secret.sgc to %s.\n", temp_fname));
532
533                         if (PHYSFS_exists(temp_fname))
534                         {
535                                 mprintf((0, "Deleting file %s\n", temp_fname));
536                                 if (!PHYSFS_delete(temp_fname))
537                                         Error("Cannot delete file <%s>: %s", temp_fname, PHYSFS_getLastError());
538                         }
539
540                         if (PHYSFS_exists(SECRETC_FILENAME))
541                         {
542                                 mprintf((0, "Copying secret.sgc to %s.\n", temp_fname));
543                                 rval = copy_file(SECRETC_FILENAME, temp_fname);
544                                 Assert(rval == 0);      //      Oops, error copying secret.sgc to temp_fname!
545                         }
546                 }
547         }
548
549         //      Save file we're going to save over in last slot and call "[autosave backup]"
550         if (!filename_override) {
551                 PHYSFS_file *tfp;
552
553                 tfp = PHYSFSX_openWriteBuffered(filename);
554
555                 if ( tfp ) {
556                         char    newname[128];
557
558                         #ifndef MACINTOSH
559                         sprintf( newname, "%s.sg%x", Players[Player_num].callsign, NUM_SAVES );
560                         #else
561                         sprintf(newname, "Players/%s.sg%x", Players[Player_num].callsign, NUM_SAVES);
562                         #endif
563
564                         PHYSFS_seek(tfp, DESC_OFFSET);
565                         PHYSFS_write(tfp, "[autosave backup]", sizeof(char) * DESC_LENGTH, 1);
566                         PHYSFS_close(tfp);
567                         PHYSFS_delete(newname);
568                         PHYSFSX_rename(filename, newname);
569                 }
570         }
571         
572         rval = state_save_all_sub(filename, desc, between_levels);
573         if (rval && !secret_save)
574                 HUD_init_message("Game saved.");
575
576         return rval;
577 }
578
579 extern  fix     Flash_effect, Time_flash_last_played;
580
581
582 int state_save_all_sub(char *filename, char *desc, int between_levels)
583 {
584         int i,j;
585         PHYSFS_file *fp;
586         grs_canvas * cnv;
587         ubyte *pal;
588
589         Assert(between_levels == 0);    //between levels save ripped out
590
591 /*      if ( Game_mode & GM_MULTI )     {
592                 {
593                 start_time();
594                 return 0;
595                 }
596         }*/
597
598         #if defined(MACINTOSH) && !defined(NDEBUG)
599         if ( strncmp(filename, ":Players:", 9) )
600                 Int3();
601         #endif
602
603         fp = PHYSFSX_openWriteBuffered(filename);
604         if ( !fp ) {
605                 if ( !(Game_mode & GM_MULTI) )
606                         nm_messagebox(NULL, 1, TXT_OK, "Error writing savegame.\nPossibly out of disk\nspace.");
607                 start_time();
608                 return 0;
609         }
610
611 //Save id
612         PHYSFS_write(fp, dgss_id, sizeof(char) * 4, 1);
613
614 //Save version
615         i = STATE_VERSION;
616         PHYSFS_write(fp, &i, sizeof(int), 1);
617
618 //Save description
619         PHYSFS_write(fp, desc, sizeof(char) * DESC_LENGTH, 1);
620         
621 // Save the current screen shot...
622
623         cnv = gr_create_canvas( THUMBNAIL_W, THUMBNAIL_H );
624         if ( cnv )
625         {
626 #ifdef OGL
627                 ubyte *buf;
628                 int k;
629                 GLint gl_draw_buffer;
630 #endif
631                 grs_canvas * cnv_save;
632                 cnv_save = grd_curcanv;
633
634                 gr_set_current_canvas( cnv );
635
636                 render_frame(0, 0);
637
638 #if defined(OGL)
639 # if 1
640                 buf = d_malloc(THUMBNAIL_W * THUMBNAIL_H * 3);
641                 glGetIntegerv(GL_DRAW_BUFFER, &gl_draw_buffer);
642                 glReadBuffer(gl_draw_buffer);
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         short TempTmapNum[MAX_SEGMENTS][MAX_SIDES_PER_SEGMENT];
1002         short TempTmapNum2[MAX_SEGMENTS][MAX_SIDES_PER_SEGMENT];
1003
1004         #if defined(MACINTOSH) && !defined(NDEBUG)
1005         if (strncmp(filename, "Players/", 9))
1006                 Int3();
1007         #endif
1008
1009         fp = PHYSFSX_openReadBuffered(filename);
1010         if ( !fp ) return 0;
1011
1012 //Read id
1013         //FIXME: check for swapped file, react accordingly...
1014         PHYSFS_read(fp, id, sizeof(char) * 4, 1);
1015         if ( memcmp( id, dgss_id, 4 )) {
1016                 PHYSFS_close(fp);
1017                 return 0;
1018         }
1019
1020 //Read version
1021         PHYSFS_read(fp, &version, sizeof(int), 1);
1022         if (version < STATE_COMPATIBLE_VERSION) {
1023                 PHYSFS_close(fp);
1024                 return 0;
1025         }
1026
1027 // Read description
1028         PHYSFS_read(fp, desc, sizeof(char) * DESC_LENGTH, 1);
1029
1030 // Skip the current screen shot...
1031         PHYSFS_seek(fp, PHYSFS_tell(fp) + THUMBNAIL_W * THUMBNAIL_H);
1032
1033 // And now...skip the goddamn palette stuff that somebody forgot to add
1034         PHYSFS_seek(fp, PHYSFS_tell(fp) + 768);
1035
1036 // Read the Between levels flag...
1037         PHYSFS_read(fp, &between_levels, sizeof(int), 1);
1038
1039         Assert(between_levels == 0);    //between levels save ripped out
1040
1041 // Read the mission info...
1042         PHYSFS_read(fp, mission, sizeof(char) * 9, 1);
1043         mprintf ((0,"Missionname to load = %s\n",mission));
1044
1045         if (!load_mission_by_name( mission ))   {
1046                 nm_messagebox( NULL, 1, "Ok", "Error!\nUnable to load mission\n'%s'\n", mission );
1047                 PHYSFS_close(fp);
1048                 return 0;
1049         }
1050
1051 //Read level info
1052         PHYSFS_read(fp, &current_level, sizeof(int), 1);
1053         PHYSFS_read(fp, &next_level, sizeof(int), 1);
1054
1055 //Restore GameTime
1056         PHYSFS_read(fp, &GameTime, sizeof(fix), 1);
1057
1058 // Start new game....
1059         if (!multi)     {
1060                 Game_mode = GM_NORMAL;
1061                 Function_mode = FMODE_GAME;
1062 #ifdef NETWORK
1063                 change_playernum_to(0);
1064 #endif
1065                 strcpy( org_callsign, Players[0].callsign );
1066                 N_players = 1;
1067                 if (!secret_restore) {
1068                         InitPlayerObject();                             //make sure player's object set up
1069                         init_player_stats_game();               //clear all stats
1070                 }
1071         } else {
1072                 strcpy( org_callsign, Players[Player_num].callsign );
1073         }
1074
1075 #ifdef NETWORK
1076    if (Game_mode & GM_MULTI)
1077          {
1078                 PHYSFS_read(fp, &state_game_id, sizeof(int), 1);
1079                 PHYSFS_read(fp, &Netgame, sizeof(netgame_info), 1);
1080                 PHYSFS_read(fp, &NetPlayers, sizeof(AllNetPlayers_info), 1);
1081                 PHYSFS_read(fp, &nplayers, sizeof(N_players), 1);
1082                 PHYSFS_read(fp, &Player_num, sizeof(Player_num), 1);
1083                 for (i=0;i<nplayers;i++)
1084                         PHYSFS_read(fp, &restore_players[i], sizeof(player), 1);
1085 #ifdef RISKY_PROPOSITION
1086                 PHYSFS_read(fp, &robot_controlled[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1087                 PHYSFS_read(fp, &robot_agitation[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1088                 PHYSFS_read(fp, &robot_controlled_time[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1089                 PHYSFS_read(fp, &robot_last_send_time[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1090                 PHYSFS_read(fp, &robot_last_message_time[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1091                 PHYSFS_read(fp, &robot_send_pending[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1092                 PHYSFS_read(fp, &robot_fired[0], 4 * MAX_ROBOTS_CONTROLLED, 1);
1093
1094       for (i=0;i<MAX_ROBOTS_CONTROLLED;i++)
1095                         PHYSFS_read(fp, &robot_fire_buf[i][0],21,1);
1096 #endif
1097
1098            for (i=0;i<nplayers;i++)
1099                  {
1100                   found=0;
1101                   for (j=0;j<nplayers;j++)
1102                          {
1103            if ((!strcmp (restore_players[i].callsign,Players[j].callsign)) && Players[j].connected==1)
1104                                  found=1;
1105                          }
1106                   restore_players[i].connected=found;
1107             }
1108                 memcpy (&Players,&restore_players,sizeof(player)*nplayers);
1109                 N_players=nplayers;
1110
1111       if (network_i_am_master())
1112                  {
1113                   for (i=0;i<N_players;i++)
1114                         {
1115                          if (i==Player_num)
1116                                 continue;
1117                  Players[i].connected=0;
1118                         }
1119                  }
1120
1121                 //Viewer = ConsoleObject = &Objects[Players[Player_num].objnum];
1122          }
1123
1124 #endif
1125
1126 //Read player info
1127
1128         {
1129                 StartNewLevelSub(current_level, 1, secret_restore);
1130
1131                 if (secret_restore) {
1132                         player  dummy_player;
1133
1134                         PHYSFS_read(fp, &dummy_player, sizeof(player), 1);
1135                         if (secret_restore == 1) {              //      This means he didn't die, so he keeps what he got in the secret level.
1136                                 Players[Player_num].level = dummy_player.level;
1137                                 Players[Player_num].last_score = dummy_player.last_score;
1138                                 Players[Player_num].time_level = dummy_player.time_level;
1139
1140                                 Players[Player_num].num_robots_level = dummy_player.num_robots_level;
1141                                 Players[Player_num].num_robots_total = dummy_player.num_robots_total;
1142                                 Players[Player_num].hostages_rescued_total = dummy_player.hostages_rescued_total;
1143                                 Players[Player_num].hostages_total = dummy_player.hostages_total;
1144                                 Players[Player_num].hostages_on_board = dummy_player.hostages_on_board;
1145                                 Players[Player_num].hostages_level = dummy_player.hostages_level;
1146                                 Players[Player_num].homing_object_dist = dummy_player.homing_object_dist;
1147                                 Players[Player_num].hours_level = dummy_player.hours_level;
1148                                 Players[Player_num].hours_total = dummy_player.hours_total;
1149                                 do_cloak_invul_secret_stuff(old_gametime);
1150                         } else {
1151                                 Players[Player_num] = dummy_player;
1152                         }
1153                 } else {
1154                         PHYSFS_read(fp, &Players[Player_num], sizeof(player), 1);
1155                 }
1156         }
1157         strcpy( Players[Player_num].callsign, org_callsign );
1158
1159 // Set the right level
1160         if ( between_levels )
1161                 Players[Player_num].level = next_level;
1162
1163 // Restore the weapon states
1164         PHYSFS_read(fp, &Primary_weapon, sizeof(sbyte), 1);
1165         PHYSFS_read(fp, &Secondary_weapon, sizeof(sbyte), 1);
1166
1167         select_weapon(Primary_weapon, 0, 0, 0);
1168         select_weapon(Secondary_weapon, 1, 0, 0);
1169
1170 // Restore the difficulty level
1171         PHYSFS_read(fp, &Difficulty_level, sizeof(int), 1);
1172
1173 // Restore the cheats enabled flag
1174
1175         PHYSFS_read(fp, &Cheats_enabled, sizeof(int),1);
1176
1177         if ( !between_levels )  {
1178                 Do_appearance_effect = 0;                       // Don't do this for middle o' game stuff.
1179
1180                 ObjectStartLocation = PHYSFS_tell(fp);
1181                 //Clear out all the objects from the lvl file
1182                 for (segnum=0; segnum <= Highest_segment_index; segnum++)
1183                         Segments[segnum].objects = -1;
1184                 reset_objects(1);
1185         
1186                 //Read objects, and pop 'em into their respective segments.
1187                 PHYSFS_read(fp, &i, sizeof(int), 1);
1188                 Highest_object_index = i-1;
1189                 PHYSFS_read(fp, Objects, sizeof(object) * i, 1);
1190         
1191                 Object_next_signature = 0;
1192                 for (i=0; i<=Highest_object_index; i++ )        {
1193                         obj = &Objects[i];
1194                         obj->rtype.pobj_info.alt_textures = -1;
1195                         segnum = obj->segnum;
1196                         obj->next = obj->prev = obj->segnum = -1;
1197                         if ( obj->type != OBJ_NONE )    {
1198                                 obj_link(i,segnum);
1199                                 if ( obj->signature > Object_next_signature )
1200                                         Object_next_signature = obj->signature;
1201                         }
1202
1203                         //look for, and fix, boss with bogus shields
1204                         if (obj->type == OBJ_ROBOT && Robot_info[obj->id].boss_flag) {
1205                                 fix save_shields = obj->shields;
1206
1207                                 copy_defaults_to_robot(obj);            //calculate starting shields
1208
1209                                 //if in valid range, use loaded shield value
1210                                 if (save_shields > 0 && save_shields <= obj->shields)
1211                                         obj->shields = save_shields;
1212                                 else
1213                                         obj->shields /= 2;  //give player a break
1214                         }
1215
1216                 }       
1217                 special_reset_objects();
1218                 Object_next_signature++;
1219         
1220                 //      1 = Didn't die on secret level.
1221                 //      2 = Died on secret level.
1222                 if (secret_restore && (Current_level_num >= 0)) {
1223                         set_pos_from_return_segment();
1224                         if (secret_restore == 2)
1225                                 init_player_stats_new_ship();
1226                 }
1227
1228                 //Restore wall info
1229                 PHYSFS_read(fp, &i, sizeof(int), 1);
1230                 Num_walls = i;
1231                 PHYSFS_read(fp, Walls, sizeof(wall), Num_walls);
1232
1233                 //now that we have the walls, check if any sounds are linked to
1234                 //walls that are now open
1235                 for (i=0;i<Num_walls;i++) {
1236                         if (Walls[i].type == WALL_OPEN)
1237                                 digi_kill_sound_linked_to_segment(Walls[i].segnum,Walls[i].sidenum,-1); //-1 means kill any sound
1238                 }
1239
1240                 //Restore exploding wall info
1241                 if (version >= 10) {
1242                         PHYSFS_read(fp, &i, sizeof(int), 1);
1243                         PHYSFS_read(fp, expl_wall_list, sizeof(*expl_wall_list), i);
1244                 }
1245
1246                 //Restore door info
1247                 PHYSFS_read(fp, &i, sizeof(int), 1);
1248                 Num_open_doors = i;
1249                 PHYSFS_read(fp, ActiveDoors, sizeof(active_door), Num_open_doors);
1250         
1251                 if (version >= 14) {            //Restore cloaking wall info
1252                         PHYSFS_read(fp, &i, sizeof(int), 1);
1253                         Num_cloaking_walls = i;
1254                         PHYSFS_read(fp, CloakingWalls, sizeof(cloaking_wall), Num_cloaking_walls);
1255                 }
1256         
1257                 //Restore trigger info
1258                 PHYSFS_read(fp, &Num_triggers, sizeof(int), 1);
1259                 PHYSFS_read(fp, Triggers, sizeof(trigger), Num_triggers);
1260         
1261                 //Restore tmap info (to temp values so we can use compiled-in tmap info to compute static_light)
1262                 for (i=0; i<=Highest_segment_index; i++ )       {
1263                         for (j=0; j<6; j++ )    {
1264                                 PHYSFS_read(fp, &Segments[i].sides[j].wall_num, sizeof(short), 1);
1265                                 PHYSFS_read(fp, &TempTmapNum[i][j], sizeof(short), 1);
1266                                 PHYSFS_read(fp, &TempTmapNum2[i][j], sizeof(short), 1);
1267                         }
1268                 }
1269         
1270                 //Restore the fuelcen info
1271                 PHYSFS_read(fp, &Control_center_destroyed, sizeof(int), 1);
1272                 PHYSFS_read(fp, &Countdown_timer, sizeof(int), 1);
1273                 PHYSFS_read(fp, &Num_robot_centers, sizeof(int), 1);
1274                 PHYSFS_read(fp, RobotCenters, sizeof(matcen_info), Num_robot_centers);
1275                 PHYSFS_read(fp, &ControlCenterTriggers, sizeof(control_center_triggers), 1);
1276                 PHYSFS_read(fp, &Num_fuelcenters, sizeof(int), 1);
1277                 PHYSFS_read(fp, Station, sizeof(FuelCenter), Num_fuelcenters);
1278         
1279                 // Restore the control cen info
1280                 PHYSFS_read(fp, &Control_center_been_hit, sizeof(int), 1);
1281                 PHYSFS_read(fp, &Control_center_player_been_seen, sizeof(int), 1);
1282                 PHYSFS_read(fp, &Control_center_next_fire_time, sizeof(int), 1);
1283                 PHYSFS_read(fp, &Control_center_present, sizeof(int), 1);
1284                 PHYSFS_read(fp, &Dead_controlcen_object_num, sizeof(int), 1);
1285         
1286                 // Restore the AI state
1287                 ai_restore_state( fp, version );
1288         
1289                 // Restore the automap visited info
1290                 PHYSFS_read(fp, Automap_visited, sizeof(ubyte), MAX_SEGMENTS);
1291
1292                 //      Restore hacked up weapon system stuff.
1293                 Fusion_next_sound_time = GameTime;
1294                 Auto_fire_fusion_cannon_time = 0;
1295                 Next_laser_fire_time = GameTime;
1296                 Next_missile_fire_time = GameTime;
1297                 Last_laser_fired_time = GameTime;
1298
1299         }
1300         state_game_id = 0;
1301
1302         if ( version >= 7 )     {
1303                 PHYSFS_read(fp, &state_game_id, sizeof(uint), 1);
1304                 PHYSFS_read(fp, &Laser_rapid_fire, sizeof(int), 1);
1305                 PHYSFS_read(fp, &Lunacy, sizeof(int), 1);               //      Yes, writing this twice.  Removed the Ugly robot system, but didn't want to change savegame format.
1306                 PHYSFS_read(fp, &Lunacy, sizeof(int), 1);
1307                 if ( Lunacy )
1308                         do_lunacy_on();
1309         }
1310
1311         if (version >= 17) {
1312                 PHYSFS_read(fp, MarkerObject, sizeof(MarkerObject), 1);
1313                 PHYSFS_read(fp, MarkerOwner, sizeof(MarkerOwner), 1);
1314                 PHYSFS_read(fp, MarkerMessage, sizeof(MarkerMessage), 1);
1315         }
1316         else {
1317                 int num,dummy;
1318
1319                 // skip dummy info
1320
1321                 PHYSFS_read(fp, &num,sizeof(int), 1);           // was NumOfMarkers
1322                 PHYSFS_read(fp, &dummy,sizeof(int), 1);         // was CurMarker
1323
1324                 PHYSFS_seek(fp, PHYSFS_tell(fp) + num * (sizeof(vms_vector) + 40));
1325
1326                 for (num=0;num<NUM_MARKERS;num++)
1327                         MarkerObject[num] = -1;
1328         }
1329
1330         if (version>=11) {
1331                 if (secret_restore != 1)
1332                         PHYSFS_read(fp, &Afterburner_charge, sizeof(fix), 1);
1333                 else {
1334                         fix     dummy_fix;
1335                         PHYSFS_read(fp, &dummy_fix, sizeof(fix), 1);
1336                 }
1337         }
1338         if (version>=12) {
1339                 //read last was super information
1340                 PHYSFS_read(fp, &Primary_last_was_super, sizeof(Primary_last_was_super), 1);
1341                 PHYSFS_read(fp, &Secondary_last_was_super, sizeof(Secondary_last_was_super), 1);
1342         }
1343
1344         if (version >= 12) {
1345                 PHYSFS_read(fp, &Flash_effect, sizeof(int), 1);
1346                 PHYSFS_read(fp, &Time_flash_last_played, sizeof(int), 1);
1347                 PHYSFS_read(fp, &PaletteRedAdd, sizeof(int), 1);
1348                 PHYSFS_read(fp, &PaletteGreenAdd, sizeof(int), 1);
1349                 PHYSFS_read(fp, &PaletteBlueAdd, sizeof(int), 1);
1350         } else {
1351                 Flash_effect = 0;
1352                 Time_flash_last_played = 0;
1353                 PaletteRedAdd = 0;
1354                 PaletteGreenAdd = 0;
1355                 PaletteBlueAdd = 0;
1356         }
1357
1358         //      Load Light_subtracted
1359         if (version >= 16) {
1360                 PHYSFS_read(fp, Light_subtracted, sizeof(Light_subtracted[0]), MAX_SEGMENTS);
1361                 apply_all_changed_light();
1362         } else {
1363                 int     i;
1364                 for (i=0; i<=Highest_segment_index; i++)
1365                         Light_subtracted[i] = 0;
1366         }
1367
1368         // static_light should now be computed - now actually set tmap info
1369         for (i=0; i<=Highest_segment_index; i++ )       {
1370                 for (j=0; j<6; j++ )    {
1371                         Segments[i].sides[j].tmap_num=TempTmapNum[i][j];
1372                         Segments[i].sides[j].tmap_num2=TempTmapNum2[i][j];
1373                 }
1374         }
1375
1376         if (!secret_restore) {
1377                 if (version >= 20) {
1378                         PHYSFS_read(fp, &First_secret_visit, sizeof(First_secret_visit), 1);
1379                         mprintf((0, "File: [%s] Read First_secret_visit: New value = %i\n", filename, First_secret_visit));
1380                 } else
1381                         First_secret_visit = 1;
1382         } else
1383                 First_secret_visit = 0;
1384
1385         if (version >= 22)
1386         {
1387                 if (secret_restore != 1)
1388                         PHYSFS_read(fp, &Omega_charge, sizeof(fix), 1);
1389                 else {
1390                         fix     dummy_fix;
1391                         PHYSFS_read(fp, &dummy_fix, sizeof(fix), 1);
1392                 }
1393         }
1394
1395         PHYSFS_close(fp);
1396
1397 #ifdef NETWORK
1398    if (Game_mode & GM_MULTI)   // Get rid of ships that aren't
1399          {                                                                       // connected in the restored game
1400                 for (i=0;i<nplayers;i++)
1401                  {
1402                   mprintf ((0,"Testing %s = %d\n",Players[i].callsign,Players[i].connected));
1403                   if (Players[i].connected!=1)
1404                    {
1405                     network_disconnect_player (i);
1406                create_player_appearance_effect(&Objects[Players[i].objnum]);
1407                          mprintf ((0,"Killing player ship %s!\n",Players[i].callsign));
1408               }
1409                  }
1410                         
1411          }
1412 #endif
1413
1414 // Load in bitmaps, etc..
1415 //!!    piggy_load_level_data();        //already done by StartNewLevelSub()
1416
1417         return 1;
1418 }
1419
1420
1421 int state_get_game_id(char *filename)
1422 {
1423         int version;
1424         PHYSFS_file *fp;
1425         int between_levels;
1426         char mission[16];
1427         char desc[DESC_LENGTH+1];
1428         char id[5];
1429         int dumbint;
1430
1431 mprintf((0, "Restoring multigame from [%s]\n", filename));
1432
1433         fp = PHYSFS_openRead(filename);
1434         if (!fp) return 0;
1435
1436 //Read id
1437         //FIXME: check for swapped file, react accordingly...
1438         PHYSFS_read(fp, id, sizeof(char) * 4, 1);
1439         if ( memcmp( id, dgss_id, 4 )) {
1440                 PHYSFS_close(fp);
1441                 return 0;
1442         }
1443
1444 //Read version
1445         PHYSFS_read(fp, &version, sizeof(int), 1);
1446         if (version < STATE_COMPATIBLE_VERSION) {
1447                 PHYSFS_close(fp);
1448                 return 0;
1449         }
1450
1451 // Read description
1452         PHYSFS_read(fp, desc, sizeof(char) * DESC_LENGTH, 1);
1453
1454 // Skip the current screen shot...
1455         PHYSFS_seek(fp, PHYSFS_tell(fp) + THUMBNAIL_W * THUMBNAIL_H);
1456
1457 // And now...skip the palette stuff that somebody forgot to add
1458         PHYSFS_seek(fp, PHYSFS_tell(fp) + 768);
1459
1460 // Read the Between levels flag...
1461         PHYSFS_read(fp, &between_levels, sizeof(int), 1);
1462
1463         Assert(between_levels == 0);    //between levels save ripped out
1464
1465 // Read the mission info...
1466         PHYSFS_read(fp, mission, sizeof(char) * 9, 1);
1467 //Read level info
1468         PHYSFS_read(fp, &dumbint, sizeof(int), 1);
1469         PHYSFS_read(fp, &dumbint, sizeof(int), 1);
1470
1471 //Restore GameTime
1472         PHYSFS_read(fp, &dumbint, sizeof(fix), 1);
1473
1474         PHYSFS_read(fp, &state_game_id, sizeof(int), 1);
1475
1476         return (state_game_id);
1477  }