示例#1
0
/** 解析特效元素 */
void VEffectManager::_parseElement(const VString &type, Ogre::DataStreamPtr &stream, VEffect *effect)
{
	VEffectElement *element = createElement(type);
	assert(element != VNULL);

	effect->addElement(element);

	Ogre::String line;

	while (!stream->eof())
	{
		line = stream->getLine();
		++mParsingLineNumber;

		if (!(line.empty() || line.substr(0, 2) == "//"))
		{
			// 跳过空行和注释行
			if (line == "}")
			{
				break;
			}
			else
			{
				_parseElementAttrib(line, element);
			}
		}
	}
}
示例#2
0
/** 解析animation sound */
void VEffectManager::_parseAnimSound(Ogre::DataStreamPtr &stream, VSkill *skill)
{
	assert(skill != VNULL);

	VAnimationSound *sound = skill->addAnimationSound();
	assert(sound != VNULL);

	Ogre::String line;

	while (!stream->eof())
	{
		line = stream->getLine();
		++mParsingLineNumber;

		if (!(line.empty() || line.substr(0, 2) == "//"))
		{
			if (line == "}")
			{
				break;
			}
			else
			{
				_parseAnimSoundAttrib(line, sound);
			}
		}
	}
}
示例#3
0
void RoR::SkinManager::parseScript(Ogre::DataStreamPtr& stream, const Ogre::String& groupName)
{
    SkinDef* skin_def = nullptr;
    bool     skin_is_new = true;
    try
    {
        while(!stream->eof())
        {
            std::string line = RoR::Utils::SanitizeUtf8String(stream->getLine());

            // Ignore blanks & comments
            if (!line.length() || line.substr(0, 2) == "//")
            {
                continue;
            }

            if (!skin_def)
            {
                // No current skin -- So first valid data should be skin name
                Ogre::StringUtil::trim(line);
                auto search = m_skins.find(line);
                if (search != m_skins.end())
                {
                    skin_def = search->second;
                    skin_is_new = false;
                }
                else
                {
                    skin_def = new SkinDef;
                    skin_def->name = line;
                    skin_is_new = true;
                }
                stream->skipLine("{");
            }
            else
            {
                // Already in skin
                if (line == "}")
                {
                    if (skin_is_new)
                        m_skins.insert(std::make_pair(skin_def->name, skin_def));
                    skin_def = nullptr;// Finished
                }
                else
                {
                    this->ParseSkinAttribute(line, skin_def);
                }
            }
        }
    }
    catch (Ogre::ItemIdentityException)
    {
        // this catches duplicates -> to be ignored
        // this happens since we load the full skin data off the cache, so we don't need
        // to re-add it to the SkinManager
        return;
    }
}
示例#4
0
/** 跳到下一个左大括号 */
void VEffectManager::_skipToNextOpenBrace(Ogre::DataStreamPtr &stream)
{
	Ogre::String line = "";

	while (!stream->eof() && line != "{")
	{
		line = stream->getLine();
		++mParsingLineNumber;
	}
}
void AudioScriptLoader::parseScript(Ogre::DataStreamPtr& dataStream, const Ogre::String& groupName)
{
	Ogre::String line;
	bool nextIsOpenBrace = false;

	mScriptContext.mSection = ASS_NONE;
	mScriptContext.mSection= ASS_NONE;
	mScriptContext.mSound.setNull();
	mScriptContext.mLineNo = 0;
	mScriptContext.mFileName=dataStream->getName();
	mScriptContext.mGroupName=groupName;

	Logger::getInstance()->log("About to start parsing sound script "+dataStream->getName());

	while(!dataStream->eof())
	{
		line = dataStream->getLine();
		mScriptContext.mLineNo++;

		// DEBUG LINE
		//Logger::getInstance()->log("About to attempt line(#" +
		//	Ogre::StringConverter::toString(mScriptContext.mLineNo) + "): " + line);

		// Ignore comments & blanks
		if (!(line.length() == 0 || line.substr(0,2) == "//"))
		{
			if (nextIsOpenBrace)
			{
				// NB, parser will have changed context already
				if (line != "{")
				{
					logParseError("Expecting '{' but got " +
						line + " instead.", mScriptContext);
				}
				nextIsOpenBrace = false;
			}
			else
			{
				nextIsOpenBrace = parseLine(line);
			}

		}
	}

	// Check all braces were closed
	if (mScriptContext.mSection != ASS_NONE)
	{
		logParseError("Unexpected end of file.", mScriptContext);
	}

	// Make sure we invalidate our context shared pointer (don't wanna hold on)
	mScriptContext.mSound.setNull();
}
示例#6
0
void UnloadMaterials(const std::string& filename)
{
    if (filename.empty())
    {
        Ogre::LogManager::getSingleton().logMessage("Filename is empty.");
        return;
    }
 
    Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(filename);
    if(!stream.isNull())
    {
        try
        {
            while(!stream->eof())
            {
                std::string line = stream->getLine();
                StringUtil::trim(line);
 
                ///
                /// UNLOAD MATERIALS
                ///
                if (StringUtil::startsWith(line, "material"))
                {
                    Ogre::vector<Ogre::String>::type vec = StringUtil::split(line," \t:");
                    bool skipFirst = true;
                    for (Ogre::vector<Ogre::String>::type::iterator it = vec.begin(); it < vec.end(); ++it)
                    {
                        if (skipFirst)
                        {
                            skipFirst = false;
                            continue;
                        }
                        std::string match = (*it);
                        StringUtil::trim(match);
                        if (!match.empty())
                        {
                            UnloadResource(Ogre::MaterialManager::getSingletonPtr(), match);
                            break;
                        }
                    }
                }
            }
        }
        catch (Ogre::Exception &e)
        {
            StringUtil::StrStreamType msg;
            msg << "Exception: FILE: " << __FILE__ << " LINE: " << __LINE__ << " DESC: " << e.getFullDescription() << std::endl;
            Ogre::LogManager::getSingleton().logMessage(msg.str());
        }
    }
    stream->close();
}
示例#7
0
void RoR::SkidmarkConfig::LoadDefaultSkidmarkDefs()
{
    LOG("[RoR] Loading skidmarks.cfg...");
    Ogre::String group = "";
    try
    {
        group = Ogre::ResourceGroupManager::getSingleton().findGroupContainingResource("skidmarks.cfg");
        if (group.empty())
        {
            LOG("[RoR] Failed to load skidmarks.cfg (file not found)");
            return;
        }

        Ogre::DataStreamPtr ds = Ogre::ResourceGroupManager::getSingleton().openResource("skidmarks.cfg", group);
        Ogre::String line = "";
        Ogre::String currentModel = "";

        while (!ds->eof())
        {
            line = RoR::Utils::SanitizeUtf8String(ds->getLine());
            Ogre::StringUtil::trim(line);

            if (line.empty() || line[0] == ';')
                continue;

            Ogre::StringVector args = Ogre::StringUtil::split(line, ",");

            if (args.size() == 1)
            {
                currentModel = line;
                continue;
            }

            // process the line if we got a model
            if (!currentModel.empty())
                this->ProcessSkidmarkConfLine(args, currentModel);
        }
    }
    catch (...)
    {
        LOG("[RoR] Error loading skidmarks.cfg (unknown error)");
        m_models.clear(); // Delete anything we might have loaded
        return;
    }
    LOG("[RoR] skidmarks.cfg loaded OK");
}
	void LanguageManager::_loadLanguage(const Ogre::DataStreamPtr& stream, bool _user)
	{
		std::string read;
		while (false == stream->eof()) {
			read = stream->getLine (false);
			if (read.empty()) continue;

			size_t pos = read.find_first_of(" \t");
			if (_user) {
				if (pos == std::string::npos) mUserMapLanguage[read] = "";
				else mUserMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
			}
			else {
				if (pos == std::string::npos) mMapLanguage[read] = "";
				else mMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
			}
		};
	}
