예제 #1
0
파일: O_String.cpp 프로젝트: psxcode/demo4
	//-----------------------------------------------------------------------
	void StringUtil::splitBaseFilename(const Ogre::String& fullName, 
		Ogre::String& outBasename, Ogre::String& outExtention)
	{
		size_t i = fullName.find_last_of(".");
		if (i == Ogre::String::npos)
		{
			outExtention.clear();
			outBasename = fullName;
		}
		else
		{
			outExtention = fullName.substr(i+1);
			outBasename = fullName.substr(0, i);
		}
	}
	/// __DATE__ sieht ca. so aus : Nov 08 2005
	long parseDate(char* date)
	{   
		Ogre::String dateStr = Ogre::String(date);
		Ogre::String monthStr = dateStr.substr(0,3);
		int day = Ogre::StringConverter::parseInt( dateStr.substr(4,2) );
		int year = Ogre::StringConverter::parseInt( dateStr.substr(7,4) );
		int month = 0;

		while( month < 12 && monthStr.compare(sMonths[month]) != 0 )
			month++;

		return /* Jahr */		  year * 100000 +
			   /* Monat */	 (month+1) * 1000 + 
			   /* Tag */		   day * 10 + 
			   /* Sub-Version */	 0;	
	}
예제 #3
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);
			}
		}
	}
}
예제 #4
0
//-----------------------------------------------------------------------------
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());
}
예제 #5
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);
			}
		}
	}
}
예제 #6
0
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;
}
예제 #7
0
	VBOOL splitResourceName(const Ogre::String& name,Ogre::String& resourceName,Ogre::String& groupName)
	{
		Ogre::String::size_type pos = name.find_first_of(':');
		if (pos ==Ogre::String::npos)
		{
			if (groupName.empty())
				groupName = DEFAULT_RESOURCE_GROUP_NAME;
			resourceName = name;
			return VFALSE;
		}
		else
		{
			groupName = name.substr(0, pos);
			resourceName = name.substr(pos+1,Ogre::String::npos);
			return VTRUE;
		}
	}
