当前位置: 首页>>代码示例>>C++>>正文


C++ string::find_last_of方法代码示例

本文整理汇总了C++中std::string::find_last_of方法的典型用法代码示例。如果您正苦于以下问题:C++ string::find_last_of方法的具体用法?C++ string::find_last_of怎么用?C++ string::find_last_of使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在std::string的用法示例。


在下文中一共展示了string::find_last_of方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: Locate

	std::string ResLoader::Locate(std::string const & name)
	{
#if defined(KLAYGE_PLATFORM_ANDROID)
		android_app* state = Context::Instance().AppState();
		AAssetManager* am = state->activity->assetManager;
		AAsset* asset = AAssetManager_open(am, name.c_str(), AASSET_MODE_UNKNOWN);
		if (asset != nullptr)
		{
			AAsset_close(asset);
			return name;
		}
#elif defined(KLAYGE_PLATFORM_IOS)
		std::string::size_type found = name.find_last_of(".");
		if (found != std::string::npos)
		{
			std::string::size_type found2 = name.find_last_of("/");
			CFBundleRef main_bundle = CFBundleGetMainBundle();
			CFStringRef file_name = CFStringCreateWithCString(kCFAllocatorDefault,
				name.substr(found2 + 1, found - found2 - 1).c_str(), kCFStringEncodingASCII);
			CFStringRef file_ext = CFStringCreateWithCString(kCFAllocatorDefault,
				name.substr(found + 1).c_str(), kCFStringEncodingASCII);
			CFURLRef file_url = CFBundleCopyResourceURL(main_bundle, file_name, file_ext, NULL);
			CFRelease(file_name);
			CFRelease(file_ext);
			if (file_url != nullptr)
			{
				CFStringRef file_path = CFURLCopyFileSystemPath(file_url, kCFURLPOSIXPathStyle);

				char const * path = CFStringGetCStringPtr(file_path, CFStringGetSystemEncoding());
				std::string const res_name(path);

				CFRelease(file_url);
				CFRelease(file_path);

				return res_name;
			}
		}
#else
		typedef KLAYGE_DECLTYPE(paths_) PathsType;
		KLAYGE_FOREACH(PathsType::const_reference path, paths_)
		{
			std::string const res_name(path + name);

			if (filesystem::exists(filesystem::path(res_name)))
			{
				return res_name;
			}
			else
			{
				std::string::size_type const pkt_offset(res_name.find("//"));
				if (pkt_offset != std::string::npos)
				{
					std::string pkt_name = res_name.substr(0, pkt_offset);
					filesystem::path pkt_path(pkt_name);
					if (filesystem::exists(pkt_path)
							&& (filesystem::is_regular_file(pkt_path)
									|| filesystem::is_symlink(pkt_path)))
					{
						std::string::size_type const password_offset = pkt_name.find("|");
						std::string password;
						if (password_offset != std::string::npos)
						{
							password = pkt_name.substr(password_offset + 1);
							pkt_name = pkt_name.substr(0, password_offset - 1);
						}
						std::string const file_name = res_name.substr(pkt_offset + 2);

#ifdef KLAYGE_TR2_LIBRARY_FILESYSTEM_V3_SUPPORT
						uint64_t timestamp = filesystem::last_write_time(pkt_path).time_since_epoch().count();
#else
						uint64_t timestamp = filesystem::last_write_time(pkt_path);
#endif
						ResIdentifierPtr pkt_file = MakeSharedPtr<ResIdentifier>(name, timestamp,
							MakeSharedPtr<std::ifstream>(pkt_name.c_str(), std::ios_base::binary));
						if (*pkt_file)
						{
							if (Find7z(pkt_file, password, file_name) != 0xFFFFFFFF)
							{
								return res_name;
							}
						}
					}
				}
			}
		}
开发者ID:qioixiy,项目名称:KlayGE,代码行数:85,代码来源:ResLoader.cpp

示例2: showGraph

void showGraph(TGraph* graph, 
	       const std::string& xAxisTitle,
	       Float_t* genX, 
	       double yMin, double yMax, const std::string& yAxisTitle,
	       const std::string& outputFileName)
{
  TCanvas* canvas = new TCanvas("canvas", "canvas", 800, 600);
  canvas->SetFillColor(10);
  canvas->SetBorderSize(2);

  canvas->SetTopMargin(0.10);
  canvas->SetLeftMargin(0.16);
  canvas->SetRightMargin(0.14);
  canvas->SetBottomMargin(0.12);

  int numPoints = graph->GetN();
  double xMin, xMax, yDummy;
  graph->GetPoint(0, xMin, yDummy);
  graph->GetPoint(numPoints - 1, xMax, yDummy);

  TH1* dummyHistogram = new TH1D("dummyHistogram", "dummyHistogram", numPoints/100, xMin, xMax);
  dummyHistogram->SetStats(false);
  dummyHistogram->SetMinimum(yMin);
  dummyHistogram->SetMaximum(yMax);

  TAxis* xAxis = dummyHistogram->GetXaxis();
  xAxis->SetTitle(xAxisTitle.data());
  xAxis->SetTitleOffset(1.15);

  TAxis* yAxis = dummyHistogram->GetYaxis();
  yAxis->SetTitle(yAxisTitle.data());
  yAxis->SetTitleOffset(1.15);

  dummyHistogram->Draw("axis");

  TGraph* genMarker = 0;
  if ( genX ) {
    genMarker = new TGraph(2);
    genMarker->SetPoint(0, xMin, *genX);
    genMarker->SetPoint(1, xMax, *genX);
    genMarker->SetLineColor(8);
    genMarker->SetLineWidth(1);
    genMarker->SetMarkerColor(8);
    genMarker->SetMarkerStyle(20);
    genMarker->SetMarkerSize(1);
    genMarker->Draw("L");
  }

  graph->SetLineColor(1);
  graph->SetLineWidth(2);
  graph->SetMarkerColor(1);
  graph->SetMarkerStyle(20);
  graph->SetMarkerSize(1);
  graph->Draw("L");

  canvas->Update();
  size_t idx = outputFileName.find_last_of('.');
  std::string outputFileName_plot = std::string(outputFileName, 0, idx);
  if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data());
  canvas->Print(std::string(outputFileName_plot).append(".png").data());
  canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas->Print(std::string(outputFileName_plot).append(".root").data());

  delete dummyHistogram;
  delete genMarker;
  delete canvas;  
}
开发者ID:veelken,项目名称:SVfitDevelopment,代码行数:67,代码来源:plotMarkovChainMonitorTree.C

