//-----------------------------------------------------------------------------------------
void CTerrainGroupEditor::importFullTerrainFromHeightMap()
{
    UTFStringVector extlist;
    extlist.push_back(OTR("PNG Grayscale"));
    extlist.push_back("*.png");
    extlist.push_back(OTR("Raw 32bit Float File"));
    extlist.push_back("*.raw;*.ohm;*.f32;*.r32");

    Ogre::UTFString defaultPath = mSystem->GetSetting("system", "ExportTerrainPath", "");

    Ogre::String filename = mSystem->DisplayOpenDialog(OTR("Import Heightmap"), extlist, defaultPath);
    if(filename == "") 
        return;

    mSystem->SetSetting("system", "ExportTerrainPath", OgitorsUtils::ExtractFilePath(filename));

    Ogre::NameValuePairList params;
    if(!mSystem->DisplayImportHeightMapDialog(params))
        return;
    
    Ogre::Real fScale = Ogre::StringConverter::parseReal(params["scale"]);
    Ogre::Real fBias = Ogre::StringConverter::parseReal(params["bias"]);
    Ogre::String normal = params["normal"];
    Ogre::String diffuse = params["diffuse"];
    bool flipV = Ogre::StringConverter::parseBool(params["inverted"]);

    float *data = 0;
    float *flipBV = 0;

    Ogre::String namePart = OgitorsUtils::ExtractFileName(filename);
    namePart.erase(0, namePart.find("."));

    int imgW = 0;
    int imgH = 0;

    if(namePart == ".png")
    {
        std::fstream fstr(filename.c_str(), std::ios::in|std::ios::binary);
        Ogre::DataStreamPtr stream = Ogre::DataStreamPtr(OGRE_NEW Ogre::FileStreamDataStream(&fstr, false));

        Ogre::Image img;
        img.load(stream);

        data = OGRE_ALLOC_T(float, img.getWidth() * img.getHeight(), Ogre::MEMCATEGORY_GEOMETRY);
        Ogre::PixelBox pb(img.getWidth(), img.getHeight(), 1, Ogre::PF_FLOAT32_R, data);
        Ogre::PixelUtil::bulkPixelConversion(img.getPixelBox(), pb);

        imgW = img.getWidth();
        imgH = img.getHeight();
        
        img.freeMemory();
        stream.setNull();
    }
Esempio n. 2
0
//-----------------------------------------------------------------------
void ExpatParser::parseXMLFile(XMLHandler& handler,
                               const Ogre::String& xmlName, const Ogre::String& xmlResourceGroup,
                               const Ogre::String& schemaName, const Ogre::String& schemaResourceGroup)
{
    XML_Parser parser = XML_ParserCreate(NULL);

    try
    {
        MyUserData myUserData;
        myUserData.handler = &handler;
        if (_locale.get())
            myUserData.converter = boost::bind(&expat_to_local, _1, _2, boost::ref(*_locale));
        else
            myUserData.converter = boost::bind(&expat_to_local_win32, _1, _2, boost::ref(_buffer));

        XML_SetUserData(parser, &myUserData);
        XML_SetElementHandler(parser, expatStartElementHandler, expatEndElementHandler);
        XML_SetCharacterDataHandler(parser, expatCharacterDataHandler);

        const size_t MaxBufferSize = 64*1024;
        Ogre::DataStreamPtr dataStream = Ogre::ResourceGroupManager::getSingleton().openResource(xmlName, xmlResourceGroup);
        bool done;
        do
        {
            void* buffer = XML_GetBuffer(parser, MaxBufferSize);
            if (!buffer)
            {
                OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR,
                            "Can't allocate buffer while parse XML file '" + xmlName + "'.",
                            "ExpatParser::parseXMLFile");
            }

            size_t count = dataStream->read(buffer, MaxBufferSize);
            done = dataStream->eof();

            if (XML_ParseBuffer(parser, count, done) != XML_STATUS_OK)
            {
                OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR,
                            "An error occurred while parsing XML file '" + xmlName +
                            "' at line " + Ogre::StringConverter::toString(XML_GetCurrentLineNumber(parser)) +
                            ". Additional information: " + XML_ErrorString(XML_GetErrorCode(parser)),
                            "ExpatParser::parseXMLFile");
            }
        } while (!done);
    }
    catch(...)
    {
        XML_ParserFree(parser);
        throw;
    }

    XML_ParserFree(parser);
}
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();
}
qint64 OgreNetworkReply::readData(char *data, qint64 maxSize)
{
    if (mDataStream.isNull()) {
        setErrorString("This network request is closed.");
        return -1;
    }

    if (mDataStream->eof())
        return -1;

    return mDataStream->read(data, maxSize);
}
Esempio n. 5
0
void UnloadMaterials(const std::string& filename)
{
    if (filename.empty())
    {
        Ogre::LogManager::getSingleton().logMessage("Filename is empty.");
        return;
    }
 
    Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(filename);
    if(!stream.isNull())
    {
        try
        {
            while(!stream->eof())
            {
                std::string line = stream->getLine();
                StringUtil::trim(line);
 
                ///
                /// UNLOAD MATERIALS
                ///
                if (StringUtil::startsWith(line, "material"))
                {
                    Ogre::vector<Ogre::String>::type vec = StringUtil::split(line," \t:");
                    bool skipFirst = true;
                    for (Ogre::vector<Ogre::String>::type::iterator it = vec.begin(); it < vec.end(); ++it)
                    {
                        if (skipFirst)
                        {
                            skipFirst = false;
                            continue;
                        }
                        std::string match = (*it);
                        StringUtil::trim(match);
                        if (!match.empty())
                        {
                            UnloadResource(Ogre::MaterialManager::getSingletonPtr(), match);
                            break;
                        }
                    }
                }
            }
        }
        catch (Ogre::Exception &e)
        {
            StringUtil::StrStreamType msg;
            msg << "Exception: FILE: " << __FILE__ << " LINE: " << __LINE__ << " DESC: " << e.getFullDescription() << std::endl;
            Ogre::LogManager::getSingleton().logMessage(msg.str());
        }
    }
    stream->close();
}
Esempio n. 6
0
void AnimationSystem::loadAnimationInfo( const std::string& animationInfoOgreResourceName, const std::string& ogreResourceResourceGroupName )
{
	using namespace tecnofreak::property;

	Ogre::DataStreamPtr dataStream = Ogre::ResourceGroupManager::getSingleton().openResource( animationInfoOgreResourceName, ogreResourceResourceGroupName );
	
	std::string animationInfoData( dataStream->getAsString() );

	Property animationInfo;
	xml::PropertyBuilder::initialiseFromData( &animationInfo, animationInfoData );

	loadAnimationInfo( &animationInfo );
}
void FvFTDTerrainPageSerializerImpl::ReadLayerMap(Ogre::DataStreamPtr &spStream, 
												  FvTerrainPage *pkDest, FvUInt32 uiLayerIndex)
{
	FTDLayerMapHeader kHeader;
	spStream->read(&kHeader,sizeof(FTDLayerMapHeader));
	FvTerrainPage::TextureLayerPtr spLayer = new FvTerrainPage::TextureLayer;

	FvUInt32 uiNameSize;
	spStream->read(&uiNameSize,sizeof(FvUInt32));

	char acTextureName[256];
	FV_ASSERT(uiNameSize < 256);
	spStream->read(acTextureName,uiNameSize);
	acTextureName[uiNameSize] = 0;
	spLayer->m_kTextureName = acTextureName;

	if(kHeader.m_uiVersion == VERSION_PNG)
	{
		spLayer->m_pkBlends = new Ogre::Image;
		spLayer->m_pkBlends->load(spStream,"png");
	}
	if(kHeader.m_uiVersion == VERSION_DDS)
	{
		spLayer->m_pkBlends = new Ogre::Image;
		spLayer->m_pkBlends->load(spStream,"dds");
	}

	FV_ASSERT(spLayer->m_pkBlends);

	try
	{
		spLayer->m_spTexture = Ogre::TextureManager::getSingleton().load(spLayer->m_kTextureName,
			pkDest->m_spTerrainSettings->TextureGroup());
	}
	catch (...){}

	if(spLayer->m_spTexture.isNull())
	{
		FV_ERROR_MSG("FvFTDTerrainPageSerializerImpl::ReadLayerMap texture %s not exist",
			spLayer->m_kTextureName.c_str());
	}

	spLayer->m_uiWidth = kHeader.m_uiWidth;
	spLayer->m_uiHeight = kHeader.m_uiHeight;
	memcpy(&spLayer->m_kUProjection, kHeader.m_kUProjection, sizeof(Ogre::Vector4)); 
	memcpy(&spLayer->m_kVProjection, kHeader.m_kVProjection, sizeof(Ogre::Vector4)); 

	pkDest->m_kTextureLayers.push_back(spLayer);
}
void aiBehaviorTreeTemplateManager::LoadAll()
{
	Ogre::StringVectorPtr loc = Ogre::ResourceGroupManager::getSingleton().findResourceLocation("BehaviorTemplate", "*Behaviors");
	const STRING filename = loc->at(0) + "\\Script\\";

	//加载全局黑板xml
	Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource("RaceGlobal.xml", "BehaviorTemplate");
	char* szData = strdup(stream->getAsString().c_str());

	rapidxml::xml_document<> XMLDoc;
	XMLDoc.parse<0>(szData);
	rapidxml::xml_node<>* pNode = XMLDoc.first_node("Root")->first_node("BlackBoard");

	while(pNode)
	{
		const STRING raceName = pNode->first_attribute("race")->value();
		rapidxml::xml_node<>* pVarNode = pNode->first_node("Variable");

		eGameRace race;
		if(raceName == "Terran") race = eGameRace_Terran;
		else if(raceName == "Zerg") race = eGameRace_Zerg;
		else assert(0);

		aiBlackBoard* bb = new aiBlackBoard;
		bb->LoadParams(pVarNode);
		m_globalBBs.insert(std::make_pair(race, bb));

		//脚本
		const char* szFilename = XMLDoc.first_node("Root")->first_node("Script")->first_attribute("filename")->value();
		const STRING filepath = filename + szFilename;
		SCRIPTNAMAGER.DoFile(filepath);

		pNode = pNode->next_sibling("BlackBoard");
	}

	free(szData);
	XMLDoc.clear();

	//加载各单位行为树xml
	Ogre::StringVectorPtr files = Ogre::ResourceGroupManager::getSingleton().findResourceNames("BehaviorTemplate", "*.xml");
	auto iter = std::find(files->begin(), files->end(), "RaceGlobal.xml");
	files->erase(iter);
	for (auto iter=files->begin(); iter!=files->end(); ++iter)
	{
		aiBehaviorTreeTemplate* pTmpl = new aiBehaviorTreeTemplate;
		const STRING name = pTmpl->Load(*iter);
		m_bts.insert(std::make_pair(name, pTmpl));
	}
}
Esempio n. 9
0
/*
void TextureAsset::RegenerateAllMipLevels()
{
    if (ogreTexture.isNull())
        return;

///\todo This function does not quite work, since ogreTexture->getNumMipmaps() will return 0 to denote a "full mipmap chain".

    for(int f = 0; f < ogreTexture->getNumFaces(); ++f)
        for(int i = 1; i < ogreTexture->getNumMipmaps(); ++i)
        {
            Ogre::HardwarePixelBufferSharedPtr src = ogreTexture->getBuffer(f, i-1);
            Ogre::Box srcSize(0, 0, src->getWidth(), src->getHeight());
            Ogre::HardwarePixelBufferSharedPtr dst = ogreTexture->getBuffer(f, i);
            Ogre::Box dstSize(0, 0, dst->getWidth(), dst->getHeight());
            dst->blit(src, srcSize, dstSize);
        }
}
*/
bool TextureAsset::SerializeTo(std::vector<u8> &data, const QString &serializationParameters) const
{
    if (ogreTexture.isNull())
    {
        LogWarning("SerializeTo: Called on an unloaded texture \"" + Name().toStdString() + "\".");
        return false;
    }

    try
    {
        Ogre::Image new_image;
                
        // From Ogre 1.7 Texture::convertToImage()
        size_t numMips = 1;
        size_t dataSize = Ogre::Image::calculateSize(numMips,
            ogreTexture->getNumFaces(), ogreTexture->getWidth(), ogreTexture->getHeight(), ogreTexture->getDepth(), ogreTexture->getFormat());
        void* pixData = OGRE_MALLOC(dataSize, Ogre::MEMCATEGORY_GENERAL);
        // if there are multiple faces and mipmaps we must pack them into the data
        // faces, then mips
        void* currentPixData = pixData;
        for (size_t face = 0; face < ogreTexture->getNumFaces(); ++face)
        {
            for (size_t mip = 0; mip < numMips; ++mip)
            {
                size_t mipDataSize = Ogre::PixelUtil::getMemorySize(ogreTexture->getWidth(), ogreTexture->getHeight(), ogreTexture->getDepth(), ogreTexture->getFormat());
                Ogre::PixelBox pixBox(ogreTexture->getWidth(), ogreTexture->getHeight(), ogreTexture->getDepth(), ogreTexture->getFormat(), currentPixData);
                ogreTexture->getBuffer(face, mip)->blitToMemory(pixBox);
                currentPixData = (void*)((char*)currentPixData + mipDataSize);
            }
        }
        // load, and tell Image to delete the memory when it's done.
        new_image.loadDynamicImage((Ogre::uchar*)pixData, ogreTexture->getWidth(), ogreTexture->getHeight(), ogreTexture->getDepth(), ogreTexture->getFormat(), true, 
            ogreTexture->getNumFaces(), numMips - 1);

        Ogre::DataStreamPtr imageStream = new_image.encode(serializationParameters.toStdString());
        if (imageStream.get() && imageStream->size() > 0)
        {
            data.resize(imageStream->size());
            imageStream->read(&data[0], data.size());
        }
    } catch (std::exception &e)
    {
        LogError("SerializeTo: Failed to export Ogre texture " + Name().toStdString() + ":");
        if (e.what())
            OgreRenderer::OgreRenderingModule::LogError(e.what());
        return false;
    }
    return true;
}
Esempio n. 10
0
    Resource::DataStreamPtr ResourceManager::OpenAssetStream(const String& AssetName, const String& AssetGroup)
    {
        /// @todo This entire method is a bit of a hack.  When the resource system gets refactored it should go through our archives or whatever equivalent.
        /// Since we currently have to put up with Ogre's system, we'll use it for now as a hack.

        NamedDataStreamIterator StreamIt = this->NamedDataStreams.find(AssetName);
        if( StreamIt != this->NamedDataStreams.end() )
            return (*StreamIt).second;

        Ogre::DataStreamPtr OgreStream = this->OgreResource->openResource(AssetName,AssetGroup);
        Char8* AssetBuffer = new Char8[ OgreStream->size() ];
        OgreStream->read( (void*)AssetBuffer, OgreStream->size() );

        return this->CreateDataStream(AssetName,AssetBuffer,OgreStream->size());
    }
