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