コード例 #1
0
static void test_resampler(void)
{
    std::string fbody("sweep_440-3520_1s");
    mcon::Vector<double> input;
    mfio::Wave wave;
    wave.Read(fbody + std::string(".wav"), input);

    const int baseFs = wave.GetSamplingRate();
    const int targetFs = 16000;
    const double fp = 0.35;
    const double fs = 0.45;

    masp::Resampler resampler(targetFs, baseFs, fp, fs);
    resampler.MakeFilterByWindowType(masp::Resampler::HANNING);

    {
        mcon::Vector<double> coefs;
        resampler.GetCoefficients(coefs);
        LOG("Length=%d\n", static_cast<int>(coefs.GetLength()));
    }
    {
        mcon::Vector<double> output;
        resampler.Convert(output, input);
        output *= 32767.0/output.GetMaximumAbsolute();

        mfio::Wave w(targetFs, wave.GetNumChannels(), wave.GetBitDepth());
        w.Write(fbody + std::string("_resampled1.wav"), output);
    }
    const double ripple = 0.01;
    const double decay = 80;

    resampler.MakeFilterBySpec(ripple, decay);

    {
        mcon::Vector<double> coefs;
        resampler.GetCoefficients(coefs);
        LOG("Length=%d\n", static_cast<int>(coefs.GetLength()));
    }
    {
        mcon::Vector<double> output;
        resampler.Convert(output, input);
        output *= 32767.0/output.GetMaximumAbsolute();

        mfio::Wave w(targetFs, wave.GetNumChannels(), wave.GetBitDepth());
        w.Write(fbody + std::string("_resampled2.wav"), output);
    }
    // サンプルの数を変更する
    // ==> 実質的に周波数変換?
    // ==> 違う気がする...
    {
        const int N = 100;
        const double ratio = 1.5;
        const double fp = 0.35;
        const double fs = 0.45;
        const double ripple = 0.01;
        const double decay = 80;
        mcon::Vector<double> src(N);
        for (int k = 0; k < N; ++k)
        {
            src[k] = k;
        }
        resampler.Initialize(static_cast<int>(ratio * N), N, fp, fs);
        resampler.MakeFilterBySpec(ripple, decay);

        mcon::Vector<double> dst;
        resampler.Convert(dst, src);
        mfio::Csv::Write("sample_count_convert.csv", dst);
    }
}
コード例 #2
0
ファイル: lz4mt.cpp プロジェクト: kgodlewski/lz4mt
extern "C" Lz4MtResult
lz4mtDecompress(Lz4MtContext* lz4MtContext, Lz4MtStreamDescriptor* sd)
{
	assert(lz4MtContext);
	assert(sd);

	Context ctx_(lz4MtContext);
	Context* ctx = &ctx_;

	std::atomic<bool> quit(false);

	ctx->setResult(LZ4MT_RESULT_OK);
	while(!quit && !ctx->error() && !ctx->readEof()) {
		const auto magic = ctx->readU32();
		if(ctx->error()) {
			if(ctx->readEof()) {
				ctx->setResult(LZ4MT_RESULT_OK);
			} else {
				ctx->setResult(LZ4MT_RESULT_INVALID_HEADER);
			}
			break;
		}

		if(isSkippableMagicNumber(magic)) {
			const auto size = ctx->readU32();
			if(ctx->error()) {
				ctx->setResult(LZ4MT_RESULT_INVALID_HEADER);
				break;
			}
			const auto s = ctx->readSkippable(magic, size);
			if(s < 0 || ctx->error()) {
				ctx->setResult(LZ4MT_RESULT_INVALID_HEADER);
				break;
			}
			continue;
		}

		if(LZ4S_MAGICNUMBER != magic) {
			ctx->readSeek(-4);
			ctx->setResult(LZ4MT_RESULT_INVALID_MAGIC_NUMBER);
			break;
		}

		char d[LZ4S_MAX_HEADER_SIZE] = { 0 };
		auto* p = d;
		const auto* sumBegin = p;

		if(2 != ctx->read(p, 2)) {
			ctx->setResult(LZ4MT_RESULT_INVALID_HEADER);
			break;
		}
		sd->flg = charToFlg(*p++);
		sd->bd  = charToBc(*p++);
		const auto r = validateStreamDescriptor(sd);
		if(LZ4MT_RESULT_OK != r) {
			ctx->setResult(r);
			break;
		}

		const int nExInfo =
			  (sd->flg.streamSize       ? sizeof(uint64_t) : 0)
			+ (sd->flg.presetDictionary ? sizeof(uint32_t) : 0)
			+ 1
		;
		if(nExInfo != ctx->read(p, nExInfo)) {
			ctx->setResult(LZ4MT_RESULT_INVALID_HEADER);
			break;
		}

		if(sd->flg.streamSize) {
			sd->streamSize = loadU64(p);
			p += sizeof(uint64_t);
		}

		if(sd->flg.presetDictionary) {
			sd->dictId = loadU32(p);
			p += sizeof(uint32_t);
		}

		const auto sumSize   = static_cast<int>(p - sumBegin);
		const auto calHash32 = Lz4Mt::Xxh32(sumBegin, sumSize, LZ4S_CHECKSUM_SEED).digest();
		const auto calHash   = static_cast<char>(getCheckBits_FromXXH(calHash32));
		const auto srcHash   = *p++;

		assert(p <= std::end(d));

		if(srcHash != calHash) {
			ctx->setResult(LZ4MT_RESULT_INVALID_HEADER_CHECKSUM);
			break;
		}

		const auto nBlockMaximumSize = getBlockSize(sd->bd.blockMaximumSize);
		const auto nBlockCheckSum    = sd->flg.blockChecksum ? 4 : 0;
		const bool streamChecksum    = 0 != sd->flg.streamChecksum;
		const bool singleThread      = 0 != (ctx->mode() & LZ4MT_MODE_SEQUENTIAL);
		const auto nConcurrency      = Lz4Mt::getHardwareConcurrency();
		const auto nPool             = singleThread ? 1 : nConcurrency + 1;
		const auto launch            = singleThread ? Lz4Mt::launch::deferred : std::launch::async;

		Lz4Mt::MemPool srcBufferPool(nBlockMaximumSize, nPool);
		Lz4Mt::MemPool dstBufferPool(nBlockMaximumSize, nPool);
		std::vector<std::future<void>> futures;
		Lz4Mt::Xxh32 xxhStream(LZ4S_CHECKSUM_SEED);

		const auto f = [
			&futures, &dstBufferPool, &xxhStream, &quit
			, ctx, nBlockCheckSum, streamChecksum, launch
		] (int i, Lz4Mt::MemPool::Buffer* srcRaw, bool incompressible, uint32_t blockChecksum)
		{
			BufferPtr src(srcRaw);
			if(ctx->error() || quit) {
				return;
			}

			const auto* srcPtr = src->data();
			const auto srcSize = static_cast<int>(src->size());

			std::future<uint32_t> futureBlockHash;
			if(nBlockCheckSum) {
				futureBlockHash = std::async(launch, [=] {
					return Lz4Mt::Xxh32(srcPtr, srcSize, LZ4S_CHECKSUM_SEED).digest();
				});
			}

			if(incompressible) {
				if(i > 0) {
					futures[i-1].wait();
				}

				std::future<void> futureStreamHash;
				if(streamChecksum) {
					futureStreamHash = std::async(
						  launch
						, [&xxhStream, srcPtr, srcSize] {
							xxhStream.update(srcPtr, srcSize);
						}
					);
				}
				ctx->writeBin(srcPtr, srcSize);
				if(futureStreamHash.valid()) {
					futureStreamHash.wait();
				}
			} else {
				BufferPtr dst(dstBufferPool.alloc());

				auto* dstPtr = dst->data();
				const auto dstSize = dst->size();
				const auto decSize = ctx->decompress(
					srcPtr, dstPtr, srcSize, static_cast<int>(dstSize));
				if(decSize < 0) {
					quit = true;
					ctx->setResult(LZ4MT_RESULT_DECOMPRESS_FAIL);
					return;
				}

				if(i > 0) {
					futures[i-1].wait();
				}

				std::future<void> futureStreamHash;
				if(streamChecksum) {
					futureStreamHash = std::async(
						  launch
						, [&xxhStream, dstPtr, decSize] {
							xxhStream.update(dstPtr, decSize);
						}
					);
				}
				ctx->writeBin(dstPtr, decSize);
				if(futureStreamHash.valid()) {
					futureStreamHash.wait();
				}
			}

			if(futureBlockHash.valid()) {
				auto bh = futureBlockHash.get();
				if(bh != blockChecksum) {
					quit = true;
					ctx->setResult(LZ4MT_RESULT_BLOCK_CHECKSUM_MISMATCH);
					return;
				}
			}
			return;
		};

		for(int i = 0; !quit && !ctx->readEof(); ++i) {
			const auto srcBits = ctx->readU32();
			if(ctx->error()) {
				quit = true;
				ctx->setResult(LZ4MT_RESULT_CANNOT_READ_BLOCK_SIZE);
				break;
			}

			if(LZ4S_EOS == srcBits) {
				break;
			}

			const auto incompMask     = (1 << 31);
			const bool incompressible = 0 != (srcBits & incompMask);
			const auto srcSize        = static_cast<int>(srcBits & ~incompMask);

			BufferPtr src(srcBufferPool.alloc());
			const auto readSize = ctx->read(src->data(), srcSize);
			if(srcSize != readSize || ctx->error()) {
				quit = true;
				ctx->setResult(LZ4MT_RESULT_CANNOT_READ_BLOCK_DATA);
				break;
			}
			src->resize(readSize);

			const auto blockCheckSum = nBlockCheckSum ? ctx->readU32() : 0;
			if(ctx->error()) {
				quit = true;
				ctx->setResult(LZ4MT_RESULT_CANNOT_READ_BLOCK_CHECKSUM);
				break;
			}

			if(singleThread) {
				f(0, src.release(), incompressible, blockCheckSum);
			} else {
				futures.emplace_back(std::async(
					  launch
					, f, i, src.release(), incompressible, blockCheckSum
				));
			}
		}

		for(auto& e : futures) {
			e.wait();
		}

		if(!ctx->error() && streamChecksum) {
			const auto srcStreamChecksum = ctx->readU32();
			if(ctx->error()) {
				ctx->setResult(LZ4MT_RESULT_CANNOT_READ_STREAM_CHECKSUM);
				break;
			}
			if(xxhStream.digest() != srcStreamChecksum) {
				ctx->setResult(LZ4MT_RESULT_STREAM_CHECKSUM_MISMATCH);
				break;
			}
		}
	}

	return ctx->result();
}
コード例 #3
0
/*
================
rvGEWorkspace::NewWindow

Create a new window
================
*/
idWindow* rvGEWorkspace::NewWindow ( idDict* state, rvGEWindowWrapper::EWindowType type )
{
	idWindow*			window = new idWindow ( mInterface->GetDesktop()->GetDC(), mInterface );
	rvGEWindowWrapper*	wrapper;
	int					count;
	idStr				baseName;

	switch ( type )
	{
		case rvGEWindowWrapper::WT_NORMAL:
			window = new idWindow ( mInterface->GetDesktop()->GetDC(), mInterface );
			break;

		case rvGEWindowWrapper::WT_BIND:
			window = new idBindWindow ( mInterface->GetDesktop()->GetDC(), mInterface );
			break;

		case rvGEWindowWrapper::WT_RENDER:
			window = new idRenderWindow ( mInterface->GetDesktop()->GetDC(), mInterface );
			break;

		case rvGEWindowWrapper::WT_CHOICE:
			window = new idChoiceWindow ( mInterface->GetDesktop()->GetDC(), mInterface );
			break;

		case rvGEWindowWrapper::WT_EDIT:
			window = new idEditWindow ( mInterface->GetDesktop()->GetDC(), mInterface );
			break;

		default:
			assert ( false );
			return NULL;
	}

	baseName = state ? state->GetString("name","unnamed") : "unnamed";
	baseName.StripQuotes ( );

	count = 0;
	if ( mInterface->GetDesktop()->FindChildByName ( baseName ) )
	{
		count = 1;
		while ( 1 )
		{
			drawWin_t* dw = mInterface->GetDesktop()->FindChildByName ( va("%s%d",baseName.c_str(),count) );
			if ( !dw )
			{
				break;
			}
			assert ( dw->win );
			wrapper = rvGEWindowWrapper::GetWrapper ( dw->win );
			if ( wrapper && wrapper->IsDeleted ( ) )
			{
				break;
			}
			count++;
		}
	}

	idStr winName;
	idStr winTemplate;

	if ( count )
	{
		winName = va("%s%d", baseName.c_str(), count );
	}
	else
	{
		winName = baseName;
	}
	winTemplate = winName + " { }";

	idParser src( winTemplate, winTemplate.Length(), "", LEXFL_ALLOWMULTICHARLITERALS | LEXFL_NOSTRINGCONCAT | LEXFL_ALLOWBACKSLASHSTRINGCONCAT );
	window->Parse ( &src );

	wrapper = rvGEWindowWrapper::GetWrapper ( window );

	if ( state )
	{
		wrapper->SetState ( *state );
	}

	wrapper->SetStateKey ( "name", winName );
	wrapper->Finish ( );

	SetModified ( true );


	return window;
}
コード例 #4
0
ファイル: x509_crl.cpp プロジェクト: noloader/botan
X509_CRL::X509_CRL(const std::string& fsname)
   {
   DataSource_Stream src(fsname, true);
   load_data(src);
   }