Esempio n. 11
0
void SkeletonSerializerEx::importSkeleton(Ogre::DataStreamPtr& stream, Ogre::Skeleton* pSkel)
{
	// Determine endianness (must be the first thing we do!)
	determineEndianness(stream);

	// Check header
	readFileHeader(stream);

	unsigned short streamID;
	while(!stream->eof())
	{
		streamID = readChunk(stream);
		switch (streamID)
		{
		case Ogre::SKELETON_BONE:
			readBone(stream, pSkel);
			break;
		case Ogre::SKELETON_BONE_PARENT:
			readBoneParent(stream, pSkel);
			break;
		case Ogre::SKELETON_ANIMATION:
			readAnimation(stream, pSkel);
			break;
		case Ogre::SKELETON_ANIMATION_LINK:
			readSkeletonAnimationLink(stream, pSkel);
			break;
		}
	}

	// Assume bones are stored in the binding pose
	pSkel->setBindingPose();


}
    //---------------------------------------------------------------------
    void
    BackgroundFileSerializer::readObject( Ogre::DataStreamPtr &stream, Page &pDest )
    {
        read2ByteBool( stream, pDest.enabled );
        if( !pDest.enabled ) return;

        readShort( stream, pDest.unknown_02 );
        readShort( stream, pDest.value_size );
        if( pDest.value_size != 1 && pDest.value_size != 2 )
        {
            OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS
                ,"Page value_size other then 1 and 2 is not supported"
                ,"BackgroundFileSerializer::readObject" );
        }

        size_t color_count( BackgroundFile::PAGE_DATA_SIZE );
        pDest.colors.clear();
        pDest.data.clear();

        if( pDest.value_size == 2 )
        {
            pDest.colors.reserve( color_count );
            for( size_t i( color_count ); i--; )
            {
                Color colourDest;
                readObject( stream, colourDest );
                pDest.colors.push_back( colourDest );
            }
        }
        else
        {
            pDest.data.resize( color_count );
            stream->read( &pDest.data[0], color_count );
        }
    }
 //---------------------------------------------------------------------
 void
 BackgroundFileSerializer::readPallete( Ogre::DataStreamPtr &stream
                                       ,BackgroundFile *pDest )
 {
     readSectionHeader( stream, SECTION_NAME_PALETTE );
     stream->read( pDest->getPalette().data(), BackgroundFile::PALETTE_ENTRY_COUNT );
 }
    //---------------------------------------------------------------------
    void
    BackgroundFileSerializer::readLayer( Ogre::DataStreamPtr &stream
                                        ,Layer *pDest, size_t layer_index )
    {
        if( !pDest->enabled ) return;

        uint16 tmp[4], sprite_count;
        readShorts( stream, tmp, 4 );
        pDest->width        = tmp[0];
        pDest->height       = tmp[1];
        sprite_count        = tmp[2];
        pDest->unknown_06   = tmp[3];

        switch( layer_index )
        {
          case 1:
            readShorts( stream, pDest->unknown_08, 3 );
          case 2:
          case 3:
            readShorts( stream, pDest->unknown_0E, 4 );
        }
        stream->skip( 2 * 2 ); // 2 * uint16 unused;
        m_layer_index = layer_index;
        readVector( stream, pDest->sprites, sprite_count );

        removeBuggySprites( pDest->sprites );
    }
