-
Notifications
You must be signed in to change notification settings - Fork 1
/
TMIStream.h
97 lines (76 loc) · 2.56 KB
/
TMIStream.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#pragma once
#include <iostream>
#define MINIZ_HEADER_FILE_ONLY 1
#include "miniz.c"
class TMIStream : public std::ifstream {
unsigned blockSize;
unsigned char * compressionBuffer;
unsigned compressionBufferSize;
public:
TMIStream(const char * fileName)
: std::ifstream(fileName, std::ifstream::in | std::ifstream::binary),
blockSize(0), compressionBuffer(0), compressionBufferSize(0)
{
}
~TMIStream() { delete[] compressionBuffer; }
// Reads a file block header (map, layer, tileset)
unsigned readBlockHeader()
{
unsigned identifier = 0;
*this >> identifier;
*this >> blockSize;
return identifier;
}
// Skips the current file block
void skipBlock() { seekg(blockSize, ios_base::cur); }
// Reads z-lib compressed data preceded by the size
void readCompressedData(char * destination, unsigned size)
{
// Read the size of the compressed input data
mz_ulong dataSize = 0;
*this >> dataSize;
if (destination && dataSize) {
// Buffer already exists, but is too small...
if (compressionBuffer && compressionBufferSize < dataSize) {
delete[] compressionBuffer;
compressionBuffer = 0;
}
if (!compressionBuffer) {
compressionBuffer = new unsigned char[dataSize];
compressionBufferSize = dataSize;
}
if (compressionBuffer) {
read((char *)compressionBuffer, dataSize);
mz_ulong dataAlloc = size;
mz_uncompress((unsigned char *)destination, &dataAlloc, compressionBuffer, dataSize);
return;
}
}
// If we reach this point, something went wrong - skip data
seekg(dataSize, ios_base::cur);
}
// Read a binary block as big as the given buffer
template <class T> TMIStream & operator>>(T & i)
{
read(reinterpret_cast<char *>(&i), sizeof(i));
return *this;
}
// Read a string preceded by its length into a buffer (max 256 bytes)
unsigned char readShortStr(char * buffer)
{
unsigned char length = 0;
*this >> length;
read(buffer, length);
return length;
}
// Read a string preceded by its length into a newly allocated buffer
char * readLongStr()
{
size_t length = 0;
*this >> length;
char * buffer = new char[length + 1];
buffer[length] = 0;
read(buffer, length);
return buffer;
}
};