2
0

LoadProgress.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * LoadProgress.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include "StdInc.h"
  12. #include <atomic>
  13. namespace Load
  14. {
  15. using Type = unsigned char;
  16. class ProgressAccumulator;
  17. /*
  18. * Purpose of that class is to track progress of computations
  19. * Derive from this class if you want to translate user or system
  20. * remaining amount of work needed.
  21. * Tracking of the progress should be from another thread.
  22. */
  23. class DLL_LINKAGE Progress
  24. {
  25. public:
  26. //Sets current state to 0.
  27. //Amount of steps to finish progress will be equal to 100 for default constructor
  28. Progress();
  29. Progress(int steps);
  30. virtual ~Progress() = default;
  31. //Returns current state of the progress
  32. //To translate it into percentage (to float, for example):
  33. //float progress = <>.get() / std::numeric_limits<Load::Type>::max();
  34. Type get() const;
  35. //Returns true if current state equal to final state, false otherwise
  36. bool finished() const;
  37. //Sets current state equal to the argument
  38. void set(Type);
  39. //Sets current state to 0
  40. //steps - amount of steps needed to reach final state
  41. void reset(int steps = 100);
  42. //Immediately sets state to final
  43. //finished() will return true after calling this method
  44. void finish();
  45. //Sets amount of steps needed to reach final state
  46. //doesn't modify current state
  47. void setupSteps(int steps);
  48. //Sets amount of steps needed to reach state specified
  49. //doesn't modify current state
  50. void setupStepsTill(int steps, Type state);
  51. //Increases current state by steps count
  52. //if current state reaches final state, returns immediately
  53. void step(int count = 1);
  54. private:
  55. std::atomic<Type> _progress;
  56. std::atomic<Type> _target;
  57. std::atomic<int> _step;
  58. std::atomic<int> _maxSteps;
  59. friend class ProgressAccumulator;
  60. };
  61. class DLL_LINKAGE ProgressAccumulator
  62. {
  63. public:
  64. ProgressAccumulator() = default;
  65. void include(const Progress &);
  66. void exclude(const Progress &);
  67. bool finished() const;
  68. Type get() const;
  69. private:
  70. mutable boost::mutex _mx;
  71. long long _accumulated = 0;
  72. long long _steps = 0;
  73. std::vector<std::reference_wrapper<const Progress>> _progress;
  74. };
  75. }