Example #1
0
 void CollisionShapeManager::LoadAllShapesFromBinaryFile(const String& FileName, const String& Group)
 {
     btBulletWorldImporter Importer;
     Ogre::DataStreamPtr Stream = Ogre::ResourceGroupManager::getSingleton().openResource(FileName,Group);
     char* buffer = new char[Stream->size()];
     Stream->read((void*)buffer, Stream->size());
     if(!Importer.loadFileFromMemory(buffer, Stream->size()))
     {
         MEZZ_EXCEPTION(ExceptionBase::IO_FILE_EXCEPTION,"Failed to load file: " + FileName + ".")
     }
     delete[] buffer;
     for( Whole X = 0 ; X < Importer.getNumCollisionShapes() ; ++X )
     {
         btCollisionShape* Shape = Importer.getCollisionShapeByIndex(X);
         const char* MaybeAName = Importer.getNameForPointer((void*)Shape);
         String Name;
         if(MaybeAName)
         {
             Name = String(MaybeAName);
             ShapeMapIterator it = this->CollisionShapes.find(Name);
             if(it == this->CollisionShapes.end())
             {
                 CollisionShape* NewShape = this->WrapShape(Name,Shape);
                 this->CollisionShapes.insert( std::pair<String,CollisionShape*>(Name,NewShape) );
             }
         }else{
             static Whole NameCount = 0;
             Name = String("Unnamed") += StringTools::ConvertToString(NameCount++);
             CollisionShape* NewShape = this->WrapShape(Name,Shape);
             this->UnnamedShapes.push_back(NewShape);
         }
     }
 }
Example #2
0
//----------------------------------------------------------------------------//
int OggBuffer::vorbisSeek(void *datasource, ogg_int64_t offset, int whence)
{
	size_t				spaceToEOF;
	ogg_int64_t			actualOffset;
	Ogre::DataStreamPtr	vorbisData;

	vorbisData = *(Ogre::DataStreamPtr*)datasource;

	switch (whence)
	{
	case SEEK_SET:
		if (vorbisData->size() >= offset)
			actualOffset = offset;
		else
			actualOffset = vorbisData->size();
		vorbisData->seek((int)actualOffset);
		break;
	case SEEK_CUR:
		spaceToEOF = vorbisData->size() - vorbisData->tell();
		if (offset < spaceToEOF)
			actualOffset = (offset);
		else
			actualOffset = spaceToEOF;	
		vorbisData->seek( static_cast<size_t>(vorbisData->tell() + actualOffset));
		break;
	case SEEK_END:
		vorbisData->seek(vorbisData->size());
		break;
	default:
		SoundSystem::getSingleton().logMessage("*** ERROR *** Unknown seek command in VorbisSeek");
		break;
	};

	return 0;
}
// OgreScriptBuilder
int OgreScriptBuilder::LoadScriptSection(const char* full_path_cstr)
{
    // Get filename - required to retrieve file from OGRe's resource system.
    //  This function received filename in older AngelScript versions, but now receives full path
    //      (reconstructed wrong by CScriptBuilder because it doesn't know about OGRE's ZIP files).
    //  TODO: Refactor the entire script building logic 
    //      - create fully RoR-custom builder instead of hacked stock CScriptBuilder + our overload. ~ only_a_ptr, 08/2017

    std::string full_path(full_path_cstr);
    std::string filename;
    size_t slash_pos = full_path.rfind('/'); // AngelScript always uses forward slashes in paths.
    if (slash_pos != std::string::npos)
    {
        filename = full_path.substr(slash_pos+1);
    }
    else
    {
        filename = full_path;
    }

    Ogre::DataStreamPtr ds;
    try
    {
        ds = Ogre::ResourceGroupManager::getSingleton().openResource(filename, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME);
                 //TODO: do not use `AUTODETECT_RESOURCE_GROUP_NAME`, use specific group, lookups are slow!
                 //see also https://github.com/OGRECave/ogre/blob/master/Docs/1.10-Notes.md#resourcemanager-strict-mode ~ only_a_ptr, 08/2017
    }
    catch (Ogre::Exception e)
    {
        LOG("[RoR|Scripting] exception upon loading script file '"+filename+"', message: " + e.getFullDescription());
        return -1;
    }
    // In some cases (i.e. when fed a full path with '/'-s on Windows), `openResource()` will silently return NULL for datastream. ~ only_a_ptr, 08/2017
    if (ds.isNull())
    {
        LOG("[RoR|Scripting] Failed to load file '"+filename+"', reason unknown.");
        return -1;
    }

    // Read the entire file
    std::string code;
    code.resize(ds->size());
    ds->read(&code[0], ds->size());

    // hash it
    {
        char hash_result[250];
        memset(hash_result, 0, 249);
        RoR::CSHA1 sha1;
        sha1.UpdateHash((uint8_t *)code.c_str(), (uint32_t)code.size());
        sha1.Final();
        sha1.ReportHash(hash_result, RoR::CSHA1::REPORT_HEX_SHORT);
        hash = Ogre::String(hash_result);
    }

    return ProcessScriptSection(code.c_str(), code.length(), filename.c_str(), 0);
}
Example #4
0
    void GlobalMap::write(ESM::GlobalMap& map)
    {
        map.mBounds.mMinX = mMinX;
        map.mBounds.mMaxX = mMaxX;
        map.mBounds.mMinY = mMinY;
        map.mBounds.mMaxY = mMaxY;

        Ogre::DataStreamPtr encoded = mOverlayImage.encode("png");
        map.mImageData.resize(encoded->size());
        encoded->read(&map.mImageData[0], encoded->size());
    }
Example #5
0
/*void TestStream()
{
	//String fname( "../../media/packs/chiropteraDM.txt");
	std::ifstream* roStream = new std::ifstream;
	roStream ->open	("../../media/packs/chiropteraDM.txt", std::ios::in | std::ios::binary);
	//fptr =  new FileStreamDataStream("tt", roStream, true);
	//fstrm = DataStreamPtr(fptr);
	DataStreamPtr ss = DataStreamPtr(new LodDataStream( Ogre::SharedPtr<std::ifstream>(roStream),	0x203,500));
	std::cout <<  ss -> size() << endl;
	while(!ss->eof())
	{
		cout << ss->getLine(false) << endl;
	}
	cout << 
		ss->getAsString() 
		<< endl;
}*/
void SaveStreamToFile(const Ogre::String& fname, Ogre::DataStreamPtr data)
{
	char*buff = new char[data->size()];
	std::ios::openmode mode = std::ios::binary | std::ios::out;
	std::ofstream rwStream;
	data->read(buff,data->size());
	rwStream.open(fname, mode);
	rwStream.write(buff,data->size());
	rwStream.close();
	delete[] buff;
	std::cout << "Saved: " << fname << " size: "<<data->size() << std::endl;
}
Example #6
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;
}
Example #7
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());
    }
