]> git.localhorst.tv Git - blank.git/blob - src/app/app.cpp
handle events in headless environment
[blank.git] / src / app / app.cpp
1 #include "Application.hpp"
2 #include "Assets.hpp"
3 #include "Environment.hpp"
4 #include "FrameCounter.hpp"
5 #include "State.hpp"
6 #include "StateControl.hpp"
7 #include "TextureIndex.hpp"
8
9 #include "init.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"
20
21 #include <fstream>
22 #include <iomanip>
23 #include <iostream>
24 #include <stdexcept>
25 #include <SDL_image.h>
26
27 using std::runtime_error;
28 using std::string;
29
30
31 namespace blank {
32
33 HeadlessApplication::HeadlessApplication(HeadlessEnvironment &e)
34 : env(e)
35 , states() {
36
37 }
38
39 HeadlessApplication::~HeadlessApplication() {
40
41 }
42
43
44 Application::Application(Environment &e)
45 : HeadlessApplication(e)
46 , env(e) {
47
48 }
49
50 Application::~Application() {
51         env.audio.StopAll();
52 }
53
54
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;
60                 Loop(delta);
61                 last = now;
62         }
63 }
64
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;
71                 Loop(delta);
72                 last = now;
73         }
74 }
75
76 void HeadlessApplication::RunS(size_t n, size_t t) {
77         for (size_t i = 0; HasState() && i < n; ++i) {
78                 Loop(t);
79                 std::cout << '.';
80                 if (i % 16 == 15) {
81                         std::cout << std::setfill(' ') << std::setw(5) << std::right << (i + 1) << std::endl;
82                 } else {
83                         std::cout << std::flush;
84                 }
85         }
86 }
87
88
89 void HeadlessApplication::Run() {
90         Uint32 last = SDL_GetTicks();
91         while (HasState()) {
92                 Uint32 now = SDL_GetTicks();
93                 int delta = now - last;
94                 Loop(delta);
95                 last = now;
96         }
97 }
98
99 void HeadlessApplication::Loop(int dt) {
100         env.counter.EnterFrame();
101         HandleEvents();
102         if (!HasState()) return;
103         Update(dt);
104         CommitStates();
105         if (!HasState()) return;
106         env.counter.ExitFrame();
107 }
108
109 void Application::Loop(int dt) {
110         env.counter.EnterFrame();
111         HandleEvents();
112         if (!HasState()) return;
113         Update(dt);
114         CommitStates();
115         if (!HasState()) return;
116         Render();
117         env.counter.ExitFrame();
118 }
119
120
121 void HeadlessApplication::HandleEvents() {
122         env.counter.EnterHandle();
123         SDL_Event event;
124         while (HasState() && SDL_PollEvent(&event)) {
125                 Handle(event);
126                 CommitStates();
127         }
128         env.counter.ExitHandle();
129 }
130
131 void HeadlessApplication::Handle(const SDL_Event &event) {
132         GetState().Handle(event);
133 }
134
135
136 void Application::HandleEvents() {
137         env.counter.EnterHandle();
138         SDL_Event event;
139         while (HasState() && SDL_PollEvent(&event)) {
140                 Handle(event);
141                 CommitStates();
142         }
143         env.counter.ExitHandle();
144 }
145
146 void Application::Handle(const SDL_Event &event) {
147         switch (event.type) {
148                 case SDL_WINDOWEVENT:
149                         Handle(event.window);
150                         break;
151                 default:
152                         GetState().Handle(event);
153                         break;
154         }
155 }
156
157 void Application::Handle(const SDL_WindowEvent &event) {
158         switch (event.event) {
159                 case SDL_WINDOWEVENT_FOCUS_GAINED:
160                         env.window.GrabMouse();
161                         break;
162                 case SDL_WINDOWEVENT_FOCUS_LOST:
163                         env.window.ReleaseMouse();
164                         break;
165                 case SDL_WINDOWEVENT_RESIZED:
166                         env.viewport.Resize(event.data1, event.data2);
167                         break;
168                 default:
169                         break;
170         }
171 }
172
173 void HeadlessApplication::Update(int dt) {
174         env.counter.EnterUpdate();
175         if (HasState()) {
176                 GetState().Update(dt);
177         }
178         env.counter.ExitUpdate();
179 }
180
181 void Application::Update(int dt) {
182         env.counter.EnterUpdate();
183         env.audio.Update(dt);
184         if (HasState()) {
185                 GetState().Update(dt);
186         }
187         env.counter.ExitUpdate();
188 }
189
190 void Application::Render() {
191         // gl implementation may (and will probably) delay vsync blocking until
192         // the first write after flipping, which is this clear call
193         env.viewport.Clear();
194         env.counter.EnterRender();
195
196         if (HasState()) {
197                 GetState().Render(env.viewport);
198         }
199
200         env.counter.ExitRender();
201         env.window.Flip();
202 }
203
204
205 void HeadlessApplication::PushState(State *s) {
206         if (!states.empty()) {
207                 states.top()->OnPause();
208         }
209         states.emplace(s);
210         ++s->ref_count;
211         if (s->ref_count == 1) {
212                 s->OnEnter();
213         }
214         s->OnResume();
215 }
216
217 State *HeadlessApplication::PopState() {
218         State *s = states.top();
219         states.pop();
220         s->OnPause();
221         s->OnExit();
222         if (!states.empty()) {
223                 states.top()->OnResume();
224         }
225         return s;
226 }
227
228 State *HeadlessApplication::SwitchState(State *s_new) {
229         State *s_old = states.top();
230         states.top() = s_new;
231         --s_old->ref_count;
232         ++s_new->ref_count;
233         s_old->OnPause();
234         if (s_old->ref_count == 0) {
235                 s_old->OnExit();
236         }
237         if (s_new->ref_count == 1) {
238                 s_new->OnEnter();
239         }
240         s_new->OnResume();
241         return s_old;
242 }
243
244 State &HeadlessApplication::GetState() {
245         return *states.top();
246 }
247
248 void HeadlessApplication::CommitStates() {
249         env.state.Commit(*this);
250 }
251
252 bool HeadlessApplication::HasState() const noexcept {
253         return !states.empty();
254 }
255
256
257 void StateControl::Commit(HeadlessApplication &app) {
258         while (!cue.empty()) {
259                 Memo m(cue.front());
260                 cue.pop();
261                 switch (m.cmd) {
262                         case PUSH:
263                                 app.PushState(m.state);
264                                 break;
265                         case SWITCH:
266                                 app.SwitchState(m.state);
267                                 break;
268                         case POP:
269                                 app.PopState();
270                                 break;
271                         case POP_ALL:
272                                 while (app.HasState()) {
273                                         app.PopState();
274                                 }
275                                 break;
276                         case POP_AFTER:
277                                 while (app.HasState() && &app.GetState() != m.state) {
278                                         app.PopState();
279                                 }
280                                 break;
281                         case POP_UNTIL:
282                                 while (app.HasState()) {
283                                         if (app.PopState() == m.state) {
284                                                 break;
285                                         }
286                                 }
287                 }
288         }
289 }
290
291
292 AssetLoader::AssetLoader(const string &base)
293 : fonts(base + "fonts/")
294 , sounds(base + "sounds/")
295 , textures(base + "textures/")
296 , data(base + "data/") {
297
298 }
299
300 Assets::Assets(const AssetLoader &loader)
301 : large_ui_font(loader.LoadFont("DejaVuSans", 24))
302 , small_ui_font(loader.LoadFont("DejaVuSans", 16)) {
303
304 }
305
306 namespace {
307
308 CuboidShape block_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }});
309 StairShape stair_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }}, { 0.0f, 0.0f });
310 CuboidShape slab_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.0f, 0.5f }});
311
312 }
313
314 void AssetLoader::LoadBlockTypes(const std::string &set_name, BlockTypeRegistry &reg, TextureIndex &tex_index) const {
315         string full = data + set_name + ".types";
316         std::ifstream file(full);
317         if (!file) {
318                 throw std::runtime_error("failed to open block type file " + full);
319         }
320         TokenStreamReader in(file);
321         string type_name;
322         string name;
323         string tex_name;
324         string shape_name;
325         while (in.HasMore()) {
326                 in.ReadIdentifier(type_name);
327                 in.Skip(Token::EQUALS);
328                 BlockType type;
329
330                 // read block type
331                 in.Skip(Token::ANGLE_BRACKET_OPEN);
332                 while (in.Peek().type != Token::ANGLE_BRACKET_CLOSE) {
333                         in.ReadIdentifier(name);
334                         in.Skip(Token::EQUALS);
335                         if (name == "visible") {
336                                 type.visible = in.GetBool();
337                         } else if (name == "texture") {
338                                 in.ReadString(tex_name);
339                                 type.texture = tex_index.GetID(tex_name);
340                         } else if (name == "color") {
341                                 in.ReadVec(type.color);
342                         } else if (name == "outline") {
343                                 in.ReadVec(type.outline_color);
344                         } else if (name == "label") {
345                                 in.ReadString(type.label);
346                         } else if (name == "luminosity") {
347                                 type.luminosity = in.GetInt();
348                         } else if (name == "block_light") {
349                                 type.block_light = in.GetBool();
350                         } else if (name == "collision") {
351                                 type.collision = in.GetBool();
352                         } else if (name == "collide_block") {
353                                 type.collide_block = in.GetBool();
354                         } else if (name == "generate") {
355                                 type.generate = in.GetBool();
356                         } else if (name == "min_solidity") {
357                                 type.min_solidity = in.GetFloat();
358                         } else if (name == "mid_solidity") {
359                                 type.mid_solidity = in.GetFloat();
360                         } else if (name == "max_solidity") {
361                                 type.max_solidity = in.GetFloat();
362                         } else if (name == "min_humidity") {
363                                 type.min_humidity = in.GetFloat();
364                         } else if (name == "mid_humidity") {
365                                 type.mid_humidity = in.GetFloat();
366                         } else if (name == "max_humidity") {
367                                 type.max_humidity = in.GetFloat();
368                         } else if (name == "min_temperature") {
369                                 type.min_temperature = in.GetFloat();
370                         } else if (name == "mid_temperature") {
371                                 type.mid_temperature = in.GetFloat();
372                         } else if (name == "max_temperature") {
373                                 type.max_temperature = in.GetFloat();
374                         } else if (name == "min_richness") {
375                                 type.min_richness = in.GetFloat();
376                         } else if (name == "mid_richness") {
377                                 type.mid_richness = in.GetFloat();
378                         } else if (name == "max_richness") {
379                                 type.max_richness = in.GetFloat();
380                         } else if (name == "commonness") {
381                                 type.commonness = in.GetFloat();
382                         } else if (name == "shape") {
383                                 in.ReadIdentifier(shape_name);
384                                 if (shape_name == "block") {
385                                         type.shape = &block_shape;
386                                         type.fill = {  true,  true,  true,  true,  true,  true };
387                                 } else if (shape_name == "slab") {
388                                         type.shape = &slab_shape;
389                                         type.fill = { false,  true, false, false, false, false };
390                                 } else if (shape_name == "stair") {
391                                         type.shape = &stair_shape;
392                                         type.fill = { false,  true, false, false, false,  true };
393                                 } else {
394                                         throw runtime_error("unknown block shape: " + shape_name);
395                                 }
396                         } else {
397                                 throw runtime_error("unknown block property: " + name);
398                         }
399                         in.Skip(Token::SEMICOLON);
400                 }
401                 in.Skip(Token::ANGLE_BRACKET_CLOSE);
402                 in.Skip(Token::SEMICOLON);
403
404                 reg.Add(type);
405         }
406 }
407
408 CubeMap AssetLoader::LoadCubeMap(const string &name) const {
409         string full = textures + name;
410         string right = full + "-right.png";
411         string left = full + "-left.png";
412         string top = full + "-top.png";
413         string bottom = full + "-bottom.png";
414         string back = full + "-back.png";
415         string front = full + "-front.png";
416
417         CubeMap cm;
418         cm.Bind();
419         SDL_Surface *srf;
420
421         if (!(srf = IMG_Load(right.c_str()))) throw SDLError("IMG_Load");
422         try {
423                 cm.Data(CubeMap::RIGHT, *srf);
424         } catch (...) {
425                 SDL_FreeSurface(srf);
426                 throw;
427         }
428         SDL_FreeSurface(srf);
429
430         if (!(srf = IMG_Load(left.c_str()))) throw SDLError("IMG_Load");
431         try {
432                 cm.Data(CubeMap::LEFT, *srf);
433         } catch (...) {
434                 SDL_FreeSurface(srf);
435                 throw;
436         }
437         SDL_FreeSurface(srf);
438
439         if (!(srf = IMG_Load(top.c_str()))) throw SDLError("IMG_Load");
440         try {
441                 cm.Data(CubeMap::TOP, *srf);
442         } catch (...) {
443                 SDL_FreeSurface(srf);
444                 throw;
445         }
446         SDL_FreeSurface(srf);
447
448         if (!(srf = IMG_Load(bottom.c_str()))) throw SDLError("IMG_Load");
449         try {
450                 cm.Data(CubeMap::BOTTOM, *srf);
451         } catch (...) {
452                 SDL_FreeSurface(srf);
453                 throw;
454         }
455         SDL_FreeSurface(srf);
456
457         if (!(srf = IMG_Load(back.c_str()))) throw SDLError("IMG_Load");
458         try {
459                 cm.Data(CubeMap::BACK, *srf);
460         } catch (...) {
461                 SDL_FreeSurface(srf);
462                 throw;
463         }
464         SDL_FreeSurface(srf);
465
466         if (!(srf = IMG_Load(front.c_str()))) throw SDLError("IMG_Load");
467         try {
468                 cm.Data(CubeMap::FRONT, *srf);
469         } catch (...) {
470                 SDL_FreeSurface(srf);
471                 throw;
472         }
473         SDL_FreeSurface(srf);
474
475         cm.FilterNearest();
476         cm.WrapEdge();
477
478         return cm;
479 }
480
481 Font AssetLoader::LoadFont(const string &name, int size) const {
482         string full = fonts + name + ".ttf";
483         return Font(full.c_str(), size);
484 }
485
486 Sound AssetLoader::LoadSound(const string &name) const {
487         string full = sounds + name + ".wav";
488         return Sound(full.c_str());
489 }
490
491 Texture AssetLoader::LoadTexture(const string &name) const {
492         string full = textures + name + ".png";
493         Texture tex;
494         SDL_Surface *srf = IMG_Load(full.c_str());
495         if (!srf) {
496                 throw SDLError("IMG_Load");
497         }
498         tex.Bind();
499         tex.Data(*srf);
500         SDL_FreeSurface(srf);
501         return tex;
502 }
503
504 void AssetLoader::LoadTexture(const string &name, ArrayTexture &tex, int layer) const {
505         string full = textures + name + ".png";
506         SDL_Surface *srf = IMG_Load(full.c_str());
507         if (!srf) {
508                 throw SDLError("IMG_Load");
509         }
510         tex.Bind();
511         try {
512                 tex.Data(layer, *srf);
513         } catch (...) {
514                 SDL_FreeSurface(srf);
515                 throw;
516         }
517         SDL_FreeSurface(srf);
518 }
519
520 void AssetLoader::LoadTextures(const TextureIndex &index, ArrayTexture &tex) const {
521         // TODO: where the hell should that size come from?
522         tex.Reserve(16, 16, index.Size(), Format());
523         for (const auto &entry : index.Entries()) {
524                 LoadTexture(entry.first, tex, entry.second);
525         }
526 }
527
528
529 TextureIndex::TextureIndex()
530 : id_map() {
531
532 }
533
534 int TextureIndex::GetID(const string &name) {
535         auto entry = id_map.find(name);
536         if (entry == id_map.end()) {
537                 auto result = id_map.emplace(name, Size());
538                 return result.first->second;
539         } else {
540                 return entry->second;
541         }
542 }
543
544
545 void FrameCounter::EnterFrame() noexcept {
546         last_enter = SDL_GetTicks();
547         last_tick = last_enter;
548 }
549
550 void FrameCounter::EnterHandle() noexcept {
551         Tick();
552 }
553
554 void FrameCounter::ExitHandle() noexcept {
555         current.handle = Tick();
556 }
557
558 void FrameCounter::EnterUpdate() noexcept {
559         Tick();
560 }
561
562 void FrameCounter::ExitUpdate() noexcept {
563         current.update = Tick();
564 }
565
566 void FrameCounter::EnterRender() noexcept {
567         Tick();
568 }
569
570 void FrameCounter::ExitRender() noexcept {
571         current.render = Tick();
572 }
573
574 void FrameCounter::ExitFrame() noexcept {
575         Uint32 now = SDL_GetTicks();
576         current.total = now - last_enter;
577         current.running = current.handle + current.update + current.render;
578         current.waiting = current.total - current.running;
579         Accumulate();
580
581         ++cur_frame;
582         if (cur_frame >= NUM_FRAMES) {
583                 Push();
584                 cur_frame = 0;
585                 changed = true;
586         } else {
587                 changed = false;
588         }
589 }
590
591 int FrameCounter::Tick() noexcept {
592         Uint32 now = SDL_GetTicks();
593         int delta = now - last_tick;
594         last_tick = now;
595         return delta;
596 }
597
598 void FrameCounter::Accumulate() noexcept {
599         sum.handle += current.handle;
600         sum.update += current.update;
601         sum.render += current.render;
602         sum.running += current.running;
603         sum.waiting += current.waiting;
604         sum.total += current.total;
605
606         max.handle = std::max(current.handle, max.handle);
607         max.update = std::max(current.update, max.update);
608         max.render = std::max(current.render, max.render);
609         max.running = std::max(current.running, max.running);
610         max.waiting = std::max(current.waiting, max.waiting);
611         max.total = std::max(current.total, max.total);
612
613         current = Frame<int>();
614 }
615
616 void FrameCounter::Push() noexcept {
617         peak = max;
618         avg.handle = sum.handle * factor;
619         avg.update = sum.update * factor;
620         avg.render = sum.render * factor;
621         avg.running = sum.running * factor;
622         avg.waiting = sum.waiting * factor;
623         avg.total = sum.total * factor;
624
625         sum = Frame<int>();
626         max = Frame<int>();
627 }
628
629 }