AtomicPlayer.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Atomic.h"
  23. #include "../Engine/Engine.h"
  24. #include "../IO/FileSystem.h"
  25. #include "../IO/Log.h"
  26. #include "../Core/Main.h"
  27. #include "../Core/ProcessUtils.h"
  28. #include "../Resource/ResourceCache.h"
  29. #include "../Resource/ResourceEvents.h"
  30. // Move me
  31. #include "../Environment/Environment.h"
  32. #include "../Javascript/Javascript.h"
  33. #include "../Javascript/JSFile.h"
  34. #include "AtomicPlayer.h"
  35. #include "../DebugNew.h"
  36. #include "../UI/TBUI.h"
  37. #ifdef EMSCRIPTEN
  38. #include "emscripten.h"
  39. class EmscriptenApp
  40. {
  41. public:
  42. Atomic::SharedPtr<Atomic::Context> context_;
  43. Atomic::SharedPtr<AtomicPlayer> application_;
  44. static EmscriptenApp* sInstance_;
  45. EmscriptenApp() : context_(new Atomic::Context()), application_(new AtomicPlayer(context_))
  46. {
  47. sInstance_ = this;
  48. }
  49. };
  50. EmscriptenApp* EmscriptenApp::sInstance_ = NULL;
  51. static void RunFrame()
  52. {
  53. Engine* engine = EmscriptenApp::sInstance_->application_->GetSubsystem<Engine>();
  54. if (engine->IsInitialized())
  55. engine->RunFrame();
  56. else
  57. printf("ENGINE NOT INITIALIZED\n");
  58. }
  59. int main(int argc, char** argv)
  60. {
  61. Atomic::ParseArguments(argc, argv);
  62. // leak
  63. new EmscriptenApp();
  64. EmscriptenApp::sInstance_->application_->Run();
  65. int firefox = EM_ASM_INT ( return ((navigator.userAgent.toLowerCase().indexOf('firefox') > -1) ? 1 : 0), 0);
  66. if (firefox)
  67. emscripten_set_main_loop(RunFrame, 0, 1);
  68. else
  69. emscripten_set_main_loop(RunFrame, 60, 1);
  70. return 0;
  71. }
  72. #else
  73. DEFINE_APPLICATION_MAIN(AtomicPlayer);
  74. #endif
  75. // fixme
  76. static JSVM* vm = NULL;
  77. static Javascript* javascript = NULL;
  78. AtomicPlayer::AtomicPlayer(Context* context) :
  79. Application(context)
  80. {
  81. RegisterEnvironmenttLibrary(context_);
  82. }
  83. void AtomicPlayer::Setup()
  84. {
  85. FileSystem* filesystem = GetSubsystem<FileSystem>();
  86. // On Android and iOS, read command line from a file as parameters can not otherwise be easily given
  87. #if defined(ANDROID) || defined(IOS)
  88. SharedPtr<File> commandFile(new File(context_, filesystem->GetProgramDir() + "Data/CommandLine.txt",
  89. FILE_READ));
  90. String commandLine = commandFile->ReadLine();
  91. commandFile->Close();
  92. ParseArguments(commandLine, false);
  93. // Reparse engine startup parameters now
  94. engineParameters_ = Engine::ParseParameters(GetArguments());
  95. #endif
  96. // Check for script file name
  97. const Vector<String>& arguments = GetArguments();
  98. for (unsigned i = 0; i < arguments.Size(); ++i)
  99. {
  100. if (arguments[i][0] != '-')
  101. {
  102. scriptFileName_ = GetInternalPath(arguments[i]);
  103. break;
  104. }
  105. }
  106. #ifdef EMSCRIPTEN
  107. engineParameters_["WindowWidth"] = 1280;
  108. engineParameters_["WindowHeight"] = 720;
  109. engineParameters_["FullScreen"] = false;
  110. scriptFileName_ = "PhysicsPlatformer.js";
  111. #else
  112. // TODO: FIX!
  113. #if !defined(ANDROID)
  114. //GetSubsystem<TBUI>()->SetInputDisabled(true);
  115. //GetSubsystem<TBUI>()->FadeOut(.1f);
  116. #else
  117. scriptFileName_ = "PhysicsPlatformer.js";
  118. #endif
  119. #endif
  120. scriptFileName_ = "Script/Main.js";
  121. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  122. engineParameters_["ResourcePaths"] = "AtomicResources";
  123. engineParameters_["WindowTitle"] = "AtomicPlayer";
  124. engineParameters_["FullScreen"] = false;
  125. engineParameters_["WindowWidth"] = 1280;
  126. engineParameters_["WindowHeight"] = 720;
  127. // Show usage if not found
  128. if (scriptFileName_.Empty())
  129. {
  130. ErrorExit("Usage: AtomicPlayer <scriptfile> [options]\n\n"
  131. "The script file should implement the function void Start() for initializing the "
  132. "application and subscribing to all necessary events, such as the frame update.\n"
  133. #ifndef WIN32
  134. "\nCommand line options:\n"
  135. "-x <res> Horizontal resolution\n"
  136. "-y <res> Vertical resolution\n"
  137. "-m <level> Enable hardware multisampling\n"
  138. "-v Enable vertical sync\n"
  139. "-t Enable triple buffering\n"
  140. "-w Start in windowed mode\n"
  141. "-s Enable resizing when in windowed mode\n"
  142. "-q Enable quiet mode which does not log to standard output stream\n"
  143. "-b <length> Sound buffer length in milliseconds\n"
  144. "-r <freq> Sound mixing frequency in Hz\n"
  145. "-p <paths> Resource path(s) to use, separated by semicolons\n"
  146. "-ap <paths> Autoload resource path(s) to use, seperated by semicolons\n"
  147. "-log <level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n"
  148. "-ds <file> Dump used shader variations to a file for precaching\n"
  149. "-mq <level> Material quality level, default 2 (high)\n"
  150. "-tq <level> Texture quality level, default 2 (high)\n"
  151. "-tf <level> Texture filter mode, default 2 (trilinear)\n"
  152. "-af <level> Texture anisotropy level, default 4. Also sets anisotropic filter mode\n"
  153. "-flushgpu Flush GPU command queue each frame. Effective only on Direct3D9\n"
  154. "-borderless Borderless window mode\n"
  155. "-headless Headless mode. No application window will be created\n"
  156. "-landscape Use landscape orientations (iOS only, default)\n"
  157. "-portrait Use portrait orientations (iOS only)\n"
  158. "-prepass Use light pre-pass rendering\n"
  159. "-deferred Use deferred rendering\n"
  160. "-lqshadows Use low-quality (1-sample) shadow filtering\n"
  161. "-noshadows Disable shadow rendering\n"
  162. "-nolimit Disable frame limiter\n"
  163. "-nothreads Disable worker threads\n"
  164. "-nosound Disable sound output\n"
  165. "-noip Disable sound mixing interpolation\n"
  166. "-sm2 Force SM2.0 rendering\n"
  167. "-touch Touch emulation on desktop platform\n"
  168. #endif
  169. );
  170. }
  171. else
  172. {
  173. // Use the script file name as the base name for the log file
  174. engineParameters_["LogName"] = filesystem->GetAppPreferencesDir("urho3d", "logs") + GetFileNameAndExtension(scriptFileName_) + ".log";
  175. }
  176. }
  177. void AtomicPlayer::Start()
  178. {
  179. String extension = GetExtension(scriptFileName_);
  180. if (extension == ".js")
  181. {
  182. // Instantiate and register the Javascript subsystem
  183. javascript = new Javascript(context_);
  184. context_->RegisterSubsystem(javascript);
  185. vm = javascript->InstantiateVM("MainVM");
  186. vm->SetModuleSearchPath("Modules");
  187. duk_eval_string_noresult(vm->GetJSContext(), "require(\"AtomicGame\");");
  188. // Hold a shared pointer to the script file to make sure it is not unloaded during runtime
  189. jsFile_ = GetSubsystem<ResourceCache>()->GetResource<JSFile>(scriptFileName_);
  190. // TODO: Live Reload
  191. // Subscribe to script's reload event to allow live-reload of the application
  192. //SubscribeToEvent(jsFile_, E_RELOADSTARTED, HANDLER(AtomicPlayer, HandleScriptReloadStarted));
  193. //SubscribeToEvent(jsFile_, E_RELOADFINISHED, HANDLER(AtomicPlayer, HandleScriptReloadFinished));
  194. //SubscribeToEvent(jsFile_, E_RELOADFAILED, HANDLER(AtomicPlayer, HandleScriptReloadFailed));
  195. if (jsFile_)
  196. {
  197. bool ok = vm->ExecuteFile(jsFile_);
  198. if (!ok)
  199. {
  200. ErrorExit("Error executing Javascript file");
  201. return;
  202. }
  203. LOGINFOF("Starting %s", scriptFileName_.CString());
  204. vm->ExecuteFunction("Start");
  205. }
  206. else
  207. {
  208. ErrorExit("Error loading Javascript file");
  209. return;
  210. }
  211. return;
  212. //javascript->ShutdownVM("MainVM");
  213. }
  214. // The script was not successfully loaded. Show the last error message and do not run the main loop
  215. ErrorExit();
  216. }
  217. void AtomicPlayer::Stop()
  218. {
  219. context_->RemoveSubsystem<Javascript>();
  220. /*
  221. LuaScript* luaScript = GetSubsystem<LuaScript>();
  222. if (luaScript && luaScript->GetFunction("Stop", true))
  223. luaScript->ExecuteFunction("Stop");
  224. */
  225. }
  226. void AtomicPlayer::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData)
  227. {
  228. }
  229. void AtomicPlayer::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData)
  230. {
  231. }
  232. void AtomicPlayer::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData)
  233. {
  234. ErrorExit();
  235. }