Example #8
0
bool XMLHelper::Load(TiXmlDocument& xmlDoc, Ogre::DataStreamPtr stream)
{
	size_t length(stream->size());

	if ( length )
	{
		// If we have a file, assume it is all one big XML file, and read it in.
		// The document parser may decide the document ends sooner than the entire file, however.
		std::string data(stream->getAsString());

		xmlDoc.Parse( data.c_str());

		if (xmlDoc.Error() ) {
			std::string errorDesc = xmlDoc.ErrorDesc();
			int errorLine =  xmlDoc.ErrorRow();
			int errorColumn =  xmlDoc.ErrorCol();
			std::stringstream ss;
			ss << "Failed to load xml file '" << stream->getName() << "'! Error at column: " << errorColumn << " line: " << errorLine << ". Error message: " << errorDesc;
			S_LOG_FAILURE(ss.str());
			return false;
		} else {
            return true;
		}
	}
	return false;
}
Example #9
0
bool gkAndroidApp::setup(void) {
    AAssetManager* assetMgr = m_state->activity->assetManager;
    if (assetMgr) {
        Ogre::ArchiveManager::getSingleton().addArchiveFactory(new Ogre::APKFileSystemArchiveFactory(assetMgr));
        Ogre::ArchiveManager::getSingleton().addArchiveFactory(new Ogre::APKZipArchiveFactory(assetMgr));
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation("/", "APKFileSystem",
                Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    }

    Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().
            openResource(m_blend, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    if (stream.isNull()) {
        gkPrintf("Error: Can't open file %s.\n", m_blend.c_str());
        return false;
    }

    size_t size = stream->size();
    char* buf = new char[size];
    stream->read(buf, size);

    gkBlendFile* blend = gkBlendLoader::getSingleton().loadFromMemory(buf,size,gkBlendLoader::LO_ALL_SCENES);
    gkScene* scene = blend->getMainScene();
    if (!scene) {
        gkPrintf("No usable scenes found in blend.\n");
        return false;
    }

    scene->createInstance();
    scene->getMainCamera()->getCamera()->setAutoAspectRatio(true);

    return true;
}
Example #10
0
//----------------------------------------------------------------------------//
size_t OggBuffer::vorbisRead(void *ptr, size_t byteSize, size_t sizeToRead, void *datasource )
{
	size_t				spaceToEOF;			// How much more we can read till we hit the EOF marker
	size_t				actualSizeToRead;	// How much data we are actually going to read from memory
	Ogre::DataStreamPtr	vorbisData;			// Our vorbis data, for the typecast

	// Get the data in the right format
	vorbisData = *(Ogre::DataStreamPtr*)datasource;

	// Calculate how much we need to read.  This can be sizeToRead*byteSize or less depending on how near the EOF marker we are
	spaceToEOF = vorbisData->size() - vorbisData->tell();
	if ((sizeToRead * byteSize) < spaceToEOF)
		actualSizeToRead = (sizeToRead * byteSize);
	else
		actualSizeToRead = spaceToEOF;	
	
	// A simple copy of the data from memory to the datastruct that the vorbis libs will use
	if (actualSizeToRead)
	{
		// Copy the data from the start of the file PLUS how much we have already read in
		vorbisData->read(ptr, actualSizeToRead);
	}

	// Return how much we read (in the same way fread would)
	return actualSizeToRead;
}
Example #11
0
	void SnowTerrain::defineTerrain(long x, long y, bool flat)
	{
		if (flat)
		{
			mTerrainGroup->defineTerrain(x, y, 0.0f);
		}
		else
		{
			if(StringUtil::endsWith(mSnowConfig->terrainSettings.heightDataFile, "dat"))
			{
				mTerrainGroup->defineTerrain(x, y, mSnowConfig->terrainSettings.heightDataFile);
				mTerrainGroup->loadTerrain(x,y, true);
			}
			else 
			{
				Image *img = new Image();

				if(StringUtil::endsWith(mSnowConfig->terrainSettings.heightDataFile, "raw"))
				{
					Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(mSnowConfig->terrainSettings.heightDataFile, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
					size_t size = stream->size();
					img->loadRawData(stream, mTerrainSize-1, mTerrainSize-1, 1, PixelFormat::PF_FLOAT32_R);

					// height data must be square			
					assert(img->getWidth() == img->getHeight());

					// resize the height data if it's the wrong size
					if(img->getWidth() != mTerrainSize)
						img->resize(mTerrainSize, mTerrainSize);

					//img->flipAroundY();

					//mTerrainGroup->defineTerrain(x, y, (float*)img->getPixelBox().data);
					mTerrainGroup->defineTerrain(x, y, img);
					mTerrainGroup->loadTerrain(x,y, true);

				}
				else if(StringUtil::endsWith(mSnowConfig->terrainSettings.heightDataFile, "png")||StringUtil::endsWith(mSnowConfig->terrainSettings.heightDataFile, "bmp"))
				{
 					img->load(mSnowConfig->terrainSettings.heightDataFile, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);		

					// height data must be square			
					assert(img->getWidth() == img->getHeight());

					// resize the height data if it's the wrong size
					if(img->getWidth() != mTerrainSize)
						img->resize(mTerrainSize, mTerrainSize);

					mTerrainGroup->defineTerrain(x, y, img);
					mTerrainGroup->loadTerrain(x,y, true);
				}


			}
		
			
			mTerrainsImported = true;
		}
	}
	//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();
	}
int64_t OgreResource_Seek(void *user_data, int64_t offset, int whence)
{
    Ogre::DataStreamPtr stream = static_cast<VideoState*>(user_data)->stream;

    whence &= ~AVSEEK_FORCE;
    if(whence == AVSEEK_SIZE)
        return stream->size();
    if(whence == SEEK_SET)
        stream->seek((size_t)offset);
    else if(whence == SEEK_CUR)
		stream->seek((size_t)(stream->tell() + offset));
    else if(whence == SEEK_END)
		stream->seek((size_t)(stream->size() + offset));
    else
        return -1;

    return stream->tell();
}
Example #14
0
int64_t FFmpeg_Decoder::seek(void *user_data, int64_t offset, int whence)
{
    Ogre::DataStreamPtr stream = static_cast<FFmpeg_Decoder*>(user_data)->mDataStream;

    whence &= ~AVSEEK_FORCE;
    if(whence == AVSEEK_SIZE)
        return stream->size();
    if(whence == SEEK_SET)
        stream->seek(offset);
    else if(whence == SEEK_CUR)
        stream->seek(stream->tell()+offset);
    else if(whence == SEEK_END)
        stream->seek(stream->size()+offset);
    else
        return -1;

    return stream->tell();
}
//-----------------------------------------------------------------------------------------
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;
}
Example #16
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;
	}
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();
}
Example #18
0
bool RocketInterface::Seek(Rocket::Core::FileHandle file, long offset, int origin)
{
    if (!file)
        return false;

    Ogre::DataStreamPtr stream = *reinterpret_cast<Ogre::DataStreamPtr*>(file);
    long pos = 0;
    size_t size = stream->size();

    if (origin == SEEK_CUR)
        pos = stream->tell() + offset;
    else if (origin == SEEK_END)
        pos = size + offset;
    else
        pos = offset;

    if (pos < 0 || pos > (long)size)
        return false;

    stream->seek((size_t)pos);
    return true;
}
qint64 OgreNetworkReply::bytesAvailable() const
{
    if (mDataStream.isNull())
        return 0;
    return QNetworkReply::bytesAvailable() + mDataStream->size() - mDataStream->tell();
}
Example #20
0
gkBlendListIterator::gkBlendListIterator(List* list)
	:	m_list(list),