示例3: GetCurrentDir

// Returns the current directory
std::string GetCurrentDir()
{
    // Get the current working directory (getcwd uses malloc)
#ifdef _WIN32
    wchar_t *dir;
    if (!(dir = _wgetcwd(nullptr, 0))) {
#else
    char *dir;
    if (!(dir = getcwd(nullptr, 0))) {
#endif
        LOG_ERROR(Common_Filesystem, "GetCurrentDirectory failed: %s",
                GetLastErrorMsg());
        return nullptr;
    }
#ifdef _WIN32
    std::string strDir = Common::UTF16ToUTF8(dir);
#else
    std::string strDir = dir;
#endif
    free(dir);
    return strDir;
}

// Sets the current directory to the given directory
bool SetCurrentDir(const std::string &directory)
{
#ifdef _WIN32
    return _wchdir(Common::UTF8ToUTF16W(directory).c_str()) == 0;
#else
    return chdir(directory.c_str()) == 0;
#endif
}

#if defined(__APPLE__)
std::string GetBundleDirectory()
{
    CFURLRef BundleRef;
    char AppBundlePath[MAXPATHLEN];
    // Get the main bundle for the app
    BundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef BundlePath = CFURLCopyFileSystemPath(BundleRef, kCFURLPOSIXPathStyle);
    CFStringGetFileSystemRepresentation(BundlePath, AppBundlePath, sizeof(AppBundlePath));
    CFRelease(BundleRef);
    CFRelease(BundlePath);

    return AppBundlePath;
}
#endif

#ifdef _WIN32
std::string& GetExeDirectory()
{
    static std::string exe_path;
    if (exe_path.empty())
    {
        wchar_t wchar_exe_path[2048];
        GetModuleFileNameW(nullptr, wchar_exe_path, 2048);
        exe_path = Common::UTF16ToUTF8(wchar_exe_path);
        exe_path = exe_path.substr(0, exe_path.find_last_of('\\'));
    }
    return exe_path;
}
#else
/**
 * @return The user’s home directory on POSIX systems
 */
static const std::string& GetHomeDirectory() {
    static std::string home_path;
    if (home_path.empty()) {
        const char* envvar = getenv("HOME");
        if (envvar) {
            home_path = envvar;
        } else {
            auto pw = getpwuid(getuid());
            ASSERT_MSG(pw, "$HOME isn’t defined, and the current user can’t be found in /etc/passwd.");
            home_path = pw->pw_dir;
        }
    }
    return home_path;
}

/**
 * Follows the XDG Base Directory Specification to get a directory path
 * @param envvar The XDG environment variable to get the value from
 * @return The directory path
 * @sa http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
 */
static const std::string GetUserDirectory(const std::string& envvar) {
    const char* directory = getenv(envvar.c_str());

    std::string user_dir;
    if (directory) {
        user_dir = directory;
    } else {
        std::string subdirectory;
        if (envvar == "XDG_DATA_HOME")
            subdirectory = DIR_SEP ".local" DIR_SEP "share";
        else if (envvar == "XDG_CONFIG_HOME")
            subdirectory = DIR_SEP ".config";
//.........这里部分代码省略.........
开发者ID:Gabrielbeck,项目名称:citra,代码行数:101,代码来源:file_util.cpp

示例4: strip_extension

std::string strip_extension(const std::string& fname)
{
	return fname.substr(0, fname.find_last_of('.'));
}
开发者ID:suppertails66,项目名称:heerip,代码行数:4,代码来源:datmanip.cpp

示例5: process_xml_options

/// processes all 'driver' options in the XML file
void process_xml_options(const std::string& xml_fname)
{
  // *************************************************************
  // going to remove any path from the argument and change to that
  // path; this is done so that all files referenced from the
  // local path of the XML file are found
  // *************************************************************

  // set the filename to use as the argument, by default
  std::string filename = xml_fname;

  // get the current pathname
  size_t BUFSIZE = 128;
  boost::shared_array<char> cwd;
  while (true)
  {
    cwd = boost::shared_array<char>((new char[BUFSIZE]));
    if (getcwd(cwd.get(), BUFSIZE) == cwd.get())
      break;
    if (errno != ERANGE)
    {
      std::cerr << "process_xml_options() - unable to allocate sufficient memory!" << std::endl;
      return;
    }
    BUFSIZE *= 2;
  }

  // separate the path from the filename
  size_t last_path_sep = xml_fname.find_last_of('/');
  if (last_path_sep != std::string::npos)
  {
    // get the new working path
    std::string pathname = xml_fname.substr(0,last_path_sep+1);

    // change to the new working path
    chdir(pathname.c_str());

    // get the new filename
    filename = xml_fname.substr(last_path_sep+1,std::string::npos);
  }

  // read the XML Tree 
  shared_ptr<const XMLTree> driver_tree = XMLTree::read_from_xml(filename);
  if (!driver_tree)
  {
    std::cerr << "process_xml_options() - unable to open file " << xml_fname;
    std::cerr << " for reading" << std::endl;
    chdir(cwd.get());
    return;
  }
  
  // find the driver tree 
  driver_tree = find_subtree(driver_tree, "driver");

  // make sure that the driver node was found
  if (!driver_tree)
  {
    chdir(cwd.get());
    return;
  }

  // process tags
  process_tag("window", driver_tree, process_window_tag);
  process_tag("camera", driver_tree, process_camera_tag);

  // change back to current directory 
  chdir(cwd.get());
}
开发者ID:PositronicsLab,项目名称:no-slip-and-viscous-experiments,代码行数:69,代码来源:driver.cpp

示例6: OnInit

//OpenGL initialization function
void OnInit() { 
	//get the mesh path for loading of textures	
	std::string mesh_path = mesh_filename.substr(0, mesh_filename.find_last_of("/")+1);

	//load the obj model
	if(!obj.Load(mesh_filename.c_str(), meshes, vertices, indices, materials)) { 
		cout<<"Cannot load the 3ds mesh"<<endl;
		exit(EXIT_FAILURE);
	} 
	GL_CHECK_ERRORS

	//load material textures  
	for(size_t k=0;k<materials.size();k++) {
		//if the diffuse texture name is not empty
		if(materials[k]->map_Kd != "") { 
			//generate a new OpenGL array texture
			GLuint id = 0;
			glGenTextures(1, &id);
			glBindTexture(GL_TEXTURE_2D, id);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
			int texture_width = 0, texture_height = 0, channels=0;		 	

			const string& filename =  materials[k]->map_Kd;

			std::string full_filename = mesh_path;
			full_filename.append(filename);
			//use SOIL to load the texture
			GLubyte* pData = SOIL_load_image(full_filename.c_str(), &texture_width, &texture_height, &channels, SOIL_LOAD_AUTO);
			if(pData == NULL) {
				cerr<<"Cannot load image: "<<full_filename.c_str()<<endl;
				exit(EXIT_FAILURE);
			} 

			//Flip the image on Y axis
			int i,j;
			for( j = 0; j*2 < texture_height; ++j )
			{
				int index1 = j * texture_width * channels;
				int index2 = (texture_height - 1 - j) * texture_width * channels;
				for( i = texture_width * channels; i > 0; --i )
				{
					GLubyte temp = pData[index1];
					pData[index1] = pData[index2];
					pData[index2] = temp;
					++index1;
					++index2;
				}
			} 
			//get the image format
			GLenum format = GL_RGBA;
			switch(channels) {
				case 2:	format = GL_RG32UI; break;
				case 3: format = GL_RGB;	break;
				case 4: format = GL_RGBA;	break;
			}
			//allocate texture 
			glTexImage2D(GL_TEXTURE_2D, 0, format, texture_width, texture_height, 0, format, GL_UNSIGNED_BYTE, pData);

			//release the SOIL image data
			SOIL_free_image_data(pData);

			//add loaded texture ID to vector
			textures.push_back(id);
		}
	} 
	GL_CHECK_ERRORS

	//load flat shader
	flatShader.LoadFromFile(GL_VERTEX_SHADER, "shaders/flat.vert");
	flatShader.LoadFromFile(GL_FRAGMENT_SHADER, "shaders/flat.frag");
	//compile and link shader
	flatShader.CreateAndLinkProgram();
	flatShader.Use();	
		//add attribute and uniform
		flatShader.AddAttribute("vVertex");
		flatShader.AddUniform("MVP"); 
	flatShader.UnUse();

	//load mesh rendering shader
	shader.LoadFromFile(GL_VERTEX_SHADER, "shaders/shader.vert");
	shader.LoadFromFile(GL_FRAGMENT_SHADER, "shaders/shader.frag");
	//compile and link shader
	shader.CreateAndLinkProgram();
	shader.Use();	
		//add attribute and uniform
		shader.AddAttribute("vVertex");
		shader.AddAttribute("vNormal");
		shader.AddAttribute("vUV");		
		shader.AddUniform("MV");
		shader.AddUniform("N");
		shader.AddUniform("P");
		shader.AddUniform("textureMap");
		shader.AddUniform("useDefault");		
		shader.AddUniform("light_position");
		shader.AddUniform("diffuse_color");
		//set values of constant uniforms as initialization	
//.........这里部分代码省略.........
开发者ID:EiffelOberon,项目名称:opengl33_dev_cookbook_2013,代码行数:101,代码来源:main.cpp

示例7: load_texture_from_file

GLuint load_texture_from_file(std::string filename)
{
   //define return variable
   GLuint texture;

   //strip extension
   std::string extension;
   int delimiter_index = filename.find_last_of('.');
   //if a '.' was found
   if (delimiter_index != std::string::npos)
   {
      //get extension substring
      extension = filename.substr(delimiter_index + 1);
      //convert to uppercase
      std::transform(extension.begin(), extension.end(), extension.begin(), ::toupper);
      //get c_string
      const char* ext = extension.c_str();
      //check filetype
      if (strcmp(ext, "JPG") || strcmp(ext, "BMP") || strcmp(ext, "PNG"))
      {
         //make the texture
         glGenTextures(1, &texture);
         
         //bind the texture
         glBindTexture(GL_TEXTURE_2D, texture);

         //set our texture filtering
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

         //set our texture parameters
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);

         //load .jpg using SOIL
         int width, height;
         unsigned char* image = SOIL_load_image(filename.c_str(), &width, &height, 0, SOIL_LOAD_RGB);

         //generate the texture from image
         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);

         //generate mipmaps (openGL scaling objects)
         glGenerateMipmap(GL_TEXTURE_2D);

         //free the texture thing
         glBindTexture(GL_TEXTURE_2D, 0);

         if (texture == -1)
         {
            //THERE WAS AN ERROR - do something
         }
         else
            return texture;
      }
      else
      {
         //disagree.
         //throw an error? prompt the user? be displeased.
         //(tell the user to check the input file type)
      }
   }

   return texture;
}
开发者ID:jashook,项目名称:OpenGLSection,代码行数:64,代码来源:Main.cpp

示例8: loadMaterial

void BasicOpenGLView::loadMaterial(std::string m_Material)
{
    std::ifstream t(m_Material.c_str());
    std::stringstream buffer;
    buffer << t.rdbuf();

    /**
     * we assume file contents like this:
     * vertex path/to/vertex/shader.vs
     * fragment path/to/fragment/shader.fs
     *
     * with an optional
     * texture path/to/texture.png
     *
     * paths are relative to the m_Material path
     */

    if(mProgram)
    {
        delete mProgram;
        mProgram = NULL;
    }

    if(mTextureHandle)
    {
        glDeleteTextures(1, & mTextureHandle);
        mTextureHandle = 0;
    }

    std::string filePath = m_Material.substr(0, m_Material.find_last_of("/") + 1);

    const std::string vertex("vertex");
    const std::string fragment("fragment");
    const std::string texture("texture");
    const std::string bump("bumpmap");
    const std::string alphatex("alphatex");

    mProgram = new Program();

    std::string line;
    while(std::getline(buffer, line))
    {
        if(line.compare(0, vertex.size(), vertex) == 0)
        {
            std::string vertexPath = filePath + line.substr(vertex.size() + 1);

            std::ifstream v(vertexPath.c_str());
            std::stringstream vbuffer;
            vbuffer << v.rdbuf();

            Shader * vShader = new Shader(vbuffer.str(), Shader::VERTEX);
            if(vShader->load())
            {
                mProgram->push_back(vShader);
            }
        }
        else if(line.compare(0, fragment.size(), fragment) == 0)
        {
            std::string fragmentPath = filePath + line.substr(fragment.size() + 1);

            std::ifstream f(fragmentPath.c_str());
            std::stringstream fbuffer;
            fbuffer << f.rdbuf();

            Shader * fShader = new Shader(fbuffer.str(), Shader::FRAGMENT);
            if(fShader->load())
            {
                mProgram->push_back(fShader);
            }
        }
        else if(line.compare(0, texture.size(), texture) == 0)
        {
            std::string texturePath = filePath + line.substr(texture.size() + 1);

            /**
             * @todo assignment 3
             * use the texturePath to load an image from disc, and transfer its data to
             * OpenGL and store the OpenGL image handle in mTextureHandle
             */
            QImage tex;
            if (tex.load(texturePath.c_str())) {
                QImage ogTex = QGLWidget::convertToGLFormat(tex);

                // copy the texture to opengl
                glGenTextures(1, &mTextureHandle);
                glActiveTexture(GL_TEXTURE0);
                glBindTexture(GL_TEXTURE_2D, mTextureHandle);
                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ogTex.width(), ogTex.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, tex.bits());
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            } else {
                printf("Error finding texture\n");
            }
        }
        else if(line.compare(0, bump.size(), bump) == 0)
        {
            std::string texturePath = filePath + line.substr(bump.size() + 1);

            /**
             * @todo assignment 3
//.........这里部分代码省略.........
开发者ID:Gother,项目名称:CSC305-Graphics,代码行数:101,代码来源:basicopenglview.cpp

示例9: string

 // remove the extension from a filename
 std::string
 remove_extension(std::string const& filename)
 {
     std::string::size_type const n = filename.find_last_of('.');
     return std::string(filename.begin(), filename.begin()+n);
 }
开发者ID:AndroidAppList,项目名称:Android-Supertux,代码行数:7,代码来源:utils.hpp

示例10: appDirPath

/**
 * @brief appDirPath : 获取 application 所在路径(不包含文件名称)
 * @return : application 所在路径(不包含文件名称)
 */
J_EXTERN_C J_ATTR_EXPORT const char* appDirPath()
{
    static std::string _path = "";
    if (_path.empty()) {
#ifdef __unix__
        std::stringstream ss;
        ss << "/proc/" << getpid() << "/exe";
#endif
        //
        char buffer[J_PATH_MAX + 2];
        unsigned int length = 0;
#ifdef _MSC_VER
        length = (unsigned int)GetModuleFileNameA(NULL, buffer, J_PATH_MAX + 1);
#elif defined(__unix__)
        length = (unsigned int)readlink(ss.str().c_str(), buffer, J_PATH_MAX);
#endif
        //
        if (length == 0) {
            // error
        } else if (length <= J_PATH_MAX) {
            buffer[J_PATH_MAX + 1] = '\0';
            _path = buffer;
        } else {
            // J_PATH_MAX sized buffer wasn't large enough to contain the full path, use heap
            char *bufferNew = 0;
            int i = 1;
            size_t size;
            do {
                ++i;
                size = J_PATH_MAX * i;
                bufferNew = reinterpret_cast<char *>(realloc(bufferNew, (size + 1) * sizeof(char)));
                if (bufferNew) {
#ifdef _MSC_VER
                    length = (unsigned int)GetModuleFileNameA(NULL, buffer, J_PATH_MAX + 1);
#elif defined(__unix__)
                    length = (unsigned int)readlink(ss.str().c_str(), buffer, J_PATH_MAX);
#endif
                }
            } while (bufferNew && length == size);

            if (bufferNew) {
                *(bufferNew + size) = '\0';
            }

            _path = bufferNew;
            free(bufferNew);
        }

        //
        if (!_path.empty()) {
            //
            int index = _path.find_last_of('/');
            if (index == -1) {
                index = _path.find_last_of('\\');
            }
            if (index != -1) {
                _path = _path.substr(0, index);
            }
            // replace '\\' with '/'
            std::string::iterator iter = _path.begin();
            for (; iter != _path.end(); ++iter) {
                if (*iter == '\\') {
                    *iter = '/';
                }
            }
        }
    }

    return _path.c_str();
}
开发者ID:iclosure,项目名称:jframework,代码行数:74,代码来源:main.cpp

示例11: loadFromFile

U32 LLControlGroup::loadFromFile(const std::string& filename, bool set_default_values)
{
	if(mIncludedFiles.find(filename) != mIncludedFiles.end())
		return 0; //Already included this file.
	mIncludedFiles.insert(filename);

	std::string name;
	LLSD settings;
	LLSD control_map;
	llifstream infile;
	infile.open(filename);
	if(!infile.is_open())
	{
		llwarns << "Cannot find file " << filename << " to load." << llendl;
		return 0;
	}

	S32 ret = LLSDSerialize::fromXML(settings, infile);

	if (ret <= 0)
	{
		infile.close();
		llwarns << "Unable to open LLSD control file " << filename << ". Trying Legacy Method." << llendl;		
		return loadFromFileLegacy(filename, TRUE, TYPE_STRING);
	}

	U32	validitems = 0;
	bool hidefromsettingseditor = false;
	for(LLSD::map_const_iterator itr = settings.beginMap(); itr != settings.endMap(); ++itr)
	{
		bool persist = true;
		name = (*itr).first;
		control_map = (*itr).second;
		
		if(name == "Include")
		{
			if(control_map.isArray())
			{
#if LL_WINDOWS
				size_t pos = filename.find_last_of("\\");
#else
				size_t pos = filename.find_last_of("/");
#endif			
				if(pos!=std::string::npos)
				{
					const std::string dir = filename.substr(0,++pos);
					for(LLSD::array_const_iterator array_itr = control_map.beginArray(); array_itr != control_map.endArray(); ++array_itr)
						validitems+=loadFromFile(dir+(*array_itr).asString(),set_default_values);
				}
			}
			continue;
		}
		if(control_map.has("Persist")) 
		{
			persist = control_map["Persist"].asInteger();
		}
		
		// Sometimes we want to use the settings system to provide cheap persistence, but we
		// don't want the settings themselves to be easily manipulated in the UI because 
		// doing so can cause support problems. So we have this option:
		if(control_map.has("HideFromEditor"))
		{
			hidefromsettingseditor = control_map["HideFromEditor"].asInteger();
		}
		else
		{
			hidefromsettingseditor = false;
		}
		
		// If the control exists just set the value from the input file.
		LLControlVariable* existing_control = getControl(name);
		if(existing_control)
		{
			if(set_default_values)
			{
				// Override all previously set properties of this control.
				// ... except for type. The types must match.
				eControlType new_type = typeStringToEnum(control_map["Type"].asString());
				if(existing_control->isType(new_type))
				{
					existing_control->setDefaultValue(control_map["Value"]);
					existing_control->setPersist(persist);
					existing_control->setHiddenFromSettingsEditor(hidefromsettingseditor);
					existing_control->setComment(control_map["Comment"].asString());
				}
				else
				{
					llerrs << "Mismatched type of control variable '"
						   << name << "' found while loading '"
						   << filename << "'." << llendl;
				}
			}
			else if(existing_control->isPersisted())
			{
				
				existing_control->setValue(control_map["Value"]);
			}
			// *NOTE: If not persisted and not setting defaults, 
			// the value should not get loaded.
		}
//.........这里部分代码省略.........
开发者ID:CharleyLevenque,项目名称:SingularityViewer,代码行数:101,代码来源:llcontrol.cpp

示例12: LoadFromX

	void ModelRenderer::LoadFromX(const std::string &path)
	{
		// X ファイル とテクスチャのロード
		_mesh = Mesh::CreateFromX(path);
		// マテリアル情報の取得
		D3DXMATERIAL *materials = (D3DXMATERIAL*)(_mesh->GetMaterialBuffer()->GetBufferPointer());
		// テクスチャのロード
		TextureSP texture;
		for(size_t i = 0; i < _mesh->GetMaterialNumber(); i++){
			// 特定の部分でテクスチャが存在しない場合
			if(NULL == materials[i].pTextureFilename){
				texture = NULL;
				_textures.push_back(texture);
				D3DCOLORVALUE value = materials[i].MatD3D.Diffuse;
				// マテリアルから色情報を取得
				D3DXVECTOR4 color = D3DXVECTOR4(value.r, value.g, value.b, value.a);
				_diffuseColors.push_back(color);
				continue;
			}
			_diffuseColors.push_back(D3DXVECTOR4(0,0,0,0));

			//---------------------------------------------------
			// テクスチャのパスを自動的に生成

			// ファイルパスの前部分を格納する
			std::string texturePath;
			// Xファイルのパスから必要部分だけ抜き出す

			// "/" "\\"を検索しパスの区切りの最後の部分を検索する
			// Xファイルとテクスチャは同じフォルダにあるとし、
			// Xファイルのあるフォルダのパスまでを抜き取る

			// パスの最後の"/"を検索
			std::size_t index = path.find_last_of("/");
			if(index != std::string::npos)
			{
				texturePath = path.substr(0, index + 1);
			}
			// 該当なしなら"\\"で再検索
			else
			{
				index = path.find_last_of("\\");
				if(index != std::string::npos)
				{
					// パスの区切りが"\\"のときは"\\"の部分をはずしかわりに"/"をつける
					texturePath = path.substr(0, index);
					texturePath += "/";
				}
			}

			//------------------------------------------------------------------
			// Xファイルに記述されているテクスチャのパスの最後の部分だけを抜き出し前部分に追加
			std::string stringBuffer;
			stringBuffer = materials[i].pTextureFilename;
			// パスの最後の"/"を検索
			index = stringBuffer.find_last_of("/");
			if(index != std::string::npos)
			{
				std::string stringBuffer2;
				stringBuffer2 = stringBuffer.substr(index + 1);
				texturePath += stringBuffer2;
			}
			// 該当なしなら"\\"で再検索
			else{
				index = stringBuffer.find_last_of("\\");
				if(index != std::string::npos)
				{
					std::string stringBuffer2;
					stringBuffer2 = stringBuffer.substr(index + 1);
					texturePath += stringBuffer2;
				}
				// 該当なしならそのまま追加
				else{
					texturePath += stringBuffer;
				}
			}
			// 独自テクスチャクラスとして生成
			texture = Texture::CreateFromFile(texturePath, D3DX_DEFAULT);

			_textures.push_back(texture);
		}
	}
开发者ID:nuponsalt,项目名称:Game001,代码行数:82,代码来源:ModelRenderer.cpp

示例13: InternReadFile

// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void IFCImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
{
    std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile));
    if (!stream) {
        ThrowException("Could not open file for reading");
    }


    // if this is a ifczip file, decompress its contents first
    if(GetExtension(pFile) == "ifczip") {
#ifndef ASSIMP_BUILD_NO_COMPRESSED_IFC
        unzFile zip = unzOpen( pFile.c_str() );
        if(zip == NULL) {
            ThrowException("Could not open ifczip file for reading, unzip failed");
        }

        // chop 'zip' postfix
        std::string fileName = pFile.substr(0,pFile.length() - 3);

        std::string::size_type s = pFile.find_last_of('\\');
        if(s == std::string::npos) {
            s = pFile.find_last_of('/');
        }
        if(s != std::string::npos) {
            fileName = fileName.substr(s+1);
        }

        // search file (same name as the IFCZIP except for the file extension) and place file pointer there
        if(UNZ_OK == unzGoToFirstFile(zip)) {
            do {
                // get file size, etc.
                unz_file_info fileInfo;
                char filename[256];
                unzGetCurrentFileInfo( zip , &fileInfo, filename, sizeof(filename), 0, 0, 0, 0 );
                if (GetExtension(filename) != "ifc") {
                    continue;
                }
                uint8_t* buff = new uint8_t[fileInfo.uncompressed_size];
                LogInfo("Decompressing IFCZIP file");
                unzOpenCurrentFile(zip);
                size_t total = 0;
                int read = 0;
                do {
                    int bufferSize = fileInfo.uncompressed_size < INT16_MAX ? fileInfo.uncompressed_size : INT16_MAX;
                    void* buffer = malloc(bufferSize);
                    read = unzReadCurrentFile(zip, buffer, bufferSize);
                    if (read > 0) {
                        memcpy((char*)buff + total, buffer, read);
                        total += read;
                    }
                    free(buffer);
                } while (read > 0);
                size_t filesize = fileInfo.uncompressed_size;
                if (total == 0 || size_t(total) != filesize)
                {
                    delete[] buff;
                    ThrowException("Failed to decompress IFC ZIP file");
                }
                unzCloseCurrentFile( zip );
                stream.reset(new MemoryIOStream(buff,fileInfo.uncompressed_size,true));
                break;

                if (unzGoToNextFile(zip) == UNZ_END_OF_LIST_OF_FILE) {
                    ThrowException("Found no IFC file member in IFCZIP file (1)");
                }

            } while(true);
        }
        else {
            ThrowException("Found no IFC file member in IFCZIP file (2)");
        }

        unzClose(zip);
#else
        ThrowException("Could not open ifczip file for reading, assimp was built without ifczip support");
#endif
    }

    std::unique_ptr<STEP::DB> db(STEP::ReadFileHeader(stream));
    const STEP::HeaderInfo& head = static_cast<const STEP::DB&>(*db).GetHeader();

    if(!head.fileSchema.size() || head.fileSchema.substr(0,3) != "IFC") {
        ThrowException("Unrecognized file schema: " + head.fileSchema);
    }

    if (!DefaultLogger::isNullLogger()) {
        LogDebug("File schema is \'" + head.fileSchema + '\'');
        if (head.timestamp.length()) {
            LogDebug("Timestamp \'" + head.timestamp + '\'');
        }
        if (head.app.length()) {
            LogDebug("Application/Exporter identline is \'" + head.app  + '\'');
        }
    }

    // obtain a copy of the machine-generated IFC scheme
    ::Assimp::STEP::EXPRESS::ConversionSchema schema;
    Schema_2x3::GetSchema(schema);
//.........这里部分代码省略.........
开发者ID:msavva,项目名称:assimp,代码行数:101,代码来源:IFCLoader.cpp

示例14: write_ascii


//.........这里部分代码省略.........
        } // for
    }

    // First: write out TRI3 elements:
    out_stream << "Triangles\n";
    out_stream << n_tri3 << "\n";

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
        if ((*it)->type() == TRI3)
          out_stream << (*it)->node_id(0)+1  << " "
                     << (*it)->node_id(1)+1  << " "
                     << (*it)->node_id(2)+1  << " 0\n";
    }

    // Second: write out QUAD4 elements:
    out_stream << "Quadrilaterals\n";
    out_stream << n_quad4 << "\n";

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
        if ((*it)->type() == QUAD4)
          {
            out_stream << (*it)->node_id(0)+1  << " "
                       << (*it)->node_id(1)+1  << " "
                       << (*it)->node_id(2)+1  << " "
                       << (*it)->node_id(3)+1  <<" 0\n";
          } // if
        else if ((*it)->type() == QUAD9)
          {
            out_stream << (*it)->node_id(0)+1  << " "
                       << (*it)->node_id(4)+1  << " "
                       << (*it)->node_id(8)+1  << " "
                       << (*it)->node_id(7)+1  <<" 0\n";
            out_stream << (*it)->node_id(7)+1  << " "
                       << (*it)->node_id(8)+1  << " "
                       << (*it)->node_id(6)+1  << " "
                       << (*it)->node_id(3)+1  <<" 0\n";
            out_stream << (*it)->node_id(4)+1  << " "
                       << (*it)->node_id(1)+1  << " "
                       << (*it)->node_id(5)+1  << " "
                       << (*it)->node_id(8)+1  <<" 0\n";
            out_stream << (*it)->node_id(8)+1  << " "
                       << (*it)->node_id(5)+1  << " "
                       << (*it)->node_id(2)+1  << " "
                       << (*it)->node_id(6)+1  <<" 0\n";
          } // if
    }


    // Third: write out TET4 elements:
    out_stream << "Tetrahedra\n";
    out_stream << n_tet4 << "\n";

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
        if ((*it)->type() == TET4)
          {
            out_stream << (*it)->node_id(0)+1  << " "
                       << (*it)->node_id(1)+1  << " "
                       << (*it)->node_id(2)+1  << " "
                       << (*it)->node_id(3)+1  <<" 0\n";
          } // if
    }

  }
  // end of the out file
  out_stream << '\n' << "# end of file\n";

  // optionally write the data
  if ((solution_names != libmesh_nullptr) &&
      (vec != libmesh_nullptr))
    {
      // Open the ".bb" file stream
      std::size_t idx = fname.find_last_of(".");
      std::string bbname = fname.substr(0,idx) + ".bb";

      std::ofstream bbout (bbname.c_str());

      // Make sure it opened correctly
      if (!bbout.good())
        libmesh_file_error(bbname.c_str());

      // Header: 3: 3D mesh, 1: scalar output, 2: node-indexed
      const std::size_t n_vars = solution_names->size();
      bbout << "3 1 " << the_mesh.n_nodes() << " 2\n";
      for (dof_id_type n=0; n<the_mesh.n_nodes(); n++)
        bbout << std::setprecision(10) << (*vec)[n*n_vars + scalar_idx] << " ";
      bbout << "\n";
    } // endif
}
开发者ID:borisboutkov,项目名称:libmesh,代码行数:101,代码来源:medit_io.C

