File: sgstream.cpp

package info (click to toggle)
asc 2.4.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 75,080 kB
  • ctags: 24,943
  • sloc: cpp: 155,023; sh: 8,829; ansic: 6,890; makefile: 650; perl: 138
file content (523 lines) | stat: -rw-r--r-- 15,906 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/*! \file sgstream.cpp
    \brief The IO for many basic classes and structurs of ACS
   
    These routines are gradually being moved to become methods of their classes
*/


/*
    This file is part of Advanced Strategic Command; http://www.asc-hq.de
    Copyright (C) 1994-2005  Martin Bickel  and  Marc Schellenberger

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; see the file COPYING. If not, write to the
    Free Software Foundation, Inc., 59 Temple Place, Suite 330,
    Boston, MA  02111-1307  USA
*/



#include <cstdlib>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fstream>
#include <boost/regex.hpp>

#include "global.h"
#include "typen.h"
#include "basegfx.h"
#include "misc.h"
#include "sgstream.h"
#include "basestrm.h"
#include "palette.h"
#include "gameoptions.h"

#ifdef _WIN32_
 #include <direct.h>
 #include <windows.h>
 #include <winreg.h>
 #include <shlobj.h>
#endif 


const char* asc_EnvironmentName = "ASC_CONFIGFILE";
int dataVersion = 0;

const int object_version = 1;
const int technology_version = 1;




void loadpalette ( void )
{
   if ( ! asc_paletteloaded ) {
      displayLogMessage ( 4, "loading palette ... " );

      tnfilestream stream ("palette.pal", tnstream::reading);
      stream.readdata( & pal, sizeof(pal));
      colormixbufchar = new char [ sizeof ( tmixbuf ) ];
      colormixbuf = (pmixbuf) colormixbufchar;
      stream.readdata( colormixbuf,  sizeof ( *colormixbuf ));

      for ( int i= 0; i < 8; i++ ) {
         stream.readdata( &xlattables.xl[i], sizeof ( xlattables.a.dark05 ));
         xlattables.xl[i][255] = 255;
      }
/*
      stream.readdata( &xlattables.a.dark1,  sizeof ( xlattables.a.dark1 ));
      xlattables.a.dark1[255] = 255;

      stream.readdata( &xlattables.a.dark2,  sizeof ( xlattables.a.dark2 ));
      xlattables.a.dark2[255] = 255;

      stream.readdata( &xlattables.a.dark3,  sizeof ( xlattables.a.dark3 ));
      xlattables.a.dark3[255] = 255;

      stream.readdata( &xlattables.light,  sizeof ( xlattables.light ));
      xlattables.light[255] = 255;
  */
#ifdef use_truecolor2pal
      stream.readdata( &truecolor2pal_table,  sizeof ( truecolor2pal_table ));
      stream.readdata( &bi2asc_color_translation_table,  sizeof ( bi2asc_color_translation_table ));
#endif
      xlatpictgraytable = (ppixelxlattable) malloc( sizeof(*xlatpictgraytable) );
      // xlatpictgraytable = new tpixelxlattable;
      generategrayxlattable(xlatpictgraytable,160,16,&pal);

      (*xlatpictgraytable)[255] = 255;

      asc_paletteloaded = 1;
      displayLogMessage ( 4, "done\n" );
   }

}



