Exemple #1
0
	void Zone::addSound(const Ogre::String& sound)
	{
		if (sound.length() > 0)
		{
			mSounds.push_back(sound);
		}
	}
void MaterialEditor::OnNewMaterial(wxCommandEvent &e)
{
	NewMaterialDialog *dlg = new NewMaterialDialog(this, wxID_ANY,
		wxT("新建材质"));

	bool ok = (dlg->ShowModal() == wxID_OK);
	if(ok)
	{
		const Ogre::String templateName = dlg->mTextCtrl->GetValue().c_str();

		if(templateName.length() == 0)
		{
			dlg->Destroy();
			return;
		}
		Ogre::MaterialPtr pMaterial= Ogre::MaterialManager::getSingleton().getByName(templateName);
		//Ogre::MaterialPtr *pMaterial;
		if(pMaterial.isNull())
			pMaterial = Ogre::MaterialManager::getSingleton().create(templateName,"General");
		

		InitMaterialEditor(pMaterial,templateName);
		m_Frame->GetEffectObjectProperty()->InitMaterialEditor(pMaterial,templateName);

	}
	dlg->Destroy();

}
//----------------------------------------------------------------------------//
void OgreResourceProvider::loadRawDataContainer(const String& filename,
                                                RawDataContainer& output,
                                                const String& resourceGroup)
{
    String orpGroup;
    if (resourceGroup.empty())
        orpGroup = d_defaultResourceGroup.empty() ?
            Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str() :
            d_defaultResourceGroup;
    else
        orpGroup = resourceGroup;

    Ogre::DataStreamPtr input = Ogre::ResourceGroupManager::getSingleton().
        openResource(filename.c_str(), orpGroup.c_str());

    if (input.isNull())
        CEGUI_THROW(InvalidRequestException(
            "Unable to open resource file '" + filename +
            "' in resource group '" + orpGroup + "'."));

    Ogre::String buf = input->getAsString();
    const size_t memBuffSize = buf.length();

    unsigned char* mem = new unsigned char[memBuffSize];
    memcpy(mem, buf.c_str(), memBuffSize);

    output.setData(mem);
    output.setSize(memBuffSize);
}
Exemple #4
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;
}
	//-----------------------------------------------------------------------
	void ParticleRenderer::_stripNameFromSoftPrefix(Ogre::String& name)
	{
		if (name.find(SOFT_PREFIX) != Ogre::String::npos)
		{
			// Remove the prefix
			name.erase(0, SOFT_PREFIX.length());
		}
	}
void Logger::log(const Ogre::String& component, const Logger::LogLevel level, 
			const char* message, const Ogre::String& ident)
{
	if (ident.length() == 0)
		log(level, "[" + component + "] " + message);
	else
		log(level, "[" + component + "] (" + ident + ") " + message);
}
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();
}
void OgreConsole::print(const Ogre::String &text)
{
   //subdivide it into lines
   const char *str=text.c_str();
   int len=text.length();
   Ogre::String line;
   for(int c=0;c<len;c++){
      if(str[c]=='\n'||line.length()>=CONSOLE_LINE_LENGTH){
         lines.push_back(line);
         line="";
      }
      if(str[c]!='\n')
         line+=str[c];
   }
   if(line.length())
      lines.push_back(line);
   if(lines.size()>CONSOLE_LINE_COUNT)
      mStartline=lines.size()-CONSOLE_LINE_COUNT;
   else
      mStartline=0;
   mUpdateConsole=true;
}
bool OgreSubsystem::LoadOgrePlugins(Ogre::String const & pluginsfile)
{
	Ogre::StringVector pluginList;
	Ogre::String pluginDir;
	Ogre::ConfigFile cfg;

	try
	{
		cfg.load( pluginsfile );
	}
	catch (Ogre::Exception)
	{
		Ogre::LogManager::getSingleton().logMessage(pluginsfile + " not found, automatic plugin loading disabled.");
		return false;
	}

	pluginDir = cfg.getSetting("PluginFolder"); // Ignored on Mac OS X, uses Resources/ directory
	pluginList = cfg.getMultiSetting("Plugin");

#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE && OGRE_PLATFORM != OGRE_PLATFORM_IPHONE
	if (pluginDir.empty())
	{
		// User didn't specify plugins folder, try current one
		pluginDir = ".";
	}
#endif

	char last_char = pluginDir[pluginDir.length()-1];
	if (last_char != '/' && last_char != '\\')
	{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		pluginDir += "\\";
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
		pluginDir += "/";
#endif
	}

	for ( Ogre::StringVector::iterator it = pluginList.begin(); it != pluginList.end(); ++it )
	{
		Ogre::String pluginFilename = pluginDir + (*it);
		try
		{
			m_ogre_root->loadPlugin(pluginFilename);
		} 
		catch(Ogre::Exception &e)
		{
			LOG("failed to load plugin: " + pluginFilename + ": " + e.getFullDescription());
		}
	}
	return true;
}
Exemple #10
0
    //----------------------------------------------------------------------------------
    bool GameObject::removeFlag(Ogre::String flag)
    {
	    std::string::size_type pos1 = mFlags.find("|" + flag + "|");

	    if (pos1 == Ogre::String::npos)
	    {
		    return false;
	    }

	    ++pos1;
	    std::string::size_type pos2 = flag.length() + 1;

	    mFlags.erase(pos1, pos2);

	    return true;
    }
