// evaluate a certain function for all docked objects
void dock_evaluate_all_docked_objects(p_object *objp, p_dock_function_info *infop, void (*function)(p_object *, p_dock_function_info *))
{
	Assert((objp != NULL) && (infop != NULL) && (function != NULL));

	// not docked?
	if (!object_is_docked(objp))
	{
		// call the function for just the one object
		function(objp, infop);
		return;
	}

	// we only have two objects docked
	if (dock_check_docked_one_on_one(objp))
	{
		// call the function for the first object, and return if instructed
		function(objp, infop);
		if (infop->early_return_condition) return;

		// call the function for the second object, and return if instructed
		function(objp->dock_list->docked_objp, infop);
		if (infop->early_return_condition) return;
	}

	// NOTE - never treat a group of parse objects as a hub... it cuts down on bugs, and it's
	// not needed because it's not time-critical

	// we have multiple objects docked and we must treat them as a tree
	else
	{
		// create a bit array to mark the objects we check
		ubyte *visited_bitstring = (ubyte *) vm_malloc(calculate_num_bytes(Parse_objects.size()));

		// clear it
		memset(visited_bitstring, 0, calculate_num_bytes(Parse_objects.size()));

		// start evaluating the tree
		dock_evaluate_tree(objp, infop, function, visited_bitstring);

		// destroy the bit array
		vm_free(visited_bitstring);
		visited_bitstring = NULL;
	}
}
/**
 * @brief Write the frames of a .ani file out to disk as .pcx files.
 * @details Use naming convention: filename0000.pcx, filename0001.pcx etc.
 *
 * @return If success 0, or if failed -1
 */
