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