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/CubeMap.hpp"
13 #include "../graphics/Font.hpp"
14 #include "../graphics/Texture.hpp"
15 #include "../io/TokenStreamReader.hpp"
16 #include "../model/shapes.hpp"
17 #include "../world/BlockType.hpp"
18 #include "../world/BlockTypeRegistry.hpp"
19 #include "../world/Entity.hpp"
25 #include <SDL_image.h>
27 using std::runtime_error;
33 HeadlessApplication::HeadlessApplication(HeadlessEnvironment &e)
39 HeadlessApplication::~HeadlessApplication() {
44 Application::Application(Environment &e)
45 : HeadlessApplication(e)
50 Application::~Application() {
55 void HeadlessApplication::RunN(size_t n) {
56 Uint32 last = SDL_GetTicks();
57 for (size_t i = 0; HasState() && i < n; ++i) {
58 Uint32 now = SDL_GetTicks();
59 int delta = now - last;
65 void HeadlessApplication::RunT(size_t t) {
66 Uint32 last = SDL_GetTicks();
67 Uint32 finish = last + t;
68 while (HasState() && last < finish) {
69 Uint32 now = SDL_GetTicks();
70 int delta = now - last;
76 void HeadlessApplication::RunS(size_t n, size_t t) {
77 for (size_t i = 0; HasState() && i < n; ++i) {
81 std::cout << std::setfill(' ') << std::setw(5) << std::right << (i + 1) << std::endl;
83 std::cout << std::flush;
89 void HeadlessApplication::Run() {
90 Uint32 last = SDL_GetTicks();
92 Uint32 now = SDL_GetTicks();
93 int delta = now - last;
99 void HeadlessApplication::Loop(int dt) {
100 env.counter.EnterFrame();
103 if (!HasState()) return;
104 env.counter.ExitFrame();
107 void Application::Loop(int dt) {
108 env.counter.EnterFrame();
110 if (!HasState()) return;
113 if (!HasState()) return;
115 env.counter.ExitFrame();
119 void HeadlessApplication::HandleEvents() {
120 env.counter.EnterHandle();
122 while (HasState() && SDL_PollEvent(&event)) {
126 env.counter.ExitHandle();
129 void HeadlessApplication::Handle(const SDL_Event &event) {
130 GetState().Handle(event);
134 void Application::HandleEvents() {
135 env.counter.EnterHandle();
137 while (HasState() && SDL_PollEvent(&event)) {
141 env.counter.ExitHandle();
144 void Application::Handle(const SDL_Event &event) {
145 switch (event.type) {
146 case SDL_WINDOWEVENT:
147 Handle(event.window);
150 GetState().Handle(event);
155 void Application::Handle(const SDL_WindowEvent &event) {
156 switch (event.event) {
157 case SDL_WINDOWEVENT_FOCUS_GAINED:
158 env.window.GrabMouse();
160 case SDL_WINDOWEVENT_FOCUS_LOST:
161 env.window.ReleaseMouse();
163 case SDL_WINDOWEVENT_RESIZED:
164 env.viewport.Resize(event.data1, event.data2);
171 void HeadlessApplication::Update(int dt) {
172 env.counter.EnterUpdate();
174 GetState().Update(dt);
176 env.counter.ExitUpdate();
179 void Application::Update(int dt) {
180 env.counter.EnterUpdate();
181 env.audio.Update(dt);
183 GetState().Update(dt);
185 env.counter.ExitUpdate();
188 void Application::Render() {
189 // gl implementation may (and will probably) delay vsync blocking until
190 // the first write after flipping, which is this clear call
191 env.viewport.Clear();
192 env.counter.EnterRender();
195 GetState().Render(env.viewport);
198 env.counter.ExitRender();
203 void HeadlessApplication::PushState(State *s) {
204 if (!states.empty()) {
205 states.top()->OnPause();
209 if (s->ref_count == 1) {
215 State *HeadlessApplication::PopState() {
216 State *s = states.top();
220 if (!states.empty()) {
221 states.top()->OnResume();
226 State *HeadlessApplication::SwitchState(State *s_new) {
227 State *s_old = states.top();
228 states.top() = s_new;
232 if (s_old->ref_count == 0) {
235 if (s_new->ref_count == 1) {
242 State &HeadlessApplication::GetState() {
243 return *states.top();
246 void HeadlessApplication::CommitStates() {
247 env.state.Commit(*this);
250 bool HeadlessApplication::HasState() const noexcept {
251 return !states.empty();
255 void StateControl::Commit(HeadlessApplication &app) {
256 while (!cue.empty()) {
261 app.PushState(m.state);
264 app.SwitchState(m.state);
270 while (app.HasState()) {
275 while (app.HasState() && &app.GetState() != m.state) {
280 while (app.HasState()) {
281 if (app.PopState() == m.state) {
290 AssetLoader::AssetLoader(const string &base)
291 : fonts(base + "fonts/")
292 , sounds(base + "sounds/")
293 , textures(base + "textures/")
294 , data(base + "data/") {
298 Assets::Assets(const AssetLoader &loader)
299 : large_ui_font(loader.LoadFont("DejaVuSans", 24))
300 , small_ui_font(loader.LoadFont("DejaVuSans", 16)) {
306 CuboidShape block_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }});
307 StairShape stair_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }}, { 0.0f, 0.0f });
308 CuboidShape slab_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.0f, 0.5f }});
312 void AssetLoader::LoadBlockTypes(const std::string &set_name, BlockTypeRegistry ®, TextureIndex &tex_index) const {
313 string full = data + set_name + ".types";
314 std::ifstream file(full);
316 throw std::runtime_error("failed to open block type file " + full);
318 TokenStreamReader in(file);
323 while (in.HasMore()) {
324 in.ReadIdentifier(type_name);
325 in.Skip(Token::EQUALS);
329 in.Skip(Token::ANGLE_BRACKET_OPEN);
330 while (in.Peek().type != Token::ANGLE_BRACKET_CLOSE) {
331 in.ReadIdentifier(name);
332 in.Skip(Token::EQUALS);
333 if (name == "visible") {
334 type.visible = in.GetBool();
335 } else if (name == "texture") {
336 in.ReadString(tex_name);
337 type.texture = tex_index.GetID(tex_name);
338 } else if (name == "color") {
339 in.ReadVec(type.color);
340 } else if (name == "outline") {
341 in.ReadVec(type.outline_color);
342 } else if (name == "label") {
343 in.ReadString(type.label);
344 } else if (name == "luminosity") {
345 type.luminosity = in.GetInt();
346 } else if (name == "block_light") {
347 type.block_light = in.GetBool();
348 } else if (name == "collision") {
349 type.collision = in.GetBool();
350 } else if (name == "collide_block") {
351 type.collide_block = in.GetBool();
352 } else if (name == "shape") {
353 in.ReadIdentifier(shape_name);
354 if (shape_name == "block") {
355 type.shape = &block_shape;
356 type.fill = { true, true, true, true, true, true };
357 } else if (shape_name == "slab") {
358 type.shape = &slab_shape;
359 type.fill = { false, true, false, false, false, false };
360 } else if (shape_name == "stair") {
361 type.shape = &stair_shape;
362 type.fill = { false, true, false, false, false, true };
364 throw runtime_error("unknown block shape: " + shape_name);
367 throw runtime_error("unknown block property: " + name);
369 in.Skip(Token::SEMICOLON);
371 in.Skip(Token::ANGLE_BRACKET_CLOSE);
372 in.Skip(Token::SEMICOLON);
378 CubeMap AssetLoader::LoadCubeMap(const string &name) const {
379 string full = textures + name;
380 string right = full + "-right.png";
381 string left = full + "-left.png";
382 string top = full + "-top.png";
383 string bottom = full + "-bottom.png";
384 string back = full + "-back.png";
385 string front = full + "-front.png";
391 if (!(srf = IMG_Load(right.c_str()))) throw SDLError("IMG_Load");
393 cm.Data(CubeMap::RIGHT, *srf);
395 SDL_FreeSurface(srf);
398 SDL_FreeSurface(srf);
400 if (!(srf = IMG_Load(left.c_str()))) throw SDLError("IMG_Load");
402 cm.Data(CubeMap::LEFT, *srf);
404 SDL_FreeSurface(srf);
407 SDL_FreeSurface(srf);
409 if (!(srf = IMG_Load(top.c_str()))) throw SDLError("IMG_Load");
411 cm.Data(CubeMap::TOP, *srf);
413 SDL_FreeSurface(srf);
416 SDL_FreeSurface(srf);
418 if (!(srf = IMG_Load(bottom.c_str()))) throw SDLError("IMG_Load");
420 cm.Data(CubeMap::BOTTOM, *srf);
422 SDL_FreeSurface(srf);
425 SDL_FreeSurface(srf);
427 if (!(srf = IMG_Load(back.c_str()))) throw SDLError("IMG_Load");
429 cm.Data(CubeMap::BACK, *srf);
431 SDL_FreeSurface(srf);
434 SDL_FreeSurface(srf);
436 if (!(srf = IMG_Load(front.c_str()))) throw SDLError("IMG_Load");
438 cm.Data(CubeMap::FRONT, *srf);
440 SDL_FreeSurface(srf);
443 SDL_FreeSurface(srf);
451 Font AssetLoader::LoadFont(const string &name, int size) const {
452 string full = fonts + name + ".ttf";
453 return Font(full.c_str(), size);
456 Sound AssetLoader::LoadSound(const string &name) const {
457 string full = sounds + name + ".wav";
458 return Sound(full.c_str());
461 Texture AssetLoader::LoadTexture(const string &name) const {
462 string full = textures + name + ".png";
464 SDL_Surface *srf = IMG_Load(full.c_str());
466 throw SDLError("IMG_Load");
470 SDL_FreeSurface(srf);
474 void AssetLoader::LoadTexture(const string &name, ArrayTexture &tex, int layer) const {
475 string full = textures + name + ".png";
476 SDL_Surface *srf = IMG_Load(full.c_str());
478 throw SDLError("IMG_Load");
482 tex.Data(layer, *srf);
484 SDL_FreeSurface(srf);
487 SDL_FreeSurface(srf);
490 void AssetLoader::LoadTextures(const TextureIndex &index, ArrayTexture &tex) const {
491 // TODO: where the hell should that size come from?
492 tex.Reserve(16, 16, index.Size(), Format());
493 for (const auto &entry : index.Entries()) {
494 LoadTexture(entry.first, tex, entry.second);
499 TextureIndex::TextureIndex()
504 int TextureIndex::GetID(const string &name) {
505 auto entry = id_map.find(name);
506 if (entry == id_map.end()) {
507 auto result = id_map.emplace(name, Size());
508 return result.first->second;
510 return entry->second;
515 void FrameCounter::EnterFrame() noexcept {
516 last_enter = SDL_GetTicks();
517 last_tick = last_enter;
520 void FrameCounter::EnterHandle() noexcept {
524 void FrameCounter::ExitHandle() noexcept {
525 current.handle = Tick();
528 void FrameCounter::EnterUpdate() noexcept {
532 void FrameCounter::ExitUpdate() noexcept {
533 current.update = Tick();
536 void FrameCounter::EnterRender() noexcept {
540 void FrameCounter::ExitRender() noexcept {
541 current.render = Tick();
544 void FrameCounter::ExitFrame() noexcept {
545 Uint32 now = SDL_GetTicks();
546 current.total = now - last_enter;
547 current.running = current.handle + current.update + current.render;
548 current.waiting = current.total - current.running;
552 if (cur_frame >= NUM_FRAMES) {
561 int FrameCounter::Tick() noexcept {
562 Uint32 now = SDL_GetTicks();
563 int delta = now - last_tick;
568 void FrameCounter::Accumulate() noexcept {
569 sum.handle += current.handle;
570 sum.update += current.update;
571 sum.render += current.render;
572 sum.running += current.running;
573 sum.waiting += current.waiting;
574 sum.total += current.total;
576 max.handle = std::max(current.handle, max.handle);
577 max.update = std::max(current.update, max.update);
578 max.render = std::max(current.render, max.render);
579 max.running = std::max(current.running, max.running);
580 max.waiting = std::max(current.waiting, max.waiting);
581 max.total = std::max(current.total, max.total);
583 current = Frame<int>();
586 void FrameCounter::Push() noexcept {
588 avg.handle = sum.handle * factor;
589 avg.update = sum.update * factor;
590 avg.render = sum.render * factor;
591 avg.running = sum.running * factor;
592 avg.waiting = sum.waiting * factor;
593 avg.total = sum.total * factor;