int anim_write_frames_out(char *filename)
{
	anim				*source_anim;
	anim_instance	*ai;
	char				root_name[256], pcxname[256];
	char				buf[64];
	int				i,j;
	ubyte				**row_data;

	strcpy_s(root_name, filename);
	root_name[strlen(filename)-4] = 0;

	source_anim = anim_load(filename);
	if ( source_anim == NULL ) 
		return -1;

	ai = init_anim_instance(source_anim, 16);

	row_data = (ubyte**)vm_malloc((source_anim->height+1) * 4);

	for ( i = 0; i < source_anim->total_frames; i++ ) {
		anim_get_next_raw_buffer(ai, 0, 0, 16);
		strcpy_s(pcxname, root_name);
		sprintf(buf,"%04d",i);
		strcat_s(pcxname, buf);

		for ( j = 0; j < source_anim->height; j++ ) {
			row_data[j] = &ai->frame[j*source_anim->width];
		}


		pcx_write_bitmap( pcxname,
								source_anim->width,
								source_anim->height,
								row_data,
								source_anim->palette);

		printf(".");

	}
	printf("\n");
	vm_free(row_data);
	return 0;
}
Пример #3
0
void *_vm_realloc( void *ptr, int size, int quiet )
#endif
{
	// if this is the first time it's used then we need to malloc it first
	if (ptr == NULL)
		return vm_malloc(size);

	void* ret_ptr = NULL;

#ifndef NDEBUG
	// Unregistered the previous allocation
	_CrtMemBlockHeader* phd = pHdr(ptr);
	int nSize = phd->nDataSize;

	TotalRam -= nSize;
	if (Cmdline_show_mem_usage)
		unregister_malloc(filename, nSize, ptr);
#endif

	ret_ptr = _realloc_dbg(ptr, size, _NORMAL_BLOCK, __FILE__, __LINE__);

	if (ret_ptr == NULL)
	{
		mprintf(("realloc failed!!!!!!!!!!!!!!!!!!!\n"));

		if (quiet && (size > 0) && (ptr != NULL))
		{
			// realloc doesn't touch the original ptr in the case of failure so we could still use it
			return NULL;
		}

		Error(LOCATION, "Out of memory.  Try closing down other applications, increasing your\n"
			"virtual memory size, or installing more physical RAM.\n");
	}
#ifndef	NDEBUG
	TotalRam += size;

	// register this allocation
	if (Cmdline_show_mem_usage)
		register_malloc(size, filename, line, ret_ptr);
#endif
	return ret_ptr;
}
Пример #4
0
void opengl_array_state::init(GLuint n_units)
{
	Assert( n_units > 0 );
	client_texture_units = (opengl_client_texture_unit*) vm_malloc(n_units * sizeof(opengl_client_texture_unit));
	num_client_texture_units = n_units;
	active_client_texture_unit = 0;

	for (unsigned int i = 0; i < num_client_texture_units; i++) {
		client_texture_units[i].pointer = 0;
		client_texture_units[i].size = 4;
		client_texture_units[i].status = GL_FALSE;
		client_texture_units[i].stride = 0;
		client_texture_units[i].type = GL_FLOAT;
		client_texture_units[i].buffer = 0;
		client_texture_units[i].reset = false;
	}

	color_array_Buffer = 0;
	color_array_Status = GL_FALSE;
	color_array_size = 4;
	color_array_type = GL_FLOAT;
	color_array_stride = 0;
	color_array_pointer = 0;
	color_array_reset = false;

	normal_array_Buffer = 0;
	normal_array_Status = GL_FALSE;
	normal_array_Type = GL_FLOAT;
	normal_array_Stride = 0;
	normal_array_Pointer = 0;
	normal_array_reset = false;

	vertex_array_Buffer = 0;
	vertex_array_Status = GL_FALSE;
	vertex_array_Size = 4;
	vertex_array_Type = GL_FLOAT;
	vertex_array_Stride = 0;
	vertex_array_Pointer = 0;
	vertex_array_reset = false;

	array_buffer = 0;
	element_array_buffer = 0;
}
Пример #5
0
void *realloc_mre(void *memory, size_t new_size){
	/*
	MSC:
	void* realloc(void *Memory, size_t NewSize);

	MRE:
	void *vm_realloc(void* p, int size);
	*/
	/* Update: This will fail if memory is 0x00000000. You'd except it to but in C, it realises 
	that it is nothing and allocates new memory. The difference between realloc and free then malloc
	is that realloc preserves the contents. If memory variable is none, then we don't care because
	there is no array or information in this. So I think we should force this implementation to 
	check and manually call malloc */

	if (memory == NULL){
		return vm_malloc((int)new_size);
	}
	vm_realloc(memory, (int)new_size);
}
void settings_load()
{
    unsigned long size = 0;
    file_size("settings.txt", &size);
    if (size < 24) {
        return;
    }

    char *ptr = vm_malloc(size);
    if (NULL == ptr) {
        return;
    }

    file_read("settings.txt", ptr, size, 0);

    cJSON *root = cJSON_Parse(ptr);
    if (NULL == root) {
        vm_free(ptr);
        return;
    }

    g_settings_brightness = cJSON_GetObjectItem(root, "brightness")->valueint;
    g_settings_sound = cJSON_GetObjectItem(root, "sound")->valueint;

    if (g_settings_brightness > 6) {
        g_settings_brightness = 6;
    }
    snprintf(g_settings_brightness_str, sizeof(g_settings_brightness_str), "%d", g_settings_brightness);

    if (g_settings_sound > 6) {
        g_settings_sound = 6;
    }
    g_settings_sound_str[0] = '0' + g_settings_sound;

    lcd_backlight_level(g_brightness_table[g_settings_brightness]);
    audioSetVolume(g_settings_sound);

    UG_ButtonSetText(&g_settings_window, 7, g_settings_brightness_str);
    UG_ButtonSetText(&g_settings_window, 4, g_settings_sound_str);

    vm_free(ptr);
}
Пример #7
0
//===========================
int tcp_connect(lua_State* L)
{
    tcp_info_t* p;
    int ref;
    char* addr = luaL_checkstring(L, 1);
    unsigned port = luaL_checkinteger(L, 2);

    p = (tcp_info_t*)lua_newuserdata(L, sizeof(tcp_info_t));

    if ((lua_type(L, 3) == LUA_TFUNCTION) || (lua_type(L, 3) == LUA_TLIGHTFUNCTION)) {
		lua_pushvalue(L, 3);
		ref = luaL_ref(L, LUA_REGISTRYINDEX);
	    p->cb_ref = ref;
    }
    else {
    	p->cb_ref = LUA_NOREF;
        size_t sl;
        const char* pdata = luaL_checklstring(L, 3, &sl);
        if ((sl <= 0) || (pdata == NULL)) {
            return luaL_error(L, "wrong send data");
        }
        if (send_buf != NULL) {
        	vm_free(send_buf);
        }
        send_buf = vm_malloc(sl+1);
        if (send_buf == NULL) {
            return luaL_error(L, "buffer allocation error");
        }

        strncpy(send_buf, pdata, sl);
        send_buf[sl] = '\0';
    }

    luaL_getmetatable(L, LUA_TCP);
    lua_setmetatable(L, -2);

    p->L = L;
    p->handle = vm_tcp_connect(addr, port, gprs_bearer_type, p, __tcp_callback);

    return 1;
}
Пример #8
0
char *GetChannelList(void)
{
	int ichan_list_length = 0;
	char sznumusers[10];
	
	if(GettingChannelList != 2) return NULL;
	if(!Socket_connected) return NULL;

	if(Chan_list)
	{
		vm_free(Chan_list);
		Chan_list = NULL;
	}
	
	
	Currchannel = Firstchannel;
	while(Currchannel) 
	{
		ichan_list_length += strlen(Currchannel->topic)+1+strlen(Currchannel->channel_name)+1+5;//1 for the space, and 4 for the number of users 0000-9999 + space
		Currchannel = Currchannel->next;
	}
	Currchannel = Firstchannel;
	Chan_list = (char *)vm_malloc(ichan_list_length+1);
	memset(Chan_list, 0, ichan_list_length+1);
	while(Currchannel) 
	{
		strcat(Chan_list,"$");
		strcat(Chan_list,Currchannel->channel_name);
		strcat(Chan_list," ");
		sprintf(sznumusers,"%d ",Currchannel->users);
		strcat(Chan_list,sznumusers);
		strcat(Chan_list,Currchannel->topic);//fgets
		strcat(Chan_list," ");
		Currchannel = Currchannel->next;
	}
	FlushChannelList();
	GettingChannelList = 0;
	return Chan_list;
}
void opengl_array_state::init(GLuint n_units)
{
	Assert( n_units > 0 );
	client_texture_units = (opengl_client_texture_unit*) vm_malloc(n_units * sizeof(opengl_client_texture_unit));
	num_client_texture_units = n_units;
	active_client_texture_unit = 0;

	for (unsigned int i = 0; i < num_client_texture_units; i++) {
		client_texture_units[i].pointer = 0;
		client_texture_units[i].size = 4;
		client_texture_units[i].status = GL_FALSE;
		client_texture_units[i].stride = 0;
		client_texture_units[i].type = GL_FLOAT;
		client_texture_units[i].buffer = 0;
		client_texture_units[i].reset_ptr = false;
		client_texture_units[i].used_for_draw = false;
	}

	array_buffer = 0;
	element_array_buffer = 0;
	texture_array_buffer = 0;
	uniform_buffer = 0;
}
Пример #10
0
void gcc_entry(unsigned int entry, unsigned int init_array_start, unsigned int count)
{
    unsigned int i;
    __init_array ptr;
    unsigned int size = 0;
    vm_get_sym_entry = (vm_get_sym_entry_t)entry;

    size = vm_pmng_get_total_heap_size();

#if defined(__LINKIT_ONE__)
    if(size > RESERVED_MEMORY_SIZE) {
        g_memory_size = size - RESERVED_MEMORY_SIZE;
    }
#endif

    g_base_address = vm_malloc(g_memory_size);

    ptr = (__init_array)init_array_start;
    for(i = 1; i < count; i++) {
        ptr[i]();
    }
    vm_main();
}
Пример #11
0
VMINT app_client_deinit(void)
{
    vm_log_debug("[AppClient] app_client_deinit state %d!\n", g_appc_cntx.state);
    if((g_appc_cntx.state == APPC_STATUS_DISABLED)
        || (g_appc_cntx.state == APPC_STATUS_DISABLING))
        return 0;

    if(g_appc_cntx.state == APPC_STATUS_ENABLED)
    {
        {
            client_gatt_conn.context_handle = g_appc_cntx.context_handle;
            client_gatt_conn.connection_handle = appc_conn_cntx->connection_handle;
            if((appc_conn_cntx->conn_status == APPC_STATUS_CONNECTED)
                || (appc_conn_cntx->conn_status == APPC_STATUS_CONNECTING))
            {
                client_bd_addr = (vm_bt_gatt_address_t *)vm_malloc(sizeof(vm_bt_gatt_address_t));
                memset(client_bd_addr, 0x0, sizeof(vm_bt_gatt_address_t));
                memcpy(client_bd_addr->data, appc_conn_cntx->bdaddr, VM_BT_GATT_ADDRESS_SIZE);
                vm_bt_gatt_client_disconnect(&client_gatt_conn, client_bd_addr);
            }
        }
    }

    vm_bt_gatt_client_deregister(g_appc_cntx.context_handle);
    g_appc_cntx.state = APPC_STATUS_DISABLED;
    //vm_free(appc_srv_uuid);

    if (appc_conn_cntx)
    {
        vm_free(appc_conn_cntx);
    }
    if (client_bd_addr)
    {
        vm_free(client_bd_addr);
    }
    return 1;
}
Пример #12
0
void geometry_batch_render(int stream_buffer)
{
	if ( stream_buffer < 0 ) {
		return;
	}

	int n_to_render = geometry_batch_get_size();
	int n_verts = 0;

	if ( Batch_geometry_buffer_size < (n_to_render * sizeof(particle_pnt)) ) {
		if ( Batch_geometry_buffer != NULL ) {
			vm_free(Batch_geometry_buffer);
		}

		Batch_geometry_buffer_size = n_to_render * sizeof(particle_pnt);
		Batch_geometry_buffer = vm_malloc(Batch_geometry_buffer_size);
	}

	batch_load_buffer_geometry_shader_map_bitmaps((particle_pnt*)Batch_geometry_buffer, &n_verts);

	gr_update_buffer_object(stream_buffer, Batch_geometry_buffer_size, Batch_geometry_buffer);

	batch_render_geometry_shader_map_bitmaps(stream_buffer);
}
Пример #13
0
void obj_reset_pairs()
{
	int i;
	
//	mprintf(( "Resetting object pairs...\n" ));

	pair_used_list.a = pair_used_list.b = NULL;		
	pair_used_list.next = NULL;
	pair_free_list.a = pair_free_list.b = NULL;

	Num_pairs = 0;

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

	Obj_pairs = (obj_pair*) vm_malloc( sizeof(obj_pair) * MIN_PAIRS );

	if ( Obj_pairs == NULL ) {
		mprintf(("Unable to create space for collision pairs!!\n"));
		return;
	}

	Num_pairs_allocated = MIN_PAIRS;

	memset( Obj_pairs, 0, sizeof(obj_pair) * MIN_PAIRS );

	for (i = 0; i < MIN_PAIRS; i++) {
		Obj_pairs[i].next = &Obj_pairs[i+1];
	}

	Obj_pairs[MIN_PAIRS-1].next = NULL;

	pair_free_list.next = &Obj_pairs[0];
}
Пример #14
0
int opengl_init_display_device()
{
	int bpp = gr_screen.bits_per_pixel;

	Assertion((bpp == 16) || (bpp == 32), "Invalid bits-per-pixel value %d!", bpp);

	// screen format
	switch (bpp) {
		case 16: {
			Gr_red.bits = 5;
			Gr_red.shift = 11;
			Gr_red.scale = 8;
			Gr_red.mask = 0xF800;

			Gr_green.bits = 6;
			Gr_green.shift = 5;
			Gr_green.scale = 4;
			Gr_green.mask = 0x7E0;

			Gr_blue.bits = 5;
			Gr_blue.shift = 0;
			Gr_blue.scale = 8;
			Gr_blue.mask = 0x1F;

			break;
		}

		case 32: {
			Gr_red.bits = 8;
			Gr_red.shift = 16;
			Gr_red.scale = 1;
			Gr_red.mask = 0xff0000;

			Gr_green.bits = 8;
			Gr_green.shift = 8;
			Gr_green.scale = 1;
			Gr_green.mask = 0x00ff00;

			Gr_blue.bits = 8;
			Gr_blue.shift = 0;
			Gr_blue.scale = 1;
			Gr_blue.mask = 0x0000ff;

			Gr_alpha.bits = 8;
			Gr_alpha.shift = 24;
			Gr_alpha.mask = 0xff000000;
			Gr_alpha.scale = 1;

			break;
		}
	}

	// texture format
	Gr_t_red.bits = 5;
	Gr_t_red.mask = 0x7c00;
	Gr_t_red.shift = 10;
	Gr_t_red.scale = 8;

	Gr_t_green.bits = 5;
	Gr_t_green.mask = 0x03e0;
	Gr_t_green.shift = 5;
	Gr_t_green.scale = 8;

	Gr_t_blue.bits = 5;
	Gr_t_blue.mask = 0x001f;
	Gr_t_blue.shift = 0;
	Gr_t_blue.scale = 8;

	Gr_t_alpha.bits = 1;
	Gr_t_alpha.mask = 0x8000;
	Gr_t_alpha.scale = 255;
	Gr_t_alpha.shift = 15;

	// alpha-texture format
	Gr_ta_red.bits = 4;
	Gr_ta_red.mask = 0x0f00;
	Gr_ta_red.shift = 8;
	Gr_ta_red.scale = 17;

	Gr_ta_green.bits = 4;
	Gr_ta_green.mask = 0x00f0;
	Gr_ta_green.shift = 4;
	Gr_ta_green.scale = 17;

	Gr_ta_blue.bits = 4;
	Gr_ta_blue.mask = 0x000f;
	Gr_ta_blue.shift = 0;
	Gr_ta_blue.scale = 17;

	Gr_ta_alpha.bits = 4;
	Gr_ta_alpha.mask = 0xf000;
	Gr_ta_alpha.shift = 12;
	Gr_ta_alpha.scale = 17;

	// allocate storage for original gamma settings
	if ( !Cmdline_no_set_gamma && (GL_original_gamma_ramp == NULL) ) {
		GL_original_gamma_ramp = (ushort*) vm_malloc( 3 * 256 * sizeof(ushort), memory::quiet_alloc);

		if (GL_original_gamma_ramp == NULL) {
			mprintf(("  Unable to allocate memory for gamma ramp!  Disabling...\n"));
			Cmdline_no_set_gamma = 1;
		} else {
			// assume identity ramp by default, to be overwritten by true ramp later
			for (ushort x = 0; x < 256; x++) {
				GL_original_gamma_ramp[x] = GL_original_gamma_ramp[x + 256] = GL_original_gamma_ramp[x + 512] = (x << 8) | x;
			}
		}
	}

	os::ViewPortProperties attrs;
	attrs.enable_opengl = true;

	attrs.gl_attributes.major_version = MIN_REQUIRED_GL_VERSION / 10;
	attrs.gl_attributes.minor_version = MIN_REQUIRED_GL_VERSION % 10;

#ifndef NDEBUG
	attrs.gl_attributes.flags.set(os::OpenGLContextFlags::Debug);
#endif

	attrs.gl_attributes.profile = os::OpenGLProfile::Core;

	attrs.display = os_config_read_uint("Video", "Display", 0);
	attrs.width = (uint32_t) gr_screen.max_w;
	attrs.height = (uint32_t) gr_screen.max_h;

	attrs.title = Osreg_title;

	if (!Cmdline_window && ! Cmdline_fullscreen_window) {
		attrs.flags.set(os::ViewPortFlags::Fullscreen);
	} else if (Cmdline_fullscreen_window) {
		attrs.flags.set(os::ViewPortFlags::Borderless);
	}

	auto viewport = gr_opengl_create_viewport(attrs);
	if (!viewport) {
		return 1;
	}

	const int gl_versions[] = { 45, 44, 43, 42, 41, 40, 33, 32 };

	// find the latest and greatest OpenGL context
	for (auto ver : gl_versions)
	{
		auto gl_attrs = attrs.gl_attributes;
		gl_attrs.major_version = ver / 10;
		gl_attrs.minor_version = ver % 10;

		GL_context = graphic_operations->createOpenGLContext(viewport.get(), gl_attrs);

		if (GL_context != nullptr)
		{
			break;
		}
	}

	if (GL_context == nullptr) {
		return 1;
	}

	auto port = os::addViewport(std::move(viewport));
	os::setMainViewPort(port);

	// We can't use gr_use_viewport because that tries to use OpenGL which hasn't been initialized yet
	graphic_operations->makeOpenGLContextCurrent(port, GL_context.get());
	current_viewport = port;

	if (GL_original_gamma_ramp != NULL && os::getSDLMainWindow() != nullptr) {
		SDL_GetWindowGammaRamp( os::getSDLMainWindow(), GL_original_gamma_ramp, (GL_original_gamma_ramp+256),
								(GL_original_gamma_ramp+512) );
	}

	return 0;
}
Пример #15
0
int gr_opengl_save_screen()
{
	int i;
	ubyte *sptr = NULL, *dptr = NULL;
	ubyte *opengl_screen_tmp = NULL;
	int width_times_pixel;

	gr_opengl_reset_clip();

	if (GL_saved_screen || GL_screen_pbo) {
		// already have a screen saved so just bail...
		return -1;
	}

	GL_saved_screen = (ubyte*)vm_malloc( gr_screen.max_w * gr_screen.max_h * 4, memory::quiet_alloc);

	if (!GL_saved_screen) {
		mprintf(( "Couldn't get memory for saved screen!\n" ));
 		return -1;
	}

	GLboolean save_state = GL_state.DepthTest(GL_FALSE);
	glReadBuffer(GL_FRONT_LEFT);

	if ( Use_PBOs ) {
		GLubyte *pixels = NULL;

		glGenBuffers(1, &GL_screen_pbo);

		if (!GL_screen_pbo) {
			if (GL_saved_screen) {
				vm_free(GL_saved_screen);
				GL_saved_screen = NULL;
			}

			return -1;
		}

		glBindBuffer(GL_PIXEL_PACK_BUFFER, GL_screen_pbo);
		glBufferData(GL_PIXEL_PACK_BUFFER, gr_screen.max_w * gr_screen.max_h * 4, NULL, GL_STATIC_READ);

		glReadPixels(0, 0, gr_screen.max_w, gr_screen.max_h, GL_read_format, GL_UNSIGNED_INT_8_8_8_8_REV, NULL);

		pixels = (GLubyte*)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);

		width_times_pixel = (gr_screen.max_w * 4);

		sptr = (ubyte *)pixels;
		dptr = (ubyte *)&GL_saved_screen[gr_screen.max_w * gr_screen.max_h * 4];

		for (i = 0; i < gr_screen.max_h; i++) {
			dptr -= width_times_pixel;
			memcpy(dptr, sptr, width_times_pixel);
			sptr += width_times_pixel;
		}

		glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
		glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);

		glDeleteBuffers(1, &GL_screen_pbo);
		GL_screen_pbo = 0;

		GL_saved_screen_id = bm_create(32, gr_screen.max_w, gr_screen.max_h, GL_saved_screen, 0);
	} else {
		opengl_screen_tmp = (ubyte*)vm_malloc( gr_screen.max_w * gr_screen.max_h * 4, memory::quiet_alloc);

		if (!opengl_screen_tmp) {
			if (GL_saved_screen) {
				vm_free(GL_saved_screen);
				GL_saved_screen = NULL;
			}

			mprintf(( "Couldn't get memory for temporary saved screen!\n" ));
			GL_state.DepthTest(save_state);
	 		return -1;
	 	}

		glReadPixels(0, 0, gr_screen.max_w, gr_screen.max_h, GL_read_format, GL_UNSIGNED_INT_8_8_8_8_REV, opengl_screen_tmp);

		sptr = (ubyte *)&opengl_screen_tmp[gr_screen.max_w * gr_screen.max_h * 4];
		dptr = (ubyte *)GL_saved_screen;

		width_times_pixel = (gr_screen.max_w * 4);

		for (i = 0; i < gr_screen.max_h; i++) {
			sptr -= width_times_pixel;
			memcpy(dptr, sptr, width_times_pixel);
			dptr += width_times_pixel;
		}

		vm_free(opengl_screen_tmp);

		GL_saved_screen_id = bm_create(32, gr_screen.max_w, gr_screen.max_h, GL_saved_screen, 0);
	}

	GL_state.DepthTest(save_state);

	return GL_saved_screen_id;
}
Пример #16
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"));
}
Пример #17
0
int http_Asyncgethostbyname(unsigned int *ip,int command, char *hostname)
{
	
	if(command==NW_AGHBN_LOOKUP)
	{
		if(http_lastaslu)
			http_lastaslu->abort = true;

		async_dns_lookup *newaslu;
		newaslu = (async_dns_lookup *)vm_malloc(sizeof(async_dns_lookup));
		memset(&newaslu->ip,0,sizeof(unsigned int));
		newaslu->host = hostname;
		newaslu->done = false;
		newaslu->error = false;
		newaslu->abort = false;
		http_lastaslu = newaslu;
		httpaslu.done = false;

#ifdef WIN32
		_beginthread(http_gethostbynameworker, 0, newaslu);
#else
		HOSTENT *he = gethostbyname(hostname);

		if (he == NULL) {
			newaslu->error = true;
		} else if ( !newaslu->abort ) {
			memcpy( &newaslu->ip, he->h_addr_list[0], sizeof(uint) );
			newaslu->done = true;
			memcpy( &httpaslu,newaslu, sizeof(async_dns_lookup) );
		}
	//	struct hostent *he;
	//	he = gethostbyname(hostname);
	//	newaslu->ip = (uint)((in_addr *)(he->h_addr))->s_addr;
	//	newaslu->done = true;
	//	httpaslu.done = true;
	//	thread_id
#endif

		return 1;
	}
	else if(command==NW_AGHBN_CANCEL)
	{
		if(http_lastaslu)
			http_lastaslu->abort = true;
		http_lastaslu = NULL;
	}
	else if(command==NW_AGHBN_READ)
	{
		if(!http_lastaslu)
			return -1;
		if(httpaslu.done)
		{
			//vm_free(http_lastaslu);
			http_lastaslu = NULL;
			memcpy(ip,&httpaslu.ip,sizeof(unsigned int));
			return 1;
		}
		else if(httpaslu.error)
		{
			vm_free(http_lastaslu);
			http_lastaslu = NULL;
			return -1;
		}
		else return 0;
	}
	return -2;

}
/**
 * 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;
}
Пример #19
0
/**
 * @return -1 if couldn't init font, otherwise returns the font id number.
 */
