2016-07-14 18:35:07 +02:00

89 lines
2.4 KiB
C++

#ifndef RES_H
#define RES_H
#include <string>
#include <unordered_map>
#include <cstdio>
#define RESOURCE_PACK(pack) namespace Resource {\
void getResourcePack_ ## pack(ResourceMap &resourceFilesData);\
void getResourceSizes_ ## pack(ResourceSizeMap &resourceFilesSizes);\
}
/**
* To load an attached resource pack file, you must declare the pack with :
* RESOURCE_PACK(pack_name)
*
* it will allow you to use the function :
* getResourcePack_pack_name(ResourceMap &map)
* This function will give access the the embedded data through its original file name,
* using the provided map.
*
* it will also allow you to use the function :
* getResourceSizes_pack_name(ResourceSizeMap &map)
* This function will give access the the size of the embedded data.
*
* example :
* RESOURCE_PACK(shaders) // declaring the resource pack function
* Resource::ResourceMap myShaders; // defining a resource map
* Resource::getResourcePack(myShaders); // putting the resources of the resource pack in the map
* string *shader = new string(myShaders["shaders/shaderFile.glsl"]); // getting a resource file
*/
namespace Resource {
typedef std::unordered_map<std::string, const char*> ResourceMap;
typedef std::unordered_map<std::string, size_t> ResourceSizeMap;
/*
* Reader is a wrapper that allows you to read files and resources exactly the same way
*/
class Reader
{
public:
/**
* inspired from cstdio standard fread
* http://www.cplusplus.com/reference/cstdio/fread
*/
virtual size_t read (void * ptr, size_t size, size_t count) = 0;
};
class FileReader
{
FILE* m_stream;
public:
FileReader(FILE* stream) : m_stream(stream) {}
virtual size_t read (void * ptr, size_t size, size_t count)
{ return fread ( ptr, size, count, m_stream ); }
};
class ResourceReader
{
unsigned char* m_ptr;
size_t m_size;
size_t m_cursor;
public:
ResourceReader(unsigned char* ptr, size_t size) : m_ptr(ptr), m_size(size), m_cursor(0) {}
virtual size_t read (void * ptr, size_t size, size_t count)
{
size_t nbRead = 0;
unsigned char* p = (unsigned char*)ptr;
while(m_cursor + size < m_size && nbRead < count)
{
for(size_t i=0; i<size; ++i)
p[nbRead*size + i] = m_ptr[m_cursor + i];
m_cursor += size;
++nbRead;
}
return nbRead;
}
};
} // namespace Resource
#endif // RES_H