示例#9
0
void ReloadMaterial(const std::string& materialName, const std::string& groupName, const std::string& filename, bool parseMaterialScript)
{
    if (materialName.empty())
    {
        Ogre::LogManager::getSingleton().logMessage("Material name is empty.");
        return;
    }
 
    if (groupName.empty())
    {
        Ogre::LogManager::getSingleton().logMessage("Group name is empty.");
        return;
    }
 
    if (filename.empty())
    {
        Ogre::LogManager::getSingleton().logMessage("Filename is empty.");
        return;
    }
 
    UnloadMaterials(filename);
    UnloadVertexPrograms(filename);
    UnloadFragmentPrograms(filename);
 
    if (parseMaterialScript)
    {
        Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(filename);
        if(!stream.isNull())
        {
            try
            {
                Ogre::MaterialManager::getSingleton().parseScript(stream, groupName);
                Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(materialName);
                if (!materialPtr.isNull())
                {
                    materialPtr->compile();
                    materialPtr->load();
                }
            }
            catch (Ogre::Exception &e)
            {
                StringUtil::StrStreamType msg;
                msg << "Exception: FILE: " << __FILE__ << " LINE: " << __LINE__ << " DESC: " << e.getFullDescription() << std::endl;
                Ogre::LogManager::getSingleton().logMessage(msg.str());
            }
        }
        stream->close();
 
        ///
        /// RELOAD MATERIAL SCRIPT CONTENTS
        ///
        stream = Ogre::ResourceGroupManager::getSingleton().openResource(filename);
        if(!stream.isNull())
        {
            try
            {
                ///
                /// RELOAD ALL MATERIAL CONTENTS IN FILE
                ///
                while(!stream->eof())
                {
                    std::string line = stream->getLine();
                    StringUtil::trim(line);
                    ///
                    /// RELOAD MATERIALS
                    ///
                    if (StringUtil::startsWith(line, "material"))
                    {
                        Ogre::vector<Ogre::String>::type vec = StringUtil::split(line," \t:");
                        bool skipFirst = true;
                        for (Ogre::vector<Ogre::String>::type::iterator it = vec.begin(); it < vec.end(); ++it)
                        {
                            if (skipFirst)
                            {
                                skipFirst = false;
                                continue;
                            }
                            std::string match = (*it);
                            StringUtil::trim(match);
                            if (!match.empty())
                            {
                                LoadResource(Ogre::MaterialManager::getSingletonPtr(), match, groupName);
                                break;
                            }
                        }
                    }
                    ///
                    /// RELOAD VERTEX PROGRAMS
                    ///
                    if (StringUtil::startsWith(line, "vertex_program") && !StringUtil::startsWith(line, "vertex_program_ref"))
                    {
                        Ogre::vector<Ogre::String>::type vec = StringUtil::split(line," \t");
                        bool skipFirst = true;
                        for (Ogre::vector<Ogre::String>::type::iterator it = vec.begin(); it < vec.end(); ++it)
                        {
                            if (skipFirst)
                            {
                                skipFirst = false;
                                continue;
                            }
                            std::string match = (*it);
                            StringUtil::trim(match);
                            if (!match.empty())
                            {
                                LoadResource(Ogre::HighLevelGpuProgramManager::getSingletonPtr(), match, groupName);
                                break;
                            }
                        }
                    }
                    ///
                    /// RELOAD FRAGMENT PROGRAMS
                    ///
                    if (StringUtil::startsWith(line, "fragment_program") && !StringUtil::startsWith(line, "fragment_program_ref"))
                    {
                        Ogre::vector<Ogre::String>::type vec = StringUtil::split(line," \t");
                        bool skipFirst = true;
                        for (Ogre::vector<Ogre::String>::type::iterator it = vec.begin(); it < vec.end(); ++it)
                        {
                            if (skipFirst)
                            {
                                skipFirst = false;
                                continue;
                            }
                            std::string match = (*it);
                            StringUtil::trim(match);
                            if (!match.empty())
                            {
                                LoadResource(Ogre::HighLevelGpuProgramManager::getSingletonPtr(), match, groupName);
                                break;
                            }
                        }
                    }
                }
            }
            catch (Ogre::Exception &e)
            {
                StringUtil::StrStreamType msg;
                msg << "Exception: FILE: " << __FILE__ << " LINE: " << __LINE__ << " DESC: " << e.getFullDescription() << std::endl;
                Ogre::LogManager::getSingleton().logMessage(msg.str());
            }
        }
        stream->close();
 
        try
        {
            // Do a render test if it fails, leave materials unloaded
            Ogre::Root::getSingleton().renderOneFrame();
            return;
        }
        catch (Ogre::Exception &e)
        {
            UnloadVertexPrograms(filename);
 
            StringUtil::StrStreamType msg;
            msg << "Render test failed. Unloading vertex programs." << std::endl;
            msg << "Exception: FILE: " << __FILE__ << " LINE: " << __LINE__ << " DESC: " << e.getFullDescription() << std::endl;
            Ogre::LogManager::getSingleton().logMessage(msg.str());
        }
 
        try
        {
            // Do a render test if it fails, leave materials unloaded
            Ogre::Root::getSingleton().renderOneFrame();
        }
        catch (Ogre::Exception &e)
        {
            // Don't load the script this time
            ReloadMaterial(materialName, groupName, filename, false);
 
            StringUtil::StrStreamType msg;
            msg << "Render test failed. Unloading materials." << std::endl;
            msg << "Exception: FILE: " << __FILE__ << " LINE: " << __LINE__ << " DESC: " << e.getFullDescription() << std::endl;
            Ogre::LogManager::getSingleton().logMessage(msg.str());
        }
    }
}
示例#10
0
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;
}
示例#11
0
		bool xmlDocument::open(const Ogre::DataStreamPtr& stream)
		{
			clear();

			mLastErrorFile = stream->getName();
			// это текущая строка для разбора
			std::string line;
			// это строка из файла
			std::string read;
			// текущий узел для разбора
			xmlNodePtr currentNode = 0;

			while (false == stream->eof()) {
				// берем новую строку
				read = stream->getLine (false);
				mLine ++;
				mCol = 0; // потом проверить на многострочных тэгах

				if (read.empty()) continue;

				// текущая строка для разбора и то что еще прочитали
				line += read;

				// крутимся пока в строке есть теги
				while (true) {

					// сначала ищем по угловым скобкам
					size_t start = find(line, '<');
					if (start == line.npos) break;

					size_t end = find(line, '>', start+1);
					if (end == line.npos) break;

					// проверяем на наличее тела
					size_t body = line.find_first_not_of(" \t<");
					if (body < start) {

						std::string body_str = line.substr(0, start);
						// текущий символ
						mCol = body_str.find_first_not_of(" \t");
						utility::trim(body_str);

						if (currentNode != 0) 	currentNode->addBody(body_str);

					}

					// вырезаем наш тэг и парсим
					if (false == parseTag(currentNode, line.substr(start+1, end-start-1))) {
						// ошибка установится внутри
						return false;
					}

					// и обрезаем текущую строку разбора
					line = line.substr(end+1);

				}; // while (true)

			}; // while (!stream.eof())

			if (currentNode) {
				mLastError = xml::errors::XML_ERROR_NON_CLOSE_ALL_TAGS;
				return false;
			}

			return true;
		}
