TinyRaytracer 0.1
A simple C++ raytracer
Loading...
Searching...
No Matches
progress.hpp
1#include <iostream>
2#include <string>
3#include <thread>
4#include <atomic>
5#include <chrono>
6#include <cstdio>
7
9public:
10 ProgressBar(int total, int barWidth = 50)
11 : total_(total), barWidth_(barWidth), current_(0), stop_(false) {
12 hideCursor();
13 // Start the progress bar thread
14 thread_ = std::thread(&ProgressBar::run, this);
15 }
16
17 ~ProgressBar() {
18 finish(); // Ensure progress bar finishes and cursor is shown
19 }
20
21 void update(int progress) {
22 current_ = progress;
23 if (progress > total_) current_ = total_;
24 }
25
26 void finish() {
27 stop_ = true;
28 if (thread_.joinable()) {
29 thread_.join(); // Wait for the thread to finish
30 }
31 // Ensure the bar shows 100%
32 update(total_);
33 display(); // Final display call to ensure it shows 100%
34 showCursor();
35 std::cout << std::flush; // Flush without printing a new line
36 }
37
38private:
39 void run() {
40 while (!stop_) {
41 display();
42 std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Sleep to reduce CPU usage
43 }
44 }
45
46 void display() {
47 float fraction = static_cast<float>(current_) / total_;
48 int pos = static_cast<int>(barWidth_ * fraction);
49
50 // Output the progress bar (overwrite the existing line)
51 std::cout << "\r["; // Carriage return to start of line
52 for (int i = 0; i < barWidth_; ++i) {
53 if (i < pos) std::cout << "\033[32m=\033[0m"; // Green =
54 else if (i == pos) std::cout << "\033[32m>\033[0m"; // Green >
55 else std::cout << " ";
56 }
57 std::cout << "] " << int(fraction * 100) << " %" << std::flush; // Flush output without a new line
58 }
59
60 void hideCursor() {
61 std::cout << "\033[?25l"; // ANSI escape code to hide the cursor
62 std::cout.flush();
63 }
64
65 void showCursor() {
66 std::cout << "\033[?25h"; // ANSI escape code to show the cursor
67 std::cout.flush();
68 }
69
70 int total_;
71 int barWidth_;
72 std::atomic<int> current_;
73 std::atomic<bool> stop_;
74 std::thread thread_;
75};
Definition: progress.hpp:8