#if OGREKIT_USE_BPARSE
		m_index(0)
#else
		m_index(list ? list->first : 0)
#endif
{
}

bool gkBlendListIterator::hasMoreElements() const
{
	if (m_list == 0) return false;

#if OGREKIT_USE_BPARSE
	return m_index < m_list->size();
#else
	return m_index != 0;
#endif
}


gkBlendListIterator::ListItem* gkBlendListIterator::getNext(void)	 
{ 
#if OGREKIT_USE_BPARSE
	return m_list->at(m_index++);
#else
	ListItem* item = m_index;
	m_index = m_index->next;
	return item;
#endif
}

//--

gkBlendInternalFile::gkBlendInternalFile()
	:	m_file(0)
{
}

gkBlendInternalFile::~gkBlendInternalFile()
{
	delete m_file;
	m_file = 0;
}

bool gkBlendInternalFile::parse(const gkString& fname)
{

	if (fname.empty()) 
	{
		gkLogMessage("BlendFile: File " << fname << " loading failed. File name is empty.");
		return false;
	}

#if OGREKIT_USE_BPARSE

	utMemoryStream fs;
	fs.open(fname.c_str(), utStream::SM_READ);

	if (!fs.isOpen())
	{
		gkLogMessage("BlendFile: File " << fname << " loading failed. No such file.");
		return false;
	}

	// Write contents and inflate.
	utMemoryStream buffer(utStream::SM_WRITE);
	fs.inflate(buffer);

	m_file = new bParse::bBlenderFile((char*)buffer.ptr(), buffer.size());
	m_file->parse(false);

	if (!m_file->ok())
	{
		gkLogMessage("BlendFile: File " << fname << " loading failed. Data error.");
		return false;
	}

#else

	m_file = new fbtBlend();
	int status = m_file->parse(fname.c_str(), fbtFile::PM_COMPRESSED);
	if (status != fbtFile::FS_OK)
	{
		delete m_file;
		m_file = 0;
		gkLogMessage("BlendFile: File " << fname << " loading failed. code: " << status);
		//return false;
	}
	else 
	{
		 gkLogMessage("BlendFile: File " << fname << " loading end1" );
	    return true;
	}
	//gkLogMessage("BlendFile: File " << fname << " loading end" );
	m_file = new fbtBlend();
	Ogre::DataStreamPtr stream;
	Ogre::ArchiveManager::ArchiveMapIterator beginItera = Ogre::ArchiveManager::getSingleton().getArchiveIterator();
	while(beginItera.hasMoreElements())
	{
		typedef std::map<Ogre::String, Ogre::Archive*>::iterator ArchiveIterator;
		ArchiveIterator arch = beginItera.current();	
		if (arch->second)
		{
			 Ogre::FileInfoListPtr fileInfo = arch->second->findFileInfo(fname);
			 if (fileInfo->size() > 0)
			 {
				 stream = arch->second->open(fname);
				 gkLogMessage("BlendFile: File found create stream");
				 break;
			 }
		}
		beginItera.moveNext();
	}
	//gkLogMessage("malloc buffer");
	unsigned char * buffer = new unsigned char[stream->size()];
	//gkLogMessage(" stream->read ");
    long sizeCount = stream->read(buffer,stream->size());
    //gkLogMessage(" m_file->parse");
	if(m_file) m_file->parse(buffer,sizeCount);
	delete buffer;
	//gkLogMessage(" m_file->parse end");
#endif
	return true;
}


Blender::FileGlobal* gkBlendInternalFile::getFileGlobal()
{
	GK_ASSERT(m_file);
	
#if OGREKIT_USE_BPARSE
	return (Blender::FileGlobal*)m_file->getFileGlobal();
#else
	return m_file->m_fg;
#endif
}

