JSVM.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  2. // Please see LICENSE.md in repository root for license information
  3. // https://github.com/AtomicGameEngine/AtomicGameEngine
  4. #include <Duktape/duktape.h>
  5. #include <Atomic/Core/Profiler.h>
  6. #include <Atomic/Core/CoreEvents.h>
  7. #include <Atomic/IO/File.h>
  8. #include <Atomic/IO/Log.h>
  9. #include <Atomic/IO/FileSystem.h>
  10. #include <Atomic/IO/PackageFile.h>
  11. #include <Atomic/Resource/ResourceCache.h>
  12. #include "JSRequire.h"
  13. #include "JSPlugin.h"
  14. #include "JSEvents.h"
  15. #include "JSVM.h"
  16. #include "JSAtomic.h"
  17. #include "JSUI.h"
  18. #include "JSMetrics.h"
  19. namespace Atomic
  20. {
  21. JSVM* JSVM::instance_ = NULL;
  22. JSVM::JSVM(Context* context) :
  23. Object(context),
  24. ctx_(0),
  25. gcTime_(0.0f)
  26. {
  27. assert(!instance_);
  28. instance_ = this;
  29. metrics_ = new JSMetrics(context, this);
  30. }
  31. JSVM::~JSVM()
  32. {
  33. duk_destroy_heap(ctx_);
  34. instance_ = NULL;
  35. }
  36. void JSVM::InitJSContext()
  37. {
  38. ctx_ = duk_create_heap_default();
  39. // create root Atomic Object
  40. duk_push_global_object(ctx_);
  41. duk_push_object(ctx_);
  42. duk_put_prop_string(ctx_, -2, "Atomic");
  43. duk_pop(ctx_);
  44. duk_push_global_stash(ctx_);
  45. duk_push_object(ctx_);
  46. duk_put_prop_index(ctx_, -2, JS_GLOBALSTASH_INDEX_COMPONENTS);
  47. duk_pop(ctx_);
  48. js_init_require(this);
  49. js_init_jsplugin(this);
  50. jsapi_init_atomic(this);
  51. ui_ = new JSUI(context_);
  52. // handle this elsewhere?
  53. SubscribeToEvents();
  54. }
  55. void JSVM::SubscribeToEvents()
  56. {
  57. SubscribeToEvent(E_UPDATE, HANDLER(JSVM, HandleUpdate));
  58. }
  59. void JSVM::HandleUpdate(StringHash eventType, VariantMap& eventData)
  60. {
  61. PROFILE(JSVM_HandleUpdate);
  62. using namespace Update;
  63. // Take the frame time step, which is stored as a float
  64. float timeStep = eventData[P_TIMESTEP].GetFloat();
  65. gcTime_ += timeStep;
  66. if (gcTime_ > 5.0f)
  67. {
  68. PROFILE(JSVM_GC);
  69. // run twice to call finalizers
  70. // see duktape docs
  71. // also ensure #define DUK_OPT_NO_VOLUNTARY_GC
  72. // is enabled in duktape.h
  73. duk_gc(ctx_, 0);
  74. duk_gc(ctx_, 0);
  75. gcTime_ = 0;
  76. }
  77. duk_get_global_string(ctx_, "__js_atomicgame_update");
  78. if (duk_is_function(ctx_, -1))
  79. {
  80. duk_push_number(ctx_, timeStep);
  81. duk_pcall(ctx_, 1);
  82. duk_pop(ctx_);
  83. }
  84. else
  85. {
  86. duk_pop(ctx_);
  87. }
  88. }
  89. bool JSVM::ExecuteFunction(const String& functionName)
  90. {
  91. duk_get_global_string(ctx_, functionName.CString());
  92. if (duk_is_function(ctx_, -1))
  93. {
  94. bool ok = true;
  95. if (duk_pcall(ctx_, 0) != 0)
  96. {
  97. ok = false;
  98. if (duk_is_object(ctx_, -1))
  99. {
  100. SendJSErrorEvent();
  101. }
  102. else
  103. {
  104. assert(0);
  105. }
  106. }
  107. duk_pop(ctx_);
  108. return ok;
  109. }
  110. else
  111. {
  112. duk_pop(ctx_);
  113. }
  114. return false;
  115. }
  116. void JSVM::SendJSErrorEvent(const String& filename)
  117. {
  118. duk_context* ctx = GetJSContext();
  119. using namespace JSError;
  120. VariantMap eventData;
  121. if (duk_is_string(ctx, -1))
  122. {
  123. eventData[P_ERRORNAME] = "(Unknown Error Name)";
  124. eventData[P_ERRORFILENAME] = "(Unknown Filename)";
  125. eventData[P_ERRORLINENUMBER] = -1;
  126. eventData[P_ERRORMESSAGE] = duk_to_string(ctx, -1);
  127. eventData[P_ERRORSTACK] = "";
  128. SendEvent(E_JSERROR, eventData);
  129. return;
  130. }
  131. assert(duk_is_object(ctx, -1));
  132. duk_get_prop_string(ctx, -1, "fileName");
  133. if (duk_is_string(ctx, -1))
  134. {
  135. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  136. }
  137. else
  138. {
  139. eventData[P_ERRORFILENAME] = filename;
  140. }
  141. // Component script are wrapped within a closure, the line number
  142. // needs to be offset by this header
  143. duk_get_prop_string(ctx, -2, "lineNumber");
  144. int lineNumber = (int) (duk_to_number(ctx, -1));
  145. eventData[P_ERRORLINENUMBER] = lineNumber;
  146. duk_get_prop_string(ctx, -3, "name");
  147. String name = duk_to_string(ctx, -1);
  148. eventData[P_ERRORNAME] = name;
  149. duk_get_prop_string(ctx, -4, "message");
  150. String message = duk_to_string(ctx, -1);
  151. eventData[P_ERRORMESSAGE] = message;
  152. // we're not getting good file/line from duktape on parser errors
  153. if (name == "SyntaxError")
  154. {
  155. lineNumber = -1;
  156. // parse line if we have it
  157. if (message.Contains("(line "))
  158. {
  159. if (!filename.Length())
  160. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  161. unsigned pos = message.Find("(line ");
  162. const char* parse = message.CString() + pos + 6;
  163. String number;
  164. while (*parse >= '0' && *parse<='9')
  165. {
  166. number += *parse;
  167. parse++;
  168. }
  169. lineNumber = ToInt(number);
  170. }
  171. eventData[P_ERRORLINENUMBER] = lineNumber;
  172. }
  173. duk_get_prop_string(ctx, -5, "stack");
  174. String stack = duk_to_string(ctx, -1);
  175. eventData[P_ERRORSTACK] = stack;
  176. duk_pop_n(ctx, 5);
  177. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  178. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  179. SendEvent(E_JSERROR, eventData);
  180. }
  181. bool JSVM::ExecuteScript(const String& scriptPath)
  182. {
  183. String path = scriptPath;
  184. if (!path.StartsWith("Scripts/"))
  185. path = "Scripts/" + path;
  186. if (!path.EndsWith(".js"))
  187. path += ".js";
  188. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  189. if (file.Null())
  190. {
  191. return false;
  192. }
  193. String source;
  194. file->ReadText(source);
  195. duk_push_string(ctx_, file->GetFullPath().CString());
  196. if (duk_eval_raw(ctx_, source.CString(), 0,
  197. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  198. {
  199. if (duk_is_object(ctx_, -1))
  200. SendJSErrorEvent(path);
  201. duk_pop(ctx_);
  202. return false;
  203. }
  204. duk_pop(ctx_);
  205. return true;
  206. }
  207. bool JSVM::ExecuteFile(File *file)
  208. {
  209. if (!file)
  210. return false;
  211. String source;
  212. file->ReadText(source);
  213. duk_push_string(ctx_, file->GetFullPath().CString());
  214. if (duk_eval_raw(ctx_, source.CString(), 0,
  215. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  216. {
  217. SendJSErrorEvent(file->GetFullPath());
  218. duk_pop(ctx_);
  219. return false;
  220. }
  221. duk_pop(ctx_);
  222. return true;
  223. }
  224. void JSVM::GC()
  225. {
  226. // run twice to ensure finalizers are run
  227. duk_gc(ctx_, 0);
  228. duk_gc(ctx_, 0);
  229. }
  230. bool JSVM::ExecuteMain()
  231. {
  232. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile("Scripts/main.js"));
  233. if (file.Null())
  234. {
  235. return false;
  236. }
  237. return ExecuteFile(file);
  238. }
  239. }