JSVM.cpp 11 KB

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