Device.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. /*
  2. Copyright (c) 2013 Daniele Bartolini, Michele Rossi
  3. Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. #include <cstdlib>
  25. #include "Config.h"
  26. #include "Device.h"
  27. #include "Accelerometer.h"
  28. #include "Args.h"
  29. #include "ConsoleServer.h"
  30. #include "DebugRenderer.h"
  31. #include "DiskFile.h"
  32. #include "DiskFilesystem.h"
  33. #include "InputManager.h"
  34. #include "JSONParser.h"
  35. #include "Keyboard.h"
  36. #include "Log.h"
  37. #include "LuaEnvironment.h"
  38. #include "Memory.h"
  39. #include "Mouse.h"
  40. #include "OS.h"
  41. #include "OsWindow.h"
  42. #include "Renderer.h"
  43. #include "ResourceManager.h"
  44. #include "StringSetting.h"
  45. #include "StringUtils.h"
  46. #include "TextReader.h"
  47. #include "Touch.h"
  48. #include "Types.h"
  49. #include "Bundle.h"
  50. #include "TempAllocator.h"
  51. #include "ResourcePackage.h"
  52. #if defined(LINUX) || defined(WINDOWS)
  53. #include "BundleCompiler.h"
  54. #endif
  55. #if defined(ANDROID)
  56. #include "ApkFilesystem.h"
  57. #endif
  58. namespace crown
  59. {
  60. class MainThread : public Thread
  61. {
  62. public:
  63. MainThread()
  64. : Thread("main-thread")
  65. {
  66. }
  67. int32_t run()
  68. {
  69. Device* engine = device();
  70. engine->init();
  71. while (!is_terminating() && engine->is_running())
  72. {
  73. engine->frame();
  74. }
  75. engine->shutdown();
  76. return 0;
  77. }
  78. };
  79. static MainThread g_main_thread;
  80. //-----------------------------------------------------------------------------
  81. Device::Device() :
  82. m_allocator(m_subsystems_heap, MAX_SUBSYSTEMS_HEAP),
  83. m_preferred_window_width(1000),
  84. m_preferred_window_height(625),
  85. m_preferred_window_fullscreen(0),
  86. m_parent_window_handle(0),
  87. m_compile(0),
  88. m_continue(0),
  89. m_quit_after_init(0),
  90. m_is_init(false),
  91. m_is_running(false),
  92. m_is_paused(false),
  93. m_is_really_paused(false),
  94. m_frame_count(0),
  95. m_last_time(0),
  96. m_current_time(0),
  97. m_last_delta_time(0.0f),
  98. m_filesystem(NULL),
  99. m_input_manager(NULL),
  100. m_lua_environment(NULL),
  101. m_renderer(NULL),
  102. m_debug_renderer(NULL),
  103. m_resource_manager(NULL),
  104. m_resource_bundle(NULL),
  105. m_console_server(NULL),
  106. m_renderer_init_request(false)
  107. {
  108. // Bundle dir is current dir by default.
  109. string::strncpy(m_bundle_dir, os::get_cwd(), MAX_PATH_LENGTH);
  110. string::strncpy(m_source_dir, "", MAX_PATH_LENGTH);
  111. string::strncpy(m_boot_file, "lua/game", MAX_PATH_LENGTH);
  112. }
  113. //-----------------------------------------------------------------------------
  114. Device::~Device()
  115. {
  116. }
  117. //-----------------------------------------------------------------------------
  118. bool Device::init(int argc, char** argv)
  119. {
  120. CE_ASSERT(!is_init(), "Engine already initialized");
  121. parse_command_line(argc, argv);
  122. check_preferred_settings();
  123. // Resource compilation only in debug or development mode and only on linux or windows builds
  124. #if (defined(LINUX) || defined(WINDOWS)) && (defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT))
  125. if (m_compile == 1)
  126. {
  127. m_bundle_compiler = CE_NEW(m_allocator, BundleCompiler);
  128. if (!m_bundle_compiler->compile(m_bundle_dir, m_source_dir))
  129. {
  130. CE_DELETE(m_allocator, m_bundle_compiler);
  131. m_allocator.clear();
  132. Log::e("Exiting.");
  133. exit(EXIT_FAILURE);
  134. }
  135. if (!m_continue)
  136. {
  137. CE_DELETE(m_allocator, m_bundle_compiler);
  138. m_allocator.clear();
  139. exit(EXIT_SUCCESS);
  140. }
  141. }
  142. #endif
  143. g_main_thread.start();
  144. // g_main_thread.join();
  145. return true;
  146. }
  147. //-----------------------------------------------------------------------------
  148. void Device::init()
  149. {
  150. // Initialize
  151. Log::i("Initializing Crown Engine %d.%d.%d...", CROWN_VERSION_MAJOR, CROWN_VERSION_MINOR, CROWN_VERSION_MICRO);
  152. // Default bundle filesystem
  153. #if defined (LINUX) || defined(WINDOWS)
  154. m_filesystem = CE_NEW(m_allocator, DiskFilesystem)(m_bundle_dir);
  155. #elif defined(ANDROID)
  156. m_filesystem = CE_NEW(m_allocator, ApkFilesystem)();
  157. #endif
  158. Log::d("Filesystem created.");
  159. // Read settings from crown.config
  160. read_engine_settings();
  161. m_resource_bundle = Bundle::create(m_allocator, *m_filesystem);
  162. // // Read resource seed
  163. // DiskFile* seed_file = (DiskFile*)filesystem()->open(g_default_mountpoint.value(), "seed.ini", FOM_READ);
  164. // TextReader reader(*seed_file);
  165. // char tmp_buf[32];
  166. // reader.read_string(tmp_buf, 32);
  167. // filesystem()->close(seed_file);
  168. // uint32_t seed = string::parse_uint(tmp_buf);
  169. // Create resource manager
  170. m_resource_manager = CE_NEW(m_allocator, ResourceManager)(*m_resource_bundle, 0);
  171. Log::d("Resource manager created.");
  172. Log::d("Resource seed: %d", m_resource_manager->seed());
  173. // Create input manager
  174. m_input_manager = CE_NEW(m_allocator, InputManager)();
  175. Log::d("Input manager created.");
  176. // default_allocator, maybe it needs fix
  177. m_window = CE_NEW(default_allocator(), OsWindow)(m_preferred_window_width, m_preferred_window_height, m_parent_window_handle);
  178. CE_ASSERT(m_window != NULL, "Unable to create the window");
  179. // Create main window
  180. m_window->set_title("Crown Game Engine");
  181. Log::d("Window created.");
  182. // Create renderer
  183. m_renderer = Renderer::create(m_allocator);
  184. m_renderer->init();
  185. m_renderer_init_request = false;
  186. Log::d("Renderer created.");
  187. // Create debug renderer
  188. m_debug_renderer = CE_NEW(m_allocator, DebugRenderer)(*m_renderer);
  189. Log::d("Debug renderer created.");
  190. m_lua_environment = CE_NEW(m_allocator, LuaEnvironment)();
  191. m_lua_environment->init();
  192. Log::d("Lua environment created.");
  193. Log::i("Crown Engine initialized.");
  194. Log::i("Initializing Game...");
  195. m_is_init = true;
  196. start();
  197. // Execute lua boot file
  198. if (m_lua_environment->load_and_execute(m_boot_file))
  199. {
  200. if (!m_lua_environment->call_global("init", 0))
  201. {
  202. pause();
  203. }
  204. }
  205. else
  206. {
  207. pause();
  208. }
  209. // Show main window
  210. m_window->show();
  211. if (m_quit_after_init == 1)
  212. {
  213. stop();
  214. shutdown();
  215. }
  216. }
  217. //-----------------------------------------------------------------------------
  218. void Device::shutdown()
  219. {
  220. CE_ASSERT(is_init(), "Engine is not initialized");
  221. g_main_thread.stop();
  222. // Shutdowns the game
  223. m_lua_environment->call_global("shutdown", 0);
  224. Log::i("Releasing ConsoleServer...");
  225. if (m_console_server)
  226. {
  227. //m_console_server->shutdown();
  228. CE_DELETE(m_allocator, m_console_server);
  229. }
  230. Log::i("Releasing LuaEnvironment...");
  231. if (m_lua_environment)
  232. {
  233. m_lua_environment->shutdown();
  234. CE_DELETE(m_allocator, m_lua_environment);
  235. }
  236. Log::i("Releasing InputManager...");
  237. if (m_input_manager)
  238. {
  239. CE_DELETE(m_allocator, m_input_manager);
  240. }
  241. Log::i("Releasing DebugRenderer...");
  242. if (m_debug_renderer)
  243. {
  244. CE_DELETE(m_allocator, m_debug_renderer);
  245. }
  246. Log::i("Releasing Renderer...");
  247. if (m_renderer)
  248. {
  249. m_renderer->shutdown();
  250. Renderer::destroy(m_allocator, m_renderer);
  251. }
  252. Log::i("Releasing Window...");
  253. if (m_window)
  254. {
  255. CE_DELETE(default_allocator(), m_window);
  256. }
  257. Log::i("Releasing ResourceManager...");
  258. if (m_resource_manager)
  259. {
  260. CE_DELETE(m_allocator, m_resource_manager);
  261. }
  262. if (m_resource_bundle)
  263. {
  264. Bundle::destroy(m_allocator, m_resource_bundle);
  265. }
  266. Log::i("Releasing Filesystem...");
  267. if (m_filesystem)
  268. {
  269. CE_DELETE(m_allocator, m_filesystem);
  270. }
  271. #if (defined(LINUX) || defined(WINDOWS)) && (defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT))
  272. Log::i("Releasing BundleCompiler...");
  273. if (m_bundle_compiler)
  274. {
  275. CE_DELETE(m_allocator, m_bundle_compiler);
  276. }
  277. #endif
  278. m_allocator.clear();
  279. m_is_init = false;
  280. }
  281. //-----------------------------------------------------------------------------
  282. bool Device::is_init() const
  283. {
  284. return m_is_init;
  285. }
  286. //-----------------------------------------------------------------------------
  287. bool Device::is_paused() const
  288. {
  289. return m_is_paused;
  290. }
  291. //-----------------------------------------------------------------------------
  292. Filesystem* Device::filesystem()
  293. {
  294. return m_filesystem;
  295. }
  296. //-----------------------------------------------------------------------------
  297. ResourceManager* Device::resource_manager()
  298. {
  299. return m_resource_manager;
  300. }
  301. //-----------------------------------------------------------------------------
  302. InputManager* Device::input_manager()
  303. {
  304. return m_input_manager;
  305. }
  306. //-----------------------------------------------------------------------------
  307. LuaEnvironment* Device::lua_environment()
  308. {
  309. return m_lua_environment;
  310. }
  311. //-----------------------------------------------------------------------------
  312. OsWindow* Device::window()
  313. {
  314. return m_window;
  315. }
  316. //-----------------------------------------------------------------------------
  317. Renderer* Device::renderer()
  318. {
  319. return m_renderer;
  320. }
  321. //-----------------------------------------------------------------------------
  322. DebugRenderer* Device::debug_renderer()
  323. {
  324. return m_debug_renderer;
  325. }
  326. //-----------------------------------------------------------------------------
  327. Keyboard* Device::keyboard()
  328. {
  329. return m_input_manager->keyboard();
  330. }
  331. //-----------------------------------------------------------------------------
  332. Mouse* Device::mouse()
  333. {
  334. return m_input_manager->mouse();
  335. }
  336. //-----------------------------------------------------------------------------
  337. Touch* Device::touch()
  338. {
  339. return m_input_manager->touch();
  340. }
  341. //-----------------------------------------------------------------------------
  342. Accelerometer* Device::accelerometer()
  343. {
  344. return m_input_manager->accelerometer();
  345. }
  346. ConsoleServer* Device::console_server()
  347. {
  348. return m_console_server;
  349. }
  350. //-----------------------------------------------------------------------------
  351. void Device::start()
  352. {
  353. CE_ASSERT(m_is_init, "Cannot start uninitialized engine.");
  354. m_is_running = true;
  355. m_last_time = os::milliseconds();
  356. }
  357. //-----------------------------------------------------------------------------
  358. void Device::stop()
  359. {
  360. CE_ASSERT(m_is_init, "Cannot stop uninitialized engine.");
  361. m_is_running = false;
  362. }
  363. //-----------------------------------------------------------------------------
  364. void Device::pause()
  365. {
  366. m_is_paused = true;
  367. while (!m_is_really_paused)
  368. {
  369. Log::i("Pausing...");
  370. }
  371. Log::d("Engine paused");
  372. }
  373. //-----------------------------------------------------------------------------
  374. void Device::unpause()
  375. {
  376. m_is_paused = false;
  377. m_is_really_paused = false;
  378. Log::d("Engine unpaused");
  379. }
  380. //-----------------------------------------------------------------------------
  381. bool Device::is_running() const
  382. {
  383. return m_is_running;
  384. }
  385. //-----------------------------------------------------------------------------
  386. uint64_t Device::frame_count() const
  387. {
  388. return m_frame_count;
  389. }
  390. //-----------------------------------------------------------------------------
  391. float Device::last_delta_time() const
  392. {
  393. return m_last_delta_time;
  394. }
  395. //-----------------------------------------------------------------------------
  396. void Device::frame()
  397. {
  398. m_current_time = os::microseconds();
  399. m_last_delta_time = (m_current_time - m_last_time) / 1000000.0f;
  400. m_last_time = m_current_time;
  401. if (m_renderer_init_request)
  402. {
  403. m_renderer->init();
  404. m_renderer_init_request = false;
  405. }
  406. if (!m_is_paused)
  407. {
  408. m_resource_manager->poll_resource_loader();
  409. m_window->frame();
  410. m_input_manager->frame(frame_count());
  411. if (!m_lua_environment->call_global("frame", 1, ARGUMENT_FLOAT, last_delta_time()))
  412. {
  413. pause();
  414. }
  415. m_debug_renderer->draw_all();
  416. m_renderer->frame();
  417. }
  418. if (m_is_paused)
  419. {
  420. m_is_really_paused = true;
  421. }
  422. m_frame_count++;
  423. }
  424. //-----------------------------------------------------------------------------
  425. ResourcePackage* Device::create_resource_package(const char* name)
  426. {
  427. CE_ASSERT_NOT_NULL(name);
  428. ResourceId package_id = m_resource_manager->load("package", name);
  429. m_resource_manager->flush();
  430. PackageResource* package_res = (PackageResource*) m_resource_manager->data(package_id);
  431. ResourcePackage* package = CE_NEW(m_allocator, ResourcePackage)(*m_resource_manager, package_id, package_res);
  432. return package;
  433. }
  434. //-----------------------------------------------------------------------------
  435. void Device::destroy_resource_package(ResourcePackage* package)
  436. {
  437. CE_ASSERT_NOT_NULL(package);
  438. m_resource_manager->unload(package->resource_id());
  439. CE_DELETE(m_allocator, package);
  440. }
  441. //-----------------------------------------------------------------------------
  442. void Device::compile(const char* , const char* , const char* )
  443. {
  444. }
  445. //-----------------------------------------------------------------------------
  446. void Device::reload(ResourceId name)
  447. {
  448. (void)name;
  449. }
  450. //-----------------------------------------------------------------------------
  451. void Device::destroy_window()
  452. {
  453. CE_DELETE(default_allocator(), m_window);
  454. }
  455. //-----------------------------------------------------------------------------
  456. void Device::parse_command_line(int argc, char** argv)
  457. {
  458. static ArgsOption options[] =
  459. {
  460. { "help", AOA_NO_ARGUMENT, NULL, 'i' },
  461. { "source-dir", AOA_REQUIRED_ARGUMENT, NULL, 's' },
  462. { "bundle-dir", AOA_REQUIRED_ARGUMENT, NULL, 'b' },
  463. { "compile", AOA_NO_ARGUMENT, &m_compile, 1 },
  464. { "continue", AOA_NO_ARGUMENT, &m_continue, 1 },
  465. { "width", AOA_REQUIRED_ARGUMENT, NULL, 'w' },
  466. { "height", AOA_REQUIRED_ARGUMENT, NULL, 'h' },
  467. { "fullscreen", AOA_NO_ARGUMENT, &m_preferred_window_fullscreen, 1 },
  468. { "parent-window", AOA_REQUIRED_ARGUMENT, NULL, 'p' },
  469. { "quit-after-init", AOA_NO_ARGUMENT, &m_quit_after_init, 1 },
  470. { NULL, 0, NULL, 0 }
  471. };
  472. Args args(argc, argv, "", options);
  473. int32_t opt;
  474. while ((opt = args.getopt()) != -1)
  475. {
  476. switch (opt)
  477. {
  478. case 0:
  479. {
  480. break;
  481. }
  482. // Source directory
  483. case 's':
  484. {
  485. string::strncpy(m_source_dir, args.optarg(), MAX_PATH_LENGTH);
  486. break;
  487. }
  488. // Bundle directory
  489. case 'b':
  490. {
  491. string::strncpy(m_bundle_dir, args.optarg(), MAX_PATH_LENGTH);
  492. break;
  493. }
  494. // Window width
  495. case 'w':
  496. {
  497. m_preferred_window_width = atoi(args.optarg());
  498. break;
  499. }
  500. // Window height
  501. case 'h':
  502. {
  503. m_preferred_window_height = atoi(args.optarg());
  504. break;
  505. }
  506. // Parent window
  507. case 'p':
  508. {
  509. m_parent_window_handle = string::parse_uint(args.optarg());
  510. break;
  511. }
  512. case 'i':
  513. case '?':
  514. default:
  515. {
  516. print_help_message();
  517. exit(EXIT_FAILURE);
  518. }
  519. }
  520. }
  521. }
  522. //-----------------------------------------------------------------------------
  523. void Device::check_preferred_settings()
  524. {
  525. if (!os::is_absolute_path(m_bundle_dir))
  526. {
  527. Log::e("The root path must be absolute.");
  528. exit(EXIT_FAILURE);
  529. }
  530. if (m_preferred_window_width == 0 || m_preferred_window_height == 0)
  531. {
  532. Log::e("Window width and height must be greater than zero.");
  533. exit(EXIT_FAILURE);
  534. }
  535. }
  536. //-----------------------------------------------------------------------------
  537. void Device::read_engine_settings()
  538. {
  539. // Check crown.config existance
  540. CE_ASSERT(m_filesystem->is_file("crown.config"), "Unable to open crown.config");
  541. // Copy crown config in a buffer
  542. TempAllocator4096 allocator;
  543. File* config_file = m_filesystem->open("crown.config", FOM_READ);
  544. char* json_string = (char*)allocator.allocate(config_file->size());
  545. config_file->read(json_string, config_file->size());
  546. m_filesystem->close(config_file);
  547. // Parse crown.config
  548. JSONParser parser(json_string);
  549. JSONElement root = parser.root();
  550. // Boot
  551. if (root.has_key("boot"))
  552. {
  553. const char* boot = root.key("boot").string_value();
  554. const size_t boot_length = string::strlen(boot) + 1;
  555. string::strncpy(m_boot_file, boot, boot_length);
  556. }
  557. // Window width
  558. if (root.has_key("window_width"))
  559. {
  560. m_preferred_window_width = root.key("window_width").int_value();
  561. }
  562. // Window height
  563. if (root.has_key("window_height"))
  564. {
  565. m_preferred_window_height = root.key("window_height").int_value();
  566. }
  567. allocator.deallocate(json_string);
  568. Log::i("Configuration set");
  569. }
  570. //-----------------------------------------------------------------------------
  571. void Device::print_help_message()
  572. {
  573. os::printf(
  574. "Usage: crown [options]\n"
  575. "Options:\n\n"
  576. "All of the following options take precedence over\n"
  577. "environment variables and configuration files.\n\n"
  578. " --help Show this help.\n"
  579. " --bundle-dir <path> Use <path> as the source directory for compiled resources.\n"
  580. " --width <width> Set the <width> of the main window.\n"
  581. " --height <width> Set the <height> of the main window.\n"
  582. " --fullscreen Start in fullscreen.\n"
  583. " --parent-window <handle> Set the parent window <handle> of the main window.\n"
  584. " Used only by tools.\n"
  585. "\nAvailable only in debug and development builds:\n\n"
  586. " --source-dir <path> Use <path> as the source directory for resource compilation.\n"
  587. " --compile Run the engine as resource compiler.\n"
  588. " --continue Do a full compile of the resources and continue the execution.\n"
  589. " --quit-after-init Quit the engine immediately after the initialization.\n");
  590. }
  591. Device g_device;
  592. Device* device()
  593. {
  594. return &g_device;
  595. }
  596. } // namespace crown