int gkBlendInternalFile::getVersion()
{
	GK_ASSERT(m_file);

#if OGREKIT_USE_BPARSE
	return m_file->getMain()->getVersion();
#else
	return m_file->getVersion();
#endif
}
    // ----------------------------------------------------------------------
    void FontSerializer::importFont(Ogre::DataStreamPtr &stream, Font *pDest)
    {
        uint32 fccomp;
        stream->read(&fccomp, sizeof(uint32));
        if(fccomp != Font::mFourCC)
            SONETTO_THROW("Invalid Font File");
        stream->read(&pDest->mVersion, sizeof(uint32));
        stream->read(&pDest->mEncode, sizeof(uint32));
        stream->read(&pDest->mVerticalOffsetTop, sizeof(float));
        stream->read(&pDest->mVerticalOffsetBottom, sizeof(float));
        stream->read(&pDest->mHorizontalScale, sizeof(float));

        pDest->mIName = loadString(stream);

        // setup material
        pDest->mMaterial = Ogre::MaterialManager::getSingleton().create(pDest->mIName+"_mat",pDest->getGroup());

        if(pDest->mMaterial.isNull())
            SONETTO_THROW("Unable to create material for font.");

        Ogre::Pass * pass = pDest->mMaterial->getTechnique(0)->getPass(0);

        bool has_separate_blend;
        uint32 mat_scene_blend_source;
        uint32 mat_scene_blend_dest;
        uint32 mat_scene_blend_source_a;
        uint32 mat_scene_blend_dest_a;
        stream->read(&has_separate_blend, sizeof(bool));
        stream->read(&mat_scene_blend_source, sizeof(uint32));
        stream->read(&mat_scene_blend_dest, sizeof(uint32));
        stream->read(&mat_scene_blend_source_a, sizeof(uint32));
        stream->read(&mat_scene_blend_dest_a, sizeof(uint32));

        if(has_separate_blend)
        {
            pass->setSeparateSceneBlending( (Ogre::SceneBlendFactor)mat_scene_blend_source,
                                            (Ogre::SceneBlendFactor)mat_scene_blend_dest,
                                            (Ogre::SceneBlendFactor)mat_scene_blend_source_a,
                                            (Ogre::SceneBlendFactor)mat_scene_blend_dest_a);
        } else {
            pass->setSceneBlending((Ogre::SceneBlendFactor)mat_scene_blend_source,(Ogre::SceneBlendFactor)mat_scene_blend_dest);
        }
        uint32 mat_alpha_reject_func;
        uint8 mat_alpha_reject_val;
        bool map_alpha_reject_atc;
        stream->read(&mat_alpha_reject_func, sizeof(uint32));
        stream->read(&mat_alpha_reject_val, sizeof(uint8));
        stream->read(&map_alpha_reject_atc, sizeof(bool));

        pass->setAlphaRejectSettings((Ogre::CompareFunction) mat_alpha_reject_func, mat_alpha_reject_val, map_alpha_reject_atc);

        pass->setDepthCheckEnabled(false);
        pass->setDepthWriteEnabled(false);
        pass->setLightingEnabled(false);

        Ogre::TextureUnitState * tex_unit = pass->createTextureUnitState();

        uint32 tex_address_mode_u;
        uint32 tex_address_mode_v;
        uint32 tex_address_mode_w;
        uint32 tex_filtering_min;
        uint32 tex_filtering_mag;
        Ogre::ColourValue tex_border_color;
        stream->read(&tex_address_mode_u, sizeof(uint32));
        stream->read(&tex_address_mode_v, sizeof(uint32));
        stream->read(&tex_address_mode_w, sizeof(uint32));
        stream->read(&tex_filtering_min, sizeof(uint32));
        stream->read(&tex_filtering_mag, sizeof(uint32));
        stream->read(tex_border_color.ptr(), sizeof(float) * 4);

        tex_unit->setTextureAddressingMode( (Ogre::TextureUnitState::TextureAddressingMode) tex_address_mode_u,
                                            (Ogre::TextureUnitState::TextureAddressingMode) tex_address_mode_v,
                                            (Ogre::TextureUnitState::TextureAddressingMode) tex_address_mode_w);
        tex_unit->setTextureFiltering((Ogre::FilterOptions)tex_filtering_min, (Ogre::FilterOptions)tex_filtering_mag, Ogre::FO_NONE);
        tex_unit->setTextureBorderColour(tex_border_color);

        uint32 numcol = 0;
        stream->read(&numcol, sizeof(uint32));
        for(uint32 l = 0; l != numcol; ++l)
        {
            std::cout << "reading color #"<<l<<"...\n";
            Ogre::ColourValue color;
            stream->read(color.ptr(), sizeof(float) * 4);
            pDest->mColorList.push_back(color);
            std::cout << "color #"<<l<<" read complete...\n";
        }
        std::cout << "all color values have been read correctly...\n";
        std::cout << "reading font glyph list...\n";
        for(uint16 i = 0; i != 256; ++i)
        {
            std::cout << "reading glyph #"<<(int)i<<"...\n";
            FontGlyph glyph;
            stream->read(&glyph, sizeof(FontGlyph));
            pDest->mGlyph.push_back(glyph);
            std::cout << "glyph #"<<(int)i<<" read complete...\n";
        }
        std::cout << "all font glyph have been read correctly...\n";
        // size_t width, size_t height, size_t depth, size_t pixel format
        size_t txt_width, txt_height, txt_depth, txt_pixelformat, txt_faces, txt_mipmaps = 0;
        stream->read(&txt_width, sizeof(size_t));
        stream->read(&txt_height, sizeof(size_t));
        stream->read(&txt_depth, sizeof(size_t));
        stream->read(&txt_pixelformat, sizeof(size_t));
        stream->read(&txt_faces, sizeof(size_t));
        stream->read(&txt_mipmaps, sizeof(size_t));

        std::cout <<
        "Loading Font Texture Data...\n"
        "Texture Width: "<<txt_width<<"\n"
        "Texture Height: "<<txt_height<<"\n"
        "Texture Depth: "<<txt_depth<<"\n"
        "Texture Pixel Format: "<<txt_pixelformat<<"\n"
        "Texture Faces: "<<txt_faces<<"\n"
        "Texture Mipmaps: "<<txt_mipmaps<<"\n";

        pDest->mFontImage = new Ogre::Image();

        size_t totalimagesize = Ogre::Image::calculateSize(txt_mipmaps, txt_faces, txt_width, txt_height, txt_depth, (Ogre::PixelFormat)txt_pixelformat);

        std::cout << "Current position at file: "<<stream->tell()<<"\n"
        "Target Image Size: "<<totalimagesize<<"\n"
        "Remaining File Size: "<<stream->size()<<"\n";

        unsigned char * imgbuffer = new unsigned char [totalimagesize];

        stream->read(imgbuffer, totalimagesize);

        pDest->mFontImage->loadDynamicImage(imgbuffer, txt_width, txt_height, txt_depth, (Ogre::PixelFormat)txt_pixelformat, true, txt_faces, txt_mipmaps);

        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().loadImage(pDest->mIName+"_tex",pDest->getGroup(), *pDest->mFontImage, Ogre::TEX_TYPE_2D, 0);

        tex_unit->setTextureName(texture->getName(), Ogre::TEX_TYPE_2D);
    }
Example #22
0
bool MapLoader::loadMapFormFile(std::string mapname)
{
	int mapsize;
	Terrain* terrain = Terrain::getSingletonPtr();
	DataLibrary* datalibrary = DataLibrary::getSingletonPtr();
	std::string path = ".\\..\\Media\\Map\\" + mapname;

	//ticpp::Document *doc = new ticpp::Document();
	rapidxml::xml_document<> doc;
	//doc.LoadFile(path,TIXML_ENCODING_UTF8);
	Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(mapname, "Data", true);
	char* s=new char[stream->size()+1];
	stream->read(s,stream->size());
	s[stream->size()]='\0';
	doc.parse<0>(s);

	std::string str1;
	//载入地图名字,介绍和脚本名
	//ticpp::Element *element = doc.FirstChildElement("MapName");
	rapidxml::xml_node<> * element = doc.first_node("MapName");
	//element->GetText(&str1);
	str1 = element->value();
	datalibrary->setData("GameData/BattleData/MapData/MapName", StringTable::getSingleton().getString(str1));
	//delete element;

	//element = doc.FirstChildElement("MapScript");
	element = doc.first_node("MapScript");
	//element->GetText(&str1);
	str1 = element->value();
	datalibrary->setData("GameData/BattleData/MapData/MapScript", str1);
	//delete element;

	element = doc.first_node("MapMini");
	//element->GetText(&str1);
	
	if (element!=NULL)
	{
		str1 = element->value();
	}
	else
	{
		str1="MiniMap1.png";
	}
	
	datalibrary->setData("GameData/BattleData/MapData/MapMini", str1);

	//element = doc.FirstChildElement("MapInfo");
	element = doc.first_node("MapInfo");
	//element->GetText(&str1);
	str1 = element->value();
	datalibrary->setData("GameData/BattleData/MapData/MapInfo",str1);
	//delete element;

	//element = doc.FirstChildElement("MapLoadBG");
	element = doc.first_node("MapLoadBG");
	//element->GetText(&str1);
	str1 = element->value();
	datalibrary->setData("GameData/BattleData/MapData/MapLoadBG",str1);
	//delete element;

	//载入地图地形信息
	//element = doc.FirstChildElement("MapSize");
	element = doc.first_node("MapSize");
	//element->GetText(&mapsize);
	mapsize = Ogre::StringConverter::parseUnsignedInt(element->value());
	MapDataManager::getSingleton().mMapSize = mapsize;
	datalibrary->setData("GameData/BattleData/MapData/MapSize", mapsize);
	//delete element;

	//element= doc.FirstChildElement("MapGround");
	element = doc.first_node("MapGround");
	//ticpp::Iterator<ticpp::Element> child;
	rapidxml::xml_node<> *child = element->first_node();
	std::string datapath;
	//for(child = child.begin(element); child != child.end(); child++)
	for(; child; child =child->next_sibling())
	{
		std::string layer,type,texture;
		//child->GetValue(&layer);
		layer = child->name();
		//child->GetAttribute("Type",&type);
		rapidxml::xml_attribute<> *attr = child->first_attribute("Type");
		type = attr->value();
		//child->GetAttribute("Texture",&texture);
		attr = child->first_attribute("Texture");
		texture = attr->value();
		datapath = str(boost::format("GameData/BattleData/MapData/Ground/%1%")%layer);
		datalibrary->setData(datapath, type);
		datapath = str(boost::format("GameData/BattleData/MapData/Ground/%1%Tex")%layer);
		datalibrary->setData(datapath, texture);
	}
	//delete element;

	//element = doc.FirstChildElement("MapData");
	element = doc.first_node("MapData");
	//element->GetText(&str1);
	str1 = element->value();
	for(int y = 0; y < mapsize; y++)
	{
		for(int x = 0; x < mapsize; x++)
		{
			int index = y * mapsize + x;
			char datapathtemp[64];
			sprintf_s(datapathtemp, 64, "GameData/BattleData/MapData/Map/M%d", MapDataManager::getSingleton().getGridId(x, y));
			std::string datapath = datapathtemp;
			if(str1[index * 2] == 'l')
			{
				bool iscliff = false;
				for(int i = y - 1; i < y + 2; i ++)
				{
					for(int j =  x - 1; j < x + 2; j++)
					{
						int u = (i<0)?0:i;
						u = (u >= mapsize)?mapsize-1:u;
						int v = (j<0)?0:j;
						v = (v >= mapsize)?mapsize-1:v;
						int tempindex = u * mapsize + v;
						if(str1[tempindex * 2] == 'h' )
						{	
							iscliff = true;
						}
					}
				}
				if(iscliff)
					datalibrary->setData(datapath + "/TerrainType", Cliff);
				else
					datalibrary->setData(datapath + "/TerrainType", LowGround);
			}
			else if(str1[index * 2] == 'w')
			{
				datalibrary->setData(datapath + "/TerrainType", Water);
			}
			else if(str1[index * 2] == 'h')
			{
				datalibrary->setData(datapath + "/TerrainType", HighGround);
			}
			else if(str1[index * 2] == 'r')
			{
				datalibrary->setData(datapath + "/TerrainType", Ramp);
			}

			if(str1[index * 2+1] == 'g')
			{
				datalibrary->setData(datapath + "/GroundType", GreenLand);
			}
			else if(str1[index * 2+1] == 'd')
			{
				datalibrary->setData(datapath + "/GroundType", Desert);
			}
			else if(str1[index * 2+1] == 'w')
			{
				datalibrary->setData(datapath + "/GroundType", Swamp);
			}
			else if(str1[index * 2+1] == 's')
			{
				datalibrary->setData(datapath + "/GroundType", Snow);
			}
		}
	}
	//delete element;

	//element = doc.FirstChildElement("MapObject");
	element = doc.first_node("MapObject");
	//for(child = child.begin(element); child != child.end(); child++)
	for(child = element->first_node(); child; child =child->next_sibling())
	{
		std::string objname;
		//child->GetValue(&objname);
		objname = child->name();
		datapath = std::string("GameData/BattleData/MapData/MapObjModleInfo/") + objname;
		int objx,objy, objdir;
		std::string meshname,objtype;
		//child->GetAttribute("GridX",&objx);
		rapidxml::xml_attribute<> *attr = child->first_attribute("GridX");
		objx = Ogre::StringConverter::parseInt(attr->value());
		//child->GetAttribute("GridY",&objy);
		attr = child->first_attribute("GridY");
		objy = Ogre::StringConverter::parseInt(attr->value());
		//child->GetAttribute("Mesh",&meshname);
		attr=child->first_attribute("Mesh");
		meshname = attr->value();
		//child->GetAttribute("Type",&objtype);
		attr=child->first_attribute("Type");
		objtype = attr->value();
		attr=child->first_attribute("Direction");
		objdir = Ogre::StringConverter::parseInt(attr->value());
		datalibrary->setData(datapath + "/GridX", objx);
		datalibrary->setData(datapath + "/GridY", objy);
		datalibrary->setData(datapath + "/Mesh", meshname);
		datalibrary->setData(datapath + "/Direction", objdir);
		//物品类型脚本
		std::string mapobjscript("none");
		datalibrary->getData(str(boost::format("StaticData/MapObjType/%1%/Script")%objtype), mapobjscript);
		datapath = std::string("GameData/BattleData/MapData/Map/M") + Ogre::StringConverter::toString(MapDataManager::getSingleton().getGridId(objx, objy)) + std::string("/MapObjType");
		if(mapobjscript != "none")
		{
			MapObjScriptInfo scriptinfo;
			scriptinfo.x = objx;
			scriptinfo.y = objy;
			scriptinfo.script = mapobjscript;
			scriptinfo.path = datapath + "/ScriptContext";
			mMapObjScriptInfo.push(scriptinfo);
		}
		datalibrary->setData(datapath, objtype);
		datalibrary->setData(datapath + "/MapObjModuleId", objname);
	}
	//delete element;

	//element = doc.FirstChildElement("MapEffect");
	element = doc.first_node("MapEffect");
	//for(child = child.begin(element); child != child.end(); child++)
	for(child = element->first_node(); child; child =child->next_sibling())
	{
		std::string particlename;
		//child->GetValue(&particlename);
		particlename = child->name();
		datapath = std::string("GameData/BattleData/MapData/MapParticleInfo/") + particlename;
		int particlex,particley;
		std::string name;
		//child->GetAttribute("GridX",&particlex);
		rapidxml::xml_attribute<> *attr = child->first_attribute("GridX");
		particlex = Ogre::StringConverter::parseInt(attr->value());
		//child->GetAttribute("GridY",&particley);
		attr = child->first_attribute("GridY");
		particley = Ogre::StringConverter::parseInt(attr->value());
		//child->GetAttribute("Type",&name);
		attr = child->first_attribute("Type");
		name = attr->value();
		datalibrary->setData(datapath + "/GridX", particlex);
		datalibrary->setData(datapath + "/GridY", particley);
		datalibrary->setData(datapath + "/Type", name);
	}

	terrain->createTerrain();
	//delete element;

	//载入区域信息
	//element = doc.FirstChildElement("MapArea");
	element = doc.first_node("MapArea");
	//for(child = child.begin(element); child != child.end(); child++)
	for(child = element->first_node(); child; child =child->next_sibling())
	{
		std::string areaname;
		//child->GetValue(&areaname);
		areaname = child->name();
		datapath = std::string("GameData/BattleData/MapData/Area/") + areaname;
		Area area(datapath + "/CoordList");
		std::vector<Crood> croodVec;
		//ticpp::Iterator<ticpp::Element> childchild;
		rapidxml::xml_node<> *childchild = child->first_node();
		//for(childchild = childchild.begin(child.Get()); childchild != childchild.end(); childchild++)
		for(; childchild; childchild=childchild->next_sibling())
		{
			std::string coordname;
			//childchild->GetValue(&coordname);
			coordname = childchild->name();
			int x;
			int y;
			//childchild->GetAttribute("X",&x);
			rapidxml::xml_attribute<> *attr = childchild->first_attribute("X");
			x = Ogre::StringConverter::parseInt(attr->value());
			//childchild->GetAttribute("Y",&y);
			attr = childchild->first_attribute("Y");
			y = Ogre::StringConverter::parseInt(attr->value());
			croodVec.push_back(Crood(x, y));
		}
		area.setCroodVec(croodVec);
		MapDataManager::getSingleton().mMapArea.insert(std::make_pair(areaname, area));

	}
	//delete element;

	//载入队伍信息
	//element = doc.FirstChildElement("MapTeam");
	element = doc.first_node("MapTeam");
	for(int n = 2; n < 5; n++)
	{
		std::string name = std::string("Team") + Ogre::StringConverter::toString(n);
		std::string factionid;
		//ticpp::Element* subelement = element->FirstChildElement(name);
		child = element->first_node(name.c_str());
		//subelement->GetAttribute("TeamFaction",&factionid);
		rapidxml::xml_attribute<> *attr = child->first_attribute("TeamFaction");
		factionid = attr->value();
		datalibrary->setData(std::string("GameData/BattleData/Team/")+ name+ "/FactionId", factionid);
		if(factionid != "none")
		{
			//subelement->GetAttribute("TeamType",&factionid);
			attr = child->first_attribute("TeamType");
			factionid = attr->value();
			datalibrary->setData(std::string("GameData/BattleData/Team/")+ name+ "/Relation", factionid);
		}
		//delete subelement;
	}
	std::string playerfactionid;
	datalibrary->getData("GameData/StoryData/Faction",playerfactionid);
	datalibrary->setData("GameData/BattleData/Team/Team1/FactionId",playerfactionid);
	datalibrary->setData("GameData/BattleData/Team/Team1/Relation","player");
	//delete element;

	//载入部队信息
	//element = doc.FirstChildElement("MapSquad");
	element = doc.first_node("MapSquad");
	MapSquadInfo mapsquadinfo;
	//for(child = child.begin(element); child != child.end(); child++)
	for(child = element->first_node(); child;child = child->next_sibling())
	{
		std::string teamid;
		//child->GetValue(&teamid);
		teamid = child->name();
		if(teamid == "Team1")
			mapsquadinfo.team = 1;
		else if(teamid == "Team2")
			mapsquadinfo.team = 2;
		else if(teamid == "Team3")
			mapsquadinfo.team = 3;
		else
			mapsquadinfo.team = 4;
		datapath = std::string("GameData/BattleData/SquadList");
		//ticpp::Iterator<ticpp::Element> childchild;
		rapidxml::xml_node<> *childchild = child->first_node();
		//for(childchild = childchild.begin(child.Get()); childchild != childchild.end(); childchild++)
		for(; childchild; childchild =childchild->next_sibling())
		{
// 			std::string squadid;
// 			std::string squadtype;
			//childchild->GetValue(&mapsquadinfo.squadId);
			mapsquadinfo.squadId = childchild->name();
// 			int x;
// 			int y;
// 			Direction d;
// 			int unitnum;
// 			int morale;
			//childchild->GetAttribute("Type",&mapsquadinfo.squadTempId);
			rapidxml::xml_attribute<> *attr = childchild->first_attribute("Type");
			mapsquadinfo.squadTempId = attr->value();
			//childchild->GetAttribute("GridX",&mapsquadinfo.x);
			attr = childchild->first_attribute("GridX");
			mapsquadinfo.x = Ogre::StringConverter::parseInt(attr->value());
			//childchild->GetAttribute("GridY",&mapsquadinfo.y);
			attr = childchild->first_attribute("GridY");
			mapsquadinfo.y = Ogre::StringConverter::parseInt(attr->value());
			//childchild->GetAttribute("UnitNum",&mapsquadinfo.unitNum);
			attr = childchild->first_attribute("UnitNum");
			mapsquadinfo.unitNum = Ogre::StringConverter::parseInt(attr->value());
			//childchild->GetAttribute("Direction",&mapsquadinfo.dir);
			attr = childchild->first_attribute("Direction");
			mapsquadinfo.dir = Ogre::StringConverter::parseInt(attr->value());
			mMapSquadInfo.push(mapsquadinfo);
// 			AVGSquadManager::getSingleton().addSquad(squadid,squadtype, datapath);
// 			int type;
// 			Formation f;
// 			datalibrary->getData(datapath + std::string("/") + squadid + std::string("/Type"), type );
// 			if(type == SQUAD_NORMAL)
// 				f = Line;
// 			else
// 				f = Loose;
// 			datalibrary->setData(datapath + std::string("/") + squadid + std::string("/GridX"), x, true );
// 			datalibrary->setData(datapath + std::string("/") + squadid + std::string("/GridY"), y, true );
// 			datalibrary->setData(datapath + std::string("/") + squadid + std::string("/UnitNumber"), unitnum, true );
// 			datalibrary->setData(datapath + std::string("/") + squadid + std::string("/Direction"), d, true );
// 			datalibrary->setData(datapath + std::string("/") + squadid + std::string("/Formation"), f, true );
// 			datalibrary->setData(datapath + std::string("/") + squadid + std::string("/TeamId"), teamid, true );
// 			datalibrary->setData(datapath + std::string("/") + squadid + std::string("/CreateType"), MapSquad, true );
// 			datalibrary->setData(datapath + std::string("/") + squadid + std::string("/ActionPoint"), 0.0f, true );
// 			datalibrary->setData(datapath + std::string("/") + squadid + std::string("/Morale"), morale, true );
		}
	}
	//delete element;
	delete []s;
	return true;
}
Example #23
0
 size_t size() const {
     return inp->size();
 }
Example #24
0
Ogre::Codec::DecodeResult MTGACodec::decode(Ogre::DataStreamPtr& stream) const
{
	// Read 4 character code
	mtga_header_s hdr;
	//uint32 fileType;
	stream->read(&hdr, sizeof(hdr));
	if (LodResource_Bitmap != hdr.magic)
	{
		OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
			"This is not a MTGA file!", "MTGACodec::decode");
	}
	
	mtga_pal_s pal[256];
	assert(stream->size() == sizeof(hdr)+hdr.uncompressedSize + sizeof(pal));

	stream->seek(sizeof(mtga_header_s)+hdr.uncompressedSize);
	stream->read(pal,sizeof(pal));

	bool isTransparent = false;
	mtga_pal_s& clr = pal[0];
	if( (clr.r == 0 && clr.g >250 && clr.b > 250) || (clr.r > 250 && clr.g ==0 && clr.b > 250))
		isTransparent = true;


	Ogre::ImageCodec::ImageData* imgData = OGRE_NEW Ogre::ImageCodec::ImageData();
	imgData->format = PF_BYTE_BGRA;
	imgData->width = hdr.width;
	imgData->height = hdr.height;
	imgData->num_mipmaps = 3;
	imgData->depth = 1;

	imgData->size = Image::calculateSize(imgData->num_mipmaps, 1, 
			imgData->width, imgData->height, imgData->depth, imgData->format);
	
	Ogre::MemoryDataStreamPtr pixelData;
	
	pixelData.bind(OGRE_NEW MemoryDataStream(imgData->size));

	// Now deal with the data
	unsigned char* destPtr = pixelData->getPtr();
	stream->seek(sizeof(mtga_header_s));
	size_t width = hdr.width;
	size_t height = hdr.height;
	for(size_t mip = 0; mip <= imgData->num_mipmaps; ++mip)
	{
			for (size_t y = 0; y < height; y ++)
			{
				for (size_t x = 0; x < width; x ++)
				{
					unsigned char idx;
					stream->read(&idx,1);
					mtga_pal_s& clr = pal[idx];
					assert(destPtr-pixelData->getPtr() < imgData->size);
					
					*destPtr++ = clr.b;
					*destPtr++ = clr.g;
					*destPtr++ = clr.r;
					*destPtr++ = (idx == 0 && isTransparent)?0:255;
				}
			}
			width /=2;
			height /=2;

	}
	


	DecodeResult ret;
	ret.first = pixelData;
	ret.second = CodecDataPtr(imgData);
	return ret;
}
Example #25
0
void MWState::StateManager::saveGame (const std::string& description, const Slot *slot)
{
    try
    {
        ESM::SavedGame profile;

        MWBase::World& world = *MWBase::Environment::get().getWorld();

        MWWorld::Ptr player = world.getPlayerPtr();

        profile.mContentFiles = world.getContentFiles();

        profile.mPlayerName = player.getClass().getName (player);
        profile.mPlayerLevel = player.getClass().getNpcStats (player).getLevel();

        std::string classId = player.get<ESM::NPC>()->mBase->mClass;
        if (world.getStore().get<ESM::Class>().isDynamic(classId))
            profile.mPlayerClassName = world.getStore().get<ESM::Class>().find(classId)->mName;
        else
            profile.mPlayerClassId = classId;

        profile.mPlayerCell = world.getCellName();

        profile.mInGameTime.mGameHour = world.getTimeStamp().getHour();
        profile.mInGameTime.mDay = world.getDay();
        profile.mInGameTime.mMonth = world.getMonth();
        profile.mInGameTime.mYear = world.getYear();
        profile.mTimePlayed = mTimePlayed;
        profile.mDescription = description;

        int screenshotW = 259*2, screenshotH = 133*2; // *2 to get some nice antialiasing
        Ogre::Image screenshot;
        world.screenshot(screenshot, screenshotW, screenshotH);
        Ogre::DataStreamPtr encoded = screenshot.encode("jpg");
        profile.mScreenshot.resize(encoded->size());
        encoded->read(&profile.mScreenshot[0], encoded->size());

        if (!slot)
            slot = getCurrentCharacter()->createSlot (profile);
        else
            slot = getCurrentCharacter()->updateSlot (slot, profile);

        boost::filesystem::ofstream stream (slot->mPath, std::ios::binary);

        ESM::ESMWriter writer;

        const std::vector<std::string>& current =
            MWBase::Environment::get().getWorld()->getContentFiles();

        for (std::vector<std::string>::const_iterator iter (current.begin()); iter!=current.end();
            ++iter)
            writer.addMaster (*iter, 0); // not using the size information anyway -> use value of 0

        writer.setFormat (ESM::Header::CurrentFormat);
        int recordCount =         1 // saved game header
                +MWBase::Environment::get().getJournal()->countSavedGameRecords()
                +MWBase::Environment::get().getWorld()->countSavedGameRecords()
                +MWBase::Environment::get().getScriptManager()->getGlobalScripts().countSavedGameRecords()
                +MWBase::Environment::get().getDialogueManager()->countSavedGameRecords()
                +MWBase::Environment::get().getWindowManager()->countSavedGameRecords();
        writer.setRecordCount (recordCount);

        writer.save (stream);

        Loading::Listener& listener = *MWBase::Environment::get().getWindowManager()->getLoadingScreen();
        listener.setProgressRange(recordCount);
        listener.setLabel("#{sNotifyMessage4}");

        Loading::ScopedLoad load(&listener);

        writer.startRecord (ESM::REC_SAVE);
        slot->mProfile.save (writer);
        writer.endRecord (ESM::REC_SAVE);
        listener.increaseProgress();

        MWBase::Environment::get().getJournal()->write (writer, listener);
        MWBase::Environment::get().getDialogueManager()->write (writer, listener);
        MWBase::Environment::get().getWorld()->write (writer, listener);
        MWBase::Environment::get().getScriptManager()->getGlobalScripts().write (writer, listener);
        MWBase::Environment::get().getWindowManager()->write(writer, listener);

        // Ensure we have written the number of records that was estimated
        if (writer.getRecordCount() != recordCount+1) // 1 extra for TES3 record
            std::cerr << "Warning: number of written savegame records does not match. Estimated: " << recordCount+1 << ", written: " << writer.getRecordCount() << std::endl;

        writer.close();

        if (stream.fail())
            throw std::runtime_error("Write operation failed");

        Settings::Manager::setString ("character", "Saves",
            slot->mPath.parent_path().filename().string());
    }
    catch (const std::exception& e)
    {
        std::stringstream error;
        error << "Failed to save game: " << e.what();

        std::cerr << error.str() << std::endl;

        std::vector<std::string> buttons;
        buttons.push_back("#{sOk}");
        MWBase::Environment::get().getWindowManager()->messageBox(error.str(), buttons);

        // If no file was written, clean up the slot
        if (slot && !boost::filesystem::exists(slot->mPath))
            getCurrentCharacter()->deleteSlot(slot);
    }
}
Example #26
0
bool OgreKit::setup(void)
{
	LOG_FOOT;
	  
	if (assetMgr)
	{
#if USE_APK_ARCHIVE
		Ogre::ArchiveManager::getSingleton().addArchiveFactory(new Ogre::APKFileSystemArchiveFactory(assetMgr));
		Ogre::ArchiveManager::getSingleton().addArchiveFactory(new Ogre::APKZipArchiveFactory(assetMgr));

		Ogre::ResourceGroupManager::getSingleton().addResourceLocation("/", "APKFileSystem",  Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
#endif
	}

#if USE_APK_ARCHIVE
	Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(m_blend, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	if (stream.isNull())
	{
		gkPrintf("Error: Can't open file %s.", m_blend.c_str());
		return false;
	}

	size_t size = stream->size();
	char* buf = new char[size];
	stream->read(buf, size);

	gkBlendFile* blend = gkBlendLoader::getSingleton().loadFromMemory(buf,size,gkBlendLoader::LO_ALL_SCENES);	
#else
	gkBlendFile* blend = gkBlendLoader::getSingleton().loadFile(m_blend,gkBlendLoader::LO_ALL_SCENES); //, "", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);	
#endif
	if (!blend)
	{
		LOGI("File loading failed.\n");
		return false;
	}

	LOG_FOOT;

	m_scene = blend->getMainScene();
	if (!m_scene)
	{
		LOGI("No usable scenes found in blend.\n");
		return false;
	}

	LOG_FOOT;

	m_scene->createInstance();

	LOG_FOOT;
	
	m_scene->getMainCamera()->getCamera()->setAutoAspectRatio(true);

	// add input hooks
	gkWindow* win = gkWindowSystem::getSingleton().getMainWindow();
	m_input = static_cast<OIS::AndroidInputManager*>(win->getInputManager());

	LOG_FOOT;


	return true;
}
Example #27
0
OgreResourceWrapper::OgreResourceWrapper(Ogre::DataStreamPtr dataStream)
{
	mSize = dataStream->size();
	mBuffer = new char[mSize];
	dataStream->read(mBuffer, mSize);
}
Example #28
0
void MWState::StateManager::saveGame (const std::string& description, const Slot *slot)
{
    ESM::SavedGame profile;

    MWBase::World& world = *MWBase::Environment::get().getWorld();

    MWWorld::Ptr player = world.getPlayer().getPlayer();

    profile.mContentFiles = world.getContentFiles();

    profile.mPlayerName = player.getClass().getName (player);
    profile.mPlayerLevel = player.getClass().getNpcStats (player).getLevel();
    profile.mPlayerClass = player.get<ESM::NPC>()->mBase->mClass;

    profile.mPlayerCell = world.getCellName();

    profile.mInGameTime.mGameHour = world.getTimeStamp().getHour();
    profile.mInGameTime.mDay = world.getDay();
    profile.mInGameTime.mMonth = world.getMonth();
    profile.mInGameTime.mYear = world.getYear();
    profile.mTimePlayed = mTimePlayed;
    profile.mDescription = description;

    int screenshotW = 259*2, screenshotH = 133*2; // *2 to get some nice antialiasing
    Ogre::Image screenshot;
    world.screenshot(screenshot, screenshotW, screenshotH);
    Ogre::DataStreamPtr encoded = screenshot.encode("jpg");
    profile.mScreenshot.resize(encoded->size());
    encoded->read(&profile.mScreenshot[0], encoded->size());

    if (!slot)
        slot = mCharacterManager.getCurrentCharacter()->createSlot (profile);
    else
        slot = mCharacterManager.getCurrentCharacter()->updateSlot (slot, profile);

    std::ofstream stream (slot->mPath.string().c_str());

    ESM::ESMWriter writer;

    const std::vector<std::string>& current =
        MWBase::Environment::get().getWorld()->getContentFiles();

    for (std::vector<std::string>::const_iterator iter (current.begin()); iter!=current.end();
        ++iter)
        writer.addMaster (*iter, 0); // not using the size information anyway -> use value of 0

    writer.setFormat (ESM::Header::CurrentFormat);
    writer.setRecordCount (
        1 // saved game header
        +MWBase::Environment::get().getJournal()->countSavedGameRecords()
        +MWBase::Environment::get().getWorld()->countSavedGameRecords()
        +MWBase::Environment::get().getScriptManager()->getGlobalScripts().countSavedGameRecords()
                + 1 // global map
        );

    writer.save (stream);

    writer.startRecord (ESM::REC_SAVE);
    slot->mProfile.save (writer);
    writer.endRecord (ESM::REC_SAVE);

    MWBase::Environment::get().getJournal()->write (writer);
    MWBase::Environment::get().getWorld()->write (writer);
    MWBase::Environment::get().getScriptManager()->getGlobalScripts().write (writer);
    MWBase::Environment::get().getWindowManager()->write(writer);

    writer.close();

    Settings::Manager::setString ("character", "Saves",
        slot->mPath.parent_path().filename().string());
}
qint64 OgreNetworkReply::size() const
{
    return mDataStream->size();
}
Example #30
0
void MapFileSerializer::importMapFile( Ogre::DataStreamPtr& stream, WorldMapFile& dest )
{
    const auto fileSize = stream->size();
    auto numBlocks = fileSize / kWorldMapBlockSize;

    for ( unsigned int j=0; j<numBlocks; j++ )
    {

        SBlock block;

        const size_t basePos = kWorldMapBlockSize*j;
        stream->seek( basePos );

        // Read the offset to compressed data in this block
        BlockHeader header = {};
        for ( auto i=0u; i<16; i++)
        {
            readUInt32( stream, header.mCompressedDataOffsets[i] );
        }

        for ( auto i=0u; i<16; i++)
        {
            SBlockPart blockPart;

            // Go to the offset
            stream->seek( basePos + header.mCompressedDataOffsets[i] );

            // Read the size of the compressed data
            uint32 compressedDataSize = 0;
            readUInt32( stream, compressedDataSize );

            // Go back to before the compressed data size
            stream->seek( basePos + header.mCompressedDataOffsets[i] );

            // Read the compressed data into a temp buffer, including the compressed data size
            std::vector<uint8> buffer( compressedDataSize + 4 );
            stream->read(buffer.data(), buffer.size());

            // Decompress the data
            auto decompressed = LzsBuffer::Decompress(buffer);

            Ogre::MemoryDataStream decStream(decompressed.data(), decompressed.size(), false, true);

            readUInt16(decStream, blockPart.mHeader.NumberOfTriangles);
            readUInt16(decStream, blockPart.mHeader.NumberOfVertices);

            /*
            std::cout << "block: " << j
                      << " from offset " << header.mCompressedDataOffsets[i]
                      << " old size: " << buffer.size()
                      << " decompressed size is " << decompressed.size()
                      << " header is tris: " <<  blockPart.mHeader.NumberOfTriangles
                      << " verts " << blockPart.mHeader.NumberOfVertices
                      << std::endl;*/


            blockPart.mTris.resize(blockPart.mHeader.NumberOfTriangles);
            for ( int k=0; k<blockPart.mHeader.NumberOfTriangles; k++)
            {
                BlockTriangle& s = blockPart.mTris[k];

                readUInt8( decStream, s.Vertex0Index );
                readUInt8( decStream, s.Vertex1Index );
                readUInt8( decStream, s.Vertex2Index );

                readUInt8( decStream, s.WalkabilityInfo );
                //readUInt8( decStream, s.Unknown );

                readUInt8( decStream, s.uVertex0 );
                readUInt8( decStream, s.vVertex0 );

                readUInt8( decStream, s.uVertex1 );
                readUInt8( decStream, s.vVertex1 );

                readUInt8( decStream, s.uVertex2 );
                readUInt8( decStream, s.vVertex2 );

                readUInt16( decStream, s.TextureInfo );

                s.TextureInfo = s.TextureInfo & 0x1FF;

                //readUInt16( decStream, s.Location );

                /*
                std::cout << "v0: " << int(s.Vertex0Index)
                          << " v1 " << int(s.Vertex1Index)
                          << " v2 " << int(s.Vertex2Index)
                          << " walk " << int(s.WalkabilityInfo)
                          << " u1 " << int(s.uVertex1)
                          << " v1 " << int(s.vVertex1)
                          << " v2 " << int(s.uVertex2)
                          << " u2 " << int(s.vVertex2)
                          << " texture " << s.TextureInfo
                          << " locId " << s.Location
                          << std::endl;*/

            }

            blockPart.mNormal.resize( blockPart.mHeader.NumberOfVertices );
            blockPart.mVertices.resize( blockPart.mHeader.NumberOfVertices );

            // All verts
            for ( int k=0; k<blockPart.mHeader.NumberOfVertices; k++)
            {
                Vertex& v = blockPart.mVertices[k];
                readInt16( decStream, v.X );
                readInt16( decStream, v.Y );
                readInt16( decStream, v.Z );
                readUInt16( decStream, v.Unused );
            }

            // Then all normals
            for ( int k=0; k<blockPart.mHeader.NumberOfVertices; k++)
            {
                Normal& n = blockPart.mNormal[k];
                readInt16( decStream, n.X );
                readInt16( decStream, n.Y );
                readInt16( decStream, n.Z );
                readUInt16( decStream, n.Unused );
            }

            block.mMeshes.push_back( blockPart );
        }
        mBlocks.push_back(block);
    }
}