2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
4 * All source code herein is the property of Volition, Inc. You may not sell
5 * or otherwise commercially exploit the source or things you created based on
10 * $Logfile: /Freespace2/code/CFile/cfile.cpp $
15 * Utilities for operating on files
18 * Revision 1.14 2006/04/26 19:36:57 taylor
19 * address an error handling bug in cfwrite()
21 * Revision 1.13 2005/10/01 22:04:58 taylor
22 * fix FS1 (de)briefing voices, the directory names are different in FS1
23 * hard code the table values so that the fs1.vp file isn't needed
24 * hard code a mission fix for sm2-08a since a have no idea how to fix it otherwise
25 * generally cleanup some FS1 code
26 * fix volume sliders in the options screen that never went all the way up
28 * Revision 1.12 2005/08/12 08:50:09 taylor
29 * recursively create directories (hurt more on OSX) and update all _mkdir() calls accordingly
31 * Revision 1.11 2004/07/04 11:27:29 taylor
32 * cleanup CFILE code a little, warning fixes, remove redundant dir checks, amd64 support
34 * Revision 1.10 2004/06/11 00:28:39 tigital
35 * byte-swapping changes for bigendian systems
37 * Revision 1.9 2003/05/25 02:30:42 taylor
40 * Revision 1.8 2003/02/20 17:41:07 theoddone33
41 * Userdir patch from Taylor Richards
43 * Revision 1.7 2002/12/30 03:23:29 relnev
44 * disable root dir check
46 * Revision 1.6 2002/06/17 06:33:08 relnev
47 * ryan's struct patch for gcc 2.95
49 * Revision 1.5 2002/06/09 04:41:15 relnev
50 * added copyright header
52 * Revision 1.4 2002/06/05 08:05:28 relnev
53 * stub/warning removal.
55 * reworked the sound code.
57 * Revision 1.3 2002/05/28 08:52:03 relnev
58 * implemented two assembly stubs.
60 * cleaned up a few warnings.
62 * added a little demo hackery to make it progress a little farther.
64 * Revision 1.2 2002/05/28 06:28:20 theoddone33
65 * Filesystem mods, actually reads some data files now
67 * Revision 1.1.1.1 2002/05/03 03:28:08 root
71 * 20 9/08/99 10:01p Dave
72 * Make sure game won't run in a drive's root directory. Make sure
73 * standalone routes suqad war messages properly to the host.
75 * 19 9/08/99 12:03a Dave
76 * Make squad logos render properly in D3D all the time. Added intel anim
79 * 18 9/06/99 2:35p Dave
80 * Rename briefing and debriefing voice direcrory paths properly.
82 * 17 9/03/99 1:31a Dave
83 * CD checking by act. Added support to play 2 cutscenes in a row
84 * seamlessly. Fixed super low level cfile bug related to files in the
85 * root directory of a CD. Added cheat code to set campaign mission # in
88 * 16 8/31/99 9:46a Dave
89 * Support for new cfile cbanims directory.
91 * 15 8/06/99 11:20a Johns
92 * Don't call game_cd_changed() in a demo or multiplayer beta build.
94 * 14 6/08/99 2:33p Dave
95 * Fixed release build warning. Put in hud config stuff.
97 * 13 5/19/99 4:07p Dave
98 * Moved versioning code into a nice isolated common place. Fixed up
99 * updating code on the pxo screen. Fixed several stub problems.
101 * 12 4/30/99 12:18p Dave
102 * Several minor bug fixes.
104 * 11 4/07/99 5:54p Dave
105 * Fixes for encryption in updatelauncher.
107 * 10 3/28/99 5:58p Dave
108 * Added early demo code. Make objects move. Nice and framerate
109 * independant, but not much else. Don't use yet unless you're me :)
111 * 9 2/22/99 10:31p Andsager
112 * Get rid of unneeded includes.
114 * 8 1/12/99 3:15a Dave
115 * Barracks screen support for selecting squad logos. We need real artwork
118 * 7 11/30/98 1:07p Dave
119 * 16 bit conversion, first run.
121 * 6 10/29/98 10:41a Dave
122 * Change the way cfile initializes exe directory.
124 * 5 10/13/98 9:19a Andsager
125 * Add localization support to cfile. Optional parameter with cfopen that
126 * looks for localized files.
128 * 4 10/12/98 9:54a Dave
129 * Fixed a few file organization things.
131 * 3 10/07/98 6:27p Dave
132 * Globalized mission and campaign file extensions. Removed Silent Threat
133 * special code. Moved \cache \players and \multidata into the \data
136 * 2 10/07/98 10:52a Dave
139 * 1 10/07/98 10:48a Dave
141 * 110 9/17/98 10:31a Hoffoss
142 * Changed code to use location of executable as root rather than relying
143 * on the cwd being set correctly. This is most helpful in the case of
144 * Fred launching due to the user double-clicking on an .fsm file in
145 * explorer or something (where the cwd is probably the location of the
148 * 109 9/11/98 4:14p Dave
149 * Fixed file checksumming of < file_size. Put in more verbose kicking and
150 * PXO stats store reporting.
152 * 108 9/09/98 5:53p Dave
153 * Put in new tracker packets in API. Change cfile to be able to checksum
154 * portions of a file.
156 * 107 9/04/98 3:51p Dave
157 * Put in validated mission updating and application during stats
160 * 106 8/31/98 2:06p Dave
161 * Make cfile sort the ordering or vp files. Added support/checks for
162 * recognizing "mission disk" players.
164 * 105 8/20/98 5:30p Dave
165 * Put in handy multiplayer logfile system. Now need to put in useful
166 * applications of it all over the code.
168 * 104 8/12/98 4:53p Dave
169 * Put in 32 bit checksumming for PXO missions. No validation on the
170 * actual tracker yet, though.
172 * 103 6/17/98 9:30a Allender
173 * fixed red alert replay stats clearing problem
175 * 102 6/05/98 9:46a Lawrance
176 * check for CD change on cfopen()
178 * 101 5/19/98 1:19p Allender
179 * new low level reliable socket reading code. Make all missions/campaign
180 * load/save to data missions folder (i.e. we are rid of the player
183 * 100 5/13/98 10:22p John
184 * Added cfile functions to read/write rle compressed blocks of data.
185 * Made palman use it for .clr files. Made alphacolors calculate on the
186 * fly rather than caching to/from disk.
188 * 99 5/11/98 10:59a John
189 * Moved the low-level file reading code into cfilearchive.cpp.
191 * 98 5/06/98 5:30p John
192 * Removed unused cfilearchiver. Removed/replaced some unused/little used
193 * graphics functions, namely gradient_h and _v and pixel_sp. Put in new
194 * DirectX header files and libs that fixed the Direct3D alpha blending
197 * 97 5/03/98 11:53a John
198 * Fixed filename case mangling.
200 * 96 5/03/98 8:33a John
201 * Made sure there weren't any more broken function lurking around like
202 * the one Allender fixed.
204 * 95 5/02/98 11:05p Allender
205 * fix cfilelength for pack files
210 #define _CFILE_INTERNAL
220 #include <winbase.h> /* needed for memory mapping of file functions */
223 #include <sys/stat.h>
224 #include <sys/types.h>
230 //#include "outwnd.h"
231 //#include "vecmat.h"
233 #include "cfilesystem.h"
234 #include "cfilearchive.h"
236 #include "osregistry.h" // for Osreg_user_dir
239 char Cfile_user_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
241 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
243 // During cfile_init, verify that Pathtypes[n].index == n for each item
244 // Each path must have a valid parent that can be tracable all the way back to the root
245 // so that we can create directories when we need to.
247 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
248 // What type this is Path Extensions Parent type
249 { CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
250 // Root must be index 1!!
251 { CF_TYPE_ROOT, "", ".mve", CF_TYPE_ROOT },
252 { CF_TYPE_DATA, "Data", ".cfg .log .txt", CF_TYPE_ROOT },
254 { CF_TYPE_MAPS, "Data/Maps", ".pcx .ani .tga", CF_TYPE_DATA },
255 { CF_TYPE_TEXT, "Data/Text", ".txt .net", CF_TYPE_DATA },
257 { CF_TYPE_MISSIONS, "Data/Missions", ".fsm .fsc .ntl .ssv", CF_TYPE_DATA },
259 { CF_TYPE_MISSIONS, "Data/Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
261 { CF_TYPE_MODELS, "Data/Models", ".pof", CF_TYPE_DATA },
262 { CF_TYPE_TABLES, "Data/Tables", ".tbl", CF_TYPE_DATA },
263 { CF_TYPE_SOUNDS, "Data/Sounds", ".wav", CF_TYPE_DATA },
264 { CF_TYPE_SOUNDS_8B22K, "Data/Sounds/8b22k", ".wav", CF_TYPE_SOUNDS },
265 { CF_TYPE_SOUNDS_16B11K, "Data/Sounds/16b11k", ".wav", CF_TYPE_SOUNDS },
266 { CF_TYPE_VOICE, "Data/Voice", "", CF_TYPE_DATA },
268 { CF_TYPE_VOICE_BRIEFINGS, "Data/Voice/Briefings", ".wav", CF_TYPE_VOICE },
270 { CF_TYPE_VOICE_BRIEFINGS, "Data/Voice/Briefing", ".wav", CF_TYPE_VOICE },
272 { CF_TYPE_VOICE_CMD_BRIEF, "Data/Voice/Command_briefings",".wav", CF_TYPE_VOICE },
274 { CF_TYPE_VOICE_DEBRIEFINGS, "Data/Voice/Debriefings", ".wav", CF_TYPE_VOICE },
276 { CF_TYPE_VOICE_DEBRIEFINGS, "Data/Voice/Debriefing", ".wav", CF_TYPE_VOICE },
278 { CF_TYPE_VOICE_PERSONAS, "Data/Voice/Personas", ".wav", CF_TYPE_VOICE },
279 { CF_TYPE_VOICE_SPECIAL, "Data/Voice/Special", ".wav", CF_TYPE_VOICE },
280 { CF_TYPE_VOICE_TRAINING, "Data/Voice/Training", ".wav", CF_TYPE_VOICE },
281 { CF_TYPE_MUSIC, "Data/Music", ".wav", CF_TYPE_VOICE },
282 { CF_TYPE_MOVIES, "Data/Movies", ".mve .msb", CF_TYPE_DATA },
283 { CF_TYPE_INTERFACE, "Data/Interface", ".pcx .ani .tga", CF_TYPE_DATA },
284 { CF_TYPE_FONT, "Data/Fonts", ".vf", CF_TYPE_DATA },
285 { CF_TYPE_EFFECTS, "Data/Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
286 { CF_TYPE_HUD, "Data/Hud", ".ani .pcx .tga", CF_TYPE_DATA },
287 { CF_TYPE_PLAYER_MAIN, "Data/Players", "", CF_TYPE_DATA },
288 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data/Players/Images", ".pcx", CF_TYPE_PLAYER_MAIN },
289 { CF_TYPE_CACHE, "Data/Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
290 { CF_TYPE_PLAYERS, "Data/Players", ".hcf", CF_TYPE_DATA },
291 { CF_TYPE_SINGLE_PLAYERS, "Data/Players/Single", ".plr .csg .css", CF_TYPE_PLAYERS },
292 { CF_TYPE_MULTI_PLAYERS, "Data/Players/Multi", ".plr", CF_TYPE_DATA },
293 { CF_TYPE_MULTI_CACHE, "Data/MultiData", ".pcx .fs2", CF_TYPE_DATA },
294 { CF_TYPE_CONFIG, "Data/Config", ".cfg", CF_TYPE_DATA },
295 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data/Players/Squads", ".pcx", CF_TYPE_DATA },
296 { CF_TYPE_DEMOS, "Data/Demos", ".fsd", CF_TYPE_DATA },
297 { CF_TYPE_CBANIMS, "Data/CBAnims", ".ani", CF_TYPE_DATA },
298 { CF_TYPE_INTEL_ANIMS, "Data/IntelAnims", ".ani", CF_TYPE_DATA },
300 { CF_TYPE_MAPS, "Data\\Maps", ".pcx .ani .tga", CF_TYPE_DATA },
301 { CF_TYPE_TEXT, "Data\\Text", ".txt .net", CF_TYPE_DATA },
302 { CF_TYPE_MISSIONS, "Data\\Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
303 { CF_TYPE_MODELS, "Data\\Models", ".pof", CF_TYPE_DATA },
304 { CF_TYPE_TABLES, "Data\\Tables", ".tbl", CF_TYPE_DATA },
305 { CF_TYPE_SOUNDS, "Data\\Sounds", ".wav", CF_TYPE_DATA },
306 { CF_TYPE_SOUNDS_8B22K, "Data\\Sounds\\8b22k", ".wav", CF_TYPE_SOUNDS },
307 { CF_TYPE_SOUNDS_16B11K, "Data\\Sounds\\16b11k", ".wav", CF_TYPE_SOUNDS },
308 { CF_TYPE_VOICE, "Data\\Voice", "", CF_TYPE_DATA },
309 { CF_TYPE_VOICE_BRIEFINGS, "Data\\Voice\\Briefing", ".wav", CF_TYPE_VOICE },
310 { CF_TYPE_VOICE_CMD_BRIEF, "Data\\Voice\\Command_briefings",".wav", CF_TYPE_VOICE },
311 { CF_TYPE_VOICE_DEBRIEFINGS, "Data\\Voice\\Debriefing", ".wav", CF_TYPE_VOICE },
312 { CF_TYPE_VOICE_PERSONAS, "Data\\Voice\\Personas", ".wav", CF_TYPE_VOICE },
313 { CF_TYPE_VOICE_SPECIAL, "Data\\Voice\\Special", ".wav", CF_TYPE_VOICE },
314 { CF_TYPE_VOICE_TRAINING, "Data\\Voice\\Training", ".wav", CF_TYPE_VOICE },
315 { CF_TYPE_MUSIC, "Data\\Music", ".wav", CF_TYPE_VOICE },
316 { CF_TYPE_MOVIES, "Data\\Movies", ".mve .msb", CF_TYPE_DATA },
317 { CF_TYPE_INTERFACE, "Data\\Interface", ".pcx .ani .tga", CF_TYPE_DATA },
318 { CF_TYPE_FONT, "Data\\Fonts", ".vf", CF_TYPE_DATA },
319 { CF_TYPE_EFFECTS, "Data\\Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
320 { CF_TYPE_HUD, "Data\\Hud", ".ani .pcx .tga", CF_TYPE_DATA },
321 { CF_TYPE_PLAYER_MAIN, "Data\\Players", "", CF_TYPE_DATA },
322 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data\\Players\\Images", ".pcx", CF_TYPE_PLAYER_MAIN },
323 { CF_TYPE_CACHE, "Data\\Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
324 { CF_TYPE_PLAYERS, "Data\\Players", ".hcf", CF_TYPE_DATA },
325 { CF_TYPE_SINGLE_PLAYERS, "Data\\Players\\Single", ".plr .csg .css", CF_TYPE_PLAYERS },
326 { CF_TYPE_MULTI_PLAYERS, "Data\\Players\\Multi", ".plr", CF_TYPE_DATA },
327 { CF_TYPE_MULTI_CACHE, "Data\\MultiData", ".pcx .fs2", CF_TYPE_DATA },
328 { CF_TYPE_CONFIG, "Data\\Config", ".cfg", CF_TYPE_DATA },
329 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data\\Players\\Squads", ".pcx", CF_TYPE_DATA },
330 { CF_TYPE_DEMOS, "Data\\Demos", ".fsd", CF_TYPE_DATA },
331 { CF_TYPE_CBANIMS, "Data\\CBAnims", ".ani", CF_TYPE_DATA },
332 { CF_TYPE_INTEL_ANIMS, "Data\\IntelAnims", ".ani", CF_TYPE_DATA },
337 #define CFILE_STACK_MAX 8
339 int cfile_inited = 0;
340 int Cfile_stack_pos = 0;
342 char Cfile_stack[128][CFILE_STACK_MAX];
344 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
345 CFILE Cfile_list[MAX_CFILE_BLOCKS];
347 char *Cfile_cdrom_dir = NULL;
350 // Function prototypes for internally-called functions
352 int cfget_cfile_block();
353 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
354 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
355 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
356 void cf_chksum_long_init();
360 cf_free_secondary_filelist();
363 // determine if the given path is in a root directory (c:\ or c:\freespace2.exe or c:\fred2.exe etc)
364 int cfile_in_root_dir(char *exe_path)
367 char path_copy[2048] = "";
371 if(exe_path == NULL){
376 memset(path_copy, 0, 2048);
377 strncpy(path_copy, exe_path, 2047);
379 // count how many slashes there are in the path
380 tok = strtok(path_copy, DIR_SEPARATOR_STR);
386 tok = strtok(NULL, DIR_SEPARATOR_STR);
387 } while(tok != NULL);
389 // root directory if we have <= 1 slash
390 if(token_count <= 2){
394 // not-root directory
398 // cfile_init() initializes the cfile system. Called once at application start.
400 // returns: success ==> 0
401 // error ==> non-zero
403 int cfile_init(const char *exe_dir, const char *cdrom_dir)
407 // initialize encryption
410 if ( !cfile_inited ) {
415 strcpy(buf, exe_dir);
419 // are we in a root directory?
420 if(cfile_in_root_dir(buf)){
421 MessageBox((HWND)NULL, "Freespace2/Fred2 cannot be run from a drive root directory!", "Error", MB_OK);
427 if (buf[i] == DIR_SEPARATOR_CHAR){
437 fprintf (stderr, "Error trying to determine executable root directory!");
439 MessageBox((HWND)NULL, "Error trying to determine executable root directory!", "Error", MB_OK);
444 // set root directory
445 strncpy(Cfile_root_dir, buf, CFILE_ROOT_DIRECTORY_LEN-1);
448 snprintf(Cfile_user_dir, MAX_PATH, "%s/%s/", detect_home(), Osreg_user_dir);
450 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
451 Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
454 Cfile_cdrom_dir = (char *)cdrom_dir;
455 cf_build_secondary_filelist(Cfile_cdrom_dir);
457 // 32 bit CRC table init
458 cf_chksum_long_init();
460 atexit( cfile_close );
466 // Call this if pack files got added or removed or the
467 // cdrom changed. This will refresh the list of filenames
468 // stored in packfiles and on the cdrom.
471 cf_build_secondary_filelist(Cfile_cdrom_dir);
475 // Changes to a drive if valid.. 1=A, 2=B, etc
476 // If flag, then changes to it.
477 // Returns 0 if not-valid, 1 if valid.
478 int cfile_chdrive( int DriveNum, int flag )
491 _chdrive( DriveNum );
498 if ( (!flag) && (n != org) )
504 // push current directory on a 'stack' (so we can restore it) and change the directory
505 int cfile_push_chdir(int type)
509 char OriginalDirectory[128];
511 char NoDir[] = "\\.";
513 _getcwd(OriginalDirectory, 127);
514 Assert(Cfile_stack_pos < CFILE_STACK_MAX);
515 strcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
517 cf_create_default_path_string( dir, type, NULL );
520 char *Drive = strchr(dir, ':');
523 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
538 // This chdir might get a critical error!
541 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
549 int cfile_chdir(char *dir)
552 char OriginalDirectory[128];
554 char NoDir[] = "\\.";
556 _getcwd(OriginalDirectory, 127);
560 char *Drive = strchr(dir, ':');
562 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
577 // This chdir might get a critical error!
580 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
589 Assert(Cfile_stack_pos);
591 return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
594 // flush (delete all files in) the passed directory (by type), return the # of files deleted
595 // NOTE : WILL NOT DELETE READ-ONLY FILES
596 int cfile_flush_dir(int dir_type)
606 Assert( CF_TYPE_SPECIFIED(dir_type) );
608 // attempt to change the directory to the passed type
609 if(cfile_push_chdir(dir_type)){
613 // proceed to delete the files
614 find_handle = _findfirst( "*", &find );
616 if (find_handle != -1) {
618 if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
620 cf_delete(find.name,dir_type);
622 // increment the deleted count
625 } while (!_findnext(find_handle, &find));
626 _findclose( find_handle );
629 // pop the directory back
632 // return the # of files deleted
638 // add the given extention to a filename (or filepath) if it doesn't already have this
640 // filename = name of filename or filepath to process
641 // ext = extension to add. Must start with the period
642 // Returns: new filename or filepath with extension.
643 char *cf_add_ext(const char *filename, const char *ext)
646 static char path[MAX_PATH_LEN];
648 flen = strlen(filename);
650 Assert(flen < MAX_PATH_LEN);
651 strcpy(path, filename);
652 if ((flen < 4) || stricmp(path + flen - elen, ext)) {
653 Assert(flen + elen < MAX_PATH_LEN);
661 void cf_delete( const char *filename, int dir_type )
663 char longname[MAX_PATH_LEN];
665 Assert( CF_TYPE_SPECIFIED(dir_type) );
667 cf_create_default_path_string( longname, dir_type, filename );
669 FILE *fp = fopen(longname, "rb");
679 // Same as _access function to read a file's access bits
680 int cf_access( const char *filename, int dir_type, int mode )
682 char longname[MAX_PATH_LEN];
684 Assert( CF_TYPE_SPECIFIED(dir_type) );
686 cf_create_default_path_string( longname, dir_type, filename );
688 return access(longname,mode);
692 // Returns 1 if file exists, 0 if not.
693 int cf_exist( const char *filename, int dir_type )
695 char longname[MAX_PATH_LEN];
697 Assert( CF_TYPE_SPECIFIED(dir_type) );
699 cf_create_default_path_string( longname, dir_type, filename );
701 FILE *fp = fopen(longname, "rb");
710 void cf_attrib(const char *filename, int set, int clear, int dir_type)
712 char longname[MAX_PATH_LEN];
714 Assert( CF_TYPE_SPECIFIED(dir_type) );
716 cf_create_default_path_string( longname, dir_type, filename );
718 FILE *fp = fopen(longname, "rb");
725 DWORD z = GetFileAttributes(longname);
726 SetFileAttributes(longname, z | set & ~clear);
732 int cf_rename(const char *old_name, const char *name, int dir_type)
734 Assert( CF_TYPE_SPECIFIED(dir_type) );
737 char old_longname[_MAX_PATH];
738 char new_longname[_MAX_PATH];
740 cf_create_default_path_string( old_longname, dir_type, old_name );
741 cf_create_default_path_string( new_longname, dir_type, name );
743 ret_code = rename(old_longname, new_longname );
747 return CF_RENAME_FAIL_ACCESS;
750 return CF_RENAME_FAIL_EXIST;
754 return CF_RENAME_SUCCESS;
759 // Creates the directory path if it doesn't exist. Even creates all its
761 void cf_create_directory( int dir_type )
764 int dir_tree[CF_MAX_PATH_TYPES];
765 char longname[MAX_PATH_LEN];
767 Assert( CF_TYPE_SPECIFIED(dir_type) );
769 int current_dir = dir_type;
772 Assert( num_dirs < CF_MAX_PATH_TYPES ); // Invalid Pathtypes data?
774 dir_tree[num_dirs++] = current_dir;
775 current_dir = Pathtypes[current_dir].parent_index;
777 } while( current_dir != CF_TYPE_ROOT );
782 for (i=num_dirs-1; i>=0; i-- ) {
783 cf_create_default_path_string( longname, dir_tree[i], NULL );
785 if ( _mkdir(longname)==0 ) {
786 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
794 extern int game_cd_changed();
798 // parameters: *filepath ==> name of file to open (may be path+name)
799 // *mode ==> specifies how file should be opened (eg "rb" for read binary)
800 // passing NULL to mode deletes the file if it exists and returns NULL
801 // type ==> one of: CFILE_NORMAL
802 // CFILE_MEMORY_MAPPED
803 // dir_type => override extension check, value is one of CF_TYPE* #defines
805 // NOTE: type parameter is an optional parameter. The default value is CFILE_NORMAL
808 // returns: success ==> address of CFILE structure
812 CFILE *cfopen(const char *file_path, const char *mode, int type, int dir_type, bool localize)
814 char longname[_MAX_PATH];
816 // nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
817 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
819 // we no longer need to do this, and on machines with crappy-ass drivers it can slow things down horribly.
821 if ( game_cd_changed() ) {
826 //================================================
827 // Check that all the parameters make sense
828 Assert(file_path && strlen(file_path));
829 Assert( mode != NULL );
831 // Can only open read-only binary files in memory mapped mode.
832 if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
837 //===========================================================
838 // If in write mode, just try to open the file straight off
839 // the harddisk. No fancy packfile stuff here!
841 if ( strchr(mode,'w') ) {
842 // For write-only files, require a full path or a path type
844 if ( strpbrk(file_path, "/") ) {
846 if ( strpbrk(file_path,"/\\:") ) {
849 strcpy(longname, file_path );
852 Assert( dir_type != CF_TYPE_ANY );
854 // Create the directory if necessary
855 cf_create_directory( dir_type );
857 cf_create_default_path_string( longname, dir_type, file_path );
859 Assert( !(type & CFILE_MEMORY_MAPPED) );
861 // JOHN: TODO, you should create the path if it doesn't exist.
863 FILE *fp = fopen(longname, mode);
865 return cf_open_fill_cfblock(fp, dir_type);
871 //================================================
872 // Search for file on disk, on cdrom, or in a packfile
875 char copy_file_path[MAX_PATH_LEN]; // FIX change in memory from cf_find_file_location
876 strcpy(copy_file_path, file_path);
879 if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) ) {
881 // Fount it, now create a cfile out of it
883 if ( type & CFILE_MEMORY_MAPPED ) {
885 // Can't open memory mapped files out of pack files
892 hFile = CreateFile(longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
894 if (hFile != INVALID_HANDLE_VALUE) {
895 return cf_open_mapped_fill_cfblock(hFile, dir_type);
902 FILE *fp = fopen( longname, "rb" );
906 // Found it in a pack file
907 return cf_open_packed_cfblock(fp, dir_type, offset, size );
909 // Found it in a normal file
910 return cf_open_fill_cfblock(fp, dir_type);
921 // ------------------------------------------------------------------------
924 // Open up a temporary file. A unique name is automatically generated. The
925 // file will be automatically deleted when file is closed.
927 // return: NULL => tmp file could not be opened
928 // pointer to CFILE => tmp file successfully opened
935 return cf_open_fill_cfblock(fp, 0);
942 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
943 // Cfile_block_list[] array and return the index.
945 // returns: success ==> index in Cfile_block_list[] array
948 int cfget_cfile_block()
953 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
954 cb = &Cfile_block_list[i];
955 if ( cb->type == CFILE_BLOCK_UNUSED ) {
958 cb->type = CFILE_BLOCK_USED;
963 // If we've reached this point, a free Cfile_block could not be found
964 nprintf(("Warning","A free Cfile_block could not be found.\n"));
965 Assert(0); // out of free cfile blocks
970 // cfclose() closes the file
972 // returns: success ==> 0
975 int cfclose( CFILE * cfile )
979 Assert(cfile != NULL);
981 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
982 cb = &Cfile_block_list[cfile->id];
986 // close memory mapped file
990 result = UnmapViewOfFile((void*)cb->data);
992 result = CloseHandle(cb->hInFile);
993 Assert(result); // Ensure file handle is closed properly
994 result = CloseHandle(cb->hMapFile);
995 Assert(result); // Ensure file handle is closed properly
999 } else if ( cb->fp != NULL ) {
1000 Assert(cb->fp != NULL);
1001 result = fclose(cb->fp);
1006 cb->type = CFILE_BLOCK_UNUSED;
1013 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1014 // for the case of a file being opened by cf_open();
1016 // returns: success ==> ptr to CFILE structure.
1019 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
1021 int cfile_block_index;
1023 cfile_block_index = cfget_cfile_block();
1024 if ( cfile_block_index == -1 ) {
1029 cfbp = &Cfile_block_list[cfile_block_index];
1030 cfp = &Cfile_list[cfile_block_index];;
1031 cfp->id = cfile_block_index;
1035 cfbp->dir_type = type;
1037 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
1044 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1045 // for the case of a file being opened by cf_open();
1047 // returns: success ==> ptr to CFILE structure.
1050 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
1052 // Found it in a pack file
1053 int cfile_block_index;
1055 cfile_block_index = cfget_cfile_block();
1056 if ( cfile_block_index == -1 ) {
1061 cfbp = &Cfile_block_list[cfile_block_index];
1063 cfp = &Cfile_list[cfile_block_index];
1064 cfp->id = cfile_block_index;
1068 cfbp->dir_type = type;
1070 cf_init_lowlevel_read_code(cfp,offset, size );
1079 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1080 // for the case of a file being opened by cf_open_mapped();
1082 // returns: ptr CFILE structure.
1084 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
1086 int cfile_block_index;
1088 cfile_block_index = cfget_cfile_block();
1089 if ( cfile_block_index == -1 ) {
1095 cfbp = &Cfile_block_list[cfile_block_index];
1097 cfp = &Cfile_list[cfile_block_index];
1098 cfp->id = cfile_block_index;
1100 cfbp->hInFile = hFile;
1101 cfbp->dir_type = type;
1103 cf_init_lowlevel_read_code(cfp,0 , 0 );
1108 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
1109 if (cfbp->hMapFile == NULL) {
1110 nprintf(("Error", "Could not create file-mapping object.\n"));
1114 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1115 Assert( cfbp->data != NULL );
1121 int cf_get_dir_type(CFILE *cfile)
1123 return Cfile_block_list[cfile->id].dir_type;
1126 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1127 // with the CFILE structure passed as a parameter
1131 void *cf_returndata(CFILE *cfile)
1133 Assert(cfile != NULL);
1135 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1136 cb = &Cfile_block_list[cfile->id];
1137 Assert(cb->data != NULL);
1143 // version number of opened file. Will be 0 unless you put something else here after you
1144 // open a file. Once set, you can use minimum version numbers with the read functions.
1145 void cf_set_version( CFILE * cfile, int version )
1147 Assert(cfile != NULL);
1149 cfile->version = version;
1152 // routines to read basic data types from CFILE's. Put here to
1153 // simplify mac/pc reading from cfiles.
1158 float cfread_float(CFILE *file, int ver, float deflt)
1162 if (file->version < ver)
1165 if (cfread( &f, sizeof(f), 1, file) != 1)
1168 f = INTEL_FLOAT(&f);
1172 int cfread_int(CFILE *file, int ver, int deflt)
1176 if (file->version < ver)
1179 if (cfread( &i, sizeof(i), 1, file) != 1)
1186 uint cfread_uint(CFILE *file, int ver, uint deflt)
1190 if (file->version < ver)
1193 if (cfread( &i, sizeof(i), 1, file) != 1)
1200 short cfread_short(CFILE *file, int ver, short deflt)
1204 if (file->version < ver)
1207 if (cfread( &s, sizeof(s), 1, file) != 1)
1214 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1218 if (file->version < ver)
1221 if (cfread( &s, sizeof(s), 1, file) != 1)
1228 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1232 if (file->version < ver)
1235 if (cfread( &b, sizeof(b), 1, file) != 1)
1241 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1243 if (file->version < ver) {
1247 vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
1252 vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
1253 vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
1254 vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
1257 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1259 if (file->version < ver) {
1263 ang->p = ang->b = ang->h = 0.0f;
1268 ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
1269 ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
1270 ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
1273 char cfread_char(CFILE *file, int ver, char deflt)
1277 if (file->version < ver)
1280 if (cfread( &b, sizeof(b), 1, file) != 1)
1286 void cfread_string(char *buf, int n, CFILE *file)
1291 c = cfread_char(file);
1299 void cfread_string_len(char *buf,int n, CFILE *file)
1302 len = cfread_int(file);
1305 cfread(buf, len, 1, file);
1310 // equivalent write functions of above read functions follow
1312 int cfwrite_float(float f, CFILE *file)
1314 f = INTEL_FLOAT(&f);
1315 return cfwrite(&f, sizeof(f), 1, file);
1318 int cfwrite_int(int i, CFILE *file)
1321 return cfwrite(&i, sizeof(i), 1, file);
1324 int cfwrite_uint(uint i, CFILE *file)
1327 return cfwrite(&i, sizeof(i), 1, file);
1330 int cfwrite_short(short s, CFILE *file)
1333 return cfwrite(&s, sizeof(s), 1, file);
1336 int cfwrite_ushort(ushort s, CFILE *file)
1339 return cfwrite(&s, sizeof(s), 1, file);
1342 int cfwrite_ubyte(ubyte b, CFILE *file)
1344 return cfwrite(&b, sizeof(b), 1, file);
1347 int cfwrite_vector(vector *vec, CFILE *file)
1349 if(!cfwrite_float(vec->xyz.x, file)){
1352 if(!cfwrite_float(vec->xyz.y, file)){
1355 return cfwrite_float(vec->xyz.z, file);
1358 int cfwrite_angles(angles *ang, CFILE *file)
1360 if(!cfwrite_float(ang->p, file)){
1363 if(!cfwrite_float(ang->b, file)){
1366 return cfwrite_float(ang->h, file);
1369 int cfwrite_char(char b, CFILE *file)
1371 return cfwrite( &b, sizeof(b), 1, file);
1374 int cfwrite_string(const char *buf, CFILE *file)
1376 if ( (!buf) || (buf && !buf[0]) ) {
1377 return cfwrite_char(0, file);
1379 int len = strlen(buf);
1380 if(!cfwrite(buf, len, 1, file)){
1383 return cfwrite_char(0, file); // write out NULL termination
1386 int cfwrite_string_len(const char *buf, CFILE *file)
1388 int len = strlen(buf);
1390 if(!cfwrite_int(len, file)){
1394 return cfwrite(buf,len,1,file);
1400 // Get the filelength
1401 int cfilelength( CFILE * cfile )
1403 Assert(cfile != NULL);
1405 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1406 cb = &Cfile_block_list[cfile->id];
1408 // TODO: return length of memory mapped file
1409 Assert( !cb->data );
1411 Assert(cb->fp != NULL);
1413 // cb->size gets set at cfopen
1417 // cfwrite() writes to the file
1419 // returns: number of full elements actually written
1422 int cfwrite(const void *buf, int elsize, int nelem, CFILE *cfile)
1424 Assert(cfile != NULL);
1425 Assert(buf != NULL);
1430 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1431 cb = &Cfile_block_list[cfile->id];
1433 int size = elsize * nelem;
1435 // cfwrite() not supported for memory-mapped files
1436 Assert( !cb->data );
1438 Assert(cb->fp != NULL);
1439 Assert(cb->lib_offset == 0 );
1440 int bytes_written = fwrite( buf, 1, size, cb->fp );
1442 if (bytes_written > 0) {
1443 cb->raw_position += bytes_written;
1446 #if defined(CHECK_POSITION) && !defined(NDEBUG)
1447 int tmp_offset = ftell(cb->fp) - cb->lib_offset;
1448 Assert(tmp_offset == cb->raw_position);
1451 return bytes_written / elsize;
1455 // cfputc() writes a character to a file
1457 // returns: success ==> returns character written
1460 int cfputc(int c, CFILE *cfile)
1464 Assert(cfile != NULL);
1466 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1467 cb = &Cfile_block_list[cfile->id];
1470 // cfputc() not supported for memory-mapped files
1471 Assert( !cb->data );
1473 Assert(cb->fp != NULL);
1474 result = fputc(c, cb->fp);
1480 // cfgetc() reads a character from a file
1482 // returns: success ==> returns character read
1485 int cfgetc(CFILE *cfile)
1487 Assert(cfile != NULL);
1491 int result = cfread(&tmp, 1, 1, cfile );
1492 if ( result == 1 ) {
1505 // cfgets() reads a string from a file
1507 // returns: success ==> returns pointer to string
1510 char *cfgets(char *buf, int n, CFILE *cfile)
1512 Assert(cfile != NULL);
1513 Assert(buf != NULL);
1519 for (i=0; i<n-1; i++ ) {
1523 int ret = cfread( &tmp_c, 1, 1, cfile );
1533 } while ( c == 13 );
1535 if ( c=='\n' ) break;
1542 // cfputs() writes a string to a file
1544 // returns: success ==> non-negative value
1547 int cfputs(const char *str, CFILE *cfile)
1549 Assert(cfile != NULL);
1550 Assert(str != NULL);
1553 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1554 cb = &Cfile_block_list[cfile->id];
1559 // cfputs() not supported for memory-mapped files
1560 Assert( !cb->data );
1561 Assert(cb->fp != NULL);
1562 result = fputs(str, cb->fp);
1568 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1570 // CRC code for mission validation. given to us by Kevin Bentley on 7/20/98. Some sort of
1571 // checksumming code that he wrote a while ago.
1572 #define CRC32_POLYNOMIAL 0xEDB88320L
1573 unsigned long CRCTable[256];
1575 #define CF_CHKSUM_SAMPLE_SIZE 512
1577 // update cur_chksum with the chksum of the new_data of size new_data_size
1578 ushort cf_add_chksum_short(ushort seed, const char *buffer, int size)
1580 const ubyte * ptr = (const ubyte *)buffer;
1581 unsigned int sum1,sum2;
1583 sum1 = sum2 = (int)(seed);
1587 if (sum1 >= 255 ) sum1 -= 255;
1592 return (unsigned short)((sum1<<8)+ sum2);
1595 // update cur_chksum with the chksum of the new_data of size new_data_size
1596 unsigned long cf_add_chksum_long(unsigned long seed, const char *buffer, int size)
1599 unsigned const char *p;
1600 unsigned long temp1;
1601 unsigned long temp2;
1603 p = (unsigned const char*)buffer;
1607 temp1 = (crc>>8)&0x00FFFFFFL;
1608 temp2 = CRCTable[((int)crc^*p++)&0xff];
1615 void cf_chksum_long_init()
1620 for( i=0;i<=255;i++) {
1624 crc=(crc>>1)^CRC32_POLYNOMIAL;
1632 // single function convenient to use for both short and long checksums
1633 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1634 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1636 char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1642 // determine whether we're doing a short or long checksum
1653 // if max_size is -1, set it to be the size of the file
1655 cfseek(cfile, 0, SEEK_SET);
1656 max_size = cfilelength(cfile);
1661 // determine how much we want to read
1662 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1663 read_size = CF_CHKSUM_SAMPLE_SIZE;
1665 read_size = max_size - cf_total;
1668 // read in some buffer
1669 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1671 // total we've read so far
1676 // do the proper short or long checksum
1678 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1680 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1683 } while((cf_len > 0) && (cf_total < max_size));
1688 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1689 int cf_chksum_short(const char *filename, ushort *chksum, int max_size, int cf_type)
1692 CFILE *cfile = NULL;
1694 // zero the checksum
1697 // attempt to open the file
1698 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1703 // call the overloaded cf_chksum function()
1704 ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1706 // close the file down
1710 // return the result
1714 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1715 // NOTE : preserves current file position
1716 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1721 // Returns current position of file.
1722 start_pos = cftell(file);
1723 if(start_pos == -1){
1727 // move to the beginning of the file
1728 if(cfseek(file, 0, CF_SEEK_SET)){
1731 ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1732 // move back to the start position
1733 cfseek(file, start_pos, CF_SEEK_SET);
1738 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1739 int cf_chksum_long(const char *filename, uint *chksum, int max_size, int cf_type)
1742 CFILE *cfile = NULL;
1744 // zero the checksum
1747 // attempt to open the file
1748 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1753 // call the overloaded cf_chksum function()
1754 ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1756 // close the file down
1760 // return the result
1764 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1765 // NOTE : preserves current file position
1766 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1771 // Returns current position of file.
1772 start_pos = cftell(file);
1773 if(start_pos == -1){
1777 // move to the beginning of the file
1778 if(cfseek(file, 0, CF_SEEK_SET)){
1781 ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1782 // move back to the start position
1783 cfseek(file, start_pos, CF_SEEK_SET);
1789 // Flush the open file buffer
1791 // exit: 0 - success
1793 int cflush(CFILE *cfile)
1795 Assert(cfile != NULL);
1797 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1798 cb = &Cfile_block_list[cfile->id];
1800 // not supported for memory mapped files
1801 Assert( !cb->data );
1803 Assert(cb->fp != NULL);
1804 return fflush(cb->fp);