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.13 2005/10/01 22:04:58 taylor
19 * fix FS1 (de)briefing voices, the directory names are different in FS1
20 * hard code the table values so that the fs1.vp file isn't needed
21 * hard code a mission fix for sm2-08a since a have no idea how to fix it otherwise
22 * generally cleanup some FS1 code
23 * fix volume sliders in the options screen that never went all the way up
25 * Revision 1.12 2005/08/12 08:50:09 taylor
26 * recursively create directories (hurt more on OSX) and update all _mkdir() calls accordingly
28 * Revision 1.11 2004/07/04 11:27:29 taylor
29 * cleanup CFILE code a little, warning fixes, remove redundant dir checks, amd64 support
31 * Revision 1.10 2004/06/11 00:28:39 tigital
32 * byte-swapping changes for bigendian systems
34 * Revision 1.9 2003/05/25 02:30:42 taylor
37 * Revision 1.8 2003/02/20 17:41:07 theoddone33
38 * Userdir patch from Taylor Richards
40 * Revision 1.7 2002/12/30 03:23:29 relnev
41 * disable root dir check
43 * Revision 1.6 2002/06/17 06:33:08 relnev
44 * ryan's struct patch for gcc 2.95
46 * Revision 1.5 2002/06/09 04:41:15 relnev
47 * added copyright header
49 * Revision 1.4 2002/06/05 08:05:28 relnev
50 * stub/warning removal.
52 * reworked the sound code.
54 * Revision 1.3 2002/05/28 08:52:03 relnev
55 * implemented two assembly stubs.
57 * cleaned up a few warnings.
59 * added a little demo hackery to make it progress a little farther.
61 * Revision 1.2 2002/05/28 06:28:20 theoddone33
62 * Filesystem mods, actually reads some data files now
64 * Revision 1.1.1.1 2002/05/03 03:28:08 root
68 * 20 9/08/99 10:01p Dave
69 * Make sure game won't run in a drive's root directory. Make sure
70 * standalone routes suqad war messages properly to the host.
72 * 19 9/08/99 12:03a Dave
73 * Make squad logos render properly in D3D all the time. Added intel anim
76 * 18 9/06/99 2:35p Dave
77 * Rename briefing and debriefing voice direcrory paths properly.
79 * 17 9/03/99 1:31a Dave
80 * CD checking by act. Added support to play 2 cutscenes in a row
81 * seamlessly. Fixed super low level cfile bug related to files in the
82 * root directory of a CD. Added cheat code to set campaign mission # in
85 * 16 8/31/99 9:46a Dave
86 * Support for new cfile cbanims directory.
88 * 15 8/06/99 11:20a Johns
89 * Don't call game_cd_changed() in a demo or multiplayer beta build.
91 * 14 6/08/99 2:33p Dave
92 * Fixed release build warning. Put in hud config stuff.
94 * 13 5/19/99 4:07p Dave
95 * Moved versioning code into a nice isolated common place. Fixed up
96 * updating code on the pxo screen. Fixed several stub problems.
98 * 12 4/30/99 12:18p Dave
99 * Several minor bug fixes.
101 * 11 4/07/99 5:54p Dave
102 * Fixes for encryption in updatelauncher.
104 * 10 3/28/99 5:58p Dave
105 * Added early demo code. Make objects move. Nice and framerate
106 * independant, but not much else. Don't use yet unless you're me :)
108 * 9 2/22/99 10:31p Andsager
109 * Get rid of unneeded includes.
111 * 8 1/12/99 3:15a Dave
112 * Barracks screen support for selecting squad logos. We need real artwork
115 * 7 11/30/98 1:07p Dave
116 * 16 bit conversion, first run.
118 * 6 10/29/98 10:41a Dave
119 * Change the way cfile initializes exe directory.
121 * 5 10/13/98 9:19a Andsager
122 * Add localization support to cfile. Optional parameter with cfopen that
123 * looks for localized files.
125 * 4 10/12/98 9:54a Dave
126 * Fixed a few file organization things.
128 * 3 10/07/98 6:27p Dave
129 * Globalized mission and campaign file extensions. Removed Silent Threat
130 * special code. Moved \cache \players and \multidata into the \data
133 * 2 10/07/98 10:52a Dave
136 * 1 10/07/98 10:48a Dave
138 * 110 9/17/98 10:31a Hoffoss
139 * Changed code to use location of executable as root rather than relying
140 * on the cwd being set correctly. This is most helpful in the case of
141 * Fred launching due to the user double-clicking on an .fsm file in
142 * explorer or something (where the cwd is probably the location of the
145 * 109 9/11/98 4:14p Dave
146 * Fixed file checksumming of < file_size. Put in more verbose kicking and
147 * PXO stats store reporting.
149 * 108 9/09/98 5:53p Dave
150 * Put in new tracker packets in API. Change cfile to be able to checksum
151 * portions of a file.
153 * 107 9/04/98 3:51p Dave
154 * Put in validated mission updating and application during stats
157 * 106 8/31/98 2:06p Dave
158 * Make cfile sort the ordering or vp files. Added support/checks for
159 * recognizing "mission disk" players.
161 * 105 8/20/98 5:30p Dave
162 * Put in handy multiplayer logfile system. Now need to put in useful
163 * applications of it all over the code.
165 * 104 8/12/98 4:53p Dave
166 * Put in 32 bit checksumming for PXO missions. No validation on the
167 * actual tracker yet, though.
169 * 103 6/17/98 9:30a Allender
170 * fixed red alert replay stats clearing problem
172 * 102 6/05/98 9:46a Lawrance
173 * check for CD change on cfopen()
175 * 101 5/19/98 1:19p Allender
176 * new low level reliable socket reading code. Make all missions/campaign
177 * load/save to data missions folder (i.e. we are rid of the player
180 * 100 5/13/98 10:22p John
181 * Added cfile functions to read/write rle compressed blocks of data.
182 * Made palman use it for .clr files. Made alphacolors calculate on the
183 * fly rather than caching to/from disk.
185 * 99 5/11/98 10:59a John
186 * Moved the low-level file reading code into cfilearchive.cpp.
188 * 98 5/06/98 5:30p John
189 * Removed unused cfilearchiver. Removed/replaced some unused/little used
190 * graphics functions, namely gradient_h and _v and pixel_sp. Put in new
191 * DirectX header files and libs that fixed the Direct3D alpha blending
194 * 97 5/03/98 11:53a John
195 * Fixed filename case mangling.
197 * 96 5/03/98 8:33a John
198 * Made sure there weren't any more broken function lurking around like
199 * the one Allender fixed.
201 * 95 5/02/98 11:05p Allender
202 * fix cfilelength for pack files
207 #define _CFILE_INTERNAL
217 #include <winbase.h> /* needed for memory mapping of file functions */
220 #include <sys/stat.h>
221 #include <sys/types.h>
227 //#include "outwnd.h"
228 //#include "vecmat.h"
230 #include "cfilesystem.h"
231 #include "cfilearchive.h"
233 #include "osregistry.h" // for Osreg_user_dir
236 char Cfile_user_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
238 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
240 // During cfile_init, verify that Pathtypes[n].index == n for each item
241 // Each path must have a valid parent that can be tracable all the way back to the root
242 // so that we can create directories when we need to.
244 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
245 // What type this is Path Extensions Parent type
246 { CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
247 // Root must be index 1!!
248 { CF_TYPE_ROOT, "", ".mve", CF_TYPE_ROOT },
249 { CF_TYPE_DATA, "Data", ".cfg .log .txt", CF_TYPE_ROOT },
251 { CF_TYPE_MAPS, "Data/Maps", ".pcx .ani .tga", CF_TYPE_DATA },
252 { CF_TYPE_TEXT, "Data/Text", ".txt .net", CF_TYPE_DATA },
254 { CF_TYPE_MISSIONS, "Data/Missions", ".fsm .fsc .ntl .ssv", CF_TYPE_DATA },
256 { CF_TYPE_MISSIONS, "Data/Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
258 { CF_TYPE_MODELS, "Data/Models", ".pof", CF_TYPE_DATA },
259 { CF_TYPE_TABLES, "Data/Tables", ".tbl", CF_TYPE_DATA },
260 { CF_TYPE_SOUNDS, "Data/Sounds", ".wav", CF_TYPE_DATA },
261 { CF_TYPE_SOUNDS_8B22K, "Data/Sounds/8b22k", ".wav", CF_TYPE_SOUNDS },
262 { CF_TYPE_SOUNDS_16B11K, "Data/Sounds/16b11k", ".wav", CF_TYPE_SOUNDS },
263 { CF_TYPE_VOICE, "Data/Voice", "", CF_TYPE_DATA },
265 { CF_TYPE_VOICE_BRIEFINGS, "Data/Voice/Briefings", ".wav", CF_TYPE_VOICE },
267 { CF_TYPE_VOICE_BRIEFINGS, "Data/Voice/Briefing", ".wav", CF_TYPE_VOICE },
269 { CF_TYPE_VOICE_CMD_BRIEF, "Data/Voice/Command_briefings",".wav", CF_TYPE_VOICE },
271 { CF_TYPE_VOICE_DEBRIEFINGS, "Data/Voice/Debriefings", ".wav", CF_TYPE_VOICE },
273 { CF_TYPE_VOICE_DEBRIEFINGS, "Data/Voice/Debriefing", ".wav", CF_TYPE_VOICE },
275 { CF_TYPE_VOICE_PERSONAS, "Data/Voice/Personas", ".wav", CF_TYPE_VOICE },
276 { CF_TYPE_VOICE_SPECIAL, "Data/Voice/Special", ".wav", CF_TYPE_VOICE },
277 { CF_TYPE_VOICE_TRAINING, "Data/Voice/Training", ".wav", CF_TYPE_VOICE },
278 { CF_TYPE_MUSIC, "Data/Music", ".wav", CF_TYPE_VOICE },
279 { CF_TYPE_MOVIES, "Data/Movies", ".mve .msb", CF_TYPE_DATA },
280 { CF_TYPE_INTERFACE, "Data/Interface", ".pcx .ani .tga", CF_TYPE_DATA },
281 { CF_TYPE_FONT, "Data/Fonts", ".vf", CF_TYPE_DATA },
282 { CF_TYPE_EFFECTS, "Data/Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
283 { CF_TYPE_HUD, "Data/Hud", ".ani .pcx .tga", CF_TYPE_DATA },
284 { CF_TYPE_PLAYER_MAIN, "Data/Players", "", CF_TYPE_DATA },
285 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data/Players/Images", ".pcx", CF_TYPE_PLAYER_MAIN },
286 { CF_TYPE_CACHE, "Data/Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
287 { CF_TYPE_PLAYERS, "Data/Players", ".hcf", CF_TYPE_DATA },
288 { CF_TYPE_SINGLE_PLAYERS, "Data/Players/Single", ".plr .csg .css", CF_TYPE_PLAYERS },
289 { CF_TYPE_MULTI_PLAYERS, "Data/Players/Multi", ".plr", CF_TYPE_DATA },
290 { CF_TYPE_MULTI_CACHE, "Data/MultiData", ".pcx .fs2", CF_TYPE_DATA },
291 { CF_TYPE_CONFIG, "Data/Config", ".cfg", CF_TYPE_DATA },
292 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data/Players/Squads", ".pcx", CF_TYPE_DATA },
293 { CF_TYPE_DEMOS, "Data/Demos", ".fsd", CF_TYPE_DATA },
294 { CF_TYPE_CBANIMS, "Data/CBAnims", ".ani", CF_TYPE_DATA },
295 { CF_TYPE_INTEL_ANIMS, "Data/IntelAnims", ".ani", CF_TYPE_DATA },
297 { CF_TYPE_MAPS, "Data\\Maps", ".pcx .ani .tga", CF_TYPE_DATA },
298 { CF_TYPE_TEXT, "Data\\Text", ".txt .net", CF_TYPE_DATA },
299 { CF_TYPE_MISSIONS, "Data\\Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
300 { CF_TYPE_MODELS, "Data\\Models", ".pof", CF_TYPE_DATA },
301 { CF_TYPE_TABLES, "Data\\Tables", ".tbl", CF_TYPE_DATA },
302 { CF_TYPE_SOUNDS, "Data\\Sounds", ".wav", CF_TYPE_DATA },
303 { CF_TYPE_SOUNDS_8B22K, "Data\\Sounds\\8b22k", ".wav", CF_TYPE_SOUNDS },
304 { CF_TYPE_SOUNDS_16B11K, "Data\\Sounds\\16b11k", ".wav", CF_TYPE_SOUNDS },
305 { CF_TYPE_VOICE, "Data\\Voice", "", CF_TYPE_DATA },
306 { CF_TYPE_VOICE_BRIEFINGS, "Data\\Voice\\Briefing", ".wav", CF_TYPE_VOICE },
307 { CF_TYPE_VOICE_CMD_BRIEF, "Data\\Voice\\Command_briefings",".wav", CF_TYPE_VOICE },
308 { CF_TYPE_VOICE_DEBRIEFINGS, "Data\\Voice\\Debriefing", ".wav", CF_TYPE_VOICE },
309 { CF_TYPE_VOICE_PERSONAS, "Data\\Voice\\Personas", ".wav", CF_TYPE_VOICE },
310 { CF_TYPE_VOICE_SPECIAL, "Data\\Voice\\Special", ".wav", CF_TYPE_VOICE },
311 { CF_TYPE_VOICE_TRAINING, "Data\\Voice\\Training", ".wav", CF_TYPE_VOICE },
312 { CF_TYPE_MUSIC, "Data\\Music", ".wav", CF_TYPE_VOICE },
313 { CF_TYPE_MOVIES, "Data\\Movies", ".mve .msb", CF_TYPE_DATA },
314 { CF_TYPE_INTERFACE, "Data\\Interface", ".pcx .ani .tga", CF_TYPE_DATA },
315 { CF_TYPE_FONT, "Data\\Fonts", ".vf", CF_TYPE_DATA },
316 { CF_TYPE_EFFECTS, "Data\\Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
317 { CF_TYPE_HUD, "Data\\Hud", ".ani .pcx .tga", CF_TYPE_DATA },
318 { CF_TYPE_PLAYER_MAIN, "Data\\Players", "", CF_TYPE_DATA },
319 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data\\Players\\Images", ".pcx", CF_TYPE_PLAYER_MAIN },
320 { CF_TYPE_CACHE, "Data\\Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
321 { CF_TYPE_PLAYERS, "Data\\Players", ".hcf", CF_TYPE_DATA },
322 { CF_TYPE_SINGLE_PLAYERS, "Data\\Players\\Single", ".plr .csg .css", CF_TYPE_PLAYERS },
323 { CF_TYPE_MULTI_PLAYERS, "Data\\Players\\Multi", ".plr", CF_TYPE_DATA },
324 { CF_TYPE_MULTI_CACHE, "Data\\MultiData", ".pcx .fs2", CF_TYPE_DATA },
325 { CF_TYPE_CONFIG, "Data\\Config", ".cfg", CF_TYPE_DATA },
326 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data\\Players\\Squads", ".pcx", CF_TYPE_DATA },
327 { CF_TYPE_DEMOS, "Data\\Demos", ".fsd", CF_TYPE_DATA },
328 { CF_TYPE_CBANIMS, "Data\\CBAnims", ".ani", CF_TYPE_DATA },
329 { CF_TYPE_INTEL_ANIMS, "Data\\IntelAnims", ".ani", CF_TYPE_DATA },
334 #define CFILE_STACK_MAX 8
336 int cfile_inited = 0;
337 int Cfile_stack_pos = 0;
339 char Cfile_stack[128][CFILE_STACK_MAX];
341 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
342 CFILE Cfile_list[MAX_CFILE_BLOCKS];
344 char *Cfile_cdrom_dir = NULL;
347 // Function prototypes for internally-called functions
349 int cfget_cfile_block();
350 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
351 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
352 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
353 void cf_chksum_long_init();
357 cf_free_secondary_filelist();
360 // determine if the given path is in a root directory (c:\ or c:\freespace2.exe or c:\fred2.exe etc)
361 int cfile_in_root_dir(char *exe_path)
364 char path_copy[2048] = "";
368 if(exe_path == NULL){
373 memset(path_copy, 0, 2048);
374 strncpy(path_copy, exe_path, 2047);
376 // count how many slashes there are in the path
377 tok = strtok(path_copy, DIR_SEPARATOR_STR);
383 tok = strtok(NULL, DIR_SEPARATOR_STR);
384 } while(tok != NULL);
386 // root directory if we have <= 1 slash
387 if(token_count <= 2){
391 // not-root directory
395 // cfile_init() initializes the cfile system. Called once at application start.
397 // returns: success ==> 0
398 // error ==> non-zero
400 int cfile_init(char *exe_dir, char *cdrom_dir)
404 // initialize encryption
407 if ( !cfile_inited ) {
412 strcpy(buf, exe_dir);
416 // are we in a root directory?
417 if(cfile_in_root_dir(buf)){
418 MessageBox((HWND)NULL, "Freespace2/Fred2 cannot be run from a drive root directory!", "Error", MB_OK);
424 if (buf[i] == DIR_SEPARATOR_CHAR){
434 fprintf (stderr, "Error trying to determine executable root directory!");
436 MessageBox((HWND)NULL, "Error trying to determine executable root directory!", "Error", MB_OK);
441 // set root directory
442 strncpy(Cfile_root_dir, buf, CFILE_ROOT_DIRECTORY_LEN-1);
445 snprintf(Cfile_user_dir, MAX_PATH, "%s/%s/", detect_home(), Osreg_user_dir);
447 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
448 Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
451 Cfile_cdrom_dir = cdrom_dir;
452 cf_build_secondary_filelist(Cfile_cdrom_dir);
454 // 32 bit CRC table init
455 cf_chksum_long_init();
457 atexit( cfile_close );
463 // Call this if pack files got added or removed or the
464 // cdrom changed. This will refresh the list of filenames
465 // stored in packfiles and on the cdrom.
468 cf_build_secondary_filelist(Cfile_cdrom_dir);
472 // Changes to a drive if valid.. 1=A, 2=B, etc
473 // If flag, then changes to it.
474 // Returns 0 if not-valid, 1 if valid.
475 int cfile_chdrive( int DriveNum, int flag )
488 _chdrive( DriveNum );
495 if ( (!flag) && (n != org) )
501 // push current directory on a 'stack' (so we can restore it) and change the directory
502 int cfile_push_chdir(int type)
506 char OriginalDirectory[128];
508 char NoDir[] = "\\.";
510 _getcwd(OriginalDirectory, 127);
511 Assert(Cfile_stack_pos < CFILE_STACK_MAX);
512 strcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
514 cf_create_default_path_string( dir, type, NULL );
517 char *Drive = strchr(dir, ':');
520 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
535 // This chdir might get a critical error!
538 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
546 int cfile_chdir(char *dir)
549 char OriginalDirectory[128];
551 char NoDir[] = "\\.";
553 _getcwd(OriginalDirectory, 127);
557 char *Drive = strchr(dir, ':');
559 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
574 // This chdir might get a critical error!
577 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
586 Assert(Cfile_stack_pos);
588 return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
591 // flush (delete all files in) the passed directory (by type), return the # of files deleted
592 // NOTE : WILL NOT DELETE READ-ONLY FILES
593 int cfile_flush_dir(int dir_type)
603 Assert( CF_TYPE_SPECIFIED(dir_type) );
605 // attempt to change the directory to the passed type
606 if(cfile_push_chdir(dir_type)){
610 // proceed to delete the files
611 find_handle = _findfirst( "*", &find );
613 if (find_handle != -1) {
615 if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
617 cf_delete(find.name,dir_type);
619 // increment the deleted count
622 } while (!_findnext(find_handle, &find));
623 _findclose( find_handle );
626 // pop the directory back
629 // return the # of files deleted
635 // add the given extention to a filename (or filepath) if it doesn't already have this
637 // filename = name of filename or filepath to process
638 // ext = extension to add. Must start with the period
639 // Returns: new filename or filepath with extension.
640 char *cf_add_ext(char *filename, char *ext)
643 static char path[MAX_PATH_LEN];
645 flen = strlen(filename);
647 Assert(flen < MAX_PATH_LEN);
648 strcpy(path, filename);
649 if ((flen < 4) || stricmp(path + flen - elen, ext)) {
650 Assert(flen + elen < MAX_PATH_LEN);
658 void cf_delete( char *filename, int dir_type )
660 char longname[MAX_PATH_LEN];
662 Assert( CF_TYPE_SPECIFIED(dir_type) );
664 cf_create_default_path_string( longname, dir_type, filename );
666 FILE *fp = fopen(longname, "rb");
676 // Same as _access function to read a file's access bits
677 int cf_access( char *filename, int dir_type, int mode )
679 char longname[MAX_PATH_LEN];
681 Assert( CF_TYPE_SPECIFIED(dir_type) );
683 cf_create_default_path_string( longname, dir_type, filename );
685 return access(longname,mode);
689 // Returns 1 if file exists, 0 if not.
690 int cf_exist( char *filename, int dir_type )
692 char longname[MAX_PATH_LEN];
694 Assert( CF_TYPE_SPECIFIED(dir_type) );
696 cf_create_default_path_string( longname, dir_type, filename );
698 FILE *fp = fopen(longname, "rb");
707 void cf_attrib(char *filename, int set, int clear, int dir_type)
709 char longname[MAX_PATH_LEN];
711 Assert( CF_TYPE_SPECIFIED(dir_type) );
713 cf_create_default_path_string( longname, dir_type, filename );
715 FILE *fp = fopen(longname, "rb");
722 DWORD z = GetFileAttributes(longname);
723 SetFileAttributes(longname, z | set & ~clear);
729 int cf_rename(char *old_name, char *name, int dir_type)
731 Assert( CF_TYPE_SPECIFIED(dir_type) );
734 char old_longname[_MAX_PATH];
735 char new_longname[_MAX_PATH];
737 cf_create_default_path_string( old_longname, dir_type, old_name );
738 cf_create_default_path_string( new_longname, dir_type, name );
740 ret_code = rename(old_longname, new_longname );
744 return CF_RENAME_FAIL_ACCESS;
747 return CF_RENAME_FAIL_EXIST;
751 return CF_RENAME_SUCCESS;
756 // Creates the directory path if it doesn't exist. Even creates all its
758 void cf_create_directory( int dir_type )
761 int dir_tree[CF_MAX_PATH_TYPES];
762 char longname[MAX_PATH_LEN];
764 Assert( CF_TYPE_SPECIFIED(dir_type) );
766 int current_dir = dir_type;
769 Assert( num_dirs < CF_MAX_PATH_TYPES ); // Invalid Pathtypes data?
771 dir_tree[num_dirs++] = current_dir;
772 current_dir = Pathtypes[current_dir].parent_index;
774 } while( current_dir != CF_TYPE_ROOT );
779 for (i=num_dirs-1; i>=0; i-- ) {
780 cf_create_default_path_string( longname, dir_tree[i], NULL );
782 if ( _mkdir(longname)==0 ) {
783 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
791 extern int game_cd_changed();
795 // parameters: *filepath ==> name of file to open (may be path+name)
796 // *mode ==> specifies how file should be opened (eg "rb" for read binary)
797 // passing NULL to mode deletes the file if it exists and returns NULL
798 // type ==> one of: CFILE_NORMAL
799 // CFILE_MEMORY_MAPPED
800 // dir_type => override extension check, value is one of CF_TYPE* #defines
802 // NOTE: type parameter is an optional parameter. The default value is CFILE_NORMAL
805 // returns: success ==> address of CFILE structure
809 CFILE *cfopen(char *file_path, char *mode, int type, int dir_type, bool localize)
811 char longname[_MAX_PATH];
813 // nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
814 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
816 // we no longer need to do this, and on machines with crappy-ass drivers it can slow things down horribly.
818 if ( game_cd_changed() ) {
823 //================================================
824 // Check that all the parameters make sense
825 Assert(file_path && strlen(file_path));
826 Assert( mode != NULL );
828 // Can only open read-only binary files in memory mapped mode.
829 if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
834 //===========================================================
835 // If in write mode, just try to open the file straight off
836 // the harddisk. No fancy packfile stuff here!
838 if ( strchr(mode,'w') ) {
839 // For write-only files, require a full path or a path type
841 if ( strpbrk(file_path, "/") ) {
843 if ( strpbrk(file_path,"/\\:") ) {
846 strcpy(longname, file_path );
849 Assert( dir_type != CF_TYPE_ANY );
851 // Create the directory if necessary
852 cf_create_directory( dir_type );
854 cf_create_default_path_string( longname, dir_type, file_path );
856 Assert( !(type & CFILE_MEMORY_MAPPED) );
858 // JOHN: TODO, you should create the path if it doesn't exist.
860 FILE *fp = fopen(longname, mode);
862 return cf_open_fill_cfblock(fp, dir_type);
868 //================================================
869 // Search for file on disk, on cdrom, or in a packfile
872 char copy_file_path[MAX_PATH_LEN]; // FIX change in memory from cf_find_file_location
873 strcpy(copy_file_path, file_path);
876 if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) ) {
878 // Fount it, now create a cfile out of it
880 if ( type & CFILE_MEMORY_MAPPED ) {
882 // Can't open memory mapped files out of pack files
889 hFile = CreateFile(longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
891 if (hFile != INVALID_HANDLE_VALUE) {
892 return cf_open_mapped_fill_cfblock(hFile, dir_type);
899 FILE *fp = fopen( longname, "rb" );
903 // Found it in a pack file
904 return cf_open_packed_cfblock(fp, dir_type, offset, size );
906 // Found it in a normal file
907 return cf_open_fill_cfblock(fp, dir_type);
918 // ------------------------------------------------------------------------
921 // Open up a temporary file. A unique name is automatically generated. The
922 // file will be automatically deleted when file is closed.
924 // return: NULL => tmp file could not be opened
925 // pointer to CFILE => tmp file successfully opened
932 return cf_open_fill_cfblock(fp, 0);
939 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
940 // Cfile_block_list[] array and return the index.
942 // returns: success ==> index in Cfile_block_list[] array
945 int cfget_cfile_block()
950 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
951 cb = &Cfile_block_list[i];
952 if ( cb->type == CFILE_BLOCK_UNUSED ) {
955 cb->type = CFILE_BLOCK_USED;
960 // If we've reached this point, a free Cfile_block could not be found
961 nprintf(("Warning","A free Cfile_block could not be found.\n"));
962 Assert(0); // out of free cfile blocks
967 // cfclose() closes the file
969 // returns: success ==> 0
972 int cfclose( CFILE * cfile )
976 Assert(cfile != NULL);
978 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
979 cb = &Cfile_block_list[cfile->id];
983 // close memory mapped file
987 result = UnmapViewOfFile((void*)cb->data);
989 result = CloseHandle(cb->hInFile);
990 Assert(result); // Ensure file handle is closed properly
991 result = CloseHandle(cb->hMapFile);
992 Assert(result); // Ensure file handle is closed properly
996 } else if ( cb->fp != NULL ) {
997 Assert(cb->fp != NULL);
998 result = fclose(cb->fp);
1003 cb->type = CFILE_BLOCK_UNUSED;
1010 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1011 // for the case of a file being opened by cf_open();
1013 // returns: success ==> ptr to CFILE structure.
1016 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
1018 int cfile_block_index;
1020 cfile_block_index = cfget_cfile_block();
1021 if ( cfile_block_index == -1 ) {
1026 cfbp = &Cfile_block_list[cfile_block_index];
1027 cfp = &Cfile_list[cfile_block_index];;
1028 cfp->id = cfile_block_index;
1032 cfbp->dir_type = type;
1034 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
1041 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1042 // for the case of a file being opened by cf_open();
1044 // returns: success ==> ptr to CFILE structure.
1047 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
1049 // Found it in a pack file
1050 int cfile_block_index;
1052 cfile_block_index = cfget_cfile_block();
1053 if ( cfile_block_index == -1 ) {
1058 cfbp = &Cfile_block_list[cfile_block_index];
1060 cfp = &Cfile_list[cfile_block_index];
1061 cfp->id = cfile_block_index;
1065 cfbp->dir_type = type;
1067 cf_init_lowlevel_read_code(cfp,offset, size );
1076 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1077 // for the case of a file being opened by cf_open_mapped();
1079 // returns: ptr CFILE structure.
1081 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
1083 int cfile_block_index;
1085 cfile_block_index = cfget_cfile_block();
1086 if ( cfile_block_index == -1 ) {
1092 cfbp = &Cfile_block_list[cfile_block_index];
1094 cfp = &Cfile_list[cfile_block_index];
1095 cfp->id = cfile_block_index;
1097 cfbp->hInFile = hFile;
1098 cfbp->dir_type = type;
1100 cf_init_lowlevel_read_code(cfp,0 , 0 );
1105 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
1106 if (cfbp->hMapFile == NULL) {
1107 nprintf(("Error", "Could not create file-mapping object.\n"));
1111 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1112 Assert( cfbp->data != NULL );
1118 int cf_get_dir_type(CFILE *cfile)
1120 return Cfile_block_list[cfile->id].dir_type;
1123 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1124 // with the CFILE structure passed as a parameter
1128 void *cf_returndata(CFILE *cfile)
1130 Assert(cfile != NULL);
1132 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1133 cb = &Cfile_block_list[cfile->id];
1134 Assert(cb->data != NULL);
1140 // version number of opened file. Will be 0 unless you put something else here after you
1141 // open a file. Once set, you can use minimum version numbers with the read functions.
1142 void cf_set_version( CFILE * cfile, int version )
1144 Assert(cfile != NULL);
1146 cfile->version = version;
1149 // routines to read basic data types from CFILE's. Put here to
1150 // simplify mac/pc reading from cfiles.
1155 float cfread_float(CFILE *file, int ver, float deflt)
1159 if (file->version < ver)
1162 if (cfread( &f, sizeof(f), 1, file) != 1)
1165 f = INTEL_FLOAT(&f);
1169 int cfread_int(CFILE *file, int ver, int deflt)
1173 if (file->version < ver)
1176 if (cfread( &i, sizeof(i), 1, file) != 1)
1183 uint cfread_uint(CFILE *file, int ver, uint deflt)
1187 if (file->version < ver)
1190 if (cfread( &i, sizeof(i), 1, file) != 1)
1197 short cfread_short(CFILE *file, int ver, short deflt)
1201 if (file->version < ver)
1204 if (cfread( &s, sizeof(s), 1, file) != 1)
1211 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1215 if (file->version < ver)
1218 if (cfread( &s, sizeof(s), 1, file) != 1)
1225 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1229 if (file->version < ver)
1232 if (cfread( &b, sizeof(b), 1, file) != 1)
1238 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1240 if (file->version < ver) {
1244 vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
1249 vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
1250 vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
1251 vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
1254 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1256 if (file->version < ver) {
1260 ang->p = ang->b = ang->h = 0.0f;
1265 ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
1266 ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
1267 ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
1270 char cfread_char(CFILE *file, int ver, char deflt)
1274 if (file->version < ver)
1277 if (cfread( &b, sizeof(b), 1, file) != 1)
1283 void cfread_string(char *buf, int n, CFILE *file)
1288 c = cfread_char(file);
1296 void cfread_string_len(char *buf,int n, CFILE *file)
1299 len = cfread_int(file);
1302 cfread(buf, len, 1, file);
1307 // equivalent write functions of above read functions follow
1309 int cfwrite_float(float f, CFILE *file)
1311 f = INTEL_FLOAT(&f);
1312 return cfwrite(&f, sizeof(f), 1, file);
1315 int cfwrite_int(int i, CFILE *file)
1318 return cfwrite(&i, sizeof(i), 1, file);
1321 int cfwrite_uint(uint i, CFILE *file)
1324 return cfwrite(&i, sizeof(i), 1, file);
1327 int cfwrite_short(short s, CFILE *file)
1330 return cfwrite(&s, sizeof(s), 1, file);
1333 int cfwrite_ushort(ushort s, CFILE *file)
1336 return cfwrite(&s, sizeof(s), 1, file);
1339 int cfwrite_ubyte(ubyte b, CFILE *file)
1341 return cfwrite(&b, sizeof(b), 1, file);
1344 int cfwrite_vector(vector *vec, CFILE *file)
1346 if(!cfwrite_float(vec->xyz.x, file)){
1349 if(!cfwrite_float(vec->xyz.y, file)){
1352 return cfwrite_float(vec->xyz.z, file);
1355 int cfwrite_angles(angles *ang, CFILE *file)
1357 if(!cfwrite_float(ang->p, file)){
1360 if(!cfwrite_float(ang->b, file)){
1363 return cfwrite_float(ang->h, file);
1366 int cfwrite_char(char b, CFILE *file)
1368 return cfwrite( &b, sizeof(b), 1, file);
1371 int cfwrite_string(char *buf, CFILE *file)
1373 if ( (!buf) || (buf && !buf[0]) ) {
1374 return cfwrite_char(0, file);
1376 int len = strlen(buf);
1377 if(!cfwrite(buf, len, 1, file)){
1380 return cfwrite_char(0, file); // write out NULL termination
1383 int cfwrite_string_len(char *buf, CFILE *file)
1385 int len = strlen(buf);
1387 if(!cfwrite_int(len, file)){
1391 return cfwrite(buf,len,1,file);
1397 // Get the filelength
1398 int cfilelength( CFILE * cfile )
1400 Assert(cfile != NULL);
1402 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1403 cb = &Cfile_block_list[cfile->id];
1405 // TODO: return length of memory mapped file
1406 Assert( !cb->data );
1408 Assert(cb->fp != NULL);
1410 // cb->size gets set at cfopen
1414 // cfwrite() writes to the file
1416 // returns: number of full elements actually written
1419 int cfwrite(void *buf, int elsize, int nelem, CFILE *cfile)
1421 Assert(cfile != NULL);
1422 Assert(buf != NULL);
1427 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1428 cb = &Cfile_block_list[cfile->id];
1432 // cfwrite() not supported for memory-mapped files
1433 Assert( !cb->data );
1435 Assert(cb->fp != NULL);
1436 Assert(cb->lib_offset == 0 );
1437 result = fwrite(buf, elsize, nelem, cb->fp);
1443 // cfputc() writes a character to a file
1445 // returns: success ==> returns character written
1448 int cfputc(int c, CFILE *cfile)
1452 Assert(cfile != NULL);
1454 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1455 cb = &Cfile_block_list[cfile->id];
1458 // cfputc() not supported for memory-mapped files
1459 Assert( !cb->data );
1461 Assert(cb->fp != NULL);
1462 result = fputc(c, cb->fp);
1468 // cfgetc() reads a character from a file
1470 // returns: success ==> returns character read
1473 int cfgetc(CFILE *cfile)
1475 Assert(cfile != NULL);
1479 int result = cfread(&tmp, 1, 1, cfile );
1480 if ( result == 1 ) {
1493 // cfgets() reads a string from a file
1495 // returns: success ==> returns pointer to string
1498 char *cfgets(char *buf, int n, CFILE *cfile)
1500 Assert(cfile != NULL);
1501 Assert(buf != NULL);
1507 for (i=0; i<n-1; i++ ) {
1511 int ret = cfread( &tmp_c, 1, 1, cfile );
1521 } while ( c == 13 );
1523 if ( c=='\n' ) break;
1530 // cfputs() writes a string to a file
1532 // returns: success ==> non-negative value
1535 int cfputs(char *str, CFILE *cfile)
1537 Assert(cfile != NULL);
1538 Assert(str != NULL);
1541 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1542 cb = &Cfile_block_list[cfile->id];
1547 // cfputs() not supported for memory-mapped files
1548 Assert( !cb->data );
1549 Assert(cb->fp != NULL);
1550 result = fputs(str, cb->fp);
1556 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1558 // CRC code for mission validation. given to us by Kevin Bentley on 7/20/98. Some sort of
1559 // checksumming code that he wrote a while ago.
1560 #define CRC32_POLYNOMIAL 0xEDB88320L
1561 unsigned long CRCTable[256];
1563 #define CF_CHKSUM_SAMPLE_SIZE 512
1565 // update cur_chksum with the chksum of the new_data of size new_data_size
1566 ushort cf_add_chksum_short(ushort seed, char *buffer, int size)
1568 ubyte * ptr = (ubyte *)buffer;
1569 unsigned int sum1,sum2;
1571 sum1 = sum2 = (int)(seed);
1575 if (sum1 >= 255 ) sum1 -= 255;
1580 return (unsigned short)((sum1<<8)+ sum2);
1583 // update cur_chksum with the chksum of the new_data of size new_data_size
1584 unsigned long cf_add_chksum_long(unsigned long seed, char *buffer, int size)
1588 unsigned long temp1;
1589 unsigned long temp2;
1591 p = (unsigned char*)buffer;
1595 temp1 = (crc>>8)&0x00FFFFFFL;
1596 temp2 = CRCTable[((int)crc^*p++)&0xff];
1603 void cf_chksum_long_init()
1608 for( i=0;i<=255;i++) {
1612 crc=(crc>>1)^CRC32_POLYNOMIAL;
1620 // single function convenient to use for both short and long checksums
1621 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1622 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1624 char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1630 // determine whether we're doing a short or long checksum
1641 // if max_size is -1, set it to be the size of the file
1643 cfseek(cfile, 0, SEEK_SET);
1644 max_size = cfilelength(cfile);
1649 // determine how much we want to read
1650 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1651 read_size = CF_CHKSUM_SAMPLE_SIZE;
1653 read_size = max_size - cf_total;
1656 // read in some buffer
1657 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1659 // total we've read so far
1664 // do the proper short or long checksum
1666 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1668 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1671 } while((cf_len > 0) && (cf_total < max_size));
1676 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1677 int cf_chksum_short(char *filename, ushort *chksum, int max_size, int cf_type)
1680 CFILE *cfile = NULL;
1682 // zero the checksum
1685 // attempt to open the file
1686 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1691 // call the overloaded cf_chksum function()
1692 ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1694 // close the file down
1698 // return the result
1702 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1703 // NOTE : preserves current file position
1704 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1709 // Returns current position of file.
1710 start_pos = cftell(file);
1711 if(start_pos == -1){
1715 // move to the beginning of the file
1716 if(cfseek(file, 0, CF_SEEK_SET)){
1719 ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1720 // move back to the start position
1721 cfseek(file, start_pos, CF_SEEK_SET);
1726 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1727 int cf_chksum_long(char *filename, uint *chksum, int max_size, int cf_type)
1730 CFILE *cfile = NULL;
1732 // zero the checksum
1735 // attempt to open the file
1736 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1741 // call the overloaded cf_chksum function()
1742 ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1744 // close the file down
1748 // return the result
1752 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1753 // NOTE : preserves current file position
1754 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1759 // Returns current position of file.
1760 start_pos = cftell(file);
1761 if(start_pos == -1){
1765 // move to the beginning of the file
1766 if(cfseek(file, 0, CF_SEEK_SET)){
1769 ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1770 // move back to the start position
1771 cfseek(file, start_pos, CF_SEEK_SET);
1777 // Flush the open file buffer
1779 // exit: 0 - success
1781 int cflush(CFILE *cfile)
1783 Assert(cfile != NULL);
1785 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1786 cb = &Cfile_block_list[cfile->id];
1788 // not supported for memory mapped files
1789 Assert( !cb->data );
1791 Assert(cb->fp != NULL);
1792 return fflush(cb->fp);