Esempio n. 15
0
bool VehicleRenderable::load(Ogre::String fileName, Ogre::String groupName)
{
	//open resource from exist group if specify group or file does not exist
	Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(fileName, groupName);
	
	//create a tinyXml object by stream
	TinyXml::TiXmlDocument* doc = new TinyXml::TiXmlDocument;
	try
	{
		doc->Parse(stream->getAsString().c_str());
	}
	catch (...)
	{
		Ogre::LogManager::getSingleton().
			logMessage("VehicleRenderable Error : Parse <" + fileName + "> fail!");
		delete doc;
		return false;
	}

	//check if scene file can parse
	Ogre::String str = Ogre::String(doc->RootElement()->Value());
	if (str != "scene")
	{
		Ogre::LogManager::getSingleton().
			logMessage("VehicleRenderable Error : <" + fileName + "> is not a scene file!");
		delete doc;
		return false;
	}

	TinyXml::TiXmlElement* ele;

	// process scene node
	ele = doc->RootElement()->FirstChildElement("nodes");
	if (!loadSceneNodes(ele))
	{
		Ogre::LogManager::getSingleton().
			logMessage("VehicleRenderable Error : errors occurred in parsing nodes!");
		delete doc;
		return false;
	}

	Ogre::LogManager::getSingleton().
		logMessage("VehicleRenderable succeed!");

	delete doc;
	return true;
}
Esempio n. 16
0
//-----------------------------------------------------------------------------------------
QPixmap HeightImageEditorCodec::onBeforeDisplay(Ogre::DataStreamPtr stream)
{
    double file_len = stream->size() / 4;

    unsigned int map_size = sqrt(file_len);

    mBuffer = new unsigned char[map_size * map_size * sizeof(float)];
    float *buf = (float *)mBuffer;

    stream->read(buf, map_size * map_size * 4);

    float max_h = -1000000.0f;
    float min_h = 1000000.0f;

    for(unsigned int i = 0; i < map_size * map_size; i++)
    {
        if(buf[i] > max_h)
            max_h = buf[i];
        if(buf[i] < min_h)
            min_h = buf[i];
    }

    float diff = max_h - min_h;

    if(diff > 0.0f)
    {
        unsigned char *colbuf = (unsigned char *)buf;
        int pos = 0;

        for(unsigned int i = 0; i < map_size * map_size; i++)
        {
            float tval = mapToRange(buf[i], min_h, max_h, 60, 360);

            HSVtoARGB(&colbuf[pos], tval, 1.0f, 1.0f);

            pos += 4;
        }
    }
    else
        memset(buf, 0xFF, map_size * map_size * 4);

    QImage image = QImage((unsigned char *)buf, map_size, map_size, QImage::Format_ARGB32);
    mPixmap = QPixmap(QPixmap::fromImage(image));

    return mPixmap;
}
Esempio n. 17
0
 std::string getString(size_t length)
 {
     std::string str;
     str.resize(length);
     if(inp->read(&str[0], length) != length)
         return std::string();
     return str.substr(0, str.find('\0'));
 }
