device.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. /*
  2. * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "array.h"
  6. #include "audio.h"
  7. #include "config.h"
  8. #include "console_server.h"
  9. #include "device.h"
  10. #include "disk_filesystem.h"
  11. #include "filesystem.h"
  12. #include "input_device.h"
  13. #include "input_manager.h"
  14. #include "log.h"
  15. #include "lua_environment.h"
  16. #include "map.h"
  17. #include "material_manager.h"
  18. #include "memory.h"
  19. #include "os.h"
  20. #include "path.h"
  21. #include "physics.h"
  22. #include "profiler.h"
  23. #include "proxy_allocator.h"
  24. #include "resource_loader.h"
  25. #include "resource_manager.h"
  26. #include "resource_package.h"
  27. #include "shader_manager.h"
  28. #include "sjson.h"
  29. #include "string_utils.h"
  30. #include "types.h"
  31. #include "unit_manager.h"
  32. #include "vector3.h"
  33. #include "world.h"
  34. #include <bgfx/bgfx.h>
  35. #include <bx/allocator.h>
  36. #if CROWN_PLATFORM_ANDROID
  37. #include "apk_filesystem.h"
  38. #endif // CROWN_PLATFORM_ANDROID
  39. #define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024
  40. namespace crown
  41. {
  42. struct BgfxCallback : public bgfx::CallbackI
  43. {
  44. virtual void fatal(bgfx::Fatal::Enum _code, const char* _str)
  45. {
  46. CE_ASSERT(false, "Fatal error: 0x%08x: %s", _code, _str);
  47. CE_UNUSED(_code);
  48. CE_UNUSED(_str);
  49. }
  50. virtual void traceVargs(const char* /*_filePath*/, uint16_t /*_line*/, const char* _format, va_list _argList)
  51. {
  52. char buf[2048];
  53. strncpy(buf, _format, sizeof(buf));
  54. buf[strlen32(buf)-1] = '\0'; // Remove trailing newline
  55. CE_LOGDV(buf, _argList);
  56. }
  57. virtual uint32_t cacheReadSize(uint64_t /*_id*/)
  58. {
  59. return 0;
  60. }
  61. virtual bool cacheRead(uint64_t /*_id*/, void* /*_data*/, uint32_t /*_size*/)
  62. {
  63. return false;
  64. }
  65. virtual void cacheWrite(uint64_t /*_id*/, const void* /*_data*/, uint32_t /*_size*/)
  66. {
  67. }
  68. virtual void screenShot(const char* /*_filePath*/, uint32_t /*_width*/, uint32_t /*_height*/, uint32_t /*_pitch*/, const void* /*_data*/, uint32_t /*_size*/, bool /*_yflip*/)
  69. {
  70. }
  71. virtual void captureBegin(uint32_t /*_width*/, uint32_t /*_height*/, uint32_t /*_pitch*/, bgfx::TextureFormat::Enum /*_format*/, bool /*_yflip*/)
  72. {
  73. }
  74. virtual void captureEnd()
  75. {
  76. }
  77. virtual void captureFrame(const void* /*_data*/, uint32_t /*_size*/)
  78. {
  79. }
  80. };
  81. struct BgfxAllocator : public bx::AllocatorI
  82. {
  83. BgfxAllocator(Allocator& a)
  84. : _allocator(a, "bgfx")
  85. {
  86. }
  87. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* /*_file*/, uint32_t /*_line*/)
  88. {
  89. if (!_ptr)
  90. return _allocator.allocate((uint32_t)_size, (uint32_t)_align == 0 ? 1 : (uint32_t)_align);
  91. if (_size == 0)
  92. {
  93. _allocator.deallocate(_ptr);
  94. return NULL;
  95. }
  96. // Realloc
  97. void* p = _allocator.allocate((uint32_t)_size, (uint32_t)_align == 0 ? 1 : (uint32_t)_align);
  98. _allocator.deallocate(_ptr);
  99. return p;
  100. }
  101. private:
  102. ProxyAllocator _allocator;
  103. };
  104. Device::Device(const DeviceOptions& opts)
  105. : _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)
  106. , _device_options(opts)
  107. , _bundle_filesystem(NULL)
  108. , _resource_loader(NULL)
  109. , _resource_manager(NULL)
  110. , _bgfx_allocator(NULL)
  111. , _bgfx_callback(NULL)
  112. , _shader_manager(NULL)
  113. , _material_manager(NULL)
  114. , _input_manager(NULL)
  115. , _unit_manager(NULL)
  116. , _lua_environment(NULL)
  117. , _display(NULL)
  118. , _window(NULL)
  119. , _boot_package_id(uint64_t(0))
  120. , _boot_script_id(uint64_t(0))
  121. , _boot_package(NULL)
  122. , _worlds(default_allocator())
  123. , _width(0)
  124. , _height(0)
  125. , _mouse_curr_x(0)
  126. , _mouse_curr_y(0)
  127. , _mouse_last_x(0)
  128. , _mouse_last_y(0)
  129. , _is_init(false)
  130. , _is_running(false)
  131. , _is_paused(false)
  132. , _frame_count(0)
  133. , _last_time(0)
  134. , _current_time(0)
  135. , _last_delta_time(0.0f)
  136. , _time_since_start(0.0)
  137. {
  138. }
  139. void Device::init()
  140. {
  141. // Initialize
  142. CE_LOGI("Initializing Crown Engine %s...", version());
  143. profiler_globals::init();
  144. #if CROWN_PLATFORM_ANDROID
  145. _bundle_filesystem = CE_NEW(_allocator, ApkFilesystem)(const_cast<AAssetManager*>(_device_options.asset_manager()));
  146. #else
  147. _bundle_filesystem = CE_NEW(_allocator, DiskFilesystem)(_device_options.bundle_dir());
  148. #endif // CROWN_PLATFORM_ANDROID
  149. _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem);
  150. _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
  151. read_config();
  152. _bgfx_allocator = CE_NEW(_allocator, BgfxAllocator)(default_allocator());
  153. _bgfx_callback = CE_NEW(_allocator, BgfxCallback)();
  154. _display = Display::create(_allocator);
  155. _window = Window::create(_allocator);
  156. _window->open(_device_options.window_x()
  157. , _device_options.window_y()
  158. , _device_options.window_width()
  159. , _device_options.window_height()
  160. , _device_options.parent_window()
  161. );
  162. _window->bgfx_setup();
  163. bgfx::init(bgfx::RendererType::Count
  164. , BGFX_PCI_ID_NONE
  165. , 0
  166. , _bgfx_callback
  167. , _bgfx_allocator
  168. );
  169. _shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
  170. _material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
  171. _input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
  172. _unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
  173. _lua_environment = CE_NEW(_allocator, LuaEnvironment)();
  174. audio_globals::init();
  175. physics_globals::init();
  176. _boot_package = create_resource_package(_boot_package_id);
  177. _boot_package->load();
  178. _boot_package->flush();
  179. _lua_environment->load_libs();
  180. _lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id));
  181. _lua_environment->call_global("init", 0);
  182. _is_init = true;
  183. _is_running = true;
  184. _last_time = os::clocktime();
  185. CE_LOGD("Engine initialized");
  186. }
  187. void Device::shutdown()
  188. {
  189. CE_ASSERT(_is_init, "Engine is not initialized");
  190. _is_running = false;
  191. _is_init = false;
  192. _lua_environment->call_global("shutdown", 0);
  193. _boot_package->unload();
  194. destroy_resource_package(*_boot_package);
  195. physics_globals::shutdown();
  196. audio_globals::shutdown();
  197. CE_DELETE(_allocator, _lua_environment);
  198. CE_DELETE(_allocator, _unit_manager);
  199. CE_DELETE(_allocator, _input_manager);
  200. CE_DELETE(_allocator, _material_manager);
  201. CE_DELETE(_allocator, _shader_manager);
  202. CE_DELETE(_allocator, _resource_manager);
  203. CE_DELETE(_allocator, _resource_loader);
  204. CE_DELETE(_allocator, _bundle_filesystem);
  205. bgfx::shutdown();
  206. Window::destroy(_allocator, *_window);
  207. Display::destroy(_allocator, *_display);
  208. CE_DELETE(_allocator, _bgfx_callback);
  209. CE_DELETE(_allocator, _bgfx_allocator);
  210. profiler_globals::shutdown();
  211. _allocator.clear();
  212. }
  213. void Device::quit()
  214. {
  215. _is_running = false;
  216. }
  217. void Device::pause()
  218. {
  219. _is_paused = true;
  220. CE_LOGI("Engine paused.");
  221. }
  222. void Device::unpause()
  223. {
  224. _is_paused = false;
  225. CE_LOGI("Engine unpaused.");
  226. }
  227. void Device::resolution(uint16_t& width, uint16_t& height)
  228. {
  229. width = _width;
  230. height = _height;
  231. }
  232. bool Device::is_running() const
  233. {
  234. return _is_running;
  235. }
  236. uint64_t Device::frame_count() const
  237. {
  238. return _frame_count;
  239. }
  240. float Device::last_delta_time() const
  241. {
  242. return _last_delta_time;
  243. }
  244. double Device::time_since_start() const
  245. {
  246. return _time_since_start;
  247. }
  248. void Device::update()
  249. {
  250. while (!process_events() && _is_running)
  251. {
  252. _current_time = os::clocktime();
  253. const int64_t time = _current_time - _last_time;
  254. _last_time = _current_time;
  255. const double freq = (double) os::clockfrequency();
  256. _last_delta_time = float(time * (1.0 / freq));
  257. _time_since_start += _last_delta_time;
  258. profiler_globals::clear();
  259. console_server_globals::update();
  260. RECORD_FLOAT("device.dt", _last_delta_time);
  261. RECORD_FLOAT("device.fps", 1.0f/_last_delta_time);
  262. if (!_is_paused)
  263. {
  264. _resource_manager->complete_requests();
  265. _lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time());
  266. _lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time());
  267. }
  268. _input_manager->update();
  269. const bgfx::Stats* stats = bgfx::getStats();
  270. RECORD_FLOAT("bgfx.gpu_time", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq);
  271. RECORD_FLOAT("bgfx.cpu_time", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq);
  272. bgfx::frame();
  273. profiler_globals::flush();
  274. _lua_environment->reset_temporaries();
  275. _frame_count++;
  276. }
  277. }
  278. void Device::render_world(World& world, CameraInstance camera)
  279. {
  280. world.render(camera);
  281. }
  282. World* Device::create_world()
  283. {
  284. World* w = CE_NEW(default_allocator(), World)(default_allocator()
  285. , *_resource_manager
  286. , *_shader_manager
  287. , *_material_manager
  288. , *_unit_manager
  289. , *_lua_environment
  290. );
  291. array::push_back(_worlds, w);
  292. return w;
  293. }
  294. void Device::destroy_world(World& w)
  295. {
  296. for (uint32_t i = 0, n = array::size(_worlds); i < n; ++i)
  297. {
  298. if (&w == _worlds[i])
  299. {
  300. CE_DELETE(default_allocator(), &w);
  301. _worlds[i] = _worlds[n - 1];
  302. array::pop_back(_worlds);
  303. return;
  304. }
  305. }
  306. CE_ASSERT(false, "Bad world");
  307. }
  308. ResourcePackage* Device::create_resource_package(StringId64 id)
  309. {
  310. return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
  311. }
  312. void Device::destroy_resource_package(ResourcePackage& rp)
  313. {
  314. CE_DELETE(default_allocator(), &rp);
  315. }
  316. void Device::reload(StringId64 type, StringId64 name)
  317. {
  318. const void* old_resource = _resource_manager->get(type, name);
  319. _resource_manager->reload(type, name);
  320. const void* new_resource = _resource_manager->get(type, name);
  321. if (type == SCRIPT_TYPE)
  322. {
  323. _lua_environment->execute((const LuaResource*)new_resource);
  324. }
  325. }
  326. ResourceManager* Device::resource_manager()
  327. {
  328. return _resource_manager;
  329. }
  330. LuaEnvironment* Device::lua_environment()
  331. {
  332. return _lua_environment;
  333. }
  334. InputManager* Device::input_manager()
  335. {
  336. return _input_manager;
  337. }
  338. ShaderManager* Device::shader_manager()
  339. {
  340. return _shader_manager;
  341. }
  342. MaterialManager* Device::material_manager()
  343. {
  344. return _material_manager;
  345. }
  346. UnitManager* Device::unit_manager()
  347. {
  348. return _unit_manager;
  349. }
  350. Display* Device::display()
  351. {
  352. return _display;
  353. }
  354. Window* Device::window()
  355. {
  356. return _window;
  357. }
  358. void Device::read_config()
  359. {
  360. TempAllocator4096 ta;
  361. DynamicString boot_dir(ta);
  362. if (_device_options.boot_dir() != NULL)
  363. {
  364. boot_dir += _device_options.boot_dir();
  365. boot_dir += '/';
  366. }
  367. boot_dir += CROWN_BOOT_CONFIG;
  368. const StringId64 config_name(boot_dir.c_str());
  369. _resource_manager->load(CONFIG_TYPE, config_name);
  370. _resource_manager->flush();
  371. const char* cfile = (const char*)_resource_manager->get(CONFIG_TYPE, config_name);
  372. JsonObject config(ta);
  373. sjson::parse(cfile, config);
  374. _boot_script_id = sjson::parse_resource_id(config["boot_script"]);
  375. _boot_package_id = sjson::parse_resource_id(config["boot_package"]);
  376. _resource_manager->unload(CONFIG_TYPE, config_name);
  377. }
  378. bool Device::process_events()
  379. {
  380. OsEvent event;
  381. bool exit = false;
  382. InputManager* im = _input_manager;
  383. const int16_t dt_x = _mouse_curr_x - _mouse_last_x;
  384. const int16_t dt_y = _mouse_curr_y - _mouse_last_y;
  385. im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f));
  386. _mouse_last_x = _mouse_curr_x;
  387. _mouse_last_y = _mouse_curr_y;
  388. while(next_event(event))
  389. {
  390. if (event.type == OsEvent::NONE) continue;
  391. switch (event.type)
  392. {
  393. case OsEvent::TOUCH:
  394. {
  395. const OsTouchEvent& ev = event.touch;
  396. switch (ev.type)
  397. {
  398. case OsTouchEvent::POINTER:
  399. im->touch()->set_button_state(ev.pointer_id, ev.pressed);
  400. break;
  401. case OsTouchEvent::MOVE:
  402. im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f));
  403. break;
  404. default:
  405. CE_FATAL("Unknown touch event type");
  406. break;
  407. }
  408. break;
  409. }
  410. case OsEvent::MOUSE:
  411. {
  412. const OsMouseEvent& ev = event.mouse;
  413. switch (ev.type)
  414. {
  415. case OsMouseEvent::BUTTON:
  416. im->mouse()->set_button_state(ev.button, ev.pressed);
  417. break;
  418. case OsMouseEvent::MOVE:
  419. _mouse_curr_x = ev.x;
  420. _mouse_curr_y = ev.y;
  421. im->mouse()->set_axis(MouseAxis::CURSOR, vector3(ev.x, ev.y, 0.0f));
  422. break;
  423. case OsMouseEvent::WHEEL:
  424. im->mouse()->set_axis(MouseAxis::WHEEL, vector3(0.0f, ev.wheel, 0.0f));
  425. break;
  426. default:
  427. CE_FATAL("Unknown mouse event type");
  428. break;
  429. }
  430. break;
  431. }
  432. case OsEvent::KEYBOARD:
  433. {
  434. const OsKeyboardEvent& ev = event.keyboard;
  435. im->keyboard()->set_button_state(ev.button, ev.pressed);
  436. break;
  437. }
  438. case OsEvent::JOYPAD:
  439. {
  440. const OsJoypadEvent& ev = event.joypad;
  441. switch (ev.type)
  442. {
  443. case OsJoypadEvent::CONNECTED:
  444. im->joypad(ev.index)->set_connected(ev.connected);
  445. break;
  446. case OsJoypadEvent::BUTTON:
  447. im->joypad(ev.index)->set_button_state(ev.button, ev.pressed);
  448. break;
  449. case OsJoypadEvent::AXIS:
  450. im->joypad(ev.index)->set_axis(ev.button, vector3(ev.x, ev.y, ev.z));
  451. break;
  452. default:
  453. CE_FATAL("Unknown joypad event");
  454. break;
  455. }
  456. break;
  457. }
  458. case OsEvent::METRICS:
  459. {
  460. const OsMetricsEvent& ev = event.metrics;
  461. _width = ev.width;
  462. _height = ev.height;
  463. bgfx::reset(ev.width, ev.height, BGFX_RESET_VSYNC);
  464. break;
  465. }
  466. case OsEvent::EXIT:
  467. {
  468. exit = true;
  469. break;
  470. }
  471. case OsEvent::PAUSE:
  472. {
  473. pause();
  474. break;
  475. }
  476. case OsEvent::RESUME:
  477. {
  478. unpause();
  479. break;
  480. }
  481. default:
  482. {
  483. CE_FATAL("Unknown Os Event");
  484. break;
  485. }
  486. }
  487. }
  488. return exit;
  489. }
  490. char _buffer[sizeof(Device)];
  491. Device* _device = NULL;
  492. void init(const DeviceOptions& opts)
  493. {
  494. CE_ASSERT(_device == NULL, "Crown already initialized");
  495. _device = new (_buffer) Device(opts);
  496. _device->init();
  497. }
  498. void update()
  499. {
  500. _device->update();
  501. }
  502. void shutdown()
  503. {
  504. _device->shutdown();
  505. _device->~Device();
  506. _device = NULL;
  507. }
  508. Device* device()
  509. {
  510. return crown::_device;
  511. }
  512. } // namespace crown