1 #include "Application.hpp"
6 #include "../graphics/Viewport.hpp"
15 Application::Application(Window &win, graphics::Viewport &vp)
21 Application::~Application() {
25 void Application::PushState(State *s) {
27 if (!states.empty()) {
28 states.top()->OnPause();
32 if (s->ref_count == 1) {
38 State *Application::PopState() {
39 State *s = states.top();
43 if (!states.empty()) {
44 states.top()->OnResume();
49 State *Application::SwitchState(State *s_new) {
51 State *s_old = states.top();
56 if (s_old->ref_count == 0) {
59 if (s_new->ref_count == 1) {
66 State &Application::GetState() {
70 bool Application::HasState() const noexcept {
71 return !states.empty();
75 void Application::Run() {
76 Uint32 last = SDL_GetTicks();
78 Uint32 now = SDL_GetTicks();
79 int delta = now - last;
85 void Application::Loop(int dt) {
87 if (!HasState()) return;
88 GetState().Update(dt);
89 if (!HasState()) return;
91 GetState().Render(viewport);
95 void Application::HandleEvents() {
97 while (HasState() && SDL_PollEvent(&event)) {
98 if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) {
99 viewport.Resize(event.window.data1, event.window.data2);
101 GetState().Handle(event);
105 void State::Handle(const SDL_Event &event) {
106 switch (event.type) {
108 OnKeyDown(event.key);
113 case SDL_MOUSEBUTTONDOWN:
114 OnMouseDown(event.button);
116 case SDL_MOUSEBUTTONUP:
117 OnMouseUp(event.button);
119 case SDL_MOUSEMOTION:
120 OnMouseMotion(event.motion);
123 OnMouseWheel(event.wheel);
128 case SDL_WINDOWEVENT:
129 Handle(event.window);
137 void State::Handle(const SDL_WindowEvent &event) {
138 switch (event.event) {
139 case SDL_WINDOWEVENT_FOCUS_GAINED:
142 case SDL_WINDOWEVENT_FOCUS_LOST:
145 case SDL_WINDOWEVENT_RESIZED:
146 OnResize(event.data1, event.data2);
153 void State::Update(int dt) {
157 void State::Render(graphics::Viewport &viewport) {
161 void State::OnQuit() {
162 while (App().HasState()) {
170 , tile_path(path + "tiles/") {
171 graphics::Format format;
172 textures.tiles.Bind();
173 textures.tiles.Reserve(256, 256, 9, format);
174 LoadTileTexture("1", textures.tiles, 0);
175 LoadTileTexture("2", textures.tiles, 1);
176 LoadTileTexture("3", textures.tiles, 2);
177 LoadTileTexture("4", textures.tiles, 3);
178 LoadTileTexture("5", textures.tiles, 4);
179 LoadTileTexture("6", textures.tiles, 5);
180 LoadTileTexture("7", textures.tiles, 6);
181 LoadTileTexture("8", textures.tiles, 7);
182 LoadTileTexture("9", textures.tiles, 8);
188 void Assets::LoadTileTexture(const std::string &name, graphics::ArrayTexture &tex, int layer) const {
189 std::string path = tile_path + name + ".png";
190 SDL_Surface *srf = IMG_Load(path.c_str());
192 throw SDLError("IMG_Load");
195 tex.Data(layer, *srf);
197 SDL_FreeSurface(srf);
200 SDL_FreeSurface(srf);