コード例 #5
0
void pix_opencv_patreco :: loadMess (t_symbol *s, int argc, t_atom* argv)
{
	t_symbol* filename;
	int id;
	
	if ( argc != 2 ) {
		error("wrong arguments : load <id> <filename>");
		return;
	} else if ( argv[0].a_type != A_FLOAT ||  argv[1].a_type != A_SYMBOL ) {
		error("wrong arguments : load <id> <filename>");
		return;
	} else {
		id = atom_getfloat(&argv[0]);
		filename = atom_getsymbol(&argv[1]);
	}
		
	
	if ( filename->s_name[0] == 0 ) {
		error("no filename passed to load message");
		return;
	}
	if ( filename == NULL ) { 
		error("%s is not a valid matrix", filename->s_name); 
		return;
	}
	
	Mat img = imread(filename->s_name,0);
	
	if ( img.data == NULL ){
		error("failed to load image '%s'", filename->s_name);
		puts("failed to laod images");
		return;
	}
	
	if(img.cols!=img.rows){
		error("%s is not a square pattern", filename->s_name);
		puts("not a square pattern");
		return;
	}

	cv::Mat src(m_pattern_size, m_pattern_size, CV_8UC1);
	Point2f center((m_pattern_size-1)/2.0f,(m_pattern_size-1)/2.0f);
	Mat rot_mat(2,3,CV_32F);
	
	//~ std::map<int PatternLib>::iterator it;
	//~ it = m_patternLibrary.find(id);
	//~ if ( m_patternLibrary.find(id) != m_patternLibrary.end() ){
		// TODO remove item from the map
	//~ }

	PatternLib pattern;
	pattern.id = id;
		
	cv::resize(img, src, Size(m_pattern_size,m_pattern_size));
	if ( m_detector->m_ART_pattern ) {
		Mat subImg = src(cv::Range(m_pattern_size/4,3*m_pattern_size/4), cv::Range(m_pattern_size/4,3*m_pattern_size/4));
		pattern.pattern[0]  = subImg;
		pattern.mean[0] = cvMean(&((CvMat)subImg));
		pattern.norm[0] = cv::norm(subImg, NORM_L1);
		//~ m_patternLibrary.push_back(subImg);
	}
	else {
		//~ m_patternLibrary.push_back(src);
		pattern.pattern[0]  = src;
		pattern.mean[0] = cvMean(&((CvMat)src));
		pattern.norm[0] = cv::norm(src, NORM_L1);
	}
	
	rot_mat = getRotationMatrix2D( center, 90, 1.0);

	for (int i=1; i<4; i++){
		Mat dst= Mat(m_pattern_size, m_pattern_size, CV_8UC1);
		rot_mat = getRotationMatrix2D( center, -i*90, 1.0);
		cv::warpAffine( src, dst , rot_mat, Size(m_pattern_size,m_pattern_size));
		if ( m_detector->m_ART_pattern ) {
			Mat subImg = dst(cv::Range(m_pattern_size/4,3*m_pattern_size/4), cv::Range(m_pattern_size/4,3*m_pattern_size/4)); // AV crop 25% on each side -> specific to AR tag ?
			pattern.pattern[i];
			pattern.mean[i] = cvMean(&((CvMat)subImg));
			pattern.norm[i] = cv::norm(subImg, NORM_L1);
			//~ m_patternLibrary.push_back(subImg);	
		} else {
			pattern.pattern[i] = dst;
			pattern.mean[i] = cvMean(&((CvMat)dst));
			pattern.norm[i] = cv::norm(dst, NORM_L1);			
			//~ m_patternLibrary.push_back(dst);
		}
	}

	t_atom data_out;
	SETFLOAT(&data_out, m_patternLibrary.size());
	outlet_anything( m_dataout, gensym("patternCount"), 1, &data_out);
}
コード例 #6
0
ファイル: ximaraw.cpp プロジェクト: Sumxx/XUI
bool CxImageRAW::Decode(CxFile *hFile)
{
	if (hFile==NULL)
		return false;

	DCRAW  dcr;

  cx_try
  {
	// initialization
	dcr_init_dcraw(&dcr);

	dcr.opt.user_qual = GetCodecOption(CXIMAGE_FORMAT_RAW) & 0x03;

	// setup variables for debugging
	char szClass[] = "CxImageRAW";
	dcr.ifname = szClass;
	dcr.sz_error = info.szLastError;

	// setup library options, see dcr_print_manual for the available switches
	// call dcr_parse_command_line_options(&dcr,0,0,0) to set default options
	// if (dcr_parse_command_line_options(&dcr,argc,argv,&arg))
	if (dcr_parse_command_line_options(&dcr,0,0,0)){
		cx_throw("CxImageRAW: unknown option");
	}

	// set return point for error handling
	if (setjmp (dcr.failure)) {
		cx_throw("");
	}

	// install file manager
	CxFileRaw src(hFile,&dcr);

	// check file header
	dcr_identify(&dcr);
	
	if(!dcr.is_raw){
		cx_throw("CxImageRAW: not a raw image");
	}

	if (dcr.load_raw == NULL) {
		cx_throw("CxImageRAW: missing raw decoder");
	}

	// verify special case
	if (dcr.load_raw == dcr_kodak_ycbcr_load_raw) {
		dcr.height += dcr.height & 1;
		dcr.width  += dcr.width  & 1;
	}

	if (info.nEscape == -1){
		head.biWidth = dcr.width;
		head.biHeight= dcr.height;
		info.dwType = CXIMAGE_FORMAT_RAW;
		cx_throw("output dimensions returned");
	}

	// shrinked decoding available and requested?
	dcr.shrink = dcr.filters && (dcr.opt.half_size || dcr.opt.threshold || dcr.opt.aber[0] != 1 || dcr.opt.aber[2] != 1);
	dcr.iheight = (dcr.height + dcr.shrink) >> dcr.shrink;
	dcr.iwidth  = (dcr.width  + dcr.shrink) >> dcr.shrink;

	// install custom camera matrix
	if (dcr.opt.use_camera_matrix && dcr.cmatrix[0][0] > 0.25) {
		memcpy (dcr.rgb_cam, dcr.cmatrix, sizeof dcr.cmatrix);
		dcr.raw_color = 0;
	} else {
      dcr.opt.use_camera_wb = 1;
    }

	// allocate memory for the image
	dcr.image = (ushort (*)[4]) calloc (dcr.iheight*dcr.iwidth, sizeof *dcr.image);
	dcr_merror (&dcr, dcr.image, szClass);

	if (dcr.meta_length) {
		dcr.meta_data = (char *) malloc (dcr.meta_length);
		dcr_merror (&dcr, dcr.meta_data, szClass);
	}

	// start image decoder
	hFile->Seek(dcr.data_offset, SEEK_SET);
	(*dcr.load_raw)(&dcr);

	// post processing
	if (dcr.zero_is_bad) dcr_remove_zeroes(&dcr);

	dcr_bad_pixels(&dcr,dcr.opt.bpfile);

	if (dcr.opt.dark_frame) dcr_subtract (&dcr,dcr.opt.dark_frame);

	dcr.quality = 2 + !dcr.fuji_width;

	if (dcr.opt.user_qual >= 0) dcr.quality = dcr.opt.user_qual;

	if (dcr.opt.user_black >= 0) dcr.black = dcr.opt.user_black;

	if (dcr.opt.user_sat >= 0) dcr.maximum = dcr.opt.user_sat;

#ifdef COLORCHECK
	dcr_colorcheck(&dcr);
#endif

#if RESTRICTED
	if (dcr.is_foveon && !dcr.opt.document_mode) dcr_foveon_interpolate(&dcr);
#endif

	if (!dcr.is_foveon && dcr.opt.document_mode < 2) dcr_scale_colors(&dcr);

	// pixel interpolation and filters
	dcr_pre_interpolate(&dcr);

	if (dcr.filters && !dcr.opt.document_mode) {
		if (dcr.quality == 0)
			dcr_lin_interpolate(&dcr);
		else if (dcr.quality == 1 || dcr.colors > 3)
			dcr_vng_interpolate(&dcr);
		else if (dcr.quality == 2)
			dcr_ppg_interpolate(&dcr);
		else
			dcr_ahd_interpolate(&dcr);
	}

	if (dcr.mix_green) {
		int32_t i;
		for (dcr.colors=3, i=0; i < dcr.height*dcr.width; i++) {
			dcr.image[i][1] = (dcr.image[i][1] + dcr.image[i][3]) >> 1;
		}
	}

	if (!dcr.is_foveon && dcr.colors == 3) dcr_median_filter(&dcr);

	if (!dcr.is_foveon && dcr.opt.highlight == 2) dcr_blend_highlights(&dcr);

	if (!dcr.is_foveon && dcr.opt.highlight > 2) dcr_recover_highlights(&dcr);

	if (dcr.opt.use_fuji_rotate) dcr_fuji_rotate(&dcr);

#ifndef NO_LCMS
	if (dcr.opt.cam_profile) dcr_apply_profile (dcr.opt.cam_profile, dcr.opt.out_profile);
#endif

	// final conversion
	dcr_convert_to_rgb(&dcr);

	if (dcr.opt.use_fuji_rotate) dcr_stretch(&dcr);

	dcr.iheight = dcr.height;
	dcr.iwidth  = dcr.width;
	if (dcr.flip & 4) SWAP(dcr.height,dcr.width);

	// ready to transfer data from dcr.image
	if (!Create(dcr.width,dcr.height,24,CXIMAGE_FORMAT_RAW)){
		cx_throw("");
	}

	uchar  *ppm = (uchar *) calloc (dcr.width, dcr.colors*dcr.opt.output_bps/8);
	ushort *ppm2 = (ushort *) ppm;
	dcr_merror (&dcr, ppm, szClass);

	uchar lut[0x10000];
	if (dcr.opt.output_bps == 8) dcr_gamma_lut (&dcr, lut);

	int32_t c, row, col, soff, rstep, cstep;
	soff  = dcr_flip_index (&dcr, 0, 0);
	cstep = dcr_flip_index (&dcr, 0, 1) - soff;
	rstep = dcr_flip_index (&dcr, 1, 0) - dcr_flip_index (&dcr, 0, dcr.width);
	for (row=0; row < dcr.height; row++, soff += rstep) {
		for (col=0; col < dcr.width; col++, soff += cstep) {
			if (dcr.opt.output_bps == 8)
				for (c=0; c < dcr.colors; c++) ppm [col*dcr.colors+c] = lut[dcr.image[soff][c]];
			else
				for (c=0; c < dcr.colors; c++) ppm2[col*dcr.colors+c] = dcr.image[soff][c];
		}
		if (dcr.opt.output_bps == 16 && !dcr.opt.output_tiff && htons(0x55aa) != 0x55aa)
#if defined(_LINUX) || defined(__APPLE__)
			swab ((char*)ppm2, (char*)ppm2, dcr.width*dcr.colors*2);
#else
			_swab ((char*)ppm2, (char*)ppm2, dcr.width*dcr.colors*2);
#endif

		uint32_t size = dcr.width * (dcr.colors*dcr.opt.output_bps/8);
		RGBtoBGR(ppm,size);
		memcpy(GetBits(dcr.height - 1 - row), ppm, min(size,GetEffWidth()));
	}
	free (ppm);


	dcr_cleanup_dcraw(&dcr);

  } cx_catch {
コード例 #7
0
ファイル: OggVorbisLoader.cpp プロジェクト: katik/naali
bool LoadOggVorbisFromFileInMemory(const u8 *fileData, size_t numBytes, std::vector<u8> &dst, bool *isStereo, bool *is16Bit, int *frequency)
{
    if (!fileData || numBytes == 0)
    {
        LogError("Null input data passed in");
        return false;
    }

    if (!isStereo || !is16Bit || !frequency)
    {
        LogError("Outputs not set");
        return false;
    }
    
#ifndef TUNDRA_NO_AUDIO
    OggVorbis_File vf;
    OggMemDataSource src(fileData, numBytes);
    
    ov_callbacks cb;
    cb.read_func = &OggReadCallback;
    cb.seek_func = &OggSeekCallback;
    cb.tell_func = &OggTellCallback;
    cb.close_func = 0;
                   
    int ret = ov_open_callbacks(&src, &vf, 0, 0, cb);
    if (ret < 0)
    {
        LogError("Not ogg vorbis format");
        ov_clear(&vf);
        return false;
    }
    
    vorbis_info* vi = ov_info(&vf, -1);
    if (!vi)
    {
        LogError("No ogg vorbis stream info");
        ov_clear(&vf);
        return false;
    }

    std::ostringstream msg;
    msg << "Decoding ogg vorbis stream with " << vi->channels << " channels, frequency " << vi->rate; 
//    LogDebug(msg.str()); 

    *frequency = vi->rate;
    *isStereo = (vi->channels > 1);
    if (vi->channels != 1 && vi->channels != 2)
        LogWarning("Warning: Loaded Ogg Vorbis data contains an unsupported number of channels: " + QString::number(vi->channels));

    uint decoded_bytes = 0;
    dst.clear();
    for(;;)
    {
        static const int MAX_DECODE_SIZE = 16384;
        dst.resize(decoded_bytes + MAX_DECODE_SIZE);
        int bitstream;
        long ret = ov_read(&vf, (char*)&dst[decoded_bytes], MAX_DECODE_SIZE, 0, 2, 1, &bitstream);
        if (ret <= 0)
            break;
        decoded_bytes += ret;
    }
    
    dst.resize(decoded_bytes);

    {
        std::ostringstream msg;
        msg << "Decoded " << decoded_bytes << " bytes of ogg vorbis sound data";
//        LogDebug(msg.str());
    }
     
    ov_clear(&vf);
    return true;
#else
    return false;
#endif
}
コード例 #8
0
MStatus slopeShaderBehavior::connectNodeToNode( MObject &sourceNode, MObject &destinationNode, bool force )
//
//	Description:
//		Overloaded function from MPxDragAndDropBehavior
//	this method will handle the connection between the slopeShader and the shader it is
//	assigned to as well as any meshes that it is assigned to. 
//
{
	MStatus result = MS::kFailure;
	MFnDependencyNode src(sourceNode);

	//if we are dragging from a lambert
	//we want to check what we are dragging
	//onto.
	if(sourceNode.hasFn(MFn::kLambert))
	{
		MObject shaderNode;
		MPlugArray connections;
		MObjectArray shaderNodes;
		shaderNodes.clear();

		//if the source node was a lambert
		//than we will check the downstream connections to see 
		//if a slope shader is assigned to it.
		//
		src.getConnections(connections);
		unsigned i;
		for(i = 0; i < connections.length(); i++)
		{
			//check the incoming connections to this plug
			//
			MPlugArray connectedPlugs;
			connections[i].connectedTo(connectedPlugs, true, false);
			for(unsigned j = 0; j < connectedPlugs.length(); j++)
			{
				//if the incoming node is a slope shader than 
				//append the node to the shaderNodes array
				//
				MObject currentnode = connectedPlugs[j].node();
				if(MFnDependencyNode(currentnode).typeName() == "slopeShader")
				{
					shaderNodes.append(currentnode);
				}
			}
		}

		//if we found a shading node
		//than check the destination node 
		//type to see if it is a mesh
		//
		if(shaderNodes.length() > 0)
		{
			MFnDependencyNode dest(destinationNode);
			if(destinationNode.hasFn(MFn::kMesh))
			{
				//if the node is a mesh than for each slopeShader
				//connect the worldMesh attribute to the dirtyShaderPlug
				//attribute to force an evaluation of the node when the mesh
				//changes
				//
				for(i = 0; i < shaderNodes.length(); i++)
				{
					MPlug srcPlug = dest.findPlug("worldMesh");
					MPlug destPlug = MFnDependencyNode(shaderNodes[i]).findPlug("dirtyShaderPlug");

					if(!srcPlug.isNull() && !destPlug.isNull())
					{
						MString cmd = "connectAttr -na ";
						cmd += srcPlug.name() + " ";
						cmd += destPlug.name();
						MGlobal::executeCommand(cmd);
					}
				}

				//get the shading engine so we can assign the shader
				//to the mesh after doing the connection
				//
				MObject shadingEngine = findShadingEngine(sourceNode);

				//if there is a valid shading engine than make
				//the connection
				//
				if(!shadingEngine.isNull())
				{
					MString cmd = "sets -edit -forceElement ";
					cmd += MFnDependencyNode(shadingEngine).name() + " ";
					cmd += MFnDagNode(destinationNode).partialPathName();
					result = MGlobal::executeCommand(cmd);
				}
			}
		}
	}
	else if(src.typeName() == "slopeShader")
	//if we are dragging from a slope shader
	//than we want to see what we are dragging onto
	//
	{
		if(destinationNode.hasFn(MFn::kMesh))
		{
			//if the user is dragging onto a mesh
			//than make the connection from the worldMesh
			//to the dirtyShader plug on the slopeShader
			//
			MFnDependencyNode dest(destinationNode);
			MPlug srcPlug = dest.findPlug("worldMesh");
			MPlug destPlug = src.findPlug("dirtyShaderPlug");
			if(!srcPlug.isNull() && !destPlug.isNull())
			{
				MString cmd = "connectAttr -na ";
				cmd += srcPlug.name() + " ";
				cmd += destPlug.name();
				result = MGlobal::executeCommand(cmd);
			}
		}
	}

	return result;
}
コード例 #9
0
bool slopeShaderBehavior::shouldBeUsedFor( MObject &sourceNode, MObject &destinationNode,
										   MPlug &sourcePlug, MPlug &destinationPlug)
//
//	Description:
//		Overloaded function from MPxDragAndDropBehavior
//	this method will return true if it is going to handle the connection
//	between the two nodes given.
//
{
	bool result = false;

	if(sourceNode.hasFn(MFn::kLambert))
	{
		//if the source node was a lambert
		//than we will check the downstream connections to see 
		//if a slope shader is assigned to it.
		//
		MObject shaderNode;
		MFnDependencyNode src(sourceNode);
		MPlugArray connections;

		src.getConnections(connections);
		for(unsigned i = 0; i < connections.length(); i++)
		{
			//check the incoming connections to this plug
			//
			MPlugArray connectedPlugs;
			connections[i].connectedTo(connectedPlugs, true, false);
			for(unsigned j = 0; j < connectedPlugs.length(); j++)
			{
				//if the incoming node is a slope shader than 
				//set shaderNode equal to it and break out of the inner 
				//loop
				//
				if(MFnDependencyNode(connectedPlugs[j].node()).typeName() == "slopeShader")
				{
					shaderNode = connectedPlugs[j].node();
					break;
				}
			}

			//if the shaderNode is not null
			//than we have found a slopeShader
			//
			if(!shaderNode.isNull())
			{
				//if the destination node is a mesh than we will take
				//care of this connection so set the result to true
				//and break out of the outer loop
				//
				if(destinationNode.hasFn(MFn::kMesh))
					result = true;

				break;
			}
		}
	}
	if(MFnDependencyNode(sourceNode).typeName() == "slopeShader")
	//if the sourceNode is a slope shader than check what we
	//are dropping on to
	//
	{
		if(destinationNode.hasFn(MFn::kLambert))
			result = true;
		else if(destinationNode.hasFn(MFn::kMesh))
			result = true;
	}	

	return result;
}
コード例 #10
0
ファイル: MapFile.cpp プロジェクト: Salamek/Shadow-of-Dust
/*
===============
idMapFile::Parse
===============
*/
bool idMapFile::Parse( const char *filename, bool ignoreRegion, bool osPath ) {
	// no string concatenation for epairs and allow path names for materials
	idLexer src( LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS | LEXFL_ALLOWPATHNAMES );
	idToken token;
	idStr fullName;
	idMapEntity *mapEnt;
	int i, j, k;

	name = filename;
	name.StripFileExtension();
	fullName = name;
	hasPrimitiveData = false;

	if ( !ignoreRegion ) {
		// try loading a .reg file first
		fullName.SetFileExtension( "reg" );
		src.LoadFile( fullName, osPath );
	}

	if ( !src.IsLoaded() ) {
		// now try a .map file
		fullName.SetFileExtension( "map" );
		src.LoadFile( fullName, osPath );
		if ( !src.IsLoaded() ) {
			// didn't get anything at all
			return false;
		}
	}

	version = OLD_MAP_VERSION;
	fileTime = src.GetFileTime();
	entities.DeleteContents( true );

	if ( src.CheckTokenString( "Version" ) ) {
		src.ReadTokenOnLine( &token );
		version = token.GetFloatValue();
	}

	while( 1 ) {
		mapEnt = idMapEntity::Parse( src, ( entities.Num() == 0 ), version );
		if ( !mapEnt ) {
			break;
		}
		entities.Append( mapEnt );
	}

	SetGeometryCRC();

	// if the map has a worldspawn
	if ( entities.Num() ) {

		// "removeEntities" "classname" can be set in the worldspawn to remove all entities with the given classname
		const idKeyValue *removeEntities = entities[0]->epairs.MatchPrefix( "removeEntities", NULL );
		while ( removeEntities ) {
			RemoveEntities( removeEntities->GetValue() );
			removeEntities = entities[0]->epairs.MatchPrefix( "removeEntities", removeEntities );
		}

		// "overrideMaterial" "material" can be set in the worldspawn to reset all materials
		idStr material;
		if ( entities[0]->epairs.GetString( "overrideMaterial", "", material ) ) {
			for ( i = 0; i < entities.Num(); i++ ) {
				mapEnt = entities[i];
				for ( j = 0; j < mapEnt->GetNumPrimitives(); j++ ) {
					idMapPrimitive *mapPrimitive = mapEnt->GetPrimitive( j );
					switch( mapPrimitive->GetType() ) {
						case idMapPrimitive::TYPE_BRUSH: {
							idMapBrush *mapBrush = static_cast<idMapBrush *>(mapPrimitive);
							for ( k = 0; k < mapBrush->GetNumSides(); k++ ) {
								mapBrush->GetSide( k )->SetMaterial( material );
							}
							break;
						}
						case idMapPrimitive::TYPE_PATCH: {
							static_cast<idMapPatch *>(mapPrimitive)->SetMaterial( material );
							break;
						}
					}
				}
			}
		}

		// force all entities to have a name key/value pair
		if ( entities[0]->epairs.GetBool( "forceEntityNames" ) ) {
			for ( i = 1; i < entities.Num(); i++ ) {
				mapEnt = entities[i];
				if ( !mapEnt->epairs.FindKey( "name" ) ) {
					mapEnt->epairs.Set( "name", va( "%s%d", mapEnt->epairs.GetString( "classname", "forcedName" ), i ) );
				}
			}
		}

		// move the primitives of any func_group entities to the worldspawn
		if ( entities[0]->epairs.GetBool( "moveFuncGroups" ) ) {
			for ( i = 1; i < entities.Num(); i++ ) {
				mapEnt = entities[i];
				if ( idStr::Icmp( mapEnt->epairs.GetString( "classname" ), "func_group" ) == 0 ) {
					entities[0]->primitives.Append( mapEnt->primitives );
					mapEnt->primitives.Clear();
				}
			}
		}
	}

	hasPrimitiveData = true;
	return true;
}
コード例 #11
0
/*
 =======================================================================================================================
    Map_SaveFile
 =======================================================================================================================
 */
bool Map_SaveFile(const char *filename, bool use_region, bool autosave)
{
	entity_t	*e, *next;
	idStr		temp;
	int			count;
	brush_t		*b;
	idStr status;

	int len = strlen(filename);
	WIN32_FIND_DATA FileData;

	if (FindFirstFile(filename, &FileData) != INVALID_HANDLE_VALUE) {
		// the file exists;
		if (len > 0 && GetFileAttributes(filename) & FILE_ATTRIBUTE_READONLY) {
			g_pParentWnd->MessageBox("File is read only", "Read Only", MB_OK);
			return false;
		}
	}

	if (filename == NULL || len == 0 || (filename && stricmp(filename, "unnamed.map") == 0)) {
		CFileDialog dlgSave(FALSE,"map",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"Map Files (*.map)|*.map||",AfxGetMainWnd());

		if (dlgSave.DoModal() == IDOK) {
			filename = dlgSave.m_ofn.lpstrFile;
			strcpy(currentmap, filename);
		} else {
			return false;
		}
	}

	MEMORYSTATUSEX statex;
	statex.dwLength = sizeof(statex);
	GlobalMemoryStatusEx(&statex);

	if (statex.dwMemoryLoad > 95) {
		g_pParentWnd->MessageBox("Physical memory is over 95% utilized. Consider saving and restarting", "Memory");
	}

	CWaitDlg dlg;
	Pointfile_Clear();

	temp = filename;
	temp.BackSlashesToSlashes();

	if (!use_region) {
		idStr backup;
		backup = temp;
		backup.StripFileExtension();
		backup.SetFileExtension(".bak");

		if (_unlink(backup) != 0 && errno != 2) {   // errno 2 means the file doesn't exist, which we don't care about
			g_pParentWnd->MessageBox(va("Unable to delete %s: %s", backup.c_str(), strerror(errno)), "File Error");
		}

		if (rename(filename, backup) != 0) {
			g_pParentWnd->MessageBox(va("Unable to rename %s to %s: %s", filename, backup.c_str(), strerror(errno)), "File Error");
		}
	}

	common->Printf("Map_SaveFile: %s\n", filename);

	idStr mapFile;
	bool localFile = (strstr(filename, ":") != NULL);

	if (autosave || localFile) {
		mapFile = filename;
	} else {
		mapFile = fileSystem->OSPathToRelativePath(filename);
	}

	if (use_region) {
		AddRegionBrushes();
	}

	idMapFile map;
	world_entity->origin.Zero();
	idMapEntity *mapentity = EntityToMapEntity(world_entity, use_region, &dlg);
	dlg.SetText("Saving worldspawn...");
	map.AddEntity(mapentity);

	if (use_region) {
		idStr buf;
		sprintf(buf, "{\n\"classname\"    \"info_player_start\"\n\"origin\"\t \"%i %i %i\"\n\"angle\"\t \"%i\"\n}\n",
		        (int)g_pParentWnd->GetCamera()->Camera().origin[0],
		        (int)g_pParentWnd->GetCamera()->Camera().origin[1],
		        (int)g_pParentWnd->GetCamera()->Camera().origin[2],
		        (int)g_pParentWnd->GetCamera()->Camera().angles[YAW]);
		idLexer src(LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS | LEXFL_ALLOWPATHNAMES);
		src.LoadMemory(buf, buf.Length(), "regionbuf");
		idMapEntity *playerstart = idMapEntity::Parse(src);
		map.AddEntity(playerstart);
	}

	count = -1;

	for (e = entities.next; e != &entities; e = next) {
		count++;
		next = e->next;

		if (e->brushes.onext == &e->brushes) {
			Entity_Free(e); // no brushes left, so remove it
		} else {
			if (use_region) {
				for (b = e->brushes.onext; b != &e->brushes; b = b->onext) {
					if (!Map_IsBrushFiltered(b)) {
						break;	// got one
					}
				}

				if (b == &e->brushes) {
					continue;		// nothing visible
				}

			}

			idVec3 origin;

			if (!GetVectorForKey(e, "origin", origin)) {
				idStr text;
				VectorSubtract(e->brushes.onext->mins, e->eclass->mins, origin);
				sprintf(text, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
				SetKeyValue(e, "origin", text);
			}

			if (use_region && !idStr::Icmp(ValueForKey(e, "classname"), "info_player_start")) {
				continue;
			}

			idStr classname = e->epairs.GetString("classname");
			sprintf(status, "Saving entity %i (%s)...", count, classname.c_str());
			dlg.SetText(status);

			map.AddEntity(EntityToMapEntity(e, use_region, &dlg));
			count++;
		}
	}

	mapFile.StripFileExtension();
	idStr mapExt = (use_region) ? ".reg" : ".map";
	sprintf(status, "Writing file %s.%s...", mapFile.c_str(), mapExt.c_str());
	dlg.SetText(status);
	map.Write(mapFile, mapExt, !(autosave || localFile));
	mapModified = 0;

	if (use_region) {
		RemoveRegionBrushes();
	}

	if (!strstr(temp, "autosave")) {
		Sys_SetTitle(temp);
	}

	Sys_Status("Saved.\n", 0);

	return true;
}
コード例 #12
0
ファイル: ximajas.cpp プロジェクト: AceMood/webpagetest
bool CxImageJAS::Decode(CxFile *hFile, uint32_t imagetype)
{
  if (hFile == NULL) return false;

  jas_image_t *image=0;
  jas_stream_t *in=0;
  jas_matrix_t **bufs=0;
  int32_t i,error=0;
  int32_t fmt;
  //jas_setdbglevel(0);

  cx_try
  {
  if (jas_init())
    cx_throw("cannot initialize jasper");

  in = jas_stream_fdopen(0, "rb");
  if (!in)
    cx_throw("error: cannot open standard input");

  CxFileJas src(hFile,in);

  fmt = jas_image_getfmt(in);
  if (fmt<0)
    cx_throw("error: unknowm format");

  image = jas_image_decode(in, fmt, 0);
  if (!image){
    fmt = -1;
    cx_throw("error: cannot load image data");
  }

  char szfmt[4];
  *szfmt = '\0';
  strncpy(szfmt,jas_image_fmttostr(fmt),3);
  szfmt[3] = '\0';

  fmt = -1;
#if CXIMAGE_SUPPORT_JP2
  if (strcmp(szfmt,"jp2")==0) fmt = CXIMAGE_FORMAT_JP2;
#endif
#if CXIMAGE_SUPPORT_JPC
  if (strcmp(szfmt,"jpc")==0) fmt = CXIMAGE_FORMAT_JPC;
#endif
#if CXIMAGE_SUPPORT_RAS
  if (strcmp(szfmt,"ras")==0) fmt = CXIMAGE_FORMAT_RAS;
#endif
#if CXIMAGE_SUPPORT_PNM
  if (strcmp(szfmt,"pnm")==0) fmt = CXIMAGE_FORMAT_PNM;
#endif
#if CXIMAGE_SUPPORT_PGX
  if (strcmp(szfmt,"pgx")==0) fmt = CXIMAGE_FORMAT_PGX;
#endif

  //if (fmt<0)
  //	cx_throw("error: unknowm format");

  int32_t x,y,w,h,depth,cmptno;

  w = jas_image_cmptwidth(image,0);
  h = jas_image_cmptheight(image,0);
  depth = jas_image_cmptprec(image,0);

  if (info.nEscape == -1){
    head.biWidth = w;
    head.biHeight= h;
    info.dwType = fmt<0 ? 0 : fmt;
    cx_throw("output dimensions returned");
  }

  if (image->numcmpts_ > 64 || image->numcmpts_ < 0)
    cx_throw("error: too many components");

  // <LD> 01/Jan/2005: Always force conversion to sRGB. Seems to be required for many types of JPEG2000 file.
  // if (depth!=1 && depth!=4 && depth!=8)
  if (image->numcmpts_>=3 && depth <=8)
  {
    jas_image_t *newimage;
    jas_cmprof_t *outprof;
    //jas_eprintf("forcing conversion to sRGB\n");
    outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB);
    if (!outprof) {
      cx_throw("cannot create sRGB profile");
    }
    newimage = jas_image_chclrspc(image, outprof, JAS_CMXFORM_INTENT_PER);
    if (!newimage) {
      jas_cmprof_destroy(outprof); // <LD> 01/Jan/2005: Destroy color profile on error.
      cx_throw("cannot convert to sRGB");
    }
    jas_image_destroy(image);
    jas_cmprof_destroy(outprof);
    image = newimage;
  }

  bufs = (jas_matrix_t **)calloc(image->numcmpts_, sizeof(jas_matrix_t**));
  for (i = 0; i < image->numcmpts_; ++i) {
    bufs[i] = jas_matrix_create(1, w);
    if (!bufs[i]) {
      cx_throw("error: cannot allocate memory");
    }
  }

  int32_t nshift = (depth>8) ? (depth-8) : 0;

  if (image->numcmpts_==3 &&
    image->cmpts_[0]->width_ == image->cmpts_[1]->width_ &&
    image->cmpts_[1]->width_ == image->cmpts_[2]->width_ &&
    image->cmpts_[0]->height_ == image->cmpts_[1]->height_ &&
    image->cmpts_[1]->height_ == image->cmpts_[2]->height_ &&
    image->cmpts_[0]->prec_  == image->cmpts_[1]->prec_ &&
    image->cmpts_[1]->prec_ == image->cmpts_[2]->prec_ )
  {

    if(!Create(w,h,24,fmt))
      cx_throw("");

    RGBQUAD c;
        for (y=0; y<h; y++) {
      for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
        jas_image_readcmpt(image, cmptno, 0, y, w, 1, bufs[cmptno]);
      }

      for (x=0; x<w; x++){
        c.rgbRed   = (uint8_t)((jas_matrix_getv(bufs[0], x)>>nshift));
        c.rgbGreen = (uint8_t)((jas_matrix_getv(bufs[1], x)>>nshift));
        c.rgbBlue  = (uint8_t)((jas_matrix_getv(bufs[2], x)>>nshift));
        SetPixelColor(x,h-1-y,c);
      }
    }
  } else {
    info.nNumFrames = image->numcmpts_;
    if ((info.nFrame<0)||(info.nFrame>=info.nNumFrames)){
      cx_throw("wrong frame!");
    }
    for (cmptno=0; cmptno<=info.nFrame; cmptno++) {
      w = jas_image_cmptwidth(image,cmptno);
      h = jas_image_cmptheight(image,cmptno);
      depth = jas_image_cmptprec(image,cmptno);
      if (depth>8) depth=8;
      if(!Create(w,h,depth,imagetype))
        cx_throw("");
      SetGrayPalette();
      for (y=0; y<h; y++) {
        jas_image_readcmpt(image, cmptno, 0, y, w, 1, bufs[0]);
        for (x=0; x<w; x++){
          SetPixelIndex(x,h-1-y,(uint8_t)((jas_matrix_getv(bufs[0], x)>>nshift)));
        }
      }
    }
  }


  } cx_catch {
コード例 #13
0
ファイル: OverlayData.cpp プロジェクト: antdricot/TuttleOFX
/**
 * Compute full data (averages,histograms buffer and selection buffer)
 * @param clipSrc	source of the plugin
 * @param time	current time
 * @param renderScale	current renderScale
 */
void OverlayData::computeFullData( OFX::Clip* clipSrc, const OfxTime time, const OfxPointD& renderScale, const bool selectionOnly )
{
	_isComputing = true;
	resetHistogramData();
	resetHistogramSelectionData();
	
	if( ! clipSrc->isConnected() )
	{	
		_isComputing = false;
		return;
	}
	
	//TUTTLE_TCOUT_INFOS;
	//TUTTLE_TCOUT_VAR( "computeHistogramBufferData - fetchImage " << time );
	boost::scoped_ptr<OFX::Image> src( clipSrc->fetchImage(time, clipSrc->getCanonicalRod(time)) );	//scoped pointer of current source clip
	//TUTTLE_TCOUT_INFOS;
	
	//TUTTLE_TCOUT_VAR( clipSrc->getPixelRod(time, renderScale) );
	//TUTTLE_TCOUT_VAR( clipSrc->getCanonicalRod(time, renderScale) );
	
	// Compatibility tests
	if( !src.get() ) // source isn't accessible
	{
		_isComputing = false;
		std::cout << "src is not accessible" << std::endl;
		return;
	}
	
//	TUTTLE_TCOUT_VAR( src->getBounds() );
//	TUTTLE_TCOUT_VAR( src->getRegionOfDefinition() );

	if( src->getRowBytes() == 0 )//if source is wrong
	{
		BOOST_THROW_EXCEPTION( exception::WrongRowBytes() );
	}
	OfxRectI srcPixelRod = clipSrc->getPixelRod( time, renderScale ); //get current RoD
	if( (clipSrc->getPixelDepth() != OFX::eBitDepthFloat) ||
		(!clipSrc->getPixelComponents()) )
	{
		BOOST_THROW_EXCEPTION( exception::Unsupported()	<< exception::user() + "Can't compute histogram data with the actual input clip format." );
        return;
	}
	
//	TUTTLE_TCOUT_INFOS;
//	BOOST_ASSERT( srcPixelRod == src->getBounds() );
	if( srcPixelRod != src->getBounds() )
	{
		// the host does bad things !
		// remove overlay... but do not crash.
		TUTTLE_COUT_WARNING( "Image RoD and image bounds are not the same (rod=" << srcPixelRod << " , bounds:" << src->getBounds() << ")." );
		return;
	}
//	BOOST_ASSERT( srcPixelRod.x1 == src->getBounds().x1 );
//	BOOST_ASSERT( srcPixelRod.y1 == src->getBounds().y1 );
//	BOOST_ASSERT( srcPixelRod.x2 == src->getBounds().x2 );
//	BOOST_ASSERT( srcPixelRod.y2 == src->getBounds().y2 );
	
	// Compute if source is OK
	SView srcView = tuttle::plugin::getView<SView>( src.get(), srcPixelRod );	// get current view from source clip
	
	OfxPointI imgSize;
	imgSize.x = srcView.width();
	imgSize.y = srcView.height();
	
//	TUTTLE_TCOUT_INFOS;
	if( isImageSizeModified( imgSize ) )
	{
		//TUTTLE_TCOUT_INFOS;
		clearAll( imgSize );
	}
	
	//TUTTLE_TCOUT_INFOS;
	//Compute histogram buffer
	this->computeHistogramBufferData( _data, srcView, time);
	
	//TUTTLE_TCOUT_INFOS;
	//Compute selection histogram buffer
	this->computeHistogramBufferData( _selectionData, srcView, time, true );
	
	//TUTTLE_TCOUT_INFOS;
	//Compute averages
	this->computeAverages();
	_isComputing = false;
	
	_currentTime = time;
	//TUTTLE_TCOUT_INFOS;
}
コード例 #14
0
/*
================
rvGEWorkspace::WriteWindow

Writes the contents of the given window to the file
================
*/
bool rvGEWorkspace::WriteWindow( idFile *file, int depth, idWindow *window ) {
	idStr				out;
	rvGEWindowWrapper	*wrapper;
	int					i;
	wrapper = rvGEWindowWrapper::GetWrapper( window );
	if( !wrapper ) {
		return true;
	}
	if( wrapper->IsDeleted( ) ) {
		return true;
	}
	// Window def header
	WriteTabs( file, depth - 1 );
	out = wrapper->WindowTypeToString( wrapper->GetWindowType( ) );
	out.Append( " " );
	file->Write( out, out.Length() );
	out = window->GetName( );
	file->Write( out, out.Length() );
	file->Write( "\r\n", 2 );
	WriteTabs( file, depth - 1 );
	out = "{\r\n";
	file->Write( out, out.Length() );
	file->ForceFlush( );
	for( i = 0; i < wrapper->GetStateDict().GetNumKeyVals(); i ++ ) {
		const idKeyValue *key = wrapper->GetStateDict().GetKeyVal( i );
		// Dont write name to the files
		if( !key->GetKey().Icmp( "name" ) ) {
			continue;
		}
		WriteTabs( file, depth );
		out = key->GetKey();
		out.Append( "\t" );
		file->Write( out, out.Length() );
		const char *p;
		for( p = key->GetValue().c_str(); *p; p ++ ) {
			switch( *p ) {
			case '\n':
				file->Write( "\\n", 2 );
				break;
			default:
				file->Write( p, 1 );
				break;
			}
		}
		file->Write( "\r\n", 2 );
	}
	for( i = 0; i < wrapper->GetVariableDict().GetNumKeyVals(); i ++ ) {
		const idKeyValue *key = wrapper->GetVariableDict().GetKeyVal( i );
		WriteTabs( file, depth );
		out = key->GetKey();
		out.Append( "\t" );
		out.Append( key->GetValue() );
		out.Append( "\r\n" );
		file->Write( out, out.Length() );
	}
	if( wrapper->GetScriptDict().GetNumKeyVals() ) {
		file->Write( "\r\n", 2 );
	}
	for( i = 0; i < wrapper->GetScriptDict().GetNumKeyVals(); i ++ ) {
		const idKeyValue *key = wrapper->GetScriptDict().GetKeyVal( i );
		WriteTabs( file, depth );
		file->Write( key->GetKey(), key->GetKey().Length() );
		file->Write( " ", 1 );
		idLexer src( key->GetValue(), key->GetValue().Length(), "", LEXFL_ALLOWMULTICHARLITERALS | LEXFL_NOSTRINGCONCAT | LEXFL_ALLOWBACKSLASHSTRINGCONCAT );
		src.ParseBracedSectionExact( out, depth + 1 );
		file->Write( out, out.Length() );
		file->Write( "\r\n", 2 );
		file->Write( "\r\n", 2 );
	}
	for( i = 0; i < wrapper->GetChildCount(); i ++ ) {
		idWindow *child = wrapper->GetChild( i );
		WriteWindow( file, depth + 1, child );
	}
	// Window def footer
	WriteTabs( file, depth - 1 );
	out = "}\r\n";
	file->Write( out, out.Length() );
	file->ForceFlush( );
	return true;
}
コード例 #15
0
ファイル: io.hpp プロジェクト: acoffman/streamgraph
 inline
 std::string read_file(std::string const& path) {
     boost::iostreams::mapped_file_source src(path);
     return std::string(src.data(), src.size());
 }
コード例 #16
0
int main(int argc, char* argv[])
{
  // Define nonlinear thermal conductivity lambda(u) via a cubic spline.
  // Step 1: Fill the x values and use lambda_macro(u) = 1 + u^4 for the y values.
#define lambda_macro(x) (1 + Hermes::pow(x, 4))
  Hermes::vector<double> lambda_pts(-2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0);
  Hermes::vector<double> lambda_val;
  for (unsigned int i = 0; i < lambda_pts.size(); i++) 
    lambda_val.push_back(lambda_macro(lambda_pts[i]));
  // Step 2: Create the cubic spline (and plot it for visual control). 
  double bc_left = 0.0;
  double bc_right = 0.0;
  bool first_der_left = false;
  bool first_der_right = false;
  bool extrapolate_der_left = true;
  bool extrapolate_der_right = true;
  CubicSpline lambda(lambda_pts, lambda_val, bc_left, bc_right, first_der_left, first_der_right,
                     extrapolate_der_left, extrapolate_der_right);
  info("Saving cubic spline into a Pylab file spline.dat.");
  double interval_extension = 3.0; // The interval of definition of the spline will be 
                                   // extended by "interval_extension" on both sides.
  lambda.plot("spline.dat", interval_extension);

  // Load the mesh.
  Mesh mesh;
  MeshReaderH2D mloader;
  mloader.load("square.mesh", &mesh);

  // Perform initial mesh refinements.
  for(int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh.refine_all_elements();
  mesh.refine_towards_boundary("Bdy", INIT_BDY_REF_NUM);

  // Initialize boundary conditions.
  CustomEssentialBCNonConst bc_essential("Bdy");
  EssentialBCs<double> bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space<double> space(&mesh, &bcs, P_INIT);
  int ndof = space.get_num_dofs();
  info("ndof: %d", ndof);

  // Initialize the weak formulation.
  Hermes2DFunction<double> src(-heat_src);
  DefaultWeakFormPoisson<double> wf(HERMES_ANY, &lambda, &src);

  // Initialize the FE problem.
  DiscreteProblem<double> dp(&wf, &space);

  // Project the initial condition on the FE space to obtain initial 
  // coefficient vector for the Newton's method.
  // NOTE: If you want to start from the zero vector, just define 
  // coeff_vec to be a vector of ndof zeros (no projection is needed).
  info("Projecting to obtain initial vector for the Newton's method.");
  double* coeff_vec = new double[ndof];
  CustomInitialCondition init_sln(&mesh);
  OGProjection<double>::project_global(&space, &init_sln, coeff_vec, matrix_solver); 

  // Initialize Newton solver.
  NewtonSolver<double> newton(&dp, matrix_solver);

  // Perform Newton's iteration.
  bool freeze_jacobian = false;
  if (!newton.solve(coeff_vec, NEWTON_TOL, NEWTON_MAX_ITER, freeze_jacobian)) 
    error("Newton's iteration failed.");

  // Translate the resulting coefficient vector into a Solution.
  Solution<double> sln;
  Solution<double>::vector_to_solution(newton.get_sln_vector(), &space, &sln);

  // Get info about time spent during assembling in its respective parts.
  //dp.get_all_profiling_output(std::cout);

  // Clean up.
  delete [] coeff_vec;

  // Visualise the solution and mesh.
  ScalarView s_view("Solution", new WinGeom(0, 0, 440, 350));
  s_view.show_mesh(false);
  s_view.show(&sln);
  OrderView<double> o_view("Mesh", new WinGeom(450, 0, 400, 350));
  o_view.show(&space);

  // Wait for all views to be closed.
  View::wait();
  return 0;
}
コード例 #17
0
/*
 static jobject NativeDecimalFormat_parse(JNIEnv* env, jclass, jint addr, jstring text,
 jobject position, jboolean parseBigDecimal) {
 */
JNIEXPORT jobject JNICALL
Java_com_ibm_icu4jni_text_NativeDecimalFormat_parse(JNIEnv* env, jclass,
        jint addr, jstring text, jobject position, jboolean parseBigDecimal) {

    jclass parsePositionClass = env->FindClass("java/text/ParsePosition");
    static jmethodID gPP_getIndex = env->GetMethodID(parsePositionClass,
                                    "getIndex", "()I");
    static jmethodID gPP_setIndex = env->GetMethodID(parsePositionClass,
                                    "setIndex", "(I)V");
    static jmethodID gPP_setErrorIndex = env->GetMethodID(parsePositionClass,
                                         "setErrorIndex", "(I)V");

    // make sure the ParsePosition is valid. Actually icu4c would parse a number
    // correctly even if the parsePosition is set to -1, but since the RI fails
    // for that case we have to fail too
    int parsePos = env->CallIntMethod(position, gPP_getIndex, NULL);
    if (parsePos < 0 || parsePos > env->GetStringLength(text)) {
        return NULL;
    }

    Formattable res;
    ParsePosition pp(parsePos);
    ScopedJavaUnicodeString src(env, text);
    DecimalFormat* fmt = toDecimalFormat(addr);
    fmt->parse(src.unicodeString(), res, pp);

    if (pp.getErrorIndex() == -1) {
        env->CallVoidMethod(position, gPP_setIndex, (jint) pp.getIndex());
    } else {
        env->CallVoidMethod(position, gPP_setErrorIndex,
                            (jint) pp.getErrorIndex());
        return NULL;
    }

    if (parseBigDecimal) {
        UErrorCode status = U_ZERO_ERROR;
        StringPiece str = res.getDecimalNumber(status);
        if (U_SUCCESS(status)) {
            int len = str.length();
            const char* data = str.data();
            if (strncmp(data, "NaN", 3) == 0 || strncmp(data, "Inf", 3) == 0
                    || strncmp(data, "-Inf", 4) == 0) {
                double resultDouble = res.getDouble(status);
                return doubleValueOf(env, (jdouble) resultDouble);
            }
            return newBigDecimal(env, data, len);
        }
        return NULL;
    }

    Formattable::Type numType = res.getType();
    switch (numType) {
    case Formattable::kDouble: {
        double resultDouble = res.getDouble();
        return doubleValueOf(env, (jdouble) resultDouble);
    }
    case Formattable::kLong: {
        long resultLong = res.getLong();
        return longValueOf(env, (jlong) resultLong);
    }
    case Formattable::kInt64: {
        int64_t resultInt64 = res.getInt64();
        return longValueOf(env, (jlong) resultInt64);
    }
    default: {
        return NULL;
    }
    }
}
コード例 #18
0
ファイル: HexEditorActor.cpp プロジェクト: jijik/portal_game
//========================================================================
void AHexEditorActor::SaveMap(const FString& name)
{
	if (FPaths::FileExists(name))
	{
		//if file exists copy it to backup file to prevent overriding some maps
		auto newName = name;
		std::stringstream ss;	auto t = std::time(nullptr); ss << t;
		newName.Append(ss.str().c_str());
		std::ifstream src(*name, std::ios::binary);
		std::ofstream dst(*newName, std::ios::binary);
		dst << src.rdbuf();
		src.close();
		dst.close();
	}

	std::ofstream file;
	file.open(*name, std::ofstream::binary);
	
	auto& gridStorage = m_Grid.GetStorage();

	binary_write(file, (unsigned)gridStorage.size());
	this->Save(file); //editor tile first
	for (auto& pair : gridStorage)
	{
		if (pair.second != this)
		{
			pair.second->Save(file);
		}
	}

	binary_write(file, (unsigned)m_AllBarriers.size());
	for (auto* barrier : m_AllBarriers)
	{
		barrier->Save(file);
	}

	binary_write(file, (unsigned)m_AllPlatforms.size());
	for (auto* platform : m_AllPlatforms)
	{
		platform->Save(file);
	}

	binary_write(file, (unsigned)m_AllCompanions.size());
	for (auto* companion : m_AllCompanions)
	{
		companion->Save(file);
	}

	binary_write(file, (unsigned)m_AllBlockers.size());
	for (auto* blocker : m_AllBlockers)
	{
		blocker->Save(file);
	}

	binary_write(file, (unsigned)m_AllBridges.size());
	for (auto* bridges : m_AllBridges)
	{
		bridges->Save(file);
	}

	binary_write(file, (unsigned)m_AllTurrets.size());
	for (auto* turret : m_AllTurrets)
	{
		turret->Save(file);
	}

	binary_write(file, (unsigned)m_AllTeleports.size());
	for (auto* t : m_AllTeleports)
	{
		t->Save(file);
	}

	binary_write(file, m_Finish);
	m_Finish->Save(file);

	file.close();
}
コード例 #19
0
  void file_cpi_impl::sync_copy (saga::impl::void_t & ret, 
                                 saga::url            dest, 
                                 int                  flags)
  {
    adaptor_data_t       adata (this);
    file_instance_data_t idata (this);

    // check preconditions
    // We can only check coditions for local targets
    
    if ( saga::adaptors::utils::is_local_address (dest) )
    {
      saga::filesystem::directory loc ("/");

      if ( loc.exists (dest.get_path ()) )
      {
        if ( ! (flags & saga::name_space::Overwrite) )
        {
          std::stringstream ss;
          ss << "Target exists: " << dest;
          SAGA_ADAPTOR_THROW (ss.str (), saga::AlreadyExists);
        }
      }
    }

    std::string src (u_.get_string ());
    std::string tgt (dest.get_string ());


    CURLcode code;

    // get handle for input and output curl ops (see README)
    CURL * in  = adata->get_curl_handle_in  ();
    CURL * out = adata->get_curl_handle_out ();

    // create buffer file
    FILE * buf = ::fopen ("/tmp/curl-cache.dat", "w+");
    ensure (NULL != buf, "fopen() failed: ", ::strerror (errno));

    // read data into buffer
    code = curl_easy_setopt (in, CURLOPT_URL, src.c_str ());
    ensure (0 == code, "Curl Error: ", curl_easy_strerror (code));

    code = curl_easy_setopt (in, CURLOPT_WRITEDATA, buf);
    ensure (0 == code, "Curl Error: ", curl_easy_strerror (code));

    code = curl_easy_perform (in);
    ensure (0 == code, "Curl Error: ", curl_easy_strerror (code));


    // data are in buffer - now rewind buffer, and copy data to target location
    ::rewind (buf);

    code = curl_easy_setopt (out, CURLOPT_URL, tgt.c_str ());
    ensure (0 == code, "Curl Error: ", curl_easy_strerror (code));

    code = curl_easy_setopt (out, CURLOPT_VERBOSE, "true");
    ensure (0 == code, "Curl Error: ", curl_easy_strerror (code));

    code = curl_easy_setopt (out, CURLOPT_USERPWD, "merzky:Z(I)nfandel");
    ensure (0 == code, "Curl Error: ", curl_easy_strerror (code));

    code = curl_easy_setopt (out, CURLOPT_UPLOAD, "true");
    ensure (0 == code, "Curl Error: ", curl_easy_strerror (code));

    code = curl_easy_setopt (out, CURLOPT_READDATA, buf);
    ensure (0 == code, "Curl Error: ", curl_easy_strerror (code));

    code = curl_easy_perform (out);
    ensure (0 == code, "Curl Error: ", curl_easy_strerror (code));

    ::fclose (buf);

    // done :-)
  }
コード例 #20
0
ファイル: ximajpg.cpp プロジェクト: techpub/archive-code
bool CxImageJPG::Decode(CxFile * hFile)
{

	bool is_exif = false;
#if CXIMAGEJPG_SUPPORT_EXIF
	is_exif = DecodeExif(hFile);
#endif

	CImageIterator iter(this);
	/* This struct contains the JPEG decompression parameters and pointers to
	* working space (which is allocated as needed by the JPEG library).
	*/
	struct jpeg_decompress_struct cinfo;
	/* We use our private extension JPEG error handler. <CSC> */
	struct jpg_error_mgr jerr;
	jerr.buffer=info.szLastError;
	/* More stuff */
	JSAMPARRAY buffer;	/* Output row buffer */
	int row_stride;		/* physical row width in output buffer */

	/* In this example we want to open the input file before doing anything else,
	* so that the setjmp() error recovery below can assume the file is open.
	* VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
	* requires it in order to read binary files.
	*/

	/* Step 1: allocate and initialize JPEG decompression object */
	/* We set up the normal JPEG error routines, then override error_exit. */
	cinfo.err = jpeg_std_error(&jerr.pub);
	jerr.pub.error_exit = ima_jpeg_error_exit;

	/* Establish the setjmp return context for my_error_exit to use. */
	if (setjmp(jerr.setjmp_buffer)) {
		/* If we get here, the JPEG code has signaled an error.
		* We need to clean up the JPEG object, close the input file, and return.
		*/
		jpeg_destroy_decompress(&cinfo);
		return 0;
	}
	/* Now we can initialize the JPEG decompression object. */
	jpeg_create_decompress(&cinfo);

	/* Step 2: specify data source (eg, a file) */
	//jpeg_stdio_src(&cinfo, infile);
	CxFileJpg src(hFile);
    cinfo.src = &src;

	/* Step 3: read file parameters with jpeg_read_header() */
	(void) jpeg_read_header(&cinfo, TRUE);

	/* Step 4 <chupeev> handle decoder options*/
	if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & DECODE_GRAYSCALE) != 0)
		cinfo.out_color_space = JCS_GRAYSCALE;
	if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & DECODE_QUANTIZE) != 0) {
		cinfo.quantize_colors = TRUE;
		cinfo.desired_number_of_colors = info.nQuality;
	}
	if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & DECODE_DITHER) != 0)
		cinfo.dither_mode = m_nDither;
	if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & DECODE_ONEPASS) != 0)
		cinfo.two_pass_quantize = FALSE;
	if ((GetCodecOption(CXIMAGE_FORMAT_JPG) & DECODE_NOSMOOTH) != 0)
		cinfo.do_fancy_upsampling = FALSE;

