device.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. /*
  2. * Copyright (c) 2012-2017 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 "config_resource.h"
  9. #include "console_api.h"
  10. #include "console_server.h"
  11. #include "data_compiler.h"
  12. #include "device.h"
  13. #include "device_event_queue.h"
  14. #include "file.h"
  15. #include "filesystem.h"
  16. #include "filesystem_apk.h"
  17. #include "filesystem_disk.h"
  18. #include "font_resource.h"
  19. #include "input_device.h"
  20. #include "input_manager.h"
  21. #include "json_object.h"
  22. #include "level_resource.h"
  23. #include "log.h"
  24. #include "lua_environment.h"
  25. #include "lua_resource.h"
  26. #include "map.h"
  27. #include "material_manager.h"
  28. #include "material_resource.h"
  29. #include "matrix4x4.h"
  30. #include "memory.h"
  31. #include "mesh_resource.h"
  32. #include "os.h"
  33. #include "package_resource.h"
  34. #include "path.h"
  35. #include "physics.h"
  36. #include "physics_resource.h"
  37. #include "profiler.h"
  38. #include "proxy_allocator.h"
  39. #include "resource_loader.h"
  40. #include "resource_manager.h"
  41. #include "resource_package.h"
  42. #include "shader_manager.h"
  43. #include "shader_resource.h"
  44. #include "sjson.h"
  45. #include "sound_resource.h"
  46. #include "sprite_resource.h"
  47. #include "string_stream.h"
  48. #include "string_utils.h"
  49. #include "temp_allocator.h"
  50. #include "texture_resource.h"
  51. #include "types.h"
  52. #include "unit_manager.h"
  53. #include "unit_resource.h"
  54. #include "vector3.h"
  55. #include "world.h"
  56. #include <bgfx/bgfx.h>
  57. #include <bx/allocator.h>
  58. #define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024
  59. namespace crown
  60. {
  61. extern bool next_event(OsEvent& ev);
  62. struct BgfxCallback : public bgfx::CallbackI
  63. {
  64. virtual void fatal(bgfx::Fatal::Enum _code, const char* _str)
  65. {
  66. CE_ASSERT(false, "Fatal error: 0x%08x: %s", _code, _str);
  67. CE_UNUSED(_code);
  68. CE_UNUSED(_str);
  69. }
  70. virtual void traceVargs(const char* /*_filePath*/, u16 /*_line*/, const char* _format, va_list _argList)
  71. {
  72. char buf[2048];
  73. strncpy(buf, _format, sizeof(buf));
  74. buf[strlen32(buf)-1] = '\0'; // Remove trailing newline
  75. logdv(buf, _argList);
  76. }
  77. virtual u32 cacheReadSize(u64 /*_id*/)
  78. {
  79. return 0;
  80. }
  81. virtual bool cacheRead(u64 /*_id*/, void* /*_data*/, u32 /*_size*/)
  82. {
  83. return false;
  84. }
  85. virtual void cacheWrite(u64 /*_id*/, const void* /*_data*/, u32 /*_size*/)
  86. {
  87. }
  88. virtual void screenShot(const char* /*_filePath*/, u32 /*_width*/, u32 /*_height*/, u32 /*_pitch*/, const void* /*_data*/, u32 /*_size*/, bool /*_yflip*/)
  89. {
  90. }
  91. virtual void captureBegin(u32 /*_width*/, u32 /*_height*/, u32 /*_pitch*/, bgfx::TextureFormat::Enum /*_format*/, bool /*_yflip*/)
  92. {
  93. }
  94. virtual void captureEnd()
  95. {
  96. }
  97. virtual void captureFrame(const void* /*_data*/, u32 /*_size*/)
  98. {
  99. }
  100. };
  101. struct BgfxAllocator : public bx::AllocatorI
  102. {
  103. BgfxAllocator(Allocator& a)
  104. : _allocator(a, "bgfx")
  105. {
  106. }
  107. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* /*_file*/, u32 /*_line*/)
  108. {
  109. if (!_ptr)
  110. return _allocator.allocate((u32)_size, (u32)_align == 0 ? 1 : (u32)_align);
  111. if (_size == 0)
  112. {
  113. _allocator.deallocate(_ptr);
  114. return NULL;
  115. }
  116. // Realloc
  117. void* p = _allocator.allocate((u32)_size, (u32)_align == 0 ? 1 : (u32)_align);
  118. _allocator.deallocate(_ptr);
  119. return p;
  120. }
  121. private:
  122. ProxyAllocator _allocator;
  123. };
  124. Device::Device(const DeviceOptions& opts)
  125. : _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)
  126. , _device_options(opts)
  127. , _boot_config(default_allocator())
  128. , _console_server(NULL)
  129. , _data_compiler(NULL)
  130. , _bundle_filesystem(NULL)
  131. , _last_log(NULL)
  132. , _resource_loader(NULL)
  133. , _resource_manager(NULL)
  134. , _bgfx_allocator(NULL)
  135. , _bgfx_callback(NULL)
  136. , _shader_manager(NULL)
  137. , _material_manager(NULL)
  138. , _input_manager(NULL)
  139. , _unit_manager(NULL)
  140. , _lua_environment(NULL)
  141. , _display(NULL)
  142. , _window(NULL)
  143. , _worlds(default_allocator())
  144. , _width(0)
  145. , _height(0)
  146. , _quit(false)
  147. , _paused(false)
  148. , _frame_count(0)
  149. , _last_delta_time(0.0f)
  150. , _time_since_start(0.0)
  151. {
  152. }
  153. bool Device::process_events(s16& mouse_x, s16& mouse_y, s16& mouse_last_x, s16& mouse_last_y, bool vsync)
  154. {
  155. InputManager* im = _input_manager;
  156. bool exit = false;
  157. bool reset = false;
  158. OsEvent event;
  159. while(next_event(event))
  160. {
  161. if (event.type == OsEventType::NONE)
  162. continue;
  163. switch (event.type)
  164. {
  165. case OsEventType::BUTTON:
  166. {
  167. const ButtonEvent ev = event.button;
  168. switch (ev.device_id)
  169. {
  170. case InputDeviceType::KEYBOARD:
  171. im->keyboard()->set_button_state(ev.button_num, ev.pressed);
  172. break;
  173. case InputDeviceType::MOUSE:
  174. im->mouse()->set_button_state(ev.button_num, ev.pressed);
  175. break;
  176. case InputDeviceType::TOUCHSCREEN:
  177. im->touch()->set_button_state(ev.button_num, ev.pressed);
  178. break;
  179. case InputDeviceType::JOYPAD:
  180. im->joypad(ev.device_num)->set_button_state(ev.button_num, ev.pressed);
  181. break;
  182. }
  183. }
  184. break;
  185. case OsEventType::AXIS:
  186. {
  187. const AxisEvent ev = event.axis;
  188. switch (ev.device_id)
  189. {
  190. case InputDeviceType::MOUSE:
  191. im->mouse()->set_axis(ev.axis_num, vector3(ev.axis_x, ev.axis_y, ev.axis_z));
  192. if (ev.axis_num == MouseAxis::CURSOR)
  193. {
  194. mouse_x = (s16)ev.axis_x;
  195. mouse_y = (s16)ev.axis_y;
  196. }
  197. break;
  198. case InputDeviceType::JOYPAD:
  199. im->joypad(ev.device_num)->set_axis(ev.axis_num, vector3(ev.axis_x, ev.axis_y, ev.axis_z));
  200. break;
  201. }
  202. }
  203. break;
  204. case OsEventType::STATUS:
  205. {
  206. const StatusEvent ev = event.status;
  207. switch (ev.device_id)
  208. {
  209. case InputDeviceType::JOYPAD:
  210. im->joypad(ev.device_num)->set_connected(ev.connected);
  211. break;
  212. }
  213. }
  214. break;
  215. case OsEventType::RESOLUTION:
  216. {
  217. const ResolutionEvent& ev = event.resolution;
  218. _width = ev.width;
  219. _height = ev.height;
  220. reset = true;
  221. }
  222. break;
  223. case OsEventType::EXIT:
  224. exit = true;
  225. break;
  226. case OsEventType::PAUSE:
  227. pause();
  228. break;
  229. case OsEventType::RESUME:
  230. unpause();
  231. break;
  232. default:
  233. CE_FATAL("Unknown OS event");
  234. break;
  235. }
  236. }
  237. const s16 dt_x = mouse_x - mouse_last_x;
  238. const s16 dt_y = mouse_y - mouse_last_y;
  239. im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f));
  240. mouse_last_x = mouse_x;
  241. mouse_last_y = mouse_y;
  242. if (reset)
  243. bgfx::reset(_width, _height, (vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE));
  244. return exit;
  245. }
  246. void Device::run()
  247. {
  248. _console_server = CE_NEW(_allocator, ConsoleServer)(default_allocator());
  249. load_console_api(*_console_server);
  250. namespace cor = config_resource_internal;
  251. namespace ftr = font_resource_internal;
  252. namespace lur = lua_resource_internal;
  253. namespace lvr = level_resource_internal;
  254. namespace mhr = mesh_resource_internal;
  255. namespace mtr = material_resource_internal;
  256. namespace pcr = physics_config_resource_internal;
  257. namespace phr = physics_resource_internal;
  258. namespace pkr = package_resource_internal;
  259. namespace sar = sprite_animation_resource_internal;
  260. namespace sdr = sound_resource_internal;
  261. namespace shr = shader_resource_internal;
  262. namespace spr = sprite_resource_internal;
  263. namespace txr = texture_resource_internal;
  264. namespace utr = unit_resource_internal;
  265. bool do_continue = true;
  266. #if CROWN_PLATFORM_LINUX || CROWN_PLATFORM_WINDOWS
  267. if (_device_options._do_compile || _device_options._server)
  268. {
  269. _data_compiler = CE_NEW(_allocator, DataCompiler)();
  270. _data_compiler->register_compiler(RESOURCE_TYPE_CONFIG, RESOURCE_VERSION_CONFIG, cor::compile);
  271. _data_compiler->register_compiler(RESOURCE_TYPE_FONT, RESOURCE_VERSION_FONT, ftr::compile);
  272. _data_compiler->register_compiler(RESOURCE_TYPE_LEVEL, RESOURCE_VERSION_LEVEL, lvr::compile);
  273. _data_compiler->register_compiler(RESOURCE_TYPE_MATERIAL, RESOURCE_VERSION_MATERIAL, mtr::compile);
  274. _data_compiler->register_compiler(RESOURCE_TYPE_MESH, RESOURCE_VERSION_MESH, mhr::compile);
  275. _data_compiler->register_compiler(RESOURCE_TYPE_PACKAGE, RESOURCE_VERSION_PACKAGE, pkr::compile);
  276. _data_compiler->register_compiler(RESOURCE_TYPE_PHYSICS, RESOURCE_VERSION_PHYSICS, phr::compile);
  277. _data_compiler->register_compiler(RESOURCE_TYPE_PHYSICS_CONFIG, RESOURCE_VERSION_PHYSICS_CONFIG, pcr::compile);
  278. _data_compiler->register_compiler(RESOURCE_TYPE_SCRIPT, RESOURCE_VERSION_SCRIPT, lur::compile);
  279. _data_compiler->register_compiler(RESOURCE_TYPE_SHADER, RESOURCE_VERSION_SHADER, shr::compile);
  280. _data_compiler->register_compiler(RESOURCE_TYPE_SOUND, RESOURCE_VERSION_SOUND, sdr::compile);
  281. _data_compiler->register_compiler(RESOURCE_TYPE_SPRITE, RESOURCE_VERSION_SPRITE, spr::compile);
  282. _data_compiler->register_compiler(RESOURCE_TYPE_SPRITE_ANIMATION, RESOURCE_VERSION_SPRITE_ANIMATION, sar::compile);
  283. _data_compiler->register_compiler(RESOURCE_TYPE_TEXTURE, RESOURCE_VERSION_TEXTURE, txr::compile);
  284. _data_compiler->register_compiler(RESOURCE_TYPE_UNIT, RESOURCE_VERSION_UNIT, utr::compile);
  285. _data_compiler->map_source_dir("", _device_options._source_dir);
  286. if (_device_options._map_source_dir_name)
  287. {
  288. _data_compiler->map_source_dir(_device_options._map_source_dir_name
  289. , _device_options._map_source_dir_prefix
  290. );
  291. }
  292. _data_compiler->scan();
  293. if (_device_options._server)
  294. {
  295. _console_server->listen(CROWN_DEFAULT_COMPILER_PORT, false);
  296. while (true)
  297. {
  298. _console_server->update();
  299. os::sleep(60);
  300. }
  301. }
  302. else
  303. {
  304. const char* data_dir = _device_options._data_dir;
  305. const char* platform = _device_options._platform;
  306. do_continue = _data_compiler->compile(data_dir, platform);
  307. do_continue = do_continue && _device_options._do_continue;
  308. }
  309. }
  310. #endif // CROWN_PLATFORM_LINUX || CROWN_PLATFORM_WINDOWS
  311. if (do_continue)
  312. {
  313. _console_server->listen(_device_options._console_port, _device_options._wait_console);
  314. #if CROWN_PLATFORM_ANDROID
  315. _bundle_filesystem = CE_NEW(_allocator, FilesystemApk)(default_allocator(), const_cast<AAssetManager*>((AAssetManager*)_device_options._asset_manager));
  316. #else
  317. const char* data_dir = _device_options._data_dir;
  318. if (!data_dir)
  319. {
  320. char buf[1024];
  321. data_dir = os::getcwd(buf, sizeof(buf));
  322. }
  323. _bundle_filesystem = CE_NEW(_allocator, FilesystemDisk)(default_allocator());
  324. ((FilesystemDisk*)_bundle_filesystem)->set_prefix(data_dir);
  325. if (!_bundle_filesystem->exists(data_dir))
  326. _bundle_filesystem->create_directory(data_dir);
  327. _last_log = _bundle_filesystem->open(CROWN_LAST_LOG, FileOpenMode::WRITE);
  328. #endif // CROWN_PLATFORM_ANDROID
  329. logi("Initializing Crown Engine %s...", version());
  330. profiler_globals::init();
  331. _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem);
  332. _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
  333. _resource_manager->register_type(RESOURCE_TYPE_SCRIPT, lur::load, lur::unload, NULL, NULL );
  334. _resource_manager->register_type(RESOURCE_TYPE_TEXTURE, txr::load, txr::unload, txr::online, txr::offline);
  335. _resource_manager->register_type(RESOURCE_TYPE_MESH, mhr::load, mhr::unload, mhr::online, mhr::offline);
  336. _resource_manager->register_type(RESOURCE_TYPE_SOUND, sdr::load, sdr::unload, NULL, NULL );
  337. _resource_manager->register_type(RESOURCE_TYPE_UNIT, utr::load, utr::unload, NULL, NULL );
  338. _resource_manager->register_type(RESOURCE_TYPE_SPRITE, spr::load, spr::unload, NULL, NULL );
  339. _resource_manager->register_type(RESOURCE_TYPE_PACKAGE, pkr::load, pkr::unload, NULL, NULL );
  340. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS, phr::load, phr::unload, NULL, NULL );
  341. _resource_manager->register_type(RESOURCE_TYPE_MATERIAL, mtr::load, mtr::unload, mtr::online, mtr::offline);
  342. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS_CONFIG, pcr::load, pcr::unload, NULL, NULL );
  343. _resource_manager->register_type(RESOURCE_TYPE_FONT, ftr::load, ftr::unload, NULL, NULL );
  344. _resource_manager->register_type(RESOURCE_TYPE_LEVEL, lvr::load, lvr::unload, NULL, NULL );
  345. _resource_manager->register_type(RESOURCE_TYPE_SHADER, shr::load, shr::unload, shr::online, shr::offline);
  346. _resource_manager->register_type(RESOURCE_TYPE_SPRITE_ANIMATION, sar::load, sar::unload, NULL, NULL );
  347. _resource_manager->register_type(RESOURCE_TYPE_CONFIG, cor::load, cor::unload, NULL, NULL );
  348. // Read config
  349. {
  350. TempAllocator512 ta;
  351. DynamicString boot_dir(ta);
  352. if (_device_options._boot_dir != NULL)
  353. {
  354. boot_dir += _device_options._boot_dir;
  355. boot_dir += '/';
  356. }
  357. boot_dir += CROWN_BOOT_CONFIG;
  358. const StringId64 config_name(boot_dir.c_str());
  359. _resource_manager->load(RESOURCE_TYPE_CONFIG, config_name);
  360. _resource_manager->flush();
  361. _boot_config.parse((const char*)_resource_manager->get(RESOURCE_TYPE_CONFIG, config_name));
  362. _resource_manager->unload(RESOURCE_TYPE_CONFIG, config_name);
  363. }
  364. // Init all remaining subsystems
  365. _bgfx_allocator = CE_NEW(_allocator, BgfxAllocator)(default_allocator());
  366. _bgfx_callback = CE_NEW(_allocator, BgfxCallback)();
  367. _display = display::create(_allocator);
  368. _window = window::create(_allocator);
  369. _window->open(_device_options._window_x
  370. , _device_options._window_y
  371. , _boot_config.window_w
  372. , _boot_config.window_h
  373. , _device_options._parent_window
  374. );
  375. _window->set_title(_boot_config.window_title.c_str());
  376. _window->set_fullscreen(_boot_config.fullscreen);
  377. _window->bgfx_setup();
  378. bgfx::init(bgfx::RendererType::Count
  379. , BGFX_PCI_ID_NONE
  380. , 0
  381. , _bgfx_callback
  382. , _bgfx_allocator
  383. );
  384. _shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
  385. _material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
  386. _input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
  387. _unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
  388. _lua_environment = CE_NEW(_allocator, LuaEnvironment)();
  389. audio_globals::init();
  390. physics_globals::init(_allocator);
  391. ResourcePackage* boot_package = create_resource_package(_boot_config.boot_package_name);
  392. boot_package->load();
  393. boot_package->flush();
  394. _lua_environment->load_libs();
  395. _lua_environment->execute((LuaResource*)_resource_manager->get(RESOURCE_TYPE_SCRIPT, _boot_config.boot_script_name));
  396. _lua_environment->call_global("init", 0);
  397. logd("Engine initialized");
  398. s16 mouse_x = 0;
  399. s16 mouse_y = 0;
  400. s16 mouse_last_x = 0;
  401. s16 mouse_last_y = 0;
  402. s64 last_time = os::clocktime();
  403. s64 curr_time;
  404. while (!process_events(mouse_x, mouse_y, mouse_last_x, mouse_last_y, _boot_config.vsync) && !_quit)
  405. {
  406. curr_time = os::clocktime();
  407. const s64 time = curr_time - last_time;
  408. last_time = curr_time;
  409. const f64 freq = (f64)os::clockfrequency();
  410. _last_delta_time = f32(time * (1.0 / freq));
  411. _time_since_start += _last_delta_time;
  412. profiler_globals::clear();
  413. _console_server->update();
  414. RECORD_FLOAT("device.dt", _last_delta_time);
  415. RECORD_FLOAT("device.fps", 1.0f/_last_delta_time);
  416. if (!_paused)
  417. {
  418. _resource_manager->complete_requests();
  419. {
  420. const s64 t0 = os::clocktime();
  421. _lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time());
  422. const s64 t1 = os::clocktime();
  423. RECORD_FLOAT("lua.update", f32((t1 - t0)*(1.0 / freq)));
  424. }
  425. {
  426. const s64 t0 = os::clocktime();
  427. _lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time());
  428. const s64 t1 = os::clocktime();
  429. RECORD_FLOAT("lua.render", f32((t1 - t0)*(1.0 / freq)));
  430. }
  431. }
  432. _input_manager->update();
  433. const bgfx::Stats* stats = bgfx::getStats();
  434. RECORD_FLOAT("bgfx.gpu_time", f32(f64(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq));
  435. RECORD_FLOAT("bgfx.cpu_time", f32(f64(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq));
  436. bgfx::frame();
  437. profiler_globals::flush();
  438. _lua_environment->reset_temporaries();
  439. _frame_count++;
  440. }
  441. _lua_environment->call_global("shutdown", 0);
  442. boot_package->unload();
  443. destroy_resource_package(*boot_package);
  444. physics_globals::shutdown(_allocator);
  445. audio_globals::shutdown();
  446. CE_DELETE(_allocator, _lua_environment);
  447. CE_DELETE(_allocator, _unit_manager);
  448. CE_DELETE(_allocator, _input_manager);
  449. CE_DELETE(_allocator, _material_manager);
  450. CE_DELETE(_allocator, _shader_manager);
  451. CE_DELETE(_allocator, _resource_manager);
  452. CE_DELETE(_allocator, _resource_loader);
  453. bgfx::shutdown();
  454. _window->close();
  455. window::destroy(_allocator, *_window);
  456. display::destroy(_allocator, *_display);
  457. CE_DELETE(_allocator, _bgfx_callback);
  458. CE_DELETE(_allocator, _bgfx_allocator);
  459. if (_last_log)
  460. _bundle_filesystem->close(*_last_log);
  461. CE_DELETE(_allocator, _bundle_filesystem);
  462. profiler_globals::shutdown();
  463. }
  464. CE_DELETE(_allocator, _data_compiler);
  465. _console_server->shutdown();
  466. CE_DELETE(_allocator, _console_server);
  467. _allocator.clear();
  468. }
  469. void Device::quit()
  470. {
  471. _quit = true;
  472. }
  473. void Device::pause()
  474. {
  475. _paused = true;
  476. logi("Engine paused.");
  477. }
  478. void Device::unpause()
  479. {
  480. _paused = false;
  481. logi("Engine unpaused.");
  482. }
  483. void Device::resolution(u16& width, u16& height)
  484. {
  485. width = _width;
  486. height = _height;
  487. }
  488. u64 Device::frame_count() const
  489. {
  490. return _frame_count;
  491. }
  492. f32 Device::last_delta_time() const
  493. {
  494. return _last_delta_time;
  495. }
  496. f64 Device::time_since_start() const
  497. {
  498. return _time_since_start;
  499. }
  500. void Device::render(World& world, CameraInstance camera)
  501. {
  502. bgfx::setViewClear(0
  503. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  504. , 0x353839ff
  505. , 1.0f
  506. , 0
  507. );
  508. bgfx::setViewRect(0, 0, 0, _width, _height);
  509. bgfx::setViewRect(1, 0, 0, _width, _height);
  510. bgfx::setViewRect(2, 0, 0, _width, _height);
  511. const Matrix4x4 view = world.camera_view_matrix(camera);
  512. const Matrix4x4 proj = world.camera_projection_matrix(camera);
  513. bgfx::setViewTransform(0, to_float_ptr(view), to_float_ptr(proj));
  514. bgfx::setViewTransform(1, to_float_ptr(view), to_float_ptr(proj));
  515. bgfx::setViewTransform(2, to_float_ptr(MATRIX4X4_IDENTITY), to_float_ptr(MATRIX4X4_IDENTITY));
  516. bgfx::setViewSeq(2, true);
  517. bgfx::touch(0);
  518. bgfx::touch(1);
  519. bgfx::touch(2);
  520. float aspect_ratio = (_boot_config.aspect_ratio == -1.0f
  521. ? (float)_width/(float)_height
  522. : _boot_config.aspect_ratio
  523. );
  524. world.camera_set_aspect(camera, aspect_ratio);
  525. world.camera_set_viewport_metrics(camera, 0, 0, _width, _height);
  526. world.render(view, proj);
  527. }
  528. World* Device::create_world()
  529. {
  530. World* w = CE_NEW(default_allocator(), World)(default_allocator()
  531. , *_resource_manager
  532. , *_shader_manager
  533. , *_material_manager
  534. , *_unit_manager
  535. , *_lua_environment
  536. );
  537. array::push_back(_worlds, w);
  538. return w;
  539. }
  540. void Device::destroy_world(World& w)
  541. {
  542. for (u32 i = 0, n = array::size(_worlds); i < n; ++i)
  543. {
  544. if (&w == _worlds[i])
  545. {
  546. CE_DELETE(default_allocator(), &w);
  547. _worlds[i] = _worlds[n - 1];
  548. array::pop_back(_worlds);
  549. return;
  550. }
  551. }
  552. CE_FATAL("Bad world");
  553. }
  554. ResourcePackage* Device::create_resource_package(StringId64 id)
  555. {
  556. return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
  557. }
  558. void Device::destroy_resource_package(ResourcePackage& rp)
  559. {
  560. CE_DELETE(default_allocator(), &rp);
  561. }
  562. void Device::reload(StringId64 type, StringId64 name)
  563. {
  564. _resource_manager->reload(type, name);
  565. const void* new_resource = _resource_manager->get(type, name);
  566. if (type == RESOURCE_TYPE_SCRIPT)
  567. {
  568. _lua_environment->execute((const LuaResource*)new_resource);
  569. }
  570. }
  571. static StringStream& sanitize(StringStream& ss, const char* msg)
  572. {
  573. using namespace string_stream;
  574. const char* ch = msg;
  575. for (; *ch; ch++)
  576. {
  577. if (*ch == '"' || *ch == '\\')
  578. ss << "\\";
  579. ss << *ch;
  580. }
  581. return ss;
  582. }
  583. static const char* s_severity_map[] = { "info", "warning", "error", "debug" };
  584. CE_STATIC_ASSERT(countof(s_severity_map) == LogSeverity::COUNT);
  585. void Device::log(const char* msg, LogSeverity::Enum severity)
  586. {
  587. if (_last_log)
  588. {
  589. _last_log->write(msg, strlen32(msg));
  590. _last_log->write("\n", 1);
  591. _last_log->flush();
  592. }
  593. if (_console_server)
  594. {
  595. TempAllocator4096 ta;
  596. StringStream json(ta);
  597. json << "{\"type\":\"message\",";
  598. json << "\"severity\":\"" << s_severity_map[severity] << "\",";
  599. json << "\"message\":\""; sanitize(json, msg) << "\"}";
  600. _console_server->send(string_stream::c_str(json));
  601. }
  602. }
  603. ConsoleServer* Device::console_server()
  604. {
  605. return _console_server;
  606. }
  607. DataCompiler* Device::data_compiler()
  608. {
  609. return _data_compiler;
  610. }
  611. ResourceManager* Device::resource_manager()
  612. {
  613. return _resource_manager;
  614. }
  615. LuaEnvironment* Device::lua_environment()
  616. {
  617. return _lua_environment;
  618. }
  619. InputManager* Device::input_manager()
  620. {
  621. return _input_manager;
  622. }
  623. ShaderManager* Device::shader_manager()
  624. {
  625. return _shader_manager;
  626. }
  627. MaterialManager* Device::material_manager()
  628. {
  629. return _material_manager;
  630. }
  631. UnitManager* Device::unit_manager()
  632. {
  633. return _unit_manager;
  634. }
  635. Display* Device::display()
  636. {
  637. return _display;
  638. }
  639. Window* Device::window()
  640. {
  641. return _window;
  642. }
  643. char _buffer[sizeof(Device)];
  644. Device* _device = NULL;
  645. void run(const DeviceOptions& opts)
  646. {
  647. CE_ASSERT(_device == NULL, "Crown already initialized");
  648. _device = new (_buffer) Device(opts);
  649. _device->run();
  650. _device->~Device();
  651. _device = NULL;
  652. }
  653. Device* device()
  654. {
  655. return crown::_device;
  656. }
  657. } // namespace crown