-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisplay.cpp
More file actions
74 lines (63 loc) · 2.25 KB
/
display.cpp
File metadata and controls
74 lines (63 loc) · 2.25 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
70
71
72
73
74
#include "display.hpp"
#include <cstring>
#include <stdexcept>
namespace sdl8 {
display::display()
{
// initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::stringstream ss;
ss << "Could not initialize SDL2! " << SDL_GetError();
throw std::runtime_error(ss.str());
}
// Try to create window
window = SDL_CreateWindow("chip8", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH * SCALE, SCREEN_HEIGHT * SCALE, SDL_WINDOW_SHOWN);
if (window == nullptr) {
SDL_Quit();
std::stringstream ss;
ss << "Could not create window! SDL2 ERROR: " << SDL_GetError();
throw std::runtime_error(ss.str());
}
// Try to create renderer
renderer = SDL_CreateRenderer(window, -1, 0);
if (renderer == nullptr) {
SDL_DestroyWindow(window);
SDL_Quit();
std::stringstream ss;
ss << "Could not create renderer! SDL2 ERROR: " << SDL_GetError();
throw std::runtime_error(ss.str());
}
// create texture
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT);
}
display::~display() noexcept
{
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
void display::render(std::array<uint8_t, SCREEN_DIMS>& pixels)
{
// Copy emulator pixels to texture pixels on GPU
uint32_t* texture_pixels = nullptr; // used by lock function
int pitch;
// Lock texture pixels to be write only
if (SDL_LockTexture(texture, nullptr, reinterpret_cast<void**>(&texture_pixels), &pitch) != 0) {
std::stringstream ss;
ss << "Could not lock texture! SDL2 ERROR: " << SDL_GetError();
throw std::runtime_error(ss.str());
}
// copy the pixels
for (size_t i = 0; i < pixels.size(); i++) {
// white for on, black for off
texture_pixels[i] = pixels[i] != 0 ? 0xFFFFFFFF : 0xFF000000;
}
// unlock the texture applying changes.
SDL_UnlockTexture(texture);
// SDL_Rect dest_rect = {0,0,SCREEN_WIDTH * SCALE, SCREEN_HEIGHT * SCALE};
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
}
} // namespace sdl8