示例#12
0
/** 解析*.skill文件 */
void VEffectManager::_parseSkillFile(Ogre::DataStreamPtr &stream)
{
	Ogre::String line;
	VSkill *skill = VNULL;

	Ogre::StringVector vecparams;

	while (!stream->eof())
	{
		line = stream->getLine();
		++mParsingLineNumber;

		if (!(line.empty() || line.substr(0, 2) == "//"))
		{
			if (VNULL == skill)
			{
				vecparams = Ogre::StringUtil::split(line, "\t ");

				if (vecparams[0] != "skill" || vecparams.size() != 2)
				{
					_logErrorInfo("Wrong skill name line", line, "EffectManager::parseSkillFile");

					continue;
				}

				// 创建了一个空的effect
				skill = _createSkillTemplate(vecparams[1]);

				_skipToNextOpenBrace(stream);
			}
			else
			{
				if (line == "}")
				{
					// 解析一个完整的技能
					skill = VNULL;
				}
				else if (line == "AnimEffect")
				{
					_skipToNextOpenBrace(stream);
					_parseAnimEffectInfo(stream, skill);
				}
				else if (line == "Ribbon")
				{
					_skipToNextOpenBrace(stream);
					_parseAnimRibbon(stream, skill);
				}
				else if (line == "SceneLight")
				{
					_skipToNextOpenBrace(stream);
					_parseAnimSceneLight(stream, skill);
				}
				else if (line == "Sound")
				{
					_skipToNextOpenBrace(stream);
					_parseAnimSound(stream, skill);
				}
				else
				{
					// 解析技能属性
					_parseSkillAttrib(line, skill);
				}
			}
		}
	}
}
示例#13
0
/** 解析*.effect文件 */
void VEffectManager::_parseEffectFile(Ogre::DataStreamPtr &stream)
{
	Ogre::String line;
	VEffect *effect = VNULL;
	Ogre::StringVector vecparams;

	while (!stream->eof())
	{
		line = stream->getLine();
		++mParsingLineNumber;

		if (!(line.empty() || line.substr(0, 2) == "//"))
		{
			// 只要不是空行或者注释
			if (VNULL == effect)
			{
				// 一个新特效
				vecparams = Ogre::StringUtil::split(line, "\t ");

				if (vecparams[0] != "effect" || vecparams.size() != 2)
				{
					_logErrorInfo("Bad effect system name line", line, "VEffectManager::_parseEffectFile");
					return;
				}

				// 创建空的effect
				effect = _createEffectTemplate(vecparams[1]);

				_skipToNextOpenBrace(stream);
			}
			else
			{
				if (line == "}")
				{
					// 完整的解析一个特效
					effect = VNULL;
				}
				else if (line.substr(0, 7) == "element")
				{
					// 一个新的特效元素
					vecparams = Ogre::StringUtil::split(line, "\t ");
					
					if (vecparams.size() < 2)
					{
						_logErrorInfo("Bad effect system element line", line, "VEffectManager::_parseEffectFile");
						return;
					}

					_skipToNextOpenBrace(stream);

					// 解析特效元素的参数
					_parseElement(vecparams[1], stream, effect);
				}
				else
				{
					// 解析特效自己的参数
					_parseEffectAttrib(line, effect);
				}
			}
		}
	}
}
bool OgreParticleAsset::DeserializeFromData(const u8 *data_, size_t numBytes)
{
    RemoveTemplates();
    references_.clear();

    if (!data_)
    {
        OgreRenderer::OgreRenderingModule::LogError("Null source asset data pointer");
        return false;
    }
    if (numBytes == 0)
    {
        OgreRenderer::OgreRenderingModule::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 data = 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 (!data->eof())
        {
            Ogre::String line = data->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

                // Check for vector parameters to be modified, so that particle scripts can be authored in typical Ogre coord system
                ModifyVectorParameter(line, line_vec);

                // 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 = SanitateAssetIdForOgre(this->Name().toStdString()) + "_" + boost::lexical_cast<std::string>(new_templates.size());
                        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)
                            {
                                // Tundra: we only support material refs in particle scripts
                                std::string mat_name = line_vec[1];
                                ///\todo The design of whether the LookupAssetRefToStorage should occur here, or internal to Asset API needs to be revisited.
                                references_.push_back(AssetReference(assetAPI->LookupAssetRefToStorage(mat_name.c_str())));
                                line = "material " + SanitateAssetIdForOgre(mat_name);
                            }
                        }
                    }
                    // Write line to the copy
                    if (!skip_until_next)
                    {
                        output << line << std::endl;
                    }
                    else
                        OgreRenderer::OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
                }
                else
                {
                    // Write line to the copy
                    if (!skip_until_next)
                    {
                        output << line << std::endl;
                    }
                    else
                        OgreRenderer::OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);

                    if (brace_level <= skip_brace_level)
                        skip_until_next = false;
                }
            }
        }

        std::string output_str = output.str();
