JSVM.cpp 12 KB

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