This repository was archived by the owner on Sep 27, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathChunk.cpp
More file actions
69 lines (55 loc) · 1.75 KB
/
Chunk.cpp
File metadata and controls
69 lines (55 loc) · 1.75 KB
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
#include "Chunk.hpp"
#include <misc/pngencode.hpp>
#include <misc/BufferHelper.hpp>
#include <algorithm>
#include <limits>
Chunk::Pixel::Pixel(std::uint8_t r, std::uint8_t g, std::uint8_t b)
: rgb((b >> 3 & 0x1f)
| (g >> 2 & 0x3f) << 5
| (r >> 3 & 0x1f) << 11) { }
Chunk::Pixel::Pixel(std::uint16_t rgb)
: rgb(rgb) { }
Chunk::Chunk(Chunk::coord_t x, Chunk::coord_t y, Chunk::Pixel color)
: x(x),
y(y),
compressedImageSize(0),
outdatedCompressedImage(true) {
for (std::size_t i = 0; i < Chunk::areaSize * Chunk::areaSize; i++) {
pixels[i] = color.rgb;
}
}
bool Chunk::setPixel(std::uint8_t x, std::uint8_t y, Chunk::Pixel color) {
if (pixels[y * Chunk::areaSize + x] != color.rgb) {
outdatedCompressedImage = true;
pixels[y * Chunk::areaSize + x] = color.rgb;
return true;
}
return false;
}
Chunk::Pixel Chunk::getPixel(std::uint8_t x, std::uint8_t y) {
return pixels[y * Chunk::areaSize + x];
}
std::size_t Chunk::size() {
if (outdatedCompressedImage) {
updateCompressedImage();
}
return sizeof(Chunk::coord_t) * 2 + compressedImageSize;
}
std::size_t Chunk::serialize(std::uint8_t * arr) {
if (outdatedCompressedImage) { /* Should never really happen anyways */
updateCompressedImage();
}
std::uint8_t * start = arr;
arr += BufferHelper::writeLE(arr, x);
arr += BufferHelper::writeLE(arr, y);
std::copy_n(compressedImage.get(), compressedImageSize, arr);
arr += compressedImageSize;
return arr - start;
}
constexpr Chunk::key_t Chunk::key(Chunk::coord_t x, Chunk::coord_t y) {
return (Chunk::key_t) x << (std::numeric_limits<Chunk::coord_t>::digits + 1) | y;
}
void Chunk::updateCompressedImage() {
compressedImage = CompressPNG(&pixels, Chunk::areaSize, Chunk::areaSize, 2, compressedImageSize, 4);
outdatedCompressedImage = false;
}