Skip to content

Instantly share code, notes, and snippets.

@laziu
Last active August 17, 2016 07:38
Show Gist options
  • Save laziu/713c5b80bc12996529c9a1841f1c6e53 to your computer and use it in GitHub Desktop.
Save laziu/713c5b80bc12996529c9a1841f1c6e53 to your computer and use it in GitHub Desktop.
*.vox read sample
#include <cstdio>
#include <fstream>
#include <string>
#include <vector>
#include <array>
using namespace std;
// primitive types
using uint = unsigned int;
using byte = unsigned char;
struct uvec3
{
uint x { 0u }, y { 0u }, z { 0u };
uvec3(uint x, uint y, uint z): x(x), y(y), z(z) {}
};
struct vox
{
uvec3 size {0u, 0u, 0u};
array<array<array<byte, 128>, 128>, 128> voxel;
array<uint, 256> color;
vox() {}
static vox readfrom(string filename);
};
// helper functions
inline uint byte4_uint(byte u0_7, byte u8_15, byte u16_23, byte u24_31)
{
return ((uint)u24_31 << 24) |
((uint)u16_23 << 16) |
((uint)u8_15 << 8) |
((uint)u0_7 );
}
inline uint byte4_uint(vector<char>& data, uint index)
{
return byte4_uint((unsigned)data[index ],
(unsigned)data[index + 1],
(unsigned)data[index + 2],
(unsigned)data[index + 3]);
}
inline array<byte, 4> uint_byte4(uint n)
{
return { n & 0xFF, (n >> 8) & 0xFF, (n >> 16) & 0xFF, (n >> 24) & 0xFF };
}
// functions
vox vox::readfrom(string filename)
{
vox voxdata;
ifstream file(filename.c_str(), ios::binary | ios::ate);
streamsize filesize = file.tellg();
file.seekg(0, ios::beg);
vector<char> buffer(filesize);
if ( file.read(buffer.data(), filesize) ) {
voxdata.size.x = byte4_uint(buffer, 0x20);
voxdata.size.y = byte4_uint(buffer, 0x24);
voxdata.size.z = byte4_uint(buffer, 0x28);
uint box_count = byte4_uint(buffer, 0x38);
uint box_data_end = 0x3C + box_count * 4;
for ( uint i = 0x3C; i < box_data_end; i += 4 ) {
byte x = buffer[i ];
byte y = buffer[i + 1];
byte z = buffer[i + 2];
byte c = buffer[i + 3];
voxdata.voxel[x][y][z] = c;
}
uint color_data_start = box_data_end + 12;
uint color_data_end = color_data_start + byte4_uint(buffer, box_data_end + 4);
for ( uint i = color_data_start, t = 1; i < color_data_end; i += 4, ++t ) {
voxdata.color[t] = byte4_uint(buffer, i);
}
}
return voxdata;
}
// entry
int main()
{
vox voxdata = vox::readfrom("C:/Dev/Resources/Voxels/vox/grass_test.vox");
printf("size: (%d, %d, %d)\n\n", voxdata.size.x, voxdata.size.y, voxdata.size.z);
for ( int i = 0; i < voxdata.size.x; ++i ) {
for ( int j = 0; j < voxdata.size.y; ++j ) {
for ( int k = 0; k < voxdata.size.z; ++k ) {
printf("%3d ", voxdata.voxel[i][j][k]);
}
printf("\n");
}
printf("\n");
}
for ( int i = 1; i < 256; ++i ) {
array<byte, 4> color = uint_byte4(color[i]);
printf("color %d: (%3d, %3d, %3d, %3d)\n", color[0], color[1], color[2], color[3]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment