Пример #1
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);
}
Пример #2
0
	//-----------------------------------------------------------------------
	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);
		}
	}
Пример #3
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;

}
Пример #4
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;
}
    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 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);

    }
}
Пример #7
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);
}
Пример #8
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;

}
Пример #9
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;
}
Пример #10
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;
}
Пример #11
0
void
BrushSelector::ReloadTextureList(void)
{
	CatalogMap catalogMap;
	mCatalogMap.clear();

    if (!Ogre::ResourceGroupManager::getSingletonPtr())
        return;

    mBrushesTree->Freeze();

    mBrushesTree->DeleteAllItems();

	wxTreeItemId rootId = mBrushesTree->AddRoot(/*_("Brushes")*/wxT("画刷列表"));
 
    // 重新解析定义文件
    GetSceneManipulator()->reloadPaintInfo();

    const Fairy::TerrainPaintInfoContainer *paintInfoContainer = GetSceneManipulator()->getTerrainPaintInfoContainer();

    assert (paintInfoContainer);

    const Fairy::TextureInfoMap &textureInfoMap = paintInfoContainer->getTextureInfoMap();

	OwnerTexs ownerTextures;

	Fairy::TextureInfoMap::const_iterator it = textureInfoMap.begin();	

    // 遍历画刷数组
    while ( it != textureInfoMap.end() )
    {
        const Fairy::TextureInfos &textureInfos = it->second;
        
        // 遍历该画刷下的所有纹理
        for ( size_t i=0; i<textureInfos.size(); ++i )
        {
            // 取出所属的大纹理的名称
            Ogre::String ownerTexName = textureInfos[i].ownerTextureName;

			// 记录大纹理的名称
			ownerTextures.insert(OwnerTexs::value_type(ownerTexName, ownerTexName));

            // 如果该纹理名称中包含了/,说明它是在一个文件夹中的
            size_t pos = ownerTexName.find_last_of('/');

            // 在文件夹中
            if (pos != Ogre::String::npos)
            {
                // 先去除纹理文件名,剩下路径名
                ownerTexName.erase(pos+1);
                // 加上画刷的名称
                ownerTexName.append(textureInfos[i].brushName);
                wxTreeItemId id = mBrushesTree->AppendItem( GetParentId(ownerTexName, catalogMap), wxT(textureInfos[i].textureName) );
				
				mCatalogMap.insert(CatalogMap::value_type( textureInfos[i].textureName, id ));
            }
            else
            {
                Ogre::String brushName = textureInfos[i].brushName;
                // 如果是在根目录下,就直接用画刷名称来作为路径名
                wxTreeItemId id = mBrushesTree->AppendItem( GetParentId(brushName, catalogMap), wxT(textureInfos[i].textureName) );
				mCatalogMap.insert(CatalogMap::value_type( textureInfos[i].textureName, id ));
			}				
        }
        ++it;
    }

	wxString lostTexNames = wxEmptyString;
	for (OwnerTexs::iterator ownerIt = ownerTextures.begin(); ownerIt != ownerTextures.end(); ++ownerIt)
	{
		Ogre::String texName = ownerIt->first;

		Ogre::FileInfoListPtr fileInfoList =
			Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo("Brushes",texName);
		
		Ogre::FileInfoList::const_iterator itBegin = fileInfoList->begin();
		Ogre::FileInfoList::const_iterator itEnd = fileInfoList->end(); 
		if (itBegin == itEnd)
		{
			lostTexNames+=wxT("\n");
			lostTexNames+=texName.c_str();
			 continue;
		}

		Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(texName);

		if (!texture.isNull())
		{
			Ogre::TextureManager::getSingleton().remove(texName);
			Ogre::Image image;
			image.load(texName, Fairy::BRUSH_RESOURCE_GROUP_NAME);
			texture = Ogre::TextureManager::getSingleton()
				.loadImage(texName, Fairy::BRUSH_RESOURCE_GROUP_NAME, image);
		}
	}	

	if (!lostTexNames.empty())
	{
		wxMessageBox(wxT("以下贴图无法找到:")+lostTexNames);
	}

    mBrushesTree->Thaw();
}
//----------------------------------------------------------------------------
int CDotSceneSerializer::Import(Ogre::String importfile)
{
    OgitorsRoot *ogRoot = OgitorsRoot::getSingletonPtr();
    OgitorsSystem *mSystem = OgitorsSystem::getSingletonPtr();

    if(importfile == "")
    {
        UTFStringVector extlist;
        extlist.push_back(OTR("DotScene File"));
        extlist.push_back("*.scene");
        extlist.push_back(OTR("DotScene File"));
        extlist.push_back("*.xml");
        importfile = mSystem->DisplayOpenDialog(OTR("Import DotScene File"),extlist);
        if(importfile == "") return SCF_CANCEL;
    }

    ogRoot->ClearProjectOptions();

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

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

    if(filePath.find(".") == 0)
    {
        filePath = OgitorsUtils::GetExePath() + filePath;
        filePath = OgitorsUtils::QualifyPath(filePath);
    }

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

    TiXmlDocument docImport((filePath + fileName).c_str());

    if(!docImport.LoadFile()) return SCF_ERRFILE;

    TiXmlElement* element = 0;
    element = docImport.FirstChildElement("scene");
    if(!element)
        return SCF_ERRFILE;

    float version = Ogre::StringConverter::parseReal(ValidAttr(element->Attribute("formatVersion")));
    if(version != 1.0f)
    {
        mSystem->DisplayMessageDialog(OTR("Only File Version 1.0 is supported!"),DLGTYPE_OK);
        return SCF_ERRFILE;
    }
    
    pOpt->SceneManagerName = "OctreeSceneManager";

    pOpt->ResourceDirectories.push_back("/");
    TiXmlElement* resLoc = element->FirstChildElement("resourceLocations");
    if(resLoc)
    {
        resLoc = resLoc->FirstChildElement();
        while(resLoc)
        {
            Ogre::String resType = ValidAttr(resLoc->Attribute("type"));
            Ogre::String resName = ValidAttr(resLoc->Attribute("name"));
            if(resType == "FileSystem")
            {
                OgitorsUtils::CleanPath(resName);
                
                if(resName[0] == '.')
                    resName.erase(0, 1);

                pOpt->ResourceDirectories.push_back(resName);
            }

            resLoc = resLoc->NextSiblingElement();
        }
    }

    TiXmlElement* configData = element->FirstChildElement("terrain");
    if(configData)
    {
        pOpt->SceneManagerConfigFile = ValidAttr(configData->Attribute("dataFile"));
    }

    pOpt->CameraPositions[0] = Ogre::Vector3(0,10,0);
    pOpt->CameraOrientations[0] = Ogre::Quaternion::IDENTITY;
    pOpt->CameraPositions[1] = Ogre::Vector3(0,10,0);
    pOpt->CameraOrientations[1] = Ogre::Quaternion::IDENTITY;
    pOpt->CameraSaveCount = 1;

    OFS::OfsPtr& ofsFile = OgitorsRoot::getSingletonPtr()->GetProjectFile();

    Ogre::String ofs_file_name = OgitorsUtils::QualifyPath(filePath + "/" + pOpt->ProjectName + ".ofs");
    
    if(ofsFile.mount(ofs_file_name.c_str(), OFS::OFS_MOUNT_CREATE) != OFS::OFS_OK)
        return SCF_ERRFILE;

    OgitorsUtils::CopyDirOfs(filePath, "/");

    ofsFile->deleteFile(fileName.c_str());

    ofs_file_name = OgitorsUtils::ExtractFileName(ofs_file_name);

    ofsFile->deleteFile(ofs_file_name.c_str());
    
    ogRoot->PrepareProjectResources();

    OgitorsPropertyValueMap params;
    OgitorsPropertyValue propValue;
    
    propValue.propType = PROP_STRING;
    propValue.val = Ogre::Any(pOpt->SceneManagerConfigFile);
    params["configfile"] = propValue;
        
    Ogre::Vector2 vClipping(1,1000);
    TiXmlElement* environment = element->FirstChildElement("environment");
    if(environment)
    {
        TiXmlElement* current = environment->FirstChildElement("clipping");
        if(current)
        {
            vClipping.x = Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("near"),"1"));
            vClipping.y = Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("far"),"1000"));
        }

        current = environment->FirstChildElement("colourAmbient");
        if(current)
        {
            params["ambient"] = parseColourValue(current);
        }
        
        current = environment->FirstChildElement("skyBox");
        if(current)
        {
            propValue.propType = PROP_BOOL;
            propValue.val = Ogre::Any(Ogre::StringConverter::parseBool(ValidAttr(current->Attribute("enable"),"0")));
            params["skybox::active"] = propValue;
            propValue.propType = PROP_STRING;
            propValue.val = Ogre::Any(Ogre::String(ValidAttr(current->Attribute("material"))));
            params["skybox::material"] = propValue;
            propValue.propType = PROP_REAL;
            propValue.val = Ogre::Any(Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("distance"),"0")));
            params["skybox::distance"] = propValue;
        }

        current = environment->FirstChildElement("skyDome");
        if(current)
        {
            propValue.propType = PROP_BOOL;
            propValue.val = Ogre::Any(Ogre::StringConverter::parseBool(ValidAttr(current->Attribute("enable"),"0")));
            params["skydome::active"] = propValue;
            propValue.propType = PROP_STRING;
            propValue.val = Ogre::Any(Ogre::String(ValidAttr(current->Attribute("material"))));
            params["skydome::material"] = propValue;
        }

        current = environment->FirstChildElement("fog");
        if(current)
        {
            propValue.propType = PROP_INT;
            Ogre::String fogmode = ValidAttr(current->Attribute("mode"),"None");
            if(fogmode == "Linear" || fogmode == "linear" )
                propValue.val = Ogre::Any((int)Ogre::FOG_LINEAR);
            else if(fogmode == "Exp" || fogmode == "exp" )
                propValue.val = Ogre::Any((int)Ogre::FOG_EXP);
            else if(fogmode == "Exp2" || fogmode == "exp2" )
                propValue.val = Ogre::Any((int)Ogre::FOG_EXP2);
            else
                propValue.val = Ogre::Any(Ogre::StringConverter::parseInt(fogmode));

            params["fog::mode"] = propValue;
            Ogre::Real start = Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("linearStart"),"0"));
            Ogre::Real end = Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("linearEnd"),"1"));

            propValue.propType = PROP_REAL;
            propValue.val = Ogre::Any((Ogre::Real)(start * (vClipping.y - vClipping.x)));
            params["fog::start"] = propValue;
            propValue.val = Ogre::Any((Ogre::Real)(end * (vClipping.y - vClipping.x)));
            params["fog::end"] = propValue;
            propValue.val = Ogre::Any(Ogre::StringConverter::parseReal(ValidAttr(current->Attribute("expDensity"),"0")));
            params["fog::density"] = propValue;
            current = current->FirstChildElement("colourDiffuse");
            if(current)
            {
                params["fogcolour"] = parseColourValue(current);
            }
        }
    }

    propValue.propType = PROP_STRING;
    propValue.val = Ogre::Any(Ogre::String("SceneManager1"));
    params["name"] = propValue;
    CSceneManagerEditor *mngred = static_cast<CSceneManagerEditor*>(ogRoot->CreateEditorObject(0, pOpt->SceneManagerName,params,false,false));

    // read cameras placed outside nodes
    TiXmlElement* otherElems = element->FirstChildElement("camera");
    Ogitors::CBaseEditor* cbeTemp;
    while(otherElems){
        ReadCamera(otherElems, mngred, &cbeTemp);
        otherElems = otherElems->NextSiblingElement("camera");
    }

    // read lights placed outside nodes
    otherElems = element->FirstChildElement("light");
    while(otherElems){
        ReadLight(otherElems, mngred, &cbeTemp);
        otherElems = otherElems->NextSiblingElement("light");
    }

    element = element->FirstChildElement("nodes");

    RecurseReadObjects(element, mngred);
    ogRoot->AfterLoadScene();
    ogRoot->GetViewport()->getCameraEditor()->setClipDistance(vClipping);
    return SCF_OK;
}
Пример #13
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;
}
Пример #14
0
static Ogre::String getExtension(Ogre::String filename)
{
    int dotpos = filename.find_last_of(".");
    if(dotpos == Ogre::String::npos)return "";
    else return filename.substr(dotpos, filename.length() - dotpos);
}
Пример #15
0
/** Callback event when clicking the export menu option. Adds an instance of the
    options dialog as a property, then uses the InspectObj XSI command to pop it up
    in a modal dialog. If it wasn't cancelled, performs an export.
*/
XSI::CStatus OnOgreMeshExportMenu( XSI::CRef& in_ref )
{	
	Ogre::LogManager logMgr;
	logMgr.createLog("OgreXSIExporter.log", true);
	CString msg(L"OGRE Exporter Version ");
	msg += OGRE_XSI_EXPORTER_VERSION;
	LogOgreAndXSI(msg);

	Application app;
	CStatus st(CStatus::OK);
	Property prop = app.GetActiveSceneRoot().GetProperties().GetItem(exportPropertyDialogName);
	if (prop.IsValid())
	{
		// Check version number
		CString currVersion(prop.GetParameterValue(L"version"));
		if (!currVersion.IsEqualNoCase(OGRE_XSI_EXPORTER_VERSION))
		{
			DeleteObj(exportPropertyDialogName);
			prop.ResetObject();
		}
	}
	if (!prop.IsValid())
	{
		prop = app.GetActiveSceneRoot().AddProperty(exportPropertyDialogName);
		prop.PutParameterValue(L"version", CString(OGRE_XSI_EXPORTER_VERSION));
	}
	
	try
	{
		// Popup Returns true if the command was cancelled otherwise it returns false. 
		CStatus ret = Popup(exportPropertyDialogName,CValue(),L"OGRE Mesh / Skeleton Export",((LONG)siModal),true);
		if (ret == CStatus::OK)
		{
			Ogre::XsiMeshExporter meshExporter;
			Ogre::XsiSkeletonExporter skelExporter;

			// retrieve the parameters
			Parameter param = prop.GetParameters().GetItem(L"objectName");
			CString objectName = param.GetValue();
			param = prop.GetParameters().GetItem( L"targetMeshFileName" );
			Ogre::String meshFileName = XSItoOgre(XSI::CString(param.GetValue()));
			if (meshFileName.empty())
			{
				OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, 
					"You must supply a mesh file name", 
					"OGRE Exporter");
			}
			// fix any omission of '.mesh'
			if (!Ogre::StringUtil::endsWith(meshFileName, ".mesh"))
			{
				meshFileName += ".mesh";
			}
			param = prop.GetParameters().GetItem( L"mergeSubmeshes" );
			bool mergeSubmeshes = param.GetValue();
			param = prop.GetParameters().GetItem( L"exportChildren" );
			bool exportChildren = param.GetValue();
			param = prop.GetParameters().GetItem( L"calculateEdgeLists" );
			bool edgeLists = param.GetValue();
			param = prop.GetParameters().GetItem( L"calculateTangents" );
			bool tangents = param.GetValue();
			param = prop.GetParameters().GetItem( L"tangentSemantic" );
			CString tangentSemStr = param.GetValue();
			Ogre::VertexElementSemantic tangentSemantic = (tangentSemStr == L"t")?
				Ogre::VES_TANGENT : Ogre::VES_TEXTURE_COORDINATES;
			param = prop.GetParameters().GetItem( L"tangentsSplitMirrored" );
			bool tangentsSplitMirrored = param.GetValue();
			param = prop.GetParameters().GetItem( L"tangentsSplitRotated" );
			bool tangentsSplitRotated = param.GetValue();
			param = prop.GetParameters().GetItem( L"tangentsUseParity" );
			bool tangentsUseParity = param.GetValue();
			param = prop.GetParameters().GetItem( L"numLodLevels" );
			long numlods = (LONG)param.GetValue();
			Ogre::XsiMeshExporter::LodData* lodData = 0;
			if (numlods > 0)
			{
				param = prop.GetParameters().GetItem( L"lodDistanceIncrement" );
				float distanceInc = param.GetValue();

				param = prop.GetParameters().GetItem(L"lodQuota");
				CString quota = param.GetValue();

				param = prop.GetParameters().GetItem(L"lodReduction");
				float reduction = param.GetValue();

				lodData = new Ogre::XsiMeshExporter::LodData;
				float currentInc = distanceInc;
				for (int l = 0; l < numlods; ++l)
				{
					lodData->distances.push_back(currentInc);
					currentInc += distanceInc;
				}
				lodData->quota = (quota == L"p") ?
					Ogre::ProgressiveMesh::VRQ_PROPORTIONAL : Ogre::ProgressiveMesh::VRQ_CONSTANT;
				if (lodData->quota == Ogre::ProgressiveMesh::VRQ_PROPORTIONAL)
					lodData->reductionValue = reduction * 0.01;
				else
					lodData->reductionValue = reduction;

			}

			param = prop.GetParameters().GetItem( L"exportSkeleton" );
			bool exportSkeleton = param.GetValue();
			param = prop.GetParameters().GetItem( L"exportVertexAnimation" );
			bool exportVertexAnimation = param.GetValue();
			param = prop.GetParameters().GetItem( L"exportMaterials" );
			bool exportMaterials = param.GetValue();
			param = prop.GetParameters().GetItem( L"copyTextures" );
			bool copyTextures = param.GetValue();

			// create singletons
			Ogre::ResourceGroupManager rgm;
			Ogre::MeshManager meshMgr;
			Ogre::SkeletonManager skelMgr;
			Ogre::MaterialManager matMgr;
			Ogre::DefaultHardwareBufferManager hardwareBufMgr;

			
			// determine number of exportsteps
			size_t numSteps = 3 + OGRE_XSI_NUM_MESH_STEPS;
			if (numlods > 0)
				numSteps++;
			if (edgeLists)
				numSteps++;
			if (tangents)
				numSteps++;
			if (exportSkeleton)
				numSteps += 3;

			Ogre::ProgressManager progressMgr(numSteps);
			
			// Any material prefix? We need that for mesh linking too
			param = prop.GetParameters().GetItem( L"materialPrefix" );
			Ogre::String materialPrefix = XSItoOgre(XSI::CString(param.GetValue()));

			param = prop.GetParameters().GetItem( L"fps" );
			float fps = param.GetValue();
			if (fps == 0.0f)
			{
				OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, 
					"You must supply a valid value for 'FPS'", 
					"OGRE Export");
			}

			Ogre::AnimationList selAnimList;
			if (exportSkeleton || exportVertexAnimation)
			{

				param = prop.GetParameters().GetItem( L"animationList" );
				GridData gd(param.GetValue());
				for (int a = 0; a < gd.GetRowCount(); ++a)
				{
					if (gd.GetCell(ANIMATION_LIST_EXPORT_COL, a) == true)
					{
						Ogre::AnimationEntry ae;
						ae.animationName = XSItoOgre(XSI::CString(gd.GetCell(ANIMATION_LIST_NAME_COL, a)));
						ae.ikSampleInterval = gd.GetCell(ANIMATION_LIST_IKFREQ_COL, a);
						ae.startFrame = (LONG)gd.GetCell(ANIMATION_LIST_START_COL, a);
						ae.endFrame = (LONG)gd.GetCell(ANIMATION_LIST_END_COL, a);
						selAnimList.push_back(ae);
					}
				}
			}

			if (exportSkeleton)
			{
				param = prop.GetParameters().GetItem( L"targetSkeletonFileName" );
				Ogre::String skeletonFileName = XSItoOgre(XSI::CString(param.GetValue()));
				if (skeletonFileName.empty())
				{
					OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, 
						"You must supply a skeleton file name", 
						"OGRE Exporter");
				}

				// fix any omission of '.skeleton'
				if (!Ogre::StringUtil::endsWith(skeletonFileName, ".skeleton"))
				{
					skeletonFileName += ".skeleton";
				}

				// Truncate the skeleton filename to just the name (no path)
				Ogre::String skelName = skeletonFileName;
				int pos = skeletonFileName.find_last_of("\\");
				if (pos == Ogre::String::npos)
				{
					pos = skeletonFileName.find_last_of("/");
				}
				if (pos != Ogre::String::npos)
				{
					skelName = skelName.substr(pos+1, skelName.size() - pos - 1);
				}


				// Do the mesh
				Ogre::DeformerMap& deformers = 
					meshExporter.buildMeshForExport(mergeSubmeshes, 
						exportChildren, edgeLists, tangents, tangentSemantic, 
						tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity,
						exportVertexAnimation, selAnimList, fps, materialPrefix,
						lodData, skelName);
				// do the skeleton
				const Ogre::AxisAlignedBox& skelAABB = 
					skelExporter.exportSkeleton(skeletonFileName, deformers, fps, selAnimList);

				// Do final mesh export
				meshExporter.exportMesh(meshFileName, skelAABB);
			}
			else
			{
				Ogre::AxisAlignedBox nullbb;
				// No skeleton
				meshExporter.buildMeshForExport(mergeSubmeshes, 
					exportChildren, edgeLists, tangents, tangentSemantic, 
					tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity,
					exportVertexAnimation, selAnimList, fps, materialPrefix, lodData);
				meshExporter.exportMesh(meshFileName, nullbb);
			}

			
			delete lodData;

			// Do we want to export materials too?
			if (exportMaterials)
			{
				param = prop.GetParameters().GetItem( L"targetMaterialFileName" );
				Ogre::String materialFileName = XSItoOgre(XSI::CString(param.GetValue()));
				// fix any omission of '.material'
				if (!Ogre::StringUtil::endsWith(materialFileName, ".material"))
				{
					materialFileName += ".material";
				}
				
				Ogre::XsiMaterialExporter matExporter;
				try 
				{
					matExporter.exportMaterials(meshExporter.getMaterials(), 
						meshExporter.getTextureProjectionMap(), 
						materialFileName, copyTextures);
				}
				catch (Ogre::Exception& e)
				{
					// ignore, non-fatal and will be in log
				}
			}

		}

	}
	catch (Ogre::Exception& e)
	{
		// Will already have been logged to the Ogre log manager
		// Tell XSI
		app.LogMessage(OgretoXSI(e.getDescription()), XSI::siFatalMsg);
		app.LogMessage(OgretoXSI(e.getFullDescription()), XSI::siInfoMsg);
	}

	//DeleteObj( L"OgreMeshExportOptions" );
	return st;	
}