Esempio n. 18
0
void RoR::SkidmarkConfig::LoadDefaultSkidmarkDefs()
{
    LOG("[RoR] Loading skidmarks.cfg...");
    Ogre::String group = "";
    try
    {
        group = Ogre::ResourceGroupManager::getSingleton().findGroupContainingResource("skidmarks.cfg");
        if (group.empty())
        {
            LOG("[RoR] Failed to load skidmarks.cfg (file not found)");
            return;
        }

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

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

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

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

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

            // process the line if we got a model
            if (!currentModel.empty())
                this->ProcessSkidmarkConfLine(args, currentModel);
        }
    }
    catch (...)
    {
        LOG("[RoR] Error loading skidmarks.cfg (unknown error)");
        m_models.clear(); // Delete anything we might have loaded
        return;
    }
    LOG("[RoR] skidmarks.cfg loaded OK");
}
Esempio n. 19
0
/* Loads an XmlDocument from a filename.
 * Requires:
 * 	@filename		The xml filename
 * Returns:
 * 	@doc			The xmlDocument or 0 if error
 */
TiXmlDocument *Util::loadXmlDocument(const char *fname)
{
	ASSERT(fname);
	TiXmlDocument   *XMLDoc = 0;

	try
	{
		// Strip the path
		Ogre::String basename, path;
		Ogre::StringUtil::splitFilename(fname, basename, path);

		// we will hardcode the groupName
		Ogre::DataStreamPtr pStream = Ogre::ResourceGroupManager::getSingleton().
			openResource( basename, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME);

		//DataStreamPtr pStream = ResourceGroupManager::getSingleton().
		//    openResource( SceneName, groupName );

		Ogre::String data = pStream->getAsString();

		// Open the .scene File
		XMLDoc = new TiXmlDocument();
		XMLDoc->Parse( data.c_str() );

		pStream->close();
		pStream.setNull();

		if( XMLDoc->Error() )
		{
			//We'll just log, and continue on gracefully
			debug("Couldn't load the %s xml\n", fname);
			delete XMLDoc;
			return 0;
		}
	}
	catch(...)
	{
		//We'll just log, and continue on gracefully
		debug("Error creating TiXmlDocument for %s\n", fname);
		delete XMLDoc;
		return 0;
	}

	// Close the XML File
	return XMLDoc;
}
Esempio n. 20
0
	int		OOSStreamSeek(void *datasource, ogg_int64_t offset, int whence)
	{
		Ogre::DataStreamPtr dataStream = *reinterpret_cast<Ogre::DataStreamPtr*>(datasource);
		switch(whence)
		{
		case SEEK_SET:
			dataStream->seek(offset);
			break;
		case SEEK_END:
			dataStream->seek(dataStream->size());
			// Falling through purposefully here
		case SEEK_CUR:
			dataStream->skip(offset);
			break;
		}

		return 0;
	}
	void LanguageManager::_loadLanguage(const Ogre::DataStreamPtr& stream, bool _user)
	{
		std::string read;
		while (false == stream->eof()) {
			read = stream->getLine (false);
			if (read.empty()) continue;

			size_t pos = read.find_first_of(" \t");
			if (_user) {
				if (pos == std::string::npos) mUserMapLanguage[read] = "";
				else mUserMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
			}
			else {
				if (pos == std::string::npos) mMapLanguage[read] = "";
				else mMapLanguage[read.substr(0, pos)] = read.substr(pos+1, std::string::npos);
			}
		};
	}
