Script.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. //
  2. // Copyright (c) 2008-2014 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. #include "Precompiled.h"
  23. #include "Addons.h"
  24. #include "EngineEvents.h"
  25. #include "Log.h"
  26. #include "Profiler.h"
  27. #include "Scene.h"
  28. #include "Script.h"
  29. #include "ScriptAPI.h"
  30. #include "ScriptFile.h"
  31. #include "ScriptInstance.h"
  32. #include <angelscript.h>
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. Script::Script(Context* context) :
  37. Object(context),
  38. scriptEngine_(0),
  39. immediateContext_(0),
  40. scriptNestingLevel_(0),
  41. executeConsoleCommands_(false)
  42. {
  43. scriptEngine_ = asCreateScriptEngine(ANGELSCRIPT_VERSION);
  44. if (!scriptEngine_)
  45. {
  46. LOGERROR("Could not create AngelScript engine");
  47. return;
  48. }
  49. scriptEngine_->SetUserData(this);
  50. scriptEngine_->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, true);
  51. scriptEngine_->SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, true);
  52. scriptEngine_->SetEngineProperty(asEP_ALLOW_IMPLICIT_HANDLE_TYPES, true);
  53. scriptEngine_->SetEngineProperty(asEP_BUILD_WITHOUT_LINE_CUES, true);
  54. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  55. // Create the context for immediate execution
  56. immediateContext_ = scriptEngine_->CreateContext();
  57. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  58. // Register Script library object factories
  59. RegisterScriptLibrary(context_);
  60. // Register the Array, String & Dictionary API
  61. RegisterArray(scriptEngine_);
  62. RegisterString(scriptEngine_);
  63. RegisterDictionary(scriptEngine_);
  64. // Register the rest of the script API
  65. RegisterMathAPI(scriptEngine_);
  66. RegisterCoreAPI(scriptEngine_);
  67. RegisterIOAPI(scriptEngine_);
  68. RegisterResourceAPI(scriptEngine_);
  69. RegisterSceneAPI(scriptEngine_);
  70. RegisterGraphicsAPI(scriptEngine_);
  71. RegisterInputAPI(scriptEngine_);
  72. RegisterAudioAPI(scriptEngine_);
  73. RegisterUIAPI(scriptEngine_);
  74. #ifdef URHO3D_NETWORK
  75. RegisterNetworkAPI(scriptEngine_);
  76. #endif
  77. #ifdef URHO3D_PHYSICS
  78. RegisterPhysicsAPI(scriptEngine_);
  79. #endif
  80. #ifdef URHO3D_NAVIGATION
  81. RegisterNavigationAPI(scriptEngine_);
  82. #endif
  83. #ifdef URHO3D_URHO2D
  84. RegisterUrho2DAPI(scriptEngine_);
  85. #endif
  86. RegisterScriptAPI(scriptEngine_);
  87. RegisterEngineAPI(scriptEngine_);
  88. // Subscribe to console commands
  89. SetExecuteConsoleCommands(true);
  90. }
  91. Script::~Script()
  92. {
  93. if (immediateContext_)
  94. {
  95. immediateContext_->Release();
  96. immediateContext_ = 0;
  97. }
  98. for (unsigned i = 0 ; i < scriptFileContexts_.Size(); ++i)
  99. scriptFileContexts_[i]->Release();
  100. if (scriptEngine_)
  101. {
  102. scriptEngine_->Release();
  103. scriptEngine_ = 0;
  104. }
  105. }
  106. bool Script::Execute(const String& line)
  107. {
  108. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  109. PROFILE(ExecuteImmediate);
  110. ClearObjectTypeCache();
  111. String wrappedLine = "void f(){\n" + line + ";\n}";
  112. // If no immediate mode script file set, create a dummy module for compiling the line
  113. asIScriptModule* module = 0;
  114. if (defaultScriptFile_)
  115. module = defaultScriptFile_->GetScriptModule();
  116. if (!module)
  117. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  118. if (!module)
  119. return false;
  120. asIScriptFunction *function = 0;
  121. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  122. return false;
  123. if (immediateContext_->Prepare(function) < 0)
  124. {
  125. function->Release();
  126. return false;
  127. }
  128. bool success = immediateContext_->Execute() >= 0;
  129. immediateContext_->Unprepare();
  130. function->Release();
  131. return success;
  132. }
  133. void Script::SetDefaultScriptFile(ScriptFile* file)
  134. {
  135. defaultScriptFile_ = file;
  136. }
  137. void Script::SetDefaultScene(Scene* scene)
  138. {
  139. defaultScene_ = scene;
  140. }
  141. void Script::SetExecuteConsoleCommands(bool enable)
  142. {
  143. if (enable == executeConsoleCommands_)
  144. return;
  145. executeConsoleCommands_ = enable;
  146. if (enable)
  147. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(Script, HandleConsoleCommand));
  148. else
  149. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  150. }
  151. void Script::MessageCallback(const asSMessageInfo* msg)
  152. {
  153. String message;
  154. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  155. switch (msg->type)
  156. {
  157. case asMSGTYPE_ERROR:
  158. LOGERROR(message);
  159. break;
  160. case asMSGTYPE_WARNING:
  161. LOGWARNING(message);
  162. break;
  163. default:
  164. LOGINFO(message);
  165. break;
  166. }
  167. }
  168. void Script::ExceptionCallback(asIScriptContext* context)
  169. {
  170. String message;
  171. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(), context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  172. asSMessageInfo msg;
  173. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  174. msg.type = asMSGTYPE_ERROR;
  175. msg.message = message.CString();
  176. MessageCallback(&msg);
  177. }
  178. String Script::GetCallStack(asIScriptContext* context)
  179. {
  180. String str("AngelScript callstack:\n");
  181. // Append the call stack
  182. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  183. {
  184. asIScriptFunction* func;
  185. const char* scriptSection;
  186. int line, column;
  187. func = context->GetFunction(i);
  188. line = context->GetLineNumber(i, &column, &scriptSection);
  189. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  190. }
  191. return str;
  192. }
  193. ScriptFile* Script::GetDefaultScriptFile() const
  194. {
  195. return defaultScriptFile_;
  196. }
  197. Scene* Script::GetDefaultScene() const
  198. {
  199. return defaultScene_;
  200. }
  201. void Script::ClearObjectTypeCache()
  202. {
  203. objectTypes_.Clear();
  204. }
  205. asIObjectType* Script::GetObjectType(const char* declaration)
  206. {
  207. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  208. if (i != objectTypes_.End())
  209. return i->second_;
  210. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  211. objectTypes_[declaration] = type;
  212. return type;
  213. }
  214. asIScriptContext* Script::GetScriptFileContext()
  215. {
  216. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  217. {
  218. asIScriptContext* newContext = scriptEngine_->CreateContext();
  219. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  220. scriptFileContexts_.Push(newContext);
  221. }
  222. return scriptFileContexts_[scriptNestingLevel_];
  223. }
  224. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  225. {
  226. using namespace ConsoleCommand;
  227. if (eventData[P_ID].GetString() == GetTypeName())
  228. Execute(eventData[P_COMMAND].GetString());
  229. }
  230. void RegisterScriptLibrary(Context* context)
  231. {
  232. ScriptFile::RegisterObject(context);
  233. ScriptInstance::RegisterObject(context);
  234. }
  235. }