Exemple #11
0
void Manager::saveUser(const std::string& file)
{
    bfs::ofstream fout((bfs::path(file)));

    Ogre::ConfigFile::SectionIterator seci = mFile.getSectionIterator();

    while (seci.hasMoreElements())
    {
        Ogre::String sectionName = seci.peekNextKey();

        if (sectionName.length() > 0)
            fout << '\n' << '[' << seci.peekNextKey() << ']' << '\n';

        Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
        Ogre::ConfigFile::SettingsMultiMap::iterator i;
        for (i = settings->begin(); i != settings->end(); ++i)
        {
            fout << i->first.c_str() << " = " << i->second.c_str() << '\n';
        }

        CategorySettingValueMap::iterator it = mNewSettings.begin();
        while (it != mNewSettings.end())
        {
            if (it->first.first == sectionName)
            {
                fout << it->first.second << " = " << it->second << '\n';
                mNewSettings.erase(it++);
            }
            else
                ++it;
        }
    }

    std::string category = "";
    for (CategorySettingValueMap::iterator it = mNewSettings.begin();
            it != mNewSettings.end(); ++it)
    {
        if (category != it->first.first)
        {
            category = it->first.first;
            fout << '\n' << '[' << category << ']' << '\n';
        }
        fout << it->first.second << " = " << it->second << '\n';
    }

    fout.close();
}
MovableTextOverlayAttributes::MovableTextOverlayAttributes(const Ogre::String & name, const Ogre::Camera *cam,
						 const Ogre::String & fontName, int charHeight, const Ogre::ColourValue & color, const Ogre::String & materialName)