Esempio n. 22
0
	//loader for ScriptSystem
	std::string
		OgreFileLoader(lua_State* pState, std::string strFile)
	{
		if(!Ogre::ResourceGroupManager::getSingleton().resourceExists(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, strFile))
			return std::string("file not found");
		Ogre::DataStreamPtr ds = Ogre::ResourceGroupManager::getSingleton().openResource(strFile);
		char *buffer = ICE_NEW char[ds->size()];
		ds->read(buffer, ds->size());
		ds->close();

		if(luaL_loadbuffer(pState, buffer, ds->size(), strFile.c_str()) || lua_pcall(pState, 0, 0, 0))
		{
			ICE_DELETE buffer;
			return std::string(lua_tostring(pState, -1));
		}
		ICE_DELETE buffer;
		return std::string();
	}
Esempio n. 23
0
//----------------------------------------------------------------------------------
bool  UILayout::loadLayoutFile(const Ogre::String& fileName)
{
	Ogre::DataStreamPtr stream ;
	try
	{

		stream = Ogre::ResourceGroupManager::getSingleton().openResource(fileName, "UI");
	}
	catch(...)
	{

		Ogre::LogManager::getSingleton().logMessage("UIBase::loadLayoutFile error,file name is "+fileName);
		return false;
	}


	rapidxml::xml_document<> XMLDoc;    // character type defaults to char
	rapidxml::xml_node<>* XMLRoot=NULL;

	char* scene = strdup(stream->getAsString().c_str());
	XMLDoc.parse<0>(scene);


	XMLRoot=XMLDoc.first_node("GUILayout");
	if(XMLRoot==NULL)
	{
		Ogre::LogManager::getSingleton().logMessage( "UIBase::loadLayoutFile error,is not layout format" );
		return false;

	}




	XMLRoot = XMLRoot->first_node("Window");
	if( XMLRoot==NULL)
	{
		Ogre::LogManager::getSingleton().logMessage( "UIBase::loadLayoutFile error,can't find Window node" );
		return false;
	}

	return 	processRootWindow(XMLRoot);

}
	bool LanguageManager::loadLanguage(const std::string & _file, const std::string & _group, bool _user)
	{

		if (!_group.empty()) {

			if (!helper::isFileExist(_file, _group)) {
				MYGUI_LOG(Error, "file '" << _file << "' not found in group'" << _group << "'");
				return false;
			}

			Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingletonPtr()->openResource(_file, _group);

			// проверяем на сигнатуру utf8
			uint32 sign = 0;
			stream->read((void*)&sign, 3);
			if (sign != 0x00BFBBEF) {
				MYGUI_LOG(Error, "file '" << _file << "' is not UTF8 format");
				return false;
			}

			_loadLanguage(stream, _user);
			return true;
		}

		std::ifstream stream(_file.c_str());
		if (false == stream.is_open()) {
			MYGUI_LOG(Error, "error open file '" << _file << "'");
			return false;
		}

		// проверяем на сигнатуру utf8
		uint32 sign = 0;
		stream.read((char*)&sign, 3);
		if (sign != 0x00BFBBEF) {
			MYGUI_LOG(Error, "file '" << _file << "' is not UTF8 format");
			stream.close();
			return false;
		}

		_loadLanguage(stream, _user);
		stream.close();

		return true;
	}
