//-----------------------------------------------------------------------------------------
CBaseEditor *CTerrainGroupEditorFactory::CreateObject(CBaseEditor **parent, OgitorsPropertyValueMap &params)
{
    OgitorsRoot* ogitorsRoot = OgitorsRoot::getSingletonPtr();
    OgitorsPropertyValueMap::iterator ni;

    if ((ni = params.find("init")) != params.end())
    {
        addEditorResources();
        params.erase(ni);
    }

    /* Check for old 0.4 and 0.5 files that do not include the terrain textures */
    OFS::OfsPtr& file = ogitorsRoot->GetProjectFile();
    Ogre::String terrainDir = ogitorsRoot->GetProjectOptions()->TerrainDirectory;

    unsigned int flags;
    if (file->getDirFlags((terrainDir).c_str(), flags) == OFS::OFS_OK &&
        file->getDirFlags((terrainDir+"/terrain/").c_str(), flags) != OFS::OFS_OK)
    {
        // must check the both dirs exist otherwise it could possibly be a new project
        file->moveDirectory((terrainDir).c_str(), (terrainDir+"/terrain/").c_str());
        addEditorResources(false);
    }

    CTerrainGroupEditor *object = OGRE_NEW CTerrainGroupEditor(this);

    object->createProperties(params);
    object->mParentEditor->init(*parent);
    object->load();

    mInstanceCount++;
    return object;
}
Beispiel #2
0
//-----------------------------------------------------------------------------------------
CBaseEditor *CSkyxEditorFactory::CreateObject(CBaseEditor **parent, OgitorsPropertyValueMap &params)
{
  OgitorsRoot *ogroot = OgitorsRoot::getSingletonPtr();
  Ogre::ResourceGroupManager *mngr = Ogre::ResourceGroupManager::getSingletonPtr();
  Ogre::String value = ogroot->GetProjectOptions()->ProjectDir + "/SkyX/";

  CSkyxEditor *object = OGRE_NEW CSkyxEditor(this);

  if(params.find("init") != params.end())
  {
    Ogre::String dirname = OgitorsUtils::QualifyPath(value);
    OgitorsSystem::getSingletonPtr()->MakeDirectory(dirname);
    Ogre::String copydir = OgitorsUtils::GetEditorResourcesPath() + "/SKYX/*";
    OgitorsSystem::getSingletonPtr()->CopyFilesEx(copydir,dirname);

    params.erase(params.find("init"));
  }

  object->createProperties(params);
  object->mParentEditor->init(*parent);
  object->load();
  object->update(0);

  mInstanceCount++;
  return object;
}
//-----------------------------------------------------------------------------------------
void CTerrainGroupEditorFactory::addEditorResources(bool changeDefaultNames)
{
    OgitorsRoot* ogitorsRoot = OgitorsRoot::getSingletonPtr();
    Ogre::String terrainDir = ogitorsRoot->GetProjectOptions()->TerrainDirectory;
    // create Terrain project folder and folder to hold the terrain
    ogitorsRoot->GetProjectFile()->createDirectory(terrainDir.c_str());
    ogitorsRoot->GetProjectFile()->createDirectory((terrainDir+"/terrain/").c_str());

    // copy default plant textures
    ogitorsRoot->GetProjectFile()->createDirectory((terrainDir+"/plants/").c_str());
    Ogre::String copydir = Ogitors::Globals::MEDIA_PATH + "/plants/";
    OgitorsUtils::CopyDirOfs(copydir, (terrainDir+"/plants/").c_str());

    // copy default terrain textures sorting them into two different folders
    ogitorsRoot->GetProjectFile()->createDirectory((terrainDir+"/textures/").c_str());
    ogitorsRoot->GetProjectFile()->createDirectory((terrainDir+"/textures/diffusespecular").c_str());
    ogitorsRoot->GetProjectFile()->createDirectory((terrainDir+"/textures/normalheight").c_str());

    Ogre::ResourceGroupManager *mngr = Ogre::ResourceGroupManager::getSingletonPtr();
    copydir = Ogitors::Globals::MEDIA_PATH + "/terrainTextures/";
    mngr->addResourceLocation(copydir,"FileSystem","CopyTerrain");

    Ogre::FileInfoListPtr resList = mngr->listResourceFileInfo("CopyTerrain");

    // copy the files to the different directories
    OFS::OfsPtr& file = ogitorsRoot->GetProjectFile();
    for (Ogre::FileInfoList::const_iterator it = resList->begin(); it != resList->end(); ++it)
    {
        Ogre::FileInfo fInfo = (*it);
        Ogre::String loc = copydir + fInfo.path + fInfo.filename;
        Ogre::String newName = fInfo.filename;
        
        if(fInfo.archive->getType() == "FileSystem")
        {
            if(fInfo.filename.find("diffusespecular") != -1)
            {
                /* since we're using different resource groups for the terrain lets
                remove the naming scheme from the filenames except if the project
                is being upgraded, in which case leave the name alone. */
                if (changeDefaultNames) {
                    newName = Ogre::StringUtil::replaceAll(newName, "_diffusespecular", "");
                }
                OgitorsUtils::CopyFileOfs(loc, terrainDir+"/textures/diffusespecular/"+newName);
            }
            
            if(fInfo.filename.find("normalheight") != -1)
            {
                if (changeDefaultNames) {
                    newName = Ogre::StringUtil::replaceAll(newName, "_normalheight", "");
                }
                OgitorsUtils::CopyFileOfs(loc, terrainDir+"/textures/normalheight/"+newName);
            }
        }
    }
    resList.setNull();
    
    ogitorsRoot->DestroyResourceGroup("CopyTerrain");
}
Beispiel #4
0
//-----------------------------------------------------------------------------
int COFSSceneSerializer::_writeFile(Ogre::String exportfile, const bool forceSave)
{
    if (exportfile.empty())
        return SCF_ERRUNKNOWN;

    OgitorsRoot *ogRoot = OgitorsRoot::getSingletonPtr();
    // Open a stream to output our XML Content and write the general headercopyFile
    std::stringstream outfile;

    outfile << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    outfile << "<OGITORSCENE version=\"" << Globals::OGSCENE_FORMAT_VERSION << "\">\n";

    PROJECTOPTIONS *pOpt = ogRoot->GetProjectOptions();
    pOpt->CameraSpeed = ogRoot->GetViewport()->GetCameraSpeed();

    ogRoot->WriteProjectOptions(outfile, pOpt);

    ObjectVector ObjectList;
    OgitorsPropertyValueMap theList;
    OgitorsPropertyValueMap::iterator ni;

    // Start from 1, since 0 means all objects
    for(unsigned int i = 1; i < LAST_EDITOR; i++)
    {
        ogRoot->GetObjectList(i, ObjectList);
        for(unsigned int ob = 0; ob < ObjectList.size(); ob++)
        {
            /// If Object does not have a parent, then it is not part of the scene
            if(ObjectList[ob]->getParent())
            {
                ObjectList[ob]->onSave(forceSave);
                if(ObjectList[ob]->isSerializable())
                {
                    outfile << OgitorsUtils::GetObjectSaveStringV2(ObjectList[ob], 2, true, true).c_str();
                    outfile << "\n";
                }
            }
        }
    }
    outfile << "</OGITORSCENE>\n";

    if (OgitorsUtils::SaveStreamOfs(outfile, exportfile)) {
        return SCF_OK;
    }

    return SCF_ERRFILE;
}
//-----------------------------------------------------------------------------------------
bool CRoadPointEditor::load(bool async)
{
	if(mLoaded->get())
        return true;
  
    mHandle = getParent()->getNode()->createChildSceneNode(mName->get(), mPosition->get(), mOrientation->get());

	// Once road has been created, position it ON the terrain
	// Get terrain editor
	OgitorsRoot *mOgitorsRoot = OgitorsRoot::getSingletonPtr();

	try
	{
		mEntityHandle = mOgitorsRoot->GetSceneManager()->createEntity(mName->get(), "scbRoadPoint.mesh");
	}
	catch(...)
	{
		mEntityHandle = mOgitorsRoot->GetSceneManager()->createEntity(mName->get(), "missing_mesh.mesh");
		mEntityHandle->setMaterialName("MAT_GIZMO_X_L");
	}

	mHandle->attachObject(mEntityHandle);
	mEntityHandle->setQueryFlags(QUERYFLAG_MOVABLE);

	if(mOgitorsRoot->GetTerrainEditor() != NULL)
	{
		CONNECT_PROPERTY_MEMFN(this, "position", CRoadPointEditor, OnRoadPointPositionChange, mPointConnection);

		Ogitors::PGHeightFunction *func = mOgitorsRoot->GetTerrainEditor()->getHeightFunction();

		// Get height at the XZ location and change node' Y value (example of camera walk - walk height is 0 to be exactly on the terrain surface)
		Real TerrainY = 0 + (*func)(getDerivedPosition().x, getDerivedPosition().z, 0);
		// Compose vector that is positioned on the terrain (Y value)
		Vector3 TerrainPosition = Vector3(mHandle->getPosition().x, (TerrainY - getDerivedPosition().y) + mHandle->getPosition().y, mHandle->getPosition().z);

		// Invoke update to re-tesselate Road with all points
		OnRoadPointPositionChange(mPosition, Ogre::Any(TerrainPosition));
	}

	mLoaded->set(true);
    return true;
}
//----------------------------------------------------------------------------------------
int CDotSceneSerializer::Export(bool SaveAs, Ogre::String exportfile)
{
    OgitorsRoot *ogRoot = OgitorsRoot::getSingletonPtr();
    OgitorsSystem *mSystem = OgitorsSystem::getSingletonPtr();

    PROJECTOPTIONS *pOpt = ogRoot->GetProjectOptions();
    Ogre::String fileName = pOpt->ProjectName;

    UTFStringVector extlist;
    extlist.push_back(OTR("DotScene File"));
    extlist.push_back("*.scene");
    extlist.push_back(OTR("DotScene File"));
    extlist.push_back("*.xml");
    fileName = mSystem->DisplaySaveDialog(OTR("Export DotScene File"),extlist);
    if(fileName == "")
        return SCF_CANCEL;

    Ogre::String newDir = OgitorsUtils::ExtractFilePath(fileName);

    extractOFS(newDir);
    mSystem->DeleteFile(newDir + "/" + pOpt->ProjectName + ".ogscene");

    TiXmlDocument *pXMLDoc = new TiXmlDocument();
    pXMLDoc->InsertEndChild(TiXmlDeclaration("1.0", "UTF-8", ""));
    pXMLDoc->InsertEndChild(TiXmlElement("scene"));

    // export basic info
    TiXmlElement *pRoot = pXMLDoc->RootElement();
    pRoot->SetAttribute("formatVersion", "1.0.0");
    pRoot->SetAttribute("generator", Ogre::String(Ogre::String("Ogitor SceneBuilder ") + Ogre::String(OGITOR_VERSION)).c_str());

    // export resource locations
    TiXmlElement *pResourceLocations = pRoot->InsertEndChild(TiXmlElement("resourceLocations"))->ToElement();

    for(unsigned int r = 0; r < pOpt->ResourceDirectories.size(); r++)
    {
        TiXmlElement *pResourceLocation = pResourceLocations->InsertEndChild(TiXmlElement("resourceLocation"))->ToElement();
        Ogre::String loc = pOpt->ResourceDirectories[r];

        pResourceLocation->SetAttribute("type", "FileSystem");

        std::replace(loc.begin(),loc.end(),'\\','/');

        if(loc[0] != '.')
            loc = "./" + loc;

        pResourceLocation->SetAttribute("name", loc.c_str());
    }

    //TODO: do we need all those object id's ?

    TiXmlElement *pEnvironment = pRoot->InsertEndChild(TiXmlElement("environment"))->ToElement();

    // export octree scenemanagers
    NameObjectPairList smList = ogRoot->GetObjectsByTypeName("OctreeSceneManager");
    NameObjectPairList::const_iterator smIt = smList.begin();
    while(smIt != smList.end())
    {
        TiXmlElement *result = smIt->second->exportDotScene(pEnvironment);
        saveUserData(smIt->second->getCustomProperties(), result);
        smIt++;
    }

    // export viewports
    NameObjectPairList vpList = ogRoot->GetObjectsByTypeName("Viewport Object");
    NameObjectPairList::const_iterator vpIt = vpList.begin();
    while(vpIt != vpList.end())
    {
        TiXmlElement *result = vpIt->second->exportDotScene(pEnvironment);
        saveUserData(vpIt->second->getCustomProperties(), result);
        vpIt++;
    }

    // export terrains
    NameObjectPairList terrainList = ogRoot->GetObjectsByType(ETYPE_TERRAIN_MANAGER);
    NameObjectPairList::const_iterator tlIt = terrainList.begin();
    while(tlIt != terrainList.end())
    {
        TiXmlElement *result = tlIt->second->exportDotScene(pRoot);
        saveUserData(tlIt->second->getCustomProperties(), result);
        tlIt++;
    }

    NameObjectPairList items = ogRoot->GetSceneManagerEditor()->getChildren();

    // export lights
    NameObjectPairList::const_iterator nodeIt = items.begin();

    while(nodeIt != items.end())
    {
        if(nodeIt->second->getEditorType() == ETYPE_LIGHT)
        {
            TiXmlElement *result = nodeIt->second->exportDotScene(pRoot);
            saveUserData(nodeIt->second->getCustomProperties(), result);
        }
        nodeIt++;
    }

    // export cameras
    nodeIt = items.begin();

    while(nodeIt != items.end())
    {
        if(nodeIt->second->getEditorType() == ETYPE_CAMERA)
        {
            TiXmlElement *result = nodeIt->second->exportDotScene(pRoot);
            saveUserData(nodeIt->second->getCustomProperties(), result);
        }
        nodeIt++;
    }

    // export nodes
    TiXmlElement *pNodes = pRoot->InsertEndChild(TiXmlElement("nodes"))->ToElement();
    nodeIt = items.begin();

    while(nodeIt != items.end())
    {
        if( nodeIt->second->getEditorType() != ETYPE_TERRAIN_MANAGER &&
                nodeIt->second->getEditorType() != ETYPE_LIGHT &&
                nodeIt->second->getEditorType() != ETYPE_CAMERA )
        {
            TiXmlElement *result = nodeIt->second->exportDotScene(pNodes);
            saveUserData(nodeIt->second->getCustomProperties(), result);
        }
        nodeIt++;
    }

    if (pXMLDoc->SaveFile(fileName.c_str()))
    {
        OgitorsSystem::getSingletonPtr()->DisplayMessageDialog(OTR("Scene has been exported succesfully"), DLGTYPE_OK);
        delete pXMLDoc;
    }
    else
        OgitorsSystem::getSingletonPtr()->DisplayMessageDialog(OTR("An error occured during export.. :("), DLGTYPE_OK);

    return SCF_OK;
}
Beispiel #7
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;
}
Beispiel #8
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;
}
//----------------------------------------------------------------------------
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;
}