예제 #8
0
파일: OgreSetup.cpp 프로젝트: sajty/ember
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 SaveGameManager::parseScript(Ogre::DataStreamPtr &stream, const Ogre::String &groupName)
    {
        Ogre::String name = stream->getName();
        name = name.substr(0, name.length()-5); //delete ".save" at the and of the name
        int pointpos = name.find_last_of(".");
        name = name.substr(0, pointpos);

        if(Ogre::StringConverter::isNumber(name))
        {
            mHighestSaveGameNumber = std::max(mHighestSaveGameNumber, Ogre::StringConverter::parseInt(name));

            SaveGameFile* file = new SaveGameFile("", Ogre::StringConverter::parseInt(name));        
            
            LOG_MESSAGE(Logger::RULES, "Parsing header of save game: " + name + ".save");
            SaveGameFileReader reader;
            reader.parseSaveGameFileHeader(stream, groupName, file);
            
            if(file->getProperty(SaveGameFile::PROPERTY_MODULEID) != "") // broken save game
                mSaveGames[Ogre::StringConverter::parseInt(name)] = file;
        }
    }
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();
}
bool fnmatch (Ogre::String pattern, Ogre::String name, int dummy)
{
	if (pattern == "*")
	{
		return true;
	}
	if (pattern.substr(0,2) == "*.")
	{
		Ogre::StringUtil::toLowerCase(pattern);
		Ogre::StringUtil::toLowerCase(name);
		Ogre::String extToFind = pattern.substr(2, pattern.size() - 2);
		if ((name.size() > extToFind.size()) &&(extToFind == name.substr(name.size() - extToFind.size(), extToFind.size())))
		{
			return 0; // match
		}
		else
		{
			return 1; // don't match
		}
	}
	return false;
}
예제 #12
0
//-------------------------------------------------------------------------------
void MaterialViewer::onClickSave(MyGUI::WidgetPtr)
{
    Ogre::String name = mMaterialSettings["diffuse_tex"];
    Ogre::String source = createMaterialSource("Brushes/" + name);

    //Remove extension!
    Ogre::String filename = name.substr(0, name.find_last_of('.')) + ".material";
    std::ofstream out((USER_PREFIX "Content/" + filename).c_str());
    out << source;
    out.close();

    MyGUI::Message::createMessageBox("Message", "File '" + filename + "' saved!", 
            "Your material file has been saved as 'Content/" + filename + "' in the user directory!", 
            MyGUI::MessageBoxStyle::IconInfo);
}
예제 #13
0
float
ParseKeyFrameTime( const float length, const Ogre::String& string )
{
    float res = 0;

    if( string.at( string.size() - 1 ) == '%' )
    {
        res = length * Ogre::StringConverter::parseReal( string.substr( 0, string.size() - 1 ) ) / 100;
    }
    else
    {
        res = Ogre::StringConverter::parseReal( string );
    }

    return res;
}
예제 #14
0
bool MilkshapePlugin::locateSkeleton(Ogre::MeshPtr& mesh)
{
    //
    // choose filename
    //
    OPENFILENAME ofn;
    memset (&ofn, 0, sizeof (OPENFILENAME));

    char szFile[MS_MAX_PATH];
    char szFileTitle[MS_MAX_PATH];
    char szDefExt[32] = "skeleton";
    char szFilter[128] = "OGRE .skeleton Files (*.skeleton)\0*.skeleton\0All Files (*.*)\0*.*\0\0";
    szFile[0] = '\0';
    szFileTitle[0] = '\0';

    ofn.lStructSize = sizeof (OPENFILENAME);
    ofn.lpstrDefExt = szDefExt;
    ofn.lpstrFilter = szFilter;
    ofn.lpstrFile = szFile;
    ofn.nMaxFile = MS_MAX_PATH;
    ofn.lpstrFileTitle = szFileTitle;
    ofn.nMaxFileTitle = MS_MAX_PATH;
    ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
    ofn.lpstrTitle = "Locate OGRE Skeleton (since you're not exporting it)";

    if (!::GetOpenFileName (&ofn))
        return false;

    // Strip off the path
    Ogre::String skelName = szFile;
    size_t lastSlash = skelName.find_last_of("\\");
    skelName = skelName.substr(lastSlash+1);

    Ogre::String msg = "Linking mesh to skeleton file '" + skelName + "'";
    Ogre::LogManager::getSingleton().logMessage(msg);

    // Create a dummy skeleton for Mesh to link to (saves it trying to load it)
    Ogre::SkeletonPtr pSkel = Ogre::SkeletonManager::getSingleton().create(skelName, 
        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    Ogre::LogManager::getSingleton().logMessage("Dummy Skeleton object created for link.");

    mesh->_notifySkeleton(pSkel);

    return true;

}
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);
		}
	}
}
예제 #16
0
//-------------------------------------------------------------------------------------
bool UndeadLand::LoadImage(const Ogre::String& texture_name, const Ogre::String& texture_path)
{
  bool image_loaded = false;
  std::ifstream ifs( texture_path.c_str(), std::ios::binary|std::ios::in );
  if ( ifs.is_open( ) )
  {
    Ogre::String tex_ext;
    Ogre::String::size_type index_of_extension = texture_path.find_last_of('.');
    if ( index_of_extension != Ogre::String::npos )
    {
      tex_ext = texture_path.substr( index_of_extension + 1 );
      Ogre::DataStreamPtr data_stream( new Ogre::FileStreamDataStream( texture_path, &ifs, false ) );
      Ogre::Image img;
      img.load( data_stream, tex_ext );
      Ogre::TextureManager::getSingleton().loadImage( texture_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, img, Ogre::TEX_TYPE_2D, 0, 1.0f );
      image_loaded = true;
    }
    ifs.close();
  }
  return image_loaded;
}
예제 #17
0
void
ParsePersent( float& value_percent, float& value, const Ogre::String& string )
{
    if( string.at( string.size() - 1 ) == '%' )
    {
        value_percent = Ogre::StringConverter::parseReal( string.substr( 0, string.size() - 1 ) );
        value = 0;
    }
    else
    {
        Ogre::StringVector param = Ogre::StringUtil::split( string, "%" );
        if( param.size() > 1 )
        {
            value_percent = Ogre::StringConverter::parseReal( param[ 0 ] );
            value = Ogre::StringConverter::parseReal( param[ 1 ] );
        }
        else
        {
            value_percent = 0;
            value = Ogre::StringConverter::parseReal( string );
        }
    }
}
예제 #18
0
Ogre::SkeletonPtr MilkshapePlugin::doExportSkeleton(msModel* pModel, Ogre::MeshPtr& mesh)
{
    Ogre::LogManager &logMgr = Ogre::LogManager::getSingleton();
    Ogre::String msg;

    //
    // choose filename
    //
    OPENFILENAME ofn;
    memset (&ofn, 0, sizeof (OPENFILENAME));

    char szFile[MS_MAX_PATH];
    char szFileTitle[MS_MAX_PATH];
    char szDefExt[32] = "skeleton";
    char szFilter[128] = "OGRE .skeleton Files (*.skeleton)\0*.skeleton\0All Files (*.*)\0*.*\0\0";
    szFile[0] = '\0';
    szFileTitle[0] = '\0';

    ofn.lStructSize = sizeof (OPENFILENAME);
    ofn.lpstrDefExt = szDefExt;
    ofn.lpstrFilter = szFilter;
    ofn.lpstrFile = szFile;
    ofn.nMaxFile = MS_MAX_PATH;
    ofn.lpstrFileTitle = szFileTitle;
    ofn.nMaxFileTitle = MS_MAX_PATH;
    ofn.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
    ofn.lpstrTitle = "Export to OGRE Skeleton";

    if (!::GetSaveFileName (&ofn))
        return Ogre::SkeletonPtr();

    // Strip off the path
    Ogre::String skelName = szFile;
    size_t lastSlash = skelName.find_last_of("\\");
    skelName = skelName.substr(lastSlash+1);

    // Set up
    logMgr.logMessage("Trying to create Skeleton object");
    Ogre::SkeletonPtr ogreskel = Ogre::SkeletonManager::getSingleton().create(skelName, 
        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    logMgr.logMessage("Skeleton object created");

    // Complete the details

    // Do the bones
    int numBones = msModel_GetBoneCount(pModel);
	msg = "Number of bones: " + Ogre::StringConverter::toString(numBones);
    logMgr.logMessage(msg);

    int i;
    // Create all the bones in turn
    for (i = 0; i < numBones; ++i)
    {
        msBone* bone = msModel_GetBoneAt(pModel, i);
        Ogre::Bone* ogrebone = ogreskel->createBone(bone->szName);

        msVec3 msBonePos, msBoneRot;
        msBone_GetPosition(bone, msBonePos);
        msBone_GetRotation(bone, msBoneRot);

        Ogre::Vector3 bonePos(msBonePos[0], msBonePos[1], msBonePos[2]);
        ogrebone->setPosition(bonePos);
        // Hmm, Milkshape has chosen a Euler angle representation of orientation which is not smart
        // Rotation Matrix or Quaternion would have been the smarter choice
        // Might we have Gimbal lock here? What order are these 3 angles supposed to be applied?
        // Grr, we'll try our best anyway...
        Ogre::Quaternion qx, qy, qz, qfinal;
        qx.FromAngleAxis(Ogre::Radian(msBoneRot[0]), Ogre::Vector3::UNIT_X);
        qy.FromAngleAxis(Ogre::Radian(msBoneRot[1]), Ogre::Vector3::UNIT_Y);
        qz.FromAngleAxis(Ogre::Radian(msBoneRot[2]), Ogre::Vector3::UNIT_Z);

        // Assume rotate by x then y then z
        qfinal = qz * qy * qx;
        ogrebone->setOrientation(qfinal);

		Ogre::LogManager::getSingleton().stream()
			<< "Bone #" << i << ": " <<
            "Name='" << bone->szName << "' " <<
            "Position: " << bonePos << " " <<
            "Ms3d Rotation: {" << msBoneRot[0] << ", " << msBoneRot[1] << ", " << msBoneRot[2] << "} " <<
            "Orientation: " << qfinal;


    }
    // Now we've created all the bones, link them up
    logMgr.logMessage("Establishing bone hierarchy..");
    for (i = 0; i < numBones; ++i)
    {
        msBone* bone = msModel_GetBoneAt(pModel, i);

        if (strlen(bone->szParentName) == 0)
        {
            // Root bone
            msg = "Root bone detected: Name='" + Ogre::String(bone->szName) + "' Index=" 
				+ Ogre::StringConverter::toString(i);
            logMgr.logMessage(msg);
        }
        else
        {
            Ogre::Bone* ogrechild = ogreskel->getBone(bone->szName);
            Ogre::Bone* ogreparent = ogreskel->getBone(bone->szParentName);

            if (ogrechild == 0)
            {
                msg = "Error: could not locate child bone '" +
					Ogre::String(bone->szName) + "'";
                logMgr.logMessage(msg);
                continue;
            }
            if (ogreparent == 0)
            {
                msg = "Error: could not locate parent bone '"
					+ Ogre::String(bone->szParentName) + "'";
                logMgr.logMessage(msg);
                continue;
            }
            // Make child
            ogreparent->addChild(ogrechild);
        }


    }
    logMgr.logMessage("Bone hierarchy established.");

    // Create the Animation(s)
    doExportAnimations(pModel, ogreskel);



    // Create skeleton serializer & export
    Ogre::SkeletonSerializer serializer;
    msg = "Exporting skeleton to " + Ogre::String(szFile);
    logMgr.logMessage(msg);
    serializer.exportSkeleton(ogreskel.getPointer(), szFile);
    logMgr.logMessage("Skeleton exported");


    msg = "Linking mesh to skeleton file '" + skelName + "'";
    Ogre::LogManager::getSingleton().logMessage(msg);

    mesh->_notifySkeleton(ogreskel);

    return ogreskel;

}
예제 #19
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);
				}
			}
		}
	}
}
예제 #20
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;
}
void CLASS::LoadText()
{
	m_vehicle_title->setMaxTextLength(33);
	m_vehicle_title->setCaptionWithReplacing(currTruck->getTruckName());

	Ogre::UTFString txt;

	std::vector<authorinfo_t> file_authors = currTruck->getAuthors();
	if (!file_authors.empty())
	{
		Ogre::String authors = "";
		for (std::vector<authorinfo_t>::iterator it = file_authors.begin(); it != file_authors.end(); ++it)
		{
			authors += "* " + (*it).name + " \n";
		}
		txt = txt + _L("Authors: \n") + authors;
	}
	else
		txt = txt + _L("(no author information available) ");

	std::vector<std::string> description = currTruck->getDescription();
	for (unsigned int i = 1; i < 3; i++)
	{
		if (i < description.size())
		{
			txt = txt + _L("\nDescription: \n");
			txt = txt + (ANSI_TO_UTF(description[i])) + "\n";
		}
	}

	txt = txt + _L("\nCommands: \n");

	int filledCommands = 0;
	for (int i = 1; i < MAX_COMMANDS && filledCommands < COMMANDS_VISIBLE; i += 2)
	{
		if (currTruck->commandkey[i].beams.empty() || currTruck->commandkey[i].description == "hide") continue;

		filledCommands++;
		char commandID[256] = {};
		Ogre::String keyStr = "";

		sprintf(commandID, "COMMANDS_%02d", i);
		int eventID = RoR::Application::GetInputEngine()->resolveEventName(Ogre::String(commandID));
		Ogre::String keya = RoR::Application::GetInputEngine()->getEventCommand(eventID);
		sprintf(commandID, "COMMANDS_%02d", i + 1);
		eventID = RoR::Application::GetInputEngine()->resolveEventName(Ogre::String(commandID));
		Ogre::String keyb = RoR::Application::GetInputEngine()->getEventCommand(eventID);

		// cut off expl
		if (keya.size() > 6 && keya.substr(0, 5) == "EXPL+") keya = keya.substr(5);
		if (keyb.size() > 6 && keyb.substr(0, 5) == "EXPL+") keyb = keyb.substr(5);

		keyStr = keya + "/" + keyb;

		if (currTruck->commandkey[i].description.empty())
		{
			txt = txt + "* " + keyStr + ": " + _L("unknown function");
		}
		else
		{
			txt = txt + "* " + keyStr + ": " + currTruck->commandkey[i].description;
		}

		txt = txt + "\n";
	}

	m_vehicle_desc->setCaption(Ogre::String(txt));
}
예제 #22
0
void MilkshapePlugin::doExportAnimations(msModel* pModel, Ogre::SkeletonPtr& ogreskel)
{

    Ogre::LogManager& logMgr = Ogre::LogManager::getSingleton();
    std::vector<SplitAnimationStruct> splitInfo;
    Ogre::String msg;

    int numFrames = msModel_GetTotalFrames(pModel);
	msg = "Number of frames: " + Ogre::StringConverter::toString(numFrames);
    logMgr.logMessage(msg);

    if (splitAnimations)
    {
        // Explain
        msg = "You have chosen to create multiple discrete animations by splitting up the frames in "
			"the animation sequence. In order to do this, you must supply a simple text file "
            "describing the separate animations, which has a single line per animation in the format: \n\n" 
            "startFrame,endFrame,animationName\n\nFor example: \n\n"
            "1,20,Walk\n21,35,Run\n36,40,Shoot\n\n" 
            "..creates 3 separate animations (the frame numbers are inclusive)."
			"You must browse to this file in the next dialog.";
        MessageBox(0,msg.c_str(), "Splitting Animations",MB_ICONINFORMATION | MB_OK);
        // Prompt for a file which contains animation splitting info
        OPENFILENAME ofn;
        memset (&ofn, 0, sizeof (OPENFILENAME));
        
        char szFile[MS_MAX_PATH];
        char szFileTitle[MS_MAX_PATH];
        char szDefExt[32] = "skeleton";
        char szFilter[128] = "All Files (*.*)\0*.*\0\0";
        szFile[0] = '\0';
        szFileTitle[0] = '\0';

        ofn.lStructSize = sizeof (OPENFILENAME);
        ofn.lpstrDefExt = szDefExt;
        ofn.lpstrFilter = szFilter;
        ofn.lpstrFile = szFile;
        ofn.nMaxFile = MS_MAX_PATH;
        ofn.lpstrFileTitle = szFileTitle;
        ofn.nMaxFileTitle = MS_MAX_PATH;
        ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
        ofn.lpstrTitle = "Open animation split configuration file";

        if (!::GetOpenFileName (&ofn))
        {
            msg = "Splitting aborted, generating a single animation called 'Default'";
            MessageBox(0, msg.c_str(), "Info", MB_OK | MB_ICONWARNING);
            SplitAnimationStruct split;
            split.start = 1;
            split.end = numFrames;
            split.name = "Default";
            splitInfo.push_back(split);
        }
        else
        {
            // Read file
            Ogre::String sline;
            char line[256];
            SplitAnimationStruct newSplit;

            std::ifstream istr;
            istr.open(szFile);

            while (!istr.eof())
            {
                istr.getline(line, 256);
                sline = line;

                // Ignore blanks & comments
                if (sline == "" || sline.substr(0,2) == "//")
                    continue;

                // Split on ','
				std::vector<Ogre::String> svec = Ogre::StringUtil::split(line, ",\n");

                // Basic validation on number of elements
                if (svec.size() != 3)
                {
                    MessageBox(0, "Warning: corrupt animation details in file. You should look into this. ",
                        "Corrupt animations file", MB_ICONWARNING | MB_OK);
                    continue;
                }
                // Remove any embedded spaces
				Ogre::StringUtil::trim(svec[0]);
                Ogre::StringUtil::trim(svec[1]);
                Ogre::StringUtil::trim(svec[2]);
                // Create split info
                newSplit.start = atoi(svec[0].c_str());
                newSplit.end = atoi(svec[1].c_str());
                newSplit.name = svec[2];
                splitInfo.push_back(newSplit);

            }


        }

    }
    else
    {
        // No splitting
        SplitAnimationStruct split;
        split.start = 1;
        split.end = numFrames;
        split.name = "Default";
        splitInfo.push_back(split);
    }

    // Get animation length
    // Map frames -> seconds, this can be changed in speed of animation anyway



    int numBones = msModel_GetBoneCount(pModel);
    unsigned int frameTime;
    float realTime;

    std::vector<SplitAnimationStruct>::iterator animsIt;
    for (animsIt = splitInfo.begin(); animsIt != splitInfo.end(); ++animsIt)
    {
        SplitAnimationStruct& currSplit = *animsIt;

        // Create animation
        frameTime = currSplit.end - currSplit.start;
        realTime = frameTime / fps;
		Ogre::LogManager::getSingleton().stream()
			<< "Trying to create Animation object for animation "
			<<  currSplit.name << " For Frames " << currSplit.start << " to "
            << currSplit.end << " inclusive. ";

		Ogre::LogManager::getSingleton().stream()
			<< "Frame time = "
			<< frameTime << ", Seconds = " << realTime;

        Ogre::Animation *ogreanim =
            ogreskel->createAnimation(currSplit.name, realTime);
        logMgr.logMessage("Animation object created.");

        int i;
        // Create all the animation tracks
        for (i = 0; i < numBones; ++i)
        {

            msBone* bone = msModel_GetBoneAt(pModel, i);
            Ogre::Bone* ogrebone = ogreskel->getBone(bone->szName);

            // Create animation tracks
			msg = "Creating AnimationTrack for bone " + Ogre::StringConverter::toString(i);
            logMgr.logMessage(msg);

            Ogre::NodeAnimationTrack *ogretrack = ogreanim->createNodeTrack(i, ogrebone);
            logMgr.logMessage("Animation track created.");

            // OGRE uses keyframes which are both position and rotation
            // Milkshape separates them, but never seems to use the ability to
            // have a different # of pos & rot keys

            int numKeys = msBone_GetRotationKeyCount(bone);

            msg = "Number of keyframes: " + Ogre::StringConverter::toString(numKeys);
            logMgr.logMessage(msg);

            int currKeyIdx;
            msPositionKey* currPosKey;
            msRotationKey* currRotKey;
            for (currKeyIdx = 0; currKeyIdx < numKeys; ++currKeyIdx )
            {
                currPosKey = msBone_GetPositionKeyAt(bone, currKeyIdx);
                currRotKey = msBone_GetRotationKeyAt(bone, currKeyIdx);

                // Make sure keyframe is in current time frame (for splitting)
                if (currRotKey->fTime >= currSplit.start && currRotKey->fTime <= currSplit.end)
                {

                    msg = "Creating KeyFrame #" + Ogre::StringConverter::toString(currKeyIdx)
                        + " for bone #" + Ogre::StringConverter::toString(i);
                    logMgr.logMessage(msg);
                    // Create keyframe
                    // Adjust for start time, and for the fact that frames are numbered from 1
                    frameTime = currRotKey->fTime - currSplit.start;
                    realTime = frameTime / fps;
                    Ogre::TransformKeyFrame *ogrekey = ogretrack->createNodeKeyFrame(realTime);
                    logMgr.logMessage("KeyFrame created");

					Ogre::Vector3 kfPos;
					// Imported milkshape animations may not have positions 
					// for all rotation keys
					if ( currKeyIdx < bone->nNumPositionKeys ) {
						kfPos.x = currPosKey->Position[0];
						kfPos.y = currPosKey->Position[1];
						kfPos.z = currPosKey->Position[2];
					}
					else {
						kfPos.x = bone->Position[0];
						kfPos.y = bone->Position[1];
						kfPos.z = bone->Position[2];
					}
                    Ogre::Quaternion qx, qy, qz, kfQ;

					// Milkshape translations are local to own orientation, not parent
					kfPos = ogrebone->getOrientation() * kfPos;

                    ogrekey->setTranslate(kfPos);
                    qx.FromAngleAxis(Ogre::Radian(currRotKey->Rotation[0]), Ogre::Vector3::UNIT_X);
                    qy.FromAngleAxis(Ogre::Radian(currRotKey->Rotation[1]), Ogre::Vector3::UNIT_Y);
                    qz.FromAngleAxis(Ogre::Radian(currRotKey->Rotation[2]), Ogre::Vector3::UNIT_Z);
                    kfQ = qz * qy * qx;
                    ogrekey->setRotation(kfQ);

					Ogre::LogManager::getSingleton().stream()
						<< "KeyFrame details: Adjusted Frame Time=" << frameTime
						<< " Seconds: " << realTime << " Position=" << kfPos << " " 
						<< "Ms3d Rotation= {" << currRotKey->Rotation[0] << ", " 
						<< currRotKey->Rotation[1] << ", " << currRotKey->Rotation[2] 
						<< "} " << "Orientation=" << kfQ;
                } // keyframe creation

            } // keys
        } //Bones
    } // Animations




}
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());
}
예제 #24
0
int _tmain(int argc, _TCHAR* argv[])
{
	// ------------------------- Check for command line argument -------------------------------------------

	if (! argv[1])
	{
		printf("\n");
		printf("Missing argument.\nExample: \"Converter.exe job1.cfg\"");		
		return 0;	
	}

	// ------------------------- Basic Ogre Engine initialization -------------------------------------------

	Ogre::Root* root = new Ogre::Root;	
	Ogre::RenderSystem* rendersys = root->getRenderSystemByName("Direct3D9 Rendering Subsystem");
	
	rendersys->setConfigOption("Full Screen", "No");
	rendersys->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour");
	
	root->setRenderSystem(rendersys);		
	
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resource", "FileSystem", "General");
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	root->initialise(false);

	Ogre::RenderWindow* window = root->createRenderWindow("RAW2OGT", 800, 600, false);		
	Ogre::SceneManager* scenemgr = root->createSceneManager(Ogre::SceneType::ST_GENERIC);
	Ogre::Camera* camera = scenemgr->createCamera("camera");
	Ogre::Viewport* viewport = window->addViewport(camera);
	/*Ogre::Vector3 lightdir(0, -0.3, 0.75);
	lightdir.normalise();

	Ogre::Light* l = scenemgr->createLight("tstLight");
	l->setType(Ogre::Light::LT_DIRECTIONAL);
	l->setDirection(lightdir);
	l->setDiffuseColour(Ogre::ColourValue(1.0, 1.0, 1.0));
	l->setSpecularColour(Ogre::ColourValue(0.4, 0.4, 0.4));*/

	scenemgr->setAmbientLight(Ogre::ColourValue(0.7, 0.7, 0.7));
	
	// --------------------------------- Start convert ----------------------------------------------------

	// Load job config
	Ogre::ConfigFile* terrainconfig = OGRE_NEW Ogre::ConfigFile();
	terrainconfig->loadDirect(argv[1]);
		
	// Load info from [general] block
	Ogre::String heightmapfile = terrainconfig->getSetting("heightmap", "general");
	Ogre::Real heightmapscale = Ogre::StringConverter::parseReal(terrainconfig->getSetting("heightmapscale", "general"));
	Ogre::Real heightmapoffset = Ogre::StringConverter::parseReal(terrainconfig->getSetting("heightmapoffset", "general"));
	Ogre::uint16 terrainsize = Ogre::StringConverter::parseUnsignedInt(terrainconfig->getSetting("terrainsize", "general"));
	Ogre::Real worldsize = Ogre::StringConverter::parseReal(terrainconfig->getSetting("worldsize", "general"));
	Ogre::uint16 layercount = Ogre::StringConverter::parseUnsignedInt(terrainconfig->getSetting("layercount", "general"));

	// initialise stream to heightmapfile
	Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(heightmapfile, "General");
	size_t size = stream.get()->size();
		
	// verify size
	if(size != terrainsize * terrainsize * 4)
		OGRE_EXCEPT( Ogre::Exception::ERR_INTERNAL_ERROR, "Size of stream does not match terrainsize!", "TerrainPage" );
					
	// load to buffer
	float* buffer = OGRE_ALLOC_T(float, size, Ogre::MEMCATEGORY_GENERAL);
	stream->read(buffer, size);

	// apply scale and offset 
	for(int i=0;i<terrainsize*terrainsize;i++)
	{
		buffer[i]  = (buffer[i] + heightmapoffset) * heightmapscale;
	}

	// Terrain initialization
	Ogre::TerrainGlobalOptions* terrainglobals = OGRE_NEW Ogre::TerrainGlobalOptions();
	terrainglobals->setMaxPixelError(1);
	//terrainglobals->setCompositeMapDistance(30000);
	//terrainglobals->setLightMapDirection(lightdir);
    //terrainglobals->setCompositeMapAmbient(scenemgr->getAmbientLight());
    //terrainglobals->setCompositeMapDiffuse(l->getDiffuseColour());
	
	Ogre::TerrainMaterialGeneratorA::SM2Profile* pMatProfile = 
      static_cast<Ogre::TerrainMaterialGeneratorA::SM2Profile*>(terrainglobals->getDefaultMaterialGenerator()->getActiveProfile());
	
	pMatProfile->setLightmapEnabled(false);
	pMatProfile->setCompositeMapEnabled(false);
	
	Ogre::TerrainGroup* terraingroup = OGRE_NEW Ogre::TerrainGroup(scenemgr, Ogre::Terrain::ALIGN_X_Z, terrainsize, worldsize);
    terraingroup->setFilenameConvention(Ogre::String("terrain"), Ogre::String("ogt"));
    terraingroup->setOrigin(Ogre::Vector3::ZERO);
		
	Ogre::Terrain* terrain = OGRE_NEW Ogre::Terrain(scenemgr);

	// terrainsettings							
	Ogre::Terrain::ImportData& imp = terraingroup->getDefaultImportSettings();	
	imp.terrainSize = terrainsize;
	imp.worldSize = worldsize;
	imp.minBatchSize = 33;
	imp.maxBatchSize = 65;

	// use float RAW heightmap as input
	imp.inputFloat = buffer;
	
	// process texture layers
	imp.layerList.resize(layercount);
	Ogre::StringVector blendmaps(layercount);
	for(int i=0;i<layercount;i++)
	{
		// load layer info
		Ogre::String sectionStr = Ogre::StringConverter::toString(i);
		Ogre::Real layerworldsize = Ogre::StringConverter::parseReal(terrainconfig->getSetting("worldsize", sectionStr));
		
		if (i==0)
		{			
			// no blendmap at layer 0 (baselayer)
			Ogre::String specular = terrainconfig->getSetting("specular", sectionStr);
			Ogre::String normal = terrainconfig->getSetting("normal", sectionStr);

			// add layer		
			imp.layerList[i].textureNames.push_back(specular);
			imp.layerList[i].textureNames.push_back(normal);
			imp.layerList[i].worldSize = layerworldsize;			
		}
		else
		{
			Ogre::String specular = terrainconfig->getSetting("specular", sectionStr);
			Ogre::String normal = terrainconfig->getSetting("normal", sectionStr);
			Ogre::String blend = terrainconfig->getSetting("blend", sectionStr);
		
			// add layer		
			imp.layerList[i].textureNames.push_back(specular);
			imp.layerList[i].textureNames.push_back(normal);	
			imp.layerList[i].worldSize = layerworldsize;

			blendmaps[i] = blend; 
		}
	}

	// load the terrain
	terrain->prepare(imp);
	terrain->load();	
	
	// load those blendmaps into the layers
	for(int j = 1;j < terrain->getLayerCount();j++)
	{
		Ogre::TerrainLayerBlendMap *blendmap = terrain->getLayerBlendMap(j);
		Ogre::Image img;
		img.load(blendmaps[j],"General");
		int blendmapsize = terrain->getLayerBlendMapSize();
		if(img.getWidth() != blendmapsize)
			img.resize(blendmapsize, blendmapsize);

		float *ptr = blendmap->getBlendPointer();
		Ogre::uint8 *data = static_cast<Ogre::uint8*>(img.getPixelBox().data);

		for(int bp = 0;bp < blendmapsize * blendmapsize;bp++)
			ptr[bp] = static_cast<float>(data[bp]) / 255.0f;

		blendmap->dirty();
		blendmap->update();
	}

	// create filename for writing
	int pos = heightmapfile.find_last_of('.');
	if (pos < 0)	
		heightmapfile = heightmapfile + ".ogt";
	else	
		heightmapfile = heightmapfile.substr(0, pos) + ".ogt";
			
	// save as Ogre .OGT
	terrain->save(heightmapfile);	
	Ogre::LogManager::getSingletonPtr()->logMessage(Ogre::LogMessageLevel::LML_NORMAL, heightmapfile + " successfully written.");
	
	// debug viewing (exit with CTRL+C)
	camera->setPosition(-terrainsize, 7000, -terrainsize);
	camera->lookAt(terrainsize/2,0,terrainsize/2);	
	root->startRendering();

	return 0;
}
예제 #25
0
void MilkshapePlugin::doExportMaterials(msModel* pModel)
{
	Ogre::LogManager& logMgr = Ogre::LogManager::getSingleton();
	Ogre::MaterialManager matMgrSgl;
	Ogre::String msg;

    matMgrSgl.initialise();

	int numMaterials = msModel_GetMaterialCount(pModel);
	msg = "Number of materials: " + Ogre::StringConverter::toString(numMaterials);
	logMgr.logMessage(msg);

	OPENFILENAME ofn;
	memset (&ofn, 0, sizeof (OPENFILENAME));

	char szFile[MS_MAX_PATH];
	char szFileTitle[MS_MAX_PATH];
	char szDefExt[32] = "material";
	char szFilter[128] = "OGRE .material Files (*.material)\0*.material\0All Files (*.*)\0*.*\0\0";
	szFile[0] = '\0';
	szFileTitle[0] = '\0';

	ofn.lStructSize = sizeof (OPENFILENAME);
	ofn.lpstrDefExt = szDefExt;
	ofn.lpstrFilter = szFilter;
	ofn.lpstrFile = szFile;
	ofn.nMaxFile = MS_MAX_PATH;
	ofn.lpstrFileTitle = szFileTitle;
	ofn.nMaxFileTitle = MS_MAX_PATH;
	ofn.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
	ofn.lpstrTitle = "Export to OGRE Material";

	if (!::GetSaveFileName (&ofn))
		return;

	// Strip off the path
	Ogre::String matName = szFile;
	size_t lastSlash = matName.find_last_of("\\");
	matName = matName.substr(lastSlash+1);

	// Set up
	logMgr.logMessage("Trying to create Material object");

	Ogre::MaterialSerializer matSer;

	for (int i = 0; i < numMaterials; ++i)
	{
		msMaterial *mat = msModel_GetMaterialAt(pModel, i);

		msg = "Creating material " + Ogre::String(mat->szName);
		logMgr.logMessage(msg);
        Ogre::MaterialPtr ogremat = matMgrSgl.create(mat->szName, 
            Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		logMgr.logMessage("Created.");

		ogremat->setAmbient(msVec4ToColourValue(mat->Ambient));
		ogremat->setDiffuse(msVec4ToColourValue(mat->Diffuse));
		ogremat->setSpecular(msVec4ToColourValue(mat->Specular));
		ogremat->setShininess(mat->fShininess);

		if (0 < strlen(mat->szDiffuseTexture))
			ogremat->getTechnique(0)->getPass(0)->createTextureUnitState(mat->szDiffuseTexture);

        if (0 < strlen(mat->szAlphaTexture))
			ogremat->getTechnique(0)->getPass(0)->createTextureUnitState(mat->szAlphaTexture);


		matSer.queueForExport(ogremat);
	}

	msg = "Exporting materials to " + matName;
	logMgr.logMessage(msg);
	matSer.exportQueued(matName);
}
예제 #26
0
//-----------------------------------------------------------------------------
int COFSSceneSerializer::Export(bool SaveAs, Ogre::String exportfile)
{
    OgitorsRoot *ogRoot = OgitorsRoot::getSingletonPtr();
    OgitorsSystem *mSystem = OgitorsSystem::getSingletonPtr();
    OFS::OfsPtr& mFile = ogRoot->GetProjectFile();

    PROJECTOPTIONS *pOpt = ogRoot->GetProjectOptions();

    bool forceSave = false;
    Ogre::String fileLocation = ogRoot->GetProjectFile()->getFileSystemName();
    Ogre::String fileName = "";

    if (!exportfile.empty())
    {
        // Save location was passed, so use this filename
        fileLocation = exportfile;
    }

    if (SaveAs)
    {
        // Saving at a different location
        UTFStringVector extlist;

        if( mFile->getFileSystemType() == OFS::OFS_PACKED )
        {
            extlist.push_back(OTR("Ogitor File System File"));
            extlist.push_back("*.ofs");
        }
        else
        {
            extlist.push_back(OTR("Ogitor Scene File"));
            extlist.push_back("*" + Globals::OGSCENE_FORMAT_EXTENSION);
        }

        Ogre::String newfileLocation = mSystem->DisplaySaveDialog(OTR("Save As"), extlist, fileLocation);
        if(newfileLocation == "") 
            return SCF_CANCEL;

        mSystem->SetSetting("system", "oldOpenPath", newfileLocation);

        if(Ogre::StringUtil::match(newfileLocation, fileLocation, false))
        {
            SaveAs = false;
        } 
        else 
        {
            forceSave = true;
            fileLocation = newfileLocation;
        }
    }

    Ogre::String filePath = OgitorsUtils::ExtractFilePath(fileLocation);
    fileName = OgitorsUtils::ExtractFileName(fileLocation);

    // Change the project directory to the new path
    pOpt->ProjectDir = filePath;

    if(fileName.substr(fileName.size() - 4, 4) != ".ofs")
        fileLocation = filePath;

    int dotpos = fileName.find_last_of(".");
    if (dotpos > 0)
    {
        fileName.erase(dotpos, fileName.length() - dotpos);
    }

    if (SaveAs && mFile->moveFileSystemTo(fileLocation.c_str()) != OFS::OFS_OK)
    {
        return SCF_ERRFILE;
    }

    if (SaveAs)
    {
        mFile->deleteFile((pOpt->ProjectName + Globals::OGSCENE_FORMAT_EXTENSION).c_str());
        pOpt->ProjectName = fileName;
    }

    if (_writeFile(fileName + Globals::OGSCENE_FORMAT_EXTENSION, forceSave) != SCF_OK)
    {
        return SCF_ERRFILE;
    }

    return SCF_OK;
}
//
// 创建建筑物的行走面数据。
//
void FairyEditorFrame::CreateBuildingCollisionData()
{

   std::string			strTemp;			// 
   Ogre::String			meshName;			// 静态物体对应的mesh模型文件.
   Ogre::String			meshFile;			// 静态物体对应的mesh模型文件.
   Ogre::String			meshPath;			// 静态物体对应的mesh模型文件.
  
   Ogre::Vector3		position;			// 静态物体摆放的位置.
   Ogre::Quaternion		rotateQuaternion;	// 旋转数据.
   Ogre::Vector3		scale;				// 缩放数据.

   int	iStrLen = 0;	// mesh 文件名字的长度
   int  iPos	= 0;	// mesh 文件名字中 ‘ / ’的位置.

   // 清空以前的数据。
   m_TriInMapInfoMap.m_triInfoInMap.clear();


   // 查找每一个带有行走面数据的物体
   const Fairy::Scene::Objects& mObjects = GetSceneManipulator()->getSceneInfo()->getObjects();
   for (Fairy::Scene::Objects::const_iterator it = mObjects.begin(); it != mObjects.end(); ++it)
   {
       const Fairy::ObjectPtr& object = *it;
       //if ( ("StaticEntity" != object->getType())&&("Model" != object->getType()))
       //{
       //   continue;      
       //}//
	   //if ( (Fairy::StaticEntityObject::msType != object->getType())
		  // &&(Fairy::ModelObject::msType !=  object->getType()))
    //   {
    //      continue;      
    //   }//

	   if(Fairy::StaticEntityObject::msType != object->getType())
	   {
          continue;      
       }//

		meshName = Fairy::VariantCast<Ogre::String>(object->getProperty("mesh name"));
	    Ogre::StringUtil::splitFilename(meshName, meshFile, meshPath);
		iPos     = meshFile.find_last_of(".");
   		
		std::string strName;
		strName.empty();
		if(iPos> 0)
		{
			strName  = meshFile.substr(0, iPos);
		}
		else
		{
			strName = meshFile;
		}

		strName  = strName + ".cll";

		//FairyEditorFrame::BUILDING_COLLISION_MAP::iterator it1;
		//FairyEditorFrame::BUILDING_COLLISION_MAP::iterator itEnd1;

		//itEnd1 = m_buildingCollisionInfoLibMap.end();
		//for(it1 = m_buildingCollisionInfoLibMap.begin(); it1 != itEnd1; it1++)
		//{
		//	std::string strCllFileName = it1->first;
		//	if(strName == strCllFileName)
		//	{
		//		break;
		//	}
		//}

		//if(it1 == itEnd1)
		//{
		//	continue;
		//}
		////if(0 == m_buildingCollisionInfoLibMap.count(strName))
		////{
		////	continue;
		////}//

		// 得到模型的平移, 旋转和缩放数据。
		position         = Fairy::VariantCast<Ogre::Vector3>(object->getProperty("position"));
		rotateQuaternion = Fairy::VariantCast<Ogre::Quaternion>(object->getProperty("orientation"));
		scale			 = Fairy::VariantCast<Ogre::Vector3>(object->getProperty("scale"));

		// 创建变换矩阵。
		Ogre::Matrix4 TransformMatrix;
		BuildTransformMatrix(TransformMatrix, position, rotateQuaternion, scale);

		// 先把行走面数据注册到地图中去。
		RegisterCollisionToMap(strName, TransformMatrix);

    }
}
예제 #28
0
int COFSSceneSerializer::Import(Ogre::String importfile)
{
    OgitorsRoot *ogRoot = OgitorsRoot::getSingletonPtr();
    OgitorsSystem *mSystem = OgitorsSystem::getSingletonPtr();
    OFS::OfsPtr& mFile = OgitorsRoot::getSingletonPtr()->GetProjectFile();

    if(importfile == "")
    {
        UTFStringVector extlist;
        extlist.push_back(OTR("Ogitor File System File"));
        extlist.push_back("*.ofs");
        extlist.push_back(OTR("Ogitor Scene File"));
        extlist.push_back("*" + Globals::OGSCENE_FORMAT_EXTENSION);

        importfile = mSystem->GetSetting("system", "oldOpenPath", "");
        importfile = mSystem->DisplayOpenDialog(OTR("Open"), extlist, importfile);
        if(importfile == "") 
            return SCF_CANCEL;

        mSystem->SetSetting("system", "oldOpenPath", importfile);
    }

    importfile = OgitorsUtils::QualifyPath(importfile);

    Ogre::String filePath = OgitorsUtils::ExtractFilePath(importfile);
    Ogre::String fileName = OgitorsUtils::ExtractFileName(importfile);

    bool testpassed = false;
    try
    {
        std::ofstream test((filePath + "test.dat").c_str());
        if(test.is_open())
            testpassed = true;
        test.close();
        mSystem->DeleteFile(filePath + "test.dat");
    }
    catch(...)
    {
        testpassed = false;
    }

    if(!testpassed)
    {
        mSystem->DisplayMessageDialog("The path is read-only. Ogitor can not work with read-only project paths!", DLGTYPE_OK);
        return SCF_CANCEL;
    }

    Ogre::UTFString loadmsg = "";

    int typepos = importfile.find_last_of(".");
    if(typepos != -1 && (importfile.substr(typepos, 4) != ".ofs"))
        importfile = filePath;
    

    OFS::OfsResult oRet;
    if((oRet = mFile.mount(importfile.c_str(), OFS::OFS_MOUNT_OPEN | OFS::OFS_MOUNT_RECOVER)) != OFS::OFS_OK)
    {
        if(oRet == OFS::OFS_PREVIOUS_VERSION)
        {
            mSystem->DisplayMessageDialog("The OFS file is a previous version, please use qtOFS to upgrade it to new file version.", DLGTYPE_OK);
        }

        loadmsg = mSystem->Translate("Please load a Scene File...");
        mSystem->UpdateLoadProgress(-1, loadmsg);
        return SCF_ERRPARSE;
    }

    OFS::FileSystemStats fsStats;

    mFile->getFileSystemStats(fsStats);

    PROJECTOPTIONS *pOpt = ogRoot->GetProjectOptions();
    pOpt->CreatedIn = "";

    pOpt->ProjectDir = filePath;
    typepos = fileName.find_last_of(".");
    if(typepos != -1)
        fileName.erase(typepos, fileName.length() - typepos);
    pOpt->ProjectName = fileName;

    fileName += Globals::OGSCENE_FORMAT_EXTENSION;

    OFS::ofs64 file_size = 0;

    if(mFile->getFileSize(fileName.c_str(), file_size) != OFS::OFS_OK)
	{		
        // OGSCENE file name needs to match OFS container file name. If the later was renamed, we 
        // need to automatically adapt the OGSCENE file name now.
        OFS::FileList files = mFile->listFiles("/", OFS::OFS_FILE);
        unsigned int ogsceneFileExtensionLength = strlen(Globals::OGSCENE_FORMAT_EXTENSION.c_str());

		for(OFS::FileList::iterator iter = files.begin(); iter != files.end(); iter++)
		{
			// Filter out too short names
            if(iter->name.size() <= ogsceneFileExtensionLength) 
                continue;

			if(stricmp(iter->name.c_str() + (iter->name.size() - (ogsceneFileExtensionLength)), Globals::OGSCENE_FORMAT_EXTENSION.c_str()) == 0)
			{
				mFile->renameFile(iter->name.c_str(), fileName.c_str());
				break;
			}
		}

		if(mFile->getFileSize(fileName.c_str(), file_size) != OFS::OFS_OK)
			return SCF_ERRFILE;
	}

    char *file_data = new char[(unsigned int)file_size + 1];

    OFS::OFSHANDLE projHandle;

    if(mFile->openFile(projHandle, fileName.c_str(), OFS::OFS_READ) != OFS::OFS_OK)
    {
        delete [] file_data;
        return SCF_ERRFILE;
    }

    mFile->read(projHandle, file_data, file_size);
    mFile->closeFile(projHandle);

    TiXmlDocument docImport;

    if(!docImport.LoadFromMemory(file_data, file_size))
    {
        delete [] file_data;
        return SCF_ERRFILE;
    }

    delete [] file_data;

    loadmsg = mSystem->Translate("Parsing Scene File");
    mSystem->UpdateLoadProgress(1, loadmsg);

    TiXmlNode* ogitorSceneNode = 0;
    TiXmlNode* projectNode;
    TiXmlElement* element = 0;
    bool upgradeExecuted = false;
    ogitorSceneNode = docImport.FirstChild("OGITORSCENE");

    if(!ogitorSceneNode)
        return SCF_ERRPARSE;

    element = ogitorSceneNode->ToElement();

    // Old OGSCENE version check and attempt to fix/update
    int version = Ogre::StringConverter::parseInt(ValidAttr(element->Attribute("version"), "0"));    
    if(Ogre::StringConverter::toString(version) < Globals::OGSCENE_FORMAT_VERSION)
    {
        mSystem->DisplayMessageDialog(mSystem->Translate("Old OGSCENE file version detected. Ogitor will now attempt to upgrade the format and will also create a backup version of your OFS file."), DLGTYPE_OK);

        loadmsg = mSystem->Translate("Upgrading OGSCENE file.");
        mSystem->UpdateLoadProgress(10, loadmsg);

        if(version == 0)
        {
            mSystem->DisplayMessageDialog(mSystem->Translate("OGSCENE files contains no version number set and therefore cannot be loaded."), DLGTYPE_OK);
            return SCF_ERRPARSE;
        }
        else if(version == 1)
        {
            mSystem->DisplayMessageDialog(mSystem->Translate("OGSCENE files with version 1 cannot be upgraded automatically. Please contact the Ogitor team for further details."), DLGTYPE_OK);
            return SCF_ERRPARSE;
        }

        if(version > 1)
        {
            if((mFile->getFileSystemType() == OFS::OFS_PACKED) && (!mSystem->CopyFile(importfile, importfile + ".backup")))
                mSystem->DisplayMessageDialog(mSystem->Translate("Error while trying to create backup file."), DLGTYPE_OK);
        }
        switch(version)
        {
         case 2:
            _upgradeOgsceneFileFrom2To3(ogitorSceneNode);
            _upgradeOgsceneFileFrom3To4(ogitorSceneNode);
            break;
         case 3:
            _upgradeOgsceneFileFrom3To4(ogitorSceneNode);
            break;
        }

        upgradeExecuted = true;
    }  

    projectNode = ogitorSceneNode->FirstChild("PROJECT");

    if(projectNode)
    {
        loadmsg = mSystem->Translate("Parsing project options");
        mSystem->UpdateLoadProgress(5, loadmsg);
        ogRoot->LoadProjectOptions(projectNode->ToElement());
        ogRoot->PrepareProjectResources();
    }

    element = ogitorSceneNode->FirstChildElement();

    loadmsg = mSystem->Translate("Creating scene objects");
    mSystem->UpdateLoadProgress(10, loadmsg);

    unsigned int obj_count = 0;
    Ogre::String objecttype;
    OgitorsPropertyValueMap params;
    OgitorsPropertyValue tmpPropVal;
    Ogre::String objAttValue;
    Ogre::String elementName;
    TiXmlElement* properties = 0;
    Ogre::String attID;
    Ogre::String attValue;
    CBaseEditor* result = 0;
    TiXmlElement* customprop = 0;
    Ogre::StringVector invalidEditorTypes;

    do
    {
        // Make sure its NON-ZERO
        if(pOpt->ObjectCount)
        {
            ++obj_count;
            mSystem->UpdateLoadProgress(10 + ((obj_count * 70) / pOpt->ObjectCount), loadmsg);
        }

        params.clear();       

        objAttValue = ValidAttr(element->Attribute("object_id"), "");
        if(objAttValue != "")
        {
            tmpPropVal.propType = PROP_UNSIGNED_INT;
            tmpPropVal.val = Ogre::Any(Ogre::StringConverter::parseUnsignedInt(objAttValue));
            params.insert(OgitorsPropertyValueMap::value_type("object_id", tmpPropVal));
        }

        objAttValue = ValidAttr(element->Attribute("parentnode"), "");
        if(objAttValue != "")
        {
            tmpPropVal.propType = PROP_STRING;
            tmpPropVal.val = Ogre::Any(objAttValue);
            params.insert(OgitorsPropertyValueMap::value_type("parentnode", tmpPropVal));
        }

        objAttValue = ValidAttr(element->Attribute("name"), "");
        if(objAttValue != "")
        {
            tmpPropVal.propType = PROP_STRING;
            tmpPropVal.val = Ogre::Any(objAttValue);
            params.insert(OgitorsPropertyValueMap::value_type("name", tmpPropVal));
        }
        else
            continue;

        objAttValue = ValidAttr(element->Attribute("typename"), "");
        if(objAttValue != "")
        {
            tmpPropVal.propType = PROP_STRING;
            tmpPropVal.val = Ogre::Any(objAttValue);
            params.insert(OgitorsPropertyValueMap::value_type("typename", tmpPropVal));
        }
        else
            continue;

        properties = element->FirstChildElement();
        if(properties)
        {            
            do
            {
                elementName = properties->Value();
                if(elementName != "PROPERTY")
                    continue;

                attID = ValidAttr(properties->Attribute("id"), "");
                int attType = Ogre::StringConverter::parseInt(ValidAttr(properties->Attribute("type"), ""));
                attValue = ValidAttr(properties->Attribute("value"), "");

                params.insert(OgitorsPropertyValueMap::value_type(attID, OgitorsPropertyValue::createFromString((OgitorsPropertyType)attType, attValue)));
            } while(properties = properties->NextSiblingElement());
        }

        objecttype = Ogre::any_cast<Ogre::String>(params["typename"].val);
        result = ogRoot->CreateEditorObject(0, objecttype, params, false, false);
        if(result)
        {
            customprop = element->FirstChildElement("CUSTOMPROPERTIES");
            if(customprop) 
            {
                OgitorsUtils::ReadCustomPropertySet(customprop, result->getCustomProperties());
            }
        }
        else
            invalidEditorTypes.push_back(objecttype);

    } while(element = element->NextSiblingElement());

    // Print out invalid/unsupported editor types (= types where no factory could be found)
    if(invalidEditorTypes.size() > 0)
    {
        std::sort(invalidEditorTypes.begin(), invalidEditorTypes.end());
        invalidEditorTypes.erase(std::unique(invalidEditorTypes.begin(), invalidEditorTypes.end()), invalidEditorTypes.end());
        Ogre::String invalidTypesResultString;
        for(unsigned int i = 0; i < invalidEditorTypes.size(); i++)
        {
            invalidTypesResultString += invalidEditorTypes.at(i) + "\n";
        }
        mSystem->DisplayMessageDialog(mSystem->Translate("Could not create objects of types:\n" + invalidTypesResultString), DLGTYPE_OK);
    }

    //// Save directly after upgrade
    //if(upgradeExecuted)
    //    Export(false, importfile);

    ogRoot->AfterLoadScene();

    return SCF_OK;
}
예제 #29
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);
				}
			}
		}
	}
}
예제 #30
0
/**
 * 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;
}