Script.cpp 8.0 KB

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