Esempio n. 25
0
void EmberEntityMappingManager::parseScript (Ogre::DataStreamPtr &stream, const Ogre::String &groupName)
{
	TiXmlDocument xmlDoc;
	XMLHelper xmlHelper;
	if (!xmlHelper.Load(xmlDoc, stream)) {
		return;
	}

	mXmlSerializer.parseScript(xmlDoc, stream->getName());
}
Esempio n. 26
0
void Level::parseLevelFile(const Ogre::String &FileName, const Ogre::String &groupName, Ogre::SceneManager *sceneMgr, Ogre::SceneNode *AttachNode, const Ogre::String &prependNode)
{
	mGroupName = groupName;
	mSceneMgr = sceneMgr;
	mPrependNode = prependNode;

	TiXmlDocument *mXMLDoc = 0;
	TiXmlElement *mXMLRoot = 0;

	try
	{
		Ogre::String basename, path;
		Ogre::StringUtil::splitFilename(FileName, basename, path);

		Ogre::DataStreamPtr spStream = Ogre::ResourceGroupManager::getSingleton().openResource(basename,groupName);

		Ogre::String data = spStream->getAsString();

		mXMLDoc = new TiXmlDocument();
		mXMLDoc->Parse(data.c_str());

		spStream->close();
		spStream.setNull();

		mXMLRoot = mXMLDoc->RootElement();

		mAttachNode = AttachNode;


		if(!mAttachNode)
			mAttachNode = mSceneMgr->getRootSceneNode();

		parseScene(mXMLRoot);

		delete mXMLDoc;
	}
	catch(Ogre::Exception e)
	{
		Ogre::LogManager::getSingleton().logMessage("Level failed to load");
		delete mXMLDoc;
	}
}
ResourceWrapper OgreResourceProvider::getResource(const std::string& name)
{
  Ogre::DataStreamPtr input = Ogre::ResourceGroupManager::getSingleton().openResource(name, mGroupName);

  if (input.isNull()) {
    throw Exception("Unable to open resource file '" + name + "' in resource group '" + name + "'.");
  }
  OgreResourceWrapper* wrapper = new OgreResourceWrapper(input);
  input->close();
  return ResourceWrapper(wrapper, name);

// 	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);
}
 //--------------------------------------------------------------------------
 void
 FLevelFileSerializer::readSectionData( Ogre::DataStreamPtr &stream
                                       ,Ogre::DataStreamPtr &out_buffer )
 {
     uint32 length( 0 );
     readInt( stream, length );
     // TODO: implement SubDataStream class to restrict access size etc
     // so we don't have to copy the whole memory
     Ogre::MemoryDataStream *buffer( new Ogre::MemoryDataStream( length ) );
     stream->read( buffer->getPtr(), length );
     out_buffer = Ogre::DataStreamPtr( buffer );
 }