: mpCam(cam)
, mpFont(NULL)
, mName(name)
, mFontName("")
, mMaterialName("")
, mCharHeight(charHeight)
, mColor(ColourValue::ZERO)
{
	if (fontName.length() == 0)
        Ogre::Exception(Ogre::Exception::ERR_INVALIDPARAMS, "Invalid font name", "MovableTextOverlayAttributes::MovableTextOverlayAttributes");

	setFontName(fontName);
	setMaterialName(materialName);
	setColor(color);
}
Exemple #13
0
CChest::CChest(Ogre::SceneNode *pNode, CObjectManager &objectManager, btCollisionObject *pCollisionObject, EChestType eChestType, const Ogre::String &id)
	: CObject(objectManager, CHEST_OBJECT, pCollisionObject, id), m_eChestType(eChestType) {

	m_eChestState = CS_CLOSED;
	//setInnerObject(&innerObject);
	m_pInnerObject = NULL;

	m_pLidSceneNode = objectManager.getMap().getRootSceneNode()->createChildSceneNode();
	m_pLidSceneNode->setPosition(pNode->getPosition());
	m_pLidSceneNode->setOrientation(pNode->getOrientation());
	m_pLidSceneNode->setScale(pNode->getScale());
	m_vInnerObjectPos = m_pLidSceneNode->getPosition();
	btCollisionShape *pColShape(0);
	switch (m_eChestType) {
	case CT_SMALL:
		m_pLidSceneNode->attachObject(pNode->getCreator()->createEntity("Chest.Small.Upper.mesh"));
		m_pLidSceneNode->translate(0, 0.37465f, -0.30862f, Ogre::Node::TS_LOCAL);
		m_vInnerObjectPos += m_pLidSceneNode->getOrientation() * Ogre::Vector3(0, 0.15f, 0);
		pColShape = new btBoxShape(btVector3(0.3f, 0.08f, 0.2f));
		m_vPhysicsOffset = Ogre::Vector3(0, 0.15f, 0.25f);
		break;
	default:
		throw Ogre::Exception(0, "Unknown chest type", __FILE__);
		break;
	}
	m_pLidPhysics = new btRigidBody(0, new btDefaultMotionState(), pColShape);
	m_pLidPhysics->getWorldTransform().setOrigin(BtOgre::Convert::toBullet(m_pLidSceneNode->getPosition() + m_pLidSceneNode->getOrientation() * m_vPhysicsOffset));
	m_pLidPhysics->getWorldTransform().setRotation(BtOgre::Convert::toBullet(m_pLidSceneNode->getOrientation()));

	m_ObjectManager.getMap().getPhysicsManager()->getWorld()->addRigidBody(m_pLidPhysics, COL_STATIC, MASK_STATIC_COLLIDES_WITH);

	// check for safe state
	if (id.length() > 0) {
        EItemSaveState iss = CPlayerData::getSingleton().getMapItemState(m_ObjectManager.getMap().getName(), id, ISS_CLOSED);
        if (iss == ISS_OPENED) {
            // open chest as initial state
            m_eChestState = CS_OPENED;
            m_pLidSceneNode->pitch(Ogre::Radian(-CHEST_MAX_ANGLE));
            m_pLidPhysics->getWorldTransform().setOrigin(BtOgre::Convert::toBullet(m_pLidSceneNode->getPosition() + m_pLidSceneNode->getOrientation() * m_vPhysicsOffset));
            m_pLidPhysics->getWorldTransform().setRotation(BtOgre::Convert::toBullet(m_pLidSceneNode->getOrientation()));
        }
    }
}
void wxObjectFolderTree::OnSelectItemCallback()
{
	ClearObjectPreview();
	if (mCurrentItem->IsRoot()) return;
	mCurrentPath = Ogre::String(GetRelativePath(mCurrentItem->GetId()).GetPath().c_str()) + PATH_SEPERATOR;
	if (mCurrentItem->IsFile())
	{
		Ogre::String Path = "Data/Editor/Objects/" + Ogre::String(GetRelativePath(mCurrentItem->GetId()).GetPath().c_str()) + PATH_SEPERATOR;
		Ogre::String File = mCurrentItem->GetName().c_str();
		mCurrentPath += File;
		Ogre::String extension = File.substr(File.find(".")+1, File.length());
		wxEdit::Instance().GetOgrePane()->OnSelectResource();

		if (extension == "ocs" && wxEdit::Instance().GetWorldExplorer()->GetSelection() == 1)
		{
			CreateObjectPreview(Path + File);
			((wxEditGOResource*)(wxEdit::Instance().GetpropertyWindow()->SetPage("EditGOCRes")))->SetResource(Path + File);
		}
	}
}
    void 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 ObjectsViewWidget::prepareView()
{
    listWidget->clear();

    Ogre::String filename;
    Ogre::String itemname;

    Ogitors::EditorObjectFactoryMap objects = Ogitors::OgitorsRoot::getSingletonPtr()->GetEditorObjectFactories();
    Ogitors::EditorObjectFactoryMap::iterator it = objects.begin();

    while(it != objects.end())
    {

        if(it->second && it->second->mAddToObjectList) 
        {
            if(it->second->mIcon != "") 
                filename = "../Plugins/" + it->second->mIcon;

            itemname = it->second->mTypeName;

            itemname.erase(itemname.length() - 7,7);

            filename = OgitorsUtils::QualifyPath(filename);

            QListWidgetItem *item = new QListWidgetItem(QIcon(QString(filename.c_str())), QString(itemname.c_str()), listWidget);
            item->setWhatsThis(it->second->mTypeName.c_str());
            listWidget->addItem(item);
        }

        it++;
      }

    listWidget->setGridSize(QSize(64,70));

    mTimer = new QTimer(this);
    mTimer->setInterval(1000);
    connect(mTimer, SIGNAL(timeout()), this, SLOT(updateView()));
    mTimer->start();
}
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());
}
void SkillObjectEditor::OnSaveAsSkillObject(wxCommandEvent &e)
{
	if (NULL == mSkill)
	{
		wxMessageBox("您还没有创建技能,请创建后重试!","提示");
		return;
	}

	SaveAsSkillDialog *dlg = new SaveAsSkillDialog(this, wxID_ANY,
		_("另存技能"), mSkill);

	bool ok = (dlg->ShowModal() == wxID_OK);
	if(ok)
	{
		Ogre::StringVector templates;

		Ogre::String fileName = dlg->mComboBox->GetValue().c_str();
		Ogre::String templateName = dlg->mTextCtrl->GetValue().c_str();

		if(templateName.length() == 0)
		{
			dlg->Destroy();
			return;
		}

		//判断文件名
		Ogre::StringVector strings = Ogre::StringUtil::split( fileName, "." );
		if (strings.size() != 2 || strings[1] != "skill")
		{
			fileName.append(".skill");
		}

		Fairy::EffectManager::getSingleton().getSkillTemplatesFromScriptFile(fileName, templates);

		std::ofstream outFile;

		Ogre::String pathFileName = EFFECT_PATH+fileName;
		outFile.open ( pathFileName.c_str(), std::ios::out | std::ios::trunc ); // append to file

		if (!outFile.is_open())
		{
			dlg->Destroy();
			return;
		}

		bool newTemplate = true;


		// 把所有的模板都写入该文件中
		for ( size_t i=0; i<templates.size(); ++i )
		{
			//	if (templates[i] != mEffect->getTemplateName())
			///{
			Fairy::Skill *skill = Fairy::EffectManager::getSingleton().getSkill(templates[i]);
			assert (skill);

			if (skill->getSkillName() == dlg->mTextCtrl->GetValue().c_str())
			{
				saveSkill(mSkill, dlg->mTextCtrl->GetValue().c_str(), outFile );


				newTemplate = false;
			}
			else
				saveSkill(skill, skill->getSkillName(), outFile);

		}

		if (newTemplate)
		{
			
			// 刷新EffectManager中的模板内容
			Fairy::Skill *skill = Fairy::EffectManager::getSingleton().getSkill(templateName);
			if (NULL == skill)
			{
				skill = Fairy::EffectManager::getSingleton().createSkillTemplate(templateName);
			}

			*skill = *mSkill;

			saveSkill(skill, templateName, outFile );

			Fairy::EffectManager::getSingleton().addToSkillTemplateScriptFileMap(templateName, fileName);

			InitSkillEditor(skill, templateName);
		}

		outFile.close();
	}

	wxBusyInfo* busyInfo = new wxBusyInfo(wxT("更新技能数据 ..."), this);
	m_Frame->GetSkillSelector()->Reload();
	delete busyInfo;

	dlg->Destroy();

}
bool OgreMaterialResource::SetData(Foundation::AssetPtr source)
{
    // Remove old material if any
    RemoveMaterial();
    references_.clear();
    original_textures_.clear();

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

        }

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

        return false;
    }
    return true;
}
bool OgreParticleAsset::DeserializeFromData(const u8 *data_, size_t numBytes)
{
    RemoveTemplates();
    references_.clear();

    if (!data_)
    {
        OgreRenderer::OgreRenderingModule::LogError("Null source asset data pointer");
        return false;
    }
    if (numBytes == 0)
    {
        OgreRenderer::OgreRenderingModule::LogError("Zero sized particle system asset");
        return false;
    }

    // Detected template names
    StringVector new_templates;

    std::vector<u8> tempData(data_, data_ + numBytes);
#include "DisableMemoryLeakCheck.h"
    Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&tempData[0], numBytes));
