JSVM.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. InitComponents();
  52. ui_ = new JSUI(context_);
  53. // handle this elsewhere?
  54. SubscribeToEvents();
  55. }
  56. void JSVM::SubscribeToEvents()
  57. {
  58. SubscribeToEvent(E_UPDATE, HANDLER(JSVM, HandleUpdate));
  59. }
  60. void JSVM::HandleUpdate(StringHash eventType, VariantMap& eventData)
  61. {
  62. PROFILE(JSVM_HandleUpdate);
  63. using namespace Update;
  64. // Take the frame time step, which is stored as a float
  65. float timeStep = eventData[P_TIMESTEP].GetFloat();
  66. gcTime_ += timeStep;
  67. if (gcTime_ > 5.0f)
  68. {
  69. PROFILE(JSVM_GC);
  70. // run twice to call finalizers
  71. // see duktape docs
  72. // also ensure #define DUK_OPT_NO_VOLUNTARY_GC
  73. // is enabled in duktape.h
  74. duk_gc(ctx_, 0);
  75. duk_gc(ctx_, 0);
  76. gcTime_ = 0;
  77. }
  78. duk_get_global_string(ctx_, "__js_atomicgame_update");
  79. if (duk_is_function(ctx_, -1))
  80. {
  81. duk_push_number(ctx_, timeStep);
  82. duk_pcall(ctx_, 1);
  83. duk_pop(ctx_);
  84. }
  85. else
  86. {
  87. duk_pop(ctx_);
  88. }
  89. }
  90. bool JSVM::ExecuteFunction(const String& functionName)
  91. {
  92. duk_get_global_string(ctx_, functionName.CString());
  93. if (duk_is_function(ctx_, -1))
  94. {
  95. bool ok = true;
  96. if (duk_pcall(ctx_, 0) != 0)
  97. {
  98. ok = false;
  99. if (duk_is_object(ctx_, -1))
  100. {
  101. SendJSErrorEvent();
  102. }
  103. else
  104. {
  105. assert(0);
  106. }
  107. }
  108. duk_pop(ctx_);
  109. return ok;
  110. }
  111. else
  112. {
  113. duk_pop(ctx_);
  114. }
  115. return false;
  116. }
  117. bool JSVM::GenerateComponent(const String &cname, const String &jsfilename, const String& csource)
  118. {
  119. String source = "(function() {var start = null; var update = null; var fixedUpdate = null; var postUpdate = null;\n function __component_function(self) {\n";
  120. source += csource.CString();
  121. source += "self.node.components = self.node.components || {};\n";
  122. source.AppendWithFormat("self.node.components[\"%s\"] = self.node.components[\"%s\"] || [];\n",
  123. cname.CString(), cname.CString());
  124. source += "if (start instanceof Function) self.start = start; " \
  125. "if (update instanceof Function) self.update = update; "\
  126. "if (fixedUpdate instanceof Function) self.fixedUpdate = fixedUpdate; " \
  127. "if (postUpdate instanceof Function) self.postUpdate = postUpdate;\n";
  128. String scriptName = cname;
  129. scriptName[0] = tolower(scriptName[0]);
  130. source.AppendWithFormat("self.node.%s = self.node.%s || self;\n",
  131. scriptName.CString(), scriptName.CString());
  132. source.AppendWithFormat("self.node.components[\"%s\"].push(self);\n",
  133. cname.CString());
  134. source += "}\n return __component_function;\n});";
  135. duk_push_string(ctx_, jsfilename.CString());
  136. if (duk_eval_raw(ctx_, source.CString(), source.Length(),
  137. DUK_COMPILE_EVAL | DUK_COMPILE_NOSOURCE | DUK_COMPILE_SAFE) != 0)
  138. {
  139. if (duk_is_object(ctx_, -1))
  140. {
  141. SendJSErrorEvent(jsfilename);
  142. duk_pop(ctx_);
  143. }
  144. else
  145. {
  146. assert(0);
  147. }
  148. }
  149. else if (duk_pcall(ctx_, 0) != 0)
  150. {
  151. if (duk_is_object(ctx_, -1))
  152. {
  153. SendJSErrorEvent(jsfilename);
  154. duk_pop(ctx_);
  155. }
  156. else
  157. {
  158. assert(0);
  159. }
  160. }
  161. else
  162. {
  163. if (!duk_is_function(ctx_, -1))
  164. {
  165. const char* error = duk_to_string(ctx_, -1);
  166. SendJSErrorEvent();
  167. }
  168. duk_put_prop_string(ctx_, -2, cname.CString());
  169. return true;
  170. }
  171. return false;
  172. }
  173. void JSVM::InitPackageComponents()
  174. {
  175. ResourceCache* cache = GetSubsystem<ResourceCache>();
  176. duk_push_global_stash(ctx_);
  177. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_COMPONENTS);
  178. const Vector<SharedPtr<PackageFile> >& packageFiles = cache->GetPackageFiles();
  179. for (unsigned i = 0; i < packageFiles.Size(); i++)
  180. {
  181. SharedPtr<PackageFile> package = packageFiles[i];
  182. const Vector<String>& files = package->GetCaseEntryNames();
  183. for (unsigned j = 0; j < files.Size(); j++)
  184. {
  185. String name = files[j];
  186. if (!name.StartsWith("Components/"))
  187. continue;
  188. String cname = GetFileName(name);
  189. String jsname = name;
  190. SharedPtr<File> jsfile(cache->GetFile(name));
  191. String csource;
  192. jsfile->ReadText(csource);
  193. if (!GenerateComponent(cname, jsname, csource))
  194. break;
  195. }
  196. }
  197. // pop stash and component object
  198. duk_pop_2(ctx_);
  199. }
  200. void JSVM::InitComponents()
  201. {
  202. ResourceCache* cache = GetSubsystem<ResourceCache>();
  203. // TODO: better way to detect player?
  204. const Vector<SharedPtr<PackageFile> >& packageFiles = cache->GetPackageFiles();
  205. for (unsigned i = 0; i < packageFiles.Size(); i++)
  206. {
  207. String packageName = packageFiles[i]->GetName();
  208. if (packageName.Find("AtomicResources") != String::NPOS)
  209. {
  210. InitPackageComponents();
  211. return;
  212. }
  213. }
  214. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  215. const Vector<String>& dirs = cache->GetResourceDirs();
  216. duk_push_global_stash(ctx_);
  217. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_COMPONENTS);
  218. for (unsigned i = 0; i < dirs.Size(); i++)
  219. {
  220. Vector<String> files;
  221. fileSystem->ScanDir(files ,dirs[i]+"/Components", "*.js", SCAN_FILES, true );
  222. for (unsigned j = 0; j < files.Size(); j++)
  223. {
  224. String cname = GetFileName(files[j]);
  225. String jsname = dirs[i]+"Components/" + files[j];
  226. SharedPtr<File> jsfile = cache->GetFile("Components/" + files[j]);
  227. String csource;
  228. jsfile->ReadText(csource);
  229. if (!GenerateComponent(cname, jsname, csource))
  230. break;
  231. }
  232. }
  233. // pop stash and component object
  234. duk_pop_2(ctx_);
  235. }
  236. void JSVM::SendJSErrorEvent(const String& filename)
  237. {
  238. duk_context* ctx = GetJSContext();
  239. using namespace JSError;
  240. VariantMap eventData;
  241. if (duk_is_string(ctx, -1))
  242. {
  243. eventData[P_ERRORNAME] = "(Unknown Error Name)";
  244. eventData[P_ERRORFILENAME] = "(Unknown Filename)";
  245. eventData[P_ERRORLINENUMBER] = -1;
  246. eventData[P_ERRORMESSAGE] = duk_to_string(ctx, -1);
  247. eventData[P_ERRORSTACK] = "";
  248. SendEvent(E_JSERROR, eventData);
  249. return;
  250. }
  251. assert(duk_is_object(ctx, -1));
  252. duk_get_prop_string(ctx, -1, "fileName");
  253. if (duk_is_string(ctx, -1))
  254. {
  255. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  256. }
  257. else
  258. {
  259. eventData[P_ERRORFILENAME] = filename;
  260. }
  261. // Component script are wrapped within a closure, the line number
  262. // needs to be offset by this header
  263. duk_get_prop_string(ctx, -2, "lineNumber");
  264. int lineNumber = (int) (duk_to_number(ctx, -1));
  265. eventData[P_ERRORLINENUMBER] = lineNumber;
  266. duk_get_prop_string(ctx, -3, "name");
  267. String name = duk_to_string(ctx, -1);
  268. eventData[P_ERRORNAME] = name;
  269. duk_get_prop_string(ctx, -4, "message");
  270. String message = duk_to_string(ctx, -1);
  271. eventData[P_ERRORMESSAGE] = message;
  272. // we're not getting good file/line from duktape on parser errors
  273. if (name == "SyntaxError")
  274. {
  275. lineNumber = -1;
  276. // parse line if we have it
  277. if (message.Contains("(line "))
  278. {
  279. if (!filename.Length())
  280. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  281. unsigned pos = message.Find("(line ");
  282. const char* parse = message.CString() + pos + 6;
  283. String number;
  284. while (*parse >= '0' && *parse<='9')
  285. {
  286. number += *parse;
  287. parse++;
  288. }
  289. lineNumber = ToInt(number);
  290. }
  291. eventData[P_ERRORLINENUMBER] = lineNumber;
  292. }
  293. duk_get_prop_string(ctx, -5, "stack");
  294. String stack = duk_to_string(ctx, -1);
  295. eventData[P_ERRORSTACK] = stack;
  296. duk_pop_n(ctx, 5);
  297. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  298. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  299. SendEvent(E_JSERROR, eventData);
  300. }
  301. bool JSVM::ExecuteScript(const String& scriptPath)
  302. {
  303. String path = scriptPath;
  304. if (!path.StartsWith("Scripts/"))
  305. path = "Scripts/" + path;
  306. if (!path.EndsWith(".js"))
  307. path += ".js";
  308. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  309. if (file.Null())
  310. {
  311. return false;
  312. }
  313. String source;
  314. file->ReadText(source);
  315. duk_push_string(ctx_, file->GetFullPath().CString());
  316. if (duk_eval_raw(ctx_, source.CString(), 0,
  317. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  318. {
  319. if (duk_is_object(ctx_, -1))
  320. SendJSErrorEvent(path);
  321. duk_pop(ctx_);
  322. return false;
  323. }
  324. duk_pop(ctx_);
  325. return true;
  326. }
  327. bool JSVM::ExecuteFile(File *file)
  328. {
  329. if (!file)
  330. return false;
  331. String source;
  332. file->ReadText(source);
  333. duk_push_string(ctx_, file->GetFullPath().CString());
  334. if (duk_eval_raw(ctx_, source.CString(), 0,
  335. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  336. {
  337. if (duk_is_object(ctx_, -1))
  338. SendJSErrorEvent(file->GetFullPath());
  339. duk_pop(ctx_);
  340. return false;
  341. }
  342. duk_pop(ctx_);
  343. return true;
  344. }
  345. void JSVM::GC()
  346. {
  347. // run twice to ensure finalizers are run
  348. duk_gc(ctx_, 0);
  349. duk_gc(ctx_, 0);
  350. }
  351. bool JSVM::ExecuteMain()
  352. {
  353. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile("Scripts/main.js"));
  354. if (file.Null())
  355. {
  356. return false;
  357. }
  358. String source;
  359. file->ReadText(source);
  360. duk_push_string(ctx_, file->GetFullPath().CString());
  361. if (duk_eval_raw(ctx_, source.CString(), 0,
  362. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  363. {
  364. if (duk_is_object(ctx_, -1))
  365. SendJSErrorEvent(file->GetFullPath());
  366. duk_pop(ctx_);
  367. return false;
  368. }
  369. duk_pop(ctx_);
  370. return true;
  371. }
  372. }