aboutsummaryrefslogtreecommitdiff
path: root/src/engine/graphics/scene.cpp
blob: ff64edde98b165ef0bafc66179147b6f99b3bc28 (plain)
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
#include "scene.hpp"

#include "engine/escape.hpp"
#include "util/color.hpp"

#include <fmt/color.h>
#include <fmt/core.h>

#include <iostream>
#include <sys/ioctl.h>

Scene::Scene(const IMatrixFactory<MatrixElement> &matrix_factory) noexcept
	: _matrix(matrix_factory(size())), _is_shown(false)
{
	_matrix->fill(' ');
}

void Scene::enter() noexcept
{
	if (_is_shown || _original_termios != nullptr)
	{
		return;
	}

	// Enable alternative buffer
	fmt::print(ENABLE_ALT_BUFFER, fmt::arg("esc", ESC));
	std::cout.flush();

	// Create a backup of the current terminal state
	_original_termios = std::make_shared<termios>();
	tcgetattr(STDIN_FILENO, _original_termios.get());

	auto new_termios = termios(*_original_termios);

	// Set the local mode flags of the new termios structure
	//
	// The following flags are disabled:
	// ECHO   - Echoing input characters
	// ICANON - Canonical mode (line by line input)
	// ISIG   - Generate the corresponding signals for the characters
	//			INTR, QUIT, SUSP and DSUSP
	new_termios.c_lflag &= static_cast<std::uint32_t>(~(ECHO | ICANON | ISIG));

	// Set a new terminal state
	tcsetattr(STDIN_FILENO, TCSAFLUSH, &new_termios);

	_is_shown = true;
}

void Scene::leave() noexcept
{
	if (!_is_shown || _original_termios == nullptr)
	{
		return;
	}

	// Disable alternative buffer
	fmt::print(DISABLE_ALT_BUFFER, fmt::arg("esc", ESC));
	std::cout.flush();

	// Restore the original terminal state
	tcsetattr(STDIN_FILENO, TCSAFLUSH, _original_termios.get());

	_original_termios = nullptr;
	_is_shown = false;
}

auto Scene::size() const noexcept -> Bounds
{
	winsize window_size = {};

	// NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
	ioctl(0, TIOCGWINSZ, &window_size);

	return Bounds({window_size.ws_col, window_size.ws_row});
}

auto Scene::get_matrix() const noexcept -> const std::shared_ptr<IMatrix<MatrixElement>> &
{
	return _matrix;
}

void Scene::register_component(
	const std::shared_ptr<IComponent> &component,
	const Vector2 &position) noexcept
{
	_components.emplace_back(std::make_pair(component, position));
}

auto Scene::get_components() const noexcept
	-> std::vector<std::pair<std::shared_ptr<IComponent>, Vector2>>
{
	return _components;
}