//<DP>: Load true color images as RGB (no quantize) 
/* Step 4: set parameters for decompression */
/*  if (cinfo.jpeg_color_space!=JCS_GRAYSCALE) {
 *	cinfo.quantize_colors = TRUE;
 *	cinfo.desired_number_of_colors = 128;
 *}
 */ //</DP>

	// Set the scale <ignacio>
	cinfo.scale_denom = GetJpegScale();

	// Borrowed the idea from GIF implementation <ignacio>
	if (info.nEscape == -1) {
		// Return output dimensions only
		jpeg_calc_output_dimensions(&cinfo);
		head.biWidth = cinfo.output_width;
		head.biHeight = cinfo.output_height;
		jpeg_destroy_decompress(&cinfo);
		return true;
	}

	/* Step 5: Start decompressor */
	jpeg_start_decompress(&cinfo);

	/* We may need to do some setup of our own at this point before reading
	* the data.  After jpeg_start_decompress() we have the correct scaled
	* output image dimensions available, as well as the output colormap
	* if we asked for color quantization.
	*/
	//Create the image using output dimensions <ignacio>
	//Create(cinfo.image_width, cinfo.image_height, 8*cinfo.output_components, CXIMAGE_FORMAT_JPG);
	Create(cinfo.output_width, cinfo.output_height, 8*cinfo.output_components, CXIMAGE_FORMAT_JPG);

	if (!pDib) longjmp(jerr.setjmp_buffer, 1);  //<DP> check if the image has been created

	if (is_exif){
#if CXIMAGEJPG_SUPPORT_EXIF
	if ((m_exifinfo.Xresolution != 0.0) && (m_exifinfo.ResolutionUnit != 0))
		SetXDPI((long)(m_exifinfo.Xresolution/m_exifinfo.ResolutionUnit));
	if ((m_exifinfo.Yresolution != 0.0) && (m_exifinfo.ResolutionUnit != 0))
		SetYDPI((long)(m_exifinfo.Yresolution/m_exifinfo.ResolutionUnit));
#endif
	} else {
		if (cinfo.density_unit==2){
			SetXDPI((long)floor(cinfo.X_density * 254.0 / 10000.0 + 0.5));
			SetYDPI((long)floor(cinfo.Y_density * 254.0 / 10000.0 + 0.5));
		} else {
			SetXDPI(cinfo.X_density);
			SetYDPI(cinfo.Y_density);
		}
	}

	if (cinfo.out_color_space==JCS_GRAYSCALE){
		SetGrayPalette();
		head.biClrUsed =256;
	} else {
		if (cinfo.quantize_colors==TRUE){
			SetPalette(cinfo.actual_number_of_colors, cinfo.colormap[0], cinfo.colormap[1], cinfo.colormap[2]);
			head.biClrUsed=cinfo.actual_number_of_colors;
		} else {
			head.biClrUsed=0;
		}
	}

	/* JSAMPLEs per row in output buffer */
	row_stride = cinfo.output_width * cinfo.output_components;

	/* Make a one-row-high sample array that will go away when done with image */
	buffer = (*cinfo.mem->alloc_sarray)
		((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);

	/* Step 6: while (scan lines remain to be read) */
	/*           jpeg_read_scanlines(...); */
	/* Here we use the library's state variable cinfo.output_scanline as the
	* loop counter, so that we don't have to keep track ourselves.
	*/
	iter.Upset();
	while (cinfo.output_scanline < cinfo.output_height) {

		if (info.nEscape) longjmp(jerr.setjmp_buffer, 1); // <vho> - cancel decoding
		
		(void) jpeg_read_scanlines(&cinfo, buffer, 1);
		// info.nProgress = (long)(100*cinfo.output_scanline/cinfo.output_height);
		//<DP> Step 6a: CMYK->RGB */ 
		if ((cinfo.num_components==4)&&(cinfo.quantize_colors==FALSE)){
			BYTE k,*dst,*src;
			dst=iter.GetRow();
			src=buffer[0];
			for(long x3=0,x4=0; x3<(long)info.dwEffWidth && x4<row_stride; x3+=3, x4+=4){
				k=src[x4+3];
				dst[x3]  =(BYTE)((k * src[x4+2])/255);
				dst[x3+1]=(BYTE)((k * src[x4+1])/255);
				dst[x3+2]=(BYTE)((k * src[x4+0])/255);
			}
		} else {
			/* Assume put_scanline_someplace wants a pointer and sample count. */
			iter.SetRow(buffer[0], row_stride);
		}
			iter.PrevRow();
	}

	/* Step 7: Finish decompression */
	(void) jpeg_finish_decompress(&cinfo);
	/* We can ignore the return value since suspension is not possible
	* with the stdio data source.
	*/

	//<DP> Step 7A: Swap red and blue components
	// not necessary if swapped red and blue definition in jmorecfg.h;ln322 <W. Morrison>
	if ((cinfo.num_components==3)&&(cinfo.quantize_colors==FALSE)){
		BYTE* r0=GetBits();
		for(long y=0;y<head.biHeight;y++){
			if (info.nEscape) longjmp(jerr.setjmp_buffer, 1); // <vho> - cancel decoding
			RGBtoBGR(r0,3*head.biWidth);
			r0+=info.dwEffWidth;
		}
	}

	/* Step 8: Release JPEG decompression object */
	/* This is an important step since it will release a good deal of memory. */
	jpeg_destroy_decompress(&cinfo);

	/* At this point you may want to check to see whether any corrupt-data
	* warnings occurred (test whether jerr.pub.num_warnings is nonzero).
	*/

	/* And we're done! */
	return true;
}
コード例 #21
0
ファイル: x509_crl.cpp プロジェクト: noloader/botan
X509_CRL::X509_CRL(const std::vector<uint8_t>& vec)
   {
   DataSource_Memory src(vec.data(), vec.size());
   load_data(src);
   }