ASCString resolvePath( ASCString path )
{
#ifdef WIN32
   static boost::regex exevar( "\\$\\(?EXEPATH\\)?", boost::regex::icase);
   path = boost::regex_replace( path, exevar, ConfigurationFileLocator::Instance().getExecutableLocation(), boost::regex_constants::format_literal );

   static boost::regex appdata( "\\$\\(?APPDATA\\)?", boost::regex::icase);
   path = boost::regex_replace( path, appdata, ConfigurationFileLocator::Instance().getSpecialPath( CSIDL_APPDATA ), boost::regex_constants::format_literal );

   static boost::regex commonappdata( "\\$\\(?COMMON_APPDATA\\)?", boost::regex::icase);
   path = boost::regex_replace( path, commonappdata, ConfigurationFileLocator::Instance().getSpecialPath( CSIDL_COMMON_APPDATA ), boost::regex_constants::format_literal );

   static boost::regex myDocs( "\\$\\(?MY_DOCUMENTS\\)?", boost::regex::icase);
   path = boost::regex_replace( path, myDocs, ConfigurationFileLocator::Instance().getSpecialPath( CSIDL_PERSONAL ), boost::regex_constants::format_literal );
#endif

   /*
   boost::smatch what;
   if ( boost::regex_match(path, what, exevar )) 
      return boost::regex_match( ConfigurationFileLocator::Instance().getExecutableLocation() + "\\";

   static boost::regex appdata( "\\$\\(?APPDATA\\)?", boost::regex::icase);
   if ( boost::regex_match(path, what, appdata )) 
      return ConfigurationFileLocator::Instance().getSpecialPath( CSIDL_APPDATA ) + "\\";

   static boost::regex commonappdata( "\\$\\(?COMMIN_APPDATA\\)?", boost::regex::icase);
   if ( boost::regex_match(path, what, commonappdata )) 
      return ConfigurationFileLocator::Instance().getSpecialPath( CSIDL_COMMON_APPDATA ) + "\\" ;
*/
   return path;
}


bool makeDirectory ( const ASCString& path )
{
   if ( path.empty() )
      return false;
      
   ASCString path2 = resolvePath( path );

   char tmp[10000];
   constructFileName( tmp, 0, path2.c_str(), NULL );

   int existence = directoryExist ( tmp );

   if ( !existence ) {
      int res = createDirectory( tmp ); 
      if ( res ) {
         fprintf(stderr, "could neither access nor create directory %s\n", tmp );
         return false;
      }
   }

   return true;
}


ASCString getDirectory( ASCString filename )
{
   if ( directoryExist( filename ))
      return filename;

   ASCString directory;

   static boost::regex dir( "(.*)[\\\\/:][^\\\\/:]+");
   boost::smatch what;
   if( boost::regex_match( filename, what, dir)) {
      directory.assign( what[1].first, what[1].second );
      return directory;
   } else {
      return ".";
   }
}


void ConfigurationFileLocatorCore::setCommandLineParam( const ASCString& path )
{
   cmdline = path;
}

void ConfigurationFileLocatorCore::setExecutableLocation( const ASCString& path )
{
    exePath = getDirectory( path );

#ifdef WIN32
   char buffer[_MAX_PATH];
   if( _getcwd( buffer, _MAX_PATH ) ) 
	  if ( exePath == "."  || exePath == ".\\" ) 
         exePath = buffer;
	  
   
#endif

}


ASCString ConfigurationFileLocatorCore::getExecutableLocation()
{
   return exePath;
}


ASCString ConfigurationFileLocatorCore::getSpecialPath( int type)
{
#ifdef WIN32
   TCHAR szPath[MAX_PATH];

   if ( SUCCEEDED(SHGetFolderPath( NULL, type, NULL, SHGFP_TYPE_CURRENT, szPath ))) {
      ASCString dir = szPath;
      appendbackslash ( dir );
      dir += "ASC";
      appendbackslash ( dir );
      return dir;
   } 

#endif
   return "";
}

vector<ASCString> ConfigurationFileLocatorCore::getDefaultDirectory()
{
   vector<ASCString> dirs;

#ifdef _WIN32_
   HKEY key;
   if (  RegOpenKeyEx ( HKEY_LOCAL_MACHINE,
                           "SOFTWARE\\Advanced Strategic Command\\",
                           0,
                           KEY_READ,
                           &key ) == ERROR_SUCCESS) {

      DWORD type;
      const int size = 2000;
      char  buf[size];
      DWORD size2 = size;
      if ( RegQueryValueEx ( key, "InstallDir2", NULL, &type, (BYTE*)buf, &size2 ) == ERROR_SUCCESS ) {
         if ( type == REG_SZ	 ) {
            ASCString dir = buf;
            appendbackslash ( dir );
            dirs.push_back( dir );
         }
      }

      RegCloseKey ( key );
   }

/*
   ASCString dir = getSpecialPath( CSIDL_APPDATA );
   if ( !dir.empty() )
      dirs.push_back(dir);

   dir = getSpecialPath( CSIDL_COMMON_APPDATA );
   if ( !dir.empty() )
      dirs.push_back(dir);
      */


   dirs.push_back( "$(MY_DOCUMENTS)\\" );
   dirs.push_back( "$(APPDATA)\\" );
   dirs.push_back( "$(COMMON_APPDATA)\\" );
   dirs.push_back( "$(EXEPATH)\\" );
   /*
   if ( !exePath.empty()) 
      dirs.push_back( exePath );
      */


#else
   ASCString dir = getenv("HOME");
   appendbackslash ( dir );
   dir += ".asc/";
   dirs.push_back( dir );
#endif

   return dirs;

}




