device.cpp 16 KB

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