Script.cpp 8.2 KB

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