#include "EnableMemoryLeakCheck.h"
    try
    {
        int brace_level = 0;
        bool skip_until_next = false;
        int skip_brace_level = 0;
        // Parsed/modified script
        std::ostringstream output;

        while (!data->eof())
        {
            Ogre::String line = data->getLine();
            // Skip empty lines & comments
            if ((line.length()) && (line.substr(0, 2) != "//"))
            {
                // Split line to components
                std::vector<Ogre::String> line_vec;

#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6
                line_vec = Ogre::StringUtil::split(line, "\t ");
#else
                Ogre::vector<Ogre::String>::type vec = Ogre::StringUtil::split(line,"\t ");
                int size = vec.size();
                line_vec.resize(size);

                for (int i = 0; i < size; ++i)
                    line_vec[i] = vec[i];
#endif

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

                // Process opening/closing braces
                if (!ProcessBraces(line, brace_level))
                {
                    // If not a brace and on level 0, it should be a new particlesystem; replace name with resource ID + ordinal
                    if (brace_level == 0)
                    {
                        line = SanitateAssetIdForOgre(this->Name().toStdString()) + "_" + boost::lexical_cast<std::string>(new_templates.size());
                        new_templates.push_back(line);
                        // New script compilers need this
                        line = "particle_system " + line;
                    }
                    else
                    {
                        // Check for ColourImage, which is a risky affector and may easily crash if image can't be loaded
                        if (line_vec[0] == "affector")
                        {
                            if (line_vec.size() >= 2)
                            {
                                if (line_vec[1] == "ColourImage")
                                {
                                    skip_until_next = true;
                                    skip_brace_level = brace_level;
                                }
                            }
                        }
                        // Check for material definition
                        else if (line_vec[0] == "material")
                        {
                            if (line_vec.size() >= 2)
                            {
                                // Tundra: we only support material refs in particle scripts
                                std::string mat_name = line_vec[1];
                                ///\todo The design of whether the LookupAssetRefToStorage should occur here, or internal to Asset API needs to be revisited.
                                references_.push_back(AssetReference(assetAPI->LookupAssetRefToStorage(mat_name.c_str())));
                                line = "material " + SanitateAssetIdForOgre(mat_name);
                            }
                        }
                    }
                    // Write line to the copy
                    if (!skip_until_next)
                    {
                        output << line << std::endl;
                    }
                    else
                        OgreRenderer::OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
                }
                else
                {
                    // Write line to the copy
                    if (!skip_until_next)
                    {
                        output << line << std::endl;
                    }
                    else
                        OgreRenderer::OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);

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

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

    // Check which templates actually succeeded
    for (uint i = 0; i < new_templates.size(); ++i)
    {
        if (Ogre::ParticleSystemManager::getSingleton().getTemplate(new_templates[i]))
        {
            templates_.push_back(new_templates[i]);
            OgreRenderer::OgreRenderingModule::LogDebug("Ogre particle system template " + new_templates[i] + " created");
        }
    }

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

    // Theoretical success if at least one template was created
    return GetNumTemplates() > 0;
}
Exemple #21
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);
}
void ZoneListWidget::_createImages(ImageMap& retlist)
{
    retlist.clear();

    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual( "EntityTex",
                   Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,
                   256, 256, 0, Ogre::PF_A8R8G8B8 , Ogre::TU_RENDERTARGET );

    Ogre::RenderTexture *rttTex = texture->getBuffer()->getRenderTarget();
    Ogre::SceneManager *mSceneMgr = Ogre::Root::getSingletonPtr()->createSceneManager("OctreeSceneManager", "EntityTexMgr");

    Ogre::Light *dirl = mSceneMgr->createLight("DisplayLight");
    dirl->setDirection(-1,-1,-1);
    dirl->setDiffuseColour(1,1,1);
    dirl->setType(Ogre::Light::LT_DIRECTIONAL);

    Ogre::Camera* RTTCam = mSceneMgr->createCamera("EntityCam");
    RTTCam->setNearClipDistance(0.01F);
    RTTCam->setFarClipDistance(0);
    RTTCam->setAspectRatio(1);
    RTTCam->setFOVy(Ogre::Degree(90));
    RTTCam->setPosition(0,0,1);
    RTTCam->lookAt(0,0,0);

    Ogre::Viewport *v = rttTex->addViewport( RTTCam );
    v->setClearEveryFrame( true );
    v->setBackgroundColour(Ogre::ColourValue(0,0,0,0));

    ModularZoneFactory* factory = dynamic_cast<ModularZoneFactory*>(OgitorsRoot::getSingletonPtr()->GetEditorObjectFactory("Modular Zone Object"));
    if(!factory)return;
    factory->loadZoneTemplates();
    ZoneInfoMap zoneTemplates = factory->getZoneTemplateMap();

    Ogre::Entity *mEntity;

    unsigned char dataptr[300 * 300 * 6];
    unsigned char *dataptr2;
    Ogre::PixelBox pb(256,256,1,Ogre::PF_A8R8G8B8, dataptr);

    EntityMap entities;
    ZoneInfoMap::iterator zi;
    for(zi=zoneTemplates.begin();zi!=zoneTemplates.end();++zi)
    {
        Ogre::String addstr = (*zi).second.mMesh;
        if(entities.find((*zi).first) == entities.end())
            entities.insert(EntityMap::value_type((*zi).first,addstr));
    }

    EntityMap::const_iterator ite = entities.begin();

    while(ite != entities.end())
    {
        Ogre::String addstr = ite->second;

        mEntity = mSceneMgr->createEntity("MZP_Preview", addstr);

        mSceneMgr->getRootSceneNode()->attachObject(mEntity);

        //TODO: It would be nice to retrieve a Preview Camera Position from
        //the .zone file
        //TODO: also render portal outlines clearly so that the user can see
        //how the zone is laid out
        Ogre::Vector3 vSize = mEntity->getBoundingBox().getCorner(Ogre::AxisAlignedBox::NEAR_RIGHT_TOP);//.getHalfSize();//============
        Ogre::Vector3 vCenter = mEntity->getBoundingBox().getCenter();

//FIXME ------ NICE PREVIEWS NEEDED - bigger

        vSize += Ogre::Vector3(vSize.z, vSize.z, vSize.z);

        float maxsize = std::max(std::max(vSize.x,vSize.y),vSize.z);

        //vSize = Ogre::Vector3(0, 0, maxsize * 1.1f) + vCenter;
        vSize = Ogre::Vector3(maxsize * 0.5f, vSize.y, maxsize * 0.5f) + vCenter;
        //vSize.x +=vSize.x/2;//Maybe test to see which is larger x/2 or z/2 and use that?
        //vSize.z +=vSize.x/2;
        //RTTCam->setProjectionType(Ogre::PT_ORTHOGRAPHIC);

        RTTCam->setPosition(vSize.x,vSize.y,vSize.z);
        RTTCam->lookAt(vCenter.x,vCenter.y,vCenter.z);

        rttTex->update();
        rttTex->copyContentsToMemory(pb, Ogre::RenderTarget::FB_FRONT);


        dataptr2 = new unsigned char[96 * 96 * 4];
        Ogre::PixelBox pb2(96,96,1,Ogre::PF_A8R8G8B8, dataptr2);
        Ogre::Image::scale(pb,pb2);

        addstr.erase(addstr.length() - 5, 5);
        retlist.insert(ImageMap::value_type((*ite).first, dataptr2));

        mEntity->detachFromParent();
        mSceneMgr->destroyEntity(mEntity);

        ite++;
    }

    rttTex->removeAllViewports();
    Ogre::Root::getSingletonPtr()->destroySceneManager(mSceneMgr);
    Ogre::TextureManager::getSingletonPtr()->unload(texture->getName());
    Ogre::TextureManager::getSingletonPtr()->remove(texture->getName());
}
Exemple #23
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;
}
Exemple #24
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;
}
Exemple #25
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 UpdateStats(Widget* _widget)
{
    ParamsPanel* _panel = dynamic_cast<ParamsPanel*>(_widget);
    assert(_panel);

    // param names
    const Ogre::StringVector& params = _panel->getAllParamNames();
    if (params.empty())
    {
        Ogre::String ParamNames[] = {"Camera Pos","Last FPS","Average FPS","Best FPS","Worst FPS","Triangles","Batches","ProcessMemory"};
        //stat
	    Ogre::StringVector stats(ParamNames, ParamNames + sizeof(ParamNames)/sizeof(Ogre::String));

        _panel->setPanelWidth(250);
        _panel->setAllParamNames(stats);
        _panel->setPanelAlignment(Ogre::GHA_RIGHT, Ogre::GVA_BOTTOM);
    } // End if
    
    // param values
    if (_panel->getOverlayElement()->isVisible())    
	{		
        Ogre::StringVector values;

        Ogre::SceneManager* pSceneMgr = Ogre::Root::getSingletonPtr()->getSceneManager("DefaultSceneManager");
        assert(pSceneMgr);
        Ogre::Camera* pCamera = pSceneMgr->getCamera("DefaultCamera");
        assert(pCamera);
        const Ogre::Vector3& vPosition = pCamera->getPosition();

        char buf[64];
        sprintf_s(buf, sizeof(buf), "%.2f, %.2f, %.2f", vPosition.x, vPosition.y, vPosition.z);
        values.push_back(buf);

        Ogre::RenderWindow* _pRenderWindow = (Ogre::RenderWindow*)Ogre::Root::getSingletonPtr()->getRenderTarget("Ogre Render Window");
        assert(_pRenderWindow);    
        const Ogre::RenderTarget::FrameStats& stats = _pRenderWindow->getStatistics();

        // fps info
		std::ostringstream oss;
        Ogre::String str;

        float fps[] = {stats.lastFPS, stats.avgFPS, stats.bestFPS, stats.worstFPS};
        int size = sizeof(fps)/sizeof(float);
        for (int j = 0 ; j < size ; ++j)
        {
            oss.str("");
            oss << std::fixed << std::setprecision(1) << fps[j];
            str = oss.str();
		    for (int i = str.length() - 5; i > 0; i -= 3) { str.insert(i, 1, ','); }
		    values.push_back(str);
        } // End for
        
        // triangle info
		str = Ogre::StringConverter::toString(stats.triangleCount);
		for (int i = str.length() - 3; i > 0; i -= 3) { str.insert(i, 1, ','); }
		values.push_back(str);

		str = Ogre::StringConverter::toString(stats.batchCount);
		for (int i = str.length() - 3; i > 0; i -= 3) { str.insert(i, 1, ','); }
		values.push_back(str);

/*
 * calculate total triangle count for all render targets
 *
        size_t uiTotalTriangleCount = 0, uiTotalBatchCount = 0;
        Ogre::RenderSystem* _pRenderSystem = Ogre::Root::getSingletonPtr()->getRenderSystem();
        assert(_pRenderSystem);
        Ogre::RenderSystem::RenderTargetIterator it = _pRenderSystem->getRenderTargetIterator();
	    while(it.hasMoreElements())
	    {
            uiTotalTriangleCount += it.current()->second->getTriangleCount();
		    uiTotalBatchCount += it.current()->second->getBatchCount();

            it.getNext();
	    } // End while
*/
        // memory info
        oss.str("");
		oss << std::fixed << std::setprecision(3) << CalculateProcessMemory()/(1024.0f*1024.0f);
        str = oss.str();
 		values.push_back(str);

		_panel->setAllParamValues(values);
	}
}
Exemple #27
0
Ogre::StringVector
StringTokenise(const Ogre::String& str, const Ogre::String& delimiters, const Ogre::String& delimiters_preserve, const Ogre::String& quote, const Ogre::String& esc)
{
    Ogre::StringVector ret;

    Ogre::String::size_type pos = 0; // the current position (char) in the string
    char ch = 0; // buffer for the current character
    char delimiter = 0;	// the buffer for the delimiter char which
                            // will be added to the tokens if the delimiter
                            // is preserved
    char current_quote = 0; // the char of the current open quote
    bool quoted = false; // indicator if there is an open quote
    Ogre::String token;  // string buffer for the token
    bool token_complete = false; // indicates if the current token is
                                 // read to be added to the result vector
    Ogre::String::size_type len = str.length();  // length of the input-string

    // for every char in the input-string
    while(len > pos)
    {
        // get the character of the string and reset the delimiter buffer
        ch = str.at(pos);
        delimiter = 0;

        // assume ch isn't a delimiter
        bool add_char = true;

        // check ...

        // ... if the delimiter is an escaped character
        bool escaped = false; // indicates if the next char is protected
        if(esc.empty() == false) // check if esc-chars are provided
        {
            if(esc.find_first_of(ch) != std::string::npos)
            {
                // get the escaped char
                ++pos;
                if(pos < len) // if there are more chars left
                {
                    // get the next one
                    ch = str.at(pos);

                    // add the escaped character to the token
                    add_char = true;
                }
                else // cannot get any more characters
                {
                    // don't add the esc-char
                    add_char = false;
                }

                // ignore the remaining delimiter checks
                escaped = true;
            }
        }

        // ... if the delimiter is a quote
        if(quote.empty() == false && escaped == false)
        {
            // if quote chars are provided and the char isn't protected
            if(quote.find_first_of(ch) != std::string::npos)
            {
                // if not quoted, set state to open quote and set
                // the quote character
                if(quoted == false)
                {
                    quoted = true;
                    current_quote = ch;

                    // don't add the quote-char to the token
                    add_char = false;
                }
                else // if quote is open already
                {
                    // check if it is the matching character to close it
                    if(current_quote == ch)
                    {
                        // close quote and reset the quote character
                        quoted = false;
                        current_quote = 0;

                        // don't add the quote-char to the token
                        add_char = false;
                    }
                }
            }
        }

        // if the delimiter isn't preserved
        if(delimiters.empty() == false && escaped == false && quoted == false)
        {
            // if a delimiter is provided and the char isn't protected by
            // quote or escape char
            if(delimiters.find_first_of(ch) != std::string::npos)
            {
                // if ch is a delimiter and the token string isn't empty
                // the token is complete
                if(token.empty() == false)
                {
                    token_complete = true;
                }

                // don't add the delimiter to the token
                add_char = false;
            }
        }

        // if the delimiter is preserved - add it as a token
        bool add_delimiter = false;
        if(delimiters_preserve.empty() == false && escaped == false && quoted == false)
        {
            // if a delimiter which will be preserved is provided and the
            // char isn't protected by quote or escape char
            if(delimiters_preserve.find_first_of(ch) != std::string::npos)
            {
                // if ch is a delimiter and the token string isn't empty the token is complete
                if(token.empty() == false)
                {
                    token_complete = true;
                }

                // don't add the delimiter to the token
                add_char = false;

                // add the delimiter
                delimiter = ch;
                add_delimiter = true;
            }
        }

        // add the character to the token
        if(add_char == true)
        {
            // add the current char
            token.push_back(ch);
        }

        // add the token if it is complete
        if(token_complete == true && token.empty() == false)
        {
            // add the token string
            ret.push_back(token);

            // clear the contents
            token.clear();

            // build the next token
            token_complete = false;
        }

        // add the delimiter
        if(add_delimiter == true)
        {
            // the next token is the delimiter
            Ogre::String delim_token;
            delim_token.push_back(delimiter);
            ret.push_back(delim_token);
        }

        // repeat for the next character
        ++pos;
    }

    // add the final token
    if(token.empty() == false)
    {
        ret.push_back(token);
    }

    return ret;
}
Exemple #28
0
    void Actor::doPlaceIntoScene(SceneNode* parent, const Vector3& position,
        const Quaternion& orientation, const Ogre::String& physicsBone)
    {
        if( parent == NULL )
            Throw(NullPointerException, 
            "Aktor "+mName+": Kann nicht an einen leeren parentNode angehängt werden.");
        if( mBone )
            Throw(IllegalArgumentException, 
            "Aktor "+mName+": Der Aktor ist bereits an einen Bone angehängt.");
        if( mSceneNode && mSceneNode->isInSceneGraph() )
            Throw(IllegalArgumentException, 
            "Aktor "+mName+": Der Aktor ist bereits in die Szene angehängt.");

        // SceneNode erzeugen, falls nicht schon einer vorhanden
        if( !mSceneNode )
            mSceneNode = parent->createChildSceneNode( mName, position, orientation );
        // Ansonsten am Parent befestigen
        else
        {
            parent->addChild( mSceneNode );
            mSceneNode->setPosition(position);
            mSceneNode->setOrientation(orientation);
        }

        // Falls ein noch nicht befestigtes MovableObject vorhanden, dieses attachen
        if( mActorControlledObject != NULL && !mActorControlledObject->isAttached() )
        {
            mActorControlledObject->_attachSceneNode(mSceneNode);
        }

        // Physikverknüpfung anpassen
        if( mPhysicalThing != NULL && mActorControlledObject != NULL )
        {
            PhysicsManager::getSingleton().createPhysicsProxy(mPhysicalThing, mSceneNode);

            // Knochen angegeben und handelt sich um ein Mesh
            if( physicsBone.length() > 0 && mActorControlledObject->isMeshObject())
            {
                MeshObject* meshObj = dynamic_cast<MeshObject*>(mActorControlledObject);
                Entity* ent = meshObj->getEntity();

                // Braucht ein Skelett
                if( !ent->hasSkeleton() )
                    Throw(IllegalArgumentException, 
                    "Aktor "+mName+": Das kontrollierte MeshObject hat kein Skeleton." );

                // Der Slot muss existieren
                try
                {
                    ent->getSkeleton()->getBone( physicsBone );
                }
                catch (Ogre::Exception) {
                    Throw(IllegalArgumentException, 
                        "Aktor "+mName+": Der geforderte PhysicsBone '"+physicsBone+"' existiert nicht." );
                }

                mPhysicalThing->_attachToBone( meshObj, physicsBone );
            }
            // Dann an einem SceneNode befestigen
            else
            {      
                mPhysicalThing->_attachToSceneNode(mSceneNode);
            }
        }

        _update();
    }