int gr_create_font(char * typeface)
{
	CFILE *fp;
	font *fnt;
	int n, fontnum;

	fnt = Fonts;
	n = -1;
	for (fontnum=0; fontnum<Num_fonts; fontnum++ )	{
		if (fnt->id != 0 )	{
			if ( !_strnicmp( fnt->filename, typeface, MAX_FILENAME_LEN ) )	{
				return fontnum;
			}
		} else {
			if ( n < 0 )	{
				n = fontnum;
			}				
		}
		fnt++;
	}

	if ( fontnum == MAX_FONTS )	{
		Warning( LOCATION, "Too many fonts!\nSee John, or change MAX_FONTS in Graphics\\Font.h\n" );
		return -1;
	}

	if ( fontnum == Num_fonts )	{
		Num_fonts++;
	}
	
	bool localize = true;

	fp = cfopen( typeface, "rb", CFILE_NORMAL, CF_TYPE_ANY, localize );
	if ( fp == NULL ) return -1;

	strncpy( fnt->filename, typeface, MAX_FILENAME_LEN );
	cfread( &fnt->id, 4, 1, fp );
	cfread( &fnt->version, sizeof(int), 1, fp );
	cfread( &fnt->num_chars, sizeof(int), 1, fp );
	cfread( &fnt->first_ascii, sizeof(int), 1, fp );
	cfread( &fnt->w, sizeof(int), 1, fp );
	cfread( &fnt->h, sizeof(int), 1, fp );
	cfread( &fnt->num_kern_pairs, sizeof(int), 1, fp );
	cfread( &fnt->kern_data_size, sizeof(int), 1, fp );
	cfread( &fnt->char_data_size, sizeof(int), 1, fp );
	cfread( &fnt->pixel_data_size, sizeof(int), 1, fp );

	fnt->id = INTEL_SHORT( fnt->id ); //-V570
	fnt->version = INTEL_INT( fnt->version ); //-V570
	fnt->num_chars = INTEL_INT( fnt->num_chars ); //-V570
	fnt->first_ascii = INTEL_INT( fnt->first_ascii ); //-V570
	fnt->w = INTEL_INT( fnt->w ); //-V570
	fnt->h = INTEL_INT( fnt->h ); //-V570
	fnt->num_kern_pairs = INTEL_INT( fnt->num_kern_pairs ); //-V570
	fnt->kern_data_size = INTEL_INT( fnt->kern_data_size ); //-V570
	fnt->char_data_size = INTEL_INT( fnt->char_data_size ); //-V570
	fnt->pixel_data_size = INTEL_INT( fnt->pixel_data_size ); //-V570

	if ( fnt->kern_data_size )	{
		fnt->kern_data = (font_kernpair *)vm_malloc( fnt->kern_data_size );
		Assert(fnt->kern_data!=NULL);
		cfread( fnt->kern_data, fnt->kern_data_size, 1, fp );
	} else {
		fnt->kern_data = NULL;
	}
	if ( fnt->char_data_size )	{
		fnt->char_data = (font_char *)vm_malloc( fnt->char_data_size );
		Assert( fnt->char_data != NULL );
		cfread( fnt->char_data, fnt->char_data_size, 1, fp );

		for (int i=0; i<fnt->num_chars; i++) {
			fnt->char_data[i].spacing = INTEL_INT( fnt->char_data[i].spacing ); //-V570
			fnt->char_data[i].byte_width = INTEL_INT( fnt->char_data[i].byte_width ); //-V570
			fnt->char_data[i].offset = INTEL_INT( fnt->char_data[i].offset ); //-V570
			fnt->char_data[i].kerning_entry = INTEL_INT( fnt->char_data[i].kerning_entry ); //-V570
			fnt->char_data[i].user_data = INTEL_SHORT( fnt->char_data[i].user_data ); //-V570
		}
	} else {
		fnt->char_data = NULL;
	}
	if ( fnt->pixel_data_size )	{
		fnt->pixel_data = (ubyte *)vm_malloc( fnt->pixel_data_size );
		Assert(fnt->pixel_data!=NULL);
		cfread( fnt->pixel_data, fnt->pixel_data_size, 1, fp );
	} else {
		fnt->pixel_data = NULL;
	}
	cfclose(fp);

	// Create a bitmap for hardware cards.
	// JAS:  Try to squeeze this into the smallest square power of two texture.
	// This should probably be done at font generation time, not here.
	int w, h;
	if ( fnt->pixel_data_size*4 < 64*64 ) {
		w = h = 64;
	} else if ( fnt->pixel_data_size*4 < 128*128 ) {
		w = h = 128;
	} else if ( fnt->pixel_data_size*4 < 256*256 ) {
		w = h = 256;
	} else if ( fnt->pixel_data_size*4 < 512*512 ) {
		w = h = 512;
	} else {
		w = h = 1024;
	}

	fnt->bm_w = w;
	fnt->bm_h = h;
	fnt->bm_data = (ubyte *)vm_malloc(fnt->bm_w*fnt->bm_h);
	fnt->bm_u = (int *)vm_malloc(sizeof(int)*fnt->num_chars);
	fnt->bm_v = (int *)vm_malloc(sizeof(int)*fnt->num_chars);

	memset( fnt->bm_data, 0, fnt->bm_w * fnt->bm_h );

	int i,x,y;
	x = y = 0;
	for (i=0; i<fnt->num_chars; i++ )	{
		ubyte * ubp;
		int x1, y1;
		ubp = &fnt->pixel_data[fnt->char_data[i].offset];
		if ( x + fnt->char_data[i].byte_width >= fnt->bm_w )	{
			x = 0;
			y += fnt->h + 2;
			if ( y+fnt->h > fnt->bm_h ) {
				Error( LOCATION, "Font too big!\n" );
			}
		}
		fnt->bm_u[i] = x;
		fnt->bm_v[i] = y;

		for( y1=0; y1<fnt->h; y1++ )	{
			for (x1=0; x1<fnt->char_data[i].byte_width; x1++ )	{
				uint c = *ubp++;
				if ( c > 14 ) c = 14;
				fnt->bm_data[(x+x1)+(y+y1)*fnt->bm_w] = (unsigned char)(c);	
			}
		}
		x += fnt->char_data[i].byte_width + 2;
	}

	fnt->bitmap_id = bm_create( 8, fnt->bm_w, fnt->bm_h, fnt->bm_data, BMP_AABITMAP );

	return fontnum;
}
Пример #20
0
static Profile *profile_update(Profile *profile, const char *section, const char *key, const char *value)
{
	if (profile == NULL) {
		profile = (Profile *)vm_malloc(sizeof(Profile));

		profile->sections = NULL;
	}

	KeyValue *kvp;

	Section **sp_ptr = &(profile->sections);
	Section *sp = profile->sections;

	while (sp != NULL) {
		if (strcmp(section, sp->name) == 0) {
			KeyValue **kvp_ptr = &(sp->pairs);
			kvp = sp->pairs;

			while (kvp != NULL) {
				if (strcmp(key, kvp->key) == 0) {
					vm_free(kvp->value);

					if (value == NULL) {
						*kvp_ptr = kvp->next;

						vm_free(kvp->key);
						vm_free(kvp);
					}
					else {
						kvp->value = vm_strdup(value);
					}

					/* all done */
					return profile;
				}

				kvp_ptr = &(kvp->next);
				kvp = kvp->next;
			}

			if (value != NULL) {
				/* key not found */
				kvp = (KeyValue *)vm_malloc(sizeof(KeyValue));
				kvp->next = NULL;
				kvp->key = vm_strdup(key);
				kvp->value = vm_strdup(value);
			}

			*kvp_ptr = kvp;

			/* all done */
			return profile;
		}

		sp_ptr = &(sp->next);
		sp = sp->next;
	}

	/* section not found */
	sp = (Section *)vm_malloc(sizeof(Section));
	sp->next = NULL;
	sp->name = vm_strdup(section);

	kvp = (KeyValue *)vm_malloc(sizeof(KeyValue));
	kvp->next = NULL;
	kvp->key = vm_strdup(key);
	kvp->value = vm_strdup(value);

	sp->pairs = kvp;

	*sp_ptr = sp;

	return profile;
}
Пример #21
0
/**
 * @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;
}
Пример #22
0
/**
 * @brief Will add an anim instance to the anim_render_list.  
 * This will cause the anim to be played at the x,y position specified in the parameter list.
 *
 * @param aps Compressed animation that we should make an instance from
 * @return If success pointer to instance, NULL if anim anim could not be played
 */