QByteArray *ResourceManager::read(const char *path, const char *group)
{
    Ogre::String groupName = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
    if (group)
        groupName = group;

    Ogre::DataStreamPtr dataStream = Ogre::ResourceGroupManager::getSingleton().openResource(path, groupName);

    int totalSize = dataStream->size();
    QScopedPointer<QByteArray> result(new QByteArray(totalSize, Qt::Uninitialized));

    int bytesRead = 0;
    char *buffer = result->data();
    while (bytesRead < totalSize) {
        int read = dataStream->read(buffer, totalSize - bytesRead);
        buffer += read;
        bytesRead += read;
    }

    return result.take();
}
Esempio n. 30
0
void GameScriptParser::parseScript(const Ogre::String &sFileName, const Ogre::String &sResourceGroupName) {
    m_sFileName = sFileName;
    m_sResourceGroupName = sResourceGroupName;
    clearIdMap();
    setWaitFor(PauseData::WAIT_DISABLED, Ogre::StringUtil::BLANK);

    // Strip the path
    Ogre::String basename, path;
    Ogre::StringUtil::splitFilename(sFileName, basename, path);

    Ogre::DataStreamPtr pStream = Ogre::ResourceGroupManager::getSingleton().openResource(basename, sResourceGroupName, false);
    Ogre::String data = pStream->getAsString();

    int status = luaL_loadstring(lua_state, data.c_str());
    int result = 0;
    if(status == LUA_OK) {
        result = lua_pcall(lua_state, 0, LUA_MULTRET, 0);
    }
    else {
        throw Ogre::Exception(__LINE__, "Could not load the lua script", __FILE__);
    }
}