コード例 #22
0
ファイル: Material.cpp プロジェクト: ezhangle/anki-3d-engine
//==============================================================================
void Material::parseMaterialTag(const XmlElement& materialEl,
	ResourceInitializer& rinit)
{
	// levelsOfDetail
	//
	XmlElement lodEl = materialEl.getChildElementOptional("levelsOfDetail");

	if(lodEl)
	{
		I tmp = lodEl.getInt();
		m_lodsCount = (tmp < 1) ? 1 : tmp;
	}
	else
	{
		m_lodsCount = 1;
	}

	// shadow
	//
	XmlElement shadowEl = materialEl.getChildElementOptional("shadow");

	if(shadowEl)
	{
		m_shadow = shadowEl.getInt();
	}

	// blendFunctions
	//
	XmlElement blendFunctionsEl =
		materialEl.getChildElementOptional("blendFunctions");

	if(blendFunctionsEl)
	{
		// sFactor
		m_blendingSfactor = blendToEnum(
			blendFunctionsEl.getChildElement("sFactor").getText());

		// dFactor
		m_blendingDfactor = blendToEnum(
			blendFunctionsEl.getChildElement("dFactor").getText());
	}
	else
	{
		m_passesCount = 2;
	}

	// depthTesting
	//
	XmlElement depthTestingEl =
		materialEl.getChildElementOptional("depthTesting");

	if(depthTestingEl)
	{
		m_depthTesting = depthTestingEl.getInt();
	}

	// wireframe
	//
	XmlElement wireframeEl = materialEl.getChildElementOptional("wireframe");

	if(wireframeEl)
	{
		m_wireframe = wireframeEl.getInt();
	}

	// shaderProgram
	//
	MaterialProgramCreator mspc(
		materialEl.getChildElement("programs"),
		rinit.m_tempAlloc);

	m_tessellation = mspc.hasTessellation();
	U tessCount = m_tessellation ? 2 : 1;

	// Alloc program vector
	U progCount = 0;
	progCount += m_passesCount * m_lodsCount * tessCount;
	if(m_tessellation)
	{
		progCount += m_passesCount * m_lodsCount * 2;
	}
	progCount += m_passesCount * m_lodsCount;
	m_progs.resize(progCount);

	// Aloc progam descriptors
	m_pplines.resize(m_passesCount * m_lodsCount * tessCount);

	m_hash = 0;
	for(U shader = 0; shader < 5; shader++)
	{
		if(!m_tessellation && (shader == 1 || shader == 2))
		{
			continue;
		}

		if(shader == 3)
		{
			continue;
		}

		for(U level = 0; level < m_lodsCount; ++level)
		{
			for(U pid = 0; pid < m_passesCount; ++pid)
			{
				for(U tess = 0; tess < tessCount; ++tess)
				{
					TempResourceString src(rinit.m_tempAlloc);

					src.sprintf("#define LOD %u\n"
						"#define PASS %u\n"
						"#define TESSELLATION %u\n", 
						level, pid, tess);

					TempResourceString filename =
						createProgramSourceToChache(src);

					RenderingKey key((Pass)pid, level, tess);
					ProgramResourcePointer& progr = getProgram(key, shader);
					progr.load(filename.toCString(), &rinit.m_resources);

					// Update the hash
					m_hash ^= computeHash(&src[0], src.getLength());
				}
			}
		}
	}

	populateVariables(mspc);

	// Get uniform block size
	ANKI_ASSERT(m_progs.size() > 0);
	m_shaderBlockSize = 
		m_progs[0]->getGlProgram().findBlock("bDefaultBlock").getSize();
}
コード例 #23
0
void Sys_Init( void ) {

	CoInitialize( NULL );

	// make sure the timer is high precision, otherwise
	// NT gets 18ms resolution
	timeBeginPeriod( 1 );

	// get WM_TIMER messages pumped every millisecond
//	SetTimer( NULL, 0, 100, NULL );

	cmdSystem->AddCommand( "in_restart", Sys_In_Restart_f, CMD_FL_SYSTEM, "restarts the input system" );
#ifdef DEBUG
	cmdSystem->AddCommand( "createResourceIDs", CreateResourceIDs_f, CMD_FL_TOOL, "assigns resource IDs in _resouce.h files" );
#endif
#if 0
	cmdSystem->AddCommand( "setAsyncSound", Sys_SetAsyncSound_f, CMD_FL_SYSTEM, "set the async sound option" );
#endif

	//
	// Windows user name
	//
	win32.win_username.SetString( Sys_GetCurrentUser() );

	//
	// Windows version
	//
	win32.osversion.dwOSVersionInfoSize = sizeof( win32.osversion );

	if ( !GetVersionEx( (LPOSVERSIONINFO)&win32.osversion ) )
		Sys_Error( "Couldn't get OS info" );

	if ( win32.osversion.dwMajorVersion < 4 ) {
		Sys_Error( GAME_NAME " requires Windows version 4 (NT) or greater" );
	}
	if ( win32.osversion.dwPlatformId == VER_PLATFORM_WIN32s ) {
		Sys_Error( GAME_NAME " doesn't run on Win32s" );
	}

	if( win32.osversion.dwPlatformId == VER_PLATFORM_WIN32_NT ) {
		if( win32.osversion.dwMajorVersion <= 4 ) {
			win32.sys_arch.SetString( "WinNT (NT)" );
		} else if( win32.osversion.dwMajorVersion == 5 && win32.osversion.dwMinorVersion == 0 ) {
			win32.sys_arch.SetString( "Win2K (NT)" );
		} else if( win32.osversion.dwMajorVersion == 5 && win32.osversion.dwMinorVersion == 1 ) {
			win32.sys_arch.SetString( "WinXP (NT)" );
		} else if ( win32.osversion.dwMajorVersion == 6 && win32.osversion.dwMinorVersion == 0 ) {
		  win32.sys_arch.SetString( "WinVista (NT)" );
		} else if ( win32.osversion.dwMajorVersion == 6 && win32.osversion.dwMinorVersion == 1 ) {
		  win32.sys_arch.SetString( "Win7 (NT)" );
		} else if ( win32.osversion.dwMajorVersion == 6 && win32.osversion.dwMinorVersion == 2 ) {
		  win32.sys_arch.SetString( "Win8 (NT)" );
		} else {
			win32.sys_arch.SetString( "Unknown NT variant" );
		}
	} else if( win32.osversion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) {
		if( win32.osversion.dwMajorVersion == 4 && win32.osversion.dwMinorVersion == 0 ) {
			// Win95
			if( win32.osversion.szCSDVersion[1] == 'C' ) {
				win32.sys_arch.SetString( "Win95 OSR2 (95)" );
			} else {
				win32.sys_arch.SetString( "Win95 (95)" );
			}
		} else if( win32.osversion.dwMajorVersion == 4 && win32.osversion.dwMinorVersion == 10 ) {
			// Win98
			if( win32.osversion.szCSDVersion[1] == 'A' ) {
				win32.sys_arch.SetString( "Win98SE (95)" );
			} else {
				win32.sys_arch.SetString( "Win98 (95)" );
			}
		} else if( win32.osversion.dwMajorVersion == 4 && win32.osversion.dwMinorVersion == 90 ) {
			// WinMe
		  	win32.sys_arch.SetString( "WinMe (95)" );
		} else {
		  	win32.sys_arch.SetString( "Unknown 95 variant" );
		}
	} else {
		win32.sys_arch.SetString( "unknown Windows variant" );
	}

	//
	// CPU type
	//
	if ( !idStr::Icmp( win32.sys_cpustring.GetString(), "detect" ) ) {
		idStr string;

		common->Printf( "%1.0f MHz ", Sys_ClockTicksPerSecond() / 1000000.0f );

		win32.cpuid = Sys_GetCPUId();

		string.Clear();

		if ( win32.cpuid & CPUID_AMD ) {
			string += "AMD CPU";
		} else if ( win32.cpuid & CPUID_INTEL ) {
			string += "Intel CPU";
		} else if ( win32.cpuid & CPUID_UNSUPPORTED ) {
			string += "unsupported CPU";
		} else {
			string += "generic CPU";
		}

		string += " with ";
		if ( win32.cpuid & CPUID_MMX ) {
			string += "MMX & ";
		}
		if ( win32.cpuid & CPUID_3DNOW ) {
			string += "3DNow! & ";
		}
		if ( win32.cpuid & CPUID_SSE ) {
			string += "SSE & ";
		}
		if ( win32.cpuid & CPUID_SSE2 ) {
            string += "SSE2 & ";
		}
		if ( win32.cpuid & CPUID_SSE3 ) {
			string += "SSE3 & ";
		}
		if ( win32.cpuid & CPUID_HTT ) {
			string += "HTT & ";
		}
		string.StripTrailing( " & " );
		string.StripTrailing( " with " );
		win32.sys_cpustring.SetString( string );
	} else {
		common->Printf( "forcing CPU type to " );
		idLexer src( win32.sys_cpustring.GetString(), idStr::Length( win32.sys_cpustring.GetString() ), "sys_cpustring" );
		idToken token;

		int id = CPUID_NONE;
		while( src.ReadToken( &token ) ) {
			if ( token.Icmp( "generic" ) == 0 ) {
				id |= CPUID_GENERIC;
			} else if ( token.Icmp( "intel" ) == 0 ) {
				id |= CPUID_INTEL;
			} else if ( token.Icmp( "amd" ) == 0 ) {
				id |= CPUID_AMD;
			} else if ( token.Icmp( "mmx" ) == 0 ) {
				id |= CPUID_MMX;
			} else if ( token.Icmp( "3dnow" ) == 0 ) {
				id |= CPUID_3DNOW;
			} else if ( token.Icmp( "sse" ) == 0 ) {
				id |= CPUID_SSE;
			} else if ( token.Icmp( "sse2" ) == 0 ) {
				id |= CPUID_SSE2;
			} else if ( token.Icmp( "sse3" ) == 0 ) {
				id |= CPUID_SSE3;
			} else if ( token.Icmp( "htt" ) == 0 ) {
				id |= CPUID_HTT;
			}
		}
		if ( id == CPUID_NONE ) {
			common->Printf( "WARNING: unknown sys_cpustring '%s'\n", win32.sys_cpustring.GetString() );
			id = CPUID_GENERIC;
		}
		win32.cpuid = (cpuid_t) id;
	}

	common->Printf( "%s\n", win32.sys_cpustring.GetString() );
	common->Printf( "%d MB System Memory\n", Sys_GetSystemRam() );
	common->Printf( "%d MB Video Memory\n", Sys_GetVideoRam() );
}
コード例 #24
0
void idListWindow::PostParse() {
	idWindow::PostParse();
	InitScroller( horizontal );
	idList<int> tabStops;
	idList<int> tabAligns;
	if( tabStopStr.Length() ) {
		idParser src( tabStopStr, tabStopStr.Length(), "tabstops", LEXFL_NOFATALERRORS | LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS );
		idToken tok;
		while( src.ReadToken( &tok ) ) {
			if( tok == "," ) {
				continue;
			}
			tabStops.Append( atoi( tok ) );
		}
	}
	if( tabAlignStr.Length() ) {
		idParser src( tabAlignStr, tabAlignStr.Length(), "tabaligns", LEXFL_NOFATALERRORS | LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS );
		idToken tok;
		while( src.ReadToken( &tok ) ) {
			if( tok == "," ) {
				continue;
			}
			tabAligns.Append( atoi( tok ) );
		}
	}
	idList<int> tabVAligns;
	if( tabVAlignStr.Length() ) {
		idParser src( tabVAlignStr, tabVAlignStr.Length(), "tabvaligns", LEXFL_NOFATALERRORS | LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS );
		idToken tok;
		while( src.ReadToken( &tok ) ) {
			if( tok == "," ) {
				continue;
			}
			tabVAligns.Append( atoi( tok ) );
		}
	}
	idList<int> tabTypes;
	if( tabTypeStr.Length() ) {
		idParser src( tabTypeStr, tabTypeStr.Length(), "tabtypes", LEXFL_NOFATALERRORS | LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS );
		idToken tok;
		while( src.ReadToken( &tok ) ) {
			if( tok == "," ) {
				continue;
			}
			tabTypes.Append( atoi( tok ) );
		}
	}
	idList<idVec2> tabSizes;
	if( tabIconSizeStr.Length() ) {
		idParser src( tabIconSizeStr, tabIconSizeStr.Length(), "tabiconsizes", LEXFL_NOFATALERRORS | LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS );
		idToken tok;
		while( src.ReadToken( &tok ) ) {
			if( tok == "," ) {
				continue;
			}
			idVec2 size;
			size.x = atoi( tok );
			src.ReadToken( &tok );	//","
			src.ReadToken( &tok );
			size.y = atoi( tok );
			tabSizes.Append( size );
		}
	}
	idList<float> tabIconVOffsets;
	if( tabIconVOffsetStr.Length() ) {
		idParser src( tabIconVOffsetStr, tabIconVOffsetStr.Length(), "tabiconvoffsets", LEXFL_NOFATALERRORS | LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS );
		idToken tok;
		while( src.ReadToken( &tok ) ) {
			if( tok == "," ) {
				continue;
			}
			tabIconVOffsets.Append( atof( tok ) );
		}
	}
	int c = tabStops.Num();
	bool doAligns = ( tabAligns.Num() == tabStops.Num() );
	for( int i = 0; i < c; i++ ) {
		idTabRect r;
		r.x = tabStops[i];
		r.w = ( i < c - 1 ) ? tabStops[i + 1] - r.x - tabBorder : -1;
		r.align = ( doAligns ) ? tabAligns[i] : 0;
		if( tabVAligns.Num() > 0 ) {
			r.valign = tabVAligns[i];
		} else {
			r.valign = 0;
		}
		if( tabTypes.Num() > 0 ) {
			r.type = tabTypes[i];
		} else {
			r.type = TAB_TYPE_TEXT;
		}
		if( tabSizes.Num() > 0 ) {
			r.iconSize = tabSizes[i];
		} else {
			r.iconSize.Zero();
		}
		if( tabIconVOffsets.Num() > 0 ) {
			r.iconVOffset = tabIconVOffsets[i];
		} else {
			r.iconVOffset = 0;
		}
		tabInfo.Append( r );
	}
	flags |= WIN_CANFOCUS;
}
コード例 #25
0
ファイル: lz4mt.cpp プロジェクト: kgodlewski/lz4mt
extern "C" Lz4MtResult
lz4mtCompress(Lz4MtContext* lz4MtContext, const Lz4MtStreamDescriptor* sd)
{
	assert(lz4MtContext);
	assert(sd);

	Context ctx_(lz4MtContext);
	Context* ctx = &ctx_;

	{
		char d[LZ4S_MAX_HEADER_SIZE] = { 0 };
		auto p = &d[0];

		const auto r = validateStreamDescriptor(sd);
		if(LZ4MT_RESULT_OK != r) {
			return ctx->setResult(r);
		}
		p += storeU32(p, LZ4S_MAGICNUMBER);

		const auto* sumBegin = p;
		*p++ = flgToChar(sd->flg);
		*p++ = bdToChar(sd->bd);
		if(sd->flg.streamSize) {
			assert(sd->streamSize);
			p += storeU64(p, sd->streamSize);
		}
		if(sd->flg.presetDictionary) {
			p += storeU32(p, sd->dictId);
		}

		const auto sumSize = static_cast<int>(p - sumBegin);
		const auto h = Lz4Mt::Xxh32(sumBegin, sumSize, LZ4S_CHECKSUM_SEED).digest();
		*p++ = static_cast<char>(getCheckBits_FromXXH(h));
		assert(p <= std::end(d));

		const auto writeSize = static_cast<int>(p - d);
		if(writeSize != ctx->write(d, writeSize)) {
			return ctx->setResult(LZ4MT_RESULT_CANNOT_WRITE_HEADER);
		}
	}

	const auto nBlockMaximumSize = getBlockSize(sd->bd.blockMaximumSize);
	const auto nBlockSize        = 4;
	const auto nBlockCheckSum    = sd->flg.blockChecksum ? 4 : 0;
	const auto cIncompressible   = 1 << (nBlockSize * 8 - 1);
	const bool streamChecksum    = 0 != sd->flg.streamChecksum;
	const bool singleThread      = 0 != (ctx->mode() & LZ4MT_MODE_SEQUENTIAL);
	const auto nConcurrency      = Lz4Mt::getHardwareConcurrency();
	const auto nPool             = singleThread ? 1 : nConcurrency + 1;
	const auto launch            = singleThread ? Lz4Mt::launch::deferred : std::launch::async;

	Lz4Mt::MemPool srcBufferPool(nBlockMaximumSize, nPool);
	Lz4Mt::MemPool dstBufferPool(nBlockMaximumSize, nPool);
	std::vector<std::future<void>> futures;
	Lz4Mt::Xxh32 xxhStream(LZ4S_CHECKSUM_SEED);

	const auto f =
		[&futures, &dstBufferPool, &xxhStream
		 , ctx, nBlockCheckSum, streamChecksum, launch, cIncompressible
		 ]
		(int i, Lz4Mt::MemPool::Buffer* srcRawPtr, int srcSize)
	{
		BufferPtr src(srcRawPtr);
		if(ctx->error()) {
			return;
		}

		const auto* srcPtr = src->data();
		BufferPtr dst(dstBufferPool.alloc());
		auto* cmpPtr = dst->data();
		const auto cmpSize = ctx->compress(srcPtr, cmpPtr, srcSize, srcSize);
		const bool incompressible = (cmpSize <= 0);
		const auto* cPtr  = incompressible ? srcPtr  : cmpPtr;
		const auto  cSize = incompressible ? srcSize : cmpSize;

		std::future<uint32_t> futureBlockHash;
		if(nBlockCheckSum) {
			futureBlockHash = std::async(launch, [=] {
				return Lz4Mt::Xxh32(cPtr, cSize, LZ4S_CHECKSUM_SEED).digest();
			});
		}

		if(incompressible) {
			dst.reset();
		}

		if(i > 0) {
			futures[i-1].wait();
		}

		std::future<void> futureStreamHash;
		if(streamChecksum) {
			futureStreamHash = std::async(launch, [=, &xxhStream] {
				xxhStream.update(srcPtr, srcSize);
			});
		}

		if(incompressible) {
			ctx->writeU32(cSize | cIncompressible);
			ctx->writeBin(srcPtr, srcSize);
		} else {
			ctx->writeU32(cSize);
			ctx->writeBin(cmpPtr, cmpSize);
		}

		if(futureBlockHash.valid()) {
			ctx->writeU32(futureBlockHash.get());
		}

		if(futureStreamHash.valid()) {
			futureStreamHash.wait();
		}
	};

	for(int i = 0;; ++i) {
		BufferPtr src(srcBufferPool.alloc());
		auto* srcPtr = src->data();
		const auto srcSize = src->size();
		const auto readSize = ctx->read(srcPtr, static_cast<int>(srcSize));

		if(0 == readSize) {
			break;
		}

		if(singleThread) {
			f(0, src.release(), readSize);
		} else {
			futures.emplace_back(std::async(launch, f, i, src.release(), readSize));
		}
	}

	for(auto& e : futures) {
		e.wait();
	}

	if(!ctx->writeU32(LZ4S_EOS)) {
		return LZ4MT_RESULT_CANNOT_WRITE_EOS;
	}

	if(streamChecksum) {
		const auto digest = xxhStream.digest();
		if(!ctx->writeU32(digest)) {
			return LZ4MT_RESULT_CANNOT_WRITE_STREAM_CHECKSUM;
		}
	}

	return LZ4MT_RESULT_OK;
}
コード例 #26
0
ファイル: DX7SubPic.cpp プロジェクト: gaxuhongyu/mpc-hc
STDMETHODIMP CDX7SubPic::AlphaBlt(RECT* pSrc, RECT* pDst, SubPicDesc* pTarget)
{
    ASSERT(pTarget == nullptr);

    if (!m_pD3DDev || !m_pSurface || !pSrc || !pDst) {
        return E_POINTER;
    }

    CRect src(*pSrc), dst(*pDst);

    HRESULT hr;

    DDSURFACEDESC2 ddsd;
    INITDDSTRUCT(ddsd);
    if (FAILED(hr = m_pSurface->GetSurfaceDesc(&ddsd))) {
        return E_FAIL;
    }

    float w = (float)ddsd.dwWidth;
    float h = (float)ddsd.dwHeight;

    // Be careful with the code that follows. Some compilers (e.g. Visual Studio 2012) used to miscompile
    // it in some cases (namely x64 with optimizations /O2 /Ot). This bug led pVertices not to be correctly
    // initialized and thus the subtitles weren't shown.
    struct {
        float x, y, z, rhw;
        float tu, tv;
    } pVertices[] = {
        {(float)dst.left, (float)dst.top, 0.5f, 2.0f, (float)src.left / w, (float)src.top / h},
        {(float)dst.right, (float)dst.top, 0.5f, 2.0f, (float)src.right / w, (float)src.top / h},
        {(float)dst.left, (float)dst.bottom, 0.5f, 2.0f, (float)src.left / w, (float)src.bottom / h},
        {(float)dst.right, (float)dst.bottom, 0.5f, 2.0f, (float)src.right / w, (float)src.bottom / h},
    };

    for (size_t i = 0; i < _countof(pVertices); i++) {
        pVertices[i].x -= 0.5f;
        pVertices[i].y -= 0.5f;
    }

    hr = m_pD3DDev->SetTexture(0, m_pSurface);

    m_pD3DDev->SetRenderState(D3DRENDERSTATE_CULLMODE, D3DCULL_NONE);
    m_pD3DDev->SetRenderState(D3DRENDERSTATE_LIGHTING, FALSE);
    m_pD3DDev->SetRenderState(D3DRENDERSTATE_BLENDENABLE, TRUE);
    m_pD3DDev->SetRenderState(D3DRENDERSTATE_SRCBLEND, D3DBLEND_ONE); // pre-multiplied src and ...
    m_pD3DDev->SetRenderState(D3DRENDERSTATE_DESTBLEND, m_bInvAlpha ? D3DBLEND_INVSRCALPHA : D3DBLEND_SRCALPHA); // ... inverse alpha channel for dst

    m_pD3DDev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
    m_pD3DDev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
    m_pD3DDev->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);

    if (src == dst) {
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTFG_POINT);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MINFILTER, D3DTFG_POINT);
    } else {
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTFG_LINEAR);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MINFILTER, D3DTFG_LINEAR);
    }
    m_pD3DDev->SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTFP_NONE);

    m_pD3DDev->SetTextureStageState(0, D3DTSS_ADDRESS, D3DTADDRESS_CLAMP);

    /*//
    D3DDEVICEDESC7 d3ddevdesc;
    m_pD3DDev->GetCaps(&d3ddevdesc);
    if (d3ddevdesc.dpcTriCaps.dwAlphaCmpCaps & D3DPCMPCAPS_LESS)
    {
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHAREF, (DWORD)0x000000FE);
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHATESTENABLE, TRUE);
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHAFUNC, D3DPCMPCAPS_LESS);
    }
    *///

    if (FAILED(hr = m_pD3DDev->BeginScene())) {
        return E_FAIL;
    }

    hr = m_pD3DDev->DrawPrimitive(D3DPT_TRIANGLESTRIP,
                                  D3DFVF_XYZRHW | D3DFVF_TEX1,
                                  pVertices, 4, D3DDP_WAIT);
    m_pD3DDev->EndScene();

    m_pD3DDev->SetTexture(0, nullptr);

    return S_OK;
}
コード例 #27
0
ファイル: DX7SubPic.cpp プロジェクト: AeonAxan/mpc-hc
STDMETHODIMP CDX7SubPic::AlphaBlt(RECT* pSrc, RECT* pDst, SubPicDesc* pTarget)
{
    ASSERT(pTarget == NULL);

    if (!m_pD3DDev || !m_pSurface || !pSrc || !pDst) {
        return E_POINTER;
    }

    CRect src(*pSrc), dst(*pDst);

    HRESULT hr;

    do {
        DDSURFACEDESC2 ddsd;
        INITDDSTRUCT(ddsd);
        if (FAILED(hr = m_pSurface->GetSurfaceDesc(&ddsd))) {
            break;
        }

        float w = (float)ddsd.dwWidth;
        float h = (float)ddsd.dwHeight;

        struct {
            float x, y, z, rhw;
            float tu, tv;
        }
        pVertices[] = {
            {(float)dst.left, (float)dst.top, 0.5f, 2.0f, (float)src.left / w, (float)src.top / h},
            {(float)dst.right, (float)dst.top, 0.5f, 2.0f, (float)src.right / w, (float)src.top / h},
            {(float)dst.left, (float)dst.bottom, 0.5f, 2.0f, (float)src.left / w, (float)src.bottom / h},
            {(float)dst.right, (float)dst.bottom, 0.5f, 2.0f, (float)src.right / w, (float)src.bottom / h},
        };
        /*
        for (ptrdiff_t i = 0; i < _countof(pVertices); i++)
        {
            pVertices[i].x -= 0.5;
            pVertices[i].y -= 0.5;
        }
        */
        hr = m_pD3DDev->SetTexture(0, m_pSurface);

        m_pD3DDev->SetRenderState(D3DRENDERSTATE_CULLMODE, D3DCULL_NONE);
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_LIGHTING, FALSE);
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_BLENDENABLE, TRUE);
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_SRCBLEND, D3DBLEND_ONE); // pre-multiplied src and ...
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_DESTBLEND, D3DBLEND_SRCALPHA); // ... inverse alpha channel for dst

        m_pD3DDev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);

        m_pD3DDev->SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTFG_LINEAR);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MINFILTER, D3DTFN_LINEAR);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTFP_LINEAR);

        m_pD3DDev->SetTextureStageState(0, D3DTSS_ADDRESS, D3DTADDRESS_CLAMP);

        /*//

        D3DDEVICEDESC7 d3ddevdesc;
        m_pD3DDev->GetCaps(&d3ddevdesc);
        if (d3ddevdesc.dpcTriCaps.dwAlphaCmpCaps & D3DPCMPCAPS_LESS)
        {
            m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHAREF, (DWORD)0x000000FE);
            m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHATESTENABLE, TRUE);
            m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHAFUNC, D3DPCMPCAPS_LESS);
        }

        *///

        if (FAILED(hr = m_pD3DDev->BeginScene())) {
            break;
        }

        hr = m_pD3DDev->DrawPrimitive(D3DPT_TRIANGLESTRIP,
                                      D3DFVF_XYZRHW | D3DFVF_TEX1,
                                      pVertices, 4, D3DDP_WAIT);
        m_pD3DDev->EndScene();

        //

        m_pD3DDev->SetTexture(0, NULL);

        return S_OK;
    } while (0);

    return E_FAIL;
}
コード例 #28
0
ファイル: MakeDefs.cpp プロジェクト: Caraul/airgit
/*
int __cdecl main(int argc, char* argv[]) {
	File src(argv[1], File::READ, File::OPEN);
	string x = src.read();

	DWORD y = GetTickCount();
	SimpleXML xml;
	xml.fromXML(x);
	printf("%d\n", GetTickCount() - y);
	return 0;
}
*/
int __cdecl main(int argc, char* argv[])
{
	if(argc < 3) {
		return 0;
	}
	
	try {
		string tmp;
		File src(argv[1], File::READ, File::OPEN, File::BUFFER_SEQUENTIAL, false);
		File tgt(argv[2], File::WRITE, File::CREATE | File::TRUNCATE, File::BUFFER_SEQUENTIAL, false);
		File example(argv[3], File::WRITE, File::CREATE | File::TRUNCATE, File::BUFFER_SEQUENTIAL, false);
		string x = src.read();
		x = Text::acpToUtf8(x);
		string::size_type k;
		
		while((k = x.find('\r')) != string::npos) {
			x.erase(k, 1);
		}

		StringList l = StringTokenizer<string>(x, '\n').getTokens();

		StringIter i;
		string varStr;
		string varName;
		string start;

		SimpleXML ex;

		for(i = l.begin(); i != l.end(); ) {
			if( (k = i->find("// @Strings: ")) != string::npos) {
				varStr = i->substr(k + 13);
				i = l.erase(i);
			} else if( (k = i->find("// @Names: ")) != string::npos) {
				varName = i->substr(k + 11);
				i = l.erase(i);
			} else if(i->find("// @DontAdd") != string::npos) {
				i = l.erase(i);
			} else if( (k = i->find("// @Prolog: ")) != string::npos) {
				start += i->substr(k + 12) + "\r\n";
				i = l.erase(i);
			} else if(i->size() < 5) {
				i = l.erase(i);
			} else {
				++i;
			}
		}

		if(varStr.empty() || varName.empty()) {
			printf("No @Strings or @Names\n");
			return 0;
		}
		
		varStr += " = {\r\n";
		varName += " = {\r\n";
		
		/*ex.addTag("Language");
		ex.addChildAttrib("Name", string("Example Language"));
		ex.addChildAttrib("Author", string("AirDC++ Team"));
		ex.addChildAttrib("Version", string(VERSIONSTRING));
		ex.addChildAttrib("Revision", string("1"));
		ex.stepIn();
		ex.addTag("Strings");
		ex.stepIn();*/

		ex.addTag("resources");
		ex.stepIn();
		string name;
		string def;
		string xmldef;
		string s;
		for(i = l.begin(); i != l.end(); i++) {

			name.clear();
			s = *i;

			bool u = true;
			for(k = s.find_first_not_of(" \t"); s[k] != ','; k++) {
				if(s[k] == '_') {
					u = true;
				} else if(u) {
					name+=s[k];
					u = false;
				} else {
					name+=(char)tolower(s[k]);
				}
			}

			k = s.find("// ");
			def = s.substr(k + 3);
			xmldef = def.substr(1, def.size() - 2);
			while( (k = xmldef.find("\\t")) != string::npos) {
				xmldef.replace(k, 2, "\t");
			}
			while( (k = xmldef.find("\\r")) != string::npos) {
				xmldef.replace(k, 2, "\r");
			}
			while( (k = xmldef.find("\\n")) != string::npos) {
				xmldef.replace(k, 2, "\n");
			}

			while( (k = xmldef.find("\\\\")) != string::npos) {
				xmldef.replace(k, 2, "\\");
			}
			while( (k = xmldef.find("\\\"")) != string::npos) {
				xmldef.replace(k, 2, "\"");
			}
			//ex.addTag("String", xmldef);
			//ex.addChildAttrib("Name", name);
			ex.addTag("string", xmldef);
			ex.addChildAttrib("name", name);

			varStr += def + ", \r\n";
			varName += '\"' + name + "\", \r\n";

			/*if(((++a) % 5) == 0) {
				varStr += "\r\n";
				varName += "\r\n";
			}*/

		}

		varStr.erase(varStr.size()-2, 2);
		varName.erase(varName.size()-2, 2);

		varStr += "\r\n};\r\n";
		varName += "\r\n};\r\n";

		tgt.write(start);
		tgt.write(varStr);
		tgt.write(varName);

		example.write(SimpleXML::utf8Header);
		example.write(ex.toXML());
	} catch(Exception e) {
		printf("%s\n", e.getError().c_str());
	}

	return 0;
}
コード例 #29
0
int main( int argc, char** argv ) {
    
    //! Number of cells in x direction
    int l_nX = 0;
    
    //! Number of cells in y direction
    int l_nY = 0;

	//! coarseness factor
	float l_coarseness = 1.0;
    
    //! l_baseName of the plots.
    std::string l_baseName;
    
    //! bathymetry input file name
    std::string l_bathymetryFileName;
    
    //! displacement input file name
    std::string l_displacementFileName;
    
    //! checkpoint input file name
    std::string l_checkpointFileName;
    
    //! the total simulation time
    int l_simulationTime = 0.0;

#ifdef USEOPENCL
    //! Maximum number of computing devices to be used (OpenCL specific, 0 = unlimited)
    unsigned int l_maxDevices = 0;
    
    //! Maximum kernel group size
    size_t l_maxGroupSize = 1024;
    
    //! Chosen kernel optimization type
    KernelType l_kernelType = MEM_GLOBAL;
#endif
    
    //! type of boundary conditions at LEFT, RIGHT, TOP, and BOTTOM boundary
    BoundaryType l_boundaryTypes[4];
    //! whether to override the scenario-defined conditions (true) or not (false)
    bool l_overwriteBoundaryTypes = false;
    
    //! List of defined scenarios
    typedef enum {
        SCENARIO_TSUNAMI, SCENARIO_CHECKPOINT_TSUNAMI,
        SCENARIO_ARTIFICIAL_TSUNAMI, SCENARIO_PARTIAL_DAMBREAK
    } ScenarioName;
    
    //! the name of the chosen scenario
    ScenarioName l_scenarioName;
#ifdef WRITENETCDF
    l_scenarioName = SCENARIO_TSUNAMI;
#else
    l_scenarioName = SCENARIO_PARTIAL_DAMBREAK;
#endif
    
    //! number of checkpoints for visualization (at each checkpoint in time, an output file is written).
    int l_numberOfCheckPoints = 20;
    
    // Option Parsing
    // REQUIRED
    // -x <num>        // Number of cells in x-dir
    // -y <num>        // Number of cells in y-dir
    // -o <file>       // Output file basename
    // OPTIONAL (may be required for certain scenarios)
    // -i <file>       // initial bathymetry data file name (REQUIRED for certain scenarios)
    // -d <file>       // input displacement data file name (REQUIRED for certain scenarios)
    // -c <file>       // checkpoints data file name
    // -f <float>      // output coarseness factor
    // -l <num>        // maximum number of computing devices
    // -m <code>       // Kernel memory optimization type
    // -g <num         // Kernel work group size
    // -n <num>        // Number of checkpoints
    // -t <float>      // Simulation time in seconds
    // -s <scenario>   // Artificial scenario name ("artificialtsunami", "partialdambreak")
    // -b <code>       // Boundary conditions, "w" or "o"
    //                 // 1 value: for all
    //                 // 2 values: first is left/right, second is top/bottom
    //                 // 4 values: left, right, bottom, top
    int c;
    int showUsage = 0;
    std::string optstr;
    while ((c = getopt(argc, argv, "x:y:o:i:d:c:n:t:b:s:f:l:m:g:")) != -1) {
        switch(c) {
            case 'x':
                l_nX = atoi(optarg);
                break;
            case 'y':
                l_nY = atoi(optarg);
                break;
            case 'o':
                l_baseName = std::string(optarg);
                break;
#ifdef WRITENETCDF
            case 'i':
                l_bathymetryFileName = std::string(optarg);
                break;
            case 'd':
                l_displacementFileName = std::string(optarg);
                break;
            case 'c':
                l_checkpointFileName = std::string(optarg);
                break;
#endif
            case 'l':
#ifdef USEOPENCL
                l_maxDevices = atoi(optarg);
#endif
                break;
            case 'g':
#ifdef USEOPENCL
                l_maxGroupSize = atoi(optarg);
#endif
            break;
            case 'm':
#ifdef USEOPENCL
                optstr = std::string(optarg);
                if(optstr == "g" || optstr == "global")
                    l_kernelType = MEM_GLOBAL;
                else
                    l_kernelType = MEM_LOCAL;
#endif
                break;
            case 'n':
                l_numberOfCheckPoints = atoi(optarg);
                break;
            case 't':
                l_simulationTime = atof(optarg);
                break;
            case 'b':
                optstr = std::string(optarg);
                l_overwriteBoundaryTypes = true;
                switch(optstr.length()) {
                    case 1:
                        // one option for all boundaries
                        for(int i = 0; i < 4; i++)
                            l_boundaryTypes[i] = (optstr[0] == 'w') ? WALL : OUTFLOW;
                        break;
                    case 2:
                        // first: left/right, second: top/bottom
                        for(int i = 0; i < 2; i++)
                            l_boundaryTypes[i] = (optstr[0] == 'w') ? WALL : OUTFLOW;
                        for(int i = 2; i < 4; i++)
                            l_boundaryTypes[i] = (optstr[1] == 'w') ? WALL : OUTFLOW;
                        break;
                    case 4:
                        // left right bottom top
                        for(int i = 0; i < 4; i++)
                            l_boundaryTypes[i] = (optstr[i] == 'w') ? WALL : OUTFLOW;
                        break;
                    default:
                        std::cerr << "Invalid option argument: Invalid boundary specification (-b)" << std::endl;
                        showUsage = 1;
                        break;
                }
                break;
            case 's':
                optstr = std::string(optarg);
                if(optstr == "artificialtsunami") {
                    l_scenarioName = SCENARIO_ARTIFICIAL_TSUNAMI;
                } else if(optstr == "partialdambreak") {
                    l_scenarioName = SCENARIO_PARTIAL_DAMBREAK;
                } else {
                    std::cerr << "Invalid option argument: Unknown scenario (-s)" << std::endl;
                    showUsage = 1;
                }
                break;
            case 'f':
                l_coarseness = atof(optarg);
                break;
            default:
                showUsage = 1;
                break;
        }
    }
    
    // Do several checks on supplied options
    if(!showUsage) {
        // Check for required arguments x and y cells unless we can get the info from a checkpoint file
        if((l_nX == 0 || l_nY == 0) && l_checkpointFileName.empty()) {
            std::cerr << "Missing required arguments: number of cells in X (-x) and Y (-y) direction" << std::endl;
            showUsage = 1;
        }
        // Check for required output base file name
        if(l_baseName.empty() && l_checkpointFileName.empty()) {
            std::cerr << "Missing required argument: base name of output file (-o)" << std::endl;
            showUsage = 1;
        }
        // Check for valid number of checkpoints
        if(l_numberOfCheckPoints <= 0) {
            std::cerr << "Invalid option argument: Number of checkpoints must be greater than zero (-n)" << std::endl;
            showUsage = 1;
        }
        
        if(l_coarseness < 1.0) {
            std::cerr << "Invalid option argument: The coarseness factor must be greater than or equal to 1.0 (-f)" << std::endl;
            showUsage = 1;
        }
        
        // Check if a checkpoint-file is given as input. If so, switch to checkpoint scenario
        if(!l_checkpointFileName.empty()) {
            l_scenarioName = SCENARIO_CHECKPOINT_TSUNAMI;
            
            // We handle the file name of checkpoint and output data files without the ".nc"
            // extension internally, so we're removing the extension here in case it is supplied
            int cpLength = l_checkpointFileName.length();
            if(l_checkpointFileName.substr(cpLength-3, 3).compare(".nc") == 0) {
                l_checkpointFileName.erase(cpLength-3, 3);
            }
            
            if(l_nX > 0 || l_nY > 0)
                std::cerr << "WARNING: Supplied number of grid cells will be ignored (reading from checkpoint)" << std::endl;
            if(l_simulationTime > 0.0)
                std::cerr << "WARNING: Supplied simulation time will be ignored (reading from checkpoint)" << std::endl;
        }
        
        if(l_scenarioName == SCENARIO_TSUNAMI) {
            // We've got no checkpoint and no artificial scenario
            // => Bathymetry and displacement data must be supplied
            if(l_bathymetryFileName.empty() || l_displacementFileName.empty()) {
                std::cerr << "Missing required argument: bathymetry (-i) and displacement (-d) files must be supplied" << std::endl;
                showUsage = 1;
            }
        } else {
            if(!l_bathymetryFileName.empty() || !l_displacementFileName.empty())
                std::cerr << "WARNING: Supplied bathymetry and displacement data will be ignored" << std::endl;
        }
#ifdef USEOPENCL
        if(l_maxGroupSize == 0 || (l_maxGroupSize & (l_maxGroupSize - 1))) {
            std::cout << "Group size must be greater than zero and a power of two!" << std::endl;
            showUsage = 1;
        }
#endif
    }
    
    if(showUsage) {
        std::cout << "Usage:" << std::endl;
        std::cout << "Simulating a tsunami with bathymetry and displacement input:" << std::endl;
        std::cout << "    ./SWE_<opt> -i <bathymetryfile> -d <displacementfile> [OPTIONS]" << std::endl;
        std::cout << "Resuming a crashed simulation from checkpoint file:" << std::endl;
        std::cout << "    ./SWE_<opt> -c <checkpointfile> [-o <outputfile>]" << std::endl;
        std::cout << "Simulating an artificial scenario:" << std::endl;
        std::cout << "    ./SWE_<opt> -s <scenarioname> [OPTIONS]" << std::endl;
        std::cout << "" << std::endl;
        std::cout << "Options:" << std::endl;
        std::cout << "    -o <filename>   The output file base name" << std::endl;
        std::cout << "        Note: If the file already exists it is assumed to be a checkpointfile" << std::endl;
        std::cout << "        from which to resume simulation. Input options are ignored then." << std::endl;
        std::cout << "    -x <num>        The number of cells in x-direction" << std::endl;
        std::cout << "    -y <num>        The number of cells in y-direction" << std::endl;
        std::cout << "    -n <num>        Number of checkpoints to be written" << std::endl;
        std::cout << "    -t <time>       Total simulation time" << std::endl;
        std::cout << "    -f <num>        Coarseness factor (> 1.0)" << std::endl;
        std::cout << "    -l <num>        Maximum number of computing devices (OpenCL only)" << std::endl;
        std::cout << "    -b <code>       Boundary Conditions" << std::endl;
        std::cout << "                    Codes: Combination of 'w' (WALL) and 'o' (OUTFLOW)" << std::endl;
        std::cout << "                      One char: Option for ALL boundaries" << std::endl;
        std::cout << "                      Two chars: Options for left/right and top/bottom boundaries" << std::endl;
        std::cout << "                      Four chars: Options for left, right, bottom, top boundaries" << std::endl;
        std::cout << "    -i <filename>   Name of bathymetry data file" << std::endl;
        std::cout << "    -d <filename>   Name of displacement data file" << std::endl;
        std::cout << "    -c <filename>   Name of checkpointfile" << std::endl;
        std::cout << "    -s <scenario>   Name of artificial scenario" << std::endl;
        std::cout << "                    Scenarios: 'artificialtsunami', 'partialdambreak'" << std::endl;
        std::cout << "" << std::endl;
        std::cout << "Notes when using a checkpointfile:" << std::endl;
        std::cout << "    -x, -y, -n, -t, -b, -i, -d, -s are ignored (values are read from checkpointfile)" << std::endl;
        std::cout << "    An output file (-o) can be specified. In that case, the checkpointfile" << std::endl;
        std::cout << "    is copied to that location and output is appended to the output file." << std::endl;
        std::cout << "    If no output file is specified, output is appended to the checkpointfile." << std::endl;
        std::cout << "" << std::endl;
        std::cout << "Example: " << std::endl; 
        std::cout << "./SWE_<compiler>_<build>_none_dimsplit -x 100 -y 200 -o out -i b.nc -d d.nc -n 50 -b owwo" << std::endl;
        std::cout << "    will simulate a tsunami scenario using bathymetry from 'b.nc' and displacements ";
        std::cout << "from 'd.nc' on a grid of size 100 x 200 using outflow conditions for left and ";
        std::cout << "top boundary and wall conditions for right and bottom boundary, writing 50 checkpoints ";
        std::cout << "to out_<num>.nc" << std::endl;
        
        return 0;
    }
    
    //! output file basename (with block coordinates)
    std::string l_outputFileName = generateBaseFileName(l_baseName,0,0);
    
#ifdef WRITENETCDF
    if(l_scenarioName != SCENARIO_CHECKPOINT_TSUNAMI) {
        // This is a tsunami scenario, check if the output file (with .nc-extension) exists
        // In that case switch to checkpoint scenario
        int ncOutputFile;
        int status = nc_open((l_outputFileName + ".nc").c_str(), NC_NOWRITE, &ncOutputFile);
        if(status == NC_NOERR) {
            // Output file exists and is a NetCDF file => switch to checkpointing
            l_scenarioName = SCENARIO_CHECKPOINT_TSUNAMI;
            l_checkpointFileName = l_outputFileName;
            nc_close(ncOutputFile);
        }
    }
#endif
    
    //! Pointer to instance of chosen scenario
    SWE_Scenario *l_scenario;
    
    // Create scenario according to chosen options
    switch(l_scenarioName) {
#ifdef WRITENETCDF
        case SCENARIO_TSUNAMI:
            l_scenario = new SWE_TsunamiScenario(l_bathymetryFileName, l_displacementFileName);
            
            // overwrite boundary conditions from scenario in case they have 
            // been explicitly set using command line arguments
            if(l_overwriteBoundaryTypes)
                ((SWE_TsunamiScenario *)l_scenario)->setBoundaryTypes(l_boundaryTypes);
            break;
        case SCENARIO_CHECKPOINT_TSUNAMI:
            l_scenario = new SWE_CheckpointTsunamiScenario(l_checkpointFileName + ".nc");
            
            // Read number if grid cells from checkpoint
            ((SWE_CheckpointTsunamiScenario *)l_scenario)->getNumberOfCells(l_nX, l_nY);
            
            if(l_overwriteBoundaryTypes)
                std::cerr << "WARNING: Loading checkpointed Simulation does not support "
                          << "explicitly setting boundary conditions" << std::endl;
            break;
#endif
        case SCENARIO_ARTIFICIAL_TSUNAMI:
            l_scenario = new SWE_ArtificialTsunamiScenario();

            // overwrite boundary conditions from scenario in case they have 
            // been explicitly set using command line arguments
            if(l_overwriteBoundaryTypes)
                ((SWE_ArtificialTsunamiScenario *)l_scenario)->setBoundaryTypes(l_boundaryTypes);
            break;
        case SCENARIO_PARTIAL_DAMBREAK:
            l_scenario = new SWE_PartialDambreak();
            if(l_overwriteBoundaryTypes)
                std::cerr << "WARNING: PartialDambreak-Scenario does not support "
                          << "explicitly setting boundary conditions" << std::endl;
            break;
        default:
            std::cerr << "Invalid Scenario" << std::endl;
            exit(1);
            break;
    }

    //! size of a single cell in x- and y-direction
    float l_dX, l_dY;
    
    // compute the size of a single cell
    l_dX = (l_scenario->getBoundaryPos(BND_RIGHT) - l_scenario->getBoundaryPos(BND_LEFT) )/l_nX;
    l_dY = (l_scenario->getBoundaryPos(BND_TOP) - l_scenario->getBoundaryPos(BND_BOTTOM) )/l_nY;
    
    //! Dimensional Splitting Block
#ifndef USEOPENCL
    SWE_DimensionalSplitting l_dimensionalSplitting(l_nX, l_nY, l_dX, l_dY);
#else
    SWE_DimensionalSplittingOpenCL l_dimensionalSplitting(l_nX, l_nY, l_dX, l_dY, 0, l_maxDevices, l_kernelType, l_maxGroupSize);
    l_dimensionalSplitting.printDeviceInformation();
#endif
    
    //! origin of the simulation domain in x- and y-direction
    float l_originX, l_originY;

    // get the origin from the scenario
    l_originX = l_scenario->getBoundaryPos(BND_LEFT);
    l_originY = l_scenario->getBoundaryPos(BND_BOTTOM);

    // initialize the wave propagation block
    l_dimensionalSplitting.initScenario(l_originX, l_originY, *l_scenario);
    
    //! time when the simulation ends.
    float l_endSimulation;
    if(l_simulationTime <= 0.0) {
        // We haven't got a valid simulation time as arguments, use the pre-defied one from scenario
        l_endSimulation = l_scenario->endSimulation();
    } else {
        // Use time given from command line
        l_endSimulation = l_simulationTime;
    }
    
    //! simulation time.
    float l_t = 0.0;
    
    //! checkpoint counter
    int l_checkpoint = 1;

#ifdef WRITENETCDF
    if(l_scenarioName == SCENARIO_CHECKPOINT_TSUNAMI) {
        // read total number of checkpoints
        l_numberOfCheckPoints = ((SWE_CheckpointTsunamiScenario *)l_scenario)->getNumberOfCheckpoints();
        
        // load last checkpoint and timestep from scenario (checkpoint-file)
        ((SWE_CheckpointTsunamiScenario *)l_scenario)->getLastCheckpoint(l_checkpoint, l_t);
        l_checkpoint++;
        
        // forace coarseness of 1 if reading from checkpoint data
        l_coarseness = 1.0;
    }
#endif
    
    // read actual boundary types (command line merged with scenario)
    l_boundaryTypes[BND_LEFT] = l_scenario->getBoundaryType(BND_LEFT);
    l_boundaryTypes[BND_RIGHT] = l_scenario->getBoundaryType(BND_RIGHT);
    l_boundaryTypes[BND_BOTTOM] = l_scenario->getBoundaryType(BND_BOTTOM);
    l_boundaryTypes[BND_TOP] = l_scenario->getBoundaryType(BND_TOP);
    
    //! checkpoints when output files are written.
    float* l_checkPoints = new float[l_numberOfCheckPoints+1];
    
    // compute the checkpoints in time
    for(int cp = 0; cp <= l_numberOfCheckPoints; cp++) {
        l_checkPoints[cp] = cp*(l_endSimulation/l_numberOfCheckPoints);
    }
    
    // Init fancy progressbar
    tools::ProgressBar progressBar(l_endSimulation);
    
    // write the output at time zero
    tools::Logger::logger.printOutputTime((float) l_t);
    progressBar.update(l_t);
    
    //boundary size of the ghost layers
    io::BoundarySize l_boundarySize = {{1, 1, 1, 1}};
    
    // Delete scenarioto free resources and close opened files
    delete l_scenario;
    
#ifdef WRITENETCDF
    if(l_scenarioName == SCENARIO_CHECKPOINT_TSUNAMI) {
        if(l_baseName.empty()) {
            // If there is no output file name given, use the checkpoint file
            l_outputFileName = l_checkpointFileName;
        } else if(l_outputFileName.compare(l_checkpointFileName) != 0) {
            // output file name given and it is not equal to the checkpoint file
            // therefore, we have to make a copy of our checkpointfile
            // in order to continue the simulation
            std::ifstream src((l_checkpointFileName + ".nc").c_str());
            std::ofstream dst((l_outputFileName + ".nc").c_str());
            dst << src.rdbuf();
        }
    }

    //construct a NetCdfWriter
    io::NetCdfWriter l_writer( l_outputFileName,
        l_dimensionalSplitting.getBathymetry(),
  		l_boundarySize,
  		l_nX, l_nY,
  		l_dX, l_dY,
  		l_originX, l_originY,
        l_coarseness);
        
        l_writer.writeSimulationInfo(l_numberOfCheckPoints, l_endSimulation, l_boundaryTypes);
#else
    // consturct a VtkWriter
    io::VtkWriter l_writer( l_outputFileName,
  		l_dimensionalSplitting.getBathymetry(),
  		l_boundarySize,
  		l_nX, l_nY,
  		l_dX, l_dY,
        0, 0,
        l_coarseness);
#endif
    if(l_scenarioName != SCENARIO_CHECKPOINT_TSUNAMI) {
        // Write zero time step
        l_writer.writeTimeStep( l_dimensionalSplitting.getWaterHeight(),
                                l_dimensionalSplitting.getDischarge_hu(),
                                l_dimensionalSplitting.getDischarge_hv(), 
                                (float) 0.);
    }
        
    /**
     * Simulation.
     */
    // print the start message and reset the wall clock time
    progressBar.clear();
    tools::Logger::logger.printStartMessage();
    tools::Logger::logger.initWallClockTime(time(NULL));
    
    progressBar.update(l_t);
    
    unsigned int l_iterations = 0;
    
    // loop over checkpoints
    while(l_checkpoint <= l_numberOfCheckPoints) {
        
        // do time steps until next checkpoint is reached
        while( l_t < l_checkPoints[l_checkpoint] ) {
            // set values in ghost cells:
            l_dimensionalSplitting.setGhostLayer();
            
            // reset the cpu clock
            tools::Logger::logger.resetCpuClockToCurrentTime();
            
            // compute numerical flux on each edge
            l_dimensionalSplitting.computeNumericalFluxes();
            
            //! maximum allowed time step width.
            float l_maxTimeStepWidth = l_dimensionalSplitting.getMaxTimestep();
            
            // update the cell values
            l_dimensionalSplitting.updateUnknowns(l_maxTimeStepWidth);
            
            // update the cpu time in the logger
            tools::Logger::logger.updateCpuTime();
            
            // update simulation time with time step width.
            l_t += l_maxTimeStepWidth;
            l_iterations++;
            
            // print the current simulation time
            progressBar.clear();
            tools::Logger::logger.printSimulationTime(l_t);
            progressBar.update(l_t);
        }
        // print current simulation time of the output
        progressBar.clear();
        tools::Logger::logger.printOutputTime(l_t);
        progressBar.update(l_t);
        
        // write output
        l_writer.writeTimeStep( l_dimensionalSplitting.getWaterHeight(),
                              l_dimensionalSplitting.getDischarge_hu(),
                              l_dimensionalSplitting.getDischarge_hv(),
                              l_t);
        
        l_checkpoint++;
    }
    
    /**
     * Finalize.
     */
    // write the statistics message
    progressBar.clear();
    tools::Logger::logger.printStatisticsMessage();
    
    // print the cpu time
    tools::Logger::logger.printCpuTime();
    
    // print the wall clock time (includes plotting)
    tools::Logger::logger.printWallClockTime(time(NULL));
    
    // printer iteration counter
    tools::Logger::logger.printIterationsDone(l_iterations);
    
    // print average time per cell per iteration
    tools::Logger::logger.printAverageCPUTimePerCellPerIteration(l_iterations, l_nX*(l_nY+2)); 
    
#ifdef USEOPENCL
    // print opencl stats
    l_dimensionalSplitting.printProfilingInformation();
#endif
    
    return 0;
}
コード例 #30
0
/*
==============
idSessionLocal::HandleSaveGameMenuCommands
==============
*/
bool idSessionLocal::HandleSaveGameMenuCommand( idCmdArgs &args, int &icmd ) {

	const char *cmd = args.Argv(icmd-1);

	if ( !idStr::Icmp( cmd, "loadGame" ) ) {
		int choice = guiActive->State().GetInt("loadgame_sel_0");
		if ( choice >= 0 && choice < loadGameList.Num() ) {
			sessLocal.LoadGame( loadGameList[choice] );
		}
		return true;
	}

	if ( !idStr::Icmp( cmd, "saveGame" ) ) {
		const char *saveGameName = guiActive->State().GetString("saveGameName");
		if ( saveGameName && saveGameName[0] ) {

			// First see if the file already exists unless they pass '1' to authorize the overwrite
			if ( icmd == args.Argc() || atoi(args.Argv( icmd++ )) == 0 ) {
				idStr saveFileName = saveGameName;
				sessLocal.ScrubSaveGameFileName( saveFileName );
				saveFileName = "savegames/" + saveFileName;
				saveFileName.SetFileExtension(".save");

				idStr game = cvarSystem->GetCVarString( "fs_game" );
				idFile *file;
				if(game.Length()) {
					file = fileSystem->OpenFileRead( saveFileName, true, game );
				} else {
					file = fileSystem->OpenFileRead( saveFileName );
				}
				
				if ( file != NULL ) {
					fileSystem->CloseFile( file );

					// The file exists, see if it's an autosave
					saveFileName.SetFileExtension(".txt");
					idLexer src(LEXFL_NOERRORS|LEXFL_NOSTRINGCONCAT);
					if ( src.LoadFile( saveFileName ) ) {
						idToken tok;
						src.ReadToken( &tok ); // Name
						src.ReadToken( &tok ); // Map
						src.ReadToken( &tok ); // Screenshot
						if ( !tok.IsEmpty() ) {
							// NOTE: base/ gui doesn't handle that one
							guiActive->HandleNamedEvent( "autosaveOverwriteError" );
							return true;
						}
					}
					guiActive->HandleNamedEvent( "saveGameOverwrite" );
					return true;
				}
			}

			sessLocal.SaveGame( saveGameName );
			SetSaveGameGuiVars( );
			guiActive->StateChanged( com_frameTime );
		}
		return true;
	}

	if ( !idStr::Icmp( cmd, "deleteGame" ) ) {
		int choice = guiActive->State().GetInt( "loadgame_sel_0" );
		if ( choice >= 0 && choice < loadGameList.Num() ) {
			fileSystem->RemoveFile( va("savegames/%s.save", loadGameList[choice].c_str()) );
			fileSystem->RemoveFile( va("savegames/%s.tga", loadGameList[choice].c_str()) );
			fileSystem->RemoveFile( va("savegames/%s.txt", loadGameList[choice].c_str()) );
			SetSaveGameGuiVars( );
			guiActive->StateChanged( com_frameTime );
		}
		return true;
	}

	if ( !idStr::Icmp( cmd, "updateSaveGameInfo" ) ) {
		int choice = guiActive->State().GetInt( "loadgame_sel_0" );
		if ( choice >= 0 && choice < loadGameList.Num() ) {
			const idMaterial *material;

			idStr saveName, description, screenshot;
			idLexer src(LEXFL_NOERRORS|LEXFL_NOSTRINGCONCAT);
			if ( src.LoadFile( va("savegames/%s.txt", loadGameList[choice].c_str()) ) ) {
				idToken tok;

				src.ReadToken( &tok );
				saveName = tok;

				src.ReadToken( &tok );
				description = tok;

				src.ReadToken( &tok );
				screenshot = tok;

			} else {
				saveName = loadGameList[choice];
				description = loadGameList[choice];
				screenshot = "";
			}
			if ( screenshot.Length() == 0 ) {
				screenshot = va("savegames/%s.tga", loadGameList[choice].c_str());
			}
			material = declManager->FindMaterial( screenshot );
			if ( material ) {
				material->ReloadImages( false );
			}
			guiActive->SetStateString( "loadgame_shot",  screenshot );

			saveName.RemoveColors();
			guiActive->SetStateString( "saveGameName", saveName );
			guiActive->SetStateString( "saveGameDescription", description );

			ID_TIME_T timeStamp;
			fileSystem->ReadFile( va("savegames/%s.save", loadGameList[choice].c_str()), NULL, &timeStamp );
			idStr date = Sys_TimeStampToStr(timeStamp);
			int tab = date.Find( '\t' );
			idStr time = date.Right( date.Length() - tab - 1);
			guiActive->SetStateString( "saveGameDate", date.Left( tab ) );
			guiActive->SetStateString( "saveGameTime", time );
		}
		return true;
	}

	return false;
}