void ImportProjectFile::getCentroidFiles () { for ( int i = 0 ; i < centroid.size () ; i++ ) { centroidFiles.push_back ( genFilenameFromPath ( centroid [i] ) ); } }
//**************************************************************************************************** ERMsg CEnvCanGribForecast::Execute(CCallback& callback) { ERMsg msg; //string outputPath = GetDir(WORKING_DIR); callback.AddMessage(GetString(IDS_UPDATE_DIR)); callback.AddMessage(m_workingDir, 1); callback.AddMessage(GetString(IDS_UPDATE_FROM)); callback.AddMessage(SERVER_NAME, 1); callback.AddMessage(""); //delete old files msg = RemoveOldForecast(callback); if (!msg) return msg; CInternetSessionPtr pSession; CHttpConnectionPtr pConnection; msg = GetHttpConnection(SERVER_NAME, pConnection, pSession); if (!msg) return msg; //size_t type = as<size_t>(TYPE); size_t delta_h = m_type == GT_HRDPS ? 1 : 3; callback.PushTask("Download gribs list", (MAX_FORECAST_HOURS / delta_h) ); StringVector fileList; //for (size_t HH = 0; HH < 24 && msg; HH+=6) size_t HH = GetLatestHH(pConnection); if (HH!=NOT_INIT) { for (size_t hhh = 0; hhh <= MAX_FORECAST_HOURS && msg; hhh += delta_h) { string remotePath = CEnvCanGribForecast::GetRemoteFilePath(HH, hhh, "*.grib2"); CFileInfoVector fileListTmp; msg = FindFiles(pConnection, remotePath, fileListTmp); //keep only some variables for (CFileInfoVector::iterator it = fileListTmp.begin(); it != fileListTmp.end(); it++) { string fileName = GetFileName(it->m_filePath); size_t hhh = Gethhh(fileName); size_t vv = GetVariable(fileName); if (hhh <= 48 && vv != NOT_INIT) fileList.push_back(it->m_filePath); } msg += callback.StepIt(); } } callback.PopTask(); callback.AddMessage("Number of gribs to download: " + ToString(fileList.size())); callback.PushTask("Download gribs (" + ToString(fileList.size()) +")", fileList.size()); int nbDownload = 0; for (size_t i = 0; i < fileList.size() && msg; i++) { string outputFilePath = GetOutputFilePath(GetFileName(fileList[i])); CreateMultipleDir(GetPath(outputFilePath)); msg = CopyFile(pConnection, fileList[i], outputFilePath.c_str(), INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_DONT_CACHE); if (msg) nbDownload++; msg += callback.StepIt(); } pConnection->Close(); pSession->Close(); callback.AddMessage("Number of gribs downloaded: " + ToString(nbDownload)); callback.PopTask(); return msg; }
int main (int argc, const char** argv) { if (argc < 2) { printf ("USAGE: glsloptimizer testfolder\n"); return 1; } bool hasOpenGL = InitializeOpenGL (); glslopt_ctx* ctx[2] = { glslopt_initialize(true), glslopt_initialize(false), }; std::string baseFolder = argv[1]; clock_t time0 = clock(); static const char* kTypeName[2] = { "vertex", "fragment" }; size_t tests = 0; size_t errors = 0; for (int type = 0; type < 2; ++type) { std::string testFolder = baseFolder + "/" + kTypeName[type]; static const char* kAPIName[2] = { "OpenGL ES 2.0", "OpenGL" }; static const char* kApiIn [2] = {"-inES.txt", "-in.txt"}; static const char* kApiIR [2] = {"-irES.txt", "-ir.txt"}; static const char* kApiOut[2] = {"-outES.txt", "-out.txt"}; for (int api = 0; api < 2; ++api) { printf ("\n** running %s tests for %s...\n", kTypeName[type], kAPIName[api]); StringVector inputFiles = GetFiles (testFolder, kApiIn[api]); size_t n = inputFiles.size(); for (size_t i = 0; i < n; ++i) { std::string inname = inputFiles[i]; //if (inname != "ast-in.txt") // continue; std::string hirname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiIR[api]; std::string outname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiOut[api]; bool ok = TestFile (ctx[api], type==0, inname, testFolder + "/" + inname, testFolder + "/" + hirname, testFolder + "/" + outname, api==0, hasOpenGL); if (!ok) { ++errors; } ++tests; } } } clock_t time1 = clock(); float timeDelta = float(time1-time0)/CLOCKS_PER_SEC; if (errors != 0) printf ("\n**** %i tests (%.2fsec), %i !!!FAILED!!!\n", tests, timeDelta, errors); else printf ("\n**** %i tests (%.2fsec) succeeded\n", tests, timeDelta); // 3.25s // with builtin call linking, 3.84s for (int i = 0; i < 2; ++i) glslopt_cleanup (ctx[i]); return errors ? 1 : 0; }
void X11EGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams) { if (miscParams) { NameValuePairList::const_iterator opt; NameValuePairList::const_iterator end = miscParams->end(); mExternalWindow = 0; mNativeDisplay = mGLSupport->getNativeDisplay(); mParentWindow = DefaultRootWindow((Display*)mNativeDisplay); if ((opt = miscParams->find("parentWindowHandle")) != end) { //vector<String>::type tokens = StringUtil::split(opt->second, " :"); StringVector tokens = StringUtil::split(opt->second, " :"); if (tokens.size() == 3) { // deprecated display:screen:xid format mParentWindow = (Window)StringConverter::parseUnsignedLong(tokens[2]); } else { // xid format mParentWindow = (Window)StringConverter::parseUnsignedLong(tokens[0]); } } else if ((opt = miscParams->find("externalWindowHandle")) != end) { //vector<String>::type tokens = StringUtil::split(opt->second, " :"); StringVector tokens = StringUtil::split(opt->second, " :"); LogManager::getSingleton().logMessage( "EGLWindow::create: The externalWindowHandle parameter is deprecated.\n" "Use the parentWindowHandle or currentGLContext parameter instead."); if (tokens.size() == 3) { // Old display:screen:xid format // The old EGL code always created a "parent" window in this case: mParentWindow = (Window)StringConverter::parseUnsignedLong(tokens[2]); } else if (tokens.size() == 4) { // Old display:screen:xid:visualinfo format mExternalWindow = (Window)StringConverter::parseUnsignedLong(tokens[2]); } else { // xid format mExternalWindow = (Window)StringConverter::parseUnsignedLong(tokens[0]); } } } // Ignore fatal XErrorEvents during parameter validation: oldXErrorHandler = XSetErrorHandler(safeXErrorHandler); // Validate parentWindowHandle if (mParentWindow != DefaultRootWindow((Display*)mNativeDisplay)) { XWindowAttributes windowAttrib; if (!XGetWindowAttributes((Display*)mNativeDisplay, mParentWindow, &windowAttrib) || windowAttrib.root != DefaultRootWindow((Display*)mNativeDisplay)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid parentWindowHandle (wrong server or screen)", "EGLWindow::create"); } } // Validate externalWindowHandle if (mExternalWindow != 0) { XWindowAttributes windowAttrib; if (!XGetWindowAttributes((Display*)mNativeDisplay, mExternalWindow, &windowAttrib) || windowAttrib.root != DefaultRootWindow((Display*)mNativeDisplay)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid externalWindowHandle (wrong server or screen)", "EGLWindow::create"); } mEglConfig = 0; mEglSurface = createSurfaceFromWindow(mEglDisplay, (NativeWindowType)mExternalWindow); } XSetErrorHandler(oldXErrorHandler); mIsTopLevel = (!mIsExternal && mParentWindow == DefaultRootWindow((Display*)mNativeDisplay)); }
// Extract reads from an FM-index that have a k-mer match to any given haplotypes // Returns true if the reads were successfully extracted, false if there are // more reads than maxReads bool HapgenUtil::extractHaplotypeReads(const StringVector& haplotypes, const BWTIndexSet& indices, int k, bool doReverse, size_t maxReads, SeqRecordVector* pOutReads, SeqRecordVector* pOutMates) { // Skip repetitive kmers with more than this many occurrences int64_t SKIP_INTERVAL_SIZE = 500; // Extract the set of reads that have at least one kmer shared with these haplotypes // This is a bit of a lengthy procedure with a few steps: // 1) extract all the kmers in the haplotypes // 2) find the intervals for the kmers in the fm-index // 3) compute the set of read indices of the reads from the intervals (using the sampled suffix array) // 4) finally, extract the read sequences from the index // Make a set of kmers from the haplotypes std::set<std::string> kmerSet; for(size_t i = 0; i < haplotypes.size(); ++i) { const std::string& h = haplotypes[i]; if((int)h.size() < k) continue; for(size_t j = 0; j < h.size() - k + 1; ++j) { std::string ks = h.substr(j, k); if(doReverse) ks = reverseComplement(ks); kmerSet.insert(ks); } } // Compute suffix array intervals for the kmers std::vector<BWTInterval> intervals; for(std::set<std::string>::const_iterator iter = kmerSet.begin(); iter != kmerSet.end(); ++iter) { BWTInterval interval = BWTAlgorithms::findInterval(indices, *iter); if(interval.size() > (int64_t)maxReads) return false; if(interval.size() < SKIP_INTERVAL_SIZE) intervals.push_back(interval); } // Compute the set of reads ids std::set<int64_t> readIndices; for(size_t i = 0; i < intervals.size(); ++i) { BWTInterval interval = intervals[i]; for(int64_t j = interval.lower; j <= interval.upper; ++j) { // Get index from sampled suffix array SAElem elem = indices.pSSA->calcSA(j, indices.pBWT); readIndices.insert(elem.getID()); } } // Check if we have hit the limit of extracting too many reads if(readIndices.size() > maxReads) return false; for(std::set<int64_t>::const_iterator iter = readIndices.begin(); iter != readIndices.end(); ++iter) { int64_t idx = *iter; // Extract the read std::stringstream namer; namer << "idx-" << idx; SeqRecord record; record.id = namer.str(); record.seq = BWTAlgorithms::extractString(indices.pBWT, idx); assert(indices.pQualityTable != NULL); record.qual = indices.pQualityTable->getQualityString(idx, record.seq.length()); if(!record.seq.empty()) pOutReads->push_back(record); // Optionally extract its mate // If the index is constructed properly, // paired reads are in adjacent indices with the // first read at even indices if(pOutMates != NULL) { int64_t mateIdx = idx; if(idx % 2 == 0) mateIdx += 1; else mateIdx -= 1; std::stringstream mateName; mateName << "idx-" << mateIdx; SeqRecord mateRecord; mateRecord.id = mateName.str(); mateRecord.seq = BWTAlgorithms::extractString(indices.pBWT, mateIdx); mateRecord.qual = indices.pQualityTable->getQualityString(mateIdx, mateRecord.seq.length()); if(!record.seq.empty() && !mateRecord.seq.empty()) pOutMates->push_back(mateRecord); } } return true; }
int main(int argc, char *argv[]) { int count = 0; /* match count for each line */ int maxmatch = 0; /* max match for outout campaign */ string name; if (argc < 2) { cout << "Please enter a file path\n"; return -1; } std::ifstream ifsReadFile( argv[1] ); if( ifsReadFile ) { cout<<"Wait for user to type in the input data ..."<<endl; string input_line; getline(cin, input_line); StringVector vInput; StringVector vOutput; Split( input_line, " ", vInput ); std::string sFileLine; while( getline( ifsReadFile, sFileLine ) ) { StringVector vResult; Split( sFileLine, " ", vResult ); for(int i=1;i<vResult.size();i++) { for(int j=0;j<vInput.size();j++) { if(vResult[i].compare(vInput[j]) == 0) { count++; break; } } } if(count > maxmatch || (count == maxmatch && count!= 0)) { maxmatch = count; count = 0; vOutput.push_back( vResult[0] ); name = vResult[0]; } else { count = 0; } } if(maxmatch == 0) { cout<<"No campaign is matched "<<endl; } else { srand ( time(NULL) ); int index = rand() % vOutput.size(); cout<<"index"<<index<<"output size"<<vOutput.size()<<endl; cout<<"Output Campaign is : "<<vOutput[index]<<name<<endl; } } else { std::cerr << "Error: Cannot open the file." << std::endl; return -1; } return 0; }
void RenderSystemCapabilitiesSerializer::parseCapabilitiesLines(CapabilitiesLinesList& lines) { StringVector tokens; for (CapabilitiesLinesList::iterator it = lines.begin(), end = lines.end(); it != end; ++it) { // restore the current line information for debugging mCurrentLine = &(it->first); mCurrentLineNumber = it->second; tokens = StringUtil::split(it->first); // check for incomplete lines if(tokens.size() < 2) { logParseError("No parameters given for the capability keyword"); continue; } // the first token must the the keyword identifying the capability // the remaining tokens are the parameters String keyword = tokens[0]; String everythingElse = ""; for(unsigned int i = 1; i < tokens.size() - 1; i ++) { everythingElse = everythingElse + tokens[i] + " "; } everythingElse = everythingElse + tokens[tokens.size() - 1]; CapabilityKeywordType keywordType = getKeywordType(keyword); switch(keywordType) { case UNDEFINED_CAPABILITY_TYPE: logParseError("Unknown capability keyword: " + keyword); break; case SET_STRING_METHOD: callSetStringMethod(keyword, everythingElse); break; case SET_INT_METHOD: { ushort integer = (ushort)StringConverter::parseInt(tokens[1]); callSetIntMethod(keyword, integer); break; } case SET_BOOL_METHOD: { bool b = StringConverter::parseBool(tokens[1]); callSetBoolMethod(keyword, b); break; } case SET_REAL_METHOD: { Real real = StringConverter::parseReal(tokens[1]); callSetRealMethod(keyword, real); break; } case ADD_SHADER_PROFILE_STRING: { addShaderProfile(tokens[1]); break; } case SET_CAPABILITY_ENUM_BOOL: { bool b = StringConverter::parseBool(tokens[1]); setCapabilityEnumBool(tokens[0], b); break; } } } }
//----------------------------------------------------------------------- void Quake3ShaderManager::parseShaderPassAttrib( const String& line, Quake3Shader* pShader, Quake3Shader::Pass* pPass) { StringVector vecparams; vecparams = StringUtil::split(line, " \t"); StringVector::iterator params = vecparams.begin(); StringUtil::toLowerCase(params[0]); if (params[0] != "map" && params[0] != "clampmap" && params[0] != "animmap") { // lower case all except textures for (size_t i = 1; i < vecparams.size(); ++i) StringUtil::toLowerCase(params[i]); } // MAP if (params[0] == "map") { pPass->textureName = params[1]; StringUtil::toLowerCase(params[1]); if (params[1] == "$lightmap") pPass->texGen = TEXGEN_LIGHTMAP; } // CLAMPMAP if (params[0] == "clampmap") { pPass->textureName = params[1]; StringUtil::toLowerCase(params[1]); if (params[1] == "$lightmap") pPass->texGen = TEXGEN_LIGHTMAP; pPass->addressMode = TextureUnitState::TAM_CLAMP; } // ANIMMAP else if (params[0] == "animmap") { pPass->animFps = atof(params[1].c_str()); pPass->animNumFrames = static_cast<unsigned int>( vecparams.size() - 2 ); for (unsigned int frame = 0; frame < pPass->animNumFrames; ++frame) { pPass->frames[frame] = params[frame+2]; } } // BLENDFUNC else if (params[0] == "blendfunc") { if (params[1] == "add" || params[1] == "gl_add") { pPass->blend = LBO_ADD; pPass->blendDest = SBF_ONE; pPass->blendSrc = SBF_ONE; } else if (params[1] == "filter" || params[1] == "gl_filter") { pPass->blend = LBO_MODULATE; pPass->blendDest = SBF_ZERO; pPass->blendSrc = SBF_DEST_COLOUR; } else if (params[1] == "blend" || params[1] == "gl_blend") { pPass->blend = LBO_ALPHA_BLEND; pPass->blendDest = SBF_ONE_MINUS_SOURCE_ALPHA; pPass->blendSrc = SBF_SOURCE_ALPHA; } else { // Manual blend pPass->blendSrc = convertBlendFunc(params[1]); pPass->blendDest = convertBlendFunc(params[2]); // Detect common blends if (pPass->blendSrc == SBF_ONE && pPass->blendDest == SBF_ZERO) pPass->blend = LBO_REPLACE; else if (pPass->blendSrc == SBF_ONE && pPass->blendDest == SBF_ONE) pPass->blend = LBO_ADD; else if ((pPass->blendSrc == SBF_ZERO && pPass->blendDest == SBF_SOURCE_COLOUR) || (pPass->blendSrc == SBF_DEST_COLOUR && pPass->blendDest == SBF_ZERO)) pPass->blend = LBO_MODULATE; else if (pPass->blendSrc == SBF_SOURCE_ALPHA && pPass->blendDest == SBF_ONE_MINUS_SOURCE_ALPHA) pPass->blend = LBO_ALPHA_BLEND; else pPass->customBlend = true; // NB other custom blends might not work due to OGRE trying to use multitexture over multipass } } // RGBGEN else if (params[0] == "rgbgen") { // TODO } // ALPHAGEN else if (params[0] == "alphagen") { // TODO } // TCGEN else if (params[0] == "tcgen") { if (params[1] == "base") { pPass->texGen = TEXGEN_BASE; } else if (params[1] == "lightmap") { pPass->texGen = TEXGEN_LIGHTMAP; } else if (params[1] == "environment") { pPass->texGen = TEXGEN_ENVIRONMENT; } } // TCMOD else if (params[0] == "tcmod") { if (params[1] == "rotate") { pPass->tcModRotate = -atof(params[2].c_str()) / 360; // +ve is clockwise degrees in Q3 shader, anticlockwise complete rotations in Ogre } else if (params[1] == "scroll") { pPass->tcModScroll[0] = atof(params[2].c_str()); pPass->tcModScroll[1] = atof(params[3].c_str()); } else if (params[1] == "scale") { pPass->tcModScale[0] = atof(params[2].c_str()); pPass->tcModScale[1] = atof(params[3].c_str()); } else if (params[1] == "stretch") { if (params[2] == "sin") pPass->tcModStretchWave = SHADER_FUNC_SIN; else if (params[2] == "triangle") pPass->tcModStretchWave = SHADER_FUNC_TRIANGLE; else if (params[2] == "square") pPass->tcModStretchWave = SHADER_FUNC_SQUARE; else if (params[2] == "sawtooth") pPass->tcModStretchWave = SHADER_FUNC_SAWTOOTH; else if (params[2] == "inversesawtooth") pPass->tcModStretchWave = SHADER_FUNC_INVERSESAWTOOTH; pPass->tcModStretchParams[0] = atof(params[3].c_str()); pPass->tcModStretchParams[1] = atof(params[4].c_str()); pPass->tcModStretchParams[2] = atof(params[5].c_str()); pPass->tcModStretchParams[3] = atof(params[6].c_str()); } } // TURB else if (params[0] == "turb") { pPass->tcModTurbOn = true; pPass->tcModTurb[0] = atof(params[2].c_str()); pPass->tcModTurb[1] = atof(params[3].c_str()); pPass->tcModTurb[2] = atof(params[4].c_str()); pPass->tcModTurb[3] = atof(params[5].c_str()); } // DEPTHFUNC else if (params[0] == "depthfunc") { // TODO } // DEPTHWRITE else if (params[0] == "depthwrite") { // TODO } // ALPHAFUNC else if (params[0] == "alphafunc") { if (params[1] == "gt0") { pPass->alphaVal = 0; pPass->alphaFunc = CMPF_GREATER; } else if (params[1] == "ge128") { pPass->alphaVal = 128; pPass->alphaFunc = CMPF_GREATER_EQUAL; } else if (params[1] == "lt128") { pPass->alphaVal = 128; pPass->alphaFunc = CMPF_LESS; } } }
NitRuntime* wxNitShellApp::createRuntime() { NitRuntime* rt = new DefaultRuntime(this); rt->setArguments(this->argc, this->argv); // NOTE: rt may be destroyed within this function. // So do not use nit::string or RefCounted which is related MemManager std::string error; _shellConfig = new Settings(); nit::Ref<Settings> cs = new Settings(); nit::Ref<CmdLineParser> parser = new CmdLineParser(); LogManager::getSingleton().setDefaultLogLevel(LOG_LEVEL_ERROR); try { parser->allowUnknownOptions(true); parser->allowUnknownParams(true); _shellConfig->add("switch", "[-v verbose] : full verbosity (overrides log_filter)"); _shellConfig->add("switch", "[-q quiet] : quiet mode (overrides log_filter, verbose)"); _shellConfig->add("option", "[-w log_filter] : show log level equal or higher than this (default: ***)"); _shellConfig->add("option", "[-p pack_path ...] : path to pack path (can use $(macro) in app.Settings), relative to work_path"); parser->addParam("app.cfg", "path to app.cfg"); parser->addSection(_shellConfig); parser->parse(cs, rt, true); } catch (Exception& ex) { error = ex.getDescription().c_str(); } if (error.empty() && !cs->has("app.cfg")) { error = "app.cfg path expected"; } cs->dump(); if (!error.empty()) { const char* appname = "nit.exe"; const char* logo = "nit-shell: command line Noriter shell v1.0\n" "nit: Noriter game-oriented app framework v1.0\n" "Copyright (c) 2013 Jun-hyeok Jang."; parser->showUsage(appname, logo, String("*** " ) + error.c_str()); // Release references before delete Mem Manager _shellConfig = NULL; cs = NULL; parser = NULL; safeDelete(rt); _exitCode = -1; return NULL; } LogManager& logMgr = LogManager::getSingleton(); if (cs->has("log_filter")) { const String& filter = _shellConfig->get("log_filter"); LogLevel lvl = logMgr.getLogLevel(logMgr.tagId(filter.c_str())); logMgr.setDefaultLogLevel(lvl); } if (cs->get("verbose", "false") == "true") logMgr.setDefaultLogLevel(LOG_LEVEL_VERBOSE); if (cs->get("quiet", "false") == "true") logMgr.setDefaultLogLevel(LOG_LEVEL_QUIET); StringVector paths; cs->find("pack_path", paths); for (uint i=0; i<paths.size(); ++i) _packPaths.push_back(paths[i].c_str()); _appConfigFilename = cs->get("app.cfg").c_str(); if (!StringUtil::endsWith(_appConfigFilename.c_str(), ".app.cfg")) _appConfigFilename += ".app.cfg"; return rt; }
void PackageManager::addLookupPaths(const StringVector& lookupPaths) { _lookupPaths.reserve(_lookupPaths.size() + lookupPaths.size()); for (const auto& path : lookupPaths) { _lookupPaths.push_back(path); } }
//----------------------------------------------------------------------- void GLSLESProgramPipeline::extractLayoutQualifiers(void) { // Format is: // layout(location = 0) attribute vec4 vertex; if(mVertexProgram) { String shaderSource = mVertexProgram->getGLSLProgram()->getSource(); String::size_type currPos = shaderSource.find("layout"); while (currPos != String::npos) { VertexElementSemantic semantic; GLint index = 0; String::size_type endPos = shaderSource.find(";", currPos); if (endPos == String::npos) { // Problem, missing semicolon, abort break; } String line = shaderSource.substr(currPos, endPos - currPos); // Skip over 'layout' currPos += 6; // Skip until '=' String::size_type eqPos = line.find("="); String::size_type parenPos = line.find(")"); // Skip past '=' up to a ')' which contains an integer(the position). This could be a definition, does the preprocessor do replacement? String attrLocation = line.substr(eqPos + 1, parenPos - eqPos - 1); StringUtil::trim(attrLocation); GLint attrib = StringConverter::parseInt(attrLocation); // The rest of the line is a standard attribute definition. // Erase up to it then split the remainder by spaces. line.erase (0, parenPos + 1); StringUtil::trim(line); StringVector parts = StringUtil::split(line, " "); if(parts.size() < 3) { // This is a malformed attribute // It should contain 3 parts, i.e. "attribute vec4 vertex" break; } String attrName = parts[2]; // Special case for attribute named position if(attrName == "position") semantic = getAttributeSemanticEnum("vertex"); else semantic = getAttributeSemanticEnum(attrName); // Find the texture unit index String::size_type uvPos = attrName.find("uv"); if(uvPos != String::npos) { String uvIndex = attrName.substr(uvPos + 2, attrName.length() - 2); index = StringConverter::parseInt(uvIndex); } mCustomAttributesIndexes[semantic-1][index] = attrib; currPos = shaderSource.find("layout", currPos); } } }
void FontTranslator::parseAttribute(ScriptCompiler* compiler, FontPtr& pFont, PropertyAbstractNode* prop) { String& attrib = prop->name; String val; if (attrib == "glyph") { float coords[4]; if (prop->values.size() != 5 || !getString(prop->values.front(), &val) || !getFloats(++prop->values.begin(), prop->values.end(), coords, 4)) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); return; } // Set // Support numeric and character glyph specification Font::CodePoint cp; if (val.size() > 1 && val[0] == 'u') { // Unicode glyph spec String trimmed = val.substr(1); cp = StringConverter::parseUnsignedInt(trimmed); } else { // Direct character cp = val[0]; } pFont->setGlyphTexCoords(cp, coords[0], coords[1], coords[2], coords[3], 1.0); // assume image is square } else if (attrib == "antialias_colour") { bool flag; if (prop->values.empty() || !getBoolean(prop->values.front(), &flag)) { compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); return; } pFont->setAntialiasColour(flag); } else if (attrib == "code_points") { if (prop->values.empty()) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); return; } for (auto& v : prop->values) { bool succ = getString(v, &val); StringVector itemVec = StringUtil::split(val, "-"); if (succ && itemVec.size() == 2) { pFont->addCodePointRange( Font::CodePointRange(StringConverter::parseUnsignedInt(itemVec[0]), StringConverter::parseUnsignedInt(itemVec[1]))); } } } else if (prop->values.empty() || !getString(prop->values.front(), &val) || !pFont->setParameter(attrib, val)) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); } }
bool VimbaSourceSink::Init() { VmbErrorType err=system.Startup(); CameraPtrVector cameras; if( VmbErrorSuccess == err ) { // now find all cameras err = system.GetCameras( cameras ); // Fetch all cameras known to Vimba if( VmbErrorSuccess == err ) { bool camIsOpen=false; if (cameras.size()==0) { CameraPtr ipCam; if ( VmbErrorSuccess == system.OpenCameraByID("169.254.1.55",VmbAccessModeFull,ipCam)) { qDebug()<<"IP camera opened"; cameras.push_back(ipCam); camIsOpen=true; } } if (cameras.size()>0) { if (cameras.size()>1) { QStringList cams; qDebug() << "Cameras found: " << cameras.size(); // should also implement Qinputdialog to let the user choose which one to use for (uint i=0;i<cameras.size();i++) { CameraPtr cam=cameras[i]; std::string namestr; err=cam->GetName(namestr); cams<<QString::fromStdString(namestr); qDebug()<<"Next Camera is: "<<QString::fromStdString(namestr); } bool camok; QString theOne = QInputDialog::getItem(NULL, "Multiple cameras present", "Selection options:", cams, 0, false, &camok); if (camok && !theOne.isEmpty()) { int index = cams.indexOf(theOne); pCamera=cameras[index]; } } else { // now open the first one only pCamera=cameras[0]; } std::string camID; std::string namestr; err=pCamera->GetName(namestr); err=pCamera->GetID(camID); if( VmbErrorSuccess == err ) { qDebug()<<"Opening camera "<<QString::fromStdString(namestr); if (!camIsOpen) err=pCamera->Open(VmbAccessModeFull); if (err==VmbErrorSuccess) { //camera successfully opened. Now do some camera initialisation steps // Set the GeV packet size to the highest possible value => will make JAI camera stop to work correctly! // (In this example we do not test whether this cam actually is a GigE cam) FeaturePtr pCommandFeature; /* if ( VmbErrorSuccess == pCamera->GetFeatureByName( "GVSPAdjustPacketSize", pCommandFeature )) { if ( VmbErrorSuccess == pCommandFeature->RunCommand() ) { bool bIsCommandDone = false; do { if ( VmbErrorSuccess != pCommandFeature->IsCommandDone( bIsCommandDone )) { break; } } while ( false == bIsCommandDone ); } } */ // get/set some features FeaturePtr pFeature; // Set Trigger source to fixedRate if it exists (only for AVT cameras) err=pCamera->GetFeatureByName("TriggerSource",pFeature); if (err==VmbErrorSuccess) { StringVector vals; pFeature->GetValues(vals); for (uint i =0;i<vals.size();i++) { if (QString::fromStdString(vals[i])=="FixedRate") { pFeature->SetValue("FixedRate"); } } } // get Camera timestamp frequency err=pCamera->GetFeatureByName("GevTimestampTickFrequency",pFeature); if (err==VmbErrorSuccess) { err=pFeature->GetValue(camFreq); if (err==VmbErrorSuccess) { qDebug()<<"Camera freq is "<<(1.0*camFreq); } else { qDebug()<<"Could not extract freq: "<<err; } } else { qDebug()<<"Could not query frequency: "<<err<<" => Will use LUT"; if (namestr=="GE1050") { camFreq=79861111; } else if (namestr=="GE1910") { camFreq=79861111; } else if (namestr=="GE2040") { camFreq=79861111; } else { qDebug()<<"Model not yet in LUT => unreliable timestamps"; camFreq=79861111; } } // Set acquisition mode to continuous err=pCamera->GetFeatureByName("AcquisitionMode",pFeature); if (err==VmbErrorSuccess) { pFeature->SetValue("Continuous"); // this should be continuous } // set/get maximum height and width of current camera err=pCamera->GetFeatureByName("WidthMax",pFeature); if (err==VmbErrorSuccess) { pFeature->GetValue(maxWidth); } /* err=pCamera->GetFeatureByName("Width",pFeature); if (err==VmbErrorSuccess) { pFeature->SetValue(maxWidth); pFeature->GetValue(width); // this should be continuous } */ err=pCamera->GetFeatureByName("HeightMax",pFeature); if (err==VmbErrorSuccess) { pFeature->GetValue(maxHeight); } /* err=pCamera->GetFeatureByName("Height",pFeature); if (err==VmbErrorSuccess) { pFeature->SetValue(maxHeight); pFeature->GetValue(height); // this should be continuous } */ // make sure shutter time is manual err=pCamera->GetFeatureByName("ExposureAuto",pFeature); if (err==VmbErrorSuccess) { pFeature->SetValue("Off"); // this should be manual exposure setting } // now let the user select the pixel format to be used std::vector<std::string> pixF; QStringList items; pixF=listPixelFormats(); for (uint i=0;i<pixF.size();i++) { if (pixF[i]=="Mono8") { items<<"MONO8"; } else if (pixF[i]=="Mono12") { items<<"MONO12"; } else if (pixF[i]=="Mono14") { items<<"MONO14"; } else if (pixF[i]=="BayerRG8") { items<<"BAYERRG8"; } else if (pixF[i]=="BayerGB8") { items<<"BAYERGB8"; } else if (pixF[i]=="BayerRG12") { items<<"BAYERRG12"; } else if (pixF[i]=="RGB8Packed") { items<<"RGB8Packed"; } else { if (!QString::fromStdString(pixF[i]).contains("12Packed")) { qDebug()<<"This pixel-mode not yet available in Gigaviewer: "<<QString::fromStdString(pixF[i]); } } } bool ok; QString item = QInputDialog::getItem(NULL, "Pixel format", "Selection options:", items, 0, false, &ok); if (ok && !item.isEmpty()) { format=item; setFormat(format); // qDebug()<<"Selected "<<format; } // construct the frame observer to the camera frameWatcher=new VimbaFrameObserver( pCamera, parent ); } else { // camera did not open successfully return false; } } } else { qDebug()<<"Zero cameras found"; return false; } } else { qDebug() << "Could not list cameras. Error code: " << err; return false; } } else { qDebug() << "Could not start system. Error code: " << err; return false; } return true; }
void ImportProjectFile::getRawFiles () { for ( int i = 0 ; i < raw.size () ; i++ ) { rawFiles.push_back ( genFilenameFromPath ( raw [i] ) ); } }
void Logger::initialise( const std::string &id, const Options &options ) { char *envPtr; if ( !id.empty() ) this->id( id ); std::string tempLogFile; if ( options.mLogPath.size() ) { mLogPath = options.mLogPath; tempLogFile = mLogPath+"/"+mId+".log"; } if ( options.mLogFile.size() ) tempLogFile = options.mLogFile; else tempLogFile = mLogPath+"/"+mId+".log"; if ( (envPtr = getTargettedEnv( "LOG_FILE" )) ) tempLogFile = envPtr; Level tempLevel = INFO; Level tempTermLevel = mTermLevel; Level tempDatabaseLevel = mDatabaseLevel; Level tempFileLevel = mFileLevel; Level tempSyslogLevel = mSyslogLevel; if ( options.mTermLevel != NOOPT ) tempTermLevel = options.mTermLevel; if ( options.mDatabaseLevel != NOOPT ) tempDatabaseLevel = options.mDatabaseLevel; else tempDatabaseLevel = config.log_level_database >= DEBUG1 ? DEBUG9 : config.log_level_database; if ( options.mFileLevel != NOOPT ) tempFileLevel = options.mFileLevel; else tempFileLevel = config.log_level_file >= DEBUG1 ? DEBUG9 : config.log_level_file; if ( options.mSyslogLevel != NOOPT ) tempSyslogLevel = options.mSyslogLevel; else tempSyslogLevel = config.log_level_syslog >= DEBUG1 ? DEBUG9 : config.log_level_syslog; // Legacy if ( (envPtr = getenv( "LOG_PRINT" )) ) tempTermLevel = atoi(envPtr) ? DEBUG9 : NOLOG; if ( (envPtr = getTargettedEnv( "LOG_LEVEL" )) ) tempLevel = atoi(envPtr); if ( (envPtr = getTargettedEnv( "LOG_LEVEL_TERM" )) ) tempTermLevel = atoi(envPtr); if ( (envPtr = getTargettedEnv( "LOG_LEVEL_DATABASE" )) ) tempDatabaseLevel = atoi(envPtr); if ( (envPtr = getTargettedEnv( "LOG_LEVEL_FILE" )) ) tempFileLevel = atoi(envPtr); if ( (envPtr = getTargettedEnv( "LOG_LEVEL_SYSLOG" )) ) tempSyslogLevel = atoi(envPtr); if ( config.log_debug ) { StringVector targets = split( config.log_debug_target, "|" ); for ( unsigned int i = 0; i < targets.size(); i++ ) { const std::string &target = targets[i]; if ( target == mId || target == "_"+mId || target == "_"+mIdRoot || target == "_"+mIdRoot || target == "" ) { if ( config.log_debug_level > NOLOG ) { tempLevel = config.log_debug_level; if ( config.log_debug_file[0] ) { tempLogFile = config.log_debug_file; tempFileLevel = tempLevel; } } } } } logFile( tempLogFile ); termLevel( tempTermLevel ); databaseLevel( tempDatabaseLevel ); fileLevel( tempFileLevel ); syslogLevel( tempSyslogLevel ); level( tempLevel ); mFlush = (envPtr = getenv( "LOG_FLUSH")) ? atoi( envPtr ) : false; //mRuntime = (envPtr = getenv( "LOG_RUNTIME")) ? atoi( envPtr ) : false; { struct sigaction action; memset( &action, 0, sizeof(action) ); action.sa_handler = usrHandler; action.sa_flags = SA_RESTART; if ( sigaction( SIGUSR1, &action, 0 ) < 0 ) { Fatal( "sigaction(), error = %s", strerror(errno) ); } if ( sigaction( SIGUSR2, &action, 0 ) < 0) { Fatal( "sigaction(), error = %s", strerror(errno) ); } } mInitialised = true; Debug( 1, "LogOpts: level=%s/%s, screen=%s, database=%s, logfile=%s->%s, syslog=%s", smCodes[mLevel].c_str(), smCodes[mEffectiveLevel].c_str(), smCodes[mTermLevel].c_str(), smCodes[mDatabaseLevel].c_str(), smCodes[mFileLevel].c_str(), mLogFile.c_str(), smCodes[mSyslogLevel].c_str() ); }
bool OsirisLink::parse(const std::string &link) { if(link.empty()) return false; if(link.substr(0,9) == "osiris://") { // Old format // Compatibility problem: Firefox encode the | std::string link2 = link; algorithms::replace_all(link2, "%7C", "|"); StringVector array1; utils::split(link2, _S("|"), array1); if(array1.size()<2) return false; std::wstring type = array1[1].to_wide(); if( (type == OS_OSIRISLINK_TYPE_PORTAL) || (type == OS_OSIRISLINK_TYPE_ISIS) ) { if(array1.size() < 4) return false; setParam("type", type); setParam("portal", array1[2].to_wide()); for(uint32 i=3;i<array1.size();i++) { std::string part = array1[i].to_ascii(); StringVector array2; utils::split(part, _S("="), array2); std::string paramKey; std::wstring paramValue; if(array2.size()>=1) paramKey = array2[0].to_ascii(); if(array2.size()>=2) paramValue = HttpParser::urlDecodeW(array2[1].to_ascii()); if( (paramKey != "") && (paramValue != _W("")) ) setParam(paramKey, paramValue); } } else if(type == OS_OSIRISLINK_TYPE_FILE) { if(array1.size() != 3) return false; setParam("type", OS_OSIRISLINK_TYPE_FILE); setParam("id", array1[2].to_wide()); } else if(type == OS_OSIRISLINK_TYPE_URL) { if(array1.size() <= 2) return false; std::wstring url; std::wstring params; if(array1.size() > 2) url = HttpParser::urlDecodeW(array1[2].to_ascii()); if(array1.size() > 3) { params = HttpParser::urlDecodeW(array1[3].to_ascii()); int nParamsFound = 0; StringVector arrayP; utils::split(params,_S("&"), arrayP); for(uint32 a1=0; a1 < arrayP.size(); a1++) { StringVector array2; utils::split(arrayP[a1],_S("="), array2); std::wstring paramKey; std::wstring paramValue; if(array2.size()>=1) paramKey = HttpParser::urlDecodeW(array2[0].to_ascii()); if(array2.size()>=2) paramValue = HttpParser::urlDecodeW(array2[1].to_ascii()); if( (paramKey != "") && (paramValue != _W("")) ) { if(paramKey == _W("portal")) { setParam("portal", paramValue); } else { if(nParamsFound == 0) url += _W("?"); nParamsFound++; url += utils::atow(HttpParser::urlEncodeW(paramKey)); url += _W("="); url += utils::atow(HttpParser::urlEncodeW(paramValue)); } } } } setParam("type", OS_OSIRISLINK_TYPE_URL); setParam("url",url); } else if(type == _W("skin")) { if(array1.size() != 3) return false; setParam("type", OS_OSIRISLINK_TYPE_RES); setParam("path", array1[2].to_wide()); } else return false; // Conversion of old 0.X portal ID String oldPortalID = getParam("portal"); if(oldPortalID.empty() == false) setParam("portal", CryptManager:: instance()->SHA(oldPortalID.buffer(), oldPortalID.buffer_size()).toHex()); } else if(link.substr(0,8) == "osiris:?") { std::string params = link.substr(8); StringVector array1; utils::split(params,_S("&"), array1); for(uint32 a1=0; a1 < array1.size(); a1++) { StringVector array2; utils::split(array1[a1],_S("="), array2); std::string paramKey; std::wstring paramValue; if(array2.size()>=1) paramKey = array2[0].to_ascii(); if(array2.size()>=1) paramValue = HttpParser::urlDecodeW(array2[1].to_ascii()); if( (paramKey != "") && (paramValue != _W("")) ) setParam(paramKey, paramValue); } } else return false; return isValid(); }
/*! * Parses lines for function/method names. * * \param line line to be processed * \param needIndentation last line processed * \param functionStack stack of functions * \param functionName function name found * * \return 1 if function name is found */ int CPythonCounter::ParseFunctionName(const string &line, string & needIndentation, StringVector &functionStack, string &functionName, vector<int> &indenStack, int & numWS) { string str; size_t idx; int functionWS = 0; if(indenStack.empty()){ indenStack.push_back(0); } functionWS = indenStack.back(); // current function's indentation if (functionStack.empty()) { functionStack.push_back(""); needIndentation = ""; } string tmp; //get white spaces tmp = line; tmp = CUtil::TrimString(tmp, -1); numWS = (unsigned)(line.length() - tmp.length()); //last line is with "def", if needIndentation=="YES" //not consider the body of function is in the same line of "def" if(needIndentation.length() >= 3 && needIndentation == "YES"){ indenStack.push_back(numWS); needIndentation = ""; } string mark = needIndentation; idx = CUtil::FindKeyword(line, "def"); if (idx != string::npos) { if (idx + 4 < line.length()) { str = line.substr(idx + 4); functionStack.push_back(str); needIndentation = "YES"; //indicate next line need to get the indentation } } if (functionStack.size() == 1 || functionStack.size() == 0) { // dealing with some code out of any subroutines, it is a "main" code return 2; } if(mark != "YES"){ if (functionWS > numWS && functionStack.size() > 1 ) { //the first element in functionStack is "" //we need to get the function and pop the function from the functionStack if(needIndentation=="YES"){ //we have already pushed the new function to the functionStack string tempp = functionStack.back(); //pop new function functionStack.pop_back(); str = functionStack.back(); functionStack.pop_back(); functionStack.push_back(tempp); // push new function indenStack.pop_back(); //pop the function's indentation in the stack } else{ str = functionStack.back(); functionStack.pop_back(); indenStack.pop_back(); //pop the function's indentation in the stack } //get function's name idx = str.find("("); if (idx != string::npos) { functionName = CUtil::ClearRedundantSpaces(str.substr(0, idx)); return 1; } } } return 0; }
std::ostream& operator<<(std::ostream& os,const SqlFileTimeSeriesQuery& query) { os << std::endl; if (query.environment()) { EnvironmentIdentifier envId = query.environment().get(); if (envId.type()) { os << "Environment Period: Of type '" << envId.type().get().valueDescription() << "'" << std::endl; } else { os << "Environment Period: " << envId.name().get() << std::endl; } } else { os << "Environment Period: Not Specified" << std::endl; } if (query.reportingFrequency()) { os << "Reporting Frequency: " << query.reportingFrequency().get().valueDescription() << std::endl; } else { os << "Reporting Frequency: Not Specified" << std::endl; } if (query.timeSeries()) { TimeSeriesIdentifier tsId = query.timeSeries().get(); if (tsId.regex()) { os << "Time Series: Match regex '" << tsId.regex().get() << "'" << std::endl; } else { os << "Time Series: " << tsId.name().get() << std::endl; } } else { os << "Time Series: Not Specified" << std::endl; } StringVector names; if (query.keyValues()) { KeyValueIdentifier kvId = query.keyValues().get(); if (kvId.regex()) { os << "Key Values: Match regex '" << kvId.regex().get() << "'" << std::endl; } else { names = kvId.names(); if (names.size() == 1) { os << "Key Value: " << names[0] << std::endl; } else { OS_ASSERT(names.size() > 1); os << "Key Values: " << names[0] << std::endl; for (unsigned i = 1, n = names.size(); i < n; ++i) { os << std::setw(21) << " " << names[i] << std::endl; } } } } else { os << "Key Value: Not Specified" << std::endl; } os << std::endl; return os; }
//----------------------------------------------------------------------- void RenderSystemCapabilitiesSerializer::parseScript(DataStreamPtr& stream) { // reset parsing data to NULL mCurrentLineNumber = 0; mCurrentLine = 0; mCurrentStream.setNull(); mCurrentCapabilities = 0; mCurrentStream = stream; // parser operating data String line; ParseAction parseAction = PARSE_HEADER; StringVector tokens; bool parsedAtLeastOneRSC = false; // collect capabilities lines (i.e. everything that is not header, "{", "}", // comment or empty line) for further processing CapabilitiesLinesList capabilitiesLines; // for reading data char tmpBuf[OGRE_STREAM_TEMP_SIZE]; // TODO: build a smarter tokenizer so that "{" and "}" // don't need separate lines while (!stream->eof()) { stream->readLine(tmpBuf, OGRE_STREAM_TEMP_SIZE-1); line = String(tmpBuf); StringUtil::trim(line); // keep track of parse position mCurrentLine = &line; mCurrentLineNumber++; tokens = StringUtil::split(line); // skip empty and comment lines // TODO: handle end of line comments if (tokens[0] == "" || tokens[0].substr(0,2) == "//") continue; switch (parseAction) { // header line must look like this: // render_system_capabilities "Vendor Card Name Version xx.xxx" case PARSE_HEADER: if(tokens[0] != "render_system_capabilities") { logParseError("The first keyword must be render_system_capabilities. RenderSystemCapabilities NOT created!"); return; } else { // the rest of the tokens are irrevelant, beause everything between "..." is one name String rscName = line.substr(tokens[0].size()); StringUtil::trim(rscName); // the second argument must be a "" delimited string if (!StringUtil::match(rscName, "\"*\"")) { logParseError("The argument to render_system_capabilities must be a quote delimited (\"...\") string. RenderSystemCapabilities NOT created!"); return; } else { // we have a valid header // remove quotes rscName = rscName.substr(1); rscName = rscName.substr(0, rscName.size() - 1); // create RSC mCurrentCapabilities = OGRE_NEW RenderSystemCapabilities(); // RSCManager is responsible for deleting mCurrentCapabilities RenderSystemCapabilitiesManager::getSingleton()._addRenderSystemCapabilities(rscName, mCurrentCapabilities); LogManager::getSingleton().logMessage("Created RenderSystemCapabilities" + rscName); // do next action parseAction = FIND_OPEN_BRACE; parsedAtLeastOneRSC = true; } } break; case FIND_OPEN_BRACE: if (tokens[0] != "{" || tokens.size() != 1) { logParseError("Expected '{' got: " + line + ". Continuing to next line."); } else { parseAction = COLLECT_LINES; } break; case COLLECT_LINES: if (tokens[0] == "}") { // this render_system_capabilities section is over // let's process the data and look for the next one parseCapabilitiesLines(capabilitiesLines); capabilitiesLines.clear(); parseAction = PARSE_HEADER; } else capabilitiesLines.push_back(CapabilitiesLinesList::value_type(line, mCurrentLineNumber)); break; } } // Datastream is empty // if we are still looking for header, this means that we have either // finished reading one, or this is an empty file if(parseAction == PARSE_HEADER && parsedAtLeastOneRSC == false) { logParseError ("The file is empty"); } if(parseAction == FIND_OPEN_BRACE) { logParseError ("Bad .rendercaps file. Were not able to find a '{'"); } if(parseAction == COLLECT_LINES) { logParseError ("Bad .rendercaps file. Were not able to find a '}'"); } }
//------------------------------------------------------------------------------------ D3D11Texture::D3D11Texture( const StringVector& vecTexNames ) :m_pTexture2D(nullptr) ,m_pTexture3D(nullptr) ,m_pRenderSystem(g_env.pRenderSystem) ,m_rtView(nullptr) ,m_pSRV(nullptr) ,m_pDSV(nullptr) ,m_usage(0) ,m_texType(eTextureType_TextureArray) ,m_bMipMap(true) { m_pd3dDevice = m_pRenderSystem->GetDevice(); if (m_pd3dDevice) m_pd3dDevice->AddRef(); assert(!vecTexNames.empty()); HRESULT hr = S_OK; // First load all texture elements std::vector<ID3D11Texture2D*> vecTexs(vecTexNames.size()); for (size_t i=0; i<vecTexNames.size(); ++i) { D3DX11_IMAGE_LOAD_INFO loadInfo; loadInfo.Width = D3DX11_FROM_FILE; loadInfo.Height = D3DX11_FROM_FILE; loadInfo.Depth = D3DX11_FROM_FILE; loadInfo.FirstMipLevel = 0; loadInfo.BindFlags = 0; loadInfo.Usage = D3D11_USAGE_STAGING; // Local res loadInfo.MipLevels = 0; loadInfo.CpuAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; loadInfo.MiscFlags = 0; loadInfo.Format = DXGI_FORMAT_FROM_FILE; loadInfo.Filter = D3DX11_FILTER_NONE; loadInfo.MipFilter = D3DX11_FILTER_LINEAR; loadInfo.pSrcInfo = 0; V(D3DX11CreateTextureFromFileA(m_pRenderSystem->GetDevice(), vecTexNames[i].c_str(), &loadInfo, nullptr, (ID3D11Resource**)&vecTexs[i], nullptr)); } // Then create the texture array object D3D11_TEXTURE2D_DESC texElementDesc; vecTexs[0]->GetDesc(&texElementDesc); // Store dimension and format m_width = texElementDesc.Width; m_height = texElementDesc.Height; m_texFormat = ConvertFromDXFormat(texElementDesc.Format); D3D11_TEXTURE2D_DESC texArrayDesc; texArrayDesc.Width = texElementDesc.Width; texArrayDesc.Height = texElementDesc.Height; texArrayDesc.MipLevels = texElementDesc.MipLevels; texArrayDesc.ArraySize = vecTexs.size(); texArrayDesc.Format = texElementDesc.Format; texArrayDesc.SampleDesc.Count = 1; texArrayDesc.SampleDesc.Quality = 0; texArrayDesc.Usage = D3D11_USAGE_DEFAULT; texArrayDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; texArrayDesc.CPUAccessFlags = 0; texArrayDesc.MiscFlags = 0; V(m_pRenderSystem->GetDevice()->CreateTexture2D( &texArrayDesc, 0, &m_pTexture2D)); // Fill texture array data ID3D11DeviceContext* dc = m_pRenderSystem->GetDeviceContext(); for(size_t texElement=0; texElement<vecTexs.size(); ++texElement) { for(UINT mipLevel = 0; mipLevel < texElementDesc.MipLevels; ++mipLevel) { D3D11_MAPPED_SUBRESOURCE mappedTex2D; V(dc->Map(vecTexs[texElement], mipLevel, D3D11_MAP_READ, 0, &mappedTex2D)); dc->UpdateSubresource(m_pTexture2D, D3D11CalcSubresource(mipLevel, texElement, texElementDesc.MipLevels), 0, mappedTex2D.pData, mappedTex2D.RowPitch, mappedTex2D.DepthPitch); dc->Unmap(vecTexs[texElement], mipLevel); } } CreateSRV(); for(size_t i=0; i<vecTexs.size(); ++i) vecTexs[i]->Release(); }
/*! * Processes physical and logical lines according to language specific rules. * NOTE: all the blank lines + * whole line comments * should have been blanked from filemap by previous processing * before reaching this function * * \param fmap list of processed file lines * \param result counter results * \param fmapBak list of original file lines (same as fmap except it contains unmodified quoted strings) * * \return method status */ int CAssemblyCounter::LanguageSpecificProcess(filemap* fmap, results* result, filemap* /*fmapBak*/) { string logicalLine, nextPhysicalLine, physicalLine; unsigned int i; int changeSectionMode; bool isDataSection = false; bool isDataDeclarationLine = false; // specifies whether a given single line is the declaration of a data section (i.e. '.data') bool hasLineContinuation = false; int countPhysicalLine = 0; for (filemap::iterator iter = fmap->begin(); iter != fmap->end(); iter++) { // A physical line does not contain trailing or leading spaces. // nextPhysicalLine may contains multiple logical statements separated by a separator. // nextPhysicalLine may end with a line continuation character. // In this case, nextPhysicalLine will be constructed as multiple physical lines. nextPhysicalLine = iter->line; if (!hasLineContinuation) physicalLine = ""; // do not process blank lines - blank line means blank_line/comment_line if (!CUtil::CheckBlank(nextPhysicalLine)) { countPhysicalLine++; // keep track of the number of physical lines (blank is not a physical line) if (CUtil::EndsWith(nextPhysicalLine, "\\")) { physicalLine += nextPhysicalLine.substr(0, nextPhysicalLine.length() - 1) + " "; hasLineContinuation = true; continue; // go to next physical line } else { physicalLine += nextPhysicalLine; hasLineContinuation = false; } isDataDeclarationLine = false; // since a physical line may contain multiple logical lines, check for statement separator StringVector tokens = CUtil::Split(physicalLine, statementSeparator); for (i = 0; i < tokens.size(); i++) { logicalLine = CUtil::TrimString(tokens[i], 0); // one logical line changeSectionMode = SwitchSectionMode(logicalLine); if (changeSectionMode == 1) isDataSection = false; // false means it is in executable section, not data section else if (changeSectionMode == 2) { isDataSection = true; // true means it has entered a data section of the program isDataDeclarationLine = true; // declaration of a data section (i.e. '.data') itself will not be counted as data line, but counted as executable } /* Some Logical SLOC Counting Rules: 1) MyLabel: instr 1 LSLOC since instruction is present on the same line as the label 2) MyLabel: 0 LSLOC. Label without instruction is not an executable statement 3) .instruction param 1 LSLOC 4) .instruction 1 LSLOC. Some instructions do not require parameters 5) # 0 LSLOC since comment line. Comment lines have been taken care of in previous processing. No processing needed here 6) ; 0 LSLOC. Logical statement separator. Program will parse into multiple lines for processing 7) instr 1 LSLOC. If a line passes all of the above filter/exception, it is an executable line Reference: http://www.ibm.com/developerworks/library/l-ppc/ */ // The strategy is to figure out what should be excluded from counting (these are known as counting exceptions). // Those lines that are not excluded will be assumed to be instructions; thus, they will be counted. // 1. First exception to look for is mylabel: // Rationale: label without instruction is not counted as a logical SLOC if (CUtil::EndsWith(logicalLine, ":", true)) continue; // 2. Do not count the following NASM statements: %endmacro, %endif, %endrep if (CUtil::StartsWith(logicalLine, "%end", true)) continue; // 3. Do not count the following MASM statements: endm, endp, ends, endw, end, .end, .endw // and do not count the following GAS statements: .end, .endm, .endef, .endfunc, .endif, .endloop if (CUtil::StartsWith(logicalLine, ".end", true) || CUtil::StartsWith(logicalLine, "end", true)) continue; // anything that has passed the above exceptions is a logical SLOC that will be counted as 1 instruction if (isDataSection && !isDataDeclarationLine) result->data_lines[LOG]++; else result->exec_lines[LOG]++; bool trunc_flag = false; CUtil::TruncateLine(physicalLine.length(), logicalLine.length(), this->lsloc_truncate, trunc_flag); result->addSLOC(logicalLine, trunc_flag); // add SLOC so that diff can be performed } if (isDataSection && !isDataDeclarationLine) result->data_lines[PHY] += countPhysicalLine; else result->exec_lines[PHY] += countPhysicalLine; countPhysicalLine = 0; } } return 1; }
bool TestLexer::_testScan() { StringVector first; StringVector second; report( " Scanning file " << ptxFile ); std::ifstream file( ptxFile.c_str() ); std::stringstream temp; std::stringstream stream; assert( file.is_open() ); YYSTYPE token; parser::PTXLexer lexer( &file, &temp ); lexer.yylval = &token; int tokenValue = lexer.yylex(); while( tokenValue != 0 ) { report( " Line (" << lexer.lineno() << "): Scanned token " << parser::PTXLexer::toString( tokenValue ) << " \"" << lexer.YYText() << "\"" ); if( parser::PTXLexer::toString( tokenValue ) == "INVALID" ) { status << "First pass line (" << lexer.lineno() << "): Hit invalid token \"" << lexer.YYText() << "\"\n"; return false; } first.push_back( lexer.YYText() ); stream << lexer.YYText() << "\n"; tokenValue = lexer.yylex(); } report( " Scanning internal stream." ); lexer.switch_streams( &stream, 0 ); if( temp.str().size() != 0 ) { status << "First pass did not consume all of the file, the " << "following was rejected:\n'" << temp.str() << "'\n"; status << " remaining characters:" << temp.str().size() << "\n"; return false; } tokenValue = lexer.yylex(); while( tokenValue != 0 ) { report( " Line (" << lexer.lineno() << "): Scanned token " << parser::PTXLexer::toString( tokenValue ) << " \"" << lexer.YYText() << "\"" ); if( parser::PTXLexer::toString( tokenValue ) == "INVALID" ) { status << "Second pass line (" << lexer.lineno() << "): Hit invalid token \"" << lexer.YYText() << "\"\n"; return false; } second.push_back( lexer.YYText() ); tokenValue = lexer.yylex(); } if( first.size() != second.size() ) { status << "First pass scanned " << first.size() << " tokens while second scanned " << second.size() << "\n"; return false; } for( StringVector::iterator fi = first.begin(), si = second.begin(); fi != first.end() && si != second.end(); ++fi, ++si ) { if( *fi != *si ) { status << "At index " << ( fi - first.begin() ) << ", first token scanned \"" << *fi << "\" did not match second \"" << *si << "\"\n"; return false; } } report( " Scanned " << first.size() << " tokens." ); return true; }
IceUtilInternal::Options::StringVector IceUtilInternal::Options::parse(const StringVector& args) { RecMutex::Lock sync(_m); if(parseCalled) { throw APIException(__FILE__, __LINE__, "cannot call parse() more than once on the same Option instance"); } parseCalled = true; set<string> seenNonRepeatableOpts; // To catch repeated non-repeatable options. StringVector result; string::size_type i; for(i = 1; i < args.size(); ++i) { if(args[i] == "-" || args[i] == "--") { ++i; break; // "-" and "--" indicate end of options. } string opt; ValidOpts::iterator pos; bool argDone = false; if(args[i].compare(0, 2, "--") == 0) { // // Long option. If the option has an argument, it can either be separated by '=' // or appear as a separate argument. For example, "--name value" is the same // as "--name=value". // string::size_type p = args[i].find('=', 2); if(p != string::npos) { opt = args[i].substr(2, p - 2); } else { opt = args[i].substr(2); } pos = checkOpt(opt, LongOpt); if(pos->second->repeat == NoRepeat) { set<string>::iterator seenPos = seenNonRepeatableOpts.find(opt); if(seenPos != seenNonRepeatableOpts.end()) { string err = "`--"; err += opt + ":' option cannot be repeated"; throw BadOptException(__FILE__, __LINE__, err); } seenNonRepeatableOpts.insert(seenPos, opt); string synonym = getSynonym(opt); if(!synonym.empty()) { seenNonRepeatableOpts.insert(synonym); } } if(p != string::npos) { if(pos->second->arg == NoArg && p != args[i].size() - 1) { string err = "`"; err += args[i]; err += "': option does not take an argument"; throw BadOptException(__FILE__, __LINE__, err); } setOpt(opt, "", args[i].substr(p + 1), pos->second->repeat); argDone = true; } } else if(!args[i].empty() && args[i][0] == '-') { // // Short option. // for(string::size_type p = 1; p < args[i].size(); ++p) { opt.clear(); opt.push_back(args[i][p]); pos = checkOpt(opt, ShortOpt); if(pos->second->repeat == NoRepeat) { set<string>::iterator seenPos = seenNonRepeatableOpts.find(opt); if(seenPos != seenNonRepeatableOpts.end()) { string err = "`-"; err += opt + ":' option cannot be repeated"; throw BadOptException(__FILE__, __LINE__, err); } seenNonRepeatableOpts.insert(seenPos, opt); string synonym = getSynonym(opt); if(!synonym.empty()) { seenNonRepeatableOpts.insert(synonym); } } if(pos->second->arg == NeedArg && p != args[i].size() - 1) { string optArg = args[i].substr(p + 1); setOpt(opt, "", optArg, pos->second->repeat); argDone = true; break; } } } else { // // Not an option or option argument. // result.push_back(args[i]); argDone = true; } if(!argDone) { if(pos->second->arg == NeedArg) // Need an argument that is separated by whitespace. { if(i == args.size() - 1) { string err = "`-"; if(opt.size() != 1) { err += "-"; } err += opt; err += "' option requires an argument"; throw BadOptException(__FILE__, __LINE__, err); } setOpt(opt, "", args[++i], pos->second->repeat); } else { setOpt(opt, "", "1", pos->second->repeat); } } } _synonyms.clear(); // Don't need the contents anymore. while(i < args.size()) { result.push_back(args[i++]); } return result; }
ERMsg CUIEnvCanRadar::GetRadarList(StringVector& radarList, CCallback& callback)const { ERMsg msg; //Interface attribute index to attribute index //sample for Québec //http://climate.weather.gc.ca/radar/index_e.html?site=XAM&year=2015&month=7&day=25&hour=13&minute=20&duration=2&image_type=PRECIPET_SNOW_WEATHEROFFICE //http://climate.weather.gc.ca/radar/index_e.html?site=XAM&sYear=2013&sMonth=7&sDay=15&sHour=22&sMin=00&Duration=2&ImageType=PRECIP_SNOW_WEATHEROFFICE&scale=14 static const char pageFormat[] = "radar/index_e.html?" "site=%s&" "year=%d&" "month=%d&" "day=%d&" "hour=%d&" "minute=00&" "duration=2&" "image_type=%s"; CCanadianRadar radar(Get(RADAR)); CTPeriod period = GetPeriod(); callback.PushTask(GetString(IDS_LOAD_FILE_LIST), radar.count() * period.size() / 2); size_t type = as<size_t>(TYPE); size_t prcpType = as<size_t>(PRCP_TYPE); CInternetSessionPtr pSession; CHttpConnectionPtr pConnection; msg = GetHttpConnection(SERVER_NAME[type], pConnection, pSession); if (!msg) return msg; ASSERT(period.GetTM().Type() == CTM::HOURLY); std::set<string> tmpList; //loop each 2 hours for (size_t i = 0; i < radar.size() && msg; i++) { if (radar.none() || radar[i]) { for (CTRef TRef = period.Begin(); TRef <= period.End() && msg; TRef += 2) { string URL = FormatA(pageFormat, CCanadianRadar::GetName(i,0).c_str(), TRef.GetYear(), TRef.GetMonth() + 1, TRef.GetDay() + 1, TRef.GetHour(), TYPE_NAME[prcpType]); URL.resize(strlen(URL.c_str())); string source; UtilWWW::GetPageText(pConnection, URL, source, true); //string::size_type posEnd = 0; string fileList = FindString(source, "blobArray = [", "]"); if (!fileList.empty()) { string::size_type posBegin = 0; while (posBegin != string::npos) { string image = FindString(fileList, "'", "'", posBegin); if (!image.empty()) tmpList.insert(image); posBegin = fileList.find(",", posBegin); } } msg += callback.StepIt(); } } } pConnection->Close(); pSession->Close(); radarList.insert(radarList.end(), tmpList.begin(), tmpList.end()); callback.AddMessage(GetString(IDS_NB_FILES_FOUND) + ToString(radarList.size())); callback.PopTask(); return msg; }
int main (int argc, const char** argv) { if (argc < 2) { printf ("USAGE: hlsl2glsltest testfolder\n"); return 1; } bool hasOpenGL = InitializeOpenGL (); if (!hasOpenGL) printf("NOTE: will not check GLSL with actual driver (no GL/GLSL)\n"); clock_t time0 = clock(); Hlsl2Glsl_Initialize (); std::string baseFolder = argv[1]; size_t tests = 0; size_t errors = 0; for (int type = 0; type < NUM_RUN_TYPES; ++type) { printf ("TESTING %s...\n", kTypeName[type]); const ETargetVersion version1 = kTargets1[type]; const ETargetVersion version2 = kTargets2[type]; const ETargetVersion version3 = kTargets3[type]; std::string testFolder = baseFolder + "/" + kTypeName[type]; StringVector inputFiles = GetFiles (testFolder, "-in.txt"); size_t n = inputFiles.size(); tests += n; for (size_t i = 0; i < n; ++i) { std::string inname = inputFiles[i]; //if (inname != "non-matching-type-init-in.txt") // continue; bool ok = true; printf ("test %s\n", inname.c_str()); if (type == BOTH) { ok = TestCombinedFile(testFolder + "/" + inname, version1, hasOpenGL); if (ok && version2 != ETargetVersionCount) ok = TestCombinedFile(testFolder + "/" + inname, version2, hasOpenGL); } else { ok = TestFile(TestRun(type), testFolder + "/" + inname, version1, 0, hasOpenGL); if (ok && version2 != ETargetVersionCount) ok = TestFile(TestRun(type), testFolder + "/" + inname, version2, ETranslateOpEmitGLSL120ArrayInitWorkaround, hasOpenGL); if (ok && version3 != ETargetVersionCount) ok = TestFile(TestRun(type), testFolder + "/" + inname, version3, 0, hasOpenGL); } if (!ok) ++errors; } } clock_t time1 = clock(); float t = float(time1-time0) / float(CLOCKS_PER_SEC); if (errors != 0) printf ("%i tests, %i FAILED, %.2fs\n", (int)tests, (int)errors, t); else printf ("%i tests succeeded, %.2fs\n", (int)tests, t); Hlsl2Glsl_Shutdown(); CleanupOpenGL(); return errors ? 1 : 0; }
ERMsg CUIEnvCanRadar::ExecuteHistorical(CCallback& callback) { ERMsg msg; string workingDir = GetDir(WORKING_DIR); CreateMultipleDir(workingDir); CInternetSessionPtr pSession; CHttpConnectionPtr pConnection; msg = GetHttpConnection(SERVER_NAME[as<size_t>(TYPE)], pConnection, pSession); if (!msg) return msg; callback.AddMessage(GetString(IDS_UPDATE_DIR)); callback.AddMessage(workingDir, 1); callback.AddMessage(GetString(IDS_UPDATE_FROM)); callback.AddMessage(SERVER_NAME[as<size_t>(TYPE)], 1); callback.AddMessage(""); //Get remote station list StringVector imageList; if (msg) msg = GetRadarList(imageList, callback); if (msg) msg = CleanRadarList(imageList, callback); if (!msg) return msg; callback.PushTask("Download historical radar images (" + ToString(imageList.size())+ ")", imageList.size()); //callback.SetNbStep(imageList.size()); int nbRun = 0; int curI = 0; while (curI<imageList.size() && msg) { nbRun++; CInternetSessionPtr pSession; CHttpConnectionPtr pConnection; msg = GetHttpConnection(SERVER_NAME[as<size_t>(TYPE)], pConnection, pSession); if (msg) { TRY { for (int i = curI; i<imageList.size() && msg; i++) { string filePath = GetOutputFilePath(as<size_t>(TYPE), imageList[i]); msg += CreateMultipleDir(GetPath(filePath)); //msg += CopyFile(pConnection, imageList[i], filePath, INTERNET_FLAG_TRANSFER_BINARY | WININET_API_FLAG_SYNC); CString URL(imageList[i].c_str()); CHttpFile* pURLFile = pConnection->OpenRequest(_T("GET"), URL, NULL, 1, NULL, NULL, INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_TRANSFER_BINARY | WININET_API_FLAG_SYNC | INTERNET_FLAG_NEED_FILE); //CStdioFile* pURLFile = pSession->OpenURL(UtilWin::Convert(imageList[i]), 0, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_EXISTING_CONNECT); bool bRep = false; if (pURLFile != NULL) { if (pURLFile->SendRequest() != 0) { CArray<char> source; int len = 0; CArray<char> tmp; tmp.SetSize(50); DWORD dwStatusCode = 0; pURLFile->QueryInfoStatusCode(dwStatusCode); ULONGLONG length = pURLFile->GetLength(); while (length > 0) { pURLFile->Read(tmp.GetData(), 50); source.Append(tmp); length = pURLFile->GetLength(); } pURLFile->QueryInfoStatusCode(dwStatusCode); pURLFile->Close(); ofStream file; msg = file.open(filePath, ios::out | ios::binary); if (msg) { if (!source.IsEmpty()) file.write(source.GetData(), (UINT)source.GetSize()); file.close(); //convert image to GeoTiff //ConvertToGeotiff(filePath, CCanadianRadar(CCanadianRadar::coord)); } } } if (msg) { curI++; nbRun = 0; msg += callback.StepIt(); } } } CATCH_ALL(e) { msg = UtilWin::SYGetMessage(*e); } END_CATCH_ALL //if an error occur: try again if (!msg && !callback.GetUserCancel()) { //callback.AddTask(1);//one step more if (nbRun < 5) { callback.AddMessage(msg); msg.asgType(ERMsg::OK); Sleep(1000);//wait 1 sec } } //clean connection pConnection->Close(); pSession->Close(); } } callback.AddMessage(GetString(IDS_NB_FILES_DOWNLOADED) + ToString(curI)); callback.PopTask(); return msg; }
bool NucleusGridFunction:: readCellNucleusFile( const std::string cn_filename, const std::string gridFileName/* = ""*/ ) { bool okFlag=false; clearGrid2NucleusMap(); clearNucleus2GridMap(); FILE *fp=fopen( cn_filename.c_str(),"r"); if( !fp ) { okFlag=false; return( okFlag ); } DPrintf(DebugSolver,"reading file '%s'...\n",cn_filename.c_str()); DPrintf(DebugSolver,"------------------------------\n"); const int bufferLength=1000; char buffer[bufferLength]; while( fgets( buffer, bufferLength, fp)) { const int lineLength=strlen(buffer); typedef std::vector<std::string> StringVector; StringVector tokens; if( lineLength>0 ) { if( buffer[0]=='#' ) { buffer[lineLength-1]=0; DPrintf(DebugSolver,"comment< %s >\n", buffer); } else { using namespace std; Nucleus thisNuc; buffer[lineLength-1]=0; //printf("regular< %s >\n", buffer); string line(buffer); //cout << "<"<<line<<">\n"; typedef boost::tokenizer<>::iterator TokIterator; typedef boost::char_delimiters_separator<char> TokSeparator; //see boost::tokenizer 'char_delimiters_separator' docs // sep( returnable=false, returned="", separators=0) // --> separators=0 means anything for which iswhitespace() // is true is a separator TokSeparator sep(false,"",0); boost::tokenizer< TokSeparator> tok(line, sep); for (TokIterator it=tok.begin(); it!=tok.end(); ++it) { //DPrintf(DebugSolver,"<%s> ", it->c_str()); tokens.push_back( *it ); } //..INPUT FILE FORMAT FOR .cwn // format: <nucleus #> <radius> <x y z of center> <grid ID(s)> // lines with '#' in column 1 are comments int nID; const int idIndex=0; double rad; const int idRadius=1; double x,y,z; const int idX=2, idY=3, idZ=4; //std::vector<int> gridIDs; sscanf(tokens[idIndex].c_str(), "%d", &nID); sscanf(tokens[idRadius].c_str(), "%lg", &rad); sscanf(tokens[idX].c_str(), "%lg", &x); sscanf(tokens[idY].c_str(), "%lg", &y); sscanf(tokens[idZ].c_str(), "%lg", &z); DPrintf(DebugSolver," #tokens=%d, ztoken=%s -- ", tokens.size(), tokens[idZ].c_str()); DPrintf(DebugSolver,"id=%d, R=%f, x=%f, y=%f, z=%f,",nID,rad,x,y,z); DPrintf(DebugSolver,"\n"); thisNuc.setID( nID); thisNuc.setCenter(x,y,z); thisNuc.setRadius(rad); Nucleus::NucleusShape nucleusShape=Nucleus::SphericalNucleus; thisNuc.setShape( nucleusShape ); thisNuc.setBoundaryThickness( nucleusBoundaryThickness ); nucleus.push_back( thisNuc ); DPrintf(DebugSolver,"gridIDs for nucleus # %d=",nID); for( int i=idZ+1; i<tokens.size(); ++i ) { int gID=-1; sscanf(tokens[i].c_str(), "%d", &gID); DPrintf(DebugSolver," %d ",gID); grid2NucleusMap.insert( std::make_pair(gID,nID)); nucleus2GridMap.insert( std::make_pair(nID,gID)); } DPrintf(DebugSolver,"\n"); } }; } DPrintf(DebugSolver,"-------------done-------------\n"); fclose(fp); okFlag=true; return( okFlag ); }
//--------------------------------------------------------------------- void FontManager::parseAttribute(const String& line, FontPtr& pFont) { vector<String>::type params = StringUtil::split(line); String& attrib = params[0]; StringUtil::toLowerCase(attrib); if (attrib == "type") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set StringUtil::toLowerCase(params[1]); if (params[1] == "truetype") { pFont->setType(FT_TRUETYPE); } else { pFont->setType(FT_IMAGE); } } else if (attrib == "source") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set pFont->setSource(params[1]); } else if (attrib == "glyph") { // Check params if (params.size() != 6) { logBadAttrib(line, pFont); return; } // Set // Support numeric and character glyph specification Font::CodePoint cp; if (params[1].at(0) == 'u' && params[1].size() > 1) { // Unicode glyph spec String trimmed = params[1].substr(1); cp = StringConverter::parseUnsignedInt(trimmed); } else { // Direct character cp = params[1].at(0); } pFont->setGlyphTexCoords( cp, StringConverter::parseReal(params[2]), StringConverter::parseReal(params[3]), StringConverter::parseReal(params[4]), StringConverter::parseReal(params[5]), 1.0 ); // assume image is square } else if (attrib == "size") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set pFont->setTrueTypeSize( StringConverter::parseReal(params[1]) ); } else if (attrib == "resolution") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set pFont->setTrueTypeResolution( (uint)StringConverter::parseReal(params[1]) ); } else if (attrib == "antialias_colour") { // Check params if (params.size() != 2) { logBadAttrib(line, pFont); return; } // Set pFont->setAntialiasColour(StringConverter::parseBool(params[1])); } else if (attrib == "code_points") { for (size_t c = 1; c < params.size(); ++c) { String& item = params[c]; StringVector itemVec = StringUtil::split(item, "-"); if (itemVec.size() == 2) { pFont->addCodePointRange(Font::CodePointRange( StringConverter::parseLong(itemVec[0]), StringConverter::parseLong(itemVec[1]))); } } } }
int main (int argc, const char** argv) { if (argc < 2) { printf ("USAGE: hlsl2glsltest testfolder\n"); return 1; } bool hasOpenGL = InitializeOpenGL (); clock_t time0 = clock(); Hlsl2Glsl_Initialize (); std::string baseFolder = argv[1]; static const char* kTypeName[2] = { "vertex", "fragment" }; size_t tests = 0; size_t errors = 0; for (int type = 0; type < 2; ++type) { printf ("testing %s...\n", kTypeName[type]); std::string testFolder = baseFolder + "/" + kTypeName[type]; StringVector inputFiles = GetFiles (testFolder, "-in.txt"); size_t n = inputFiles.size(); tests += n; for (size_t i = 0; i < n; ++i) { std::string inname = inputFiles[i]; printf ("test %s\n", inname.c_str()); std::string outname = inname.substr (0,inname.size()-7) + "-out.txt"; std::string outnameES = inname.substr (0,inname.size()-7) + "-outES.txt"; bool ok = TestFile (type==0, testFolder + "/" + inname, testFolder + "/" + outname, false, hasOpenGL); if (ok) { ok = TestFile (type==0, testFolder + "/" + inname, testFolder + "/" + outnameES, true, false); } if (!ok) { ++errors; } } } clock_t time1 = clock(); float t = float(time1-time0) / float(CLOCKS_PER_SEC); if (errors != 0) printf ("%i tests, %i FAILED, %.2fs\n", tests, errors, t); else printf ("%i tests succeeded, %.2fs\n", tests, t); return errors ? 1 : 0; }
osg::Node* ModelResource::createNodeFromURI( const URI& uri, const osgDB::Options* dbOptions ) const { if (_status.isError()) return 0L; osg::ref_ptr< osgDB::Options > options = dbOptions ? new osgDB::Options( *dbOptions ) : 0L; // Explicitly cache images so that models that share images will only load one copy. // If the options struture doesn't contain an object cache, OSG will use the global // object cache stored in the Registry. Without this, models that share textures or // use an atlas will duplicate memory usage. // // I don't like having this here - it seems like it belongs elsewhere and the caller // should be passing it in. But it needs to be set, so keep for now. if ( options.valid() ) { options->setObjectCacheHint( osgDB::Options::CACHE_IMAGES ); } osg::Node* node = 0L; ReadResult r = uri.readNode( options.get() ); if ( r.succeeded() ) { node = r.releaseNode(); OE_INFO << LC << "Loaded " << uri.base() << "(from " << (r.isFromCache()? "cache" : "source") << ")" << std::endl; osgUtil::Optimizer o; o.optimize( node, o.REMOVE_REDUNDANT_NODES | o.COMBINE_ADJACENT_LODS | o.MERGE_GEOMETRY | o.MAKE_FAST_GEOMETRY | o.CHECK_GEOMETRY | o.SHARE_DUPLICATE_STATE | o.INDEX_MESH | o.VERTEX_PRETRANSFORM | o.VERTEX_POSTTRANSFORM ); // Disable automatic texture unref since resources can be shared/paged. SetUnRefPolicyToFalse visitor; node->accept( visitor ); } else // failing that, fall back on the old encoding format.. { StringVector tok; StringTokenizer( *uri, tok, "()" ); if (tok.size() >= 2) { node = createNodeFromURI( URI(tok[1]), options.get() ); } } if (node == 0L && _status.isOK()) { Threading::ScopedMutexLock lock(_mutex); if (_status.isOK()) { _status = Status::Error(Status::ServiceUnavailable, "Failed to load resource file"); } } return node; }