1 #include "Application.hpp"
3 #include "Environment.hpp"
4 #include "FrameCounter.hpp"
6 #include "StateControl.hpp"
7 #include "TextureIndex.hpp"
10 #include "../audio/Sound.hpp"
11 #include "../graphics/ArrayTexture.hpp"
12 #include "../graphics/Font.hpp"
13 #include "../graphics/Texture.hpp"
14 #include "../io/TokenStreamReader.hpp"
15 #include "../model/shapes.hpp"
16 #include "../world/BlockType.hpp"
17 #include "../world/BlockTypeRegistry.hpp"
18 #include "../world/Entity.hpp"
23 #include <SDL_image.h>
25 using std::runtime_error;
31 Application::Application(Environment &e)
37 Application::~Application() {
42 void Application::RunN(size_t n) {
43 Uint32 last = SDL_GetTicks();
44 for (size_t i = 0; HasState() && i < n; ++i) {
45 Uint32 now = SDL_GetTicks();
46 int delta = now - last;
52 void Application::RunT(size_t t) {
53 Uint32 last = SDL_GetTicks();
54 Uint32 finish = last + t;
55 while (HasState() && last < finish) {
56 Uint32 now = SDL_GetTicks();
57 int delta = now - last;
63 void Application::RunS(size_t n, size_t t) {
64 for (size_t i = 0; HasState() && i < n; ++i) {
70 void Application::Run() {
71 Uint32 last = SDL_GetTicks();
72 env.window.GrabMouse();
74 Uint32 now = SDL_GetTicks();
75 int delta = now - last;
81 void Application::Loop(int dt) {
82 env.counter.EnterFrame();
84 if (!HasState()) return;
86 env.state.Commit(*this);
87 if (!HasState()) return;
89 env.counter.ExitFrame();
93 void Application::HandleEvents() {
94 env.counter.EnterHandle();
96 while (HasState() && SDL_PollEvent(&event)) {
98 env.state.Commit(*this);
100 env.counter.ExitHandle();
103 void Application::Handle(const SDL_Event &event) {
104 switch (event.type) {
105 case SDL_WINDOWEVENT:
106 Handle(event.window);
109 GetState().Handle(event);
114 void Application::Handle(const SDL_WindowEvent &event) {
115 switch (event.event) {
116 case SDL_WINDOWEVENT_FOCUS_GAINED:
117 env.window.GrabMouse();
119 case SDL_WINDOWEVENT_FOCUS_LOST:
120 env.window.ReleaseMouse();
122 case SDL_WINDOWEVENT_RESIZED:
123 env.viewport.Resize(event.data1, event.data2);
130 void Application::Update(int dt) {
131 env.counter.EnterUpdate();
132 env.audio.Update(dt);
134 GetState().Update(dt);
136 env.counter.ExitUpdate();
139 void Application::Render() {
140 // gl implementation may (and will probably) delay vsync blocking until
141 // the first write after flipping, which is this clear call
142 env.viewport.Clear();
143 env.counter.EnterRender();
146 GetState().Render(env.viewport);
149 env.counter.ExitRender();
154 void Application::PushState(State *s) {
155 if (!states.empty()) {
156 states.top()->OnPause();
160 if (s->ref_count == 1) {
166 State *Application::PopState() {
167 State *s = states.top();
171 if (!states.empty()) {
172 states.top()->OnResume();
177 State *Application::SwitchState(State *s_new) {
178 State *s_old = states.top();
179 states.top() = s_new;
183 if (s_old->ref_count == 0) {
186 if (s_new->ref_count == 1) {
193 State &Application::GetState() {
194 return *states.top();
197 bool Application::HasState() const noexcept {
198 return !states.empty();
202 void StateControl::Commit(Application &app) {
203 while (!cue.empty()) {
208 app.PushState(m.state);
211 app.SwitchState(m.state);
217 while (app.HasState()) {
226 Assets::Assets(const string &base)
227 : fonts(base + "fonts/")
228 , sounds(base + "sounds/")
229 , textures(base + "textures/")
230 , data(base + "data/")
231 , large_ui_font(LoadFont("DejaVuSans", 24))
232 , small_ui_font(LoadFont("DejaVuSans", 16)) {
238 CuboidShape block_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }});
239 StairShape stair_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }}, { 0.0f, 0.0f });
240 CuboidShape slab_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.0f, 0.5f }});
244 void Assets::LoadBlockTypes(const std::string &set_name, BlockTypeRegistry ®, TextureIndex &tex_index) const {
245 string full = data + set_name + ".types";
246 std::ifstream file(full);
248 throw std::runtime_error("failed to open block type file " + full);
250 TokenStreamReader in(file);
255 while (in.HasMore()) {
256 in.ReadIdentifier(type_name);
257 in.Skip(Token::EQUALS);
261 in.Skip(Token::ANGLE_BRACKET_OPEN);
262 while (in.Peek().type != Token::ANGLE_BRACKET_CLOSE) {
263 in.ReadIdentifier(name);
264 in.Skip(Token::EQUALS);
265 if (name == "visible") {
266 type.visible = in.GetBool();
267 } else if (name == "texture") {
268 in.ReadString(tex_name);
269 type.texture = tex_index.GetID(tex_name);
270 } else if (name == "color") {
271 in.ReadVec(type.color);
272 } else if (name == "outline") {
273 in.ReadVec(type.outline_color);
274 } else if (name == "label") {
275 in.ReadString(type.label);
276 } else if (name == "luminosity") {
277 type.luminosity = in.GetInt();
278 } else if (name == "block_light") {
279 type.block_light = in.GetBool();
280 } else if (name == "collision") {
281 type.collision = in.GetBool();
282 } else if (name == "collide_block") {
283 type.collide_block = in.GetBool();
284 } else if (name == "shape") {
285 in.ReadIdentifier(shape_name);
286 if (shape_name == "block") {
287 type.shape = &block_shape;
288 type.fill = { true, true, true, true, true, true };
289 } else if (shape_name == "slab") {
290 type.shape = &slab_shape;
291 type.fill = { false, true, false, false, false, false };
292 } else if (shape_name == "stair") {
293 type.shape = &stair_shape;
294 type.fill = { false, true, false, false, false, true };
296 throw runtime_error("unknown block shape: " + shape_name);
299 throw runtime_error("unknown block property: " + name);
301 in.Skip(Token::SEMICOLON);
303 in.Skip(Token::ANGLE_BRACKET_CLOSE);
304 in.Skip(Token::SEMICOLON);
310 Font Assets::LoadFont(const string &name, int size) const {
311 string full = fonts + name + ".ttf";
312 return Font(full.c_str(), size);
315 Sound Assets::LoadSound(const string &name) const {
316 string full = sounds + name + ".wav";
317 return Sound(full.c_str());
320 Texture Assets::LoadTexture(const string &name) const {
321 string full = textures + name + ".png";
323 SDL_Surface *srf = IMG_Load(full.c_str());
325 throw SDLError("IMG_Load");
329 SDL_FreeSurface(srf);
333 void Assets::LoadTexture(const string &name, ArrayTexture &tex, int layer) const {
334 string full = textures + name + ".png";
335 SDL_Surface *srf = IMG_Load(full.c_str());
337 throw SDLError("IMG_Load");
341 tex.Data(layer, *srf);
343 SDL_FreeSurface(srf);
346 SDL_FreeSurface(srf);
349 void Assets::LoadTextures(const TextureIndex &index, ArrayTexture &tex) const {
350 // TODO: where the hell should that size come from?
351 tex.Reserve(16, 16, index.Size(), Format());
352 for (const auto &entry : index.Entries()) {
353 LoadTexture(entry.first, tex, entry.second);
358 TextureIndex::TextureIndex()
363 int TextureIndex::GetID(const string &name) {
364 auto entry = id_map.find(name);
365 if (entry == id_map.end()) {
366 auto result = id_map.emplace(name, Size());
367 return result.first->second;
369 return entry->second;
374 void FrameCounter::EnterFrame() noexcept {
375 last_enter = SDL_GetTicks();
376 last_tick = last_enter;
379 void FrameCounter::EnterHandle() noexcept {
383 void FrameCounter::ExitHandle() noexcept {
384 current.handle = Tick();
387 void FrameCounter::EnterUpdate() noexcept {
391 void FrameCounter::ExitUpdate() noexcept {
392 current.update = Tick();
395 void FrameCounter::EnterRender() noexcept {
399 void FrameCounter::ExitRender() noexcept {
400 current.render = Tick();
403 void FrameCounter::ExitFrame() noexcept {
404 Uint32 now = SDL_GetTicks();
405 current.total = now - last_enter;
406 current.running = current.handle + current.update + current.render;
407 current.waiting = current.total - current.running;
411 if (cur_frame >= NUM_FRAMES) {
420 int FrameCounter::Tick() noexcept {
421 Uint32 now = SDL_GetTicks();
422 int delta = now - last_tick;
427 void FrameCounter::Accumulate() noexcept {
428 sum.handle += current.handle;
429 sum.update += current.update;
430 sum.render += current.render;
431 sum.running += current.running;
432 sum.waiting += current.waiting;
433 sum.total += current.total;
435 max.handle = std::max(current.handle, max.handle);
436 max.update = std::max(current.update, max.update);
437 max.render = std::max(current.render, max.render);
438 max.running = std::max(current.running, max.running);
439 max.waiting = std::max(current.waiting, max.waiting);
440 max.total = std::max(current.total, max.total);
442 current = Frame<int>();
445 void FrameCounter::Push() noexcept {
447 avg.handle = sum.handle * factor;
448 avg.update = sum.update * factor;
449 avg.render = sum.render * factor;
450 avg.running = sum.running * factor;
451 avg.waiting = sum.waiting * factor;
452 avg.total = sum.total * factor;