ScriptInstance.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. //
  2. // Copyright (c) 2008-2022 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. /// \file
  23. #pragma once
  24. #include "../AngelScript/ScriptEventListener.h"
  25. #include "../Scene/Component.h"
  26. class asIScriptFunction;
  27. class asIScriptObject;
  28. class asIScriptContext;
  29. class asITypeInfo;
  30. namespace Urho3D
  31. {
  32. class Script;
  33. class ScriptFile;
  34. enum { eAttrMapUserIdx = 0x1df4};
  35. void CleanupTypeInfoScriptInstance(asITypeInfo *type);
  36. /// Inbuilt scripted component methods.
  37. enum ScriptInstanceMethod
  38. {
  39. METHOD_START = 0,
  40. METHOD_STOP,
  41. METHOD_DELAYEDSTART,
  42. METHOD_UPDATE,
  43. METHOD_POSTUPDATE,
  44. METHOD_FIXEDUPDATE,
  45. METHOD_FIXEDPOSTUPDATE,
  46. METHOD_LOAD,
  47. METHOD_SAVE,
  48. METHOD_READNETWORKUPDATE,
  49. METHOD_WRITENETWORKUPDATE,
  50. METHOD_APPLYATTRIBUTES,
  51. METHOD_TRANSFORMCHANGED,
  52. MAX_SCRIPT_METHODS
  53. };
  54. /// %Script object component.
  55. class URHO3D_API ScriptInstance : public Component, public ScriptEventListener
  56. {
  57. URHO3D_OBJECT(ScriptInstance, Component);
  58. public:
  59. /// Construct.
  60. explicit ScriptInstance(Context* context);
  61. /// Destruct.
  62. ~ScriptInstance() override;
  63. /// Register object factory.
  64. /// @nobind
  65. static void RegisterObject(Context* context);
  66. /// Handle attribute write access.
  67. void OnSetAttribute(const AttributeInfo& attr, const Variant& src) override;
  68. /// Handle attribute read access.
  69. void OnGetAttribute(const AttributeInfo& attr, Variant& dest) const override;
  70. /// Return attribute descriptions, or null if none defined.
  71. const Vector<AttributeInfo>* GetAttributes() const override { return &attributeInfos_; }
  72. /// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
  73. void ApplyAttributes() override;
  74. /// Handle enabled/disabled state change.
  75. void OnSetEnabled() override;
  76. /// Add a scripted event handler.
  77. void AddEventHandler(StringHash eventType, const String& handlerName) override;
  78. /// Add a scripted event handler for a specific sender.
  79. void AddEventHandler(Object* sender, StringHash eventType, const String& handlerName) override;
  80. /// Remove a scripted event handler.
  81. void RemoveEventHandler(StringHash eventType) override;
  82. /// Remove a scripted event handler for a specific sender.
  83. void RemoveEventHandler(Object* sender, StringHash eventType) override;
  84. /// Remove all scripted event handlers for a specific sender.
  85. void RemoveEventHandlers(Object* sender) override;
  86. /// Remove all scripted event handlers.
  87. void RemoveEventHandlers() override;
  88. /// Remove all scripted event handlers, except those listed.
  89. void RemoveEventHandlersExcept(const PODVector<StringHash>& exceptions) override;
  90. /// Return whether has subscribed to an event.
  91. bool HasEventHandler(StringHash eventType) const override;
  92. /// Return whether has subscribed to a specific sender's event.
  93. bool HasEventHandler(Object* sender, StringHash eventType) const override;
  94. /// Create object of certain class from the script file. Return true if successful.
  95. bool CreateObject(ScriptFile* scriptFile, const String& className);
  96. /// Set script file only. Recreate object if necessary.
  97. void SetScriptFile(ScriptFile* scriptFile);
  98. /// Set class name only. Recreate object if necessary.
  99. void SetClassName(const String& className);
  100. /// Query for a method by declaration and execute. Log an error if not found.
  101. bool Execute(const String& declaration, const VariantVector& parameters = Variant::emptyVariantVector);
  102. /// Execute a method.
  103. bool Execute(asIScriptFunction* method, const VariantVector& parameters = Variant::emptyVariantVector);
  104. /// Add a delay-executed method call, optionally repeating.
  105. void DelayedExecute
  106. (float delay, bool repeat, const String& declaration, const VariantVector& parameters = Variant::emptyVariantVector);
  107. /// Clear pending delay-executed method calls. If empty declaration given, clears all.
  108. void ClearDelayedExecute(const String& declaration = String::EMPTY);
  109. /// Return script file.
  110. ScriptFile* GetScriptFile() const { return scriptFile_; }
  111. /// Return script object.
  112. asIScriptObject* GetScriptObject() const { return scriptObject_; }
  113. /// Return class name.
  114. const String& GetClassName() const { return className_; }
  115. /// Check if the object is derived from a class.
  116. bool IsA(const String& className) const;
  117. /// Check if has a method.
  118. bool HasMethod(const String& declaration) const;
  119. /// Set script file attribute.
  120. void SetScriptFileAttr(const ResourceRef& value);
  121. /// Set delayed method calls attribute.
  122. void SetDelayedCallsAttr(const PODVector<unsigned char>& value);
  123. /// Set script file serialization attribute by calling a script function.
  124. void SetScriptDataAttr(const PODVector<unsigned char>& data);
  125. /// Set script network serialization attribute by calling a script function.
  126. void SetScriptNetworkDataAttr(const PODVector<unsigned char>& data);
  127. /// Return script file attribute.
  128. ResourceRef GetScriptFileAttr() const;
  129. /// Return delayed method calls attribute.
  130. PODVector<unsigned char> GetDelayedCallsAttr() const;
  131. /// Get script file serialization attribute by calling a script function.
  132. PODVector<unsigned char> GetScriptDataAttr() const;
  133. /// Get script network serialization attribute by calling a script function.
  134. PODVector<unsigned char> GetScriptNetworkDataAttr() const;
  135. protected:
  136. /// Handle scene being assigned.
  137. void OnSceneSet(Scene* scene) override;
  138. /// Handle node transform being dirtied.
  139. void OnMarkedDirty(Node* node) override;
  140. private:
  141. /// (Re)create the script object and check for supported methods if successfully created.
  142. void CreateObject();
  143. /// Release the script object.
  144. void ReleaseObject();
  145. /// Check for supported script methods.
  146. void GetScriptMethods();
  147. /// Check for script attributes.
  148. void GetScriptAttributes();
  149. /// Store values of script attributes for hot reload.
  150. void StoreScriptAttributes();
  151. /// Restore values of script attributes after hot reload is complete.
  152. void RestoreScriptAttributes();
  153. /// Clear supported script methods.
  154. void ClearScriptMethods();
  155. /// Clear attributes to C++ side attributes only.
  156. void ClearScriptAttributes();
  157. /// Subscribe/unsubscribe from scene updates as necessary.
  158. void UpdateEventSubscription();
  159. /// Handle scene update event.
  160. void HandleSceneUpdate(StringHash eventType, VariantMap& eventData);
  161. /// Handle scene post-update event.
  162. void HandleScenePostUpdate(StringHash eventType, VariantMap& eventData);
  163. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  164. /// Handle physics pre-step event.
  165. void HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData);
  166. /// Handle physics post-step event.
  167. void HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData);
  168. #endif
  169. /// Handle an event in script.
  170. void HandleScriptEvent(StringHash eventType, VariantMap& eventData);
  171. /// Handle script file reload start.
  172. void HandleScriptFileReload(StringHash eventType, VariantMap& eventData);
  173. /// Handle script file reload finished.
  174. void HandleScriptFileReloadFinished(StringHash eventType, VariantMap& eventData);
  175. template<typename Op>
  176. void executeScript(asIScriptFunction* method, Op func) const;
  177. /// Script file.
  178. WeakPtr<ScriptFile> scriptFile_;
  179. /// Script object.
  180. asIScriptObject* scriptObject_{};
  181. /// Class name.
  182. String className_;
  183. /// Pointers to supported inbuilt methods.
  184. asIScriptFunction* methods_[MAX_SCRIPT_METHODS]{};
  185. /// Delayed method calls.
  186. Vector<DelayedCall> delayedCalls_;
  187. /// Attributes, including script object variables.
  188. Vector<AttributeInfo> attributeInfos_;
  189. /// Storage for unapplied node and component ID attributes.
  190. HashMap<AttributeInfo*, unsigned> idAttributes_;
  191. /// Storage for attributes while script object is being hot-reloaded.
  192. HashMap<String, Variant> storedAttributes_;
  193. /// Subscribed to scene update events flag.
  194. bool subscribed_{};
  195. /// Subscribed to scene post and fixed update events flag.
  196. bool subscribedPostFixed_{};
  197. };
  198. /// Return the active AngelScript context. Provided as a wrapper to the AngelScript API function to avoid undefined symbol error in shared library Urho3D builds.
  199. URHO3D_API asIScriptContext* GetActiveASContext();
  200. /// Return the Urho3D context of the active AngelScript context.
  201. URHO3D_API Context* GetScriptContext();
  202. /// Return the ScriptInstance of the active AngelScript context.
  203. URHO3D_API ScriptInstance* GetScriptContextInstance();
  204. /// Return the scene node of the active AngelScript context.
  205. URHO3D_API Node* GetScriptContextNode();
  206. /// Return the scene of the active AngelScript context.
  207. URHO3D_API Scene* GetScriptContextScene();
  208. /// Return the event listener of the active AngelScript context.
  209. URHO3D_API ScriptEventListener* GetScriptContextEventListener();
  210. /// Return the event listener of the active AngelScript context as an Object pointer.
  211. URHO3D_API Object* GetScriptContextEventListenerObject();
  212. }