Beispiel #1
0
void palette_load_table(char* filename)
{
	int i;
	int w, h;
	int pcx_error;

	strcpy_s(palette_base_filename, filename);
	char* p = strchr(palette_base_filename, '.');
	if (p)
	{
		*p = 0;
	}

	pcx_error = pcx_read_header(palette_base_filename, NULL, &w, &h, NULL, palette_org);
	if (pcx_error != PCX_ERROR_NONE)
	{
		// Read the old .256 file
		CFILE* fp;
		int fsize;
		fp = cfopen(palette_base_filename, "rb");
		if (fp == NULL)
			Error(LOCATION, "Can't open palette file <%s>", palette_base_filename);

		fsize = cfilelength(fp);
		Assert(fsize == 9472);
		cfread(palette_org, 256 * 3, 1, fp);
		cfclose(fp);

		for (i = 0; i < 768; i++)
		{
			palette_org[i] = ubyte((palette_org[i] * 255) / 63);
		}
	}

	palette_base_loaded = 1;

	gr_set_palette(palette_base_filename, palette_org);
}
void fs2netd_update_ban_list()
{
	int rc = 0;

	if ( !Logged_in ) {
		return;
	}

	// destroy the file prior to updating
	cf_delete( "banlist.cfg", CF_TYPE_DATA );

	do_full_packet = true;

	In_process = true;

	if (Is_standalone) {
		do { rc = fs2netd_update_ban_list_do(); } while (!rc);
	} else {
		rc = popup_till_condition(fs2netd_update_ban_list_do, XSTR("&Cancel", 779), XSTR("Requesting IP ban list", 1587));
	}

	In_process = false;
	Local_timeout = -1;

	if ( !FS2NetD_ban_list.empty() ) {
		CFILE *banlist_cfg = cfopen("banlist.cfg", "wt", CFILE_NORMAL, CF_TYPE_DATA);

		if (banlist_cfg != NULL) {
			for (SCP_vector<SCP_string>::iterator bl = FS2NetD_ban_list.begin(); bl != FS2NetD_ban_list.end(); ++bl) {
				cfputs( const_cast<char*>(bl->c_str()), banlist_cfg );
			}

			cfclose(banlist_cfg);
		}
	}

	FS2NetD_ban_list.clear();
}
Beispiel #3
0
Datei: titles.c Projekt: btb/d1x
// -----------------------------------------------------------------------------
//	Load Descent briefing text.
void load_screen_text(char *filename, char **buf)
{
	CFILE	*tfile;
	CFILE *ifile;
	int	len, i;
	int	have_binary = 0;

	if ((tfile = cfopen(filename,"rb")) == NULL) {
		char nfilename[30], *ptr;

		strcpy(nfilename, filename);
		if ((ptr = strrchr(nfilename, '.')))
			*ptr = '\0';
		strcat(nfilename, ".txb");
		if ((ifile = cfopen(nfilename, "rb")) == NULL)
			Error("Cannot open file %s or %s", filename, nfilename);
		have_binary = 1;

		len = cfilelength(ifile);
		MALLOC(*buf,char, len);
		cfread(*buf, 1, len, ifile);
		cfclose(ifile);
	} else {
/**
 * Load a shader file from disc or from the builtin defaults in def_files.cpp if none can be found.
 * This function will also create a list of preprocessor defines for the GLSL compiler based on the shader flags
 * and the supported GLSL version as reported by the GPU driver.
 *
 * @param shader	shader_type enum defined with which shader we're loading
 * @param filename	C-string holding the filename (with extension) of the shader file
 * @param flags		integer variable holding a combination of SDR_* flags
 * @return			C-string holding the complete shader source code
 */
static SCP_string opengl_load_shader(const char* filename) {
	SCP_string content;
	if (Enable_external_shaders) {
		CFILE* cf_shader = cfopen(filename, "rt", CFILE_NORMAL, CF_TYPE_EFFECTS);

		if (cf_shader != NULL) {
			int len = cfilelength(cf_shader);
			content.resize(len);

			cfread(&content[0], len + 1, 1, cf_shader);
			cfclose(cf_shader);

			return content;
		}
	}

	//If we're still here, proceed with internals
	mprintf(("   Loading built-in default shader for: %s\n", filename));
	auto def_shader = defaults_get_file(filename);
	content.assign(reinterpret_cast<const char*>(def_shader.data), def_shader.size);

	return content;
}
Beispiel #5
0
//Specify the name of the hogfile.  Returns 1 if hogfile found & had files
int cfile_init(char *hogname)
{
	#ifdef MACINTOSH
	char mac_path[255];

	macify_dospath(hogname, mac_path);
	#endif

	Assert(Hogfile_initialized == 0);

	#ifndef MACINTOSH
	if (cfile_init_hogfile(hogname, HogFiles, &Num_hogfiles )) {
		strcpy( HogFilename, hogname );
	#else
	if (cfile_init_hogfile(mac_path, HogFiles, &Num_hogfiles )) {
		strcpy( HogFilename, mac_path );
	#endif
		Hogfile_initialized = 1;
		return 1;
	}
	else
		return 0;	//not loaded!
}


int cfile_size(char *hogname)
{
	CFILE *fp;
	struct stat statbuf;

	fp = cfopen(hogname, "rb");
	if (fp == NULL)
		return -1;
	fstat(fileno(fp->file), &statbuf);
	cfclose(fp);
	return statbuf.st_size;
}
Beispiel #6
0
void gr_use_palette_table( char * filename )
{
	CFILE *fp;
	int i,j;
	ubyte c;

	fp = cfopen( filename, "rb" );
	if ( fp==NULL)
		Error("Can't open palette file <%s> which is not in the current dir.",filename);

	cfread( gr_palette, 256*3, 1, fp );
	cfread( gr_fade_table, 256*34, 1, fp );
	cfclose(fp);

	// This is the TRANSPARENCY COLOR
	for (i=0; i<GR_FADE_LEVELS; i++ )	{
		gr_fade_table[i*256+255] = 255;
	}
	
// swap colors 0 and 255 of the palette along with fade table entries

#ifdef SWAP_0_255
	for (i = 0; i < 3; i++) {
		c = gr_palette[i];
		gr_palette[i] = gr_palette[765+i];
		gr_palette[765+i] = c;
	}

	for (i = 0; i < GR_FADE_LEVELS * 256; i++) {
		if (gr_fade_table[i] == 0)
			gr_fade_table[i] = 255;
	}
	for (i=0; i<GR_FADE_LEVELS; i++)
		gr_fade_table[i*256] = TRANSPARENCY_COLOR;
#endif
}
// plays the voice file associated with a training message.  Automatically streams the file
// from disk if it's over 100k, otherwise plays it as a normal file in memory.  Returns -1
// if it didn't play, otherwise index of voice
int message_play_training_voice(int index)
{
	int len;
	CFILE *fp;

	if (index < 0) {
		if (Training_voice >= 0) {
			if (Training_voice_type) {
				audiostream_close_file(Training_voice_handle, 0);

			} else {
				snd_stop(Training_voice_handle);
			}
		}

		Training_voice = -1;
		return -1;
	}

	if (Message_waves[index].num < 0) {
		fp = cfopen(Message_waves[index].name, "rb");
		if (!fp)
			return -1;

		len = cfilelength(fp);
		cfclose(fp);
		if (len > 100000) {
			if ((Training_voice < 0) || !Training_voice_type || (Training_voice != index)) {
				if (Training_voice >= 0) {
					if (Training_voice_type) {
						if (Training_voice == index)
							audiostream_stop(Training_voice_handle, 1, 0);
						else
							audiostream_close_file(Training_voice_handle, 0);

					} else {
						snd_stop(Training_voice_handle);
					}
				}

				if (stricmp(Message_waves[index].name, NOX("none.wav"))) {
					Training_voice_handle = audiostream_open(Message_waves[index].name, ASF_VOICE);
					if (Training_voice_handle < 0) {
						nprintf(("Warning", "Unable to load voice file %s\n", Message_waves[index].name));
					//	Warning(LOCATION, "Unable to load voice file %s\n", Message_waves[index].name);
					}
				}
			}  // Training_voice should be valid and loaded now

			Training_voice_type = 1;
			if (Training_voice_handle >= 0)
				audiostream_play(Training_voice_handle, Master_voice_volume, 0);

			Training_voice = index;
			return Training_voice;

		} else {
			game_snd tmp_gs;
			memset(&tmp_gs, 0, sizeof(game_snd));
			strcpy(tmp_gs.filename, Message_waves[index].name);
			Message_waves[index].num = snd_load(&tmp_gs, 0);
			if (Message_waves[index].num < 0) {
				nprintf(("Warning", "Cannot load message wave: %s.  Will not play\n", Message_waves[index].name));
				return -1;
			}
		}
	}

	if (Training_voice >= 0) {
		if (Training_voice_type) {
			audiostream_close_file(Training_voice_handle, 0);

		} else {
			snd_stop(Training_voice_handle);
		}
	}

	Training_voice = index;
	if (Message_waves[index].num >= 0)
		Training_voice_handle = snd_play_raw(Message_waves[index].num, 0.0f);
	else
		Training_voice_handle = -1;

	Training_voice_type = 0;
	return Training_voice;
}
/**
 * Load a shader file from disc or from the builtin defaults in def_files.cpp if none can be found.
 * This function will also create a list of preprocessor defines for the GLSL compiler based on the shader flags
 * and the supported GLSL version as reported by the GPU driver.
 *
 * @param filename	C-string holding the filename (with extension) of the shader file
 * @param flags		integer variable holding a combination of SDR_* flags
 * @return			C-string holding the complete shader source code
 */
static char *opengl_load_shader(char *filename, int flags)
{
	SCP_string sflags;

	if (Use_GLSL >= 4) {
		sflags += "#define SHADER_MODEL 4\n";
	} else if (Use_GLSL == 3) {
		sflags += "#define SHADER_MODEL 3\n";
	} else {
		sflags += "#define SHADER_MODEL 2\n";
	}

	if (flags & SDR_FLAG_DIFFUSE_MAP) {
		sflags += "#define FLAG_DIFFUSE_MAP\n";
	}

	if (flags & SDR_FLAG_ENV_MAP) {
		sflags += "#define FLAG_ENV_MAP\n";
	}

	if (flags & SDR_FLAG_FOG) {
		sflags += "#define FLAG_FOG\n";
	}

	if (flags & SDR_FLAG_GLOW_MAP) {
		sflags += "#define FLAG_GLOW_MAP\n";
	}

	if (flags & SDR_FLAG_HEIGHT_MAP) {
		sflags += "#define FLAG_HEIGHT_MAP\n";
	}

	if (flags & SDR_FLAG_LIGHT) {
		sflags += "#define FLAG_LIGHT\n";
	}

	if (flags & SDR_FLAG_NORMAL_MAP) {
		sflags += "#define FLAG_NORMAL_MAP\n";
	}

	if (flags & SDR_FLAG_SPEC_MAP) {
		sflags += "#define FLAG_SPEC_MAP\n";
	}

	if (flags & SDR_FLAG_ANIMATED) {
		sflags += "#define FLAG_ANIMATED\n";
	}

	if (flags & SDR_FLAG_DISTORTION) {
		sflags += "#define FLAG_DISTORTION\n";
	}

	if (flags & SDR_FLAG_MISC_MAP) {
		sflags += "#define FLAG_MISC_MAP\n";
	}

	if (flags & SDR_FLAG_TEAMCOLOR) {
		sflags += "#define FLAG_TEAMCOLOR\n";
	}

	if (flags & SDR_FLAG_THRUSTER) {
		sflags += "#define FLAG_THRUSTER\n";
	}

	const char *shader_flags = sflags.c_str();
	int flags_len = strlen(shader_flags);

	if (Enable_external_shaders) {
		CFILE *cf_shader = cfopen(filename, "rt", CFILE_NORMAL, CF_TYPE_EFFECTS);
	
		if (cf_shader != NULL) {
			int len = cfilelength(cf_shader);
			char *shader = (char*) vm_malloc(len + flags_len + 1);

			strcpy(shader, shader_flags);
			memset(shader + flags_len, 0, len + 1);
			cfread(shader + flags_len, len + 1, 1, cf_shader);
			cfclose(cf_shader);

			return shader;	
		}
	}

	//If we're still here, proceed with internals
	mprintf(("   Loading built-in default shader for: %s\n", filename));
	char* def_shader = defaults_get_file(filename);
	size_t len = strlen(def_shader);
	char *shader = (char*) vm_malloc(len + flags_len + 1);

	strcpy(shader, shader_flags);
	strcat(shader, def_shader);

	return shader;
}
Beispiel #9
0
void credits_init()
{
	int i, w, h;
	credits_screen_buttons *b;
	char line[512] = "";	
	char *linep1, *linep2;	

	int credits_spooled_music_index = event_music_get_spooled_music_index("Cinema");	
	if(credits_spooled_music_index != -1){
		char *credits_wavfile_name = Spooled_music[credits_spooled_music_index].filename;		
		if(credits_wavfile_name != NULL){
			credits_load_music(credits_wavfile_name);
		}
	}

	// Use this id to trigger the start of music playing on the briefing screen
	Credits_music_begin_timestamp = timestamp(CREDITS_MUSIC_DELAY);

	Credits_frametime = 0;
	Credits_last_time = timer_get_milliseconds();

	Credit_text = NULL;
	Credit_text_malloced = 0;

	// allocate enough space for credits text
	CFILE *fp = cfopen( NOX("credits.tbl"), "rb" );
	if(fp != NULL){
		int rval, size;
		size = cfilelength(fp);
		Credit_text = (char *) vm_malloc(size + 200 + strlen(fs2_open_credit_text) + strlen(unmodified_credits));
		if (Credit_text == NULL) {
			return;
		} else {
			Credit_text_malloced = 1;
		}
		cfclose(fp);

		// open localization
		lcl_ext_open();

		if ((rval = setjmp(parse_abort)) != 0) {
			mprintf(("TABLES: Unable to parse '%s'!  Error code = %i.\n", "credits.tbl", rval));
			lcl_ext_close();
			return;
		}
		
		read_file_text("credits.tbl");
		reset_parse();

		// keep reading everything in
		strcpy(Credit_text, fs2_open_credit_text); 
	   
		bool first_run = true;
		while(!check_for_string_raw("#end")){ 
			
			stuff_string_line(line, sizeof(line));

			// This is a bit odd but it means if a total conversion uses different credits the 
			// Volition credit won't happen
			if(first_run == true)
			{
				if(strcmp(line, mod_check) == 0)
				{
					strcat(Credit_text,	unmodified_credits);	
				}

				first_run = false;
			}

			linep1 = line;

			do {
				linep2 = split_str_once(linep1, Credits_text_coords[gr_screen.res][2]);
				Assert( linep2 != linep1 );
				strcat(Credit_text, linep1);
				strcat(Credit_text, "\n");			
				linep1 = linep2;
			} while (linep2 != NULL);
		}		

		// close localization
		lcl_ext_close();	
	} else {
		Credit_text = NOX("No credits available.\n");
	}	

	int ch;
	for ( i = 0; Credit_text[i]; i++ ) {
			ch = Credit_text[i];
			switch (ch) {
			case -4:
				ch = 129;
				break;

			case -28:
				ch = 132;
				break;

			case -10:
				ch = 148;
				break;

			case -23:
				ch = 130;
				break;

			case -30:
				ch = 131;
				break;

			case -25:
				ch = 135;
				break;

			case -21:
				ch = 137;
				break;

			case -24:
				ch = 138;
				break;

			case -17:
				ch = 139;
				break;

			case -18:
				ch = 140;
				break;

			case -60:
				ch = 142;
				break;

			case -55:
				ch = 144;
				break;

			case -12:
				ch = 147;
				break;

			case -14:
				ch = 149;
				break;

			case -5:
				ch = 150;
				break;

			case -7:
				ch = 151;
				break;

			case -42:
				ch = 153;
				break;

			case -36:
				ch = 154;
				break;

			case -31:
				ch = 160;
				break;

			case -19:
				ch = 161;
				break;

			case -13:
				ch = 162;
				break;

			case -6:
				ch = 163;
				break;

			case -32:
				ch = 133;
				break;

			case -22:
				ch = 136;
				break;

			case -20:
				ch = 141;
				break;
			}
			Credit_text[i] = (char)ch;
	}

	gr_get_string_size(&w, &h, Credit_text);

	Credit_start_pos = i2fl(Credits_text_coords[gr_screen.res][CREDITS_H_COORD]);
	Credit_stop_pos = -i2fl(h);
	Credit_position = Credit_start_pos;

	Ui_window.create(0, 0, gr_screen.max_w_unscaled, gr_screen.max_h_unscaled, 0);
	Ui_window.set_mask_bmap(Credits_bitmap_mask_fname[gr_screen.res]);
	common_set_interface_palette("InterfacePalette");  // set the interface palette

	for (i=0; i<NUM_BUTTONS; i++) {
		b = &Buttons[i][gr_screen.res];

		b->button.create(&Ui_window, "", b->x, b->y, 60, 30, (i < 2), 1);
		// set up callback for when a mouse first goes over a button
		b->button.set_highlight_action(common_play_highlight_sound);
		b->button.set_bmaps(b->filename);
		b->button.link_hotspot(b->hotspot);
	}

	// add some text
	Ui_window.add_XSTR("Technical Database", 1055, Buttons[TECH_DATABASE_BUTTON][gr_screen.res].xt,  Buttons[TECH_DATABASE_BUTTON][gr_screen.res].yt, &Buttons[TECH_DATABASE_BUTTON][gr_screen.res].button, UI_XSTR_COLOR_GREEN);
	Ui_window.add_XSTR("Mission Simulator", 1056, Buttons[SIMULATOR_BUTTON][gr_screen.res].xt,  Buttons[SIMULATOR_BUTTON][gr_screen.res].yt, &Buttons[SIMULATOR_BUTTON][gr_screen.res].button, UI_XSTR_COLOR_GREEN);
	Ui_window.add_XSTR("Cutscenes", 1057, Buttons[CUTSCENES_BUTTON][gr_screen.res].xt,  Buttons[CUTSCENES_BUTTON][gr_screen.res].yt, &Buttons[CUTSCENES_BUTTON][gr_screen.res].button, UI_XSTR_COLOR_GREEN);
	Ui_window.add_XSTR("Credits", 1058, Buttons[CREDITS_BUTTON][gr_screen.res].xt,  Buttons[CREDITS_BUTTON][gr_screen.res].yt, &Buttons[CREDITS_BUTTON][gr_screen.res].button, UI_XSTR_COLOR_GREEN);
	Ui_window.add_XSTR("Exit", 1420, Buttons[EXIT_BUTTON][gr_screen.res].xt,  Buttons[EXIT_BUTTON][gr_screen.res].yt, &Buttons[EXIT_BUTTON][gr_screen.res].button, UI_XSTR_COLOR_PINK);

	if (Player->flags & PLAYER_FLAGS_IS_MULTI) {
		Buttons[SIMULATOR_BUTTON][gr_screen.res].button.disable();
		Buttons[CUTSCENES_BUTTON][gr_screen.res].button.disable();
	}

	Buttons[EXIT_BUTTON][gr_screen.res].button.set_hotkey(KEY_CTRLED | KEY_ENTER);

	Background_bitmap = bm_load(Credits_bitmap_fname[gr_screen.res]);
	Credits_artwork_index = rand() % NUM_IMAGES;
	for (i=0; i<NUM_IMAGES; i++){
		Credits_bmps[i] = -1;
	}

	// CreditsWin01 = bm_load(NOX("CreditsWin01"));
	// CreditsWin02 = bm_load(NOX("CreditsWin02"));
	// CreditsWin03 = bm_load(NOX("CreditsWin03"));
	// CreditsWin04 = bm_load(NOX("CreditsWin04"));
}
Beispiel #10
0
int pcx_read_bitmap_16bpp_nondark( char * real_filename, ubyte *org_data )
{	
	PCXHeader header;
	CFILE * PCXfile;
	int row, col, count, xsize, ysize;
	ubyte data=0;
	int buffer_size, buffer_pos;
	ubyte buffer[1024];
	ubyte *pixdata;
	char filename[MAX_FILENAME_LEN];
	ubyte palette[768];	
	ushort bit_16;	
	ubyte r, g, b, al;
		
	strcpy( filename, real_filename );
	char *p = strchr( filename, '.' );
	if ( p ) *p = 0;
	strcat( filename, ".pcx" );

	PCXfile = cfopen( filename , "rb" );
	if ( !PCXfile ){
		return PCX_ERROR_OPENING;
	}

	// read 128 char PCX header
	if (cfread( &header, sizeof(PCXHeader), 1, PCXfile )!=1)	{
		cfclose( PCXfile );
		return PCX_ERROR_NO_HEADER;
	}
        header.Xmin = INTEL_SHORT( header.Xmin );
        header.Ymin = INTEL_SHORT( header.Ymin );
        header.Xmax = INTEL_SHORT( header.Xmax );
        header.Ymax = INTEL_SHORT( header.Ymax );
        header.Hdpi = INTEL_SHORT( header.Hdpi );
        header.Vdpi = INTEL_SHORT( header.Vdpi );
        header.BytesPerLine = INTEL_SHORT( header.BytesPerLine );       

	// Is it a 256 color PCX file?
	if ((header.Manufacturer != 10)||(header.Encoding != 1)||(header.Nplanes != 1)||(header.BitsPerPixel != 8)||(header.Version != 5))	{
		cfclose( PCXfile );
		return PCX_ERROR_WRONG_VERSION;
	}

	// Find the size of the image
	xsize = header.Xmax - header.Xmin + 1;
	ysize = header.Ymax - header.Ymin + 1;

	// Read the extended palette at the end of PCX file
	// Read in a character which should be 12 to be extended palette file

	cfseek( PCXfile, -768, CF_SEEK_END );
	cfread( palette, 3, 256, PCXfile );
	cfseek( PCXfile, sizeof(PCXHeader), CF_SEEK_SET );
	
	buffer_size = 1024;
	buffer_pos = 0;
	
//	Assert( buffer_size == 1024 );	// AL: removed to avoid optimized warning 'unreachable code'
	buffer_size = cfread( buffer, 1, buffer_size, PCXfile );

	count = 0;

	for (row=0; row<ysize;row++)      {
		pixdata = org_data;
		for (col=0; col<header.BytesPerLine;col++)     {
			if ( count == 0 )	{
				data = buffer[buffer_pos++];
				if ( buffer_pos == buffer_size )	{
					buffer_size = cfread( buffer, 1, buffer_size, PCXfile );
					Assert( buffer_size > 0 );
					buffer_pos = 0;
				}
				if ((data & 0xC0) == 0xC0)     {
					count = data & 0x3F;
					data = buffer[buffer_pos++];
					if ( buffer_pos == buffer_size )	{
						buffer_size = cfread( buffer, 1, buffer_size, PCXfile );
						Assert( buffer_size > 0 );
						buffer_pos = 0;
					}
				} else {
					count = 1;
				}
			}
			// stuff the pixel
			if ( col < xsize ){				
				// stuff the 24 bit value				
				r = palette[data*3];
				g = palette[data*3 + 1];
				b = palette[data*3 + 2];							

				// if this is a nondarkening texture				
				// if this color matches a nondarkening pixel color, set the alpha to high
				al = 0;
				if(palman_is_nondarkening(r, g, b)){
					al = 255;
				}

				// set the pixel
				bit_16 = 0;
				bm_set_components((ubyte*)&bit_16, &r, &g, &b, &al);					
				
				// stuff the pixel
				*((ushort*)pixdata) = bit_16;				
				pixdata += 2;
			}
			count--;
		}

		org_data += (xsize * 2);
	}
	cfclose(PCXfile);
	return PCX_ERROR_NONE;
}
Beispiel #11
0
// Reads header information from the JPEG file into the bitmap pointer
// 
// filename - name of the JPEG bitmap file
// w - (output) width of the bitmap
// h - (output) height of the bitmap
// bpp - (output) bits per pixel of the bitmap
//
// returns - JPEG_ERROR_NONE if successful, otherwise error code
//
int jpeg_read_header(char* real_filename, CFILE* img_cfp, int* w, int* h, int* bpp, ubyte* palette)
{
	CFILE* jpeg_file = NULL;
	char filename[MAX_FILENAME_LEN];

	if (img_cfp == NULL)
	{
		strcpy_s(filename, real_filename);

		char* p = strchr(filename, '.');

		if (p)
			*p = 0;

		strcat_s(filename, ".jpg");

		jpeg_file = cfopen(filename, "rb");

		if (!jpeg_file)
		{
			return JPEG_ERROR_READING;
		}
	}
	else
	{
		jpeg_file = img_cfp;
	}

	Assert(jpeg_file != NULL);

	if (jpeg_file == NULL)
		return JPEG_ERROR_READING;

	// set the basic/default error code
	Jpeg_Set_Error(JPEG_ERROR_NONE);

	// initialize error message handler and decompression struct
	jpeg_info.err = jpeg_std_error(&jpeg_err);
	jpeg_err.error_exit = jpg_error_exit;
	jpeg_err.output_message = jpg_output_message;

	jpeg_create_decompress(&jpeg_info);

	// setup to read data via CFILE
	jpeg_cfile_src(&jpeg_info, jpeg_file);

	jpeg_read_header(&jpeg_info, TRUE);

	// send the info back out
	if (w)
		*w = jpeg_info.image_width;
	if (h)
		*h = jpeg_info.image_height;
	if (bpp)
		*bpp = (jpeg_info.num_components * 8);

	// cleanup
	jpeg_destroy_decompress(&jpeg_info);

	if (img_cfp == NULL)
	{
		cfclose(jpeg_file);
		jpeg_file = NULL;
	}

	return jpeg_error_code;
}
Beispiel #12
0
// Loads a JPEG image
// 
// filename - name of the targa file to load
// image_data - allocated storage for the bitmap
//
// returns - true if succesful, false otherwise
//
int jpeg_read_bitmap(char* real_filename, ubyte* image_data, ubyte* palette, int dest_size, int cf_type)
{
	char filename[MAX_FILENAME_LEN];
	CFILE* img_cfp = NULL;
	JSAMPARRAY buffer = NULL;
	int rc = 0;

	strcpy_s(filename, real_filename);
	char* p = strchr(filename, '.');
	if (p)
		*p = 0;
	strcat_s(filename, ".jpg");


	img_cfp = cfopen(filename, "rb", CFILE_NORMAL, cf_type);

	if (img_cfp == NULL)
		return JPEG_ERROR_READING;

	// set the basic error code
	Jpeg_Set_Error(JPEG_ERROR_NONE);

	// initialize error message handler
	jpeg_info.err = jpeg_std_error(&jpeg_err);
	jpeg_err.error_exit = jpg_error_exit;
	jpeg_err.output_message = jpg_output_message;

	// SPECIAL NOTE: we've already allocated memory on the basis of original height, width and bpp
	// of the image from the header.  DO NOT change any settings that affect output variables here
	// or we risk needed more memory than we have available in "image_data".  The only exception is
	// bpp since 'dest_size' should already indicate what we want to end up with.

	if ((rc = setjmp(FSJpegError) == 0) != FALSE)
	{
		// initialize decompression struct
		jpeg_create_decompress(&jpeg_info);

		// setup to read data via CFILE
		jpeg_cfile_src(&jpeg_info, img_cfp);

		jpeg_read_header(&jpeg_info, TRUE);

		// memory for the storage of each scanline
		jpeg_calc_output_dimensions(&jpeg_info);

		// set the output components to be 'dest_size' (so we can support 16/24/32-bit images with this one function)
		// NOTE: only 24-bit is actually supported right now, we don't currently up/down sample at all
		jpeg_info.output_components = dest_size;
		jpeg_info.out_color_components = dest_size;	// may need/have to match above

		// multiplying by rec_outbuf_height isn't required but is more efficient
		int size = jpeg_info.output_width * jpeg_info.output_components * jpeg_info.rec_outbuf_height;
		// a standard malloc doesn't appear to work properly here (debug vm_malloc], crashes in lib
		buffer = (*jpeg_info.mem->alloc_sarray)((j_common_ptr)&jpeg_info, JPOOL_IMAGE, size, 1); // DON'T free() THIS! jpeg lib does it

		// begin decompression process --
		jpeg_start_decompress(&jpeg_info);

		// read each scanline and output to previously allocated 'image_data'
		while (jpeg_info.output_scanline < jpeg_info.output_height)
		{
			jpeg_read_scanlines(&jpeg_info, buffer, 1);

			memcpy(image_data, *buffer, size);
			image_data += size;
		}

		// -- done with decompression process
		jpeg_finish_decompress(&jpeg_info);

		// cleanup
		jpeg_destroy_decompress(&jpeg_info);
	}

	cfclose(img_cfp);


	return jpeg_error_code;
}
static bool load_cached_shader_binary(opengl::ShaderProgram* program, SCP_string hash) {
	if (!do_shader_caching()) {
		return false;
	}

	auto base_filename = SCP_string("ogl_shader-") + hash;

	auto metadata = base_filename + ".json";
	auto binary = base_filename + ".bin";

	auto metadata_fp = cfopen(metadata.c_str(), "rb", CFILE_NORMAL, CF_TYPE_CACHE);
	if (!metadata_fp) {
		nprintf(("ShaderCache", "Metadata file does not exist.\n"));
		return false;
	}

	auto size = cfilelength(metadata_fp);
	SCP_string metadata_content;
	metadata_content.resize((size_t) size);
	cfread(&metadata_content[0], 1, size, metadata_fp);

	cfclose(metadata_fp);

	auto metadata_root = json_loads(metadata_content.c_str(), 0, nullptr);
	if (!metadata_root) {
		mprintf(("Loading of cache metadata failed! Falling back to GLSL shader...\n"));
		return false;
	}

	json_int_t format;
	if (json_unpack(metadata_root, "{sI}", "format", &format) != 0) {
		mprintf(("Failed to unpack values from metadata JSON! Falling back to GLSL shader...\n"));
		return false;
	}
	auto binary_format = (GLenum) format;
	json_decref(metadata_root);

	auto binary_fp = cfopen(binary.c_str(), "rb", CFILE_NORMAL, CF_TYPE_CACHE);
	if (!binary_fp) {
		nprintf(("ShaderCache", "Binary file does not exist.\n"));
		return false;
	}
	
	GR_DEBUG_SCOPE("Loading cached shader");
	
	SCP_vector<uint8_t> buffer;
	int length = cfilelength(binary_fp);
	buffer.resize((size_t) length);
	cfread(&buffer[0], 1, length, binary_fp);

	cfclose(binary_fp);

	// Load the data!
	glProgramBinary(program->getShaderHandle(), binary_format, buffer.data(), (GLsizei) buffer.size());

	// Check the status...
	GLint status;
	glGetProgramiv(program->getShaderHandle(), GL_LINK_STATUS, &status);

	return status == GL_TRUE;
}
Beispiel #14
0
int
sed_main(int argc, char *argv[])
{
	int c, fflag;
	char *temp_arg;

    // init all flags:
    aflag = eflag = sed_nflag = rflags = 0;
    infile = NULL;
    outfile = NULL;
    fl_nextp = &files;
    if (files != NULL) {
        while (files != NULL) { struct s_flist *next = files->next; free(files); files = next; }
    }
    cu_nextp = &script;
    if (script != NULL) {
        while (script != NULL) { struct s_compunit *next = script->next; free(script); script = next; }
    }
    rval = 0;        /* Exit status */

	(void) setlocale(LC_ALL, "");

	fflag = 0;
	inplace = NULL;

	while ((c = getopt(argc, argv, "Eae:f:i:ln")) != -1)
		switch (c) {
		case 'E':
			rflags = REG_EXTENDED;
			break;
		case 'a':
			aflag = 1;
			break;
		case 'e':
			eflag = 1;
			if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
                fprintf(stderr, "sed: malloc: %s\n", strerror(errno)); // err(1, "malloc");
			strcpy(temp_arg, optarg);
			strcat(temp_arg, "\n");
			add_compunit(CU_STRING, temp_arg);
			break;
		case 'f':
			fflag = 1;
			add_compunit(CU_FILE, optarg);
			break;
		case 'i':
			inplace = optarg;
			break;
		case 'l':
			if(setlinebuf(stdout) != 0)
                fprintf(stderr, "sed: setlinebuf() failed\n"); // warnx("setlinebuf() failed");
			break;
		case 'n':
			sed_nflag = 1;
			break;
		default:
		case '?':
			usage();
		}
	argc -= optind;
	argv += optind;

	/* First usage case; script is the first arg */
	if (!eflag && !fflag && *argv) {
		add_compunit(CU_STRING, *argv);
		argv++;
	}

	compile();

	/* Continue with first and start second usage */
	if (*argv)
		for (; *argv; argv++)
			add_file(*argv);
	else
		add_file(NULL);
	process();
	cfclose(prog, NULL);
	// if (fclose(stdout))
	//	err(1, "stdout");
	// exit(rval);
    if ((infile != NULL) && (infile != stdin)) fclose(infile);
    if ((outfile != NULL) && (outfile != stdout)) fclose(outfile);
    return 0;
}
static bool load_cached_shader_binary(opengl::ShaderProgram* program, const SCP_string& hash) {
	if (!do_shader_caching()) {
		return false;
	}

	auto base_filename = SCP_string("ogl_shader-") + hash;

	auto metadata = base_filename + ".json";
	auto binary = base_filename + ".bin";

	auto metadata_fp = cfopen(metadata.c_str(), "rb", CFILE_NORMAL, CF_TYPE_CACHE, false,
	                          CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT);
	if (!metadata_fp) {
		nprintf(("ShaderCache", "Metadata file does not exist.\n"));
		return false;
	}

	auto size = cfilelength(metadata_fp);
	SCP_string metadata_content;
	metadata_content.resize((size_t) size);
	cfread(&metadata_content[0], 1, size, metadata_fp);

	cfclose(metadata_fp);

	auto metadata_root = json_loads(metadata_content.c_str(), 0, nullptr);
	if (!metadata_root) {
		mprintf(("Loading of cache metadata failed! Falling back to GLSL shader...\n"));
		return false;
	}

	json_int_t format;
	if (json_unpack(metadata_root, "{sI}", "format", &format) != 0) {
		mprintf(("Failed to unpack values from metadata JSON! Falling back to GLSL shader...\n"));
		return false;
	}
	auto binary_format = (GLenum) format;
	json_decref(metadata_root);

	bool supported = false;
	for (auto supported_fmt : GL_binary_formats) {
		if ((GLenum)supported_fmt == binary_format) {
			supported = true;
			break;
		}
	}

	if (!supported) {
		// This can happen in case an implementation stops supporting a particular binary format
		nprintf(("ShaderCache", "Unsupported binary format %d encountered in shader cache.\n", binary_format));
		return false;
	}

	auto binary_fp = cfopen(binary.c_str(), "rb", CFILE_NORMAL, CF_TYPE_CACHE, false,
	                        CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT);
	if (!binary_fp) {
		nprintf(("ShaderCache", "Binary file does not exist.\n"));
		return false;
	}
	
	GR_DEBUG_SCOPE("Loading cached shader");
	
	SCP_vector<uint8_t> buffer;
	int length = cfilelength(binary_fp);
	buffer.resize((size_t) length);
	cfread(&buffer[0], 1, length, binary_fp);

	cfclose(binary_fp);

	// Load the data!
	glProgramBinary(program->getShaderHandle(), binary_format, buffer.data(), (GLsizei) buffer.size());

	// Check the status...
	GLint status;
	glGetProgramiv(program->getShaderHandle(), GL_LINK_STATUS, &status);

	return status == GL_TRUE;
}
bool pilotfile_convert::plr_convert(const char *fname, bool inferno)
{
	Assert( fname != NULL );

	SCP_string filename;
	bool rval = true;


	if (plr == NULL) {
		plr = new(std::nothrow) plr_data;
	}

	if (plr == NULL) {
		return false;
	}

	filename.reserve(200);

	cf_create_default_path_string(filename, CF_TYPE_SINGLE_PLAYERS, (inferno) ? const_cast<char*>("inferno") : NULL);

	if (inferno) {
		filename.append(DIR_SEPARATOR_STR);
	}

	filename.append(fname);
	filename.append(".pl2");

	mprintf(("  PL2 => Converting '%s'...\n", filename.c_str()));

	cfp = cfopen(const_cast<char*>(filename.c_str()), "rb", CFILE_NORMAL);

	if ( !cfp ) {
		mprintf(("  PL2 => Unable to open for import!\n", fname));
		return false;
	}

	try {
		plr_import();
	} catch (const char *err) {
		mprintf((  "  PL2 => Import ERROR: %s\n", err));
		rval = false;
	}

	cfclose(cfp);
	cfp = NULL;

	if ( !rval ) {
		return false;
	}

	filename.assign(fname);
	filename.append(".plr");

	cfp = cfopen(const_cast<char*>(filename.c_str()), "wb", CFILE_NORMAL, CF_TYPE_PLAYERS);

	if ( !cfp ) {
		mprintf(("  PLR => Unable to open for export!\n", fname));
		return false;
	}

	try {
		plr_export();
	} catch (const char *err) {
		mprintf(("  PLR => Export ERROR: %s\n", err));
		rval = false;
	}

	cfclose(cfp);
	cfp = NULL;

	if (rval) {
		mprintf(("  PLR => Conversion complete!\n"));
	}

	return rval;
}
int pcx_read_bitmap_32(char *real_filename, ubyte *org_data )
{
	PCXHeader header;
	CFILE * PCXfile;
	ubyte data=0;
	int row, col, count;
	int buffer_pos;
	char filename[MAX_FILENAME_LEN];
	ubyte palette[768];	
	
	strcpy( filename, real_filename );
	char *p = strchr( filename, '.' );
	if ( p ) *p = 0;
	strcat( filename, ".pcx" );

	
	PCXfile = cfopen( filename , "rb" );
	if ( !PCXfile ){
	
		return PCX_ERROR_OPENING;
	}

	// read 128 char PCX header
	if (cfread( &header, sizeof(PCXHeader), 1, PCXfile )!=1)	{
		cfclose( PCXfile );
	
		return PCX_ERROR_OPENING;
	}

	// Is it a 256 color PCX file?
	if ((header.Manufacturer != 10)||(header.Encoding != 1)||(header.Nplanes != 1)||(header.BitsPerPixel != 8)||(header.Version != 5))	{
		cfclose( PCXfile );
		return PCX_ERROR_OPENING;
	}

	// Find the size of the image
	int src_xsize = header.Xmax - header.Xmin + 1;
	int src_ysize = header.Ymax - header.Ymin + 1;

	// Read the extended palette at the end of PCX file
	// Read in a character which should be 12 to be extended palette file
	cfseek( PCXfile, -768, CF_SEEK_END );
	cfread( palette, 3, 256, PCXfile );
	cfseek( PCXfile, sizeof(PCXHeader), CF_SEEK_SET );
	
	int buffer_size = 1024;
	ubyte buffer[1024];
	buffer_pos = 0;
	
	buffer_size = cfread( buffer, 1, buffer_size, PCXfile );

	count = 0; 
	
	typedef struct {ubyte b,g,r,a;} COLOR32;

	for (row=0; row < src_ysize;row++)      {
	
		COLOR32 *pixdata = (COLOR32 *) org_data;

		for (col=0; col < header.BytesPerLine;col++)     {
			if ( count == 0 )	{
				data = buffer[buffer_pos++];
				if ( buffer_pos == buffer_size )	{
					buffer_size = cfread( buffer, 1, buffer_size, PCXfile );
					Assert( buffer_size > 0 );
					buffer_pos = 0;
				}
				if ((data & 0xC0) == 0xC0)     {
					count = data & 0x3F;
					data = buffer[buffer_pos++];
					if ( buffer_pos == buffer_size )	{
						buffer_size = cfread( buffer, 1, buffer_size, PCXfile );
						Assert( buffer_size > 0 );
						buffer_pos = 0;
					}
				} else {
					count = 1;
				}
			}
			// stuff the pixel
			if ( col < src_xsize ){	  
				
				if((0 == (int)palette[data*3]) && (255 == (int)palette[data*3+1]) && (0 == (int)palette[data*3+2])){
					pixdata->r = pixdata->b = pixdata->g = pixdata->a = 0;					
				} else {

					// stuff the 24 bit value				
					pixdata->r = palette[data*3];
					pixdata->g = palette[data*3 + 1];
					pixdata->b = palette[data*3 + 2];
	
					pixdata->a = 255;
				}

				pixdata++;
			}
			count--;
		}

		org_data += (src_xsize * 4);
	}
	
	cfclose(PCXfile);

	return PCX_ERROR_NONE;
}
Beispiel #18
0
hmp_file *hmp_open(const char *filename) {
    int i;
    char buf[256];
    int32_t	data;
    CFILE *fp;
    hmp_file *hmp;
    int num_tracks;
    unsigned char *p;

    if (!(fp = cfopen((char *)filename, "rb")))
        return NULL;

    hmp = malloc(sizeof(hmp_file));
    if (!hmp) {
        cfclose(fp);
        return NULL;
    }

    memset(hmp, 0, sizeof(*hmp));

    if ((cfread(buf, 1, 8, fp) != 8) || (memcmp(buf, "HMIMIDIP", 8)))
        goto err;

    if (cfseek(fp, 0x30, SEEK_SET))
        goto err;

    if (cfread(&num_tracks, 4, 1, fp) != 1)
        goto err;

    if ((num_tracks < 1) || (num_tracks > HMP_TRACKS))
        goto err;

    hmp->num_trks = num_tracks;
    hmp->tempo = 120;

    if (cfseek(fp, 0x308, SEEK_SET))
        goto err;

    for (i = 0; i < num_tracks; i++) {
        if ((cfseek(fp, 4, SEEK_CUR)) || (cfread(&data, 4, 1, fp) != 1))
            goto err;

        data -= 12;

#if 0
        if (i == 0)  /* track 0: reserve length for tempo */
			data += sizeof(hmp_tempo);
#endif

        hmp->trks[i].len = data;

        if (!(p = hmp->trks[i].data = malloc(data)))
            goto err;

#if 0
        if (i == 0) { /* track 0: add tempo */
			memcpy(p, hmp_tempo, sizeof(hmp_tempo));
			p += sizeof(hmp_tempo);
			data -= sizeof(hmp_tempo);
		}
#endif
        /* finally, read track data */
        if ((cfseek(fp, 4, SEEK_CUR)) || (cfread(p, data, 1, fp) != 1))
            goto err;
    }
    cfclose(fp);
    return hmp;

    err:
    cfclose(fp);
    hmp_close(hmp);
    return NULL;
}
Beispiel #19
0
int
main(int argc, char *argv[])
{
	int c, fflag;
	char *temp_arg;

	(void) setlocale(LC_ALL, "");

	fflag = 0;
	inplace = NULL;

	while ((c = getopt(argc, argv, "EI:ae:f:i:lnru")) != -1)
		switch (c) {
		case 'r':		/* Gnu sed compat */
		case 'E':
			rflags = REG_EXTENDED;
			break;
		case 'I':
			inplace = optarg;
			ispan = 1;	/* span across input files */
			break;
		case 'a':
			aflag = 1;
			break;
		case 'e':
			eflag = 1;
			if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
				err(1, "malloc");
			strcpy(temp_arg, optarg);
			strcat(temp_arg, "\n");
			add_compunit(CU_STRING, temp_arg);
			break;
		case 'f':
			fflag = 1;
			add_compunit(CU_FILE, optarg);
			break;
		case 'i':
			inplace = optarg;
			ispan = 0;	/* don't span across input files */
			break;
		case 'l':
			if(setvbuf(stdout, NULL, _IOLBF, 0) != 0)
				warnx("setting line buffered output failed");
			break;
		case 'n':
			nflag = 1;
			break;
		case 'u':
			if(setvbuf(stdout, NULL, _IONBF, 0) != 0)
				warnx("setting unbuffered output failed");
			break;
		default:
		case '?':
			usage();
		}
	argc -= optind;
	argv += optind;

	/* First usage case; script is the first arg */
	if (!eflag && !fflag && *argv) {
		add_compunit(CU_STRING, *argv);
		argv++;
	}

	compile();

	/* Continue with first and start second usage */
	if (*argv)
		for (; *argv; argv++)
			add_file(*argv);
	else
		add_file(NULL);
	process();
	cfclose(prog, NULL);
	if (fclose(stdout))
		err(1, "stdout");
	exit(rval);
}
pilot::JSONFileHandler::~JSONFileHandler() {
	json_decref(_rootObj);

	cfclose(_cfp);
	_cfp = nullptr;
}
Beispiel #21
0
//called for each level to load & setup the exit sequence
load_endlevel_data(int level_num)
{
	char filename[13];
	char line[LINE_LEN],*p;
	CFILE *ifile;
	int var,segnum,sidenum;
	int exit_side, i;
	int have_binary = 0;

	endlevel_data_loaded = 0;		//not loaded yet

try_again:
	;

	if (level_num<0)		//secret level
		strcpy(filename,Secret_level_names[-level_num-1]);
	else					//normal level
		strcpy(filename,Level_names[level_num-1]);

	if (!convert_ext(filename,"END"))
		return;

	ifile = cfopen(filename,"rb");

	if (!ifile) {

		convert_ext(filename,"TXB");

		ifile = cfopen(filename,"rb");

		if (!ifile)
			if (level_num==1) {
				return;		//abort
				//Error("Cannot load file text of binary version of <%s>",filename);
			}
			else {
				level_num = 1;
				goto try_again;
			}

		have_binary = 1;
	}

	//ok...this parser is pretty simple.  It ignores comments, but
	//everything else must be in the right place

	var = 0;

	while (cfgets(line,LINE_LEN,ifile)) {

		if (have_binary) {
			for (i = 0; i < strlen(line) - 1; i++) {
				encode_rotate_left(&(line[i]));
				line[i] = line[i] ^ BITMAP_TBL_XOR;
				encode_rotate_left(&(line[i]));
			}
			p = line;
		}

		if ((p=strchr(line,';'))!=NULL)
			*p = 0;		//cut off comment

		for (p=line+strlen(line)-1;p>line && isspace(*p);*p--=0);
		for (p=line;isspace(*p);p++);

		if (!*p)		//empty line
			continue;

		switch (var) {

			case 0: {						//ground terrain
				int iff_error;
				ubyte pal[768];

				if (terrain_bm_instance.bm_data)
					free(terrain_bm_instance.bm_data);

				iff_error = iff_read_bitmap(p,&terrain_bm_instance,BM_LINEAR,pal);
				if (iff_error != IFF_NO_ERROR) {
					mprintf((1, "File %s - IFF error: %s",p,iff_errormsg(iff_error)));
					Error("File %s - IFF error: %s",p,iff_errormsg(iff_error));
				}

				terrain_bitmap = &terrain_bm_instance;
				gr_remap_bitmap_good( terrain_bitmap, pal, iff_transparent_color, -1);

				break;
			}

			case 1:							//height map

				load_terrain(p);
				break;


			case 2:

				sscanf(p,"%d,%d",&exit_point_bmx,&exit_point_bmy);
				break;

			case 3:							//exit heading

				exit_angles.h = i2f(atoi(p))/360;
				break;

			case 4: {						//planet bitmap
				int iff_error;
				ubyte pal[768];

				if (satellite_bm_instance.bm_data)
					free(satellite_bm_instance.bm_data);

				iff_error = iff_read_bitmap(p,&satellite_bm_instance,BM_LINEAR,pal);
				if (iff_error != IFF_NO_ERROR) {
					mprintf((1, "File %s - IFF error: %s",p,iff_errormsg(iff_error)));
					Error("File %s - IFF error: %s",p,iff_errormsg(iff_error));
				}

				satellite_bitmap = &satellite_bm_instance;
				gr_remap_bitmap_good( satellite_bitmap, pal, iff_transparent_color, -1);

				break;
			}

			case 5:							//earth pos
			case 7: {						//station pos
				vms_matrix tm;
				vms_angvec ta;
				int pitch,head;

				sscanf(p,"%d,%d",&head,&pitch);

				ta.h = i2f(head)/360;
				ta.p = -i2f(pitch)/360;
				ta.b = 0;

				vm_angles_2_matrix(&tm,&ta);

				if (var==5)
					satellite_pos = tm.fvec;
					//vm_vec_copy_scale(&satellite_pos,&tm.fvec,SATELLITE_DIST);
				else
					station_pos = tm.fvec;

				break;
			}

			case 6:						//planet size
				satellite_size = i2f(atoi(p));
				break;
		}

		var++;

	}

	Assert(var == NUM_VARS);


	// OK, now the data is loaded.  Initialize everything

	//find the exit sequence by searching all segments for a side with
	//children == -2

	for (segnum=0,exit_segnum=-1;exit_segnum==-1 && segnum<=Highest_segment_index;segnum++)
		for (sidenum=0;sidenum<6;sidenum++)
			if (Segments[segnum].children[sidenum] == -2) {
				exit_segnum = segnum;
				exit_side = sidenum;
				break;
			}

	Assert(exit_segnum!=-1);

	compute_segment_center(&mine_exit_point,&Segments[exit_segnum]);
	extract_orient_from_segment(&mine_exit_orient,&Segments[exit_segnum]);
	compute_center_point_on_side(&mine_side_exit_point,&Segments[exit_segnum],exit_side);

	vm_vec_scale_add(&mine_ground_exit_point,&mine_exit_point,&mine_exit_orient.uvec,-i2f(20));

	//compute orientation of surface
	{
		vms_vector tv;
		vms_matrix exit_orient,tm;

		vm_angles_2_matrix(&exit_orient,&exit_angles);
		vm_transpose_matrix(&exit_orient);
		vm_matrix_x_matrix(&surface_orient,&mine_exit_orient,&exit_orient);

		vm_copy_transpose_matrix(&tm,&surface_orient);
		vm_vec_rotate(&tv,&station_pos,&tm);
		vm_vec_scale_add(&station_pos,&mine_exit_point,&tv,STATION_DIST);

vm_vec_rotate(&tv,&satellite_pos,&tm);
vm_vec_scale_add(&satellite_pos,&mine_exit_point,&tv,SATELLITE_DIST);

vm_vector_2_matrix(&tm,&tv,&surface_orient.uvec,NULL);
vm_vec_copy_scale(&satellite_upvec,&tm.uvec,SATELLITE_HEIGHT);


	}

	cfclose(ifile);

	endlevel_data_loaded = 1;

}
Beispiel #22
0
int do_ipc(int qid, struct msgbuf *buf, int flags)
{
	int ipc_read;
	CFILE *fptr=NULL;
	float last_volume = volume;
	int l=0;
	
	ipc_read = msgrcv(qid,buf,16,0,flags | MSG_NOERROR);
	
	switch (ipc_read)
	{
	 case -1:
		if (errno == ENOMSG)
		  break;
		perror("IPC trouble");
		break;
	 case 0:
		break;
	 default:
		printf ("do_ipc %s\n", buf->mtext);//##########3
		switch (buf->mtext[0])
		{
		 case 'v':
			volume=(double) (atof(buf->mtext+1)/128.0);
			printf("vol %f->%f\n",last_volume,volume);
			if (last_volume<=0 && volume>0) {
				buf->mtext[0]='p';//start playing again if volume raised above 0
				strcpy(buf->mtext+1, digi_last_midi_song);
				//fall through to case 'p'
			}else if (last_volume>0 && volume<=0) {
				strcpy(buf->mtext, "s"); //stop playing if volume reduced to 0
				stop = 2;
				break;
			}else
				break;
		 case 'p':
			if (buf->mtext[1]) {
				strcpy(digi_last_midi_song, buf->mtext+1);
				if (volume>0)
					fptr=cfopen((buf->mtext+1),"rb");
			}
			if(fptr != NULL)
			{
				l = cfilelength(fptr);
				data=realloc(data,(size_t) l);
				cfread(data, l, 1, fptr);
				cfclose(fptr);
				printf ("good. fpr=%p l=%i data=%p\n", fptr, l, data);//##########3
				stop = 0;
			} else {
				strcpy(buf->mtext, "s"); //not playing, thus "stop".
				stop = 2;
			}
			break;
		 case 's':
			stop = 2;
			break;
		 case 'q':
//			SDL_KillThread(player_thread);
			break;  
		}
//		printf ("do_ipc %s ret %i\n", buf->mtext, ipc_read);//##########3
	}
	
	return ipc_read;
}
Beispiel #23
0
Datei: menubar.c Projekt: btb/d2x
void menubar_init( char * file )
{
	int i,j, np;
	int aw, w, h;
	CFILE * infile;
	char buffer[200];
	char buf1[200];
	char buf2[200];
	int menu, item;
		
	num_menus = state = 0;

	for (i=0; i < MAXMENUS; i++ )
	{
		Menu[i].x = Menu[i].y = Menu[i].w = Menu[i].h = 0;
		Menu[i].ShowBar = 0;
		Menu[i].CurrentItem = 0;
		Menu[i].NumItems = 0;
		Menu[i].Displayed = 0;
		Menu[i].Background = 0;
		for (j=0; j< MAXITEMS; j++ )
		{
			Menu[i].Item[j].x = Menu[i].Item[j].y = Menu[i].Item[j].w = Menu[i].Item[j].h = 0;
			Menu[i].Item[j].Text = NULL;
			Menu[i].Item[j].Hotkey = -1;
			Menu[i].Item[j].user_function = NULL;
		}
	}
		
	infile = cfopen( file, "rt" );

	if (!infile) return;
		
	while ( cfgets( buffer, 200, infile) != NULL )
	{
		if ( buffer[0] == ';' ) continue;
		
		//mprintf( 0, "%s\n", buffer );
				
		CommaParse( 0, buf1, buffer );
		menu = atoi( buf1 );
		if (menu >= MAXMENUS)
			Error("Too many menus (%d).",menu);

		CommaParse( 1, buf1, buffer );
		item = atoi(buf1 );
		if (item >= MAXITEMS)
			Error("Too many items (%d) in menu %d.",item+1,menu);

		CommaParse( 2, buf1, buffer );
		ul_xlate(buf1);

		if (buf1[0] != '-' )
		{
			sprintf( buf2, " %s ", buf1 );
			Menu[menu].Item[item].Text = d_strdup(buf2);
		} else 
			Menu[menu].Item[item].Text = d_strdup(buf1);
		
		Menu[menu].Item[item].InactiveText = d_strdup(Menu[menu].Item[item].Text);
		
		j= 0;
		for (i=0; i<=strlen(Menu[menu].Item[item].Text); i++ )
		{
			np = Menu[menu].Item[item].Text[i];
			if (np != CC_UNDERLINE) 
				Menu[menu].Item[item].InactiveText[j++] = np;
		}

		CommaParse( 3, buf1, buffer );
		if (buf1[0]=='{' && buf1[1] =='}')
			Menu[menu].Item[item].Hotkey = -1;
		else			{
			i = DecodeKeyText(buf1);
			if (i<1) {
				Error("Unknown key, %s, in %s\n", buf1, file );
			} else {
				Menu[menu].Item[item].Hotkey = i;
			}
		}
		CommaParse( 4, buf1, buffer );

		if (strlen(buf1))
		{
			Menu[menu].Item[item].user_function = func_get(buf1, &np);

//			if (!strcmp(buf1,"do-wall-dialog")) {
//				mprintf( 0, "Found function %s\n", buf1);
//				mprintf( 0, "User function %s\n", Menu[menu].Item[item].user_function);
//			}
				
			if (Menu[menu].Item[item].user_function==NULL)
			{
				Error( "Unknown function, %s, in %s\n", buf1, file );
				//ui_messagebox( -2, -2, 1, buffer, "Ok" );
			}
		}
				
		Menu[menu].Item[item].x = Menu[menu].x;
		Menu[menu].Item[item].y = Menu[menu].y;

		if ( Menu[menu].Item[item].Text[0] == '-' )
		{
			w = 1; h = 3;
		} else {
			gr_get_string_size( Menu[menu].Item[item].Text, &w, &h, &aw );
			w += 2;
			h += 2;
		}
								
		if (menu==0)	{
			Menu[0].h = h;

			Menu[0].Item[item].x = Menu[0].x + Menu[0].w;

			Menu[0].Item[item].y = Menu[0].y;
			
			Menu[item+1].x = Menu[0].x + Menu[0].w;
			Menu[item+1].y = Menu[0].h - 2;

			Menu[0].Item[item].w = w;
			Menu[0].Item[item].h = h;

			Menu[0].w += w;

		}else	{
			if ( w > Menu[menu].w )
			{
				Menu[menu].w = w;
				for (i=0; i< Menu[menu].NumItems; i++ )
					Menu[menu].Item[i].w = Menu[menu].w;
			}
			Menu[menu].Item[item].w = Menu[menu].w;
			Menu[menu].Item[item].x = Menu[menu].x;
			Menu[menu].Item[item].y = Menu[menu].y+Menu[menu].h;
			Menu[menu].Item[item].h = h;
			Menu[menu].h += h;
		}
	
		if ( item >= Menu[menu].NumItems )
		{
			Menu[menu].NumItems = item+1;
		}

		if ( menu >= num_menus )
			num_menus = menu+1;

	}

	Menu[0].w = 700;
			
	cfclose( infile );

	
	for (i=0; i<num_menus; i++ )
		Menu[i].Background = gr_create_bitmap(Menu[i].w, Menu[i].h );

	menubar_hid = 1;
}
Beispiel #24
0
void read_menu_tbl(char* menu_name, char* bkg_filename, char* mask_filename, MENU_REGION* regions, int* num_regions, int play_sound)
{
	CFILE* fp;
	int state=0;
	char* p1, *p2, *p3;
	//char music_filename[128];

	char seps[]   = NOX(" ,\t");
	char *token;
	char tmp_line[132];

	*num_regions=0;

	// open localization
	lcl_ext_open();

	fp = cfopen( NOX("menu.tbl"), "rt" );
	if (fp == NULL) {
		Error(LOCATION, "menu.tbl could not be opened\n");

		// close localization
		lcl_ext_close();

		return;
	}


	while (cfgets(tmp_line, 132, fp)) {
		p1 = strchr(tmp_line,'\n'); if (p1) *p1 = '\0';
		p1 = strchr(tmp_line,';'); if (p1) *p1 = '\0';
		p1 = p3 = strchr( tmp_line, '[' );

		if (p3 && state == 1) {	
			// close localization
			lcl_ext_close();

			cfclose(fp);
			return;
		}
		
		if ( p1 || p3)	{
			if (!state)	{
				p2 = strchr( tmp_line, ']' );
				if (p2) *p2 = 0;
				if (!stricmp( ++p1, menu_name )) state = 1;
			} else {
				cfclose(fp);
				break;
			}
		} else if (state) {
			
		
			// parse a region line
			p1 = strchr( tmp_line, '\"' );
			if (p1) {
				p2 = strchr( tmp_line+1, '\"' );
				if (!p2) {
					nprintf(("Warning","Error parsing menu file\n"));

					// close localization
					lcl_ext_close();

					return;
				}
				*p2 = 0;
				strcpy(regions[*num_regions].text,++p1);
				p2++;

				// get the tokens mask number
				token = strtok( p2, seps );
				regions[*num_regions].mask = atoi(token);
				
				// get the hot key character
				token = strtok( NULL, seps );
				regions[*num_regions].key = token[0];

				// stuff default click sound (not in menu.tbl)
				if ( play_sound ) {
					regions[*num_regions].click_sound = SND_IFACE_MOUSE_CLICK;
				} else {
					regions[*num_regions].click_sound = -1;
				}

				*num_regions = *num_regions + 1;

			}
				else {
				// get the menu filenames

				// Establish string and get the first token
				token = strtok( tmp_line, seps );
				if ( token != NULL )
				{
					// store the background filename
					strcpy(bkg_filename, token);

					// get the mask filename
					token = strtok( NULL, seps );
					strcpy(mask_filename, token);
				}
			}
		}
	}	
	cfclose(fp);
	
	// close localization
	lcl_ext_close();
}
Beispiel #25
0
//load all the text strings for Descent
void load_text()
{
	CFILE  *tfile;
	CFILE *ifile;
	int len,i, have_binary = 0;
	char *tptr;
	char *filename="descent.tex";

	if ((i=FindArg("-text"))!=0)
		filename = Args[i+1];

	if ((tfile = cfopen(filename,"rb")) == NULL) {
		filename="descent.txb";
		if ((ifile = cfopen(filename, "rb")) == NULL)
			Error("Cannot open file DESCENT.TEX or DESCENT.TXB");
		have_binary = 1;

		len = cfilelength(ifile);

		//MALLOC(text,char,len);//Won't compile... working on it..-KRB
		text=malloc(len*sizeof(char));//my hack -KRB
		atexit(free_text);

		cfread(text,1,len,ifile);

		cfclose(ifile);

	} else {
		int c;
		char * p;

		len = cfilelength(tfile);

		//MALLOC(text,char,len);//Won't compile... working on it..-KRB
		text=malloc(len*sizeof(char));//my hack -KRB

		atexit(free_text);

		//fread(text,1,len,tfile);
		p = text;
		do {
			c = cfgetc( tfile );
			if ( c != 13 )
				*p++ = c;
		} while ( c!=EOF );

		cfclose(tfile);
	}

	for (i=0,tptr=text;i<N_TEXT_STRINGS;i++) {
		char *p;

		Text_string[i] = tptr;

		tptr = strchr(tptr,'\n');

		if (!tptr)
			Error("Not enough strings in text file - expecting %d, found %d",N_TEXT_STRINGS,i);

		if ( tptr ) *tptr++ = 0;

		if (have_binary) {
			for (p=Text_string[i]; p < tptr - 1; p++) {
				encode_rotate_left(p);
				*p = *p ^ BITMAP_TBL_XOR;
				encode_rotate_left(p);
			}
		}

		//scan for special chars (like \n)
		for (p=Text_string[i];p=strchr(p,'\\');) {
			char newchar;

			if (p[1] == 'n') newchar = '\n';
			else if (p[1] == 't') newchar = '\t';
			else if (p[1] == '\\') newchar = '\\';
			else
				Error("Unsupported key sequence <\\%c> on line %d of file <%s>",p[1],i+1,filename); 

			p[0] = newchar;
			sprintf(p+1, "%s", p+2);
			p++;
		}

	}

//	Assert(tptr==text+len || tptr==text+len-2);
	
}
Beispiel #26
0
int generic_anim_stream(generic_anim *ga, const bool cache)
{
	CFILE *img_cfp = NULL;
	int anim_fps = 0;
	char full_path[MAX_PATH];
	int size = 0, offset = 0;
	const int NUM_TYPES = 3;
	const ubyte type_list[NUM_TYPES] = {BM_TYPE_EFF, BM_TYPE_ANI, BM_TYPE_PNG};
	const char *ext_list[NUM_TYPES] = {".eff", ".ani", ".png"};
	int rval = -1;
	int bpp;

	ga->type = BM_TYPE_NONE;

	rval = cf_find_file_location_ext(ga->filename, NUM_TYPES, ext_list, CF_TYPE_ANY, sizeof(full_path) - 1, full_path, &size, &offset, 0);

	// could not be found, or is invalid for some reason
	if ( (rval < 0) || (rval >= NUM_TYPES) )
		return -1;

	//make sure we can open it
	img_cfp = cfopen_special(full_path, "rb", size, offset, CF_TYPE_ANY);

	if (img_cfp == NULL) {
		return -1;
	}

	strcat_s(ga->filename, ext_list[rval]);
	ga->type = type_list[rval];
	//seek to the end
	cfseek(img_cfp, 0, CF_SEEK_END);

	cfclose(img_cfp);

	if(ga->type == BM_TYPE_ANI) {
		bpp = ANI_BPP_CHECK;
		if(ga->use_hud_color)
			bpp = 8;
		if (ga->ani.animation == nullptr) {
			ga->ani.animation = anim_load(ga->filename, CF_TYPE_ANY, 0);
		}
		if (ga->ani.instance == nullptr) {
			ga->ani.instance = init_anim_instance(ga->ani.animation, bpp);
		}

	#ifndef NDEBUG
		// for debug of ANI sizes
		strcpy_s(ga->ani.animation->name, ga->filename);
	#endif

		ga->num_frames = ga->ani.animation->total_frames;
		anim_fps = ga->ani.animation->fps;
		ga->height = ga->ani.animation->height;
		ga->width = ga->ani.animation->width;
		ga->buffer = ga->ani.instance->frame;
		ga->bitmap_id = bm_create(bpp, ga->width, ga->height, ga->buffer, (bpp==8)?BMP_AABITMAP:0);
		ga->ani.instance->last_bitmap = -1;

		ga->ani.instance->file_offset = ga->ani.animation->file_offset;
		ga->ani.instance->data = ga->ani.animation->data;

		ga->previous_frame = -1;
	}
	else if (ga->type == BM_TYPE_PNG) {
		if (ga->png.anim == nullptr) {
			try {
				ga->png.anim = new apng::apng_ani(ga->filename, cache);
			}
			catch (const apng::ApngException& e) {
				mprintf(("Failed to load apng: %s\n", e.what() ));
				delete ga->png.anim;
				ga->png.anim = nullptr;
				return -1;
			}
			nprintf(("apng", "apng read OK (%ix%i@%i) duration (%f)\n", ga->png.anim->w, ga->png.anim->h,
					ga->png.anim->bpp, ga->png.anim->anim_time));
		}
		ga->png.anim->goto_start();
		ga->current_frame = 0;
		ga->png.previous_frame_time = 0.0f;
		ga->num_frames = ga->png.anim->nframes;
		ga->height = ga->png.anim->h;
		ga->width = ga->png.anim->w;
		ga->previous_frame = -1;
		ga->buffer = ga->png.anim->frame.data.data();
		ga->bitmap_id = bm_create(ga->png.anim->bpp, ga->width, ga->height, ga->buffer, 0);
	}
	else {
		bpp = 32;
		if(ga->use_hud_color)
			bpp = 8;
		bm_load_and_parse_eff(ga->filename, CF_TYPE_ANY, &ga->num_frames, &anim_fps, &ga->keyframe, 0);
		char *p = strrchr( ga->filename, '.' );
		if ( p )
			*p = 0;
		char frame_name[MAX_FILENAME_LEN];
		snprintf(frame_name, MAX_FILENAME_LEN, "%s_0000", ga->filename);
		ga->bitmap_id = bm_load(frame_name);
		if(ga->bitmap_id < 0) {
			mprintf(("Cannot find first frame for eff streaming. eff Filename: %s", ga->filename));
			return -1;
		}
		snprintf(frame_name, MAX_FILENAME_LEN, "%s_0001", ga->filename);
		ga->eff.next_frame = bm_load(frame_name);
		bm_get_info(ga->bitmap_id, &ga->width, &ga->height);
		ga->previous_frame = 0;
	}

	// keyframe info
	if (ga->type == BM_TYPE_ANI) {
		//we only care if there are 2 keyframes - first frame, other frame to jump to for ship/weapons
		//mainhall door anis hav every frame as keyframe, so we don't care
		//other anis only have the first frame
		if(ga->ani.animation->num_keys == 2) {
			int key1 = ga->ani.animation->keys[0].frame_num;
			int key2 = ga->ani.animation->keys[1].frame_num;

			if (key1 < 0 || key1 >= ga->num_frames) key1 = -1;
			if (key2 < 0 || key2 >= ga->num_frames) key2 = -1;

			// some retail anis have their keyframes reversed
			// and some have their keyframes out of bounds
			if (key1 >= 0 && key1 >= key2) {
				ga->keyframe = ga->ani.animation->keys[0].frame_num;
				ga->keyoffset = ga->ani.animation->keys[0].offset;
			}
			else if (key2 >= 0 && key2 >= key1) {
				ga->keyframe = ga->ani.animation->keys[1].frame_num;
				ga->keyoffset = ga->ani.animation->keys[1].offset;
			}
		}
	}

	ga->streaming = 1;

	if (ga->type == BM_TYPE_PNG) {
		ga->total_time = ga->png.anim->anim_time;
	}
	else {
		if (anim_fps == 0) {
			Error(LOCATION, "animation (%s) has invalid fps of zero, fix this!", ga->filename);
		}
		ga->total_time = ga->num_frames / (float) anim_fps;
	}
	ga->done_playing = 0;
	ga->anim_time = 0.0f;

	return 0;
}
Beispiel #27
0
// #define GET_BUF()			do { buffer = &Pcx_load[Pcx_load_offset]; if(Pcx_load_offset + buffer_size > Pcx_load_size) { buffer_size = Pcx_load_size - Pcx_load_offset; } } while(0);
int pcx_read_bitmap_8bpp( char * real_filename, ubyte *org_data, ubyte *palette )
{
		PCXHeader header;
	CFILE * PCXfile;
	int row, col, count, xsize, ysize;
	ubyte data=0;
	int buffer_size, buffer_pos;
	ubyte buffer[1024];
	ubyte *pixdata;
	char filename[MAX_FILENAME_LEN];
		
	strcpy( filename, real_filename );
	char *p = strchr( filename, '.' );
	if ( p ) *p = 0;
	strcat( filename, ".pcx" );

	PCXfile = cfopen( filename , "rb" );
	if ( !PCXfile )
		return PCX_ERROR_OPENING;

	// read 128 char PCX header
	if (cfread( &header, sizeof(PCXHeader), 1, PCXfile )!=1)	{
		cfclose( PCXfile );
		return PCX_ERROR_NO_HEADER;
	}
        header.Xmin = INTEL_SHORT( header.Xmin );
        header.Ymin = INTEL_SHORT( header.Ymin );
        header.Xmax = INTEL_SHORT( header.Xmax );
        header.Ymax = INTEL_SHORT( header.Ymax );
        header.Hdpi = INTEL_SHORT( header.Hdpi );
        header.Vdpi = INTEL_SHORT( header.Vdpi );

        header.BytesPerLine = INTEL_SHORT( header.BytesPerLine );

	// Is it a 256 color PCX file?
	if ((header.Manufacturer != 10)||(header.Encoding != 1)||(header.Nplanes != 1)||(header.BitsPerPixel != 8)||(header.Version != 5))	{
		cfclose( PCXfile );
		return PCX_ERROR_WRONG_VERSION;
	}

	// Find the size of the image
	xsize = header.Xmax - header.Xmin + 1;
	ysize = header.Ymax - header.Ymin + 1;

	// Read the extended palette at the end of PCX file
	// Read in a character which should be 12 to be extended palette file

	cfseek( PCXfile, -768, CF_SEEK_END );
	cfread( palette, 3, 256, PCXfile );
        
        for ( int i=0; i<256; i++ ){				//tigital
            palette[i] = INTEL_INT( palette[i] );
        }
	cfseek( PCXfile, sizeof(PCXHeader), CF_SEEK_SET );
	
	buffer_size = 1024;
	buffer_pos = 0;
	
//	Assert( buffer_size == 1024 );	// AL: removed to avoid optimized warning 'unreachable code'
	buffer_size = cfread( buffer, 1, buffer_size, PCXfile );

	count = 0;

	for (row=0; row<ysize;row++)      {
		pixdata = org_data;
		for (col=0; col<header.BytesPerLine;col++)     {
			if ( count == 0 )	{
				data = buffer[buffer_pos++];
				if ( buffer_pos == buffer_size )	{
					buffer_size = cfread( buffer, 1, buffer_size, PCXfile );
					Assert( buffer_size > 0 );
					buffer_pos = 0;
				}
				if ((data & 0xC0) == 0xC0)     {
					count = data & 0x3F;
					data = buffer[buffer_pos++];
					if ( buffer_pos == buffer_size )	{
						buffer_size = cfread( buffer, 1, buffer_size, PCXfile );
						Assert( buffer_size > 0 );
						buffer_pos = 0;
					}
				} else {
					count = 1;
				}
			}
			if ( col < xsize )
				*pixdata++ = data;
			count--;
		}
		org_data += xsize;
	}
	cfclose(PCXfile);
	return PCX_ERROR_NONE;
}
/**
 * @brief Load an animation.  This stores the compressed data, which instances of the animation can reference.  
 * Must be free'ed later with anim_free().
 * 
 * @param real_filename Filename of animation
 * @param cf_dir_type 
 * @param file_mapped Whether to use memory-mapped file or not.
 * 
 * @details Memory-mapped files will page in the animation from disk as it is needed, but performance is not as good.
 * @return Pointer to anim that is loaded if sucess, NULL if failure.
 */
anim *anim_load(char *real_filename, int cf_dir_type, int file_mapped)
{
	anim			*ptr;
	CFILE			*fp;
	int			count,idx;
	char name[_MAX_PATH];

	Assert( real_filename != NULL );

	strcpy_s( name, real_filename );
	char *p = strchr( name, '.' );
	if ( p ) {
		*p = 0;
	}
	strcat_s( name, ".ani" );

	ptr = first_anim;
	while (ptr) {
		if (!stricmp(name, ptr->name))
			break;

		ptr = ptr->next;
	}

	if (!ptr) {
		fp = cfopen(name, "rb", CFILE_NORMAL, cf_dir_type);
		if ( !fp )
			return NULL;

		ptr = (anim *) vm_malloc(sizeof(anim));
		Assert(ptr);

		ptr->flags = 0;
		ptr->next = first_anim;
		first_anim = ptr;
		Assert(strlen(name) < _MAX_PATH - 1);
		strcpy_s(ptr->name, name);
		ptr->instance_count = 0;
		ptr->width = 0;
		ptr->height = 0;
		ptr->total_frames = 0;
		ptr->keys = NULL;
		ptr->ref_count=0;

		anim_read_header(ptr, fp);

		if(ptr->num_keys > 0){
			ptr->keys = (key_frame*)vm_malloc(sizeof(key_frame) * ptr->num_keys);
			Assert(ptr->keys != NULL);
		} 			

		// store how long the anim should take on playback (in seconds)
		ptr->time = i2fl(ptr->total_frames)/ptr->fps;

		for(idx=0;idx<ptr->num_keys;idx++){
			ptr->keys[idx].frame_num = 0;
			cfread(&ptr->keys[idx].frame_num, 2, 1, fp);
			cfread(&ptr->keys[idx].offset, 4, 1, fp);
			ptr->keys[idx].frame_num = INTEL_INT( ptr->keys[idx].frame_num ); //-V570
			ptr->keys[idx].offset = INTEL_INT( ptr->keys[idx].offset ); //-V570
		}

		cfread(&count, 4, 1, fp);	// size of compressed data
		count = INTEL_INT( count );

		ptr->cfile_ptr = NULL;

		if ( file_mapped == PAGE_FROM_MEM) {
			// Try mapping the file to memory 
			ptr->flags |= ANF_MEM_MAPPED;
			ptr->cfile_ptr = cfopen(name, "rb", CFILE_MEMORY_MAPPED, cf_dir_type);
		}

		// couldn't memory-map file... must be in a packfile, so stream manually
		if ( file_mapped && !ptr->cfile_ptr ) {
			ptr->flags &= ~ANF_MEM_MAPPED;
			ptr->flags |= ANF_STREAMED;
			ptr->cfile_ptr = cfopen(name, "rb", CFILE_NORMAL, cf_dir_type);
		}

		ptr->cache = NULL;

		// If it opened properly as mem-mapped (or streamed)
		if (ptr->cfile_ptr != NULL)	{
			// VERY IMPORTANT STEP
			// Set the data pointer to the compressed data (which is not at the start of the
			// file).  Use ftell() to find out how far we've already parsed into the file
			//
			int offset;
			offset = cftell(fp);
			ptr->file_offset = offset;
			if ( ptr->flags & ANF_STREAMED ) {
				ptr->data = NULL;
				ptr->cache_file_offset = ptr->file_offset;
				ptr->cache = (ubyte*)vm_malloc(ANI_STREAM_CACHE_SIZE+2);
				Assert(ptr->cache);
				cfseek(ptr->cfile_ptr, offset, CF_SEEK_SET);
				cfread(ptr->cache, ANI_STREAM_CACHE_SIZE, 1, ptr->cfile_ptr);
			} else {
				ptr->data = (ubyte*)cf_returndata(ptr->cfile_ptr) + offset;
			}
		} else {
			// Not a memory mapped file (or streamed)
			ptr->flags &= ~ANF_MEM_MAPPED;
			ptr->flags &= ~ANF_STREAMED;
			ptr->data = (ubyte *) vm_malloc(count);
			ptr->file_offset = -1;
			cfread(ptr->data, count, 1, fp);
		}

		cfclose(fp);

		// store screen signature, so we can tell if palette changes
		ptr->screen_sig = gr_screen.signature;

		anim_set_palette(ptr);
	}

	ptr->ref_count++;
	return ptr;
}
pilotfile::~pilotfile()
{
	if (cfp) {
		cfclose(cfp);
	}
}
/**
 * @brief Display information and statistics about a .ani file.
 * @details This is called when -i switch is on when running ac.exe
 */
void anim_display_info(char *real_filename)
{
	CFILE				*fp;
	anim				A;
	float				percent;
	int				i, uncompressed, compressed, *key_frame_nums=NULL, tmp;
	char filename[MAX_FILENAME_LEN];

	strcpy_s( filename, real_filename );
	char *p = strchr( filename, '.' );
	if ( p ) {
		*p = 0;
	}
	strcat_s( filename, ".ani" );

	fp = cfopen(filename, "rb");
	if ( !fp ) {
		printf("Fatal error opening %s", filename);
		return;
	}

	anim_read_header(&A, fp);
	// read the keyframe frame nums and offsets
	key_frame_nums = (int*)vm_malloc(sizeof(int)*A.num_keys);
	Assert(key_frame_nums != NULL);
	if (key_frame_nums == NULL)
		return;

	for ( i = 0; i < A.num_keys; i++ ) {
		key_frame_nums[i] = 0;
		cfread(&key_frame_nums[i], 2, 1, fp);
		cfread(&tmp, 4, 1, fp);
	}

	cfread(&compressed, 4, 1, fp);

	uncompressed = A.width * A.height * A.total_frames;	// 8 bits per pixel
	percent = i2fl(compressed) / uncompressed * 100.0f;

	printf("%% of uncompressed size:    %.0f%%\n", percent);
	printf("Width:                     %d\n", A.width);
	printf("Height:                    %d\n", A.height);
	printf("Total Frames:              %d\n", A.total_frames);

#ifndef NDEBUG
	printf("Key Frames:                %d\n", A.num_keys);
	if ( A.num_keys > 1 && (A.total_frames != A.num_keys) ) {
		printf("key list: (");
		for ( i = 0; i < A.num_keys; i++ ) {
			if ( i < A.num_keys-1 ) 
				printf("%d, ", key_frame_nums[i]);
			else
				printf("%d)\n", key_frame_nums[i]);
		}
	}
#endif

	printf("FPS:                       %d\n", A.fps);

#ifndef NDEBUG
	printf("Transparent RGB:           (%u,%u,%u)\n", A.xparent_r, A.xparent_g, A.xparent_b); 
#endif

	printf("ac version:                %d\n", A.version);

	if ( key_frame_nums != NULL ) {
		vm_free(key_frame_nums);
	}

	cfclose(fp);
}