summaryrefslogtreecommitdiff
path: root/ui/gameMainSelector.cpp
blob: 635dce0561d5dbf1c9cb9232eb47d9a371dfef48 (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
#include "gameMainSelector.h"
#include "collection.hpp"
#include "text.h"
#include "ui/uiComponent.h"
#include <SDL2/SDL.h>
#include <game/gamestate.h>
#include <game/geoData.h>
#include <game/selectable.h>
#include <game/worldobject.h> // IWYU pragma: keep
#include <gfx/gl/camera.h>
#include <optional>
#include <span>
#include <stream_support.hpp>
#include <typeinfo>
#include <vector>

GameMainSelector::GameMainSelector(const Camera * c, glm::vec2 size) : UIComponent {{{}, size}}, camera {c} { }

void
GameMainSelector::render(const UIShader & shader, const Position & pos) const
{
	if (!clicked.empty()) {
		Text {clicked, {{50, 10}, {0, 15}}, {1, 1, 0}}.render(shader, pos);
	}
}

bool
GameMainSelector::handleInput(const SDL_Event & e, const Position &)
{
	switch (e.type) {
		case SDL_MOUSEBUTTONDOWN:
			if (e.button.button == SDL_BUTTON_LEFT) {
				const auto mouse = glm::vec2 {e.button.x, e.button.y} / position.size;
				const auto ray = camera->unProject(mouse);

				if (target) {
					target->click(ray);
				}
				else {
					defaultClick(ray);
				}
				return true;
			}
			break;

		case SDL_MOUSEMOTION:
			if (target && target->handleMove()) {
				const auto mouse = glm::vec2 {e.motion.x, e.motion.y} / position.size;
				const auto ray = camera->unProject(mouse);

				if (target) {
					target->move(ray);
				}
				return true;
			}
			break;
	}
	return false;
}

void
GameMainSelector::defaultClick(const Ray & ray)
{
	glm::vec2 baryPos {};
	float distance;

	if (const auto selected
			= gameState->world.applyOne<Selectable>(&Selectable::intersectRay, ray, &baryPos, &distance);
			selected != gameState->world.end()) {
		const auto & ref = *selected.base()->get();
		clicked = typeid(ref).name();
	}
	else if (const auto pos = gameState->geoData->intersectRay(ray)) {
		clicked = streamed_string(*pos);
	}
	else {
		clicked.clear();
	}
}