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.12 2005/08/12 08:50:09 taylor
19 * recursively create directories (hurt more on OSX) and update all _mkdir() calls accordingly
21 * Revision 1.11 2004/07/04 11:27:29 taylor
22 * cleanup CFILE code a little, warning fixes, remove redundant dir checks, amd64 support
24 * Revision 1.10 2004/06/11 00:28:39 tigital
25 * byte-swapping changes for bigendian systems
27 * Revision 1.9 2003/05/25 02:30:42 taylor
30 * Revision 1.8 2003/02/20 17:41:07 theoddone33
31 * Userdir patch from Taylor Richards
33 * Revision 1.7 2002/12/30 03:23:29 relnev
34 * disable root dir check
36 * Revision 1.6 2002/06/17 06:33:08 relnev
37 * ryan's struct patch for gcc 2.95
39 * Revision 1.5 2002/06/09 04:41:15 relnev
40 * added copyright header
42 * Revision 1.4 2002/06/05 08:05:28 relnev
43 * stub/warning removal.
45 * reworked the sound code.
47 * Revision 1.3 2002/05/28 08:52:03 relnev
48 * implemented two assembly stubs.
50 * cleaned up a few warnings.
52 * added a little demo hackery to make it progress a little farther.
54 * Revision 1.2 2002/05/28 06:28:20 theoddone33
55 * Filesystem mods, actually reads some data files now
57 * Revision 1.1.1.1 2002/05/03 03:28:08 root
61 * 20 9/08/99 10:01p Dave
62 * Make sure game won't run in a drive's root directory. Make sure
63 * standalone routes suqad war messages properly to the host.
65 * 19 9/08/99 12:03a Dave
66 * Make squad logos render properly in D3D all the time. Added intel anim
69 * 18 9/06/99 2:35p Dave
70 * Rename briefing and debriefing voice direcrory paths properly.
72 * 17 9/03/99 1:31a Dave
73 * CD checking by act. Added support to play 2 cutscenes in a row
74 * seamlessly. Fixed super low level cfile bug related to files in the
75 * root directory of a CD. Added cheat code to set campaign mission # in
78 * 16 8/31/99 9:46a Dave
79 * Support for new cfile cbanims directory.
81 * 15 8/06/99 11:20a Johns
82 * Don't call game_cd_changed() in a demo or multiplayer beta build.
84 * 14 6/08/99 2:33p Dave
85 * Fixed release build warning. Put in hud config stuff.
87 * 13 5/19/99 4:07p Dave
88 * Moved versioning code into a nice isolated common place. Fixed up
89 * updating code on the pxo screen. Fixed several stub problems.
91 * 12 4/30/99 12:18p Dave
92 * Several minor bug fixes.
94 * 11 4/07/99 5:54p Dave
95 * Fixes for encryption in updatelauncher.
97 * 10 3/28/99 5:58p Dave
98 * Added early demo code. Make objects move. Nice and framerate
99 * independant, but not much else. Don't use yet unless you're me :)
101 * 9 2/22/99 10:31p Andsager
102 * Get rid of unneeded includes.
104 * 8 1/12/99 3:15a Dave
105 * Barracks screen support for selecting squad logos. We need real artwork
108 * 7 11/30/98 1:07p Dave
109 * 16 bit conversion, first run.
111 * 6 10/29/98 10:41a Dave
112 * Change the way cfile initializes exe directory.
114 * 5 10/13/98 9:19a Andsager
115 * Add localization support to cfile. Optional parameter with cfopen that
116 * looks for localized files.
118 * 4 10/12/98 9:54a Dave
119 * Fixed a few file organization things.
121 * 3 10/07/98 6:27p Dave
122 * Globalized mission and campaign file extensions. Removed Silent Threat
123 * special code. Moved \cache \players and \multidata into the \data
126 * 2 10/07/98 10:52a Dave
129 * 1 10/07/98 10:48a Dave
131 * 110 9/17/98 10:31a Hoffoss
132 * Changed code to use location of executable as root rather than relying
133 * on the cwd being set correctly. This is most helpful in the case of
134 * Fred launching due to the user double-clicking on an .fsm file in
135 * explorer or something (where the cwd is probably the location of the
138 * 109 9/11/98 4:14p Dave
139 * Fixed file checksumming of < file_size. Put in more verbose kicking and
140 * PXO stats store reporting.
142 * 108 9/09/98 5:53p Dave
143 * Put in new tracker packets in API. Change cfile to be able to checksum
144 * portions of a file.
146 * 107 9/04/98 3:51p Dave
147 * Put in validated mission updating and application during stats
150 * 106 8/31/98 2:06p Dave
151 * Make cfile sort the ordering or vp files. Added support/checks for
152 * recognizing "mission disk" players.
154 * 105 8/20/98 5:30p Dave
155 * Put in handy multiplayer logfile system. Now need to put in useful
156 * applications of it all over the code.
158 * 104 8/12/98 4:53p Dave
159 * Put in 32 bit checksumming for PXO missions. No validation on the
160 * actual tracker yet, though.
162 * 103 6/17/98 9:30a Allender
163 * fixed red alert replay stats clearing problem
165 * 102 6/05/98 9:46a Lawrance
166 * check for CD change on cfopen()
168 * 101 5/19/98 1:19p Allender
169 * new low level reliable socket reading code. Make all missions/campaign
170 * load/save to data missions folder (i.e. we are rid of the player
173 * 100 5/13/98 10:22p John
174 * Added cfile functions to read/write rle compressed blocks of data.
175 * Made palman use it for .clr files. Made alphacolors calculate on the
176 * fly rather than caching to/from disk.
178 * 99 5/11/98 10:59a John
179 * Moved the low-level file reading code into cfilearchive.cpp.
181 * 98 5/06/98 5:30p John
182 * Removed unused cfilearchiver. Removed/replaced some unused/little used
183 * graphics functions, namely gradient_h and _v and pixel_sp. Put in new
184 * DirectX header files and libs that fixed the Direct3D alpha blending
187 * 97 5/03/98 11:53a John
188 * Fixed filename case mangling.
190 * 96 5/03/98 8:33a John
191 * Made sure there weren't any more broken function lurking around like
192 * the one Allender fixed.
194 * 95 5/02/98 11:05p Allender
195 * fix cfilelength for pack files
200 #define _CFILE_INTERNAL
210 #include <winbase.h> /* needed for memory mapping of file functions */
213 #include <sys/stat.h>
214 #include <sys/types.h>
220 //#include "outwnd.h"
221 //#include "vecmat.h"
223 #include "cfilesystem.h"
224 #include "cfilearchive.h"
226 #include "osregistry.h" // for Osreg_user_dir
229 char Cfile_user_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
231 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
233 // During cfile_init, verify that Pathtypes[n].index == n for each item
234 // Each path must have a valid parent that can be tracable all the way back to the root
235 // so that we can create directories when we need to.
237 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
238 // What type this is Path Extensions Parent type
239 { CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
240 // Root must be index 1!!
241 { CF_TYPE_ROOT, "", ".mve", CF_TYPE_ROOT },
242 { CF_TYPE_DATA, "Data", ".cfg .log .txt", CF_TYPE_ROOT },
244 { CF_TYPE_MAPS, "Data/Maps", ".pcx .ani .tga", CF_TYPE_DATA },
245 { CF_TYPE_TEXT, "Data/Text", ".txt .net", CF_TYPE_DATA },
247 { CF_TYPE_MISSIONS, "Data/Missions", ".fsm .fsc .ntl .ssv", CF_TYPE_DATA },
249 { CF_TYPE_MISSIONS, "Data/Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
251 { CF_TYPE_MODELS, "Data/Models", ".pof", CF_TYPE_DATA },
252 { CF_TYPE_TABLES, "Data/Tables", ".tbl", CF_TYPE_DATA },
253 { CF_TYPE_SOUNDS, "Data/Sounds", ".wav", CF_TYPE_DATA },
254 { CF_TYPE_SOUNDS_8B22K, "Data/Sounds/8b22k", ".wav", CF_TYPE_SOUNDS },
255 { CF_TYPE_SOUNDS_16B11K, "Data/Sounds/16b11k", ".wav", CF_TYPE_SOUNDS },
256 { CF_TYPE_VOICE, "Data/Voice", "", CF_TYPE_DATA },
257 { CF_TYPE_VOICE_BRIEFINGS, "Data/Voice/Briefing", ".wav", CF_TYPE_VOICE },
258 { CF_TYPE_VOICE_CMD_BRIEF, "Data/Voice/Command_briefings",".wav", CF_TYPE_VOICE },
259 { CF_TYPE_VOICE_DEBRIEFINGS, "Data/Voice/Debriefing", ".wav", CF_TYPE_VOICE },
260 { CF_TYPE_VOICE_PERSONAS, "Data/Voice/Personas", ".wav", CF_TYPE_VOICE },
261 { CF_TYPE_VOICE_SPECIAL, "Data/Voice/Special", ".wav", CF_TYPE_VOICE },
262 { CF_TYPE_VOICE_TRAINING, "Data/Voice/Training", ".wav", CF_TYPE_VOICE },
263 { CF_TYPE_MUSIC, "Data/Music", ".wav", CF_TYPE_VOICE },
264 { CF_TYPE_MOVIES, "Data/Movies", ".mve .msb", CF_TYPE_DATA },
265 { CF_TYPE_INTERFACE, "Data/Interface", ".pcx .ani .tga", CF_TYPE_DATA },
266 { CF_TYPE_FONT, "Data/Fonts", ".vf", CF_TYPE_DATA },
267 { CF_TYPE_EFFECTS, "Data/Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
268 { CF_TYPE_HUD, "Data/Hud", ".ani .pcx .tga", CF_TYPE_DATA },
269 { CF_TYPE_PLAYER_MAIN, "Data/Players", "", CF_TYPE_DATA },
270 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data/Players/Images", ".pcx", CF_TYPE_PLAYER_MAIN },
271 { CF_TYPE_CACHE, "Data/Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
272 { CF_TYPE_PLAYERS, "Data/Players", ".hcf", CF_TYPE_DATA },
273 { CF_TYPE_SINGLE_PLAYERS, "Data/Players/Single", ".plr .csg .css", CF_TYPE_PLAYERS },
274 { CF_TYPE_MULTI_PLAYERS, "Data/Players/Multi", ".plr", CF_TYPE_DATA },
275 { CF_TYPE_MULTI_CACHE, "Data/MultiData", ".pcx .fs2", CF_TYPE_DATA },
276 { CF_TYPE_CONFIG, "Data/Config", ".cfg", CF_TYPE_DATA },
277 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data/Players/Squads", ".pcx", CF_TYPE_DATA },
278 { CF_TYPE_DEMOS, "Data/Demos", ".fsd", CF_TYPE_DATA },
279 { CF_TYPE_CBANIMS, "Data/CBAnims", ".ani", CF_TYPE_DATA },
280 { CF_TYPE_INTEL_ANIMS, "Data/IntelAnims", ".ani", CF_TYPE_DATA },
282 { CF_TYPE_MAPS, "Data\\Maps", ".pcx .ani .tga", CF_TYPE_DATA },
283 { CF_TYPE_TEXT, "Data\\Text", ".txt .net", CF_TYPE_DATA },
284 { CF_TYPE_MISSIONS, "Data\\Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
285 { CF_TYPE_MODELS, "Data\\Models", ".pof", CF_TYPE_DATA },
286 { CF_TYPE_TABLES, "Data\\Tables", ".tbl", CF_TYPE_DATA },
287 { CF_TYPE_SOUNDS, "Data\\Sounds", ".wav", CF_TYPE_DATA },
288 { CF_TYPE_SOUNDS_8B22K, "Data\\Sounds\\8b22k", ".wav", CF_TYPE_SOUNDS },
289 { CF_TYPE_SOUNDS_16B11K, "Data\\Sounds\\16b11k", ".wav", CF_TYPE_SOUNDS },
290 { CF_TYPE_VOICE, "Data\\Voice", "", CF_TYPE_DATA },
291 { CF_TYPE_VOICE_BRIEFINGS, "Data\\Voice\\Briefing", ".wav", CF_TYPE_VOICE },
292 { CF_TYPE_VOICE_CMD_BRIEF, "Data\\Voice\\Command_briefings",".wav", CF_TYPE_VOICE },
293 { CF_TYPE_VOICE_DEBRIEFINGS, "Data\\Voice\\Debriefing", ".wav", CF_TYPE_VOICE },
294 { CF_TYPE_VOICE_PERSONAS, "Data\\Voice\\Personas", ".wav", CF_TYPE_VOICE },
295 { CF_TYPE_VOICE_SPECIAL, "Data\\Voice\\Special", ".wav", CF_TYPE_VOICE },
296 { CF_TYPE_VOICE_TRAINING, "Data\\Voice\\Training", ".wav", CF_TYPE_VOICE },
297 { CF_TYPE_MUSIC, "Data\\Music", ".wav", CF_TYPE_VOICE },
298 { CF_TYPE_MOVIES, "Data\\Movies", ".mve .msb", CF_TYPE_DATA },
299 { CF_TYPE_INTERFACE, "Data\\Interface", ".pcx .ani .tga", CF_TYPE_DATA },
300 { CF_TYPE_FONT, "Data\\Fonts", ".vf", CF_TYPE_DATA },
301 { CF_TYPE_EFFECTS, "Data\\Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
302 { CF_TYPE_HUD, "Data\\Hud", ".ani .pcx .tga", CF_TYPE_DATA },
303 { CF_TYPE_PLAYER_MAIN, "Data\\Players", "", CF_TYPE_DATA },
304 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data\\Players\\Images", ".pcx", CF_TYPE_PLAYER_MAIN },
305 { CF_TYPE_CACHE, "Data\\Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
306 { CF_TYPE_PLAYERS, "Data\\Players", ".hcf", CF_TYPE_DATA },
307 { CF_TYPE_SINGLE_PLAYERS, "Data\\Players\\Single", ".plr .csg .css", CF_TYPE_PLAYERS },
308 { CF_TYPE_MULTI_PLAYERS, "Data\\Players\\Multi", ".plr", CF_TYPE_DATA },
309 { CF_TYPE_MULTI_CACHE, "Data\\MultiData", ".pcx .fs2", CF_TYPE_DATA },
310 { CF_TYPE_CONFIG, "Data\\Config", ".cfg", CF_TYPE_DATA },
311 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data\\Players\\Squads", ".pcx", CF_TYPE_DATA },
312 { CF_TYPE_DEMOS, "Data\\Demos", ".fsd", CF_TYPE_DATA },
313 { CF_TYPE_CBANIMS, "Data\\CBAnims", ".ani", CF_TYPE_DATA },
314 { CF_TYPE_INTEL_ANIMS, "Data\\IntelAnims", ".ani", CF_TYPE_DATA },
319 #define CFILE_STACK_MAX 8
321 int cfile_inited = 0;
322 int Cfile_stack_pos = 0;
324 char Cfile_stack[128][CFILE_STACK_MAX];
326 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
327 CFILE Cfile_list[MAX_CFILE_BLOCKS];
329 char *Cfile_cdrom_dir = NULL;
332 // Function prototypes for internally-called functions
334 int cfget_cfile_block();
335 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
336 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
337 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
338 void cf_chksum_long_init();
342 cf_free_secondary_filelist();
345 // determine if the given path is in a root directory (c:\ or c:\freespace2.exe or c:\fred2.exe etc)
346 int cfile_in_root_dir(char *exe_path)
349 char path_copy[2048] = "";
353 if(exe_path == NULL){
358 memset(path_copy, 0, 2048);
359 strncpy(path_copy, exe_path, 2047);
361 // count how many slashes there are in the path
362 tok = strtok(path_copy, DIR_SEPARATOR_STR);
368 tok = strtok(NULL, DIR_SEPARATOR_STR);
369 } while(tok != NULL);
371 // root directory if we have <= 1 slash
372 if(token_count <= 2){
376 // not-root directory
380 // cfile_init() initializes the cfile system. Called once at application start.
382 // returns: success ==> 0
383 // error ==> non-zero
385 int cfile_init(char *exe_dir, char *cdrom_dir)
389 // initialize encryption
392 if ( !cfile_inited ) {
397 strcpy(buf, exe_dir);
401 // are we in a root directory?
402 if(cfile_in_root_dir(buf)){
403 MessageBox((HWND)NULL, "Freespace2/Fred2 cannot be run from a drive root directory!", "Error", MB_OK);
409 if (buf[i] == DIR_SEPARATOR_CHAR){
419 fprintf (stderr, "Error trying to determine executable root directory!");
421 MessageBox((HWND)NULL, "Error trying to determine executable root directory!", "Error", MB_OK);
426 // set root directory
427 strncpy(Cfile_root_dir, buf, CFILE_ROOT_DIRECTORY_LEN-1);
430 snprintf(Cfile_user_dir, MAX_PATH, "%s/%s/", detect_home(), Osreg_user_dir);
432 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
433 Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
436 Cfile_cdrom_dir = cdrom_dir;
437 cf_build_secondary_filelist(Cfile_cdrom_dir);
439 // 32 bit CRC table init
440 cf_chksum_long_init();
442 atexit( cfile_close );
448 // Call this if pack files got added or removed or the
449 // cdrom changed. This will refresh the list of filenames
450 // stored in packfiles and on the cdrom.
453 cf_build_secondary_filelist(Cfile_cdrom_dir);
457 // Changes to a drive if valid.. 1=A, 2=B, etc
458 // If flag, then changes to it.
459 // Returns 0 if not-valid, 1 if valid.
460 int cfile_chdrive( int DriveNum, int flag )
473 _chdrive( DriveNum );
480 if ( (!flag) && (n != org) )
486 // push current directory on a 'stack' (so we can restore it) and change the directory
487 int cfile_push_chdir(int type)
491 char OriginalDirectory[128];
493 char NoDir[] = "\\.";
495 _getcwd(OriginalDirectory, 127);
496 Assert(Cfile_stack_pos < CFILE_STACK_MAX);
497 strcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
499 cf_create_default_path_string( dir, type, NULL );
502 char *Drive = strchr(dir, ':');
505 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
520 // This chdir might get a critical error!
523 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
531 int cfile_chdir(char *dir)
534 char OriginalDirectory[128];
536 char NoDir[] = "\\.";
538 _getcwd(OriginalDirectory, 127);
542 char *Drive = strchr(dir, ':');
544 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
559 // This chdir might get a critical error!
562 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
571 Assert(Cfile_stack_pos);
573 return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
576 // flush (delete all files in) the passed directory (by type), return the # of files deleted
577 // NOTE : WILL NOT DELETE READ-ONLY FILES
578 int cfile_flush_dir(int dir_type)
588 Assert( CF_TYPE_SPECIFIED(dir_type) );
590 // attempt to change the directory to the passed type
591 if(cfile_push_chdir(dir_type)){
595 // proceed to delete the files
596 find_handle = _findfirst( "*", &find );
598 if (find_handle != -1) {
600 if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
602 cf_delete(find.name,dir_type);
604 // increment the deleted count
607 } while (!_findnext(find_handle, &find));
608 _findclose( find_handle );
611 // pop the directory back
614 // return the # of files deleted
620 // add the given extention to a filename (or filepath) if it doesn't already have this
622 // filename = name of filename or filepath to process
623 // ext = extension to add. Must start with the period
624 // Returns: new filename or filepath with extension.
625 char *cf_add_ext(char *filename, char *ext)
628 static char path[MAX_PATH_LEN];
630 flen = strlen(filename);
632 Assert(flen < MAX_PATH_LEN);
633 strcpy(path, filename);
634 if ((flen < 4) || stricmp(path + flen - elen, ext)) {
635 Assert(flen + elen < MAX_PATH_LEN);
643 void cf_delete( char *filename, int dir_type )
645 char longname[MAX_PATH_LEN];
647 Assert( CF_TYPE_SPECIFIED(dir_type) );
649 cf_create_default_path_string( longname, dir_type, filename );
651 FILE *fp = fopen(longname, "rb");
661 // Same as _access function to read a file's access bits
662 int cf_access( char *filename, int dir_type, int mode )
664 char longname[MAX_PATH_LEN];
666 Assert( CF_TYPE_SPECIFIED(dir_type) );
668 cf_create_default_path_string( longname, dir_type, filename );
670 return access(longname,mode);
674 // Returns 1 if file exists, 0 if not.
675 int cf_exist( char *filename, int dir_type )
677 char longname[MAX_PATH_LEN];
679 Assert( CF_TYPE_SPECIFIED(dir_type) );
681 cf_create_default_path_string( longname, dir_type, filename );
683 FILE *fp = fopen(longname, "rb");
692 void cf_attrib(char *filename, int set, int clear, int dir_type)
694 char longname[MAX_PATH_LEN];
696 Assert( CF_TYPE_SPECIFIED(dir_type) );
698 cf_create_default_path_string( longname, dir_type, filename );
700 FILE *fp = fopen(longname, "rb");
707 DWORD z = GetFileAttributes(longname);
708 SetFileAttributes(longname, z | set & ~clear);
714 int cf_rename(char *old_name, char *name, int dir_type)
716 Assert( CF_TYPE_SPECIFIED(dir_type) );
719 char old_longname[_MAX_PATH];
720 char new_longname[_MAX_PATH];
722 cf_create_default_path_string( old_longname, dir_type, old_name );
723 cf_create_default_path_string( new_longname, dir_type, name );
725 ret_code = rename(old_longname, new_longname );
729 return CF_RENAME_FAIL_ACCESS;
732 return CF_RENAME_FAIL_EXIST;
736 return CF_RENAME_SUCCESS;
741 // Creates the directory path if it doesn't exist. Even creates all its
743 void cf_create_directory( int dir_type )
746 int dir_tree[CF_MAX_PATH_TYPES];
747 char longname[MAX_PATH_LEN];
749 Assert( CF_TYPE_SPECIFIED(dir_type) );
751 int current_dir = dir_type;
754 Assert( num_dirs < CF_MAX_PATH_TYPES ); // Invalid Pathtypes data?
756 dir_tree[num_dirs++] = current_dir;
757 current_dir = Pathtypes[current_dir].parent_index;
759 } while( current_dir != CF_TYPE_ROOT );
764 for (i=num_dirs-1; i>=0; i-- ) {
765 cf_create_default_path_string( longname, dir_tree[i], NULL );
767 if ( _mkdir(longname)==0 ) {
768 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
776 extern int game_cd_changed();
780 // parameters: *filepath ==> name of file to open (may be path+name)
781 // *mode ==> specifies how file should be opened (eg "rb" for read binary)
782 // passing NULL to mode deletes the file if it exists and returns NULL
783 // type ==> one of: CFILE_NORMAL
784 // CFILE_MEMORY_MAPPED
785 // dir_type => override extension check, value is one of CF_TYPE* #defines
787 // NOTE: type parameter is an optional parameter. The default value is CFILE_NORMAL
790 // returns: success ==> address of CFILE structure
794 CFILE *cfopen(char *file_path, char *mode, int type, int dir_type, bool localize)
796 char longname[_MAX_PATH];
798 // nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
799 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
801 // we no longer need to do this, and on machines with crappy-ass drivers it can slow things down horribly.
803 if ( game_cd_changed() ) {
808 //================================================
809 // Check that all the parameters make sense
810 Assert(file_path && strlen(file_path));
811 Assert( mode != NULL );
813 // Can only open read-only binary files in memory mapped mode.
814 if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
819 //===========================================================
820 // If in write mode, just try to open the file straight off
821 // the harddisk. No fancy packfile stuff here!
823 if ( strchr(mode,'w') ) {
824 // For write-only files, require a full path or a path type
826 if ( strpbrk(file_path, "/") ) {
828 if ( strpbrk(file_path,"/\\:") ) {
831 strcpy(longname, file_path );
834 Assert( dir_type != CF_TYPE_ANY );
836 // Create the directory if necessary
837 cf_create_directory( dir_type );
839 cf_create_default_path_string( longname, dir_type, file_path );
841 Assert( !(type & CFILE_MEMORY_MAPPED) );
843 // JOHN: TODO, you should create the path if it doesn't exist.
845 FILE *fp = fopen(longname, mode);
847 return cf_open_fill_cfblock(fp, dir_type);
853 //================================================
854 // Search for file on disk, on cdrom, or in a packfile
857 char copy_file_path[MAX_PATH_LEN]; // FIX change in memory from cf_find_file_location
858 strcpy(copy_file_path, file_path);
861 if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) ) {
863 // Fount it, now create a cfile out of it
865 if ( type & CFILE_MEMORY_MAPPED ) {
867 // Can't open memory mapped files out of pack files
874 hFile = CreateFile(longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
876 if (hFile != INVALID_HANDLE_VALUE) {
877 return cf_open_mapped_fill_cfblock(hFile, dir_type);
884 FILE *fp = fopen( longname, "rb" );
888 // Found it in a pack file
889 return cf_open_packed_cfblock(fp, dir_type, offset, size );
891 // Found it in a normal file
892 return cf_open_fill_cfblock(fp, dir_type);
903 // ------------------------------------------------------------------------
906 // Open up a temporary file. A unique name is automatically generated. The
907 // file will be automatically deleted when file is closed.
909 // return: NULL => tmp file could not be opened
910 // pointer to CFILE => tmp file successfully opened
917 return cf_open_fill_cfblock(fp, 0);
924 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
925 // Cfile_block_list[] array and return the index.
927 // returns: success ==> index in Cfile_block_list[] array
930 int cfget_cfile_block()
935 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
936 cb = &Cfile_block_list[i];
937 if ( cb->type == CFILE_BLOCK_UNUSED ) {
940 cb->type = CFILE_BLOCK_USED;
945 // If we've reached this point, a free Cfile_block could not be found
946 nprintf(("Warning","A free Cfile_block could not be found.\n"));
947 Assert(0); // out of free cfile blocks
952 // cfclose() closes the file
954 // returns: success ==> 0
957 int cfclose( CFILE * cfile )
961 Assert(cfile != NULL);
963 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
964 cb = &Cfile_block_list[cfile->id];
968 // close memory mapped file
972 result = UnmapViewOfFile((void*)cb->data);
974 result = CloseHandle(cb->hInFile);
975 Assert(result); // Ensure file handle is closed properly
976 result = CloseHandle(cb->hMapFile);
977 Assert(result); // Ensure file handle is closed properly
981 } else if ( cb->fp != NULL ) {
982 Assert(cb->fp != NULL);
983 result = fclose(cb->fp);
988 cb->type = CFILE_BLOCK_UNUSED;
995 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
996 // for the case of a file being opened by cf_open();
998 // returns: success ==> ptr to CFILE structure.
1001 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
1003 int cfile_block_index;
1005 cfile_block_index = cfget_cfile_block();
1006 if ( cfile_block_index == -1 ) {
1011 cfbp = &Cfile_block_list[cfile_block_index];
1012 cfp = &Cfile_list[cfile_block_index];;
1013 cfp->id = cfile_block_index;
1017 cfbp->dir_type = type;
1019 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
1026 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1027 // for the case of a file being opened by cf_open();
1029 // returns: success ==> ptr to CFILE structure.
1032 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
1034 // Found it in a pack file
1035 int cfile_block_index;
1037 cfile_block_index = cfget_cfile_block();
1038 if ( cfile_block_index == -1 ) {
1043 cfbp = &Cfile_block_list[cfile_block_index];
1045 cfp = &Cfile_list[cfile_block_index];
1046 cfp->id = cfile_block_index;
1050 cfbp->dir_type = type;
1052 cf_init_lowlevel_read_code(cfp,offset, size );
1061 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1062 // for the case of a file being opened by cf_open_mapped();
1064 // returns: ptr CFILE structure.
1066 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
1068 int cfile_block_index;
1070 cfile_block_index = cfget_cfile_block();
1071 if ( cfile_block_index == -1 ) {
1077 cfbp = &Cfile_block_list[cfile_block_index];
1079 cfp = &Cfile_list[cfile_block_index];
1080 cfp->id = cfile_block_index;
1082 cfbp->hInFile = hFile;
1083 cfbp->dir_type = type;
1085 cf_init_lowlevel_read_code(cfp,0 , 0 );
1090 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
1091 if (cfbp->hMapFile == NULL) {
1092 nprintf(("Error", "Could not create file-mapping object.\n"));
1096 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1097 Assert( cfbp->data != NULL );
1103 int cf_get_dir_type(CFILE *cfile)
1105 return Cfile_block_list[cfile->id].dir_type;
1108 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1109 // with the CFILE structure passed as a parameter
1113 void *cf_returndata(CFILE *cfile)
1115 Assert(cfile != NULL);
1117 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1118 cb = &Cfile_block_list[cfile->id];
1119 Assert(cb->data != NULL);
1125 // version number of opened file. Will be 0 unless you put something else here after you
1126 // open a file. Once set, you can use minimum version numbers with the read functions.
1127 void cf_set_version( CFILE * cfile, int version )
1129 Assert(cfile != NULL);
1131 cfile->version = version;
1134 // routines to read basic data types from CFILE's. Put here to
1135 // simplify mac/pc reading from cfiles.
1140 float cfread_float(CFILE *file, int ver, float deflt)
1144 if (file->version < ver)
1147 if (cfread( &f, sizeof(f), 1, file) != 1)
1150 f = INTEL_FLOAT(&f);
1154 int cfread_int(CFILE *file, int ver, int deflt)
1158 if (file->version < ver)
1161 if (cfread( &i, sizeof(i), 1, file) != 1)
1168 uint cfread_uint(CFILE *file, int ver, uint deflt)
1172 if (file->version < ver)
1175 if (cfread( &i, sizeof(i), 1, file) != 1)
1182 short cfread_short(CFILE *file, int ver, short deflt)
1186 if (file->version < ver)
1189 if (cfread( &s, sizeof(s), 1, file) != 1)
1196 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1200 if (file->version < ver)
1203 if (cfread( &s, sizeof(s), 1, file) != 1)
1210 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1214 if (file->version < ver)
1217 if (cfread( &b, sizeof(b), 1, file) != 1)
1223 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1225 if (file->version < ver) {
1229 vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
1234 vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
1235 vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
1236 vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
1239 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1241 if (file->version < ver) {
1245 ang->p = ang->b = ang->h = 0.0f;
1250 ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
1251 ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
1252 ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
1255 char cfread_char(CFILE *file, int ver, char deflt)
1259 if (file->version < ver)
1262 if (cfread( &b, sizeof(b), 1, file) != 1)
1268 void cfread_string(char *buf, int n, CFILE *file)
1273 c = cfread_char(file);
1281 void cfread_string_len(char *buf,int n, CFILE *file)
1284 len = cfread_int(file);
1287 cfread(buf, len, 1, file);
1292 // equivalent write functions of above read functions follow
1294 int cfwrite_float(float f, CFILE *file)
1296 f = INTEL_FLOAT(&f);
1297 return cfwrite(&f, sizeof(f), 1, file);
1300 int cfwrite_int(int i, CFILE *file)
1303 return cfwrite(&i, sizeof(i), 1, file);
1306 int cfwrite_uint(uint i, CFILE *file)
1309 return cfwrite(&i, sizeof(i), 1, file);
1312 int cfwrite_short(short s, CFILE *file)
1315 return cfwrite(&s, sizeof(s), 1, file);
1318 int cfwrite_ushort(ushort s, CFILE *file)
1321 return cfwrite(&s, sizeof(s), 1, file);
1324 int cfwrite_ubyte(ubyte b, CFILE *file)
1326 return cfwrite(&b, sizeof(b), 1, file);
1329 int cfwrite_vector(vector *vec, CFILE *file)
1331 if(!cfwrite_float(vec->xyz.x, file)){
1334 if(!cfwrite_float(vec->xyz.y, file)){
1337 return cfwrite_float(vec->xyz.z, file);
1340 int cfwrite_angles(angles *ang, CFILE *file)
1342 if(!cfwrite_float(ang->p, file)){
1345 if(!cfwrite_float(ang->b, file)){
1348 return cfwrite_float(ang->h, file);
1351 int cfwrite_char(char b, CFILE *file)
1353 return cfwrite( &b, sizeof(b), 1, file);
1356 int cfwrite_string(char *buf, CFILE *file)
1358 if ( (!buf) || (buf && !buf[0]) ) {
1359 return cfwrite_char(0, file);
1361 int len = strlen(buf);
1362 if(!cfwrite(buf, len, 1, file)){
1365 return cfwrite_char(0, file); // write out NULL termination
1368 int cfwrite_string_len(char *buf, CFILE *file)
1370 int len = strlen(buf);
1372 if(!cfwrite_int(len, file)){
1376 return cfwrite(buf,len,1,file);
1382 // Get the filelength
1383 int cfilelength( CFILE * cfile )
1385 Assert(cfile != NULL);
1387 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1388 cb = &Cfile_block_list[cfile->id];
1390 // TODO: return length of memory mapped file
1391 Assert( !cb->data );
1393 Assert(cb->fp != NULL);
1395 // cb->size gets set at cfopen
1399 // cfwrite() writes to the file
1401 // returns: number of full elements actually written
1404 int cfwrite(void *buf, int elsize, int nelem, CFILE *cfile)
1406 Assert(cfile != NULL);
1407 Assert(buf != NULL);
1412 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1413 cb = &Cfile_block_list[cfile->id];
1417 // cfwrite() not supported for memory-mapped files
1418 Assert( !cb->data );
1420 Assert(cb->fp != NULL);
1421 Assert(cb->lib_offset == 0 );
1422 result = fwrite(buf, elsize, nelem, cb->fp);
1428 // cfputc() writes a character to a file
1430 // returns: success ==> returns character written
1433 int cfputc(int c, CFILE *cfile)
1437 Assert(cfile != NULL);
1439 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1440 cb = &Cfile_block_list[cfile->id];
1443 // cfputc() not supported for memory-mapped files
1444 Assert( !cb->data );
1446 Assert(cb->fp != NULL);
1447 result = fputc(c, cb->fp);
1453 // cfgetc() reads a character from a file
1455 // returns: success ==> returns character read
1458 int cfgetc(CFILE *cfile)
1460 Assert(cfile != NULL);
1464 int result = cfread(&tmp, 1, 1, cfile );
1465 if ( result == 1 ) {
1478 // cfgets() reads a string from a file
1480 // returns: success ==> returns pointer to string
1483 char *cfgets(char *buf, int n, CFILE *cfile)
1485 Assert(cfile != NULL);
1486 Assert(buf != NULL);
1492 for (i=0; i<n-1; i++ ) {
1496 int ret = cfread( &tmp_c, 1, 1, cfile );
1506 } while ( c == 13 );
1508 if ( c=='\n' ) break;
1515 // cfputs() writes a string to a file
1517 // returns: success ==> non-negative value
1520 int cfputs(char *str, CFILE *cfile)
1522 Assert(cfile != NULL);
1523 Assert(str != NULL);
1526 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1527 cb = &Cfile_block_list[cfile->id];
1532 // cfputs() not supported for memory-mapped files
1533 Assert( !cb->data );
1534 Assert(cb->fp != NULL);
1535 result = fputs(str, cb->fp);
1541 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1543 // CRC code for mission validation. given to us by Kevin Bentley on 7/20/98. Some sort of
1544 // checksumming code that he wrote a while ago.
1545 #define CRC32_POLYNOMIAL 0xEDB88320L
1546 unsigned long CRCTable[256];
1548 #define CF_CHKSUM_SAMPLE_SIZE 512
1550 // update cur_chksum with the chksum of the new_data of size new_data_size
1551 ushort cf_add_chksum_short(ushort seed, char *buffer, int size)
1553 ubyte * ptr = (ubyte *)buffer;
1554 unsigned int sum1,sum2;
1556 sum1 = sum2 = (int)(seed);
1560 if (sum1 >= 255 ) sum1 -= 255;
1565 return (unsigned short)((sum1<<8)+ sum2);
1568 // update cur_chksum with the chksum of the new_data of size new_data_size
1569 unsigned long cf_add_chksum_long(unsigned long seed, char *buffer, int size)
1573 unsigned long temp1;
1574 unsigned long temp2;
1576 p = (unsigned char*)buffer;
1580 temp1 = (crc>>8)&0x00FFFFFFL;
1581 temp2 = CRCTable[((int)crc^*p++)&0xff];
1588 void cf_chksum_long_init()
1593 for( i=0;i<=255;i++) {
1597 crc=(crc>>1)^CRC32_POLYNOMIAL;
1605 // single function convenient to use for both short and long checksums
1606 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1607 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1609 char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1615 // determine whether we're doing a short or long checksum
1626 // if max_size is -1, set it to be the size of the file
1628 cfseek(cfile, 0, SEEK_SET);
1629 max_size = cfilelength(cfile);
1634 // determine how much we want to read
1635 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1636 read_size = CF_CHKSUM_SAMPLE_SIZE;
1638 read_size = max_size - cf_total;
1641 // read in some buffer
1642 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1644 // total we've read so far
1649 // do the proper short or long checksum
1651 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1653 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1656 } while((cf_len > 0) && (cf_total < max_size));
1661 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1662 int cf_chksum_short(char *filename, ushort *chksum, int max_size, int cf_type)
1665 CFILE *cfile = NULL;
1667 // zero the checksum
1670 // attempt to open the file
1671 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1676 // call the overloaded cf_chksum function()
1677 ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1679 // close the file down
1683 // return the result
1687 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1688 // NOTE : preserves current file position
1689 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1694 // Returns current position of file.
1695 start_pos = cftell(file);
1696 if(start_pos == -1){
1700 // move to the beginning of the file
1701 if(cfseek(file, 0, CF_SEEK_SET)){
1704 ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1705 // move back to the start position
1706 cfseek(file, start_pos, CF_SEEK_SET);
1711 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1712 int cf_chksum_long(char *filename, uint *chksum, int max_size, int cf_type)
1715 CFILE *cfile = NULL;
1717 // zero the checksum
1720 // attempt to open the file
1721 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1726 // call the overloaded cf_chksum function()
1727 ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1729 // close the file down
1733 // return the result
1737 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1738 // NOTE : preserves current file position
1739 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1744 // Returns current position of file.
1745 start_pos = cftell(file);
1746 if(start_pos == -1){
1750 // move to the beginning of the file
1751 if(cfseek(file, 0, CF_SEEK_SET)){
1754 ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1755 // move back to the start position
1756 cfseek(file, start_pos, CF_SEEK_SET);
1762 // Flush the open file buffer
1764 // exit: 0 - success
1766 int cflush(CFILE *cfile)
1768 Assert(cfile != NULL);
1770 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1771 cb = &Cfile_block_list[cfile->id];
1773 // not supported for memory mapped files
1774 Assert( !cb->data );
1776 Assert(cb->fp != NULL);
1777 return fflush(cb->fp);