示例15: saveOtbm

void Map::saveOtbm(const std::string& fileName)
{
    try {
        FileStreamPtr fin = g_resources.createFile(fileName);
        if(!fin)
            stdext::throw_exception(stdext::format("failed to open file '%s' for write", fileName));

        fin->cache();
        std::string dir;
        if(fileName.find_last_of('/') == std::string::npos)
            dir = g_resources.getWorkDir();
        else
            dir = fileName.substr(0, fileName.find_last_of('/'));

        uint32 version = 0;
        if(g_things.getOtbMajorVersion() < ClientVersion820)
            version = 1;
        else
            version = 2;

        /// Usually when a map has empty house/spawn file it means the map is new.
        /// TODO: Ask the user for a map name instead of those ugly uses of substr
        std::string::size_type sep_pos;
        std::string houseFile = getHouseFile();
        std::string spawnFile = getSpawnFile();
        std::string cpyf;

        if((sep_pos = fileName.rfind('.')) != std::string::npos && stdext::ends_with(fileName, ".otbm"))
            cpyf = fileName.substr(0, sep_pos);

        if(houseFile.empty())
            houseFile = cpyf + "-houses.xml";

        if(spawnFile.empty())
            spawnFile = cpyf + "-spawns.xml";

        /// we only need the filename to save to, the directory should be resolved by the OTBM loader not here
        if((sep_pos = spawnFile.rfind('/')) != std::string::npos)
            spawnFile = spawnFile.substr(sep_pos + 1);

        if((sep_pos = houseFile.rfind('/')) != std::string::npos)
            houseFile = houseFile.substr(sep_pos + 1);

        fin->addU32(0); // file version
        OutputBinaryTreePtr root(new OutputBinaryTree(fin));
        {
            root->addU32(version);

            Size mapSize = getSize();
            root->addU16(mapSize.width());
            root->addU16(mapSize.height());

            root->addU32(g_things.getOtbMajorVersion());
            root->addU32(g_things.getOtbMinorVersion());

            root->startNode(OTBM_MAP_DATA);
            {
                root->addU8(OTBM_ATTR_DESCRIPTION);
                root->addString(m_attribs.get<std::string>(OTBM_ATTR_DESCRIPTION));

                root->addU8(OTBM_ATTR_SPAWN_FILE);
                root->addString(spawnFile);

                root->addU8(OTBM_ATTR_HOUSE_FILE);
                root->addString(houseFile);

                int px = -1, py = -1, pz =-1;
                bool firstNode = true;

                for(uint8_t z = 0; z <= Otc::MAX_Z; ++z) {
                    for(const auto& it : m_tileBlocks[z]) {
                        const TileBlock& block = it.second;
                        for(const TilePtr& tile : block.getTiles()) {
                            if(unlikely(!tile || tile->isEmpty()))
                                continue;

                            const Position& pos = tile->getPosition();
                            if(unlikely(!pos.isValid()))
                                continue;

                            if(pos.x < px || pos.x >= px + 256
                                    || pos.y < py || pos.y >= py + 256
                                    || pos.z != pz) {
                                if(!firstNode)
                                    root->endNode(); /// OTBM_TILE_AREA

                                firstNode = false;
                                root->startNode(OTBM_TILE_AREA);

                                px = pos.x & 0xFF00;
                                py = pos.y & 0xFF00;
                                pz = pos.z;
                                root->addPos(px, py, pz);
                            }

                            root->startNode(tile->isHouseTile() ? OTBM_HOUSETILE : OTBM_TILE);
                            root->addPoint(Point(pos.x, pos.y) & 0xFF);
                            if(tile->isHouseTile())
                                root->addU32(tile->getHouseId());

//.........这里部分代码省略.........
开发者ID:AdamSC1-ddg,项目名称:otclient,代码行数:101,代码来源:mapio.cpp


注:本文中的std::string::find_last_of方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。