device.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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. logiv(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. _console_server->listen(_device_options._server ? CROWN_DEFAULT_COMPILER_PORT : _device_options._console_port, _device_options._wait_console);
  251. namespace cor = config_resource_internal;
  252. namespace ftr = font_resource_internal;
  253. namespace lur = lua_resource_internal;
  254. namespace lvr = level_resource_internal;
  255. namespace mhr = mesh_resource_internal;
  256. namespace mtr = material_resource_internal;
  257. namespace pcr = physics_config_resource_internal;
  258. namespace phr = physics_resource_internal;
  259. namespace pkr = package_resource_internal;
  260. namespace sar = sprite_animation_resource_internal;
  261. namespace sdr = sound_resource_internal;
  262. namespace shr = shader_resource_internal;
  263. namespace spr = sprite_resource_internal;
  264. namespace txr = texture_resource_internal;
  265. namespace utr = unit_resource_internal;
  266. bool do_continue = true;
  267. #if CROWN_PLATFORM_LINUX || CROWN_PLATFORM_WINDOWS
  268. if (_device_options._do_compile || _device_options._server)
  269. {
  270. _data_compiler = CE_NEW(_allocator, DataCompiler)(*_console_server);
  271. _data_compiler->register_compiler(RESOURCE_TYPE_CONFIG, RESOURCE_VERSION_CONFIG, cor::compile);
  272. _data_compiler->register_compiler(RESOURCE_TYPE_FONT, RESOURCE_VERSION_FONT, ftr::compile);
  273. _data_compiler->register_compiler(RESOURCE_TYPE_LEVEL, RESOURCE_VERSION_LEVEL, lvr::compile);
  274. _data_compiler->register_compiler(RESOURCE_TYPE_MATERIAL, RESOURCE_VERSION_MATERIAL, mtr::compile);
  275. _data_compiler->register_compiler(RESOURCE_TYPE_MESH, RESOURCE_VERSION_MESH, mhr::compile);
  276. _data_compiler->register_compiler(RESOURCE_TYPE_PACKAGE, RESOURCE_VERSION_PACKAGE, pkr::compile);
  277. _data_compiler->register_compiler(RESOURCE_TYPE_PHYSICS, RESOURCE_VERSION_PHYSICS, phr::compile);
  278. _data_compiler->register_compiler(RESOURCE_TYPE_PHYSICS_CONFIG, RESOURCE_VERSION_PHYSICS_CONFIG, pcr::compile);
  279. _data_compiler->register_compiler(RESOURCE_TYPE_SCRIPT, RESOURCE_VERSION_SCRIPT, lur::compile);
  280. _data_compiler->register_compiler(RESOURCE_TYPE_SHADER, RESOURCE_VERSION_SHADER, shr::compile);
  281. _data_compiler->register_compiler(RESOURCE_TYPE_SOUND, RESOURCE_VERSION_SOUND, sdr::compile);
  282. _data_compiler->register_compiler(RESOURCE_TYPE_SPRITE, RESOURCE_VERSION_SPRITE, spr::compile);
  283. _data_compiler->register_compiler(RESOURCE_TYPE_SPRITE_ANIMATION, RESOURCE_VERSION_SPRITE_ANIMATION, sar::compile);
  284. _data_compiler->register_compiler(RESOURCE_TYPE_TEXTURE, RESOURCE_VERSION_TEXTURE, txr::compile);
  285. _data_compiler->register_compiler(RESOURCE_TYPE_UNIT, RESOURCE_VERSION_UNIT, utr::compile);
  286. _data_compiler->map_source_dir("", _device_options._source_dir);
  287. if (_device_options._map_source_dir_name)
  288. {
  289. _data_compiler->map_source_dir(_device_options._map_source_dir_name
  290. , _device_options._map_source_dir_prefix
  291. );
  292. }
  293. _data_compiler->scan();
  294. if (_device_options._server)
  295. {
  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. #if CROWN_PLATFORM_ANDROID
  314. _bundle_filesystem = CE_NEW(_allocator, FilesystemApk)(default_allocator(), const_cast<AAssetManager*>((AAssetManager*)_device_options._asset_manager));
  315. #else
  316. const char* data_dir = _device_options._data_dir;
  317. if (!data_dir)
  318. {
  319. char buf[1024];
  320. data_dir = os::getcwd(buf, sizeof(buf));
  321. }
  322. _bundle_filesystem = CE_NEW(_allocator, FilesystemDisk)(default_allocator());
  323. ((FilesystemDisk*)_bundle_filesystem)->set_prefix(data_dir);
  324. if (!_bundle_filesystem->exists(data_dir))
  325. _bundle_filesystem->create_directory(data_dir);
  326. _last_log = _bundle_filesystem->open(CROWN_LAST_LOG, FileOpenMode::WRITE);
  327. #endif // CROWN_PLATFORM_ANDROID
  328. logi("Initializing Crown Engine %s...", version());
  329. profiler_globals::init();
  330. _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem);
  331. _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
  332. _resource_manager->register_type(RESOURCE_TYPE_SCRIPT, lur::load, lur::unload, NULL, NULL );
  333. _resource_manager->register_type(RESOURCE_TYPE_TEXTURE, txr::load, txr::unload, txr::online, txr::offline);
  334. _resource_manager->register_type(RESOURCE_TYPE_MESH, mhr::load, mhr::unload, mhr::online, mhr::offline);
  335. _resource_manager->register_type(RESOURCE_TYPE_SOUND, sdr::load, sdr::unload, NULL, NULL );
  336. _resource_manager->register_type(RESOURCE_TYPE_UNIT, utr::load, utr::unload, NULL, NULL );
  337. _resource_manager->register_type(RESOURCE_TYPE_SPRITE, spr::load, spr::unload, NULL, NULL );
  338. _resource_manager->register_type(RESOURCE_TYPE_PACKAGE, pkr::load, pkr::unload, NULL, NULL );
  339. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS, phr::load, phr::unload, NULL, NULL );
  340. _resource_manager->register_type(RESOURCE_TYPE_MATERIAL, mtr::load, mtr::unload, mtr::online, mtr::offline);
  341. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS_CONFIG, pcr::load, pcr::unload, NULL, NULL );
  342. _resource_manager->register_type(RESOURCE_TYPE_FONT, ftr::load, ftr::unload, NULL, NULL );
  343. _resource_manager->register_type(RESOURCE_TYPE_LEVEL, lvr::load, lvr::unload, NULL, NULL );
  344. _resource_manager->register_type(RESOURCE_TYPE_SHADER, shr::load, shr::unload, shr::online, shr::offline);
  345. _resource_manager->register_type(RESOURCE_TYPE_SPRITE_ANIMATION, sar::load, sar::unload, NULL, NULL );
  346. _resource_manager->register_type(RESOURCE_TYPE_CONFIG, cor::load, cor::unload, NULL, NULL );
  347. // Read config
  348. {
  349. TempAllocator512 ta;
  350. DynamicString boot_dir(ta);
  351. if (_device_options._boot_dir != NULL)
  352. {
  353. boot_dir += _device_options._boot_dir;
  354. boot_dir += '/';
  355. }
  356. boot_dir += CROWN_BOOT_CONFIG;
  357. const StringId64 config_name(boot_dir.c_str());
  358. _resource_manager->load(RESOURCE_TYPE_CONFIG, config_name);
  359. _resource_manager->flush();
  360. _boot_config.parse((const char*)_resource_manager->get(RESOURCE_TYPE_CONFIG, config_name));
  361. _resource_manager->unload(RESOURCE_TYPE_CONFIG, config_name);
  362. }
  363. // Init all remaining subsystems
  364. _bgfx_allocator = CE_NEW(_allocator, BgfxAllocator)(default_allocator());
  365. _bgfx_callback = CE_NEW(_allocator, BgfxCallback)();
  366. _display = display::create(_allocator);
  367. _window = window::create(_allocator);
  368. _window->open(_device_options._window_x
  369. , _device_options._window_y
  370. , _boot_config.window_w
  371. , _boot_config.window_h
  372. , _device_options._parent_window
  373. );
  374. _window->set_title(_boot_config.window_title.c_str());
  375. _window->set_fullscreen(_boot_config.fullscreen);
  376. _window->bgfx_setup();
  377. bgfx::init(bgfx::RendererType::Count
  378. , BGFX_PCI_ID_NONE
  379. , 0
  380. , _bgfx_callback
  381. , _bgfx_allocator
  382. );
  383. _shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
  384. _material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
  385. _input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
  386. _unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
  387. _lua_environment = CE_NEW(_allocator, LuaEnvironment)();
  388. audio_globals::init();
  389. physics_globals::init(_allocator);
  390. ResourcePackage* boot_package = create_resource_package(_boot_config.boot_package_name);
  391. boot_package->load();
  392. boot_package->flush();
  393. _lua_environment->load_libs();
  394. _lua_environment->execute((LuaResource*)_resource_manager->get(RESOURCE_TYPE_SCRIPT, _boot_config.boot_script_name));
  395. _lua_environment->call_global("init", 0);
  396. logi("Engine initialized");
  397. s16 mouse_x = 0;
  398. s16 mouse_y = 0;
  399. s16 mouse_last_x = 0;
  400. s16 mouse_last_y = 0;
  401. s64 last_time = os::clocktime();
  402. s64 curr_time;
  403. while (!process_events(mouse_x, mouse_y, mouse_last_x, mouse_last_y, _boot_config.vsync) && !_quit)
  404. {
  405. curr_time = os::clocktime();
  406. const s64 time = curr_time - last_time;
  407. last_time = curr_time;
  408. const f64 freq = (f64)os::clockfrequency();
  409. _last_delta_time = f32(time * (1.0 / freq));
  410. _time_since_start += _last_delta_time;
  411. profiler_globals::clear();
  412. _console_server->update();
  413. RECORD_FLOAT("device.dt", _last_delta_time);
  414. RECORD_FLOAT("device.fps", 1.0f/_last_delta_time);
  415. if (!_paused)
  416. {
  417. _resource_manager->complete_requests();
  418. {
  419. const s64 t0 = os::clocktime();
  420. _lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time());
  421. const s64 t1 = os::clocktime();
  422. RECORD_FLOAT("lua.update", f32((t1 - t0)*(1.0 / freq)));
  423. }
  424. {
  425. const s64 t0 = os::clocktime();
  426. _lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time());
  427. const s64 t1 = os::clocktime();
  428. RECORD_FLOAT("lua.render", f32((t1 - t0)*(1.0 / freq)));
  429. }
  430. }
  431. _input_manager->update();
  432. const bgfx::Stats* stats = bgfx::getStats();
  433. RECORD_FLOAT("bgfx.gpu_time", f32(f64(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq));
  434. RECORD_FLOAT("bgfx.cpu_time", f32(f64(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq));
  435. bgfx::frame();
  436. profiler_globals::flush();
  437. _lua_environment->reset_temporaries();
  438. _frame_count++;
  439. }
  440. _lua_environment->call_global("shutdown", 0);
  441. boot_package->unload();
  442. destroy_resource_package(*boot_package);
  443. physics_globals::shutdown(_allocator);
  444. audio_globals::shutdown();
  445. CE_DELETE(_allocator, _lua_environment);
  446. CE_DELETE(_allocator, _unit_manager);
  447. CE_DELETE(_allocator, _input_manager);
  448. CE_DELETE(_allocator, _material_manager);
  449. CE_DELETE(_allocator, _shader_manager);
  450. CE_DELETE(_allocator, _resource_manager);
  451. CE_DELETE(_allocator, _resource_loader);
  452. bgfx::shutdown();
  453. _window->close();
  454. window::destroy(_allocator, *_window);
  455. display::destroy(_allocator, *_display);
  456. CE_DELETE(_allocator, _bgfx_callback);
  457. CE_DELETE(_allocator, _bgfx_allocator);
  458. if (_last_log)
  459. _bundle_filesystem->close(*_last_log);
  460. CE_DELETE(_allocator, _bundle_filesystem);
  461. profiler_globals::shutdown();
  462. }
  463. CE_DELETE(_allocator, _data_compiler);
  464. _console_server->shutdown();
  465. CE_DELETE(_allocator, _console_server);
  466. _allocator.clear();
  467. }
  468. void Device::quit()
  469. {
  470. _quit = true;
  471. }
  472. void Device::pause()
  473. {
  474. _paused = true;
  475. logi("Engine paused.");
  476. }
  477. void Device::unpause()
  478. {
  479. _paused = false;
  480. logi("Engine unpaused.");
  481. }
  482. void Device::resolution(u16& width, u16& height)
  483. {
  484. width = _width;
  485. height = _height;
  486. }
  487. u64 Device::frame_count() const
  488. {
  489. return _frame_count;
  490. }
  491. f32 Device::last_delta_time() const
  492. {
  493. return _last_delta_time;
  494. }
  495. f64 Device::time_since_start() const
  496. {
  497. return _time_since_start;
  498. }
  499. void Device::render(World& world, CameraInstance camera)
  500. {
  501. bgfx::setViewClear(0
  502. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  503. , 0x353839ff
  504. , 1.0f
  505. , 0
  506. );
  507. bgfx::setViewRect(0, 0, 0, _width, _height);
  508. bgfx::setViewRect(1, 0, 0, _width, _height);
  509. bgfx::setViewRect(2, 0, 0, _width, _height);
  510. const Matrix4x4 view = world.camera_view_matrix(camera);
  511. const Matrix4x4 proj = world.camera_projection_matrix(camera);
  512. bgfx::setViewTransform(0, to_float_ptr(view), to_float_ptr(proj));
  513. bgfx::setViewTransform(1, to_float_ptr(view), to_float_ptr(proj));
  514. bgfx::setViewTransform(2, to_float_ptr(MATRIX4X4_IDENTITY), to_float_ptr(MATRIX4X4_IDENTITY));
  515. bgfx::setViewSeq(2, true);
  516. bgfx::touch(0);
  517. bgfx::touch(1);
  518. bgfx::touch(2);
  519. float aspect_ratio = (_boot_config.aspect_ratio == -1.0f
  520. ? (float)_width/(float)_height
  521. : _boot_config.aspect_ratio
  522. );
  523. world.camera_set_aspect(camera, aspect_ratio);
  524. world.camera_set_viewport_metrics(camera, 0, 0, _width, _height);
  525. world.render(view, proj);
  526. }
  527. World* Device::create_world()
  528. {
  529. World* w = CE_NEW(default_allocator(), World)(default_allocator()
  530. , *_resource_manager
  531. , *_shader_manager
  532. , *_material_manager
  533. , *_unit_manager
  534. , *_lua_environment
  535. );
  536. array::push_back(_worlds, w);
  537. return w;
  538. }
  539. void Device::destroy_world(World& w)
  540. {
  541. for (u32 i = 0, n = array::size(_worlds); i < n; ++i)
  542. {
  543. if (&w == _worlds[i])
  544. {
  545. CE_DELETE(default_allocator(), &w);
  546. _worlds[i] = _worlds[n - 1];
  547. array::pop_back(_worlds);
  548. return;
  549. }
  550. }
  551. CE_FATAL("Bad world");
  552. }
  553. ResourcePackage* Device::create_resource_package(StringId64 id)
  554. {
  555. return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
  556. }
  557. void Device::destroy_resource_package(ResourcePackage& rp)
  558. {
  559. CE_DELETE(default_allocator(), &rp);
  560. }
  561. void Device::reload(StringId64 type, StringId64 name)
  562. {
  563. _resource_manager->reload(type, name);
  564. const void* new_resource = _resource_manager->get(type, name);
  565. if (type == RESOURCE_TYPE_SCRIPT)
  566. {
  567. _lua_environment->execute((const LuaResource*)new_resource);
  568. }
  569. }
  570. void Device::log(const char* msg, LogSeverity::Enum severity)
  571. {
  572. static const char* s_severity_map[] = { "info", "warning", "error" };
  573. CE_STATIC_ASSERT(countof(s_severity_map) == LogSeverity::COUNT);
  574. if (_last_log)
  575. {
  576. _last_log->write(msg, strlen32(msg));
  577. _last_log->write("\n", 1);
  578. _last_log->flush();
  579. }
  580. if (_console_server)
  581. {
  582. TempAllocator4096 ta;
  583. StringStream json(ta);
  584. json << "{\"type\":\"message\",";
  585. json << "\"severity\":\"";
  586. json << s_severity_map[severity];
  587. json << "\",";
  588. json << "\"message\":\"";
  589. // Sanitize msg
  590. for (; *msg; msg++)
  591. {
  592. if (*msg == '"' || *msg == '\\')
  593. json << "\\";
  594. json << *msg;
  595. }
  596. json << "\"}";
  597. _console_server->send(string_stream::c_str(json));
  598. }
  599. }
  600. char _buffer[sizeof(Device)];
  601. Device* _device = NULL;
  602. void run(const DeviceOptions& opts)
  603. {
  604. CE_ASSERT(_device == NULL, "Crown already initialized");
  605. _device = new (_buffer) Device(opts);
  606. _device->run();
  607. _device->~Device();
  608. _device = NULL;
  609. }
  610. Device* device()
  611. {
  612. return crown::_device;
  613. }
  614. } // namespace crown