void CLASS::SaveSettings()
{
	//Get combo boxes values first
	//Check boxes and sliders values are updated as they are being used
	GameSettingsMap["GearboxMode"] = m_gearbox_mode->getCaption();
	OgreSettingsMap["Render System"] = m_render_sys->getCaption(); //This one is special 
	OgreSettingsMap["Video Mode"] = m_resolution->getCaption(); //This one is special 
	OgreSettingsMap["FSAA"] = m_fsaa->getCaption(); //This one is special 
	GameSettingsMap["FOV External"] = m_fovexternal->getCaption();
	GameSettingsMap["FOV Internal"] = m_fovinternal->getCaption();
	GameSettingsMap["Texture Filtering"] = m_tex_filter->getCaption();
	GameSettingsMap["Sky effects"] = m_sky_type->getCaption();
	GameSettingsMap["Shadow technique"] = m_shadow_type->getCaption();
	GameSettingsMap["Water effects"] = m_water_type->getCaption();
	GameSettingsMap["Vegetation"] = m_vegetation->getCaption();
	GameSettingsMap["Lights"] = m_light_source_effects->getCaption(); 
	GameSettingsMap["AudioDevice"] = m_audio_dev->getCaption();
	GameSettingsMap["SpeedUnit"] = m_speed_unit->getCaption();
	//That's it i think

	//Not sure if these settings really need a restart, temporary.
	if (GameSettingsMap["AudioDevice"] != ExGameSettingsMap["AudioDevice"])
		ShowRestartNotice = true;
	else if (GameSettingsMap["FOV External"] != ExGameSettingsMap["FOV External"] || GameSettingsMap["FOV Internal"] != ExGameSettingsMap["FOV Internal"])
		ShowRestartNotice = true;
	else if (OgreSettingsMap["Render System"] != ExOgreSettingsMap["Render System"])
		ShowRestartNotice = true;
	else if (OgreSettingsMap["Video Mode"] != ExOgreSettingsMap["Video Mode"])
		ShowRestartNotice = true;
	else if (OgreSettingsMap["FSAA"] != ExOgreSettingsMap["FSAA"])
		ShowRestartNotice = true;


	if (GameSettingsMap["Water effects"] == "Hydrax")
		GameSettingsMap["SightRange"] = "5000";

	if (isKeyMapLoaded)
	{
		Application::GetInputEngine()->saveMapping("input.map", RoR::Application::GetOgreSubsystem()->GetMainHWND());
	}

	//Something used by both saves
	std::map<std::string, std::string>::iterator it;

	//Save ogre's settings
	Ogre::RenderSystem* rs = Ogre::Root::getSingleton().getRenderSystem();
	for (it = OgreSettingsMap.begin(); it != OgreSettingsMap.end(); it++)
	{
		try
		{
			rs->setConfigOption(it->first.c_str(), it->second.c_str());
		}
		catch (...)
		{
			LOG("Error setting Ogre Values");
		}
	}
	Ogre::String err = rs->validateConfigOptions();
	if (err.length() > 0)
	{
		LOG("Ogre config validation error");
	}
	else
	{
		Ogre::Root::getSingleton().saveConfig();
	}

	// now save the GameSettingsMap
	for (it = GameSettingsMap.begin(); it != GameSettingsMap.end(); it++)
	{
		if (it->first.c_str() == "User Token" || it->first.c_str() == "User Token Hash" || it->first.c_str() == "Config Root" || it->first.c_str() == "Cache Path" || it->first.c_str() == "Log Path" || it->first.c_str() == "Resources Path" || it->first.c_str() == "Program Path")
			return;

		Settings::getSingleton().setSetting(it->first.c_str(), it->second.c_str()); //Avoid restarting the game in few cases.
		Settings::getSingleton().saveSettings();
	}

	//Apply fullscreen
	//Not working correctly
	/*
	if (BSETTING("DevMode", false)) //let's disable this for now
	{
		if (OgreSettingsMap["Full Screen"].c_str() != ExOgreSettingsMap["Full Screen"].c_str())
		{
			Ogre::StringVector args = Ogre::StringUtil::split(OgreSettingsMap["Video Mode"], " ");

			static int org_width = -1, org_height = -1;
			int width = RoR::Application::GetOgreSubsystem()->GetRenderWindow()->getWidth();
			int height = RoR::Application::GetOgreSubsystem()->GetRenderWindow()->getHeight();
			if (org_width == -1)
				org_width = width;
			if (org_height == -1)
				org_height = height;
			bool mode = RoR::Application::GetOgreSubsystem()->GetRenderWindow()->isFullScreen();
			if (!mode)
			{
				RoR::Application::GetOgreSubsystem()->GetRenderWindow()->setFullscreen(true, (int)args[0].c_str(), (int)args[2].c_str());
				LOG(" ** switched to fullscreen: " + TOSTRING(width) + "x" + TOSTRING(height));
			}
			else
			{
				RoR::Application::GetOgreSubsystem()->GetRenderWindow()->setFullscreen(false, 640, 480);
				RoR::Application::GetOgreSubsystem()->GetRenderWindow()->setFullscreen(false, org_width, org_height);
				LOG(" ** switched to windowed mode: ");
			}
			ShowRestartNotice = false;
		}
	}*/

} 
Exemple #30
0
    bool OgreModel::fromJson(const Json::Value &node, Ogre::SceneNode *levelRoot, Ogre::SceneManager *sceneManager, const Ogre::String &resourceGroupName)
    {
        // data to gather
        Ogre::String meshName;
        Ogre::Vector3 pos(Ogre::Vector3::ZERO);
        Ogre::Quaternion rot(Ogre::Radian(0), -Ogre::Vector3::UNIT_Z);
        Ogre::Vector3 scale(Ogre::Vector3::UNIT_SCALE);

        Json::Value value;
        bool allWasFine = true;

        // position
        if(node[OgreModel::POSITION_ATTRIBUTE].isNull())
            Debug::error(STEEL_METH_INTRO, "position is null: no translation applied.").endl();
        else
            pos = JsonUtils::asVector3(node[OgreModel::POSITION_ATTRIBUTE], pos);

        //rotation
        if(!node[OgreModel::ROTATION_ATTRIBUTE].isNull())
            rot = JsonUtils::asQuaternion(node[OgreModel::ROTATION_ATTRIBUTE], rot);

        //scale
        if(!node[OgreModel::SCALE_ATTRIBUTE].isNull())
            scale = JsonUtils::asVector3(node[OgreModel::SCALE_ATTRIBUTE], scale);

        // mesh name
        value = node[OgreModel::ENTITY_MESH_NAME_ATTRIBUTE];

        if(value.isNull() && !(allWasFine = false))
            Debug::error(STEEL_METH_INTRO, "field ").quotes(OgreModel::ENTITY_MESH_NAME_ATTRIBUTE)(" is null.").endl();
        else
            meshName = Ogre::String(value.asString());

        // custom material
        Ogre::String materialName = StringUtils::BLANK;

        if(node.isMember(OgreModel::MATERIAL_OVERRIDE_ATTRIBUTE))
        {
            value = node[OgreModel::MATERIAL_OVERRIDE_ATTRIBUTE];
            materialName = JsonUtils::asString(value, StringUtils::BLANK);

            if(StringUtils::BLANK == materialName)
                Debug::error(STEEL_METH_INTRO, "could not read field ").quotes(OgreModel::MATERIAL_OVERRIDE_ATTRIBUTE)(": ").quotes(value).endl();
        }

        // agentTags
        allWasFine &= deserializeTags(node);

        if(!allWasFine)
        {
            Debug::error("json was:").endl()(node.toStyledString()).endl();
            Debug::error("model deserialisation aborted.").endl();
            return false;
        }

        // now whether we have minor changes (and we apply them directly), or major ones (cleanup, then init).
        // lets start with major ones
        if(mEntity == nullptr || meshName != mEntity->getMesh()->getName())
        {
            // make sure we've been called with all arguments, because they're all needed now
            if(levelRoot == nullptr || sceneManager == nullptr)
            {
                Debug::error(STEEL_METH_INTRO, "a new mesh is required, but sceneManager or levelRoot are nullptr. Aborting.").endl();
                return false;
            }

            // make sure the new meshName is valid
            if(meshName.length() == 0 || !Ogre::ResourceGroupManager::getSingletonPtr()->resourceExistsInAnyGroup(meshName))
            {
                Debug::error(STEEL_METH_INTRO, "could not find resource ").quotes(meshName)(" in any group. Aborting.").endl();
                return false;
            }

            if(!init(meshName, pos, rot, scale, levelRoot, sceneManager, resourceGroupName))
            {
                return false;
            }
        }
        else
        {
            setPosition(pos);
            setRotation(rot);
            setScale(scale);
        }

        if(StringUtils::BLANK != materialName)
        {
            setMaterial(materialName, resourceGroupName);
        }

        return true;
    }