JSVM.cpp 13 KB

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