ASCString ConfigurationFileLocatorCore::getConfigFileName()
{
   if ( cmdline.length() ) {
      configFileType = 1;
      displayLogMessage( 7, "ConfigurationFileLocatorCore::getConfigFileName() returns cmdline: " + cmdline + "\n" );
      return cmdline;      
   }

   if ( getenv ( asc_EnvironmentName )) {
      ASCString res = getenv ( asc_EnvironmentName );
      configFileType = 2;
      displayLogMessage( 7, "ConfigurationFileLocatorCore::getConfigFileName() returns env dir: " + res + "\n" );
      return res;
   }

   if ( !exePath.empty() && !isPathRelative(exePath) ) {
      displayLogMessage( 5, "Exe path is " + exePath + "\n" );
      ASCString completeName = exePath + "/" + asc_configurationfile;
      if ( exist( completeName )) {
         configFileType = 3;
         displayLogMessage( 7, "ConfigurationFileLocatorCore::getConfigFileName() returns exepath: " + completeName + "\n" );
         return completeName;
      }
   }

   vector<ASCString> list = getDefaultDirectory();
   if ( list.size() >= 1 ) {
      configFileType = 4;
      for ( vector<ASCString>::iterator i = list.begin(); i != list.end(); ++i ) {
         ASCString p = resolvePath( *i ) + asc_configurationfile; 
         if( exist( p )) {
            displayLogMessage( 7, "ConfigurationFileLocatorCore::getConfigFileName() returns default dir: " + p + "\n" );
            return p;
         }
      }
      ASCString res = resolvePath( list[0] ) + asc_configurationfile;
      displayLogMessage( 7, "ConfigurationFileLocatorCore::getConfigFileName() returns list0: " + res + "\n" );
      return res;
   }

   configFileType = 5;
   displayLogMessage( 7, "ConfigurationFileLocatorCore::getConfigFileName() returns asc_configurationfile: " + ASCString(asc_configurationfile) + "\n" );
   return asc_configurationfile;

}

ASCString ConfigurationFileLocatorCore::getConfigForPrinting()
{
   return "";
}

ConfigurationFileLocatorCore::ConfigurationFileLocatorCore() : configFileType(-1) 
{
}

void ConfigurationFileLocatorCore::writeDefaultPathsToOptions()
{
   #ifdef WIN32
   vector<ASCString> dirs = getDefaultDirectory();
   CGameOptions::Instance()->searchPathNum = 0;
   for ( vector<ASCString>::iterator i = dirs.begin(); i != dirs.end(); ++i )
      CGameOptions::Instance()->addSearchPath ( *i );
   #else
   CGameOptions::Instance()->setDefaultDirectories();
   #endif
}

ASCString getConfigFileName ()
{
   ASCString configFileName = ConfigurationFileLocator::Instance().getConfigFileName();
   if ( !configFileName.empty() )
      return configFileName ;
   else
      return "-none- ; default values used";
}



int readgameoptions ( const ASCString& filename )
{
   displayLogMessage ( 4, "loading game options ... " );


   displayLogMessage ( 6, ASCString("Path is ") + filename + "; " );


   if ( exist ( filename )) {
      displayLogMessage ( 6, "found, " );
      try {
         CGameOptions::Instance()->load( filename );
      } 
      catch ( ParsingError err ) {
         fatalError ( "Error parsing text file " + err.getMessage() );
      }
      catch ( tfileerror err ) {
         fatalError ( "Error loading file " + err.getFileName() );
      }
      catch ( ... ) {
         fatalError ( "caught undefined exception" );
      }

   } else {
     displayLogMessage ( 6, "not found, using defaults, " );

     ConfigurationFileLocator::Instance().writeDefaultPathsToOptions();

     if ( !filename.empty() ) {
        CGameOptions::Instance()->setChanged();
        if ( writegameoptions( filename ))
           displayLogMessage ( 6, "A config file has been sucessfully written to " + filename + " ");
        else {
           warningMessage("Unable to write file " + filename );
           displayLogMessage ( 6, "Failed to write config file to " + filename + " ");
        }
     }
   }

   displayLogMessage ( 4, "done\n" );

   makeDirectory ( CGameOptions::Instance()->getSearchPath(0) );

   return 0;
}