#include "DisableMemoryLeakCheck.h"
        Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&output_str[0], output_str.size()));
#include "EnableMemoryLeakCheck.h"
        Ogre::ParticleSystemManager::getSingleton().parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    }
    catch (Ogre::Exception& e)
    {
        OgreRenderer::OgreRenderingModule::LogWarning(e.what());
        OgreRenderer::OgreRenderingModule::LogWarning("Failed to parse Ogre particle script " + Name().toStdString() + ".");
    }

    // 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]);
            OgreRenderer::OgreRenderingModule::LogDebug("Ogre particle system template " + new_templates[i] + " created");
        }
    }

    // Give only the name of the first template
    internal_name_ = SanitateAssetIdForOgre(Name().toStdString()) + "_0";

    // Theoretical success if at least one template was created
    return GetNumTemplates() > 0;
}
示例#15
0
bool Main::LoadRigDefFile(MyGUI::UString const & directory, MyGUI::UString const & filename)
{
	/* CLOSE PREVIOUS RIG */

	if (m_rig != nullptr)
	{
		this->CommandCloseCurrentRig();
	}

	/* LOAD */

	Ogre::DataStreamPtr stream = Ogre::DataStreamPtr();
	Ogre::String resource_group_name("RigEditor_CurrentProject");

	try
	{
		Ogre::ResourceGroupManager::getSingleton().addResourceLocation(directory, "FileSystem", resource_group_name);
		stream = Ogre::ResourceGroupManager::getSingleton().openResource(filename, resource_group_name);
	} 
	catch (Ogre::Exception& e)
	{
		// TODO: Report error to user

		LOG("RigEditor: Failed to retrieve rig file" + filename + ", Ogre::Exception was thrown with message: " + e.what());
		return false;
	}

	/* PARSE */

	LOG("RigEditor: Parsing rig file: " + filename);

	RigDef::Parser parser;
	parser.Prepare();
	while(! stream->eof())
	{
		parser.ParseLine(stream->getLine());
	}
	parser.Finalize();

	RigEditor_LogParserMessages(parser);

	/* VALIDATE */

	LOG("RigEditor: Validating vehicle: " + parser.GetFile()->name);

	RigDef::Validator validator;
	validator.Setup(parser.GetFile());
	bool valid = validator.Validate();

	RigEditor_LogValidatorMessages(validator);

	if (! valid)
	{
		// TODO: Report error to user

		LOG("RigEditor: Validating failed!");
		return false;
	}

	/* BUILD RIG MESH */

	m_rig = new RigEditor::Rig(m_config);
	RigEditor::RigBuildingReport rig_build_report;
	Ogre::SceneNode* parent_scene_node = m_scene_manager->getRootSceneNode();
	m_rig->Build(parser.GetFile(), this, parent_scene_node, &rig_build_report);

	/* SHOW MESH */
    this->OnNewRigCreatedOrLoaded(parent_scene_node);

	LOG(Ogre::String("RigEditor: Finished loading rig, report:\n") + rig_build_report.ToString());

	return true;
}
示例#16
0
bool OgreMaterialResource::SetData(Foundation::AssetPtr source)
{
    // Remove old material if any
    RemoveMaterial();
    references_.clear();
    original_textures_.clear();

    Ogre::MaterialManager& matmgr = Ogre::MaterialManager::getSingleton();

    OgreRenderingModule::LogDebug("Parsing material " + source->GetId());

    if (!source)
    {
        OgreRenderingModule::LogError("Null source asset data pointer");
        return false;
    }
    if (!source->GetSize())
    {
        OgreRenderingModule::LogError("Zero sized material asset");
        return false;
    }

    Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<u8 *>(source->GetData()), source->GetSize()));

    static int tempname_count = 0;
    tempname_count++;
    std::string tempname = "TempMat" + ToString<int>(tempname_count);

    try
    {
        int num_materials = 0;
        int brace_level = 0;
        bool skip_until_next = false;
        int skip_brace_level = 0;
        // Parsed/modified material script
        std::ostringstream output;


        while (!data->eof())
        {
            Ogre::String line = data->getLine();

            // Skip empty lines & comments
            if ((line.length()) && (line.substr(0, 2) != "//"))
            {
                // Process opening/closing braces
                if (!ResourceHandler::ProcessBraces(line, brace_level))
                {
                    // If not a brace and on level 0, it should be a new material; replace name
                    if ((brace_level == 0) && (line.substr(0, 8) == "material"))
                    {
                        if (num_materials == 0)
                        {
                            line = "material " + tempname;
                            ++num_materials;
                        }
                        else
                        {
                            OgreRenderingModule::LogWarning("More than one material defined in material asset " + source->GetId() + " - only first one supported");
                            break;
                        }
                    }
                    else
                    {
                        // Check for textures
                        if ((line.substr(0, 8) == "texture ") && (line.length() > 8))
                        {
                            std::string tex_name = line.substr(8);
                            // Note: we assume all texture references are asset based. ResourceHandler checks later whether this is true,
                            // before requesting the reference
                            references_.push_back(Foundation::ResourceReference(tex_name, OgreTextureResource::GetTypeStatic()));
                            original_textures_.push_back(tex_name);
                            // Replace any / with \ in the material, then change the texture names back later, so that Ogre does not go nuts
                            ReplaceCharInplace(line, '/', '\\');
                            ReplaceCharInplace(line, ':', '@');
                        }
                    }

                    // Write line to the modified copy
                    if (!skip_until_next)
                        output << line << std::endl;
                }
                else
                {
                    // Write line to the modified copy
                    if (!skip_until_next)
                        output << line << std::endl;
                    if (brace_level <= skip_brace_level)
                        skip_until_next = false;
                }
            }
        }

        std::string output_str = output.str();
        Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream((u8 *)(&output_str[0]), output_str.size()));

        matmgr.parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
        Ogre::MaterialPtr tempmat;
        tempmat = matmgr.getByName(tempname);
        if (tempmat.isNull())
        {
            OgreRenderingModule::LogWarning(std::string("Failed to create an Ogre material from material asset ") +
                                            source->GetId());

            return false;
        }
        if(!tempmat->getNumTechniques())
        {
            OgreRenderingModule::LogWarning("Failed to create an Ogre material from material asset "  +
                                            source->GetId());
            return false;
        }

        ogre_material_ = tempmat->clone(id_);
        tempmat.setNull();
        matmgr.remove(tempname);
        if (ogre_material_.isNull())
        {
            OgreRenderingModule::LogWarning("Failed to create an Ogre material from material asset "  +
                                            source->GetId());
            return false;
        }

        // Now go through all the texturenames and restore \ back to / and @ to :
        Ogre::Material::TechniqueIterator iter = ogre_material_->getTechniqueIterator();
        while (iter.hasMoreElements())
        {
            Ogre::Technique *tech = iter.getNext();
            Ogre::Technique::PassIterator passIter = tech->getPassIterator();
            while (passIter.hasMoreElements())
            {
                Ogre::Pass *pass = passIter.getNext();
                Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
                while (texIter.hasMoreElements())
                {
                    Ogre::TextureUnitState *texUnit = texIter.getNext();
                    std::string texname = texUnit->getTextureName();
                    if (texname.find('\\') != std::string::npos)
                    {
                        ReplaceCharInplace(texname, '\\', '/');
                        ReplaceCharInplace(texname, '@', ':');
                        texUnit->setTextureName(texname);
                    }
                }
            }
        }

        //workaround: if receives shadows, check the amount of shadowmaps. If only 1 specified, add 2 more to support 3 shadowmaps
        if(ogre_material_->getReceiveShadows() && shadowquality_ == Shadows_High && ogre_material_->getNumTechniques() > 0)
        {
            Ogre::Technique *tech = ogre_material_->getTechnique(0);
            if(tech)
            {
                Ogre::Technique::PassIterator passiterator = tech->getPassIterator();
                while(passiterator.hasMoreElements())
                {
                    Ogre::Pass* pass = passiterator.getNext();
                    Ogre::Pass::TextureUnitStateIterator texiterator = pass->getTextureUnitStateIterator();
                    int shadowmaps = 0;
                    while(texiterator.hasMoreElements())
                    {
                        Ogre::TextureUnitState* state = texiterator.getNext();
                        if(state->getContentType() == Ogre::TextureUnitState::CONTENT_SHADOW)
                        {
                            shadowmaps++;
                        }
                    }
                    if(shadowmaps>0 && shadowmaps<3)
                    {
                        Ogre::TextureUnitState* sm2 = pass->createTextureUnitState();
                        sm2->setContentType(Ogre::TextureUnitState::CONTENT_SHADOW);

                        Ogre::TextureUnitState* sm3 = pass->createTextureUnitState();
                        sm3->setContentType(Ogre::TextureUnitState::CONTENT_SHADOW);
                    }
                }
            }

        }

    } catch (Ogre::Exception &e)
    {
        OgreRenderingModule::LogWarning(e.what());
        OgreRenderingModule::LogWarning("Failed to parse Ogre material " + source->GetId() + ".");
        try
        {
            if (!matmgr.getByName(tempname).isNull())
                Ogre::MaterialManager::getSingleton().remove(tempname);
        }
        catch (...) {}

        return false;
    }
    return true;
}