|
| 1 | +#include "chomper/ui/countdown.hpp" |
| 2 | +#include "chomper/theme.hpp" |
| 3 | +#include <klib/assert.hpp> |
| 4 | + |
| 5 | +namespace chomper::ui { |
| 6 | +Countdown::Countdown(gsl::not_null<le::IFont*> font, le::TextHeight const textHeight, kvf::Seconds const timer) |
| 7 | + : m_font(font), m_textHeight(textHeight), m_timer(timer), m_remain(timer) { |
| 8 | + auto const diameter = float(m_textHeight) + 30.0f; |
| 9 | + m_background.create(diameter); |
| 10 | + m_background.tint = theme::clearColor_v; |
| 11 | +} |
| 12 | + |
| 13 | +void Countdown::tick(kvf::Seconds const dt) { |
| 14 | + if (m_remain <= 0s) { |
| 15 | + return; |
| 16 | + } |
| 17 | + |
| 18 | + auto const prevSeconds = std::chrono::duration_cast<std::chrono::seconds>(m_remain); |
| 19 | + m_remain -= dt; |
| 20 | + auto const currSeconds = std::chrono::duration_cast<std::chrono::seconds>(m_remain); |
| 21 | + if (prevSeconds > currSeconds) { |
| 22 | + setTimerText(currSeconds + 1s); |
| 23 | + } |
| 24 | + |
| 25 | + updateSector(); |
| 26 | +} |
| 27 | + |
| 28 | +void Countdown::draw(le::IRenderer& renderer) const { |
| 29 | + if (m_remain <= 0s) { |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + m_sector.draw(renderer); |
| 34 | + m_background.draw(renderer); |
| 35 | + m_text.draw(renderer); |
| 36 | +} |
| 37 | + |
| 38 | +void Countdown::setTimerText(std::chrono::seconds const value) { |
| 39 | + auto const params = le::drawable::Text::Params{ |
| 40 | + .height = m_textHeight, |
| 41 | + .expand = le::drawable::TextExpand::eBoth, |
| 42 | + }; |
| 43 | + auto const text = std::format("{}", value.count()); |
| 44 | + m_text.set_string(*m_font, text, params); |
| 45 | + |
| 46 | + // technically this isn't correct y-centering because parts of glyphs can be above/below the baseline, |
| 47 | + // and Text::get_size() is insufficient to adjust for that. |
| 48 | + // here, since each displayed glyph (0-9) is entirely above the baseline (unlike say 'g'), |
| 49 | + // it can be pushed down by half the size and it will "look" y-centered. |
| 50 | + // this is what is known as a "hack". |
| 51 | + m_text.transform.position.y = -0.5f * m_text.get_size().y; |
| 52 | +} |
| 53 | + |
| 54 | +void Countdown::updateSector() { |
| 55 | + KLIB_ASSERT(m_timer > 0s); |
| 56 | + auto const ratio = m_remain / m_timer; |
| 57 | + static constexpr auto degreesBegin{90.0f}; |
| 58 | + auto const degreesEnd = degreesBegin + (ratio * 360.0f); |
| 59 | + auto const diameter = m_background.get_diameter() + 30.0f; |
| 60 | + auto const sectorParams = le::shape::Sector::Params{ |
| 61 | + .degrees_begin = degreesBegin, |
| 62 | + .degrees_end = degreesEnd, |
| 63 | + }; |
| 64 | + m_sector.create(diameter, sectorParams); |
| 65 | +} |
| 66 | +} // namespace chomper::ui |
0 commit comments