bool writegameoptions ( ASCString configFileName )
{
   try {
      if ( configFileName.empty() )
         configFileName = ConfigurationFileLocator::Instance().getConfigFileName();

      configFileName = resolvePath( configFileName );

      if ( CGameOptions::Instance()->isChanged() && !configFileName.empty() ) {
         char buf[10000];
         if ( makeDirectory ( extractPath ( buf, configFileName.c_str() ))) {
            CGameOptions::Instance()->save( configFileName );
            return true;
         }
      }
   }
   catch ( ... ) {
      // warning("Could not save game options");
   }
   return false;
}

void checkFileLoadability ( const ASCString& filename )
{
   try {
      tnfilestream strm ( filename, tnstream::reading );
      strm.readChar();
   }
   catch ( ASCexception ) {
      ASCString msg = "Unable to access " + filename + "\n";
      msg +=           "Make sure the file main.ascdat is in one of the search paths specified in your config file !\n";

      ASCString configFileName = ConfigurationFileLocator::Instance().getConfigFileName();
      if ( exist( configFileName ))
         msg +=        "The configuration file that is used is: " + configFileName  + "\n";
      else
         if ( !configFileName.empty() ) {
            CGameOptions::Instance()->setChanged();
            if ( writegameoptions( configFileName ))
               msg += "A configuration file has been written to " + configFileName + "\n";
         }

      msg +=           "These paths are being searched for data files:\n ";
      
      for ( int i = 0; i < getSearchPathNum(); ++i )
         if ( !getSearchPath(i).empty() ) 
            msg += getSearchPath(i) + "\n ";

     fatalError ( msg );
   }
   catch ( ... ) {
      fatalError ( "checkFileLoadability threw an unspecified exception\n" );
   }
}



void initFileIO ( const ASCString& configFileName, int skipChecks )
{

   ConfigurationFileLocator::Instance().setCommandLineParam( configFileName );
   
   readgameoptions( ConfigurationFileLocator::Instance().getConfigFileName() );

   for ( int i = 0; i < CGameOptions::Instance()->getSearchPathNum(); i++ )
      if ( !CGameOptions::Instance()->getSearchPath(i).empty()   ) {
         displayLogMessage ( 3, "adding search patch " + CGameOptions::Instance()->getSearchPath(i) + "\n" );
         ASCString path = resolvePath( CGameOptions::Instance()->getSearchPath(i) );

         if ( isPathRelative( path ) && !isPathRelative( ConfigurationFileLocator::Instance().getConfigFileName() )) {
            ASCString path2 = getDirectory( ConfigurationFileLocator::Instance().getConfigFileName() );
            appendbackslash ( path2 );
            addSearchPath( path2 + path );
         } else
            addSearchPath ( path );
      }
   try {
     opencontainer ( "*.ascdat" );
   }
   catch ( tfileerror err ) {
      fatalError ( "a fatal IO error occured while mounting the container file %s\n"
                   "It is probably damaged, try getting a new one.\n", err.getFileName().c_str() );
   }
   catch ( tcompressionerror err ) {
      fatalError ( "a fatal error occured while decompressing a container file.\n"
                   "If you have several *.ascdat files in your ASC directory, try removing all but main.ascdat.\n"
                   "If the error still occurs then, get a new data package from www.asc-hq.org\n" );
   }
   catch ( ASCexception ) {
      fatalError ( "a fatal error occured while mounting the container files \n");
   }
   catch ( ... ) {
       fatalError ( "loading of game failed during pre graphic initializing" );
   }

   if ( ! (skipChecks & 1 ))
      checkFileLoadability ( "palette.pal" );
}

void versionError( const ASCString& filename, const ASCString& location )
{
   ASCString msg = "A newer version of the data file '";
   msg += filename + "' is required. \nYou can get a new data package at http://www.asc-hq.org\n";
   msg += "The old file is " + location;
   fatalError( msg );
}