2
0

device.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. /*
  2. * Copyright (c) 2012-2025 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: MIT
  4. */
  5. #include "config.h"
  6. #include "core/containers/array.inl"
  7. #include "core/filesystem/file.h"
  8. #include "core/filesystem/filesystem.h"
  9. #include "core/filesystem/filesystem_apk.h"
  10. #include "core/filesystem/filesystem_disk.h"
  11. #include "core/json/json_object.inl"
  12. #include "core/json/sjson.h"
  13. #include "core/list.inl"
  14. #include "core/math/constants.h"
  15. #include "core/math/matrix4x4.inl"
  16. #include "core/math/vector3.inl"
  17. #include "core/memory/globals.h"
  18. #include "core/memory/proxy_allocator.h"
  19. #include "core/memory/temp_allocator.inl"
  20. #include "core/network/ip_address.h"
  21. #include "core/network/socket.h"
  22. #include "core/option.inl"
  23. #include "core/os.h"
  24. #include "core/strings/dynamic_string.inl"
  25. #include "core/strings/string.inl"
  26. #include "core/strings/string_id.inl"
  27. #include "core/strings/string_stream.inl"
  28. #include "core/time.h"
  29. #include "core/types.h"
  30. #include "device/console_server.h"
  31. #include "device/device.h"
  32. #include "device/graph.h"
  33. #include "device/input_device.h"
  34. #include "device/input_manager.h"
  35. #include "device/log.h"
  36. #include "device/pipeline.h"
  37. #include "device/profiler.h"
  38. #include "lua/lua_environment.h"
  39. #include "lua/lua_stack.inl"
  40. #include "resource/config_resource.h"
  41. #include "resource/font_resource.h"
  42. #include "resource/level_resource.h"
  43. #include "resource/lua_resource.h"
  44. #include "resource/material_resource.h"
  45. #include "resource/mesh_resource.h"
  46. #include "resource/mesh_skeleton_resource.h"
  47. #include "resource/package_resource.h"
  48. #include "resource/physics_resource.h"
  49. #include "resource/resource_id.inl"
  50. #include "resource/resource_loader.h"
  51. #include "resource/resource_manager.h"
  52. #include "resource/resource_package.h"
  53. #include "resource/shader_resource.h"
  54. #include "resource/sound_resource.h"
  55. #include "resource/sprite_resource.h"
  56. #include "resource/state_machine_resource.h"
  57. #include "resource/texture_resource.h"
  58. #include "resource/unit_resource.h"
  59. #include "world/audio.h"
  60. #include "world/material_manager.h"
  61. #include "world/physics.h"
  62. #include "world/shader_manager.h"
  63. #include "world/unit_manager.h"
  64. #include "world/world.h"
  65. #include <bgfx/bgfx.h>
  66. #include <bimg/bimg.h>
  67. #include <bx/allocator.h>
  68. #include <bx/error.h>
  69. #include <bx/error.h>
  70. #include <bx/file.h>
  71. #include <bx/math.h>
  72. #if CROWN_PLATFORM_EMSCRIPTEN
  73. #include <emscripten/emscripten.h>
  74. #endif
  75. #define CROWN_MAX_SUBSYSTEMS_HEAP (8*1024*1024)
  76. LOG_SYSTEM(DEVICE, "device")
  77. namespace crown
  78. {
  79. extern bool next_event(OsEvent &ev);
  80. struct BgfxCallback : public bgfx::CallbackI
  81. {
  82. DynamicString _screenshot_path;
  83. std::atomic_int _screenshot_ready;
  84. explicit BgfxCallback(Allocator &a)
  85. : _screenshot_path(a)
  86. , _screenshot_ready(0)
  87. {
  88. }
  89. virtual void fatal(const char *_filePath, uint16_t _line, bgfx::Fatal::Enum _code, const char *_str) override
  90. {
  91. CE_UNUSED_4(_filePath, _line, _code, _str);
  92. error::abort("%s (code 0x%08x).\n", _str, _code);
  93. }
  94. virtual void traceVargs(const char *_filePath, u16 _line, const char *_format, va_list _argList) override
  95. {
  96. CE_UNUSED_2(_filePath, _line);
  97. char buf[2048];
  98. strncpy(buf, _format, sizeof(buf) - 1);
  99. buf[strlen32(buf) - 1] = '\0'; // Remove trailing newline
  100. vlogi(DEVICE, buf, _argList);
  101. }
  102. virtual void profilerBegin(const char *_name, uint32_t _abgr, const char *_filePath, uint16_t _line) override
  103. {
  104. CE_UNUSED_4(_name, _abgr, _filePath, _line);
  105. }
  106. virtual void profilerBeginLiteral(const char *_name, uint32_t _abgr, const char *_filePath, uint16_t _line) override
  107. {
  108. CE_UNUSED_4(_name, _abgr, _filePath, _line);
  109. }
  110. virtual void profilerEnd() override
  111. {
  112. }
  113. virtual u32 cacheReadSize(u64 _id) override
  114. {
  115. CE_UNUSED(_id);
  116. return 0;
  117. }
  118. virtual bool cacheRead(u64 _id, void *_data, u32 _size) override
  119. {
  120. CE_UNUSED_3(_id, _data, _size);
  121. return false;
  122. }
  123. virtual void cacheWrite(u64 _id, const void *_data, u32 _size) override
  124. {
  125. CE_UNUSED_3(_id, _data, _size);
  126. }
  127. virtual void screenShot(const char *_filePath, u32 _width, u32 _height, u32 _pitch, const void *_data, u32 _size, bool _yflip) override
  128. {
  129. CE_UNUSED(_size);
  130. bx::Error err;
  131. bx::FileWriter writer;
  132. if (bx::open(&writer, _filePath, false, &err)) {
  133. bimg::imageWritePng(&writer
  134. , _width
  135. , _height
  136. , _pitch
  137. , _data
  138. , bimg::TextureFormat::BGRA8
  139. , _yflip
  140. , &err
  141. );
  142. bx::close(&writer);
  143. }
  144. _screenshot_path = _filePath;
  145. _screenshot_ready = 1;
  146. ++device()->_needs_draw; // 1 frame for _screenshot_ready to be evaluated.
  147. }
  148. virtual void captureBegin(u32 _width, u32 _height, u32 _pitch, bgfx::TextureFormat::Enum _format, bool _yflip) override
  149. {
  150. CE_UNUSED_5(_width, _height, _pitch, _format, _yflip);
  151. }
  152. virtual void captureEnd() override
  153. {
  154. }
  155. virtual void captureFrame(const void *_data, u32 _size) override
  156. {
  157. CE_UNUSED_2(_data, _size);
  158. }
  159. };
  160. struct BgfxAllocator : public bx::AllocatorI
  161. {
  162. ProxyAllocator _allocator;
  163. explicit BgfxAllocator(Allocator &a)
  164. : _allocator(a, "bgfx")
  165. {
  166. }
  167. ~BgfxAllocator()
  168. {
  169. }
  170. virtual void *realloc(void *_ptr, size_t _size, size_t _align, const char * /*_file*/, u32 /*_line*/)
  171. {
  172. return _allocator.reallocate(_ptr, _size, _align);
  173. }
  174. };
  175. static void device_command_pause(ConsoleServer & /*cs*/, u32 /*client_id*/, const JsonArray & /*args*/, void * /*user_data*/)
  176. {
  177. device()->pause();
  178. }
  179. static void device_command_unpause(ConsoleServer & /*cs*/, u32 /*client_id*/, const JsonArray & /*args*/, void * /*user_data*/)
  180. {
  181. device()->unpause();
  182. }
  183. static void device_command_game(ConsoleServer &cs, u32 client_id, const JsonArray &args, void *user_data)
  184. {
  185. CE_UNUSED(user_data);
  186. TempAllocator1024 ta;
  187. if (array::size(args) < 2) {
  188. cs.error(client_id, "Usage: game <pause|resume>");
  189. return;
  190. }
  191. DynamicString subcmd(ta);
  192. sjson::parse_string(subcmd, args[1]);
  193. if (subcmd == "pause") {
  194. device()->pause();
  195. } else if (subcmd == "resume") {
  196. device()->unpause();
  197. } else {
  198. loge(DEVICE, "Unknown game parameter");
  199. }
  200. }
  201. static void device_command_crash(ConsoleServer &cs, u32 client_id, const JsonArray &args, void *user_data)
  202. {
  203. CE_UNUSED(user_data);
  204. TempAllocator1024 ta;
  205. struct CrashType
  206. {
  207. enum Enum
  208. {
  209. DIVISION_BY_ZERO,
  210. UNALIGNED_ACCESS,
  211. SEGMENTATION_FAULT,
  212. OUT_OF_MEMORY,
  213. ASSERT,
  214. COUNT
  215. };
  216. };
  217. struct
  218. {
  219. const char *type;
  220. const char *desc;
  221. }
  222. crash_info[] =
  223. {
  224. { "div_by_zero", "Divide a number by zero." },
  225. { "unaligned", "Do an unaligned memory access." },
  226. { "segfault", "Trigger a segmentation fault." },
  227. { "oom", "Allocate too much memory." },
  228. { "assert", "Call CE_ASSERT(false)." }
  229. };
  230. CE_STATIC_ASSERT(countof(crash_info) == CrashType::COUNT);
  231. if (array::size(args) < 2) {
  232. cs.error(client_id, "Usage: crash <type>");
  233. return;
  234. }
  235. DynamicString subcmd(ta);
  236. sjson::parse_string(subcmd, args[1]);
  237. if (subcmd == crash_info[CrashType::DIVISION_BY_ZERO].type) {
  238. f32(time::now()) / 0.0f;
  239. } else if (subcmd == crash_info[CrashType::UNALIGNED_ACCESS].type) {
  240. CE_ALIGN_DECL(alignof(s64), u8 buf[16]);
  241. *((s64 *)&buf[1]) = time::now();
  242. } else if (subcmd == crash_info[CrashType::SEGMENTATION_FAULT].type) {
  243. *((s64 *)(uintptr_t)time::now()) = time::now();
  244. } else if (subcmd == crash_info[CrashType::OUT_OF_MEMORY].type) {
  245. while (s64 t = time::now())
  246. *((s64 *)malloc(1024*1024)) = t;
  247. } else if (subcmd == crash_info[CrashType::ASSERT].type) {
  248. CE_ASSERT(false, "False");
  249. } else if (subcmd == "help") {
  250. for (u32 i = 0; i < CrashType::COUNT; ++i) {
  251. logi(DEVICE, "%s %s", crash_info[i].type, crash_info[i].desc);
  252. }
  253. } else {
  254. loge(DEVICE, "Unknown crash parameter");
  255. }
  256. }
  257. static void device_message_resize(ConsoleServer & /*cs*/, u32 /*client_id*/, const char *json, void * /*user_data*/)
  258. {
  259. TempAllocator256 ta;
  260. JsonObject obj(ta);
  261. s32 width;
  262. s32 height;
  263. sjson::parse(obj, json);
  264. width = sjson::parse_int(obj["width"]);
  265. height = sjson::parse_int(obj["height"]);
  266. device()->_window->resize((u16)width, (u16)height);
  267. }
  268. static void device_message_frame(ConsoleServer & /*cs*/, u32 /*client_id*/, const char * /*json*/, void *user_data)
  269. {
  270. ++((Device *)user_data)->_needs_draw;
  271. }
  272. static void device_message_quit(ConsoleServer &cs, u32 client_id, const char *json, void *user_data)
  273. {
  274. CE_UNUSED_3(cs, client_id, json);
  275. ((Device *)user_data)->quit();
  276. }
  277. static void device_message_refresh(ConsoleServer &cs, u32 client_id, const char *json, void *user_data)
  278. {
  279. CE_UNUSED_2(cs, client_id);
  280. ((Device *)user_data)->refresh(json);
  281. TempAllocator512 ta;
  282. StringStream ss(ta);
  283. ss << "{";
  284. ss << "\"type\":\"refresh\",";
  285. ss << "\"success\":" << (true ? "true" : "false");
  286. ss << "}";
  287. cs.send(client_id, string_stream::c_str(ss));
  288. }
  289. Device::Device(const DeviceOptions &opts, ConsoleServer &cs)
  290. : _allocator(default_allocator(), CROWN_MAX_SUBSYSTEMS_HEAP)
  291. , _options(opts)
  292. , _boot_config(default_allocator())
  293. , _console_server(&cs)
  294. , _data_filesystem(NULL)
  295. , _resource_loader(NULL)
  296. , _resource_manager(NULL)
  297. , _bgfx_allocator(NULL)
  298. , _bgfx_callback(NULL)
  299. , _shader_manager(NULL)
  300. , _material_manager(NULL)
  301. , _input_manager(NULL)
  302. , _unit_manager(NULL)
  303. , _lua_environment(NULL)
  304. , _pipeline(NULL)
  305. , _display(NULL)
  306. , _window(NULL)
  307. , _timestep_policy(TimestepPolicy::VARIABLE)
  308. , _width(CROWN_DEFAULT_WINDOW_WIDTH)
  309. , _height(CROWN_DEFAULT_WINDOW_HEIGHT)
  310. , _quit(false)
  311. , _paused(false)
  312. , _needs_draw(1)
  313. {
  314. list::init_head(_worlds);
  315. }
  316. bool Device::process_events()
  317. {
  318. bool exit = false;
  319. OsEvent event;
  320. while (next_event(event)) {
  321. switch (event.type) {
  322. case OsEventType::BUTTON:
  323. case OsEventType::AXIS:
  324. case OsEventType::STATUS:
  325. _input_manager->read(event);
  326. break;
  327. case OsEventType::RESOLUTION:
  328. _width = event.resolution.width;
  329. _height = event.resolution.height;
  330. break;
  331. case OsEventType::EXIT:
  332. exit = true;
  333. break;
  334. case OsEventType::PAUSE:
  335. pause();
  336. break;
  337. case OsEventType::RESUME:
  338. unpause();
  339. break;
  340. case OsEventType::TEXT:
  341. break;
  342. default:
  343. CE_FATAL("Unknown OS event");
  344. break;
  345. }
  346. }
  347. return exit;
  348. }
  349. void Device::set_timestep_policy(TimestepPolicy::Enum tp)
  350. {
  351. if (_timestep_policy == tp)
  352. return;
  353. _timestep_policy = tp;
  354. }
  355. void Device::set_timestep_smoothing(u32 num_samples, u32 num_outliers, f32 average_cap)
  356. {
  357. _delta_time_filter.set_smoothing(num_samples, num_outliers, average_cap);
  358. }
  359. bool Device::frame()
  360. {
  361. if (CE_UNLIKELY(process_events() || _quit))
  362. return true;
  363. const s64 time = time::now();
  364. const s64 raw_dt_ticks = time - _last_time;
  365. const f32 raw_dt = f32(time::seconds(raw_dt_ticks));
  366. _last_time = time;
  367. profiler_globals::clear();
  368. RECORD_FLOAT("device.dt", raw_dt);
  369. RECORD_FLOAT("device.fps", 1.0f/raw_dt);
  370. f32 dt;
  371. if (_timestep_policy == TimestepPolicy::SMOOTHED) {
  372. f32 smoothed_dt = _delta_time_filter.filter(raw_dt_ticks);
  373. RECORD_FLOAT("device.smoothed_dt", smoothed_dt);
  374. RECORD_FLOAT("device.smoothed_fps", 1.0f/smoothed_dt);
  375. dt = smoothed_dt;
  376. } else {
  377. dt = raw_dt;
  378. }
  379. if (CE_UNLIKELY(_width != _prev_width || _height != _prev_height)) {
  380. _prev_width = _width;
  381. _prev_height = _height;
  382. bgfx::reset(_width, _height, (_boot_config.vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE));
  383. _pipeline->reset(_width, _height);
  384. // Force pipeline reset in one cycle.
  385. bgfx::frame();
  386. bgfx::frame();
  387. // Force redraw.
  388. ++_needs_draw;
  389. }
  390. // Only block if redraw is not needed.
  391. const bool sync = !_needs_draw;
  392. #if !CROWN_PLATFORM_EMSCRIPTEN
  393. _console_server->execute_message_handlers(sync);
  394. #endif
  395. if (CE_UNLIKELY(!_needs_draw))
  396. return false;
  397. if (CE_LIKELY(!_paused)) {
  398. _resource_manager->complete_requests();
  399. {
  400. const s64 t0 = time::now();
  401. LuaStack stack(_lua_environment->L);
  402. stack.push_float(dt);
  403. _lua_environment->call_global("update", 1);
  404. RECORD_FLOAT("lua.update", f32(time::seconds(time::now() - t0)));
  405. }
  406. {
  407. const s64 t0 = time::now();
  408. LuaStack stack(_lua_environment->L);
  409. stack.push_float(dt);
  410. _lua_environment->call_global("render", 1);
  411. RECORD_FLOAT("lua.render", f32(time::seconds(time::now() - t0)));
  412. }
  413. if (_bgfx_callback->_screenshot_ready) {
  414. _bgfx_callback->_screenshot_ready = 0;
  415. LuaStack stack(_lua_environment->L);
  416. stack.push_string(_bgfx_callback->_screenshot_path.c_str());
  417. _lua_environment->call_global("screenshot", 1);
  418. }
  419. }
  420. _lua_environment->reset_temporaries();
  421. _input_manager->update();
  422. const bgfx::Stats *stats = bgfx::getStats();
  423. RECORD_FLOAT("bgfx.gpu_time", f32(f64(stats->gpuTimeEnd - stats->gpuTimeBegin)/stats->gpuTimerFreq));
  424. RECORD_FLOAT("bgfx.cpu_time", f32(f64(stats->cpuTimeEnd - stats->cpuTimeBegin)/stats->cpuTimerFreq));
  425. profiler_globals::flush();
  426. graph_globals::draw_all(_width, _height);
  427. _pipeline->render(_width, _height);
  428. bgfx::frame();
  429. if (_needs_draw-- == 1)
  430. _needs_draw = (int)!_options._pumped;
  431. return false;
  432. }
  433. void Device::run()
  434. {
  435. s64 run_t0 = time::now();
  436. _console_server->register_command_name("pause", "Pause the engine.", device_command_pause, this);
  437. _console_server->register_command_name("unpause", "Resume the engine.", device_command_unpause, this);
  438. _console_server->register_command_name("game", "Pause/resume the engine.", device_command_game, this);
  439. _console_server->register_command_name("crash", "Crash the engine.", device_command_crash, this);
  440. _console_server->register_message_type("resize", device_message_resize, this);
  441. _console_server->register_message_type("frame", device_message_frame, this);
  442. _console_server->register_message_type("quit", device_message_quit, this);
  443. _console_server->register_message_type("refresh", device_message_refresh, this);
  444. #if !CROWN_PLATFORM_EMSCRIPTEN
  445. _console_server->listen(_options._console_port, _options._wait_console);
  446. #endif
  447. bool is_bundle = true;
  448. #if CROWN_PLATFORM_ANDROID
  449. _data_filesystem = CE_NEW(_allocator, FilesystemApk)(default_allocator(), const_cast<AAssetManager *>((AAssetManager *)_options._asset_manager));
  450. #else
  451. _data_filesystem = CE_NEW(_allocator, FilesystemDisk)(default_allocator());
  452. {
  453. char cwd[1024];
  454. const char *data_dir = NULL;
  455. if (_options._bundle_dir.empty() && _options._data_dir.empty()) {
  456. data_dir = os::getcwd(cwd, sizeof(cwd));
  457. } else {
  458. if (!_options._bundle_dir.empty()) {
  459. data_dir = _options._bundle_dir.c_str();
  460. } else {
  461. is_bundle = false;
  462. if (!_options._data_dir.empty())
  463. data_dir = _options._data_dir.c_str();
  464. else
  465. data_dir = os::getcwd(cwd, sizeof(cwd));
  466. }
  467. }
  468. ((FilesystemDisk *)_data_filesystem)->set_prefix(data_dir);
  469. }
  470. #endif // if CROWN_PLATFORM_ANDROID
  471. logi(DEVICE, "Crown %s %s %s", CROWN_VERSION, CROWN_PLATFORM_NAME, CROWN_ARCH_NAME);
  472. profiler_globals::init();
  473. _shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
  474. namespace smr = state_machine_internal;
  475. namespace cor = config_resource_internal;
  476. namespace ftr = font_resource_internal;
  477. namespace lur = lua_resource_internal;
  478. namespace lvr = level_resource_internal;
  479. namespace mhr = mesh_resource_internal;
  480. namespace mtr = material_resource_internal;
  481. namespace pcr = physics_config_resource_internal;
  482. namespace pkr = package_resource_internal;
  483. namespace sar = sprite_animation_resource_internal;
  484. namespace sdr = sound_resource_internal;
  485. namespace shr = shader_resource_internal;
  486. namespace spr = sprite_resource_internal;
  487. namespace txr = texture_resource_internal;
  488. namespace utr = unit_resource_internal;
  489. _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_data_filesystem, is_bundle);
  490. _resource_loader->register_fallback(RESOURCE_TYPE_TEXTURE, STRING_ID_64("core/fallback/fallback", 0xd09058ae71962248));
  491. _resource_loader->register_fallback(RESOURCE_TYPE_MATERIAL, STRING_ID_64("core/fallback/fallback", 0xd09058ae71962248));
  492. _resource_loader->register_fallback(RESOURCE_TYPE_UNIT, STRING_ID_64("core/fallback/fallback", 0xd09058ae71962248));
  493. _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
  494. _resource_manager->register_type(RESOURCE_TYPE_CONFIG, RESOURCE_VERSION_CONFIG, cor::load, cor::unload, NULL, NULL);
  495. _resource_manager->register_type(RESOURCE_TYPE_FONT, RESOURCE_VERSION_FONT, NULL, NULL, NULL, NULL);
  496. _resource_manager->register_type(RESOURCE_TYPE_LEVEL, RESOURCE_VERSION_LEVEL, NULL, NULL, NULL, NULL);
  497. _resource_manager->register_type(RESOURCE_TYPE_MATERIAL, RESOURCE_VERSION_MATERIAL, NULL, NULL, mtr::online, mtr::offline);
  498. _resource_manager->register_type(RESOURCE_TYPE_MESH, RESOURCE_VERSION_MESH, mhr::load, mhr::unload, mhr::online, mhr::offline);
  499. _resource_manager->register_type(RESOURCE_TYPE_MESH_SKELETON, RESOURCE_VERSION_MESH_SKELETON, NULL, NULL, NULL, NULL);
  500. _resource_manager->register_type(RESOURCE_TYPE_PACKAGE, RESOURCE_VERSION_PACKAGE, NULL, NULL, NULL, NULL);
  501. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS_CONFIG, RESOURCE_VERSION_PHYSICS_CONFIG, NULL, NULL, NULL, NULL);
  502. _resource_manager->register_type(RESOURCE_TYPE_SCRIPT, RESOURCE_VERSION_SCRIPT, NULL, NULL, NULL, NULL);
  503. _resource_manager->register_type(RESOURCE_TYPE_SHADER, RESOURCE_VERSION_SHADER, shr::load, shr::unload, shr::online, shr::offline);
  504. _resource_manager->register_type(RESOURCE_TYPE_SOUND, RESOURCE_VERSION_SOUND, NULL, NULL, NULL, NULL);
  505. _resource_manager->register_type(RESOURCE_TYPE_SPRITE, RESOURCE_VERSION_SPRITE, NULL, NULL, NULL, NULL);
  506. _resource_manager->register_type(RESOURCE_TYPE_SPRITE_ANIMATION, RESOURCE_VERSION_SPRITE_ANIMATION, NULL, NULL, NULL, NULL);
  507. _resource_manager->register_type(RESOURCE_TYPE_STATE_MACHINE, RESOURCE_VERSION_STATE_MACHINE, NULL, NULL, NULL, NULL);
  508. _resource_manager->register_type(RESOURCE_TYPE_TEXTURE, RESOURCE_VERSION_TEXTURE, txr::load, txr::unload, txr::online, txr::offline);
  509. _resource_manager->register_type(RESOURCE_TYPE_UNIT, RESOURCE_VERSION_UNIT, NULL, NULL, NULL, NULL);
  510. _material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager, *_shader_manager);
  511. // Read config
  512. {
  513. TempAllocator512 ta;
  514. DynamicString boot_dir(ta);
  515. if (_options._boot_dir != NULL) {
  516. boot_dir += _options._boot_dir;
  517. boot_dir += '/';
  518. }
  519. boot_dir += CROWN_BOOT_CONFIG;
  520. const StringId64 config_name(boot_dir.c_str());
  521. while (!_resource_manager->try_load(PACKAGE_RESOURCE_NONE, RESOURCE_TYPE_CONFIG, config_name, 0)) {
  522. _resource_manager->complete_requests();
  523. #if CROWN_PLATFORM_EMSCRIPTEN
  524. os::sleep(16);
  525. #endif
  526. }
  527. while (!_resource_manager->can_get(RESOURCE_TYPE_CONFIG, config_name)) {
  528. _resource_manager->complete_requests();
  529. #if CROWN_PLATFORM_EMSCRIPTEN
  530. os::sleep(16);
  531. #endif
  532. }
  533. _boot_config.parse((const char *)_resource_manager->get(RESOURCE_TYPE_CONFIG, config_name));
  534. _resource_manager->unload(RESOURCE_TYPE_CONFIG, config_name);
  535. }
  536. // Init all remaining subsystems
  537. _display = display::create(_allocator);
  538. #if !CROWN_PLATFORM_EMSCRIPTEN
  539. if (_options._window_width.has_changed() || _options._window_height.has_changed()) {
  540. _width = _options._window_width.value();
  541. _height = _options._window_height.value();
  542. } else {
  543. _width = _boot_config.window_w;
  544. _height = _boot_config.window_h;
  545. }
  546. #endif
  547. _window = window::create(_allocator);
  548. _window->open(_options._window_x
  549. , _options._window_y
  550. , _width
  551. , _height
  552. , _options._parent_window
  553. );
  554. _window->set_title(_boot_config.window_title.c_str());
  555. _window->set_fullscreen(_boot_config.fullscreen);
  556. if (!_options._hidden)
  557. _window->show();
  558. _bgfx_allocator = CE_NEW(_allocator, BgfxAllocator)(default_allocator());
  559. _bgfx_callback = CE_NEW(_allocator, BgfxCallback)(default_allocator());
  560. bgfx::Init init;
  561. init.resolution.width = _width;
  562. init.resolution.height = _height;
  563. init.resolution.reset = _boot_config.vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE;
  564. init.callback = _bgfx_callback;
  565. init.allocator = _bgfx_allocator;
  566. init.platformData.ndt = _window->native_display();
  567. init.platformData.nwh = _window->native_handle();
  568. init.vendorId = BGFX_PCI_ID_NONE;
  569. #if CROWN_PLATFORM_ANDROID || CROWN_PLATFORM_EMSCRIPTEN
  570. init.type = bgfx::RendererType::OpenGLES;
  571. #elif CROWN_PLATFORM_LINUX
  572. init.type = bgfx::RendererType::OpenGL;
  573. #elif CROWN_PLATFORM_WINDOWS
  574. init.type = bgfx::RendererType::Direct3D11;
  575. #else
  576. #error "Unknown platform"
  577. #endif
  578. bgfx::init(init);
  579. _input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
  580. _unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
  581. _lua_environment = CE_NEW(_allocator, LuaEnvironment)();
  582. _lua_environment->register_console_commands(*_console_server);
  583. audio_globals::init();
  584. physics_globals::init(_allocator);
  585. ResourcePackage *boot_package = create_resource_package(_boot_config.boot_package_name);
  586. boot_package->load();
  587. boot_package->flush();
  588. _lua_environment->load_libs();
  589. _lua_environment->require(_boot_config.boot_script_name.c_str());
  590. _lua_environment->execute_string(_options._lua_string.c_str());
  591. _pipeline = CE_NEW(_allocator, Pipeline)(*_shader_manager);
  592. _pipeline->create(_width, _height);
  593. graph_globals::init(_allocator, *_pipeline, *_console_server);
  594. logi(DEVICE, "Initialized in " TIME_FMT, time::seconds(time::now() - run_t0));
  595. _lua_environment->call_global("init");
  596. _prev_width = _width;
  597. _prev_height = _height;
  598. _last_time = time::now();
  599. #if CROWN_PLATFORM_EMSCRIPTEN
  600. emscripten_set_main_loop_arg([](void *thiz) { ((Device *)thiz)->frame(); }, this, 0, -1);
  601. #else
  602. while (!frame()) { }
  603. #endif
  604. _lua_environment->call_global("shutdown");
  605. boot_package->unload();
  606. destroy_resource_package(*boot_package);
  607. physics_globals::shutdown(_allocator);
  608. audio_globals::shutdown();
  609. graph_globals::shutdown();
  610. _pipeline->destroy();
  611. CE_DELETE(_allocator, _pipeline);
  612. CE_DELETE(_allocator, _lua_environment);
  613. CE_DELETE(_allocator, _unit_manager);
  614. CE_DELETE(_allocator, _input_manager);
  615. CE_DELETE(_allocator, _resource_manager);
  616. CE_DELETE(_allocator, _resource_loader);
  617. CE_DELETE(_allocator, _material_manager);
  618. CE_DELETE(_allocator, _shader_manager);
  619. bgfx::shutdown();
  620. CE_DELETE(_allocator, _bgfx_callback);
  621. CE_DELETE(_allocator, _bgfx_allocator);
  622. _window->close();
  623. window::destroy(_allocator, *_window);
  624. display::destroy(_allocator, *_display);
  625. CE_DELETE(_allocator, _data_filesystem);
  626. profiler_globals::shutdown();
  627. _allocator.clear();
  628. }
  629. void Device::quit()
  630. {
  631. _quit = true;
  632. }
  633. int Device::argc() const
  634. {
  635. return _options._argc;
  636. }
  637. const char **Device::argv() const
  638. {
  639. return (const char **)_options._argv;
  640. }
  641. void Device::pause()
  642. {
  643. _paused = true;
  644. logi(DEVICE, "Paused");
  645. }
  646. void Device::unpause()
  647. {
  648. _paused = false;
  649. logi(DEVICE, "Unpaused");
  650. }
  651. void Device::resolution(u16 &width, u16 &height)
  652. {
  653. width = _width;
  654. height = _height;
  655. }
  656. void Device::render(World &world, UnitId camera_unit)
  657. {
  658. const f32 aspect_ratio = (_boot_config.aspect_ratio == -1.0f
  659. ? (f32)_width/(f32)_height
  660. : _boot_config.aspect_ratio
  661. );
  662. CameraInstance camera = world.camera_instance(camera_unit);
  663. const Matrix4x4 view = world.camera_view_matrix(camera);
  664. const Matrix4x4 proj = world.camera_projection_matrix(camera, aspect_ratio);
  665. const bgfx::Caps *caps = bgfx::getCaps();
  666. f32 bx_ortho[16];
  667. bx::mtxOrtho(bx_ortho, 0, _width, 0, _height, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth, bx::Handedness::Right);
  668. Matrix4x4 ortho_proj = from_array(bx_ortho);
  669. bgfx::setViewClear(VIEW_SPRITE_0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x080808ff, 1.0f, 0);
  670. bgfx::setViewClear(VIEW_SELECTION, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, UNIT_INVALID._idx, 1.0f, 0);
  671. bgfx::setViewTransform(VIEW_SPRITE_0, to_float_ptr(view), to_float_ptr(proj));
  672. bgfx::setViewTransform(VIEW_SPRITE_1, to_float_ptr(view), to_float_ptr(proj));
  673. bgfx::setViewTransform(VIEW_SPRITE_2, to_float_ptr(view), to_float_ptr(proj));
  674. bgfx::setViewTransform(VIEW_SPRITE_3, to_float_ptr(view), to_float_ptr(proj));
  675. bgfx::setViewTransform(VIEW_SPRITE_4, to_float_ptr(view), to_float_ptr(proj));
  676. bgfx::setViewTransform(VIEW_SPRITE_5, to_float_ptr(view), to_float_ptr(proj));
  677. bgfx::setViewTransform(VIEW_SPRITE_6, to_float_ptr(view), to_float_ptr(proj));
  678. bgfx::setViewTransform(VIEW_SPRITE_7, to_float_ptr(view), to_float_ptr(proj));
  679. bgfx::setViewTransform(VIEW_MESH, to_float_ptr(view), to_float_ptr(proj));
  680. bgfx::setViewTransform(VIEW_WORLD_GUI, to_float_ptr(view), to_float_ptr(proj));
  681. bgfx::setViewTransform(VIEW_DEBUG, to_float_ptr(view), to_float_ptr(proj));
  682. bgfx::setViewTransform(VIEW_SELECTION, to_float_ptr(view), to_float_ptr(proj));
  683. bgfx::setViewTransform(VIEW_SCREEN_GUI, to_float_ptr(MATRIX4X4_IDENTITY), to_float_ptr(ortho_proj));
  684. f32 graph_ortho[16];
  685. bx::mtxOrtho(graph_ortho
  686. , -_width / 2.0f
  687. , _width / 2.0f
  688. , -_height / 2.0f
  689. , _height / 2.0f
  690. , 0.0f
  691. , 1.0f
  692. , 0.0f
  693. , caps->homogeneousDepth
  694. , bx::Handedness::Right
  695. );
  696. bgfx::setViewTransform(VIEW_GRAPH, to_float_ptr(MATRIX4X4_IDENTITY), to_float_ptr(from_array(graph_ortho)));
  697. bgfx::setViewRect(VIEW_SPRITE_0, 0, 0, _width, _height);
  698. bgfx::setViewRect(VIEW_SPRITE_1, 0, 0, _width, _height);
  699. bgfx::setViewRect(VIEW_SPRITE_2, 0, 0, _width, _height);
  700. bgfx::setViewRect(VIEW_SPRITE_3, 0, 0, _width, _height);
  701. bgfx::setViewRect(VIEW_SPRITE_4, 0, 0, _width, _height);
  702. bgfx::setViewRect(VIEW_SPRITE_5, 0, 0, _width, _height);
  703. bgfx::setViewRect(VIEW_SPRITE_6, 0, 0, _width, _height);
  704. bgfx::setViewRect(VIEW_SPRITE_7, 0, 0, _width, _height);
  705. bgfx::setViewRect(VIEW_MESH, 0, 0, _width, _height);
  706. bgfx::setViewRect(VIEW_WORLD_GUI, 0, 0, _width, _height);
  707. bgfx::setViewRect(VIEW_DEBUG, 0, 0, _width, _height);
  708. bgfx::setViewRect(VIEW_SELECTION, 0, 0, _width, _height);
  709. bgfx::setViewRect(VIEW_OUTLINE, 0, 0, _width, _height);
  710. bgfx::setViewRect(VIEW_SCREEN_GUI, 0, 0, _width, _height);
  711. bgfx::setViewRect(VIEW_GRAPH, 0, 0, _width, _height);
  712. bgfx::setViewMode(VIEW_SPRITE_0, bgfx::ViewMode::DepthAscending);
  713. bgfx::setViewMode(VIEW_SPRITE_1, bgfx::ViewMode::DepthAscending);
  714. bgfx::setViewMode(VIEW_SPRITE_2, bgfx::ViewMode::DepthAscending);
  715. bgfx::setViewMode(VIEW_SPRITE_3, bgfx::ViewMode::DepthAscending);
  716. bgfx::setViewMode(VIEW_SPRITE_4, bgfx::ViewMode::DepthAscending);
  717. bgfx::setViewMode(VIEW_SPRITE_5, bgfx::ViewMode::DepthAscending);
  718. bgfx::setViewMode(VIEW_SPRITE_6, bgfx::ViewMode::DepthAscending);
  719. bgfx::setViewMode(VIEW_SPRITE_7, bgfx::ViewMode::DepthAscending);
  720. bgfx::setViewMode(VIEW_WORLD_GUI, bgfx::ViewMode::DepthDescending);
  721. bgfx::setViewMode(VIEW_SCREEN_GUI, bgfx::ViewMode::DepthDescending);
  722. bgfx::setViewMode(VIEW_BLIT, bgfx::ViewMode::Sequential);
  723. bgfx::setViewFrameBuffer(VIEW_SPRITE_0, _pipeline->_main_frame_buffer);
  724. bgfx::setViewFrameBuffer(VIEW_SPRITE_1, _pipeline->_main_frame_buffer);
  725. bgfx::setViewFrameBuffer(VIEW_SPRITE_2, _pipeline->_main_frame_buffer);
  726. bgfx::setViewFrameBuffer(VIEW_SPRITE_3, _pipeline->_main_frame_buffer);
  727. bgfx::setViewFrameBuffer(VIEW_SPRITE_4, _pipeline->_main_frame_buffer);
  728. bgfx::setViewFrameBuffer(VIEW_SPRITE_5, _pipeline->_main_frame_buffer);
  729. bgfx::setViewFrameBuffer(VIEW_SPRITE_6, _pipeline->_main_frame_buffer);
  730. bgfx::setViewFrameBuffer(VIEW_SPRITE_7, _pipeline->_main_frame_buffer);
  731. bgfx::setViewFrameBuffer(VIEW_MESH, _pipeline->_main_frame_buffer);
  732. bgfx::setViewFrameBuffer(VIEW_WORLD_GUI, _pipeline->_main_frame_buffer);
  733. bgfx::setViewFrameBuffer(VIEW_DEBUG, _pipeline->_main_frame_buffer);
  734. bgfx::setViewFrameBuffer(VIEW_SELECTION, _pipeline->_selection_frame_buffer);
  735. bgfx::setViewFrameBuffer(VIEW_OUTLINE, _pipeline->_main_frame_buffer);
  736. bgfx::setViewFrameBuffer(VIEW_SCREEN_GUI, _pipeline->_main_frame_buffer);
  737. bgfx::setViewFrameBuffer(VIEW_GRAPH, _pipeline->_main_frame_buffer);
  738. bgfx::setViewFrameBuffer(VIEW_BLIT, BGFX_INVALID_HANDLE);
  739. bgfx::touch(VIEW_SPRITE_0);
  740. bgfx::touch(VIEW_SPRITE_1);
  741. bgfx::touch(VIEW_SPRITE_2);
  742. bgfx::touch(VIEW_SPRITE_3);
  743. bgfx::touch(VIEW_SPRITE_4);
  744. bgfx::touch(VIEW_SPRITE_5);
  745. bgfx::touch(VIEW_SPRITE_6);
  746. bgfx::touch(VIEW_SPRITE_7);
  747. bgfx::touch(VIEW_MESH);
  748. bgfx::touch(VIEW_WORLD_GUI);
  749. bgfx::touch(VIEW_DEBUG);
  750. bgfx::touch(VIEW_SELECTION);
  751. bgfx::touch(VIEW_OUTLINE);
  752. bgfx::touch(VIEW_SCREEN_GUI);
  753. bgfx::touch(VIEW_GRAPH);
  754. bgfx::touch(VIEW_BLIT);
  755. world.render(view);
  756. }
  757. World *Device::create_world()
  758. {
  759. World *world = CE_NEW(default_allocator(), World)(default_allocator()
  760. , *_resource_manager
  761. , *_shader_manager
  762. , *_material_manager
  763. , *_unit_manager
  764. , *_lua_environment
  765. , *_pipeline
  766. );
  767. list::add(world->_node, _worlds);
  768. return world;
  769. }
  770. void Device::destroy_world(World &world)
  771. {
  772. list::remove(world._node);
  773. CE_DELETE(default_allocator(), &world);
  774. }
  775. ResourcePackage *Device::create_resource_package(StringId64 id)
  776. {
  777. return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
  778. }
  779. void Device::destroy_resource_package(ResourcePackage &rp)
  780. {
  781. CE_DELETE(default_allocator(), &rp);
  782. }
  783. void Device::refresh(const char *json)
  784. {
  785. #if CROWN_CAN_RELOAD
  786. TempAllocator4096 ta;
  787. JsonObject obj(ta);
  788. JsonArray list(ta);
  789. DynamicString type(ta);
  790. sjson::parse(obj, json);
  791. bool refresh_lua = false;
  792. sjson::parse_array(list, obj["list"]);
  793. for (u32 i = 0; i < array::size(list); ++i) {
  794. DynamicString resource(ta);
  795. sjson::parse_string(resource, list[i]);
  796. const char *type = resource_type(resource.c_str());
  797. const u32 len = resource_name_length(type, resource.c_str());
  798. StringId64 resource_type(type);
  799. StringId64 resource_name(resource.c_str(), len);
  800. bool is_type_reloadable = resource_type == RESOURCE_TYPE_SCRIPT
  801. || resource_type == RESOURCE_TYPE_TEXTURE
  802. || resource_type == RESOURCE_TYPE_SHADER
  803. || resource_type == RESOURCE_TYPE_MATERIAL
  804. ;
  805. if (is_type_reloadable && _resource_manager->can_get(resource_type, resource_name)) {
  806. const void *old_resource = _resource_manager->get(resource_type, resource_name);
  807. const void *new_resource = _resource_manager->reload(resource_type, resource_name);
  808. if (resource_type == RESOURCE_TYPE_SCRIPT) {
  809. refresh_lua = true;
  810. } else if (resource_type == RESOURCE_TYPE_TEXTURE) {
  811. _material_manager->reload_textures((TextureResource *)old_resource, (TextureResource *)new_resource);
  812. } else if (resource_type == RESOURCE_TYPE_SHADER) {
  813. _pipeline->reload_shaders((ShaderResource *)old_resource, (ShaderResource *)new_resource);
  814. _material_manager->reload_shaders((ShaderResource *)old_resource, (ShaderResource *)new_resource);
  815. } else if (resource_type == RESOURCE_TYPE_MATERIAL) {
  816. ListNode *cur;
  817. list_for_each(cur, &_worlds)
  818. {
  819. World *w = (World *)container_of(cur, World, _node);
  820. w->reload_materials((MaterialResource *)old_resource, (MaterialResource *)new_resource);
  821. }
  822. }
  823. }
  824. }
  825. if (array::size(list)) {
  826. if (refresh_lua)
  827. _lua_environment->reload();
  828. }
  829. if (_paused)
  830. unpause();
  831. #else
  832. CE_UNUSED(json);
  833. #endif // if CROWN_CAN_RELOAD
  834. }
  835. void Device::screenshot(const char *path)
  836. {
  837. bgfx::requestScreenShot(BGFX_INVALID_HANDLE, path);
  838. ++device()->_needs_draw; // 1 frame for the request to be fulfilled.
  839. }
  840. Device *_device = NULL;
  841. void run(const DeviceOptions &opts)
  842. {
  843. CE_ASSERT(_device == NULL, "Crown already initialized");
  844. console_server_globals::init();
  845. _device = CE_NEW(default_allocator(), Device)(opts, *console_server());
  846. _device->run();
  847. CE_DELETE(default_allocator(), _device);
  848. _device = NULL;
  849. console_server_globals::shutdown();
  850. }
  851. Device *device()
  852. {
  853. return crown::_device;
  854. }
  855. } // namespace crown