bool GBufferSchemeHandler::checkNormalMap( TextureUnitState* tus, GBufferSchemeHandler::PassProperties& props) { bool isNormal = false; Ogre::String lowerCaseAlias = tus->getTextureNameAlias(); Ogre::StringUtil::toLowerCase(lowerCaseAlias); if (lowerCaseAlias.find(NORMAL_MAP_PATTERN) != Ogre::String::npos) { isNormal = true; } else { Ogre::String lowerCaseName = tus->getTextureName(); Ogre::StringUtil::toLowerCase(lowerCaseName); if (lowerCaseName.find(NORMAL_MAP_PATTERN) != Ogre::String::npos) { isNormal = true; } } if (isNormal) { if (props.normalMap == 0) { props.normalMap = tus; } else { OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, "Multiple normal map patterns matches", "GBufferSchemeHandler::inspectPass"); } } return isNormal; }
//----------------------------------------------------------------------------- void Ogitors::COFSSceneSerializer::_upgradeOgsceneFileFrom2To3(TiXmlNode* ogsceneRootNode) { TiXmlElement* element = ogsceneRootNode->FirstChildElement(); unsigned int obj_count = 0; Ogre::String objecttype; OgitorsPropertyValueMap params; OgitorsPropertyValue tmpPropVal; Ogre::String objAttValue; size_t offset = 0; do { objAttValue = ValidAttr(element->Attribute("typename"), ""); if(objAttValue != "") { if((offset = objAttValue.find(" Object")) != Ogre::String::npos) { objAttValue = objAttValue.substr(0, offset); element->SetAttribute("typename", objAttValue.c_str()); } } else continue; } while(element = element->NextSiblingElement()); }
Version::Version(const Ogre::String& version) { size_t length = version.length(); size_t offset = 0; size_t foundAt; Ogre::String component; int index = 0; while (index < MAX_COMPONENTS && offset < length) { //Extract the current component foundAt = version.find('.', offset); component = version.substr(offset); this->components[index++] = Ogre::StringConverter::parseInt(component); //Break out if there is no next '.' if (foundAt == Ogre::String::npos) break; //Move past the next '.' offset = foundAt + 1; } for (; index < MAX_COMPONENTS; index++) this->components[index] = 0; }
/* Always get the actual pointers, because they may change. That is the reason why the datablock pointer cannot be cached. * The same seems to apply to the texture pointer. */ Ogre::HlmsDatablock* datablock; Ogre::HlmsPbsDatablock* datablockPbs; Ogre::TexturePtr texture; Ogre::HlmsManager* hlmsManager = Ogre::Root::getSingletonPtr()->getHlmsManager(); Ogre::HlmsPbs* hlmsPbs = static_cast<Ogre::HlmsPbs*>(hlmsManager->getHlms(Ogre::HLMS_PBS)); datablock = hlmsPbs->getDatablock(mDatablockId); if (!datablock) return; datablockPbs = static_cast<Ogre::HlmsPbsDatablock*>(datablock); try { // Get texture on GPU if (!datablockPbs->getTexture(mTextureType).isNull()) { texture = datablockPbs->getTexture(mTextureType); // TextureType MUST exist, otherwise the application crashes mNumMipMaps = texture->getNumMipmaps(); } } catch (Ogre::Exception e){} if (texture.isNull()) return; Ogre::uint8 maxMipMaps = mNumMipMaps + 1; // Increase with one, because there is always one image to blit maxMipMaps = maxMipMaps > PAINT_MAX_MIP_MAPS ? PAINT_MAX_MIP_MAPS : maxMipMaps; // Just paint a few mipmaps (not all) Ogre::Image textureOnWhichIsPaintedScaled = mTextureOnWhichIsPainted; // Temporary image must be used, otherwise painting doesn't work size_t w = mTextureOnWhichIsPaintedWidth; size_t h = mTextureOnWhichIsPaintedHeight; Ogre::v1::HardwarePixelBuffer* buffer; for (Ogre::uint8 i = 0; i < maxMipMaps; ++i) { buffer = texture->getBuffer(0, i).getPointer(); buffer->blitFromMemory(textureOnWhichIsPaintedScaled.getPixelBox(0, 0), Ogre::Box(0, 0, 0, w, h, 1)); w*=0.5f; // Mipmaps always are half of the previous one h*=0.5f; if (w < 1.0f || h < 1.0f) break; // Stop when the mipmaps are too small textureOnWhichIsPaintedScaled.resize(w, h); } textureOnWhichIsPaintedScaled.freeMemory(); } //****************************************************************************/ void TextureLayer::setFirstTextureGeneration (void) { // Don't check on existence mTextureFileName, because it does exist loadTextureGeneration(mTextureFileName); } //****************************************************************************/ void TextureLayer::setLastTextureGeneration (void) { Ogre::String textureFileNameGeneration = getTextureFileNameGeneration (mMaxSequence); // returns full qualified filename if (textureFileExists(textureFileNameGeneration)) loadTextureGeneration(textureFileNameGeneration); } //****************************************************************************/ void TextureLayer::loadTextureGeneration (Ogre::ushort sequence) { Ogre::String textureFileNameGeneration = getTextureFileNameGeneration (sequence); // returns full qualified filename if (sequence == 0) loadTextureGeneration(textureFileNameGeneration); // Don't check the filename if sequence is 0, because it is without path else if (textureFileExists(textureFileNameGeneration)) loadTextureGeneration(textureFileNameGeneration); } //****************************************************************************/ void TextureLayer::loadTextureGeneration (const Ogre::String& filename) { // Assume the filename exists mTextureOnWhichIsPainted.load(filename, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); mPixelboxTextureOnWhichIsPainted = mTextureOnWhichIsPainted.getPixelBox(0, 0); mTextureOnWhichIsPaintedHasAlpha = mTextureOnWhichIsPainted.getHasAlpha(); mTextureOnWhichIsPaintedWidth = mPixelboxTextureOnWhichIsPainted.getWidth(); mTextureOnWhichIsPaintedHeight = mPixelboxTextureOnWhichIsPainted.getHeight(); // In theory, createCarbonCopyTexture() of all related paintlayers should be called, // but the texture size doesn't change in practice. blitTexture(); } //****************************************************************************/ void TextureLayer::saveTextureGeneration (void) { // Increase the sequence ++mMaxSequence; Ogre::String textureFileNameGeneration = getTextureFileNameGeneration (mMaxSequence); // returns full qualified filename // Saving the Image must be done in the background, otherwise the painting stutters QThread* thread = new QThread; TextureSaveWorker* textureSaveWorker = new TextureSaveWorker (mTextureOnWhichIsPainted, textureFileNameGeneration); textureSaveWorker->moveToThread(thread); connect(thread, SIGNAL(started()), textureSaveWorker, SLOT(saveImage())); connect(textureSaveWorker, SIGNAL(finished()), thread, SLOT(quit())); connect(textureSaveWorker, SIGNAL(finished()), textureSaveWorker, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); } //****************************************************************************/ const Ogre::String& TextureLayer::saveTextureWithTimeStampToImportDir (void) { Ogre::String strippedTextureFileName = mTextureFileName; Ogre::String extension = mTextureFileName; strippedTextureFileName.erase(strippedTextureFileName.find_last_of("."), Ogre::String::npos); // Remove extension if (strippedTextureFileName.find("_hlms") != Ogre::String::npos) strippedTextureFileName.erase(strippedTextureFileName.find("_hlms"), Ogre::String::npos); // Remove earlier hlms editor additions extension.erase(0, extension.find_last_of(".")); mHelperString = strippedTextureFileName + "_hlms" + Ogre::StringConverter::toString((size_t)time(0)) + extension; mTextureOnWhichIsPainted.save(DEFAULT_IMPORT_PATH.toStdString() + mHelperString); // Saving to the import dir doesn't have to be in the background return mHelperString; // Return the basename }
//----------------------------------------------------------------------------------------- void CEntityEditor::createProperties(OgitorsPropertyValueMap ¶ms) { PROPERTY_PTR(mMeshFile , "meshfile" , Ogre::String,"" ,0, SETTER(Ogre::String, CEntityEditor, _setMeshFile)); PROPERTY_PTR(mCastShadows , "castshadows" , bool ,false,0, SETTER(bool, CEntityEditor, _setCastShadows)); PROPERTY_PTR(mSubEntityCount, "subentitycount", int , -1 ,0, 0); PROPERTY_PTR(mRenderingDistance, "renderingdistance",Ogre::Real ,5000,0, SETTER(Ogre::Real, CEntityEditor, _setRenderingDistance)); int count = 0; OgitorsPropertyValueMap::const_iterator it = params.find("subentitycount"); if(it != params.end()) count = Ogre::any_cast<int>(it->second.val); OgitorsPropertyDef *definition; for(int ix = 0; ix < count; ix++) { Ogre::String sCount1 = "SubEntities::SubEntity" + Ogre::StringConverter::toString(ix); Ogre::String sCount2 = "subentity" + Ogre::StringConverter::toString(ix); definition = mFactory->AddPropertyDefinition(sCount2 + "::material", sCount1 + "::Material", "Sub Entity's Material Name", PROP_STRING, true, true); definition->setOptions(OgitorsRoot::GetMaterialNames()); mFactory->AddPropertyDefinition(sCount2 + "::visible", sCount1 + "::Visible", "Sub Entity's Visibility", PROP_BOOL, true, true); PROPERTY(sCount2 + "::material", Ogre::String, "", ix, SETTER(Ogre::String, CEntityEditor, _setSubMaterial)); PROPERTY(sCount2 + "::visible", bool, true, ix, SETTER(bool, CEntityEditor, _setSubVisible)); } mProperties.initValueMap(params); Ogre::String addstr = mMeshFile->get(); int ret = addstr.find(".mesh"); if(ret != -1) { addstr.erase(ret, 5); mMeshFile->init(addstr); } }
//----------------------------------------------------------------------- void ParticleRenderer::_stripNameFromSoftPrefix(Ogre::String& name) { if (name.find(SOFT_PREFIX) != Ogre::String::npos) { // Remove the prefix name.erase(0, SOFT_PREFIX.length()); } }
void LiquidCreatorDialog::OnInitDialog(wxInitDialogEvent &e) { wxDialog::OnInitDialog(e); wxSizer* sizer = LiquidCreator(this, true, true); /// 获取各控件的引用 mComboBox = wxDynamicCast(this->FindWindow(ID_MATERIALCOMBO),wxComboBox); assert (mComboBox); Ogre::ResourceManager::ResourceMapIterator resourceMapIterator = Ogre::MaterialManager::getSingleton().getResourceIterator(); while ( resourceMapIterator.hasMoreElements() ) { if ( resourceMapIterator.peekNextValue()->getGroup() == Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME ) { Ogre::String matName = resourceMapIterator.peekNextValue()->getName(); // 只有材质名称中包含“水”才加入到combobox中 if (matName.find("water") != Ogre::String::npos || matName.find("Water") != Ogre::String::npos || matName.find("水01") != Ogre::String::npos) mComboBox->AppendString( matName.c_str() ); } resourceMapIterator.moveNext(); } resourceMapIterator = Ogre::MaterialManager::getSingleton().getResourceIterator(); mComboBox->SetValue( resourceMapIterator.peekNextValue()->getName().c_str() ); mSubDivideTextCtrl = wxDynamicCast(this->FindWindow(ID_SUBDIVISIONTEXTCTRL),wxTextCtrl); assert (mSubDivideTextCtrl); mTexScaleTextCtrl = wxDynamicCast(this->FindWindow(ID_TEXCOORDSCALETEXTCTRL),wxTextCtrl); assert (mTexScaleTextCtrl); mDiffuseTextCtrl = wxDynamicCast(this->FindWindow(ID_DIFFUSETEXTCTRL),wxTextCtrl); assert (mDiffuseTextCtrl); mDepthTextCtrl = wxDynamicCast(this->FindWindow(ID_DEPTHTEXTCTRL),wxTextCtrl); assert (mDepthTextCtrl); }
//----------------------------------------------------------------------- void EntityRenderer::_destroyAll(void) { if (!mParentTechnique) return; // Delete the visual data vector<EntityRendererVisualData*>::const_iterator it; vector<EntityRendererVisualData*>::const_iterator itEnd = mAllVisualData.end(); for (it = mAllVisualData.begin(); it != itEnd; ++it) { PU_DELETE_T(*it, EntityRendererVisualData, MEMCATEGORY_SCENE_OBJECTS); } mAllVisualData.clear(); mVisualData.clear(); // V1.5: Destroy the created ChildSceneNodes (which leads to detaching the Entities) if (mParentTechnique->getParentSystem()) { Ogre::SceneNode* parentNode = mParentTechnique->getParentSystem()->getParentSceneNode(); if (parentNode) { String sceneNodeName; std::stringstream ss; unsigned short numChilds = parentNode->numChildren(); for (unsigned short i = 0; i < numChilds; ++i) { Ogre::Node* node = parentNode->getChild(i); if (node) { Ogre::String name = node->getName(); if (name.find("ParticleUniverse") != Ogre::String::npos) { parentNode->removeAndDestroyChild(i); } } } } } // V1.5 // Destroy the Entities. Do it like this, because it must be assured that the entity still exists // and has not already been destroyed. Ogre::SceneManager* sceneManager = mParentTechnique->getParentSystem()->getSceneManager(); for (size_t i = 0; i < mQuota; i++) { if (sceneManager->hasEntity(mEntityName + StringConverter::toString(i))) { sceneManager->destroyEntity(mEntityName + StringConverter::toString(i)); } } mEntities.clear(); // Reset the visual data in the pool mParentTechnique->initVisualDataInPool(); }
void Main::AddOgreResourcePath(Ogre::String dir, Ogre::String resourceGroup) { if (dir.find("svn") != Ogre::String::npos) return; boost::filesystem::path path(dir.c_str()); Ogre::ResourceGroupManager::getSingleton().addResourceLocation(dir, "FileSystem", resourceGroup); for (boost::filesystem::directory_iterator i(path); i != boost::filesystem::directory_iterator(); i++) { if (boost::filesystem::is_directory((*i))) AddOgreResourcePath((*i).path().directory_string().c_str(), resourceGroup); } }
//----------------------------------------------------------------------------------------- void CTerrainGroupEditor::importFullTerrainFromHeightMap() { UTFStringVector extlist; extlist.push_back(OTR("PNG Grayscale")); extlist.push_back("*.png"); extlist.push_back(OTR("Raw 32bit Float File")); extlist.push_back("*.raw;*.ohm;*.f32;*.r32"); Ogre::UTFString defaultPath = mSystem->GetSetting("system", "ExportTerrainPath", ""); Ogre::String filename = mSystem->DisplayOpenDialog(OTR("Import Heightmap"), extlist, defaultPath); if(filename == "") return; mSystem->SetSetting("system", "ExportTerrainPath", OgitorsUtils::ExtractFilePath(filename)); Ogre::NameValuePairList params; if(!mSystem->DisplayImportHeightMapDialog(params)) return; Ogre::Real fScale = Ogre::StringConverter::parseReal(params["scale"]); Ogre::Real fBias = Ogre::StringConverter::parseReal(params["bias"]); Ogre::String normal = params["normal"]; Ogre::String diffuse = params["diffuse"]; bool flipV = Ogre::StringConverter::parseBool(params["inverted"]); float *data = 0; float *flipBV = 0; Ogre::String namePart = OgitorsUtils::ExtractFileName(filename); namePart.erase(0, namePart.find(".")); int imgW = 0; int imgH = 0; if(namePart == ".png") { std::fstream fstr(filename.c_str(), std::ios::in|std::ios::binary); Ogre::DataStreamPtr stream = Ogre::DataStreamPtr(OGRE_NEW Ogre::FileStreamDataStream(&fstr, false)); Ogre::Image img; img.load(stream); data = OGRE_ALLOC_T(float, img.getWidth() * img.getHeight(), Ogre::MEMCATEGORY_GEOMETRY); Ogre::PixelBox pb(img.getWidth(), img.getHeight(), 1, Ogre::PF_FLOAT32_R, data); Ogre::PixelUtil::bulkPixelConversion(img.getPixelBox(), pb); imgW = img.getWidth(); imgH = img.getHeight(); img.freeMemory(); stream.setNull(); }
void WidgetFactory::Widget_Caption(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value) { // change '\n' on char 10 size_t pos = _value.find("\\n"); if (pos == std::string::npos) _widget->setCaption(_value); else { std::string value(_value); while (pos != std::string::npos) { value[pos++] = '\n'; value.erase(pos, 1); pos = value.find("\\n"); } _widget->setCaption(value); } }
void dmz::RenderModuleCoreOgreBasic::_init_render_system (Config &local) { if (_root) { String renderSystemName ( config_to_string ("renderSystem.name", local, "OpenGL")); Ogre::RenderSystem *renderSystem (0); Ogre::RenderSystemList *renderSystemList = _root->getAvailableRenderers (); if (renderSystemList) { Ogre::RenderSystemList::iterator it = renderSystemList->begin (); while (it != renderSystemList->end () && !renderSystem) { if (renderSystemList->size () == 1) { renderSystem = *it; } else { Ogre::String curName ((*it)->getName ()); if (curName.find (renderSystemName.get_buffer ()) >= 0) { renderSystem = *it; } } it++; } } if (renderSystem) { _root->setRenderSystem (renderSystem); _root->initialise (false); // don't autocreate a window } else { _log.error << "Specified render system (" << renderSystemName << ") not found" << endl; } } }
void OgreSetup::parseWindowGeometry(Ogre::ConfigOptionMap& config, unsigned int& width, unsigned int& height, bool& fullscreen) { auto opt = config.find("Video Mode"); if (opt != config.end()) { Ogre::String val = opt->second.currentValue; Ogre::String::size_type pos = val.find('x'); if (pos != Ogre::String::npos) { width = Ogre::StringConverter::parseUnsignedInt(val.substr(0, pos)); height = Ogre::StringConverter::parseUnsignedInt(val.substr(pos + 1)); } } //now on to whether we should use fullscreen opt = config.find("Full Screen"); if (opt != config.end()) { fullscreen = (opt->second.currentValue == "Yes"); } }
void wxObjectFolderTree::OnToolbarEvent(int toolID, Ogre::String toolname) { if (toolname == "NewResource") { wxEdit::Instance().GetWorldExplorer()->GetResourceTree()->ClearObjectPreview(); Ogre::String insertpath = wxEdit::Instance().GetWorldExplorer()->GetResourceTree()->GetInsertPath(); Ogre::String file = wxEdit::Instance().GetWorldExplorer()->GetResourceTree()->DoCreateFileDialog(); if (file == "") return; if (file.find(".ocs") == Ogre::String::npos) file = file + ".ocs"; Ogre::String fullPath = wxEdit::Instance().GetWorldExplorer()->GetResourceTree()->mRootPath + PATH_SEPERATOR + insertpath + file; wxEditGOResource *page = ((wxEditGOResource*)(wxEdit::Instance().GetpropertyWindow()->SetPage("EditGOCRes"))); page->NewResource(fullPath); page->OnApply(); page->SetResource(fullPath); wxTreeItemId id = wxEdit::Instance().GetWorldExplorer()->GetResourceTree()->ExpandToPath(wxFileName(insertpath + file)); } }
void wxObjectFolderTree::OnSelectItemCallback() { ClearObjectPreview(); if (mCurrentItem->IsRoot()) return; mCurrentPath = Ogre::String(GetRelativePath(mCurrentItem->GetId()).GetPath().c_str()) + PATH_SEPERATOR; if (mCurrentItem->IsFile()) { Ogre::String Path = "Data/Editor/Objects/" + Ogre::String(GetRelativePath(mCurrentItem->GetId()).GetPath().c_str()) + PATH_SEPERATOR; Ogre::String File = mCurrentItem->GetName().c_str(); mCurrentPath += File; Ogre::String extension = File.substr(File.find(".")+1, File.length()); wxEdit::Instance().GetOgrePane()->OnSelectResource(); if (extension == "ocs" && wxEdit::Instance().GetWorldExplorer()->GetSelection() == 1) { CreateObjectPreview(Path + File); ((wxEditGOResource*)(wxEdit::Instance().GetpropertyWindow()->SetPage("EditGOCRes")))->SetResource(Path + File); } } }
void wxObjectFolderTree::OnMenuCallback(int id) { if (id == ResTree_addGOC) { wxEdit::Instance().GetWorldExplorer()->GetResourceTree()->ClearObjectPreview(); Ogre::String relPath = Ogre::String(this->GetRelativePath(mCurrentItem->GetId()).GetFullPath().c_str()) + PATH_SEPERATOR; Ogre::String file = wxEdit::Instance().GetWorldExplorer()->GetResourceTree()->DoCreateFileDialog(); if (file == "") return; if (file.find(".ocs") == Ogre::String::npos) file = file + ".ocs"; Ogre::String fullPath = wxEdit::Instance().GetWorldExplorer()->GetResourceTree()->mRootPath + PATH_SEPERATOR + relPath + file; wxEditGOResource *page = ((wxEditGOResource*)(wxEdit::Instance().GetpropertyWindow()->SetPage("EditGOCRes"))); page->NewResource(fullPath); page->OnApply(); page->SetResource(fullPath); wxTreeItemId id = ExpandToPath(wxFileName(relPath + file)); } }
void ContentModule::initializeTextures() const { Ogre::String resourceGroup = getId(); StringVector texLocations = getTextureLocations(); for(StringVector::iterator iter = texLocations.begin(); iter != texLocations.end(); iter++) { Ogre::String location = *iter; if (location.find(".zip") != Ogre::String::npos) { ResourceGroupManager::getSingleton().addResourceLocation( getDirectory() + "/materials/" + location, Ogre::String("Zip"), resourceGroup); } else { ResourceGroupManager::getSingleton().addResourceLocation( getDirectory() + "/materials/" + location, "FileSystem", resourceGroup); } } addSearchPath(getDirectory()+"/materials", resourceGroup); }
void ScopeLog::messageLogged( const Ogre::String& message, Ogre::LogMessageLevel lml, bool maskDebug, const Ogre::String &logName, bool& skipThisMessage) #endif // OGRE_VERSION { if (!f) return; counter++; if (!headerWritten) { time_t t = time(NULL); fprintf(f, "<html><header><title>%s</title>\n", name.c_str()); fprintf(f, "<style type=\"text/css\">\n"); fprintf(f, ".LogMessageLevel1 { font-size:0.9em;color:DarkGreen; }\n"); fprintf(f, ".LogMessageLevel2 { font-size:1.0em;color:Black; }\n"); fprintf(f, ".LogMessageLevel3 { font-size:1.2em;color:DarkRed; }\n"); fprintf(f, ".Warning { font-size:1.1em;color:Orange; }\n"); fprintf(f, ".WarningMeshFormat { font-size:0.8em;color:GoldenRod; }\n"); fprintf(f, ".OgreNotice { font-size:0.8em;color:OliveDrab; }\n"); fprintf(f, ".RoRNotice { font-size:0.8em;color:SeaGreen; }\n"); fprintf(f, ".CompilerError { font-size:1.2em;color:Red; }\n"); fprintf(f, ".MaterialError { font-size:1.2em;color:Red; }\n"); fprintf(f, ".GeneralError { font-size:1.2em;color:Red; }\n"); fprintf(f, ".IgnoreThis { font-size:0.8em;color:DarkGrey; }\n"); fprintf(f, ".BeamInputOutputInfo { font-size:0.9em;color:DeepSkyBlue; }\n"); fprintf(f, ".BeamInputOutputWarning { font-size:1.2em;color:Orange; }\n"); fprintf(f, ".BeamInputOutputError { font-size:1.2em;color:OrangeRed; }\n"); fprintf(f, ".BeamInputOutputFatal { font-size:1.2em;color:DarkRed; }\n"); fprintf(f, ".tableheader { font-weight:bold; }\n"); fprintf(f, ".logtable { border-collapse:collapse;font-family:monospace;border:1px solid #aaaaaa; }\n"); fprintf(f, ".logtd { border:1px solid #aaaaaa;vertical-align:top; }\n"); fprintf(f, "</style>\n"); fprintf(f, "</header><body>\n"); fprintf(f, "Log for <b>%s</b> created on <b>%s</b> with <b>Rigs of Rods %s</b> ", name.c_str(), ctime(&t), ROR_VERSION_STRING); fprintf(f, "(built at %s on %s )<br/>\n", __DATE__, __TIME__); fprintf(f, "<table class=\"logtable\"><tr class='tableheader'><td class='logtd'>counter</td><td class='logtd'>ms since start</td><td class='logtd'>type</td><td class='logtd'>message</td></tr>\n"); fprintf(f, "<tr><td colspan=\"4\" class='logtd'>Log started: %s</td></tr>\n", ctime(&t)); headerWritten = true; } // use type depending on log message level char type[50]=""; sprintf(type, "LogMessageLevel%d", lml); // reminder: this if switch is highly sorted if (message.find("you should upgrade it as soon as possible using the OgreMeshUpgrade tool") != String::npos) { sprintf(type, "WarningMeshFormat"); obsoleteWarning++; } else if (message.find("WARNING:") != String::npos) { sprintf(type, "Warning"); warning++; } else if (message.find("Can't assign material ") != String::npos) { sprintf(type, "MaterialError"); error++; } else if (message.find("Compiler error: ") != String::npos) { sprintf(type, "CompilerError"); error++; } else if (message.find("Invalid WAV file: ") != String::npos) { sprintf(type, "GeneralError"); error++; } else if (message.find("Error while loading Terrain: ") != String::npos) { sprintf(type, "GeneralError"); error++; } else if (message.find("Error loading texture ") != String::npos) { sprintf(type, "GeneralError"); error++; } else if (message.find("ODEF: ") != String::npos) { sprintf(type, "BeamInputOutputInfo"); info++; } else if (message.find("BIO|INFO") != String::npos) { sprintf(type, "BeamInputOutputInfo"); info++; } else if (message.find("BIO|WARNING") != String::npos) { sprintf(type, "BeamInputOutputWarning"); // no counter usage, handle differently for BIO } else if (message.find("BIO|ERROR") != String::npos) { sprintf(type, "BeamInputOutputError"); // no counter usage, handle differently for BIO } else if (message.find("BIO|FATAL") != String::npos) { sprintf(type, "BeamInputOutputFatal"); // no counter usage, handle differently for BIO } else if (message.find("Inertia|") != String::npos) { sprintf(type, "BeamInputOutputInfo"); info++; } else if (message.find("Mesh: Loading ") != String::npos) { sprintf(type, "OgreNotice"); info++; } else if (message.find("Loading 2D Texture") != String::npos) { sprintf(type, "OgreNotice"); info++; } else if (message.find("Loading 2D Texture") != String::npos) { sprintf(type, "OgreNotice"); info++; } else if (message.find("Texture: ") != String::npos) { sprintf(type, "OgreNotice"); info++; } else if (message.find("Caelum: ") != String::npos) { sprintf(type, "OgreNotice"); info++; } else if (message.find("Info: Freetype returned ") != String::npos) { sprintf(type, "IgnoreThis"); // no counter } else if (message.find("static map icon not found: ") != String::npos) { sprintf(type, "IgnoreThis"); // no counter } else if (message.find("COLL: ") != String::npos) { sprintf(type, "RoRNotice"); info++; } else if (message.find("Loading WAV file ") != String::npos) { sprintf(type, "RoRNotice"); info++; } else if (message.find("SoundScriptInstance: instance created: ") != String::npos) { sprintf(type, "RoRNotice"); info++; } else if (message.find("FLEXBODY ") != String::npos) { sprintf(type, "RoRNotice"); info++; } else if (message.find("MaterialFunctionMapper: replaced mesh material ") != String::npos) { sprintf(type, "RoRNotice"); info++; } else if (message.find("MaterialFunctionMapper: replaced entity material ") != String::npos) { sprintf(type, "RoRNotice"); info++; } unsigned long time = Ogre::Root::getSingleton().getTimer()->getMilliseconds(); fprintf(f, "<tr class='%s'>"\ "<td class='logtd'><a name='%d' href='#%d'>%d</a></td>" \ "<td class='logtd'>%ld</td>" \ "<td class='logtd'>%s</td>" \ "<td class='logtd'>%s</td>" \ "</tr>\n", type, counter, counter, counter, time, type, message.c_str()); }
//----------------------------------------------------------------------- void MaterialTab::OnLoadTexture(wxCommandEvent& event) { // Add a new directory and parse all resources in that directory wxFileDialog loadDialog(this, _("Load a texture"), wxT(""), wxT(""), _("Textures (*.*)|*.*"), wxFD_OPEN, wxDefaultPosition, wxDefaultSize, _("Load")); if (loadDialog.ShowModal() == wxID_OK) { SetCursor(*wxHOURGLASS_CURSOR); Ogre::TextureUnitState* tut = 0; // User has pressed ok, so load the texture Ogre::String fileName = wx2ogre(loadDialog.GetFilename()); Ogre::String path = wx2ogre(loadDialog.GetPath()); Ogre::String baseName; // should be the same as fileName Ogre::String extension; Ogre::String dir; Ogre::StringUtil::splitFullFilename(path, baseName, extension, dir); // Validate the extension Ogre::String types = "bmp,ico,jpg,jif,jpeg,jpe,jng,koa,iff,lbm,mng,pbm,pbm,pcd,pcx,pgm,pgm,png,ppm,ppm,ras,tga,targa,tif,tiff,wap,wbmp,wbm,psd,cut,xbm,xpm,gif,hdr,g3,sgi,exr,j2k,j2c,jp2,pfm,pct,pict,pic,bay,bmq,cr2,crw,cs1,dc2,dcr,dng,erf,fff,hdr,k25,kdc,mdc,mos,mrw,nef,orf,pef,pxn,raf,raw,rdc,sr2,srf,arw,3fr,cine,ia,kc2,mef,nrw,qtk,rw2,sti,drf,dsc,ptx,cap,iiq,rwz,dds"; Ogre::StringUtil::toLowerCase(extension); if (types.find(extension) == Ogre::String::npos) return; // Unsupported format // Load the resource Ogre::ResourceGroupManager::getSingletonPtr()->removeResourceLocation(dir, TEMP_TEXTURE_GROUP); Ogre::ResourceGroupManager::getSingletonPtr()->addResourceLocation(dir, "FileSystem", TEMP_TEXTURE_GROUP); Ogre::ResourceGroupManager::getSingletonPtr()->clearResourceGroup(TEMP_TEXTURE_GROUP); Ogre::ResourceGroupManager::getSingletonPtr()->initialiseResourceGroup(TEMP_TEXTURE_GROUP); Ogre::TextureManager::getSingleton().prepare(fileName, TEMP_TEXTURE_GROUP); Ogre::TextureManager::getSingleton().load(fileName, TEMP_TEXTURE_GROUP); Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(fileName, TEMP_TEXTURE_GROUP); if (!texture.isNull()) { // Set the texture name tut = forceCreateFirstTexture(fileName); // Return texture unit state if (tut) { tut->setName(fileName); mTxtTextureLoad->SetValue(loadDialog.GetFilename()); } // Compile the material wxString materialName = mMaterialListBox->GetStringSelection(); Ogre::String name = wx2ogre(materialName); Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(name); if (!material.isNull()) { material->compile(); } mResourceLocationTexture = ogre2wx(dir); } // Display image viewTexture(tut); // Clear the old texture if no TextureUnitState SetCursor(wxNullCursor); } }
//---------------------------------------------------------------------------- int CDotSceneSerializer::Import(Ogre::String importfile) { OgitorsRoot *ogRoot = OgitorsRoot::getSingletonPtr(); OgitorsSystem *mSystem = OgitorsSystem::getSingletonPtr(); if(importfile == "") { UTFStringVector extlist; extlist.push_back(OTR("DotScene File")); extlist.push_back("*.scene"); extlist.push_back(OTR("DotScene File")); extlist.push_back("*.xml"); importfile = mSystem->DisplayOpenDialog(OTR("Import DotScene File"),extlist); if(importfile == "") return SCF_CANCEL; } ogRoot->ClearProjectOptions(); Ogre::String filePath = OgitorsUtils::ExtractFilePath(importfile); Ogre::String fileName = OgitorsUtils::ExtractFileName(importfile); PROJECTOPTIONS *pOpt = ogRoot->GetProjectOptions(); pOpt->CreatedIn = ""; if(filePath.find(".") == 0) { filePath = OgitorsUtils::GetExePath() + filePath; filePath = OgitorsUtils::QualifyPath(filePath); } pOpt->ProjectDir = filePath; int typepos = fileName.find_last_of("."); pOpt->ProjectName = fileName; if(typepos != -1) pOpt->ProjectName.erase(typepos,pOpt->ProjectName.length() - typepos); TiXmlDocument docImport((filePath + fileName).c_str()); if(!docImport.LoadFile()) return SCF_ERRFILE; TiXmlElement* element = 0; element = docImport.FirstChildElement("scene"); if(!element) return SCF_ERRFILE; float version = Ogre::StringConverter::parseReal(ValidAttr(element->Attribute("formatVersion"))); if(version != 1.0f) { mSystem->DisplayMessageDialog(OTR("Only File Version 1.0 is supported!"),DLGTYPE_OK); return SCF_ERRFILE; } pOpt->SceneManagerName = "OctreeSceneManager"; pOpt->ResourceDirectories.push_back("/"); TiXmlElement* resLoc = element->FirstChildElement("resourceLocations"); if(resLoc) { resLoc = resLoc->FirstChildElement(); while(resLoc) { Ogre::String resType = ValidAttr(resLoc->Attribute("type")); Ogre::String resName = ValidAttr(resLoc->Attribute("name")); if(resType == "FileSystem") { OgitorsUtils::CleanPath(resName); if(resName[0] == '.') resName.erase(0, 1); pOpt->ResourceDirectories.push_back(resName); } resLoc = resLoc->NextSiblingElement(); } } TiXmlElement* configData = element->FirstChildElement("terrain"); if(configData) { pOpt->SceneManagerConfigFile = ValidAttr(configData->Attribute("dataFile")); } pOpt->CameraPositions[0] = Ogre::Vector3(0,10,0); pOpt->CameraOrientations[0] = Ogre::Quaternion::IDENTITY; pOpt->CameraPositions[1] = Ogre::Vector3(0,10,0); pOpt->CameraOrientations[1] = Ogre::Quaternion::IDENTITY; pOpt->CameraSaveCount = 1; OFS::OfsPtr& ofsFile = OgitorsRoot::getSingletonPtr()->GetProjectFile(); Ogre::String ofs_file_name = OgitorsUtils::QualifyPath(filePath + "/" + pOpt->ProjectName + ".ofs"); if(ofsFile.mount(ofs_file_name.c_str(), OFS::OFS_MOUNT_CREATE) != OFS::OFS_OK) return SCF_ERRFILE; OgitorsUtils::CopyDirOfs(filePath, "/"); ofsFile->deleteFile(fileName.c_str()); ofs_file_name = OgitorsUtils::ExtractFileName(ofs_file_name); ofsFile->deleteFile(ofs_file_name.c_str()); ogRoot->PrepareProjectResources(); OgitorsPropertyValueMap params; OgitorsPropertyValue propValue; propValue.propType = PROP_STRING; propValue.val = Ogre::Any(pOpt->SceneManagerConfigFile); params["configfile"] = propValue; Ogre::Vector2 vClipping(1,1000); TiXmlElement* environment = element->FirstChildElement("environment"); if(environment) { TiXmlElement* current = environment->FirstChildElement("clipping"); if(current) { vClipping.x = Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("near"),"1")); vClipping.y = Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("far"),"1000")); } current = environment->FirstChildElement("colourAmbient"); if(current) { params["ambient"] = parseColourValue(current); } current = environment->FirstChildElement("skyBox"); if(current) { propValue.propType = PROP_BOOL; propValue.val = Ogre::Any(Ogre::StringConverter::parseBool(ValidAttr(current->Attribute("enable"),"0"))); params["skybox::active"] = propValue; propValue.propType = PROP_STRING; propValue.val = Ogre::Any(Ogre::String(ValidAttr(current->Attribute("material")))); params["skybox::material"] = propValue; propValue.propType = PROP_REAL; propValue.val = Ogre::Any(Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("distance"),"0"))); params["skybox::distance"] = propValue; } current = environment->FirstChildElement("skyDome"); if(current) { propValue.propType = PROP_BOOL; propValue.val = Ogre::Any(Ogre::StringConverter::parseBool(ValidAttr(current->Attribute("enable"),"0"))); params["skydome::active"] = propValue; propValue.propType = PROP_STRING; propValue.val = Ogre::Any(Ogre::String(ValidAttr(current->Attribute("material")))); params["skydome::material"] = propValue; } current = environment->FirstChildElement("fog"); if(current) { propValue.propType = PROP_INT; Ogre::String fogmode = ValidAttr(current->Attribute("mode"),"None"); if(fogmode == "Linear" || fogmode == "linear" ) propValue.val = Ogre::Any((int)Ogre::FOG_LINEAR); else if(fogmode == "Exp" || fogmode == "exp" ) propValue.val = Ogre::Any((int)Ogre::FOG_EXP); else if(fogmode == "Exp2" || fogmode == "exp2" ) propValue.val = Ogre::Any((int)Ogre::FOG_EXP2); else propValue.val = Ogre::Any(Ogre::StringConverter::parseInt(fogmode)); params["fog::mode"] = propValue; Ogre::Real start = Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("linearStart"),"0")); Ogre::Real end = Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("linearEnd"),"1")); propValue.propType = PROP_REAL; propValue.val = Ogre::Any((Ogre::Real)(start * (vClipping.y - vClipping.x))); params["fog::start"] = propValue; propValue.val = Ogre::Any((Ogre::Real)(end * (vClipping.y - vClipping.x))); params["fog::end"] = propValue; propValue.val = Ogre::Any(Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("expDensity"),"0"))); params["fog::density"] = propValue; current = current->FirstChildElement("colourDiffuse"); if(current) { params["fogcolour"] = parseColourValue(current); } } } propValue.propType = PROP_STRING; propValue.val = Ogre::Any(Ogre::String("SceneManager1")); params["name"] = propValue; CSceneManagerEditor *mngred = static_cast<CSceneManagerEditor*>(ogRoot->CreateEditorObject(0, pOpt->SceneManagerName,params,false,false)); // read cameras placed outside nodes TiXmlElement* otherElems = element->FirstChildElement("camera"); Ogitors::CBaseEditor* cbeTemp; while(otherElems){ ReadCamera(otherElems, mngred, &cbeTemp); otherElems = otherElems->NextSiblingElement("camera"); } // read lights placed outside nodes otherElems = element->FirstChildElement("light"); while(otherElems){ ReadLight(otherElems, mngred, &cbeTemp); otherElems = otherElems->NextSiblingElement("light"); } element = element->FirstChildElement("nodes"); RecurseReadObjects(element, mngred); ogRoot->AfterLoadScene(); ogRoot->GetViewport()->getCameraEditor()->setClipDistance(vClipping); return SCF_OK; }
/** * Hovercraft Universe Application entry point. * * @author Kristof Overdulve & Olivier Berghmans & Pieter-Jan Pintens */ INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT) { // Create ZoidCom ZoidCom *zcom = new ZoidCom(process_zoidcom_log); if (!zcom || !zcom->Init()) { return 1; } bool console = false; bool server = false; unsigned int port = 2375; Ogre::String host = "localhost"; //parse all commandline parameters (seperated by spaces) Ogre::String commandline (strCmdLine); Ogre::vector<Ogre::String>::type result = Ogre::StringUtil::split(commandline, " "); for (Ogre::vector<Ogre::String>::type::iterator i = result.begin(); i != result.end(); i++ ) { if ((*i) == "--server") { server = true; } else if (Ogre::StringUtil::startsWith(*i,"--host=")) { //string of the form host:port Ogre::String connectionstring = (*i).substr(7); size_t pos = connectionstring.find(":"); if (pos == Ogre::String::npos) { host = connectionstring; } else { host = connectionstring.substr(0,pos); port = Ogre::StringConverter::parseInt(connectionstring.substr(pos+1)); } } else if ((*i) == "--console") { console = true; } } if (server) { HovUni::Console::createConsole("HovercraftUniverse Dedicated Server"); HovUni::HUDedicatedServer app("Server.ini"); try { app.init(); app.run(); } catch (Ogre::Exception& e) { MessageBox(NULL, e.getFullDescription().c_str(), "An Ogre exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); } catch (HovUni::Exception& e2) { MessageBox(NULL, e2.getMessage().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); } catch (std::exception& e) { MessageBox(NULL, e.what(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); } catch (...) { MessageBox(NULL, "Unknown fatal exception!", "An error has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); } HovUni::Console::destroyConsole(); } else { if (console) { HovUni::Console::createConsole("HovercraftUniverse Debug Console"); } HovUni::HUApplication app("HovercraftUniverse.ini"); try { app.init(); app.go(host,port); } catch (Ogre::Exception & e) { MessageBox(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); } catch (HovUni::Exception e2) { MessageBox(NULL, e2.getMessage().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); } catch (std::exception e) { MessageBox(NULL, e.what(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); } catch (...) { MessageBox(NULL, "Unknown fatal exception!", "An error has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); } if ( console ) HovUni::Console::destroyConsole(); } delete zcom; return 0; }
//----------------------------------------------------------------------------------------- bool CTerrainPageEditor::importHeightMap(Ogre::String filename, Ogre::Real fBias, Ogre::Real fScale) { if(!mHandle || !mLoaded->get()) return false; Ogre::StringUtil::trim(filename); if(filename.empty()) { UTFStringVector extlist; extlist.push_back(OTR("Raw 32bit Float File")); extlist.push_back("*.raw;*.ohm;*.f32;*.r32"); extlist.push_back(OTR("PNG Grayscale")); extlist.push_back("*.png"); filename = mSystem->DisplayOpenDialog(OTR("Import Heightmap"),extlist); if(filename == "") return false; } bool flipV = false; float *flipBV = 0; if(fBias == 0.0f && fScale == 0.0f) { Ogre::NameValuePairList params; params["check1"] = "true"; if(!mSystem->DisplayImportHeightMapDialog(params)) return false; fScale = Ogre::StringConverter::parseReal(params["input1"]); fBias = Ogre::StringConverter::parseReal(params["input2"]); flipV = Ogre::StringConverter::parseBool(params["inputCheckV"]); } float *mHeightData = mHandle->getHeightData(); Ogre::String namePart = OgitorsUtils::ExtractFileName(filename); namePart.erase(0, namePart.find(".")); OgitorsUndoManager::getSingletonPtr()->BeginCollection("Import Heightmap"); Ogre::Rect rect(0,0,mHandle->getSize(), mHandle->getSize()); _notifyModification(-1, rect); _notifyEndModification(); if(namePart == ".ohm" || namePart == ".raw" || namePart == ".f32" || namePart == ".r32") { size_t vertexNum = mHandle->getSize() * mHandle->getSize(); float *data = OGRE_ALLOC_T(float, vertexNum, Ogre::MEMCATEGORY_GEOMETRY); try { FILE *f = fopen(filename.c_str(),"rb"); fread(data,sizeof(float),vertexNum,f); fclose(f); } catch(...) { OGRE_FREE(data, Ogre::MEMCATEGORY_GEOMETRY); return false; } if(flipV) { flipBV = OGRE_ALLOC_T(float, mHandle->getSize(), Ogre::MEMCATEGORY_GEOMETRY); int linelength = mHandle->getSize() * sizeof(float); for(int fj = 0;fj < mHandle->getSize();fj++) { memcpy(flipBV, data + (fj * linelength), linelength); memcpy(data + (fj * linelength), data + ((mHandle->getSize() - fj - 1) * linelength), linelength); memcpy(data + ((mHandle->getSize() - fj - 1) * linelength), flipBV, linelength); } OGRE_FREE(flipBV, Ogre::MEMCATEGORY_GEOMETRY); } for(unsigned int px = 0;px < vertexNum;px++) mHeightData[px] = fBias + (data[px] * fScale); OGRE_FREE(data, Ogre::MEMCATEGORY_GEOMETRY); }
Ogre::String CBlinkingMaterialManager::getBlinkingMat(const Ogre::String &matName) { assert(matName.find(BLINKING_MATERIAL_EXTENSION) == Ogre::String::npos); return matName + BLINKING_MATERIAL_EXTENSION; }
Ogre::String CBlinkingMaterialManager::getNonBlinkingMat(const Ogre::String &matName) { assert(matName.find(BLINKING_MATERIAL_EXTENSION) != Ogre::String::npos); return matName.substr(0, matName.length() - BLINKING_MATERIAL_EXTENSION.length()); }
size_t CLASS::SearchCompare(Ogre::String searchString, CacheEntry *ce) { if (searchString.find(":") == Ogre::String::npos) { // normal search // the name Ogre::String dname_lower = ce->dname; Ogre::StringUtil::toLowerCase(dname_lower); if (dname_lower.find(searchString) != Ogre::String::npos) return dname_lower.find(searchString); // the filename Ogre::String fname_lower = ce->fname; Ogre::StringUtil::toLowerCase(fname_lower); if (fname_lower.find(searchString) != Ogre::String::npos) return 100 + fname_lower.find(searchString); // the description Ogre::String desc = ce->description; Ogre::StringUtil::toLowerCase(desc); if (desc.find(searchString) != Ogre::String::npos) return 200 + desc.find(searchString); // the authors if (!ce->authors.empty()) { std::vector<AuthorInfo>::const_iterator it; for (it = ce->authors.begin(); it != ce->authors.end(); it++) { // author name Ogre::String aname = it->name; Ogre::StringUtil::toLowerCase(aname); if (aname.find(searchString) != Ogre::String::npos) return 300 + aname.find(searchString); // author email Ogre::String aemail = it->email; Ogre::StringUtil::toLowerCase(aemail); if (aemail.find(searchString) != Ogre::String::npos) return 400 + aemail.find(searchString); } } return Ogre::String::npos; } else { Ogre::StringVector v = Ogre::StringUtil::split(searchString, ":"); if (v.size() < 2) return Ogre::String::npos; //invalid syntax if (v[0] == "hash") { Ogre::String hash = ce->hash; Ogre::StringUtil::toLowerCase(hash); return hash.find(v[1]); } else if (v[0] == "guid") { Ogre::String guid = ce->guid; Ogre::StringUtil::toLowerCase(guid); return guid.find(v[1]); } else if (v[0] == "author") { // the authors if (!ce->authors.empty()) { std::vector<AuthorInfo>::const_iterator it; for (it = ce->authors.begin(); it != ce->authors.end(); it++) { // author name Ogre::String aname = it->name; Ogre::StringUtil::toLowerCase(aname); if (aname.find(v[1]) != Ogre::String::npos) return aname.find(v[1]); // author email Ogre::String aemail = it->email; Ogre::StringUtil::toLowerCase(aemail); if (aemail.find(v[1]) != Ogre::String::npos) return aemail.find(v[1]); } } return Ogre::String::npos; } else if (v[0] == "wheels") { Ogre::String wheelsStr = TOUTFSTRING(ce->wheelcount) + "x" + TOUTFSTRING(ce->propwheelcount); return wheelsStr.find(v[1]); } else if (v[0] == "file") { Ogre::String fn = ce->fname; Ogre::StringUtil::toLowerCase(fn); return fn.find(v[1]); } } return Ogre::String::npos; }
bool OgreParticleAsset::DeserializeFromData(const u8 *data, size_t numBytes, bool allowAsynchronous) { RemoveTemplates(); references.clear(); if (!data) { LogError("Null source asset data pointer"); return false; } if (numBytes == 0) { LogError("Zero sized particle system asset"); return false; } // Detected template names StringVector new_templates; std::vector<u8> tempData(data, data + numBytes); #include "DisableMemoryLeakCheck.h" Ogre::DataStreamPtr dataPtr = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&tempData[0], numBytes)); #include "EnableMemoryLeakCheck.h" try { int brace_level = 0; bool skip_until_next = false; int skip_brace_level = 0; // Parsed/modified script std::ostringstream output; while(!dataPtr->eof()) { Ogre::String line = dataPtr->getLine(); // Skip empty lines & comments if ((line.length()) && (line.substr(0, 2) != "//")) { // Split line to components std::vector<Ogre::String> line_vec; #if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6 line_vec = Ogre::StringUtil::split(line, "\t "); #else Ogre::vector<Ogre::String>::type vec = Ogre::StringUtil::split(line,"\t "); int size = vec.size(); line_vec.resize(size); for(int i = 0; i < size; ++i) line_vec[i] = vec[i]; #endif // Process opening/closing braces if (!ProcessBraces(line, brace_level)) { // If not a brace and on level 0, it should be a new particlesystem; replace name with resource ID + ordinal if (brace_level == 0) { line = AssetAPI::SanitateAssetRef(this->Name() + "_" + QString::number(new_templates.size())).toStdString(); new_templates.push_back(line); // New script compilers need this line = "particle_system " + line; } else { // Check for ColourImage, which is a risky affector and may easily crash if image can't be loaded if (line_vec[0] == "affector") { if (line_vec.size() >= 2) { if (line_vec[1] == "ColourImage") { skip_until_next = true; skip_brace_level = brace_level; } } } // Check for material definition else if (line_vec[0] == "material") { if (line_vec.size() >= 2) { std::string mat_name = line_vec[1]; AssetReference assetRef(assetAPI->ResolveAssetRef(Name(), mat_name.c_str())); references.push_back(assetRef); line = "material " + AssetAPI::SanitateAssetRef(assetRef.ref).toStdString(); } } } // Write line to the copy if (!skip_until_next) { // Maintain the intendation. int numIntendations = brace_level; if (line.find("{") != std::string::npos) --numIntendations; for(int i = 0; i < numIntendations; ++i) output << " "; output << line << std::endl; } else LogDebug("Skipping risky particle effect line: " + line); } else { // Write line to the copy if (!skip_until_next) { // Maintain the intendation. int numIntendations = brace_level; if (line.find("{") != std::string::npos) --numIntendations; for(int i = 0; i < numIntendations; ++i) output << " "; output << line << std::endl; } else LogDebug("Skipping risky particle effect line: " + line); if (brace_level <= skip_brace_level) skip_until_next = false; } } } originalData = output.str(); #include "DisableMemoryLeakCheck.h" Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&originalData[0], originalData.size())); #include "EnableMemoryLeakCheck.h" Ogre::ParticleSystemManager::getSingleton().parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); } catch(Ogre::Exception& e) { LogWarning(e.what()); LogWarning("Failed to parse Ogre particle script " + Name() + "."); } // Check which templates actually succeeded for(uint i = 0; i < new_templates.size(); ++i) { if (Ogre::ParticleSystemManager::getSingleton().getTemplate(new_templates[i])) { templates.push_back(new_templates[i]); LogDebug("Ogre particle system template " + new_templates[i] + " created"); } } // Give only the name of the first template internalName = (AssetAPI::SanitateAssetRef(Name()) + "_0").toStdString(); // Theoretical success if at least one template was created. bool success = (GetNumTemplates() > 0); if (success) assetAPI->AssetLoadCompleted(Name()); return success; }