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.11 2004/07/04 11:27:29 taylor
19 * cleanup CFILE code a little, warning fixes, remove redundant dir checks, amd64 support
21 * Revision 1.10 2004/06/11 00:28:39 tigital
22 * byte-swapping changes for bigendian systems
24 * Revision 1.9 2003/05/25 02:30:42 taylor
27 * Revision 1.8 2003/02/20 17:41:07 theoddone33
28 * Userdir patch from Taylor Richards
30 * Revision 1.7 2002/12/30 03:23:29 relnev
31 * disable root dir check
33 * Revision 1.6 2002/06/17 06:33:08 relnev
34 * ryan's struct patch for gcc 2.95
36 * Revision 1.5 2002/06/09 04:41:15 relnev
37 * added copyright header
39 * Revision 1.4 2002/06/05 08:05:28 relnev
40 * stub/warning removal.
42 * reworked the sound code.
44 * Revision 1.3 2002/05/28 08:52:03 relnev
45 * implemented two assembly stubs.
47 * cleaned up a few warnings.
49 * added a little demo hackery to make it progress a little farther.
51 * Revision 1.2 2002/05/28 06:28:20 theoddone33
52 * Filesystem mods, actually reads some data files now
54 * Revision 1.1.1.1 2002/05/03 03:28:08 root
58 * 20 9/08/99 10:01p Dave
59 * Make sure game won't run in a drive's root directory. Make sure
60 * standalone routes suqad war messages properly to the host.
62 * 19 9/08/99 12:03a Dave
63 * Make squad logos render properly in D3D all the time. Added intel anim
66 * 18 9/06/99 2:35p Dave
67 * Rename briefing and debriefing voice direcrory paths properly.
69 * 17 9/03/99 1:31a Dave
70 * CD checking by act. Added support to play 2 cutscenes in a row
71 * seamlessly. Fixed super low level cfile bug related to files in the
72 * root directory of a CD. Added cheat code to set campaign mission # in
75 * 16 8/31/99 9:46a Dave
76 * Support for new cfile cbanims directory.
78 * 15 8/06/99 11:20a Johns
79 * Don't call game_cd_changed() in a demo or multiplayer beta build.
81 * 14 6/08/99 2:33p Dave
82 * Fixed release build warning. Put in hud config stuff.
84 * 13 5/19/99 4:07p Dave
85 * Moved versioning code into a nice isolated common place. Fixed up
86 * updating code on the pxo screen. Fixed several stub problems.
88 * 12 4/30/99 12:18p Dave
89 * Several minor bug fixes.
91 * 11 4/07/99 5:54p Dave
92 * Fixes for encryption in updatelauncher.
94 * 10 3/28/99 5:58p Dave
95 * Added early demo code. Make objects move. Nice and framerate
96 * independant, but not much else. Don't use yet unless you're me :)
98 * 9 2/22/99 10:31p Andsager
99 * Get rid of unneeded includes.
101 * 8 1/12/99 3:15a Dave
102 * Barracks screen support for selecting squad logos. We need real artwork
105 * 7 11/30/98 1:07p Dave
106 * 16 bit conversion, first run.
108 * 6 10/29/98 10:41a Dave
109 * Change the way cfile initializes exe directory.
111 * 5 10/13/98 9:19a Andsager
112 * Add localization support to cfile. Optional parameter with cfopen that
113 * looks for localized files.
115 * 4 10/12/98 9:54a Dave
116 * Fixed a few file organization things.
118 * 3 10/07/98 6:27p Dave
119 * Globalized mission and campaign file extensions. Removed Silent Threat
120 * special code. Moved \cache \players and \multidata into the \data
123 * 2 10/07/98 10:52a Dave
126 * 1 10/07/98 10:48a Dave
128 * 110 9/17/98 10:31a Hoffoss
129 * Changed code to use location of executable as root rather than relying
130 * on the cwd being set correctly. This is most helpful in the case of
131 * Fred launching due to the user double-clicking on an .fsm file in
132 * explorer or something (where the cwd is probably the location of the
135 * 109 9/11/98 4:14p Dave
136 * Fixed file checksumming of < file_size. Put in more verbose kicking and
137 * PXO stats store reporting.
139 * 108 9/09/98 5:53p Dave
140 * Put in new tracker packets in API. Change cfile to be able to checksum
141 * portions of a file.
143 * 107 9/04/98 3:51p Dave
144 * Put in validated mission updating and application during stats
147 * 106 8/31/98 2:06p Dave
148 * Make cfile sort the ordering or vp files. Added support/checks for
149 * recognizing "mission disk" players.
151 * 105 8/20/98 5:30p Dave
152 * Put in handy multiplayer logfile system. Now need to put in useful
153 * applications of it all over the code.
155 * 104 8/12/98 4:53p Dave
156 * Put in 32 bit checksumming for PXO missions. No validation on the
157 * actual tracker yet, though.
159 * 103 6/17/98 9:30a Allender
160 * fixed red alert replay stats clearing problem
162 * 102 6/05/98 9:46a Lawrance
163 * check for CD change on cfopen()
165 * 101 5/19/98 1:19p Allender
166 * new low level reliable socket reading code. Make all missions/campaign
167 * load/save to data missions folder (i.e. we are rid of the player
170 * 100 5/13/98 10:22p John
171 * Added cfile functions to read/write rle compressed blocks of data.
172 * Made palman use it for .clr files. Made alphacolors calculate on the
173 * fly rather than caching to/from disk.
175 * 99 5/11/98 10:59a John
176 * Moved the low-level file reading code into cfilearchive.cpp.
178 * 98 5/06/98 5:30p John
179 * Removed unused cfilearchiver. Removed/replaced some unused/little used
180 * graphics functions, namely gradient_h and _v and pixel_sp. Put in new
181 * DirectX header files and libs that fixed the Direct3D alpha blending
184 * 97 5/03/98 11:53a John
185 * Fixed filename case mangling.
187 * 96 5/03/98 8:33a John
188 * Made sure there weren't any more broken function lurking around like
189 * the one Allender fixed.
191 * 95 5/02/98 11:05p Allender
192 * fix cfilelength for pack files
197 #define _CFILE_INTERNAL
207 #include <winbase.h> /* needed for memory mapping of file functions */
210 #include <sys/stat.h>
211 #include <sys/types.h>
217 //#include "outwnd.h"
218 //#include "vecmat.h"
220 #include "cfilesystem.h"
221 #include "cfilearchive.h"
223 #include "osregistry.h" // for Osreg_user_dir
226 char Cfile_user_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
228 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
230 // During cfile_init, verify that Pathtypes[n].index == n for each item
231 // Each path must have a valid parent that can be tracable all the way back to the root
232 // so that we can create directories when we need to.
234 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
235 // What type this is Path Extensions Parent type
236 { CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
237 // Root must be index 1!!
238 { CF_TYPE_ROOT, "", ".mve", CF_TYPE_ROOT },
239 { CF_TYPE_DATA, "Data", ".cfg .log .txt", CF_TYPE_ROOT },
241 { CF_TYPE_MAPS, "Data/Maps", ".pcx .ani .tga", CF_TYPE_DATA },
242 { CF_TYPE_TEXT, "Data/Text", ".txt .net", CF_TYPE_DATA },
244 { CF_TYPE_MISSIONS, "Data/Missions", ".fsm .fsc .ntl .ssv", CF_TYPE_DATA },
246 { CF_TYPE_MISSIONS, "Data/Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
248 { CF_TYPE_MODELS, "Data/Models", ".pof", CF_TYPE_DATA },
249 { CF_TYPE_TABLES, "Data/Tables", ".tbl", CF_TYPE_DATA },
250 { CF_TYPE_SOUNDS, "Data/Sounds", ".wav", CF_TYPE_DATA },
251 { CF_TYPE_SOUNDS_8B22K, "Data/Sounds/8b22k", ".wav", CF_TYPE_SOUNDS },
252 { CF_TYPE_SOUNDS_16B11K, "Data/Sounds/16b11k", ".wav", CF_TYPE_SOUNDS },
253 { CF_TYPE_VOICE, "Data/Voice", "", CF_TYPE_DATA },
254 { CF_TYPE_VOICE_BRIEFINGS, "Data/Voice/Briefing", ".wav", CF_TYPE_VOICE },
255 { CF_TYPE_VOICE_CMD_BRIEF, "Data/Voice/Command_briefings",".wav", CF_TYPE_VOICE },
256 { CF_TYPE_VOICE_DEBRIEFINGS, "Data/Voice/Debriefing", ".wav", CF_TYPE_VOICE },
257 { CF_TYPE_VOICE_PERSONAS, "Data/Voice/Personas", ".wav", CF_TYPE_VOICE },
258 { CF_TYPE_VOICE_SPECIAL, "Data/Voice/Special", ".wav", CF_TYPE_VOICE },
259 { CF_TYPE_VOICE_TRAINING, "Data/Voice/Training", ".wav", CF_TYPE_VOICE },
260 { CF_TYPE_MUSIC, "Data/Music", ".wav", CF_TYPE_VOICE },
261 { CF_TYPE_MOVIES, "Data/Movies", ".mve .msb", CF_TYPE_DATA },
262 { CF_TYPE_INTERFACE, "Data/Interface", ".pcx .ani .tga", CF_TYPE_DATA },
263 { CF_TYPE_FONT, "Data/Fonts", ".vf", CF_TYPE_DATA },
264 { CF_TYPE_EFFECTS, "Data/Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
265 { CF_TYPE_HUD, "Data/Hud", ".ani .pcx .tga", CF_TYPE_DATA },
266 { CF_TYPE_PLAYER_MAIN, "Data/Players", "", CF_TYPE_DATA },
267 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data/Players/Images", ".pcx", CF_TYPE_PLAYER_MAIN },
268 { CF_TYPE_CACHE, "Data/Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
269 { CF_TYPE_PLAYERS, "Data/Players", ".hcf", CF_TYPE_DATA },
270 { CF_TYPE_SINGLE_PLAYERS, "Data/Players/Single", ".plr .csg .css", CF_TYPE_PLAYERS },
271 { CF_TYPE_MULTI_PLAYERS, "Data/Players/Multi", ".plr", CF_TYPE_DATA },
272 { CF_TYPE_MULTI_CACHE, "Data/MultiData", ".pcx .fs2", CF_TYPE_DATA },
273 { CF_TYPE_CONFIG, "Data/Config", ".cfg", CF_TYPE_DATA },
274 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data/Players/Squads", ".pcx", CF_TYPE_DATA },
275 { CF_TYPE_DEMOS, "Data/Demos", ".fsd", CF_TYPE_DATA },
276 { CF_TYPE_CBANIMS, "Data/CBAnims", ".ani", CF_TYPE_DATA },
277 { CF_TYPE_INTEL_ANIMS, "Data/IntelAnims", ".ani", CF_TYPE_DATA },
279 { CF_TYPE_MAPS, "Data\\Maps", ".pcx .ani .tga", CF_TYPE_DATA },
280 { CF_TYPE_TEXT, "Data\\Text", ".txt .net", CF_TYPE_DATA },
281 { CF_TYPE_MISSIONS, "Data\\Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
282 { CF_TYPE_MODELS, "Data\\Models", ".pof", CF_TYPE_DATA },
283 { CF_TYPE_TABLES, "Data\\Tables", ".tbl", CF_TYPE_DATA },
284 { CF_TYPE_SOUNDS, "Data\\Sounds", ".wav", CF_TYPE_DATA },
285 { CF_TYPE_SOUNDS_8B22K, "Data\\Sounds\\8b22k", ".wav", CF_TYPE_SOUNDS },
286 { CF_TYPE_SOUNDS_16B11K, "Data\\Sounds\\16b11k", ".wav", CF_TYPE_SOUNDS },
287 { CF_TYPE_VOICE, "Data\\Voice", "", CF_TYPE_DATA },
288 { CF_TYPE_VOICE_BRIEFINGS, "Data\\Voice\\Briefing", ".wav", CF_TYPE_VOICE },
289 { CF_TYPE_VOICE_CMD_BRIEF, "Data\\Voice\\Command_briefings",".wav", CF_TYPE_VOICE },
290 { CF_TYPE_VOICE_DEBRIEFINGS, "Data\\Voice\\Debriefing", ".wav", CF_TYPE_VOICE },
291 { CF_TYPE_VOICE_PERSONAS, "Data\\Voice\\Personas", ".wav", CF_TYPE_VOICE },
292 { CF_TYPE_VOICE_SPECIAL, "Data\\Voice\\Special", ".wav", CF_TYPE_VOICE },
293 { CF_TYPE_VOICE_TRAINING, "Data\\Voice\\Training", ".wav", CF_TYPE_VOICE },
294 { CF_TYPE_MUSIC, "Data\\Music", ".wav", CF_TYPE_VOICE },
295 { CF_TYPE_MOVIES, "Data\\Movies", ".mve .msb", CF_TYPE_DATA },
296 { CF_TYPE_INTERFACE, "Data\\Interface", ".pcx .ani .tga", CF_TYPE_DATA },
297 { CF_TYPE_FONT, "Data\\Fonts", ".vf", CF_TYPE_DATA },
298 { CF_TYPE_EFFECTS, "Data\\Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
299 { CF_TYPE_HUD, "Data\\Hud", ".ani .pcx .tga", CF_TYPE_DATA },
300 { CF_TYPE_PLAYER_MAIN, "Data\\Players", "", CF_TYPE_DATA },
301 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data\\Players\\Images", ".pcx", CF_TYPE_PLAYER_MAIN },
302 { CF_TYPE_CACHE, "Data\\Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
303 { CF_TYPE_PLAYERS, "Data\\Players", ".hcf", CF_TYPE_DATA },
304 { CF_TYPE_SINGLE_PLAYERS, "Data\\Players\\Single", ".plr .csg .css", CF_TYPE_PLAYERS },
305 { CF_TYPE_MULTI_PLAYERS, "Data\\Players\\Multi", ".plr", CF_TYPE_DATA },
306 { CF_TYPE_MULTI_CACHE, "Data\\MultiData", ".pcx .fs2", CF_TYPE_DATA },
307 { CF_TYPE_CONFIG, "Data\\Config", ".cfg", CF_TYPE_DATA },
308 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data\\Players\\Squads", ".pcx", CF_TYPE_DATA },
309 { CF_TYPE_DEMOS, "Data\\Demos", ".fsd", CF_TYPE_DATA },
310 { CF_TYPE_CBANIMS, "Data\\CBAnims", ".ani", CF_TYPE_DATA },
311 { CF_TYPE_INTEL_ANIMS, "Data\\IntelAnims", ".ani", CF_TYPE_DATA },
316 #define CFILE_STACK_MAX 8
318 int cfile_inited = 0;
319 int Cfile_stack_pos = 0;
321 char Cfile_stack[128][CFILE_STACK_MAX];
323 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
324 CFILE Cfile_list[MAX_CFILE_BLOCKS];
326 char *Cfile_cdrom_dir = NULL;
329 // Function prototypes for internally-called functions
331 int cfget_cfile_block();
332 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
333 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
334 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
335 void cf_chksum_long_init();
339 cf_free_secondary_filelist();
342 // determine if the given path is in a root directory (c:\ or c:\freespace2.exe or c:\fred2.exe etc)
343 int cfile_in_root_dir(char *exe_path)
346 char path_copy[2048] = "";
350 if(exe_path == NULL){
355 memset(path_copy, 0, 2048);
356 strncpy(path_copy, exe_path, 2047);
358 // count how many slashes there are in the path
359 tok = strtok(path_copy, DIR_SEPARATOR_STR);
365 tok = strtok(NULL, DIR_SEPARATOR_STR);
366 } while(tok != NULL);
368 // root directory if we have <= 1 slash
369 if(token_count <= 2){
373 // not-root directory
377 // cfile_init() initializes the cfile system. Called once at application start.
379 // returns: success ==> 0
380 // error ==> non-zero
382 int cfile_init(char *exe_dir, char *cdrom_dir)
386 // initialize encryption
389 if ( !cfile_inited ) {
394 strcpy(buf, exe_dir);
398 // are we in a root directory?
399 if(cfile_in_root_dir(buf)){
400 MessageBox((HWND)NULL, "Freespace2/Fred2 cannot be run from a drive root directory!", "Error", MB_OK);
406 if (buf[i] == DIR_SEPARATOR_CHAR){
416 fprintf (stderr, "Error trying to determine executable root directory!");
418 MessageBox((HWND)NULL, "Error trying to determine executable root directory!", "Error", MB_OK);
423 // set root directory
424 strncpy(Cfile_root_dir, buf, CFILE_ROOT_DIRECTORY_LEN-1);
427 snprintf(Cfile_user_dir, MAX_PATH, "%s/%s/", detect_home(), Osreg_user_dir);
429 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
430 Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
433 Cfile_cdrom_dir = cdrom_dir;
434 cf_build_secondary_filelist(Cfile_cdrom_dir);
436 // 32 bit CRC table init
437 cf_chksum_long_init();
439 atexit( cfile_close );
445 // Call this if pack files got added or removed or the
446 // cdrom changed. This will refresh the list of filenames
447 // stored in packfiles and on the cdrom.
450 cf_build_secondary_filelist(Cfile_cdrom_dir);
454 // Changes to a drive if valid.. 1=A, 2=B, etc
455 // If flag, then changes to it.
456 // Returns 0 if not-valid, 1 if valid.
457 int cfile_chdrive( int DriveNum, int flag )
470 _chdrive( DriveNum );
477 if ( (!flag) && (n != org) )
483 // push current directory on a 'stack' (so we can restore it) and change the directory
484 int cfile_push_chdir(int type)
488 char OriginalDirectory[128];
490 char NoDir[] = "\\.";
492 _getcwd(OriginalDirectory, 127);
493 Assert(Cfile_stack_pos < CFILE_STACK_MAX);
494 strcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
496 cf_create_default_path_string( dir, type, NULL );
499 char *Drive = strchr(dir, ':');
502 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
517 // This chdir might get a critical error!
520 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
528 int cfile_chdir(char *dir)
531 char OriginalDirectory[128];
533 char NoDir[] = "\\.";
535 _getcwd(OriginalDirectory, 127);
539 char *Drive = strchr(dir, ':');
541 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
556 // This chdir might get a critical error!
559 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
568 Assert(Cfile_stack_pos);
570 return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
573 // flush (delete all files in) the passed directory (by type), return the # of files deleted
574 // NOTE : WILL NOT DELETE READ-ONLY FILES
575 int cfile_flush_dir(int dir_type)
585 Assert( CF_TYPE_SPECIFIED(dir_type) );
587 // attempt to change the directory to the passed type
588 if(cfile_push_chdir(dir_type)){
592 // proceed to delete the files
593 find_handle = _findfirst( "*", &find );
595 if (find_handle != -1) {
597 if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
599 cf_delete(find.name,dir_type);
601 // increment the deleted count
604 } while (!_findnext(find_handle, &find));
605 _findclose( find_handle );
608 // pop the directory back
611 // return the # of files deleted
617 // add the given extention to a filename (or filepath) if it doesn't already have this
619 // filename = name of filename or filepath to process
620 // ext = extension to add. Must start with the period
621 // Returns: new filename or filepath with extension.
622 char *cf_add_ext(char *filename, char *ext)
625 static char path[MAX_PATH_LEN];
627 flen = strlen(filename);
629 Assert(flen < MAX_PATH_LEN);
630 strcpy(path, filename);
631 if ((flen < 4) || stricmp(path + flen - elen, ext)) {
632 Assert(flen + elen < MAX_PATH_LEN);
640 void cf_delete( char *filename, int dir_type )
642 char longname[MAX_PATH_LEN];
644 Assert( CF_TYPE_SPECIFIED(dir_type) );
646 cf_create_default_path_string( longname, dir_type, filename );
648 FILE *fp = fopen(longname, "rb");
658 // Same as _access function to read a file's access bits
659 int cf_access( char *filename, int dir_type, int mode )
661 char longname[MAX_PATH_LEN];
663 Assert( CF_TYPE_SPECIFIED(dir_type) );
665 cf_create_default_path_string( longname, dir_type, filename );
667 return access(longname,mode);
671 // Returns 1 if file exists, 0 if not.
672 int cf_exist( char *filename, int dir_type )
674 char longname[MAX_PATH_LEN];
676 Assert( CF_TYPE_SPECIFIED(dir_type) );
678 cf_create_default_path_string( longname, dir_type, filename );
680 FILE *fp = fopen(longname, "rb");
689 void cf_attrib(char *filename, int set, int clear, int dir_type)
691 char longname[MAX_PATH_LEN];
693 Assert( CF_TYPE_SPECIFIED(dir_type) );
695 cf_create_default_path_string( longname, dir_type, filename );
697 FILE *fp = fopen(longname, "rb");
704 DWORD z = GetFileAttributes(longname);
705 SetFileAttributes(longname, z | set & ~clear);
711 int cf_rename(char *old_name, char *name, int dir_type)
713 Assert( CF_TYPE_SPECIFIED(dir_type) );
716 char old_longname[_MAX_PATH];
717 char new_longname[_MAX_PATH];
719 cf_create_default_path_string( old_longname, dir_type, old_name );
720 cf_create_default_path_string( new_longname, dir_type, name );
722 ret_code = rename(old_longname, new_longname );
726 return CF_RENAME_FAIL_ACCESS;
729 return CF_RENAME_FAIL_EXIST;
733 return CF_RENAME_SUCCESS;
738 // Creates the directory path if it doesn't exist. Even creates all its
740 void cf_create_directory( int dir_type )
743 int dir_tree[CF_MAX_PATH_TYPES];
744 char longname[MAX_PATH_LEN];
746 Assert( CF_TYPE_SPECIFIED(dir_type) );
748 int current_dir = dir_type;
751 Assert( num_dirs < CF_MAX_PATH_TYPES ); // Invalid Pathtypes data?
753 dir_tree[num_dirs++] = current_dir;
754 current_dir = Pathtypes[current_dir].parent_index;
756 } while( current_dir != CF_TYPE_ROOT );
761 for (i=num_dirs-1; i>=0; i-- ) {
762 cf_create_default_path_string( longname, dir_tree[i], NULL );
765 if ( _mkdir(longname, 0700)==0 ) {
766 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
769 if ( _mkdir(longname)==0 ) {
770 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
779 extern int game_cd_changed();
783 // parameters: *filepath ==> name of file to open (may be path+name)
784 // *mode ==> specifies how file should be opened (eg "rb" for read binary)
785 // passing NULL to mode deletes the file if it exists and returns NULL
786 // type ==> one of: CFILE_NORMAL
787 // CFILE_MEMORY_MAPPED
788 // dir_type => override extension check, value is one of CF_TYPE* #defines
790 // NOTE: type parameter is an optional parameter. The default value is CFILE_NORMAL
793 // returns: success ==> address of CFILE structure
797 CFILE *cfopen(char *file_path, char *mode, int type, int dir_type, bool localize)
799 char longname[_MAX_PATH];
801 // nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
802 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
804 // we no longer need to do this, and on machines with crappy-ass drivers it can slow things down horribly.
806 if ( game_cd_changed() ) {
811 //================================================
812 // Check that all the parameters make sense
813 Assert(file_path && strlen(file_path));
814 Assert( mode != NULL );
816 // Can only open read-only binary files in memory mapped mode.
817 if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
822 //===========================================================
823 // If in write mode, just try to open the file straight off
824 // the harddisk. No fancy packfile stuff here!
826 if ( strchr(mode,'w') ) {
827 // For write-only files, require a full path or a path type
829 if ( strpbrk(file_path, "/") ) {
831 if ( strpbrk(file_path,"/\\:") ) {
834 strcpy(longname, file_path );
837 Assert( dir_type != CF_TYPE_ANY );
839 // Create the directory if necessary
840 cf_create_directory( dir_type );
842 cf_create_default_path_string( longname, dir_type, file_path );
844 Assert( !(type & CFILE_MEMORY_MAPPED) );
846 // JOHN: TODO, you should create the path if it doesn't exist.
848 FILE *fp = fopen(longname, mode);
850 return cf_open_fill_cfblock(fp, dir_type);
856 //================================================
857 // Search for file on disk, on cdrom, or in a packfile
860 char copy_file_path[MAX_PATH_LEN]; // FIX change in memory from cf_find_file_location
861 strcpy(copy_file_path, file_path);
864 if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) ) {
866 // Fount it, now create a cfile out of it
868 if ( type & CFILE_MEMORY_MAPPED ) {
870 // Can't open memory mapped files out of pack files
877 hFile = CreateFile(longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
879 if (hFile != INVALID_HANDLE_VALUE) {
880 return cf_open_mapped_fill_cfblock(hFile, dir_type);
887 FILE *fp = fopen( longname, "rb" );
891 // Found it in a pack file
892 return cf_open_packed_cfblock(fp, dir_type, offset, size );
894 // Found it in a normal file
895 return cf_open_fill_cfblock(fp, dir_type);
906 // ------------------------------------------------------------------------
909 // Open up a temporary file. A unique name is automatically generated. The
910 // file will be automatically deleted when file is closed.
912 // return: NULL => tmp file could not be opened
913 // pointer to CFILE => tmp file successfully opened
920 return cf_open_fill_cfblock(fp, 0);
927 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
928 // Cfile_block_list[] array and return the index.
930 // returns: success ==> index in Cfile_block_list[] array
933 int cfget_cfile_block()
938 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
939 cb = &Cfile_block_list[i];
940 if ( cb->type == CFILE_BLOCK_UNUSED ) {
943 cb->type = CFILE_BLOCK_USED;
948 // If we've reached this point, a free Cfile_block could not be found
949 nprintf(("Warning","A free Cfile_block could not be found.\n"));
950 Assert(0); // out of free cfile blocks
955 // cfclose() closes the file
957 // returns: success ==> 0
960 int cfclose( CFILE * cfile )
964 Assert(cfile != NULL);
966 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
967 cb = &Cfile_block_list[cfile->id];
971 // close memory mapped file
975 result = UnmapViewOfFile((void*)cb->data);
977 result = CloseHandle(cb->hInFile);
978 Assert(result); // Ensure file handle is closed properly
979 result = CloseHandle(cb->hMapFile);
980 Assert(result); // Ensure file handle is closed properly
984 } else if ( cb->fp != NULL ) {
985 Assert(cb->fp != NULL);
986 result = fclose(cb->fp);
991 cb->type = CFILE_BLOCK_UNUSED;
998 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
999 // for the case of a file being opened by cf_open();
1001 // returns: success ==> ptr to CFILE structure.
1004 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
1006 int cfile_block_index;
1008 cfile_block_index = cfget_cfile_block();
1009 if ( cfile_block_index == -1 ) {
1014 cfbp = &Cfile_block_list[cfile_block_index];
1015 cfp = &Cfile_list[cfile_block_index];;
1016 cfp->id = cfile_block_index;
1020 cfbp->dir_type = type;
1022 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
1029 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1030 // for the case of a file being opened by cf_open();
1032 // returns: success ==> ptr to CFILE structure.
1035 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
1037 // Found it in a pack file
1038 int cfile_block_index;
1040 cfile_block_index = cfget_cfile_block();
1041 if ( cfile_block_index == -1 ) {
1046 cfbp = &Cfile_block_list[cfile_block_index];
1048 cfp = &Cfile_list[cfile_block_index];
1049 cfp->id = cfile_block_index;
1053 cfbp->dir_type = type;
1055 cf_init_lowlevel_read_code(cfp,offset, size );
1064 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1065 // for the case of a file being opened by cf_open_mapped();
1067 // returns: ptr CFILE structure.
1069 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
1071 int cfile_block_index;
1073 cfile_block_index = cfget_cfile_block();
1074 if ( cfile_block_index == -1 ) {
1080 cfbp = &Cfile_block_list[cfile_block_index];
1082 cfp = &Cfile_list[cfile_block_index];
1083 cfp->id = cfile_block_index;
1085 cfbp->hInFile = hFile;
1086 cfbp->dir_type = type;
1088 cf_init_lowlevel_read_code(cfp,0 , 0 );
1093 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
1094 if (cfbp->hMapFile == NULL) {
1095 nprintf(("Error", "Could not create file-mapping object.\n"));
1099 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1100 Assert( cfbp->data != NULL );
1106 int cf_get_dir_type(CFILE *cfile)
1108 return Cfile_block_list[cfile->id].dir_type;
1111 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1112 // with the CFILE structure passed as a parameter
1116 void *cf_returndata(CFILE *cfile)
1118 Assert(cfile != NULL);
1120 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1121 cb = &Cfile_block_list[cfile->id];
1122 Assert(cb->data != NULL);
1128 // version number of opened file. Will be 0 unless you put something else here after you
1129 // open a file. Once set, you can use minimum version numbers with the read functions.
1130 void cf_set_version( CFILE * cfile, int version )
1132 Assert(cfile != NULL);
1134 cfile->version = version;
1137 // routines to read basic data types from CFILE's. Put here to
1138 // simplify mac/pc reading from cfiles.
1143 float cfread_float(CFILE *file, int ver, float deflt)
1147 if (file->version < ver)
1150 if (cfread( &f, sizeof(f), 1, file) != 1)
1153 f = INTEL_FLOAT(&f);
1157 int cfread_int(CFILE *file, int ver, int deflt)
1161 if (file->version < ver)
1164 if (cfread( &i, sizeof(i), 1, file) != 1)
1171 uint cfread_uint(CFILE *file, int ver, uint deflt)
1175 if (file->version < ver)
1178 if (cfread( &i, sizeof(i), 1, file) != 1)
1185 short cfread_short(CFILE *file, int ver, short deflt)
1189 if (file->version < ver)
1192 if (cfread( &s, sizeof(s), 1, file) != 1)
1199 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1203 if (file->version < ver)
1206 if (cfread( &s, sizeof(s), 1, file) != 1)
1213 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1217 if (file->version < ver)
1220 if (cfread( &b, sizeof(b), 1, file) != 1)
1226 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1228 if (file->version < ver) {
1232 vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
1237 vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
1238 vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
1239 vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
1242 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1244 if (file->version < ver) {
1248 ang->p = ang->b = ang->h = 0.0f;
1253 ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
1254 ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
1255 ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
1258 char cfread_char(CFILE *file, int ver, char deflt)
1262 if (file->version < ver)
1265 if (cfread( &b, sizeof(b), 1, file) != 1)
1271 void cfread_string(char *buf, int n, CFILE *file)
1276 c = cfread_char(file);
1284 void cfread_string_len(char *buf,int n, CFILE *file)
1287 len = cfread_int(file);
1290 cfread(buf, len, 1, file);
1295 // equivalent write functions of above read functions follow
1297 int cfwrite_float(float f, CFILE *file)
1299 f = INTEL_FLOAT(&f);
1300 return cfwrite(&f, sizeof(f), 1, file);
1303 int cfwrite_int(int i, CFILE *file)
1306 return cfwrite(&i, sizeof(i), 1, file);
1309 int cfwrite_uint(uint i, CFILE *file)
1312 return cfwrite(&i, sizeof(i), 1, file);
1315 int cfwrite_short(short s, CFILE *file)
1318 return cfwrite(&s, sizeof(s), 1, file);
1321 int cfwrite_ushort(ushort s, CFILE *file)
1324 return cfwrite(&s, sizeof(s), 1, file);
1327 int cfwrite_ubyte(ubyte b, CFILE *file)
1329 return cfwrite(&b, sizeof(b), 1, file);
1332 int cfwrite_vector(vector *vec, CFILE *file)
1334 if(!cfwrite_float(vec->xyz.x, file)){
1337 if(!cfwrite_float(vec->xyz.y, file)){
1340 return cfwrite_float(vec->xyz.z, file);
1343 int cfwrite_angles(angles *ang, CFILE *file)
1345 if(!cfwrite_float(ang->p, file)){
1348 if(!cfwrite_float(ang->b, file)){
1351 return cfwrite_float(ang->h, file);
1354 int cfwrite_char(char b, CFILE *file)
1356 return cfwrite( &b, sizeof(b), 1, file);
1359 int cfwrite_string(char *buf, CFILE *file)
1361 if ( (!buf) || (buf && !buf[0]) ) {
1362 return cfwrite_char(0, file);
1364 int len = strlen(buf);
1365 if(!cfwrite(buf, len, 1, file)){
1368 return cfwrite_char(0, file); // write out NULL termination
1371 int cfwrite_string_len(char *buf, CFILE *file)
1373 int len = strlen(buf);
1375 if(!cfwrite_int(len, file)){
1379 return cfwrite(buf,len,1,file);
1385 // Get the filelength
1386 int cfilelength( CFILE * cfile )
1388 Assert(cfile != NULL);
1390 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1391 cb = &Cfile_block_list[cfile->id];
1393 // TODO: return length of memory mapped file
1394 Assert( !cb->data );
1396 Assert(cb->fp != NULL);
1398 // cb->size gets set at cfopen
1402 // cfwrite() writes to the file
1404 // returns: number of full elements actually written
1407 int cfwrite(void *buf, int elsize, int nelem, CFILE *cfile)
1409 Assert(cfile != NULL);
1410 Assert(buf != NULL);
1415 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1416 cb = &Cfile_block_list[cfile->id];
1420 // cfwrite() not supported for memory-mapped files
1421 Assert( !cb->data );
1423 Assert(cb->fp != NULL);
1424 Assert(cb->lib_offset == 0 );
1425 result = fwrite(buf, elsize, nelem, cb->fp);
1431 // cfputc() writes a character to a file
1433 // returns: success ==> returns character written
1436 int cfputc(int c, CFILE *cfile)
1440 Assert(cfile != NULL);
1442 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1443 cb = &Cfile_block_list[cfile->id];
1446 // cfputc() not supported for memory-mapped files
1447 Assert( !cb->data );
1449 Assert(cb->fp != NULL);
1450 result = fputc(c, cb->fp);
1456 // cfgetc() reads a character from a file
1458 // returns: success ==> returns character read
1461 int cfgetc(CFILE *cfile)
1463 Assert(cfile != NULL);
1467 int result = cfread(&tmp, 1, 1, cfile );
1468 if ( result == 1 ) {
1481 // cfgets() reads a string from a file
1483 // returns: success ==> returns pointer to string
1486 char *cfgets(char *buf, int n, CFILE *cfile)
1488 Assert(cfile != NULL);
1489 Assert(buf != NULL);
1495 for (i=0; i<n-1; i++ ) {
1499 int ret = cfread( &tmp_c, 1, 1, cfile );
1509 } while ( c == 13 );
1511 if ( c=='\n' ) break;
1518 // cfputs() writes a string to a file
1520 // returns: success ==> non-negative value
1523 int cfputs(char *str, CFILE *cfile)
1525 Assert(cfile != NULL);
1526 Assert(str != NULL);
1529 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1530 cb = &Cfile_block_list[cfile->id];
1535 // cfputs() not supported for memory-mapped files
1536 Assert( !cb->data );
1537 Assert(cb->fp != NULL);
1538 result = fputs(str, cb->fp);
1544 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1546 // CRC code for mission validation. given to us by Kevin Bentley on 7/20/98. Some sort of
1547 // checksumming code that he wrote a while ago.
1548 #define CRC32_POLYNOMIAL 0xEDB88320L
1549 unsigned long CRCTable[256];
1551 #define CF_CHKSUM_SAMPLE_SIZE 512
1553 // update cur_chksum with the chksum of the new_data of size new_data_size
1554 ushort cf_add_chksum_short(ushort seed, char *buffer, int size)
1556 ubyte * ptr = (ubyte *)buffer;
1557 unsigned int sum1,sum2;
1559 sum1 = sum2 = (int)(seed);
1563 if (sum1 >= 255 ) sum1 -= 255;
1568 return (unsigned short)((sum1<<8)+ sum2);
1571 // update cur_chksum with the chksum of the new_data of size new_data_size
1572 unsigned long cf_add_chksum_long(unsigned long seed, char *buffer, int size)
1576 unsigned long temp1;
1577 unsigned long temp2;
1579 p = (unsigned char*)buffer;
1583 temp1 = (crc>>8)&0x00FFFFFFL;
1584 temp2 = CRCTable[((int)crc^*p++)&0xff];
1591 void cf_chksum_long_init()
1596 for( i=0;i<=255;i++) {
1600 crc=(crc>>1)^CRC32_POLYNOMIAL;
1608 // single function convenient to use for both short and long checksums
1609 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1610 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1612 char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1618 // determine whether we're doing a short or long checksum
1629 // if max_size is -1, set it to be the size of the file
1631 cfseek(cfile, 0, SEEK_SET);
1632 max_size = cfilelength(cfile);
1637 // determine how much we want to read
1638 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1639 read_size = CF_CHKSUM_SAMPLE_SIZE;
1641 read_size = max_size - cf_total;
1644 // read in some buffer
1645 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1647 // total we've read so far
1652 // do the proper short or long checksum
1654 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1656 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1659 } while((cf_len > 0) && (cf_total < max_size));
1664 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1665 int cf_chksum_short(char *filename, ushort *chksum, int max_size, int cf_type)
1668 CFILE *cfile = NULL;
1670 // zero the checksum
1673 // attempt to open the file
1674 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1679 // call the overloaded cf_chksum function()
1680 ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1682 // close the file down
1686 // return the result
1690 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1691 // NOTE : preserves current file position
1692 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1697 // Returns current position of file.
1698 start_pos = cftell(file);
1699 if(start_pos == -1){
1703 // move to the beginning of the file
1704 if(cfseek(file, 0, CF_SEEK_SET)){
1707 ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1708 // move back to the start position
1709 cfseek(file, start_pos, CF_SEEK_SET);
1714 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1715 int cf_chksum_long(char *filename, uint *chksum, int max_size, int cf_type)
1718 CFILE *cfile = NULL;
1720 // zero the checksum
1723 // attempt to open the file
1724 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1729 // call the overloaded cf_chksum function()
1730 ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1732 // close the file down
1736 // return the result
1740 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1741 // NOTE : preserves current file position
1742 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1747 // Returns current position of file.
1748 start_pos = cftell(file);
1749 if(start_pos == -1){
1753 // move to the beginning of the file
1754 if(cfseek(file, 0, CF_SEEK_SET)){
1757 ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1758 // move back to the start position
1759 cfseek(file, start_pos, CF_SEEK_SET);
1765 // Flush the open file buffer
1767 // exit: 0 - success
1769 int cflush(CFILE *cfile)
1771 Assert(cfile != NULL);
1773 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1774 cb = &Cfile_block_list[cfile->id];
1776 // not supported for memory mapped files
1777 Assert( !cb->data );
1779 Assert(cb->fp != NULL);
1780 return fflush(cb->fp);