BsScriptObject.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #pragma once
  2. #include "BsScriptEnginePrerequisites.h"
  3. #include "BsScriptMeta.h"
  4. #include "BsMonoField.h"
  5. #include "CmException.h"
  6. #include <mono/jit/jit.h>
  7. namespace BansheeEngine
  8. {
  9. template <class Type>
  10. struct InitScriptObjectOnStart
  11. {
  12. public:
  13. InitScriptObjectOnStart()
  14. {
  15. Type::initMetaData();
  16. }
  17. void makeSureIAmInstantiated() { }
  18. };
  19. /**
  20. * @brief Base class for objects that can be extended using Mono scripting
  21. */
  22. template <class Type>
  23. class ScriptObject
  24. {
  25. public:
  26. ScriptObject()
  27. :mManagedInstance(nullptr)
  28. {
  29. // Compiler will only generate code for stuff that is directly used, including static data members,
  30. // so we fool it here like we're using the class directly. Otherwise compiler won't generate the code for the member
  31. // and our type won't get initialized on start (Actual behavior is a bit more random)
  32. initOnStart.makeSureIAmInstantiated();
  33. }
  34. virtual ~ScriptObject()
  35. {
  36. if(mManagedInstance != nullptr)
  37. CM_EXCEPT(InvalidStateException, "Script object is being destroyed without its instance previously being released.");
  38. }
  39. MonoObject* getManagedInstance() const { return mManagedInstance; }
  40. virtual void* getNativeRaw() const { return nullptr; }
  41. static Type* toNative(MonoObject* managedInstance)
  42. {
  43. Type* nativeInstance = nullptr;
  44. metaData.thisPtrField->getValue(managedInstance, &nativeInstance);
  45. return nativeInstance;
  46. }
  47. protected:
  48. static ScriptMeta metaData;
  49. MonoObject* mManagedInstance;
  50. void createInstance(MonoObject* instance)
  51. {
  52. if(mManagedInstance != nullptr)
  53. CM_EXCEPT(InvalidStateException, "Trying to instantiate an already instantiated script object.");
  54. mManagedInstance = instance;
  55. }
  56. template <class Type2>
  57. static void throwIfInstancesDontMatch(ScriptObject<Type2>* lhs, void* rhs)
  58. {
  59. #if CM_DEBUG_MODE
  60. if((lhs == nullptr && rhs != nullptr) || (rhs == nullptr && lhs != nullptr) || lhs->getNativeRaw() != rhs)
  61. {
  62. CM_EXCEPT(InvalidStateException, "Native and script instance do not match. This usually happens when you modify a native object " \
  63. " that is also being referenced from script code. You should only modify such objects directly from script code.");
  64. }
  65. #endif
  66. }
  67. private:
  68. static InitScriptObjectOnStart<Type> initOnStart;
  69. };
  70. template <typename Type>
  71. InitScriptObjectOnStart<Type> ScriptObject<Type>::initOnStart;
  72. template <typename Type>
  73. ScriptMeta ScriptObject<Type>::metaData;
  74. }