Script.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. RegisterNetworkAPI(scriptEngine_);
  75. #ifdef URHO3D_PHYSICS
  76. RegisterPhysicsAPI(scriptEngine_);
  77. #endif
  78. #ifdef URHO3D_NAVIGATION
  79. RegisterNavigationAPI(scriptEngine_);
  80. #endif
  81. RegisterUrho2DAPI(scriptEngine_);
  82. RegisterScriptAPI(scriptEngine_);
  83. RegisterEngineAPI(scriptEngine_);
  84. // Subscribe to console commands
  85. SetExecuteConsoleCommands(true);
  86. }
  87. Script::~Script()
  88. {
  89. if (immediateContext_)
  90. {
  91. immediateContext_->Release();
  92. immediateContext_ = 0;
  93. }
  94. for (unsigned i = 0 ; i < scriptFileContexts_.Size(); ++i)
  95. scriptFileContexts_[i]->Release();
  96. if (scriptEngine_)
  97. {
  98. scriptEngine_->Release();
  99. scriptEngine_ = 0;
  100. }
  101. }
  102. bool Script::Execute(const String& line)
  103. {
  104. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  105. PROFILE(ExecuteImmediate);
  106. ClearObjectTypeCache();
  107. String wrappedLine = "void f(){\n" + line + ";\n}";
  108. // If no immediate mode script file set, create a dummy module for compiling the line
  109. asIScriptModule* module = 0;
  110. if (defaultScriptFile_)
  111. module = defaultScriptFile_->GetScriptModule();
  112. if (!module)
  113. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  114. if (!module)
  115. return false;
  116. asIScriptFunction *function = 0;
  117. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  118. return false;
  119. if (immediateContext_->Prepare(function) < 0)
  120. {
  121. function->Release();
  122. return false;
  123. }
  124. bool success = immediateContext_->Execute() >= 0;
  125. immediateContext_->Unprepare();
  126. function->Release();
  127. return success;
  128. }
  129. void Script::SetDefaultScriptFile(ScriptFile* file)
  130. {
  131. defaultScriptFile_ = file;
  132. }
  133. void Script::SetDefaultScene(Scene* scene)
  134. {
  135. defaultScene_ = scene;
  136. }
  137. void Script::SetExecuteConsoleCommands(bool enable)
  138. {
  139. if (enable == executeConsoleCommands_)
  140. return;
  141. executeConsoleCommands_ = enable;
  142. if (enable)
  143. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(Script, HandleConsoleCommand));
  144. else
  145. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  146. }
  147. void Script::MessageCallback(const asSMessageInfo* msg)
  148. {
  149. String message;
  150. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  151. switch (msg->type)
  152. {
  153. case asMSGTYPE_ERROR:
  154. LOGERROR(message);
  155. break;
  156. case asMSGTYPE_WARNING:
  157. LOGWARNING(message);
  158. break;
  159. default:
  160. LOGINFO(message);
  161. break;
  162. }
  163. }
  164. void Script::ExceptionCallback(asIScriptContext* context)
  165. {
  166. String message;
  167. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(), context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  168. asSMessageInfo msg;
  169. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  170. msg.type = asMSGTYPE_ERROR;
  171. msg.message = message.CString();
  172. MessageCallback(&msg);
  173. }
  174. String Script::GetCallStack(asIScriptContext* context)
  175. {
  176. String str("AngelScript callstack:\n");
  177. // Append the call stack
  178. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  179. {
  180. asIScriptFunction* func;
  181. const char* scriptSection;
  182. int line, column;
  183. func = context->GetFunction(i);
  184. line = context->GetLineNumber(i, &column, &scriptSection);
  185. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  186. }
  187. return str;
  188. }
  189. ScriptFile* Script::GetDefaultScriptFile() const
  190. {
  191. return defaultScriptFile_;
  192. }
  193. Scene* Script::GetDefaultScene() const
  194. {
  195. return defaultScene_;
  196. }
  197. void Script::ClearObjectTypeCache()
  198. {
  199. objectTypes_.Clear();
  200. }
  201. asIObjectType* Script::GetObjectType(const char* declaration)
  202. {
  203. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  204. if (i != objectTypes_.End())
  205. return i->second_;
  206. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  207. objectTypes_[declaration] = type;
  208. return type;
  209. }
  210. asIScriptContext* Script::GetScriptFileContext()
  211. {
  212. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  213. {
  214. asIScriptContext* newContext = scriptEngine_->CreateContext();
  215. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  216. scriptFileContexts_.Push(newContext);
  217. }
  218. return scriptFileContexts_[scriptNestingLevel_];
  219. }
  220. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  221. {
  222. using namespace ConsoleCommand;
  223. if (eventData[P_ID].GetString() == GetTypeName())
  224. Execute(eventData[P_COMMAND].GetString());
  225. }
  226. void RegisterScriptLibrary(Context* context)
  227. {
  228. ScriptFile::RegisterObject(context);
  229. ScriptInstance::RegisterObject(context);
  230. }
  231. }