anim_instance *anim_play(anim_play_struct *aps)
{
	Assert( aps->anim_info != NULL );
	Assert( aps->start_at >= 0 );
	Assert( aps->stop_at < aps->anim_info->total_frames );
	Assert( !(aps->looped && aps->ping_pong) );  // shouldn't have these both set at once

	MONITOR_INC(NumANIPlayed, 1);

	anim_instance *instance;

	// Find next free anim instance slot on queue
	instance = GET_FIRST(&anim_free_list);
	Assert( instance != &anim_free_list );  // shouldn't have the dummy element

	// remove instance from the free list
	list_remove( &anim_free_list, instance );

	// insert instance onto the end of anim_render_list
	list_append( &anim_render_list, instance );

	aps->anim_info->instance_count++;
	instance->frame_num = -1;
	instance->last_frame_num = -99;
	instance->parent = aps->anim_info;
	instance->data = aps->anim_info->data;
	if ( anim_instance_is_streamed(instance) ) {
		instance->file_offset = instance->parent->file_offset;
	}
	instance->frame = (ubyte *) vm_malloc(instance->parent->width * instance->parent->height * 2);
	Assert( instance->frame != NULL );
	memset( instance->frame, 0, instance->parent->width * instance->parent->height * 2 );
	instance->time_elapsed = 0.0f;
	instance->stop_at = aps->stop_at;
	instance->x = aps->x;
	instance->y = aps->y;
	instance->world_pos = aps->world_pos;
	instance->radius = aps->radius;
	instance->framerate_independent = aps->framerate_independent;
	instance->last_bitmap = -1;
	instance->stop_now = FALSE;
	instance->screen_id = aps->screen_id;
	instance->aa_color = aps->color;
	instance->skip_frames = aps->skip_frames;
	instance->looped = aps->looped;
	instance->ping_pong = aps->ping_pong;
	instance->direction = ANIM_DIRECT_FORWARD;
	instance->paused = 0;
	instance->loop_count = 0;
	if ( aps->color == NULL ){
		instance->xlate_pal = 1;
	} else {
		instance->xlate_pal = 0;
	}

	if(aps->base_w < 0 || aps->base_h < 0) {
		instance->base_w = gr_screen.max_w_unscaled_zoomed;
		instance->base_h = gr_screen.max_h_unscaled_zoomed;
	} else {
		instance->base_w = aps->base_w;
		instance->base_h = aps->base_h;
	}

	// determining the start_at frame is more complicated, since it must be a key-frame.
	// Futhermore, need to subtract 1 from key-frame number, since frame number is always
	// incremented the first time anim_show_next_frame() is called

	instance->start_at = aps->start_at;

	if ( aps->start_at > 0 ) {
		key_frame *keyp;
		int idx;
		int key = 0;
		int offset = 0;
		int frame_num = aps->start_at;

		keyp = instance->parent->keys;
		idx = 0;
		while (idx < instance->parent->num_keys) {
			if (key == frame_num)
				break;

			key = keyp[idx].frame_num - 1;
			offset = keyp[idx].offset;

			idx++;
		}

		if (key > instance->frame_num) {  // best key is closer than current position
			instance->frame_num = key;
			if ( anim_instance_is_streamed(instance) ) {
				instance->file_offset = instance->parent->file_offset + offset;
			} else {
				instance->data = instance->parent->data + offset;
			}

		}

		instance->frame_num--;	// required
	}

	return instance;
}
Пример #23
0
/*
	uint32_t DecodeImage(uint32_t op_id, uint8_t* pSrc, uint32_t size, struct void* pStruct)
		
		op_id	- id of operation to perform from enum DecoderOps
		pSrc	- pointer to compressed file
		size    - size of available compressed file
		pStruct - pointer to ImageInfo or DecodeInfo struct depends on operation

		Return Value
		VM_DECODER_OK - success
		VM_DECODER_DECODE_FAILED - some error appears, maybe file corrupted or system haven't enough memory for decoder
		VM_DECODER_REACHED_MAX_THREADS - number of threads currently running by VM is reached their limit, wait a bit

*/
uint32_t SYSCALL SysDecodeImage(struct VirtualMachine* pVM)
{
	uint32_t id = pVM->Registers.r[0];

	switch(id){
		case VM_DECODER_GET_INFO:
		{
			struct UserFileStruct* pFile;
			struct ImageInfo* pImageInfo;
			uint32_t file_addr = pVM->Registers.r[1];
			uint32_t struct_addr = pVM->Registers.r[2];

			// check input structs
			if(((uint64_t)file_addr + sizeof(struct UserFileStruct)) > pVM->GlobalMemorySize){
				assert(false);
				return VM_DATA_ACCESS_VIOLATION;
			}
			if(((uint64_t)struct_addr + sizeof(struct ImageInfo)) > pVM->GlobalMemorySize){
				assert(false);
				return VM_DATA_ACCESS_VIOLATION;
			}
			// check buffers
			pFile = (struct UserFileStruct*)(pVM->pGlobalMemory + file_addr);
			if(((uint64_t)pFile->pBuf + pFile->buf_size) > pVM->GlobalMemorySize){
				assert(false);
				return VM_DATA_ACCESS_VIOLATION;
			}
			struct DecodeStruct* pInfo;
			pInfo = (struct DecodeStruct*)vm_malloc(sizeof(DecodeStruct));
			if(pInfo == NULL){
				assert(false);
				return VM_NOT_ENOUGH_MEMORY;
			}
			pImageInfo = (struct ImageInfo*)(pVM->pGlobalMemory + struct_addr);

			memset(pInfo, 0, sizeof(struct DecodeStruct));
			pInfo->pVM = pVM;
			pInfo->pFile = pFile;
			pInfo->pUser = (struct UserDecodeStruct*)pImageInfo;
			pInfo->pSrc = pVM->pGlobalMemory + pFile->pBuf;
			pInfo->src_size = pFile->buf_size;
			
			pVM->Registers.r[0] = GetImageInfo(pVM, pFile, pInfo, pImageInfo);
		}
		break;
		case VM_DECODE_JPEG:
		{
			struct UserFileStruct* pFile;
			struct UserDecodeStruct* pUserInfo;
			uint32_t file_addr = pVM->Registers.r[1];
			uint32_t addr = pVM->Registers.r[2];

			// check input structs
			if(((uint64_t)file_addr + sizeof(UserFileStruct)) > pVM->GlobalMemorySize){
				assert(false);
				return VM_DATA_ACCESS_VIOLATION;
			}
			if(((uint64_t)addr + sizeof(UserDecodeStruct)) > pVM->GlobalMemorySize){
				assert(false);
				return VM_DATA_ACCESS_VIOLATION;
			}
			// check buffers
			pFile = (struct UserFileStruct*)(pVM->pGlobalMemory + file_addr);
			if(((uint64_t)pFile->pBuf + pFile->buf_size) > pVM->GlobalMemorySize){
				assert(false);
				return VM_DATA_ACCESS_VIOLATION;
			}
			pUserInfo = (struct UserDecodeStruct*)(pVM->pGlobalMemory + addr);
			if(((uint64_t)pUserInfo->pDst + pUserInfo->dst_size) > pVM->GlobalMemorySize){
				assert(false);
				return VM_DATA_ACCESS_VIOLATION;
			}
			struct DecodeStruct* pInfo = (struct DecodeStruct*)vm_malloc(sizeof(DecodeStruct));
			if(pInfo == NULL){
				assert(false);
				return VM_NOT_ENOUGH_MEMORY;
			}
			memset(pInfo, 0, sizeof(struct DecodeStruct));
			pInfo->pVM = pVM;
			pInfo->pFile = pFile;
			pInfo->pUser = pUserInfo;
			pInfo->pSrc = pVM->pGlobalMemory + pFile->pBuf;
			pInfo->pDst = pVM->pGlobalMemory + pUserInfo->pDst;
			pInfo->src_size = pFile->buf_size;

			if(AddThread(pVM, DecodeJPEG, pInfo) != VM_OK){
				assert(false);
				pVM->Registers.r[0] = VM_DECODER_CANT_CREATE_THREAD;
			}
			pVM->Registers.r[0] = VM_DECODER_OK;
		}
		break;
		default:
			assert(false);
			return VM_INVALID_SYSCALL;		
	}

	return VM_OK;
}
Пример #24
0
void model_collide_parse_bsp(bsp_collision_tree *tree, void *model_ptr, int version)
{
	TRACE_SCOPE(tracing::ModelParseBSPTree);

	ubyte *p = (ubyte *)model_ptr;
	ubyte *next_p;

	int chunk_type = w(p);
	int chunk_size = w(p+4);

	int next_chunk_type;
	int next_chunk_size;

	Assert(chunk_type == OP_DEFPOINTS);

	int n_verts = model_collide_parse_bsp_defpoints(p);

	if ( n_verts <= 0) {
		tree->point_list = NULL;
		tree->n_verts = 0;

		tree->n_nodes = 0;
		tree->node_list = NULL;

		tree->n_leaves = 0;
		tree->leaf_list = NULL;

		// finally copy the vert list.
		tree->vert_list = NULL;

		return;
	}

	p += chunk_size;

	bsp_collision_node new_node;
	bsp_collision_leaf new_leaf;

	SCP_vector<bsp_collision_node> node_buffer;
	SCP_vector<bsp_collision_leaf> leaf_buffer;
	SCP_vector<model_tmap_vert> vert_buffer;

	SCP_map<size_t, ubyte*> bsp_datap;

	node_buffer.push_back(new_node);

	size_t i = 0;
	vec3d *min;
	vec3d *max;

	bsp_datap[i] = p;

	while ( i < node_buffer.size() ) {
		p = bsp_datap[i];

		chunk_type = w(p);
		chunk_size = w(p+4);

		switch ( chunk_type ) {
		case OP_SORTNORM:
			if ( version >= 2000 ) {
				min = vp(p+56);
				max = vp(p+68);

				node_buffer[i].min = *min;
				node_buffer[i].max = *max;
			}

			node_buffer[i].leaf = -1;
			node_buffer[i].front = -1;
			node_buffer[i].back = -1;

			if ( w(p+36) ) {
				next_chunk_type = w(p+w(p+36));

				if ( next_chunk_type != OP_EOF ) {
					node_buffer.push_back(new_node);
					node_buffer[i].front = (int)(node_buffer.size() - 1);
					bsp_datap[node_buffer[i].front] = p+w(p+36);
				}
			}

			if ( w(p+40) ) {
				next_chunk_type = w(p+w(p+40));
				
				if ( next_chunk_type != OP_EOF ) {
					node_buffer.push_back(new_node);
					node_buffer[i].back = (int)(node_buffer.size() - 1);
					bsp_datap[node_buffer[i].back] = p+w(p+40);
				}
			}

			next_p = p + chunk_size;
			next_chunk_type = w(next_p);

			Assert( next_chunk_type == OP_EOF );

			++i;
			break;
		case OP_BOUNDBOX:
			min = vp(p+8);
			max = vp(p+20);

			node_buffer[i].min = *min;
			node_buffer[i].max = *max;

			node_buffer[i].front = -1;
			node_buffer[i].back = -1;
			node_buffer[i].leaf = -1;

			next_p = p + chunk_size;
			next_chunk_type = w(next_p);
			next_chunk_size = w(next_p+4);

			if ( next_chunk_type != OP_EOF && (next_chunk_type == OP_TMAPPOLY || next_chunk_type == OP_FLATPOLY ) ) {
				new_leaf.next = -1;

				node_buffer[i].leaf = (int)leaf_buffer.size();	// get index of where our poly list starts in the leaf buffer

				while ( next_chunk_type != OP_EOF ) {
					if ( next_chunk_type == OP_TMAPPOLY ) {

						model_collide_parse_bsp_tmappoly(&new_leaf, &vert_buffer, next_p);

						leaf_buffer.push_back(new_leaf);

						leaf_buffer.back().next = (int)leaf_buffer.size();
					} else if ( next_chunk_type == OP_FLATPOLY ) {
						model_collide_parse_bsp_flatpoly(&new_leaf, &vert_buffer, next_p);

						leaf_buffer.push_back(new_leaf);

						leaf_buffer.back().next = (int)leaf_buffer.size();
					} else {
						Int3();
					}

					next_p += next_chunk_size;
					next_chunk_type = w(next_p);
					next_chunk_size = w(next_p+4);
				}

				leaf_buffer.back().next = -1;
			}

			Assert(next_chunk_type == OP_EOF);

			++i;
			break;
		}
	}

	// copy point list
	Assert(n_verts != -1);

	tree->point_list = (vec3d*)vm_malloc(sizeof(vec3d) * n_verts);

	for ( i = 0; i < (size_t)n_verts; ++i ) {
		tree->point_list[i] = *Mc_point_list[i];
	}

	tree->n_verts = n_verts;

	// copy node info. this might be a good time to organize the nodes into a cache efficient tree layout.
	tree->n_nodes = (int)node_buffer.size();
	tree->node_list = (bsp_collision_node*)vm_malloc(sizeof(bsp_collision_node) * node_buffer.size());
	memcpy(tree->node_list, &node_buffer[0], sizeof(bsp_collision_node) * node_buffer.size());
	node_buffer.clear();

	// copy leaves.
	tree->n_leaves = (int)leaf_buffer.size();
	tree->leaf_list = (bsp_collision_leaf*)vm_malloc(sizeof(bsp_collision_leaf) * leaf_buffer.size());
	memcpy(tree->leaf_list, &leaf_buffer[0], sizeof(bsp_collision_leaf) * leaf_buffer.size());
	leaf_buffer.clear();

	// finally copy the vert list.
	tree->vert_list = (model_tmap_vert*)vm_malloc(sizeof(model_tmap_vert) * vert_buffer.size());
	memcpy(tree->vert_list, &vert_buffer[0], sizeof(model_tmap_vert) * vert_buffer.size());
	vert_buffer.clear();
}
Пример #25
0
void *operator new[](size_t size) {
  return vm_malloc(size);
}
Пример #26
0
void pilotfile::csg_read_missions()
{
	int i, j, idx, list_size;
	cmission *missionp;

	if ( !m_have_info ) {
		throw "Missions before Info!";
	}

	for (i = 0; i < Campaign.num_missions_completed; i++) {
		idx = cfread_int(cfp);
		missionp = &Campaign.missions[idx];

		missionp->completed = 1;

		// flags
		missionp->flags = cfread_int(cfp);

		// goals
		missionp->num_goals = cfread_int(cfp);

		if (missionp->num_goals > 0) {
			missionp->goals = (mgoal *) vm_malloc( missionp->num_goals * sizeof(mgoal) );
			Verify( missionp->goals != NULL );

			memset( missionp->goals, 0, missionp->num_goals * sizeof(mgoal) );

			for (j = 0; j < missionp->num_goals; j++) {
				cfread_string_len(missionp->goals[j].name, NAME_LENGTH, cfp);
				missionp->goals[j].status = cfread_char(cfp);
			}
		}

		// events
		missionp->num_events = cfread_int(cfp);

		if (missionp->num_events > 0) {
			missionp->events = (mevent *) vm_malloc( missionp->num_events * sizeof(mevent) );
			Verify( missionp->events != NULL );

			memset( missionp->events, 0, missionp->num_events * sizeof(mevent) );

			for (j = 0; j < missionp->num_events; j++) {
				cfread_string_len(missionp->events[j].name, NAME_LENGTH, cfp);
				missionp->events[j].status = cfread_char(cfp);
			}
		}

		// variables
		missionp->num_variables = cfread_int(cfp);

		if (missionp->num_variables > 0) {
			missionp->variables = (sexp_variable *) vm_malloc( missionp->num_variables * sizeof(sexp_variable) );
			Verify( missionp->variables != NULL );

			memset( missionp->variables, 0, missionp->num_variables * sizeof(sexp_variable) );

			for (j = 0; j < missionp->num_variables; j++) {
				missionp->variables[j].type = cfread_int(cfp);
				cfread_string_len(missionp->variables[j].text, TOKEN_LENGTH, cfp);
				cfread_string_len(missionp->variables[j].variable_name, TOKEN_LENGTH, cfp);
			}
		}

		// scoring stats
		missionp->stats.score = cfread_int(cfp);
		missionp->stats.rank = cfread_int(cfp);
		missionp->stats.assists = cfread_int(cfp);
		missionp->stats.kill_count = cfread_int(cfp);
		missionp->stats.kill_count_ok = cfread_int(cfp);
		missionp->stats.bonehead_kills = cfread_int(cfp);

		missionp->stats.p_shots_fired = cfread_uint(cfp);
		missionp->stats.p_shots_hit = cfread_uint(cfp);
		missionp->stats.p_bonehead_hits = cfread_uint(cfp);

		missionp->stats.s_shots_fired = cfread_uint(cfp);
		missionp->stats.s_shots_hit = cfread_uint(cfp);
		missionp->stats.s_bonehead_hits = cfread_uint(cfp);

		// ship kills (scoring)
		list_size = (int)ship_list.size();
		for (j = 0; j < list_size; j++) {
			idx = cfread_int(cfp);

			if (ship_list[j].index >= 0) {
				missionp->stats.kills[ship_list[j].index] = idx;
			}
		}

		// medals (scoring)
		list_size = (int)medals_list.size();
		for (j = 0; j < list_size; j++) {
			idx = cfread_int(cfp);

			if (medals_list[j].index >= 0) {
				missionp->stats.medal_counts[medals_list[j].index] = idx;
			}
		}
	}
}
Пример #27
0
static Profile *profile_read(const char *file)
{
	FILE *fp = NULL;
	char *str;

	if (os_is_legacy_mode()) {
#ifdef WIN32
		return nullptr; // No config file in legacy mode
#else
		// Try to use the config file at the old location
		char legacy_path[MAX_PATH_LEN];
		snprintf(legacy_path, MAX_PATH_LEN, "%s/%s/%s", getenv("HOME"), Osreg_user_dir_legacy, file);

		fp = fopen(legacy_path, "rt");
#endif
	}
	else {
		fp = fopen(os_get_config_path(file).c_str(), "rt");
	}

	if (fp == NULL)
		return NULL;

	Profile *profile = (Profile *)vm_malloc(sizeof(Profile));
	profile->sections = NULL;

	Section **sp_ptr = &(profile->sections);
	Section *sp = NULL;

	KeyValue **kvp_ptr = NULL;

	while ((str = read_line_from_file(fp)) != NULL) {
		char *ptr = trim_string(str);

		if (*ptr == '[') {
			ptr++;

			char *pend = strchr(ptr, ']');
			if (pend != NULL) {
				// if (pend[1]) { /* trailing garbage! */ }

				*pend = 0;

				if (*ptr) {
					sp = (Section *)vm_malloc(sizeof(Section));
					sp->next = NULL;

					sp->name = vm_strdup(ptr);
					sp->pairs = NULL;

					*sp_ptr = sp;
					sp_ptr = &(sp->next);

					kvp_ptr = &(sp->pairs);
				} // else { /* null name! */ }
			} // else { /* incomplete section name! */ }
		}
		else {
			if (*ptr) {
				char *key = ptr;
				char *value = NULL;

				ptr = strchr(ptr, '=');
				if (ptr != NULL) {
					*ptr = 0;
					ptr++;

					value = ptr;
				} // else { /* random garbage! */ }

				if (key && *key && value /* && *value */) {
					if (sp != NULL) {
						KeyValue *kvp = (KeyValue *)vm_malloc(sizeof(KeyValue));

						kvp->key = vm_strdup(key);
						kvp->value = vm_strdup(value);

						kvp->next = NULL;

						*kvp_ptr = kvp;
						kvp_ptr = &(kvp->next);
					} // else { /* key/value with no section! */
				} // else { /* malformed key/value entry! */ }
			} // else it's just a comment or empty string
		}

		vm_free(str);
	}

	fclose(fp);

	return profile;
}
Пример #28
0
static png_voidp png_malloc_fn(png_structp, png_size_t size)
{
	return vm_malloc(size);
}
Пример #29
0
/**
 * @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);
}
Пример #30
0
void* __cdecl operator new[](size_t size, vm_args)
{
    return vm_malloc(size, lpcFileName, iStringNumber);
}