JSVM.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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 "JSEvents.h"
  13. #include "JSVM.h"
  14. #include "JSAtomic.h"
  15. #include "JSUI.h"
  16. #include "JSMetrics.h"
  17. namespace Atomic
  18. {
  19. JSVM* JSVM::instance_ = NULL;
  20. JSVM::JSVM(Context* context) :
  21. Object(context),
  22. ctx_(0),
  23. gcTime_(0.0f)
  24. {
  25. assert(!instance_);
  26. instance_ = this;
  27. metrics_ = new JSMetrics(context, this);
  28. }
  29. JSVM::~JSVM()
  30. {
  31. duk_destroy_heap(ctx_);
  32. instance_ = NULL;
  33. }
  34. void JSVM::InitJSContext()
  35. {
  36. ctx_ = duk_create_heap_default();
  37. // create root Atomic Object
  38. duk_push_global_object(ctx_);
  39. duk_push_object(ctx_);
  40. duk_put_prop_string(ctx_, -2, "Atomic");
  41. duk_pop(ctx_);
  42. duk_push_global_stash(ctx_);
  43. duk_push_object(ctx_);
  44. duk_put_prop_index(ctx_, -2, JS_GLOBALSTASH_INDEX_COMPONENTS);
  45. duk_pop(ctx_);
  46. duk_get_global_string(ctx_, "Duktape");
  47. duk_push_c_function(ctx_, js_module_search, 1);
  48. duk_put_prop_string(ctx_, -2, "modSearch");
  49. duk_pop(ctx_);
  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. int JSVM::js_module_search(duk_context* ctx)
  237. {
  238. JSVM* vm = GetJSVM(ctx);
  239. FileSystem* fs = vm->GetSubsystem<FileSystem>();
  240. ResourceCache* cache = vm->GetSubsystem<ResourceCache>();
  241. String path = duk_to_string(ctx, 0);
  242. // first check if this is an AtomicModule
  243. // attempting to avoid module search paths
  244. // so have AtomicEditor, Atomic, and the projects "Modules"
  245. String pathName, fileName, extension;
  246. SplitPath(path, pathName, fileName, extension);
  247. if (fileName.StartsWith("AtomicEditor"))
  248. {
  249. path = "AtomicEditor/Modules/" + path + ".js";
  250. }
  251. else if (fileName.StartsWith("Atomic"))
  252. {
  253. path = "AtomicModules/" + path + ".js";
  254. }
  255. else
  256. {
  257. // a module can exist in the Modules path or reside in a project directory
  258. // prefer modules path
  259. String modulePath = vm->moduleSearchPath_ + "/" + path + ".js";
  260. if (fs->FileExists(modulePath))
  261. {
  262. // unless the file doesn't exist and then use project path
  263. path = modulePath;
  264. }
  265. else
  266. {
  267. path += ".js";
  268. }
  269. }
  270. SharedPtr<File> jsfile(cache->GetFile(path));
  271. if (!jsfile)
  272. {
  273. duk_push_null(ctx);
  274. }
  275. else
  276. {
  277. vm->SetLastModuleSearchFile(jsfile->GetFullPath());
  278. String source;
  279. jsfile->ReadText(source);
  280. duk_push_string(ctx, source.CString());
  281. }
  282. return 1;
  283. }
  284. void JSVM::SendJSErrorEvent(const String& filename)
  285. {
  286. duk_context* ctx = GetJSContext();
  287. assert(duk_is_object(ctx, -1));
  288. using namespace JSError;
  289. VariantMap eventData;
  290. duk_get_prop_string(ctx, -1, "fileName");
  291. if (duk_is_string(ctx, -1))
  292. {
  293. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  294. }
  295. else
  296. {
  297. eventData[P_ERRORFILENAME] = filename;
  298. }
  299. // Component script are wrapped within a closure, the line number
  300. // needs to be offset by this header
  301. duk_get_prop_string(ctx, -2, "lineNumber");
  302. int lineNumber = (int) (duk_to_number(ctx, -1));
  303. eventData[P_ERRORLINENUMBER] = lineNumber;
  304. duk_get_prop_string(ctx, -3, "name");
  305. String name = duk_to_string(ctx, -1);
  306. eventData[P_ERRORNAME] = name;
  307. duk_get_prop_string(ctx, -4, "message");
  308. String message = duk_to_string(ctx, -1);
  309. eventData[P_ERRORMESSAGE] = message;
  310. // we're not getting good file/line from duktape on parser errors
  311. if (name == "SyntaxError")
  312. {
  313. lineNumber = -1;
  314. // parse line if we have it
  315. if (message.Contains("(line "))
  316. {
  317. if (!filename.Length())
  318. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  319. unsigned pos = message.Find("(line ");
  320. const char* parse = message.CString() + pos + 6;
  321. String number;
  322. while (*parse >= '0' && *parse<='9')
  323. {
  324. number += *parse;
  325. parse++;
  326. }
  327. lineNumber = ToInt(number);
  328. }
  329. eventData[P_ERRORLINENUMBER] = lineNumber;
  330. }
  331. duk_get_prop_string(ctx, -5, "stack");
  332. String stack = duk_to_string(ctx, -1);
  333. eventData[P_ERRORSTACK] = stack;
  334. duk_pop_n(ctx, 5);
  335. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  336. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  337. SendEvent(E_JSERROR, eventData);
  338. }
  339. bool JSVM::ExecuteScript(const String& scriptPath)
  340. {
  341. String path = scriptPath;
  342. if (!path.StartsWith("Scripts/"))
  343. path = "Scripts/" + path;
  344. if (!path.EndsWith(".js"))
  345. path += ".js";
  346. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  347. if (file.Null())
  348. {
  349. return false;
  350. }
  351. String source;
  352. file->ReadText(source);
  353. duk_push_string(ctx_, file->GetFullPath().CString());
  354. if (duk_eval_raw(ctx_, source.CString(), 0,
  355. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  356. {
  357. if (duk_is_object(ctx_, -1))
  358. SendJSErrorEvent(path);
  359. duk_pop(ctx_);
  360. return false;
  361. }
  362. duk_pop(ctx_);
  363. return true;
  364. }
  365. bool JSVM::ExecuteFile(File *file)
  366. {
  367. if (!file)
  368. return false;
  369. String source;
  370. file->ReadText(source);
  371. duk_push_string(ctx_, file->GetFullPath().CString());
  372. if (duk_eval_raw(ctx_, source.CString(), 0,
  373. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  374. {
  375. if (duk_is_object(ctx_, -1))
  376. SendJSErrorEvent(file->GetFullPath());
  377. duk_pop(ctx_);
  378. return false;
  379. }
  380. duk_pop(ctx_);
  381. return true;
  382. }
  383. bool JSVM::ExecuteMain()
  384. {
  385. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile("Scripts/main.js"));
  386. if (file.Null())
  387. {
  388. return false;
  389. }
  390. String source;
  391. file->ReadText(source);
  392. duk_push_string(ctx_, file->GetFullPath().CString());
  393. if (duk_eval_raw(ctx_, source.CString(), 0,
  394. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  395. {
  396. if (duk_is_object(ctx_, -1))
  397. SendJSErrorEvent(file->GetFullPath());
  398. duk_pop(ctx_);
  399. return false;
  400. }
  401. duk_pop(ctx_);
  402. return true;
  403. }
  404. }