1 #include "Application.hpp"
3 #include "Environment.hpp"
4 #include "FrameCounter.hpp"
6 #include "StateControl.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"
29 #include <SDL_image.h>
31 using std::runtime_error;
37 HeadlessApplication::HeadlessApplication(HeadlessEnvironment &e)
43 HeadlessApplication::~HeadlessApplication() {
48 Application::Application(Environment &e)
49 : HeadlessApplication(e)
54 Application::~Application() {
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;
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;
80 void HeadlessApplication::RunS(size_t n, size_t t) {
81 for (size_t i = 0; HasState() && i < n; ++i) {
85 std::cout << std::setfill(' ') << std::setw(5) << std::right << (i + 1) << std::endl;
87 std::cout << std::flush;
93 void HeadlessApplication::Run() {
94 Uint32 last = SDL_GetTicks();
96 Uint32 now = SDL_GetTicks();
97 int delta = now - last;
103 void HeadlessApplication::Loop(int dt) {
104 env.counter.EnterFrame();
106 if (!HasState()) return;
109 if (!HasState()) return;
110 env.counter.ExitFrame();
113 void Application::Loop(int dt) {
114 env.counter.EnterFrame();
116 if (!HasState()) return;
119 if (!HasState()) return;
121 env.counter.ExitFrame();
125 void HeadlessApplication::HandleEvents() {
126 env.counter.EnterHandle();
128 while (HasState() && SDL_PollEvent(&event)) {
132 env.counter.ExitHandle();
135 void HeadlessApplication::Handle(const SDL_Event &event) {
136 GetState().Handle(event);
140 void Application::HandleEvents() {
141 env.counter.EnterHandle();
143 while (HasState() && SDL_PollEvent(&event)) {
147 env.counter.ExitHandle();
150 void Application::Handle(const SDL_Event &event) {
151 switch (event.type) {
152 case SDL_WINDOWEVENT:
153 Handle(event.window);
156 GetState().Handle(event);
161 void Application::Handle(const SDL_WindowEvent &event) {
162 switch (event.event) {
163 case SDL_WINDOWEVENT_FOCUS_GAINED:
164 GetState().OnFocus();
166 case SDL_WINDOWEVENT_FOCUS_LOST:
169 case SDL_WINDOWEVENT_RESIZED:
170 env.viewport.Resize(event.data1, event.data2);
171 GetState().OnResize(env.viewport);
178 void HeadlessApplication::Update(int dt) {
179 env.counter.EnterUpdate();
181 GetState().Update(dt);
183 env.counter.ExitUpdate();
186 void Application::Update(int dt) {
187 env.counter.EnterUpdate();
188 env.audio.Update(dt);
190 GetState().Update(dt);
192 env.counter.ExitUpdate();
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();
202 GetState().Render(env.viewport);
205 env.counter.ExitRender();
210 void HeadlessApplication::PushState(State *s) {
211 if (!states.empty()) {
212 states.top()->OnPause();
216 if (s->ref_count == 1) {
222 State *HeadlessApplication::PopState() {
223 State *s = states.top();
227 if (!states.empty()) {
228 states.top()->OnResume();
233 State *HeadlessApplication::SwitchState(State *s_new) {
234 State *s_old = states.top();
235 states.top() = s_new;
239 if (s_old->ref_count == 0) {
242 if (s_new->ref_count == 1) {
249 State &HeadlessApplication::GetState() {
250 return *states.top();
253 void HeadlessApplication::CommitStates() {
254 env.state.Commit(*this);
257 bool HeadlessApplication::HasState() const noexcept {
258 return !states.empty();
262 void StateControl::Commit(HeadlessApplication &app) {
263 while (!cue.empty()) {
268 app.PushState(m.state);
271 app.SwitchState(m.state);
277 while (app.HasState()) {
282 while (app.HasState() && &app.GetState() != m.state) {
287 while (app.HasState()) {
288 if (app.PopState() == m.state) {
297 AssetLoader::AssetLoader(const string &base)
298 : fonts(base + "fonts/")
299 , sounds(base + "sounds/")
300 , textures(base + "textures/")
301 , data(base + "data/") {
305 Assets::Assets(const AssetLoader &loader)
306 : large_ui_font(loader.LoadFont("DejaVuSans", 24))
307 , small_ui_font(loader.LoadFont("DejaVuSans", 16)) {
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 }});
319 void AssetLoader::LoadBlockTypes(
320 const string &set_name,
321 BlockTypeRegistry ®,
322 ResourceIndex &snd_index,
323 ResourceIndex &tex_index,
324 const ShapeRegistry &shapes
326 string full = data + set_name + ".types";
327 std::ifstream file(full);
329 throw std::runtime_error("failed to open block type file " + full);
331 TokenStreamReader in(file);
336 while (in.HasMore()) {
337 in.ReadIdentifier(type_name);
338 in.Skip(Token::EQUALS);
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);
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);
415 std::cerr << "warning: unknown block type property " << name << std::endl;
416 while (in.Peek().type != Token::SEMICOLON) {
420 in.Skip(Token::SEMICOLON);
422 in.Skip(Token::ANGLE_BRACKET_CLOSE);
423 in.Skip(Token::SEMICOLON);
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";
442 if (!(srf = IMG_Load(right.c_str()))) throw SDLError("IMG_Load");
444 cm.Data(CubeMap::RIGHT, *srf);
446 SDL_FreeSurface(srf);
449 SDL_FreeSurface(srf);
451 if (!(srf = IMG_Load(left.c_str()))) throw SDLError("IMG_Load");
453 cm.Data(CubeMap::LEFT, *srf);
455 SDL_FreeSurface(srf);
458 SDL_FreeSurface(srf);
460 if (!(srf = IMG_Load(top.c_str()))) throw SDLError("IMG_Load");
462 cm.Data(CubeMap::TOP, *srf);
464 SDL_FreeSurface(srf);
467 SDL_FreeSurface(srf);
469 if (!(srf = IMG_Load(bottom.c_str()))) throw SDLError("IMG_Load");
471 cm.Data(CubeMap::BOTTOM, *srf);
473 SDL_FreeSurface(srf);
476 SDL_FreeSurface(srf);
478 if (!(srf = IMG_Load(back.c_str()))) throw SDLError("IMG_Load");
480 cm.Data(CubeMap::BACK, *srf);
482 SDL_FreeSurface(srf);
485 SDL_FreeSurface(srf);
487 if (!(srf = IMG_Load(front.c_str()))) throw SDLError("IMG_Load");
489 cm.Data(CubeMap::FRONT, *srf);
491 SDL_FreeSurface(srf);
494 SDL_FreeSurface(srf);
502 Font AssetLoader::LoadFont(const string &name, int size) const {
503 string full = fonts + name + ".ttf";
504 return Font(full.c_str(), size);
507 void AssetLoader::LoadModels(
508 const string &set_name,
509 ModelRegistry &models,
510 ResourceIndex &tex_index,
511 const ShapeRegistry &shapes
513 string full = data + set_name + ".models";
514 std::ifstream file(full);
516 throw std::runtime_error("failed to open model file " + full);
518 TokenStreamReader in(file);
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 == "body") {
532 model.SetBody(in.GetULong());
533 } else if (prop_name == "eyes") {
534 model.SetEyes(in.GetULong());
536 while (in.HasMore() && in.Peek().type != Token::SEMICOLON) {
540 in.Skip(Token::SEMICOLON);
543 in.Skip(Token::ANGLE_BRACKET_CLOSE);
544 in.Skip(Token::SEMICOLON);
548 void AssetLoader::LoadShapes(const string &set_name, ShapeRegistry &shapes) const {
549 string full = data + set_name + ".shapes";
550 std::ifstream file(full);
552 throw std::runtime_error("failed to open shape file " + full);
554 TokenStreamReader in(file);
556 while (in.HasMore()) {
557 in.ReadIdentifier(shape_name);
558 in.Skip(Token::EQUALS);
559 Shape &shape = shapes.Add(shape_name);
561 in.Skip(Token::SEMICOLON);
565 Sound AssetLoader::LoadSound(const string &name) const {
566 string full = sounds + name + ".wav";
567 return Sound(full.c_str());
570 Texture AssetLoader::LoadTexture(const string &name) const {
571 string full = textures + name + ".png";
573 SDL_Surface *srf = IMG_Load(full.c_str());
575 throw SDLError("IMG_Load");
579 SDL_FreeSurface(srf);
583 void AssetLoader::LoadTexture(const string &name, ArrayTexture &tex, int layer) const {
584 string full = textures + name + ".png";
585 SDL_Surface *srf = IMG_Load(full.c_str());
587 throw SDLError("IMG_Load");
591 tex.Data(layer, *srf);
593 SDL_FreeSurface(srf);
596 SDL_FreeSurface(srf);
599 void AssetLoader::LoadTextures(const ResourceIndex &index, ArrayTexture &tex) const {
600 // TODO: where the hell should that size come from?
601 tex.Reserve(16, 16, index.Size(), Format());
602 for (const auto &entry : index.Entries()) {
603 LoadTexture(entry.first, tex, entry.second);
608 void FrameCounter::EnterFrame() noexcept {
609 last_enter = SDL_GetTicks();
610 last_tick = last_enter;
613 void FrameCounter::EnterHandle() noexcept {
617 void FrameCounter::ExitHandle() noexcept {
618 current.handle = Tick();
621 void FrameCounter::EnterUpdate() noexcept {
625 void FrameCounter::ExitUpdate() noexcept {
626 current.update = Tick();
629 void FrameCounter::EnterRender() noexcept {
633 void FrameCounter::ExitRender() noexcept {
634 current.render = Tick();
637 void FrameCounter::ExitFrame() noexcept {
638 Uint32 now = SDL_GetTicks();
639 current.total = now - last_enter;
640 current.running = current.handle + current.update + current.render;
641 current.waiting = current.total - current.running;
645 if (cur_frame >= NUM_FRAMES) {
654 int FrameCounter::Tick() noexcept {
655 Uint32 now = SDL_GetTicks();
656 int delta = now - last_tick;
661 void FrameCounter::Accumulate() noexcept {
662 sum.handle += current.handle;
663 sum.update += current.update;
664 sum.render += current.render;
665 sum.running += current.running;
666 sum.waiting += current.waiting;
667 sum.total += current.total;
669 max.handle = std::max(current.handle, max.handle);
670 max.update = std::max(current.update, max.update);
671 max.render = std::max(current.render, max.render);
672 max.running = std::max(current.running, max.running);
673 max.waiting = std::max(current.waiting, max.waiting);
674 max.total = std::max(current.total, max.total);
676 current = Frame<int>();
679 void FrameCounter::Push() noexcept {
681 avg.handle = sum.handle * factor;
682 avg.update = sum.update * factor;
683 avg.render = sum.render * factor;
684 avg.running = sum.running * factor;
685 avg.waiting = sum.waiting * factor;
686 avg.total = sum.total * factor;