Created
August 26, 2018 19:02
-
-
Save MarioLiebisch/127b3c6968fd0ef4391abd26ab3914b8 to your computer and use it in GitHub Desktop.
Small example how to add stats counting to a SFML `sf::RenderWindow`. Release builds could just use `sf::RenderWindow` directly instead. Note this isn't necessarily 100% perfect or correct; written from memory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SFML/Graphics.hpp> | |
#include <sstream> | |
class RenderWindowStats : public sf::RenderWindow { | |
public: | |
RenderWindowStats() : RenderWindow({640, 480}, "Test") { | |
} | |
void draw(sf::Drawable &dr, sf::RenderStates states = sf::RenderStates()) { | |
++mDrawCallsTemp; | |
sf::RenderWindow::draw(dr, states); | |
if (mTimer.getElapsedTime() > sf::seconds(1)) { | |
mDrawCalls = mDrawCallsTemp; | |
mDrawCallsTemp = 0; | |
mFrames = mFramesTemp; | |
mFramesTemp = 0; | |
mTimer.restart(); | |
} | |
} | |
void display() { | |
++mFramesTemp; | |
sf::RenderWindow::display(); | |
} | |
std::size_t getDrawCallsPerSecond() const { return mDrawCalls; } | |
std::size_t getFramesPerSecond() const { return mFrames; } | |
private: | |
std::size_t mDrawCallsTemp = 0; | |
std::size_t mDrawCalls = 0; | |
std::size_t mFramesTemp = 0; | |
std::size_t mFrames = 0; | |
sf::Clock mTimer; | |
}; | |
int main(int argc, char **argv) { | |
RenderWindowStats window; | |
window.setVerticalSyncEnabled(true); | |
sf::Font font; font.loadFromFile("C:/Windows/Fonts/Arial.ttf"); | |
sf::Text statsText("", font, 10); | |
statsText.setFillColor(sf::Color::White); | |
statsText.setOutlineColor(sf::Color::Black); | |
statsText.setOutlineThickness(1); | |
sf::RectangleShape rect; | |
while(window.isOpen()) { | |
sf::Event event; | |
while (window.pollEvent(event)) { | |
switch (event.type) { | |
case sf::Event::Closed: | |
window.close(); | |
break; | |
} | |
} | |
statsText.setString( | |
std::string("Draw Calls per Second: ") + std::to_string(window.getDrawCallsPerSecond()) + "\n" + | |
std::string("Frames per Second: ") + std::to_string(window.getFramesPerSecond()) + "\n" | |
); | |
window.clear(); | |
for (unsigned int i = 0; i < 10; ++i) | |
window.draw(rect); | |
window.draw(statsText); | |
window.display(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment