CmModule.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #pragma once
  2. #include "CmPrerequisitesUtil.h"
  3. #include "CmException.h"
  4. namespace CamelotEngine
  5. {
  6. /**
  7. * @brief Represents one engine module. Essentially it is a specialized type of singleton.
  8. */
  9. template <class T> // TODO - Make it thread safe
  10. class Module
  11. {
  12. public:
  13. static T& instance()
  14. {
  15. if(isShutDown)
  16. {
  17. CM_EXCEPT(InternalErrorException,
  18. "Trying to access a module but it hasn't been started up yet.");
  19. }
  20. if(isDestroyed)
  21. {
  22. CM_EXCEPT(InternalErrorException,
  23. "Trying to access a destroyed module.");
  24. }
  25. return *_instance;
  26. }
  27. static T* instancePtr()
  28. {
  29. if(isShutDown)
  30. {
  31. CM_EXCEPT(InternalErrorException,
  32. "Trying to access a module but it hasn't been started up yet.");
  33. }
  34. if(isDestroyed)
  35. {
  36. CM_EXCEPT(InternalErrorException,
  37. "Trying to access a destroyed module.");
  38. }
  39. return _instance;
  40. }
  41. /**
  42. * @brief Initializes the module.
  43. *
  44. * @param [in] moduleInstance Instantiated module. Module takes ownership of instance memory
  45. * and releases it when shutDown is called.
  46. */
  47. static void startUp(T* moduleInstance)
  48. {
  49. if(!isShutDown)
  50. {
  51. CM_EXCEPT(InternalErrorException,
  52. "Trying to start an already started module.");
  53. }
  54. _instance = moduleInstance;
  55. isShutDown = false;
  56. }
  57. /**
  58. * @brief Shuts down this module and frees any resources it is using.
  59. */
  60. static void shutDown()
  61. {
  62. if(isShutDown)
  63. {
  64. CM_EXCEPT(InternalErrorException,
  65. "Trying to shut down an already shut down module.");
  66. }
  67. delete _instance;
  68. isShutDown = true;
  69. }
  70. protected:
  71. Module()
  72. {
  73. }
  74. virtual ~Module()
  75. {
  76. _instance = nullptr;
  77. isDestroyed = true;
  78. }
  79. Module(const Module&) { }
  80. Module& operator=(const Module&) { return *this; }
  81. private:
  82. static T* _instance;
  83. static bool isShutDown;
  84. static bool isDestroyed;
  85. };
  86. template <class T>
  87. T* Module<T>::_instance = nullptr;
  88. template <class T>
  89. bool Module<T>::isShutDown = true;
  90. template <class T>
  91. bool Module<T>::isDestroyed = false;
  92. }