device.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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 "bundle_compiler.h"
  8. #include "config.h"
  9. #include "config_resource.h"
  10. #include "console_api.h"
  11. #include "console_server.h"
  12. #include "device.h"
  13. #include "file.h"
  14. #include "filesystem.h"
  15. #include "filesystem_apk.h"
  16. #include "filesystem_disk.h"
  17. #include "font_resource.h"
  18. #include "input_device.h"
  19. #include "input_manager.h"
  20. #include "json_object.h"
  21. #include "level_resource.h"
  22. #include "log.h"
  23. #include "lua_environment.h"
  24. #include "lua_resource.h"
  25. #include "map.h"
  26. #include "material_manager.h"
  27. #include "material_resource.h"
  28. #include "matrix4x4.h"
  29. #include "memory.h"
  30. #include "mesh_resource.h"
  31. #include "os.h"
  32. #include "os_event_queue.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. , _console_server(NULL)
  128. , _bundle_compiler(NULL)
  129. , _bundle_filesystem(NULL)
  130. , _last_log(NULL)
  131. , _resource_loader(NULL)
  132. , _resource_manager(NULL)
  133. , _bgfx_allocator(NULL)
  134. , _bgfx_callback(NULL)
  135. , _shader_manager(NULL)
  136. , _material_manager(NULL)
  137. , _input_manager(NULL)
  138. , _unit_manager(NULL)
  139. , _lua_environment(NULL)
  140. , _display(NULL)
  141. , _window(NULL)
  142. , _worlds(default_allocator())
  143. , _width(0)
  144. , _height(0)
  145. , _quit(false)
  146. , _paused(false)
  147. , _frame_count(0)
  148. , _last_delta_time(0.0f)
  149. , _time_since_start(0.0)
  150. {
  151. }
  152. bool Device::process_events(s16& mouse_x, s16& mouse_y, s16& mouse_last_x, s16& mouse_last_y)
  153. {
  154. OsEvent event;
  155. bool exit = false;
  156. InputManager* im = _input_manager;
  157. const s16 dt_x = mouse_x - mouse_last_x;
  158. const s16 dt_y = mouse_y - mouse_last_y;
  159. im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f));
  160. mouse_last_x = mouse_x;
  161. mouse_last_y = mouse_y;
  162. while(next_event(event))
  163. {
  164. if (event.type == OsEvent::NONE)
  165. continue;
  166. switch (event.type)
  167. {
  168. case OsEvent::TOUCH:
  169. {
  170. const OsTouchEvent& ev = event.touch;
  171. switch (ev.type)
  172. {
  173. case OsTouchEvent::POINTER:
  174. im->touch()->set_button_state(ev.pointer_id, ev.pressed);
  175. break;
  176. case OsTouchEvent::MOVE:
  177. im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f));
  178. break;
  179. default:
  180. CE_FATAL("Unknown touch event type");
  181. break;
  182. }
  183. break;
  184. }
  185. case OsEvent::MOUSE:
  186. {
  187. const OsMouseEvent& ev = event.mouse;
  188. switch (ev.type)
  189. {
  190. case OsMouseEvent::BUTTON:
  191. im->mouse()->set_button_state(ev.button, ev.pressed);
  192. break;
  193. case OsMouseEvent::MOVE:
  194. mouse_x = ev.x;
  195. mouse_y = ev.y;
  196. im->mouse()->set_axis(MouseAxis::CURSOR, vector3(ev.x, ev.y, 0.0f));
  197. break;
  198. case OsMouseEvent::WHEEL:
  199. im->mouse()->set_axis(MouseAxis::WHEEL, vector3(0.0f, ev.wheel, 0.0f));
  200. break;
  201. default:
  202. CE_FATAL("Unknown mouse event type");
  203. break;
  204. }
  205. break;
  206. }
  207. case OsEvent::KEYBOARD:
  208. {
  209. const OsKeyboardEvent& ev = event.keyboard;
  210. im->keyboard()->set_button_state(ev.button, ev.pressed);
  211. break;
  212. }
  213. case OsEvent::JOYPAD:
  214. {
  215. const OsJoypadEvent& ev = event.joypad;
  216. switch (ev.type)
  217. {
  218. case OsJoypadEvent::CONNECTED:
  219. im->joypad(ev.index)->set_connected(ev.connected);
  220. break;
  221. case OsJoypadEvent::BUTTON:
  222. im->joypad(ev.index)->set_button_state(ev.button, ev.pressed);
  223. break;
  224. case OsJoypadEvent::AXIS:
  225. im->joypad(ev.index)->set_axis(ev.button, vector3(ev.x, ev.y, ev.z));
  226. break;
  227. default:
  228. CE_FATAL("Unknown joypad event");
  229. break;
  230. }
  231. break;
  232. }
  233. case OsEvent::METRICS:
  234. {
  235. const OsMetricsEvent& ev = event.metrics;
  236. _width = ev.width;
  237. _height = ev.height;
  238. bgfx::reset(ev.width, ev.height, BGFX_RESET_VSYNC);
  239. break;
  240. }
  241. case OsEvent::EXIT:
  242. {
  243. exit = true;
  244. break;
  245. }
  246. case OsEvent::PAUSE:
  247. {
  248. pause();
  249. break;
  250. }
  251. case OsEvent::RESUME:
  252. {
  253. unpause();
  254. break;
  255. }
  256. default:
  257. {
  258. CE_FATAL("Unknown Os Event");
  259. break;
  260. }
  261. }
  262. }
  263. return exit;
  264. }
  265. void Device::run()
  266. {
  267. _console_server = CE_NEW(_allocator, ConsoleServer)(default_allocator());
  268. load_console_api(*_console_server);
  269. namespace pcr = physics_config_resource;
  270. namespace phr = physics_resource;
  271. namespace pkr = package_resource;
  272. namespace sdr = sound_resource;
  273. namespace mhr = mesh_resource;
  274. namespace utr = unit_resource;
  275. namespace txr = texture_resource;
  276. namespace mtr = material_resource;
  277. namespace lur = lua_resource;
  278. namespace ftr = font_resource;
  279. namespace lvr = level_resource;
  280. namespace spr = sprite_resource;
  281. namespace shr = shader_resource;
  282. namespace sar = sprite_animation_resource;
  283. namespace cor = config_resource;
  284. bool do_continue = true;
  285. #if CROWN_PLATFORM_LINUX || CROWN_PLATFORM_WINDOWS
  286. if (_device_options._do_compile || _device_options._server)
  287. {
  288. _bundle_compiler = CE_NEW(_allocator, BundleCompiler)();
  289. _bundle_compiler->register_compiler(RESOURCE_TYPE_SCRIPT, RESOURCE_VERSION_SCRIPT, lur::compile);
  290. _bundle_compiler->register_compiler(RESOURCE_TYPE_TEXTURE, RESOURCE_VERSION_TEXTURE, txr::compile);
  291. _bundle_compiler->register_compiler(RESOURCE_TYPE_MESH, RESOURCE_VERSION_MESH, mhr::compile);
  292. _bundle_compiler->register_compiler(RESOURCE_TYPE_SOUND, RESOURCE_VERSION_SOUND, sdr::compile);
  293. _bundle_compiler->register_compiler(RESOURCE_TYPE_UNIT, RESOURCE_VERSION_UNIT, utr::compile);
  294. _bundle_compiler->register_compiler(RESOURCE_TYPE_SPRITE, RESOURCE_VERSION_SPRITE, spr::compile);
  295. _bundle_compiler->register_compiler(RESOURCE_TYPE_PACKAGE, RESOURCE_VERSION_PACKAGE, pkr::compile);
  296. _bundle_compiler->register_compiler(RESOURCE_TYPE_PHYSICS, RESOURCE_VERSION_PHYSICS, phr::compile);
  297. _bundle_compiler->register_compiler(RESOURCE_TYPE_MATERIAL, RESOURCE_VERSION_MATERIAL, mtr::compile);
  298. _bundle_compiler->register_compiler(RESOURCE_TYPE_PHYSICS_CONFIG, RESOURCE_VERSION_PHYSICS_CONFIG, pcr::compile);
  299. _bundle_compiler->register_compiler(RESOURCE_TYPE_FONT, RESOURCE_VERSION_FONT, ftr::compile);
  300. _bundle_compiler->register_compiler(RESOURCE_TYPE_LEVEL, RESOURCE_VERSION_LEVEL, lvr::compile);
  301. _bundle_compiler->register_compiler(RESOURCE_TYPE_SHADER, RESOURCE_VERSION_SHADER, shr::compile);
  302. _bundle_compiler->register_compiler(RESOURCE_TYPE_SPRITE_ANIMATION, RESOURCE_VERSION_SPRITE_ANIMATION, sar::compile);
  303. _bundle_compiler->register_compiler(RESOURCE_TYPE_CONFIG, RESOURCE_VERSION_CONFIG, cor::compile);
  304. _bundle_compiler->scan(_device_options._source_dir);
  305. if (_device_options._server)
  306. {
  307. _console_server->listen(CROWN_DEFAULT_COMPILER_PORT, false);
  308. while (true)
  309. {
  310. _console_server->update();
  311. os::sleep(60);
  312. }
  313. }
  314. else
  315. {
  316. const char* bundle_dir = _device_options._bundle_dir;
  317. const char* platform = _device_options._platform;
  318. do_continue = _bundle_compiler->compile(bundle_dir, platform);
  319. do_continue = do_continue && _device_options._do_continue;
  320. }
  321. }
  322. #endif // CROWN_PLATFORM_LINUX || CROWN_PLATFORM_WINDOWS
  323. if (do_continue)
  324. {
  325. _console_server->listen(_device_options._console_port, _device_options._wait_console);
  326. #if CROWN_PLATFORM_ANDROID
  327. _bundle_filesystem = CE_NEW(_allocator, FilesystemApk)(default_allocator(), const_cast<AAssetManager*>((AAssetManager*)_device_options._asset_manager));
  328. #else
  329. const char* bundle_dir = _device_options._bundle_dir;
  330. if (!bundle_dir)
  331. {
  332. char buf[1024];
  333. bundle_dir = os::getcwd(buf, sizeof(buf));
  334. }
  335. _bundle_filesystem = CE_NEW(_allocator, FilesystemDisk)(default_allocator());
  336. ((FilesystemDisk*)_bundle_filesystem)->set_prefix(bundle_dir);
  337. if (!_bundle_filesystem->exists(bundle_dir))
  338. _bundle_filesystem->create_directory(bundle_dir);
  339. _last_log = _bundle_filesystem->open(CROWN_LAST_LOG, FileOpenMode::WRITE);
  340. #endif // CROWN_PLATFORM_ANDROID
  341. logi("Initializing Crown Engine %s...", version());
  342. profiler_globals::init();
  343. _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem);
  344. _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
  345. _resource_manager->register_type(RESOURCE_TYPE_SCRIPT, lur::load, lur::unload, NULL, NULL );
  346. _resource_manager->register_type(RESOURCE_TYPE_TEXTURE, txr::load, txr::unload, txr::online, txr::offline);
  347. _resource_manager->register_type(RESOURCE_TYPE_MESH, mhr::load, mhr::unload, mhr::online, mhr::offline);
  348. _resource_manager->register_type(RESOURCE_TYPE_SOUND, sdr::load, sdr::unload, NULL, NULL );
  349. _resource_manager->register_type(RESOURCE_TYPE_UNIT, utr::load, utr::unload, NULL, NULL );
  350. _resource_manager->register_type(RESOURCE_TYPE_SPRITE, spr::load, spr::unload, spr::online, spr::offline);
  351. _resource_manager->register_type(RESOURCE_TYPE_PACKAGE, pkr::load, pkr::unload, NULL, NULL );
  352. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS, phr::load, phr::unload, NULL, NULL );
  353. _resource_manager->register_type(RESOURCE_TYPE_MATERIAL, mtr::load, mtr::unload, mtr::online, mtr::offline);
  354. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS_CONFIG, pcr::load, pcr::unload, NULL, NULL );
  355. _resource_manager->register_type(RESOURCE_TYPE_FONT, ftr::load, ftr::unload, NULL, NULL );
  356. _resource_manager->register_type(RESOURCE_TYPE_LEVEL, lvr::load, lvr::unload, NULL, NULL );
  357. _resource_manager->register_type(RESOURCE_TYPE_SHADER, shr::load, shr::unload, shr::online, shr::offline);
  358. _resource_manager->register_type(RESOURCE_TYPE_SPRITE_ANIMATION, sar::load, sar::unload, NULL, NULL );
  359. _resource_manager->register_type(RESOURCE_TYPE_CONFIG, cor::load, cor::unload, NULL, NULL );
  360. // Read config
  361. StringId64 boot_package_name(u64(0));
  362. StringId64 boot_script_name(u64(0));
  363. u16 window_w = CROWN_DEFAULT_WINDOW_WIDTH;
  364. u16 window_h = CROWN_DEFAULT_WINDOW_HEIGHT;
  365. {
  366. TempAllocator4096 ta;
  367. DynamicString boot_dir(ta);
  368. if (_device_options._boot_dir != NULL)
  369. {
  370. boot_dir += _device_options._boot_dir;
  371. boot_dir += '/';
  372. }
  373. boot_dir += CROWN_BOOT_CONFIG;
  374. const StringId64 config_name(boot_dir.c_str());
  375. _resource_manager->load(RESOURCE_TYPE_CONFIG, config_name);
  376. _resource_manager->flush();
  377. const char* cfile = (const char*)_resource_manager->get(RESOURCE_TYPE_CONFIG, config_name);
  378. JsonObject config(ta);
  379. sjson::parse(cfile, config);
  380. boot_script_name = sjson::parse_resource_id(config["boot_script"]);
  381. boot_package_name = sjson::parse_resource_id(config["boot_package"]);
  382. // Platform-specific configs
  383. if (json_object::has(config, CROWN_PLATFORM_NAME))
  384. {
  385. JsonObject platform(ta);
  386. sjson::parse(config[CROWN_PLATFORM_NAME], platform);
  387. if (json_object::has(platform, "window_width"))
  388. {
  389. window_w = (u16)sjson::parse_int(platform["window_width"]);
  390. }
  391. if (json_object::has(platform, "window_height"))
  392. {
  393. window_h = (u16)sjson::parse_int(platform["window_height"]);
  394. }
  395. }
  396. _resource_manager->unload(RESOURCE_TYPE_CONFIG, config_name);
  397. }
  398. // Init all remaining subsystems
  399. _bgfx_allocator = CE_NEW(_allocator, BgfxAllocator)(default_allocator());
  400. _bgfx_callback = CE_NEW(_allocator, BgfxCallback)();
  401. _display = display::create(_allocator);
  402. _window = window::create(_allocator);
  403. _window->open(_device_options._window_x
  404. , _device_options._window_y
  405. , window_w
  406. , window_h
  407. , _device_options._parent_window
  408. );
  409. _window->bgfx_setup();
  410. bgfx::init(bgfx::RendererType::Count
  411. , BGFX_PCI_ID_NONE
  412. , 0
  413. , _bgfx_callback
  414. , _bgfx_allocator
  415. );
  416. _shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
  417. _material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
  418. _input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
  419. _unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
  420. _lua_environment = CE_NEW(_allocator, LuaEnvironment)();
  421. audio_globals::init();
  422. physics_globals::init(_allocator);
  423. ResourcePackage* boot_package = create_resource_package(boot_package_name);
  424. boot_package->load();
  425. boot_package->flush();
  426. _lua_environment->load_libs();
  427. _lua_environment->execute((LuaResource*)_resource_manager->get(RESOURCE_TYPE_SCRIPT, boot_script_name));
  428. _lua_environment->call_global("init", 0);
  429. logd("Engine initialized");
  430. s16 mouse_x = 0;
  431. s16 mouse_y = 0;
  432. s16 mouse_last_x = 0;
  433. s16 mouse_last_y = 0;
  434. s64 last_time = os::clocktime();
  435. s64 curr_time;
  436. while (!process_events(mouse_x, mouse_y, mouse_last_x, mouse_last_y) && !_quit)
  437. {
  438. curr_time = os::clocktime();
  439. const s64 time = curr_time - last_time;
  440. last_time = curr_time;
  441. const f64 freq = (f64)os::clockfrequency();
  442. _last_delta_time = f32(time * (1.0 / freq));
  443. _time_since_start += _last_delta_time;
  444. profiler_globals::clear();
  445. _console_server->update();
  446. RECORD_FLOAT("device.dt", _last_delta_time);
  447. RECORD_FLOAT("device.fps", 1.0f/_last_delta_time);
  448. if (!_paused)
  449. {
  450. _resource_manager->complete_requests();
  451. {
  452. const s64 t0 = os::clocktime();
  453. _lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time());
  454. const s64 t1 = os::clocktime();
  455. RECORD_FLOAT("lua.update", (t1 - t0)*(1.0 / freq));
  456. }
  457. {
  458. const s64 t0 = os::clocktime();
  459. _lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time());
  460. const s64 t1 = os::clocktime();
  461. RECORD_FLOAT("lua.render", (t1 - t0)*(1.0 / freq));
  462. }
  463. }
  464. _input_manager->update();
  465. const bgfx::Stats* stats = bgfx::getStats();
  466. RECORD_FLOAT("bgfx.gpu_time", f32(f64(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq));
  467. RECORD_FLOAT("bgfx.cpu_time", f32(f64(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq));
  468. bgfx::frame();
  469. profiler_globals::flush();
  470. _lua_environment->reset_temporaries();
  471. _frame_count++;
  472. }
  473. _lua_environment->call_global("shutdown", 0);
  474. boot_package->unload();
  475. destroy_resource_package(*boot_package);
  476. physics_globals::shutdown(_allocator);
  477. audio_globals::shutdown();
  478. CE_DELETE(_allocator, _lua_environment);
  479. CE_DELETE(_allocator, _unit_manager);
  480. CE_DELETE(_allocator, _input_manager);
  481. CE_DELETE(_allocator, _material_manager);
  482. CE_DELETE(_allocator, _shader_manager);
  483. CE_DELETE(_allocator, _resource_manager);
  484. CE_DELETE(_allocator, _resource_loader);
  485. bgfx::shutdown();
  486. window::destroy(_allocator, *_window);
  487. display::destroy(_allocator, *_display);
  488. CE_DELETE(_allocator, _bgfx_callback);
  489. CE_DELETE(_allocator, _bgfx_allocator);
  490. if (_last_log)
  491. _bundle_filesystem->close(*_last_log);
  492. CE_DELETE(_allocator, _bundle_filesystem);
  493. profiler_globals::shutdown();
  494. }
  495. _console_server->shutdown();
  496. CE_DELETE(_allocator, _console_server);
  497. CE_DELETE(_allocator, _bundle_compiler);
  498. _allocator.clear();
  499. }
  500. void Device::quit()
  501. {
  502. _quit = true;
  503. }
  504. void Device::pause()
  505. {
  506. _paused = true;
  507. logi("Engine paused.");
  508. }
  509. void Device::unpause()
  510. {
  511. _paused = false;
  512. logi("Engine unpaused.");
  513. }
  514. void Device::resolution(u16& width, u16& height)
  515. {
  516. width = _width;
  517. height = _height;
  518. }
  519. u64 Device::frame_count() const
  520. {
  521. return _frame_count;
  522. }
  523. f32 Device::last_delta_time() const
  524. {
  525. return _last_delta_time;
  526. }
  527. f64 Device::time_since_start() const
  528. {
  529. return _time_since_start;
  530. }
  531. void Device::render(World& world, CameraInstance camera)
  532. {
  533. bgfx::setViewClear(0
  534. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  535. , 0x353839ff
  536. , 1.0f
  537. , 0
  538. );
  539. bgfx::setViewRect(0, 0, 0, _width, _height);
  540. bgfx::setViewRect(1, 0, 0, _width, _height);
  541. bgfx::setViewRect(2, 0, 0, _width, _height);
  542. const f32* view = to_float_ptr(world.camera_view_matrix(camera));
  543. const f32* proj = to_float_ptr(world.camera_projection_matrix(camera));
  544. bgfx::setViewTransform(0, view, proj);
  545. bgfx::setViewTransform(1, view, proj);
  546. bgfx::setViewTransform(2, to_float_ptr(MATRIX4X4_IDENTITY), to_float_ptr(MATRIX4X4_IDENTITY));
  547. bgfx::setViewSeq(2, true);
  548. bgfx::touch(0);
  549. bgfx::touch(1);
  550. bgfx::touch(2);
  551. world.camera_set_aspect(camera, (float)_width/(float)_height);
  552. world.camera_set_viewport_metrics(camera, 0, 0, _width, _height);
  553. world.render(camera);
  554. }
  555. World* Device::create_world()
  556. {
  557. World* w = CE_NEW(default_allocator(), World)(default_allocator()
  558. , *_resource_manager
  559. , *_shader_manager
  560. , *_material_manager
  561. , *_unit_manager
  562. , *_lua_environment
  563. );
  564. array::push_back(_worlds, w);
  565. return w;
  566. }
  567. void Device::destroy_world(World& w)
  568. {
  569. for (u32 i = 0, n = array::size(_worlds); i < n; ++i)
  570. {
  571. if (&w == _worlds[i])
  572. {
  573. CE_DELETE(default_allocator(), &w);
  574. _worlds[i] = _worlds[n - 1];
  575. array::pop_back(_worlds);
  576. return;
  577. }
  578. }
  579. CE_ASSERT(false, "Bad world");
  580. }
  581. ResourcePackage* Device::create_resource_package(StringId64 id)
  582. {
  583. return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
  584. }
  585. void Device::destroy_resource_package(ResourcePackage& rp)
  586. {
  587. CE_DELETE(default_allocator(), &rp);
  588. }
  589. void Device::reload(StringId64 type, StringId64 name)
  590. {
  591. _resource_manager->reload(type, name);
  592. const void* new_resource = _resource_manager->get(type, name);
  593. if (type == RESOURCE_TYPE_SCRIPT)
  594. {
  595. _lua_environment->execute((const LuaResource*)new_resource);
  596. }
  597. }
  598. static StringStream& sanitize(StringStream& ss, const char* msg)
  599. {
  600. using namespace string_stream;
  601. const char* ch = msg;
  602. for (; *ch; ch++)
  603. {
  604. if (*ch == '"' || *ch == '\\')
  605. ss << "\\";
  606. ss << *ch;
  607. }
  608. return ss;
  609. }
  610. static const char* s_severity_map[] = { "info", "warning", "error", "debug" };
  611. CE_STATIC_ASSERT(countof(s_severity_map) == LogSeverity::COUNT);
  612. void Device::log(const char* msg, LogSeverity::Enum severity)
  613. {
  614. if (_last_log)
  615. {
  616. _last_log->write(msg, strlen32(msg));
  617. _last_log->write("\n", 1);
  618. _last_log->flush();
  619. }
  620. if (_console_server)
  621. {
  622. TempAllocator4096 ta;
  623. StringStream json(ta);
  624. json << "{\"type\":\"message\",";
  625. json << "\"severity\":\"" << s_severity_map[severity] << "\",";
  626. json << "\"message\":\""; sanitize(json, msg) << "\"}";
  627. _console_server->send(string_stream::c_str(json));
  628. }
  629. }
  630. ConsoleServer* Device::console_server()
  631. {
  632. return _console_server;
  633. }
  634. BundleCompiler* Device::bundle_compiler()
  635. {
  636. return _bundle_compiler;
  637. }
  638. ResourceManager* Device::resource_manager()
  639. {
  640. return _resource_manager;
  641. }
  642. LuaEnvironment* Device::lua_environment()
  643. {
  644. return _lua_environment;
  645. }
  646. InputManager* Device::input_manager()
  647. {
  648. return _input_manager;
  649. }
  650. ShaderManager* Device::shader_manager()
  651. {
  652. return _shader_manager;
  653. }
  654. MaterialManager* Device::material_manager()
  655. {
  656. return _material_manager;
  657. }
  658. UnitManager* Device::unit_manager()
  659. {
  660. return _unit_manager;
  661. }
  662. Display* Device::display()
  663. {
  664. return _display;
  665. }
  666. Window* Device::window()
  667. {
  668. return _window;
  669. }
  670. char _buffer[sizeof(Device)];
  671. Device* _device = NULL;
  672. void run(const DeviceOptions& opts)
  673. {
  674. CE_ASSERT(_device == NULL, "Crown already initialized");
  675. _device = new (_buffer) Device(opts);
  676. _device->run();
  677. _device->~Device();
  678. _device = NULL;
  679. }
  680. Device* device()
  681. {
  682. return crown::_device;
  683. }
  684. } // namespace crown