WHY_CPP  0.1
video_memory_holder.cpp
1 #include "video_memory_holder.h"
2 #include <whycpp/color.h>
3 #include <whycpp/types.h>
4 #include <algorithm>
5 #include "../int_utils.h"
6 #include "../logger.h"
7 
8 union RGBA_flatten {
9  RGBA rgba_;
10  uint32_t value;
11 };
12 
14  uint32_t value;
15  RGBA rgba_;
16 };
17 
18 uint32_t FlattenRGBA(const RGBA& rgba) {
19  return RGBA_flatten{rgba}.value;
20 }
21 
22 VideoMemoryHolder::VideoMemoryHolder(i32 width, i32 height)
23  : width(width), height(height), buffer(std::make_unique<uint32_t[]>(AsSize(width * height))) {
24  LOG_DEBUG("VideoMemoryHolder [%d, %d] created", width, height);
25 }
26 VideoMemoryHolder::~VideoMemoryHolder() {
27  LOG_DEBUG("VideoMemoryHolder [%d, %d] destroyed", width, height);
28 }
29 void VideoMemoryHolder::Set(i32 x, i32 y, const RGBA& color) {
30  auto index = CheckY(y) * AsSize(width) + CheckX(x);
31  buffer[index] = RGBA_flatten{color}.value;
32 }
33 const RGBA VideoMemoryHolder::Get(i32 x, i32 y) const {
34  auto index = CheckY(y) * AsSize(width) + CheckX(x);
35  return RGBA_unflatten{buffer[index]}.rgba_;
36 }
37 i32 VideoMemoryHolder::GetHeight() const {
38  return height;
39 }
40 i32 VideoMemoryHolder::GetWidth() const {
41  return width;
42 }
43 size_t VideoMemoryHolder::CheckX(i32 x) const {
44  if (x >= width || x < 0) {
45  LOG_VERBOSE("VideoMemoryHolder: X is out of bound, should be [0, %d) but %d", width, x);
46  return AsSize(clamp(x, 0, width - 1));
47  }
48  return AsSize(x);
49 }
50 size_t VideoMemoryHolder::CheckY(i32 y) const {
51  if (y >= height || y < 0) {
52  LOG_VERBOSE("VideoMemoryHolder: Y is out of bound, should be [0, %d) but %d", height, y);
53  return AsSize(clamp(y, 0, height - 1));
54  }
55  return AsSize(y);
56 }
57 i32 VideoMemoryHolder::GetScreenWidth() const {
58  return screen_width;
59 }
60 void VideoMemoryHolder::SetScreenWidth(i32 screen_width_) {
61  if (screen_width_ < 1) return;
62  screen_width = screen_width_;
63 }
64 i32 VideoMemoryHolder::GetScreenHeight() const {
65  return screen_height;
66 }
67 void VideoMemoryHolder::SetScreenHeight(i32 screen_height_) {
68  if (screen_height_ < 1) return;
69  screen_height = screen_height_;
70 }
71 const uint8_t* VideoMemoryHolder::GetBuffer() const {
72  return reinterpret_cast<uint8_t*>(buffer.get());
73 }
74 
75 void VideoMemoryHolder::Fill(const RGBA& color) {
76  auto len = AsSize(width * height);
77  uint64_t col = RGBA_flatten{color}.value;
78  uint64_t col2 = (col << 32u) | col;
79  auto buf = reinterpret_cast<uint64_t*>(buffer.get());
80  for (size_t i = 0; i < len / 2; i++) {
81  buf[i] = col2;
82  }
83 }
Definition: color.h:11