Device.cpp 17 KB

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