]> icculus.org git repositories - btb/d2x.git/blob - cfile/cfile.c
correct warnings caused by change of 2004-09-30
[btb/d2x.git] / cfile / cfile.c
1 /* $Id: cfile.c,v 1.31 2004-10-09 21:47:49 schaffner Exp $ */
2 /*
3 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
4 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
5 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
6 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
7 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
8 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
9 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
10 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
11 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
12 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
13 */
14
15 /*
16  *
17  * Functions for accessing compressed files.
18  * (Actually, the files are not compressed, but concatenated within hogfiles)
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <conf.h>
24 #endif
25
26 #include <stdio.h>
27 #include <string.h>
28 #ifdef _WIN32_WCE
29 # include <windows.h>
30 #elif defined(macintosh)
31 # include <Files.h>
32 # include <CFURL.h>
33 #else
34 # include <sys/stat.h>
35 #endif
36
37 #include "pstypes.h"
38 #include "u_mem.h"
39 #include "strutil.h"
40 #include "d_io.h"
41 #include "error.h"
42 #include "cfile.h"
43 #include "byteswap.h"
44
45 /* a file (if offset == 0) or a part of a hog file */
46 struct CFILE {
47         FILE    *file;
48         int     size;
49         int     offset;
50         int     raw_position;
51 };
52
53 struct file_in_hog {
54         char    name[13];
55         int     offset;
56         int     length;
57 };
58
59 #define MAX_FILES_IN_HOG 300
60
61 /* a hog file is an archive, like a tar file */
62 typedef struct {
63         char filename[64];
64         int num_files;
65         struct file_in_hog files[MAX_FILES_IN_HOG];
66 } hog;
67
68 hog *builtin_hog = NULL;
69 hog *alt_hog = NULL;
70 hog *d1_hog = NULL;
71
72 void free_builtin_hog() { if (builtin_hog) d_free (builtin_hog); }
73 void free_alt_hog() { if (alt_hog) d_free (alt_hog); }
74 void free_d1_hog() { if (d1_hog) d_free (d1_hog); }
75
76 char AltHogDir[64];
77 char AltHogdir_initialized = 0;
78
79 // routine to take a DOS path and turn it into a macintosh
80 // pathname.  This routine is based on the fact that we should
81 // see a \ character in the dos path.  The sequence .\ a tthe
82 // beginning of a path is turned into a :
83
84 // routine to take a POSIX style path and turn it into a pre OS X
85 // pathname.  This routine uses CFURL's. This function is necessary
86 // because even though fopen exists in StdCLib
87 // it must take a path in the OS native format.
88
89 #ifdef macintosh
90 void macify_posix_path(char *posix_path, char *mac_path)
91 {
92     CFURLRef    url;
93
94     url = CFURLCreateWithBytes (kCFAllocatorDefault, (ubyte *) posix_path, strlen(posix_path), GetApplicationTextEncoding(), NULL);
95     CFURLGetFileSystemRepresentation (url, 0, (ubyte *) mac_path, 255);
96     CFRelease(url);
97 }
98 #endif
99
100 void cfile_use_alternate_hogdir( char * path )
101 {
102         if ( path )     {
103                 strcpy( AltHogDir, path );
104                 AltHogdir_initialized = 1;
105         } else {
106                 AltHogdir_initialized = 0;
107         }
108 }
109
110 //in case no one installs one
111 int default_error_counter=0;
112
113 //ptr to counter of how many critical errors
114 int *critical_error_counter_ptr=&default_error_counter;
115
116 //tell cfile about your critical error counter
117 void cfile_set_critical_error_counter_ptr(int *ptr)
118 {
119         critical_error_counter_ptr = ptr;
120
121 }
122
123
124 FILE * cfile_get_filehandle( char * filename, char * mode )
125 {
126     FILE * fp;
127     char temp[128];
128 #ifdef macintosh
129     char mac_path[256];
130 #endif
131
132     *critical_error_counter_ptr = 0;
133 #ifdef macintosh
134     macify_posix_path(filename, mac_path);
135     fp = fopen( mac_path, mode );
136 #else
137     fp = fopen( filename, mode );
138 #endif
139     if ( fp && *critical_error_counter_ptr )    {
140         fclose(fp);
141         fp = NULL;
142     }
143     if ( (fp==NULL) && (AltHogdir_initialized) )        {
144         strcpy( temp, AltHogDir );
145         strcat( temp, "/");
146         strcat( temp, filename );
147         *critical_error_counter_ptr = 0;
148 #ifdef macintosh
149         macify_posix_path(temp, mac_path);
150         fp = fopen( mac_path, mode );
151 #else
152         fp = fopen( temp, mode );
153 #endif
154         if ( fp && *critical_error_counter_ptr )        {
155             fclose(fp);
156             fp = NULL;
157         }
158     }
159     return fp;
160 }
161
162 hog * cfile_init_hogfile (char *fname)
163 {
164         char id[4];
165         FILE * fp;
166         int i, len;
167
168         fp = cfile_get_filehandle (fname, "rb");
169         if (fp == NULL)
170                 return 0;
171
172         // verify that it is really a Descent Hog File
173         fread( id, 3, 1, fp );
174         if ( strncmp( id, "DHF", 3 ) )  {
175                 fclose(fp);
176                 return NULL;
177         }
178
179         hog *new_hog = (hog *) d_malloc (sizeof (hog));
180
181         new_hog->num_files = 0;
182         strcpy (new_hog->filename, fname);
183
184         // read file name or reach EOF
185         while (! feof (fp)) {
186                 if (new_hog->num_files >= MAX_FILES_IN_HOG) {
187                         fclose (fp);
188                         d_free (new_hog);
189                         Error ("Exceeded max. number of files in hog (%d).\n",
190                                MAX_FILES_IN_HOG);
191                 }
192                 i = fread (new_hog->files[new_hog->num_files].name, 13, 1, fp);
193                 if (i != 1)
194                         break; // we assume it is EOF, so it is OK
195                 
196                 i = fread( &len, 4, 1, fp );
197                 if (i != 1)
198                         break;
199                 new_hog->files[new_hog->num_files].length = INTEL_INT (len);
200                 new_hog->files[new_hog->num_files].offset = ftell (fp);
201                 // skip over embedded file:
202                 i = fseek (fp, INTEL_INT (len), SEEK_CUR);
203                 new_hog->num_files++;
204         }
205         fclose (fp);
206         return new_hog;
207 }
208
209 // Opens builtin hog given its filename. Returns 1 on success.
210 int cfile_init(char *hogname)
211 {
212         Assert (builtin_hog == NULL);
213
214         builtin_hog = cfile_init_hogfile (hogname);
215         atexit (free_builtin_hog);
216         return builtin_hog != NULL ? 1 : 0;
217 }
218
219
220 int cfile_size(char *hogname)
221 {
222         CFILE *fp;
223         int size;
224
225         fp = cfopen(hogname, "rb");
226         if (fp == NULL)
227                 return -1;
228         size = ffilelength(fp->file);
229         cfclose(fp);
230         return size;
231 }
232
233 FILE * cfile_find_in_hog (char * name, int * length, hog *my_hog) {
234         FILE * fp;
235         int i;
236         for (i = 0; i < my_hog->num_files; i++ )
237                 if (! stricmp (my_hog->files[i].name, name)) {
238                         fp = cfile_get_filehandle (my_hog->filename, "rb");
239                         if (fp == NULL)
240                                 return NULL;
241                         fseek (fp,  my_hog->files[i].offset, SEEK_SET);
242                         *length = my_hog->files[i].length;
243                         return fp;
244                 }
245         return NULL;
246 }
247
248 /*
249  * return handle for file called "name", embedded in one of the hogfiles
250  */
251 FILE * cfile_find_embedded_file (char * name, int * length)
252 {
253         FILE * fp;
254         if (alt_hog) {
255                 fp = cfile_find_in_hog (name, length, alt_hog);
256                 if (fp)
257                         return fp;
258         }
259
260         if (builtin_hog) {
261                 fp = cfile_find_in_hog (name, length, builtin_hog);
262                 if (fp)
263                         return fp;
264         }
265
266         if (d1_hog) {
267                 fp = cfile_find_in_hog (name, length, d1_hog);
268                 if (fp)
269                         return fp;
270         }
271
272         return NULL;
273 }
274
275 int cfile_use_alternate_hogfile (char * name)
276 {
277         if (alt_hog) {
278                 d_free (alt_hog);
279                 alt_hog = NULL;
280         }
281         if (name) {
282                 alt_hog = cfile_init_hogfile (name);
283                 atexit (free_alt_hog);
284                 if (alt_hog)
285                         return 1; // success
286         }
287         return 0;
288 }
289
290 /* we use the d1 hog for d1 textures... */
291 int cfile_use_descent1_hogfile( char * name )
292 {
293         if (d1_hog) {
294                 d_free (d1_hog);
295                 d1_hog = NULL;
296         }
297         if (name) {
298                 d1_hog = cfile_init_hogfile (name);
299                 atexit (free_d1_hog);
300                 if (d1_hog)
301                         return 1; // success
302         }
303         return 0;
304 }
305
306 // cfeof() Tests for end-of-file on a stream
307 //
308 // returns a nonzero value after the first read operation that attempts to read
309 // past the end of the file. It returns 0 if the current position is not end of file.
310 // There is no error return.
311
312 int cfeof(CFILE *cfile)
313 {
314         Assert(cfile != NULL);
315
316         Assert(cfile->file != NULL);
317
318     return (cfile->raw_position >= cfile->size);
319 }
320
321
322 int cferror(CFILE *cfile)
323 {
324         return ferror(cfile->file);
325 }
326
327
328 int cfexist( char * filename )
329 {
330         int length;
331         FILE *fp;
332
333
334         if (filename[0] != '\x01')
335                 fp = cfile_get_filehandle( filename, "rb" );            // Check for non-hog file first...
336         else {
337                 fp = NULL;              //don't look in dir, only in hogfile
338                 filename++;
339         }
340
341         if ( fp )       {
342                 fclose(fp);
343                 return 1;
344         }
345
346         fp = cfile_find_embedded_file (filename, &length);
347         if ( fp )       {
348                 fclose(fp);
349                 return 2;               // file found in hog
350         }
351
352         return 0;               // Couldn't find it.
353 }
354
355
356 // Deletes a file.
357 int cfile_delete(char *filename)
358 {
359 #ifndef _WIN32_WCE
360         return remove(filename);
361 #else
362         return !DeleteFile(filename);
363 #endif
364 }
365
366
367 // Rename a file.
368 int cfile_rename(char *oldname, char *newname)
369 {
370 #ifndef _WIN32_WCE
371         return rename(oldname, newname);
372 #else
373         return !MoveFile(oldname, newname);
374 #endif
375 }
376
377
378 // Make a directory.
379 int cfile_mkdir(char *pathname)
380 {
381 #ifdef _WIN32
382 # ifdef _WIN32_WCE
383         return !CreateDirectory(pathname, NULL);
384 # else
385         return _mkdir(pathname);
386 # endif
387 #elif defined(macintosh)
388     char        mac_path[256];
389     Str255      pascal_path;
390     long        dirID;  // Insists on returning this
391
392     macify_posix_path(pathname, mac_path);
393     CopyCStringToPascal(mac_path, pascal_path);
394     return DirCreate(0, 0, pascal_path, &dirID);
395 #else
396         return mkdir(pathname, 0755);
397 #endif
398 }
399
400
401 CFILE * cfopen(char * filename, char * mode )
402 {
403         int length;
404         FILE * fp;
405         CFILE *cfile;
406
407         if (filename[0] != '\x01')
408                 fp = cfile_get_filehandle( filename, mode );            // Check for non-hog file first...
409         else {
410                 fp = NULL;              //don't look in dir, only in hogfile
411                 filename++;
412         }
413
414         if ( !fp ) {
415                 fp = cfile_find_embedded_file (filename, &length);
416                 if ( !fp )
417                         return NULL;            // No file found
418                 if (stricmp(mode, "rb"))
419                         Error("mode must be rb for files in hog.\n");
420                 cfile = d_malloc ( sizeof(CFILE) );
421                 if ( cfile == NULL ) {
422                         fclose(fp);
423                         return NULL;
424                 }
425                 cfile->file = fp;
426                 cfile->size = length;
427                 cfile->offset = ftell( fp );
428                 cfile->raw_position = 0;
429                 return cfile;
430         } else {
431                 cfile = d_malloc ( sizeof(CFILE) );
432                 if ( cfile == NULL ) {
433                         fclose(fp);
434                         return NULL;
435                 }
436                 cfile->file = fp;
437                 cfile->size = ffilelength(fp);
438                 cfile->offset = 0;
439                 cfile->raw_position = 0;
440                 return cfile;
441         }
442 }
443
444 int cfilelength( CFILE *fp )
445 {
446         return fp->size;
447 }
448
449
450 // cfwrite() writes to the file
451 //
452 // returns:   number of full elements actually written
453 //
454 //
455 int cfwrite(void *buf, int elsize, int nelem, CFILE *cfile)
456 {
457         int items_written;
458
459         Assert(cfile != NULL);
460         Assert(buf != NULL);
461         Assert(elsize > 0);
462
463         Assert(cfile->file != NULL);
464         Assert(cfile->offset == 0);
465
466         items_written = fwrite(buf, elsize, nelem, cfile->file);
467         cfile->raw_position = ftell(cfile->file);
468
469         return items_written;
470 }
471
472
473 // cfputc() writes a character to a file
474 //
475 // returns:   success ==> returns character written
476 //            error   ==> EOF
477 //
478 int cfputc(int c, CFILE *cfile)
479 {
480         int char_written;
481
482         Assert(cfile != NULL);
483
484         Assert(cfile->file != NULL);
485         Assert(cfile->offset == 0);
486
487         char_written = fputc(c, cfile->file);
488         cfile->raw_position = ftell(cfile->file);
489
490         return char_written;
491 }
492
493
494 int cfgetc( CFILE * fp )
495 {
496         int c;
497
498         if (fp->raw_position >= fp->size ) return EOF;
499
500         c = getc( fp->file );
501         if (c!=EOF)
502                 fp->raw_position = ftell(fp->file)-fp->offset;
503
504         return c;
505 }
506
507
508 // cfputs() writes a string to a file
509 //
510 // returns:   success ==> non-negative value
511 //            error   ==> EOF
512 //
513 int cfputs(char *str, CFILE *cfile)
514 {
515         int ret;
516
517         Assert(cfile != NULL);
518         Assert(str != NULL);
519
520         Assert(cfile->file != NULL);
521
522         ret = fputs(str, cfile->file);
523         cfile->raw_position = ftell(cfile->file);
524
525         return ret;
526 }
527
528
529 char * cfgets( char * buf, size_t n, CFILE * fp )
530 {
531         int i;
532         int c;
533
534 #if 0 // don't use the standard fgets, because it will only handle the native line-ending style
535         if (fp->offset == 0) // This is not an archived file
536         {
537                 t = fgets(buf, n, fp->file);
538                 fp->raw_position = ftell(fp->file);
539                 return t;
540         }
541 #endif
542
543         for (i=0; i<n-1; i++ ) {
544                 do {
545                         if (fp->raw_position >= fp->size ) {
546                                 *buf = 0;
547                                 return NULL;
548                         }
549                         c = cfgetc(fp);
550                         if (c == 0 || c == 10)        // Unix line ending
551                                 break;
552                         if (c == 13) {      // Mac or DOS line ending
553                                 int c1;
554
555                                 c1 = cfgetc(fp);
556                                 if (c1 != EOF)  // The file could end with a Mac line ending
557                                         cfseek(fp, -1, SEEK_CUR);
558                                 if ( c1 == 10 ) // DOS line ending
559                                         continue;
560                                 else            // Mac line ending
561                                         break;
562                         }
563                 } while ( c == 13 );
564                 if ( c == 13 )  // because cr-lf is a bad thing on the mac
565                         c = '\n';   // and anyway -- 0xod is CR on mac, not 0x0a
566                 if ( c=='\n' ) break;
567                 *buf++ = c;
568         }
569         *buf++ = 0;
570         return  buf;
571 }
572
573 size_t cfread( void * buf, size_t elsize, size_t nelem, CFILE * fp ) 
574 {
575         unsigned int i, size;
576
577         size = elsize * nelem;
578         if ( size < 1 ) return 0;
579
580         i = fread ( buf, 1, size, fp->file );
581         fp->raw_position += i;
582         return i/elsize;
583 }
584
585
586 int cftell( CFILE *fp ) 
587 {
588         return fp->raw_position;
589 }
590
591 int cfseek( CFILE *fp, long int offset, int where )
592 {
593         int c, goal_position;
594
595         switch( where ) {
596         case SEEK_SET:
597                 goal_position = offset;
598                 break;
599         case SEEK_CUR:
600                 goal_position = fp->raw_position+offset;
601                 break;
602         case SEEK_END:
603                 goal_position = fp->size+offset;
604                 break;
605         default:
606                 return 1;
607         }       
608         c = fseek( fp->file, fp->offset + goal_position, SEEK_SET );
609         fp->raw_position = ftell(fp->file)-fp->offset;
610         return c;
611 }
612
613 int cfclose(CFILE *fp)
614 {
615         int result;
616
617         result = fclose(fp->file);
618         d_free(fp);
619
620         return result;
621 }
622
623 // routines to read basic data types from CFILE's.  Put here to
624 // simplify mac/pc reading from cfiles.
625
626 int cfile_read_int(CFILE *file)
627 {
628         int32_t i;
629
630         if (cfread( &i, sizeof(i), 1, file) != 1)
631                 Error( "Error reading int in cfile_read_int()" );
632
633         i = INTEL_INT(i);
634         return i;
635 }
636
637 short cfile_read_short(CFILE *file)
638 {
639         int16_t s;
640
641         if (cfread( &s, sizeof(s), 1, file) != 1)
642                 Error( "Error reading short in cfile_read_short()" );
643
644         s = INTEL_SHORT(s);
645         return s;
646 }
647
648 sbyte cfile_read_byte(CFILE *file)
649 {
650         sbyte b;
651
652         if (cfread( &b, sizeof(b), 1, file) != 1)
653                 Error( "Error reading byte in cfile_read_byte()" );
654
655         return b;
656 }
657
658 fix cfile_read_fix(CFILE *file)
659 {
660         fix f;
661
662         if (cfread( &f, sizeof(f), 1, file) != 1)
663                 Error( "Error reading fix in cfile_read_fix()" );
664
665         f = (fix)INTEL_INT((int)f);
666         return f;
667 }
668
669 fixang cfile_read_fixang(CFILE *file)
670 {
671         fixang f;
672
673         if (cfread(&f, 2, 1, file) != 1)
674                 Error("Error reading fixang in cfile_read_fixang()");
675
676         f = (fixang) INTEL_SHORT((int) f);
677         return f;
678 }
679
680 void cfile_read_vector(vms_vector *v, CFILE *file)
681 {
682         v->x = cfile_read_fix(file);
683         v->y = cfile_read_fix(file);
684         v->z = cfile_read_fix(file);
685 }
686
687 void cfile_read_angvec(vms_angvec *v, CFILE *file)
688 {
689         v->p = cfile_read_fixang(file);
690         v->b = cfile_read_fixang(file);
691         v->h = cfile_read_fixang(file);
692 }
693
694 void cfile_read_matrix(vms_matrix *m,CFILE *file)
695 {
696         cfile_read_vector(&m->rvec,file);
697         cfile_read_vector(&m->uvec,file);
698         cfile_read_vector(&m->fvec,file);
699 }
700
701
702 void cfile_read_string(char *buf, int n, CFILE *file)
703 {
704         char c;
705
706         do {
707                 c = (char)cfile_read_byte(file);
708                 if (n > 0)
709                 {
710                         *buf++ = c;
711                         n--;
712                 }
713         } while (c != 0);
714 }
715
716
717 // equivalent write functions of above read functions follow
718
719 int cfile_write_int(int i, CFILE *file)
720 {
721         i = INTEL_INT(i);
722         return cfwrite(&i, sizeof(i), 1, file);
723 }
724
725
726 int cfile_write_short(short s, CFILE *file)
727 {
728         s = INTEL_SHORT(s);
729         return cfwrite(&s, sizeof(s), 1, file);
730 }
731
732
733 int cfile_write_byte(sbyte b, CFILE *file)
734 {
735         return cfwrite(&b, sizeof(b), 1, file);
736 }
737
738
739 int cfile_write_string(char *buf, CFILE *file)
740 {
741         int len;
742
743         if ((!buf) || (buf && !buf[0]))
744                 return cfile_write_byte(0, file);
745
746         len = strlen(buf);
747         if (!cfwrite(buf, len, 1, file))
748                 return 0;
749
750         return cfile_write_byte(0, file);   // write out NULL termination
751 }