os.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. /**************************************************************************/
  2. /* os.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "os.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/dir_access.h"
  33. #include "core/io/file_access.h"
  34. #include "core/io/json.h"
  35. #include "core/os/midi_driver.h"
  36. #include "core/version_generated.gen.h"
  37. #include <cstdarg>
  38. #ifdef MINGW_ENABLED
  39. #define MINGW_STDTHREAD_REDUNDANCY_WARNING
  40. #include "thirdparty/mingw-std-threads/mingw.thread.h"
  41. #define THREADING_NAMESPACE mingw_stdthread
  42. #else
  43. #include <thread>
  44. #define THREADING_NAMESPACE std
  45. #endif
  46. OS *OS::singleton = nullptr;
  47. uint64_t OS::target_ticks = 0;
  48. OS *OS::get_singleton() {
  49. return singleton;
  50. }
  51. uint64_t OS::get_ticks_msec() const {
  52. return get_ticks_usec() / 1000ULL;
  53. }
  54. double OS::get_unix_time() const {
  55. return 0;
  56. }
  57. void OS::_set_logger(CompositeLogger *p_logger) {
  58. if (_logger) {
  59. memdelete(_logger);
  60. }
  61. _logger = p_logger;
  62. }
  63. void OS::add_logger(Logger *p_logger) {
  64. if (!_logger) {
  65. Vector<Logger *> loggers;
  66. loggers.push_back(p_logger);
  67. _logger = memnew(CompositeLogger(loggers));
  68. } else {
  69. _logger->add_logger(p_logger);
  70. }
  71. }
  72. String OS::get_identifier() const {
  73. return get_name().to_lower();
  74. }
  75. void OS::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify, Logger::ErrorType p_type, const Vector<Ref<ScriptBacktrace>> &p_script_backtraces) {
  76. if (!_stderr_enabled) {
  77. return;
  78. }
  79. if (_logger) {
  80. _logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type, p_script_backtraces);
  81. }
  82. }
  83. void OS::print(const char *p_format, ...) {
  84. if (!_stdout_enabled) {
  85. return;
  86. }
  87. va_list argp;
  88. va_start(argp, p_format);
  89. if (_logger) {
  90. _logger->logv(p_format, argp, false);
  91. }
  92. va_end(argp);
  93. }
  94. void OS::print_rich(const char *p_format, ...) {
  95. if (!_stdout_enabled) {
  96. return;
  97. }
  98. va_list argp;
  99. va_start(argp, p_format);
  100. if (_logger) {
  101. _logger->logv(p_format, argp, false);
  102. }
  103. va_end(argp);
  104. }
  105. void OS::printerr(const char *p_format, ...) {
  106. if (!_stderr_enabled) {
  107. return;
  108. }
  109. va_list argp;
  110. va_start(argp, p_format);
  111. if (_logger) {
  112. _logger->logv(p_format, argp, true);
  113. }
  114. va_end(argp);
  115. }
  116. void OS::alert(const String &p_alert, const String &p_title) {
  117. fprintf(stderr, "%s: %s\n", p_title.utf8().get_data(), p_alert.utf8().get_data());
  118. }
  119. void OS::set_low_processor_usage_mode(bool p_enabled) {
  120. low_processor_usage_mode = p_enabled;
  121. }
  122. bool OS::is_in_low_processor_usage_mode() const {
  123. return low_processor_usage_mode;
  124. }
  125. void OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
  126. low_processor_usage_mode_sleep_usec = p_usec;
  127. }
  128. int OS::get_low_processor_usage_mode_sleep_usec() const {
  129. return low_processor_usage_mode_sleep_usec;
  130. }
  131. void OS::set_delta_smoothing(bool p_enabled) {
  132. _delta_smoothing_enabled = p_enabled;
  133. }
  134. bool OS::is_delta_smoothing_enabled() const {
  135. return _delta_smoothing_enabled;
  136. }
  137. String OS::get_executable_path() const {
  138. return _execpath;
  139. }
  140. int OS::get_process_id() const {
  141. return -1;
  142. }
  143. bool OS::is_stdout_verbose() const {
  144. return _verbose_stdout;
  145. }
  146. bool OS::is_stdout_debug_enabled() const {
  147. return _debug_stdout;
  148. }
  149. bool OS::is_stdout_enabled() const {
  150. return _stdout_enabled;
  151. }
  152. bool OS::is_stderr_enabled() const {
  153. return _stderr_enabled;
  154. }
  155. void OS::set_stdout_enabled(bool p_enabled) {
  156. _stdout_enabled = p_enabled;
  157. }
  158. void OS::set_stderr_enabled(bool p_enabled) {
  159. _stderr_enabled = p_enabled;
  160. }
  161. String OS::multibyte_to_string(const String &p_encoding, const PackedByteArray &p_array) const {
  162. return String();
  163. }
  164. PackedByteArray OS::string_to_multibyte(const String &p_encoding, const String &p_string) const {
  165. return PackedByteArray();
  166. }
  167. int OS::get_exit_code() const {
  168. return _exit_code;
  169. }
  170. void OS::set_exit_code(int p_code) {
  171. _exit_code = p_code;
  172. }
  173. String OS::get_locale() const {
  174. return "en";
  175. }
  176. // Non-virtual helper to extract the 2 or 3-letter language code from
  177. // `get_locale()` in a way that's consistent for all platforms.
  178. String OS::get_locale_language() const {
  179. return get_locale().left(3).remove_char('_');
  180. }
  181. // Embedded PCK offset.
  182. uint64_t OS::get_embedded_pck_offset() const {
  183. return 0;
  184. }
  185. // Default boot screen rect scale mode is "Keep Aspect Centered"
  186. Rect2 OS::calculate_boot_screen_rect(const Size2 &p_window_size, const Size2 &p_imgrect_size) const {
  187. Rect2 screenrect;
  188. if (p_window_size.width > p_window_size.height) {
  189. // Scale horizontally.
  190. screenrect.size.y = p_window_size.height;
  191. screenrect.size.x = p_imgrect_size.x * p_window_size.height / p_imgrect_size.y;
  192. screenrect.position.x = (p_window_size.width - screenrect.size.x) / 2;
  193. } else {
  194. // Scale vertically.
  195. screenrect.size.x = p_window_size.width;
  196. screenrect.size.y = p_imgrect_size.y * p_window_size.width / p_imgrect_size.x;
  197. screenrect.position.y = (p_window_size.height - screenrect.size.y) / 2;
  198. }
  199. return screenrect;
  200. }
  201. // Helper function to ensure that a dir name/path will be valid on the OS
  202. String OS::get_safe_dir_name(const String &p_dir_name, bool p_allow_paths) const {
  203. String safe_dir_name = p_dir_name;
  204. Vector<String> invalid_chars = String(": * ? \" < > |").split(" ");
  205. if (p_allow_paths) {
  206. // Dir separators are allowed, but disallow ".." to avoid going up the filesystem
  207. invalid_chars.push_back("..");
  208. safe_dir_name = safe_dir_name.replace_char('\\', '/').replace("//", "/").strip_edges();
  209. } else {
  210. invalid_chars.push_back("/");
  211. invalid_chars.push_back("\\");
  212. safe_dir_name = safe_dir_name.strip_edges();
  213. // These directory names are invalid.
  214. if (safe_dir_name == ".") {
  215. safe_dir_name = "dot";
  216. } else if (safe_dir_name == "..") {
  217. safe_dir_name = "twodots";
  218. }
  219. }
  220. for (int i = 0; i < invalid_chars.size(); i++) {
  221. safe_dir_name = safe_dir_name.replace(invalid_chars[i], "-");
  222. }
  223. // Trim trailing periods from the returned value as it's not valid for folder names on Windows.
  224. // This check is still applied on non-Windows platforms so the returned value is consistent across platforms.
  225. return safe_dir_name.rstrip(".");
  226. }
  227. // Path to data, config, cache, etc. OS-specific folders
  228. // Get properly capitalized engine name for system paths
  229. String OS::get_godot_dir_name() const {
  230. // Default to lowercase, so only override when different case is needed
  231. return String(GODOT_VERSION_SHORT_NAME).to_lower();
  232. }
  233. // OS equivalent of XDG_DATA_HOME
  234. String OS::get_data_path() const {
  235. return ".";
  236. }
  237. // OS equivalent of XDG_CONFIG_HOME
  238. String OS::get_config_path() const {
  239. return ".";
  240. }
  241. // OS equivalent of XDG_CACHE_HOME
  242. String OS::get_cache_path() const {
  243. return ".";
  244. }
  245. String OS::get_temp_path() const {
  246. return ".";
  247. }
  248. // Path to macOS .app bundle resources
  249. String OS::get_bundle_resource_dir() const {
  250. return ".";
  251. }
  252. // Path to macOS .app bundle embedded icon
  253. String OS::get_bundle_icon_path() const {
  254. return String();
  255. }
  256. // OS specific path for user://
  257. String OS::get_user_data_dir(const String &p_user_dir) const {
  258. return ".";
  259. }
  260. String OS::get_user_data_dir() const {
  261. String appname = get_safe_dir_name(GLOBAL_GET("application/config/name"));
  262. if (!appname.is_empty()) {
  263. bool use_custom_dir = GLOBAL_GET("application/config/use_custom_user_dir");
  264. if (use_custom_dir) {
  265. String custom_dir = get_safe_dir_name(GLOBAL_GET("application/config/custom_user_dir_name"), true);
  266. if (custom_dir.is_empty()) {
  267. custom_dir = appname;
  268. }
  269. return get_user_data_dir(custom_dir);
  270. } else {
  271. return get_user_data_dir(get_godot_dir_name().path_join("app_userdata").path_join(appname));
  272. }
  273. } else {
  274. return get_user_data_dir(get_godot_dir_name().path_join("app_userdata").path_join("[unnamed project]"));
  275. }
  276. }
  277. // Absolute path to res://
  278. String OS::get_resource_dir() const {
  279. return ProjectSettings::get_singleton()->get_resource_path();
  280. }
  281. // Access system-specific dirs like Documents, Downloads, etc.
  282. String OS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  283. return ".";
  284. }
  285. void OS::create_lock_file() {
  286. if (Engine::get_singleton()->is_recovery_mode_hint()) {
  287. return;
  288. }
  289. String lock_file_path = get_user_data_dir().path_join(".recovery_mode_lock");
  290. Ref<FileAccess> lock_file = FileAccess::open(lock_file_path, FileAccess::WRITE);
  291. if (lock_file.is_valid()) {
  292. lock_file->close();
  293. }
  294. }
  295. void OS::remove_lock_file() {
  296. String lock_file_path = get_user_data_dir().path_join(".recovery_mode_lock");
  297. DirAccess::remove_absolute(lock_file_path);
  298. }
  299. Error OS::shell_open(const String &p_uri) {
  300. return ERR_UNAVAILABLE;
  301. }
  302. Error OS::shell_show_in_file_manager(String p_path, bool p_open_folder) {
  303. p_path = p_path.trim_prefix("file://");
  304. if (!DirAccess::dir_exists_absolute(p_path)) {
  305. p_path = p_path.get_base_dir();
  306. }
  307. p_path = String("file://") + p_path;
  308. return shell_open(p_path);
  309. }
  310. // implement these with the canvas?
  311. uint64_t OS::get_static_memory_usage() const {
  312. return Memory::get_mem_usage();
  313. }
  314. uint64_t OS::get_static_memory_peak_usage() const {
  315. return Memory::get_mem_max_usage();
  316. }
  317. Error OS::set_cwd(const String &p_cwd) {
  318. return ERR_CANT_OPEN;
  319. }
  320. Dictionary OS::get_memory_info() const {
  321. Dictionary meminfo;
  322. meminfo["physical"] = -1;
  323. meminfo["free"] = -1;
  324. meminfo["available"] = -1;
  325. meminfo["stack"] = -1;
  326. return meminfo;
  327. }
  328. void OS::yield() {
  329. }
  330. void OS::ensure_user_data_dir() {
  331. String dd = get_user_data_dir();
  332. if (DirAccess::exists(dd)) {
  333. return;
  334. }
  335. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  336. Error err = da->make_dir_recursive(dd);
  337. ERR_FAIL_COND_MSG(err != OK, vformat("Error attempting to create data dir: %s.", dd));
  338. }
  339. String OS::get_model_name() const {
  340. return "GenericDevice";
  341. }
  342. void OS::set_cmdline(const char *p_execpath, const List<String> &p_args, const List<String> &p_user_args) {
  343. _execpath = String::utf8(p_execpath);
  344. _cmdline = p_args;
  345. _user_args = p_user_args;
  346. }
  347. String OS::get_unique_id() const {
  348. return "";
  349. }
  350. int OS::get_processor_count() const {
  351. return THREADING_NAMESPACE::thread::hardware_concurrency();
  352. }
  353. String OS::get_processor_name() const {
  354. return "";
  355. }
  356. void OS::set_has_server_feature_callback(HasServerFeatureCallback p_callback) {
  357. has_server_feature_callback = p_callback;
  358. }
  359. bool OS::has_feature(const String &p_feature) {
  360. // Feature tags are always lowercase for consistency.
  361. if (p_feature == get_identifier()) {
  362. return true;
  363. }
  364. if (p_feature == "movie") {
  365. return _writing_movie;
  366. }
  367. #ifdef DEBUG_ENABLED
  368. if (p_feature == "debug") {
  369. return true;
  370. }
  371. #endif // DEBUG_ENABLED
  372. #ifdef TOOLS_ENABLED
  373. if (p_feature == "editor") {
  374. return true;
  375. }
  376. if (p_feature == "editor_hint") {
  377. return _in_editor;
  378. } else if (p_feature == "editor_runtime") {
  379. return !_in_editor;
  380. } else if (p_feature == "embedded_in_editor") {
  381. return _embedded_in_editor;
  382. }
  383. #else
  384. if (p_feature == "template") {
  385. return true;
  386. }
  387. #ifdef DEBUG_ENABLED
  388. if (p_feature == "template_debug") {
  389. return true;
  390. }
  391. #else
  392. if (p_feature == "template_release" || p_feature == "release") {
  393. return true;
  394. }
  395. #endif // DEBUG_ENABLED
  396. #endif // TOOLS_ENABLED
  397. #ifdef REAL_T_IS_DOUBLE
  398. if (p_feature == "double") {
  399. return true;
  400. }
  401. #else
  402. if (p_feature == "single") {
  403. return true;
  404. }
  405. #endif // REAL_T_IS_DOUBLE
  406. if (sizeof(void *) == 8 && p_feature == "64") {
  407. return true;
  408. }
  409. if (sizeof(void *) == 4 && p_feature == "32") {
  410. return true;
  411. }
  412. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(_M_X64)
  413. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64)
  414. #if defined(MACOS_ENABLED)
  415. if (p_feature == "universal") {
  416. return true;
  417. }
  418. #endif
  419. if (p_feature == "x86_64") {
  420. return true;
  421. }
  422. #elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
  423. if (p_feature == "x86_32") {
  424. return true;
  425. }
  426. #endif
  427. if (p_feature == "x86") {
  428. return true;
  429. }
  430. #elif defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  431. #if defined(__aarch64__) || defined(_M_ARM64)
  432. #if defined(MACOS_ENABLED)
  433. if (p_feature == "universal") {
  434. return true;
  435. }
  436. #endif
  437. if (p_feature == "arm64") {
  438. return true;
  439. }
  440. #elif defined(__arm__) || defined(_M_ARM)
  441. if (p_feature == "arm32") {
  442. return true;
  443. }
  444. #endif
  445. #if defined(__ARM_ARCH_7A__)
  446. if (p_feature == "armv7a" || p_feature == "armv7") {
  447. return true;
  448. }
  449. #endif
  450. #if defined(__ARM_ARCH_7S__)
  451. if (p_feature == "armv7s" || p_feature == "armv7") {
  452. return true;
  453. }
  454. #endif
  455. if (p_feature == "arm") {
  456. return true;
  457. }
  458. #elif defined(__riscv)
  459. #if __riscv_xlen == 8
  460. if (p_feature == "rv64") {
  461. return true;
  462. }
  463. #endif
  464. if (p_feature == "riscv") {
  465. return true;
  466. }
  467. #elif defined(__powerpc__)
  468. #if defined(__powerpc64__)
  469. if (p_feature == "ppc64") {
  470. return true;
  471. }
  472. #endif
  473. if (p_feature == "ppc") {
  474. return true;
  475. }
  476. #elif defined(__wasm__)
  477. #if defined(__wasm64__)
  478. if (p_feature == "wasm64") {
  479. return true;
  480. }
  481. #elif defined(__wasm32__)
  482. if (p_feature == "wasm32") {
  483. return true;
  484. }
  485. #endif
  486. if (p_feature == "wasm") {
  487. return true;
  488. }
  489. #elif defined(__loongarch64)
  490. if (p_feature == "loongarch64") {
  491. return true;
  492. }
  493. #endif
  494. #if defined(IOS_SIMULATOR)
  495. if (p_feature == "simulator") {
  496. return true;
  497. }
  498. #endif
  499. #ifdef THREADS_ENABLED
  500. if (p_feature == "threads") {
  501. return true;
  502. }
  503. #else
  504. if (p_feature == "nothreads") {
  505. return true;
  506. }
  507. #endif
  508. if (_check_internal_feature_support(p_feature)) {
  509. return true;
  510. }
  511. if (has_server_feature_callback && has_server_feature_callback(p_feature)) {
  512. return true;
  513. }
  514. if (ProjectSettings::get_singleton()->has_custom_feature(p_feature)) {
  515. return true;
  516. }
  517. return false;
  518. }
  519. bool OS::is_sandboxed() const {
  520. return false;
  521. }
  522. void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) {
  523. restart_on_exit = p_restart;
  524. restart_commandline = p_restart_arguments;
  525. }
  526. bool OS::is_restart_on_exit_set() const {
  527. return restart_on_exit;
  528. }
  529. List<String> OS::get_restart_on_exit_arguments() const {
  530. return restart_commandline;
  531. }
  532. PackedStringArray OS::get_connected_midi_inputs() {
  533. if (MIDIDriver::get_singleton()) {
  534. return MIDIDriver::get_singleton()->get_connected_inputs();
  535. }
  536. PackedStringArray list;
  537. ERR_FAIL_V_MSG(list, vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  538. }
  539. void OS::open_midi_inputs() {
  540. if (MIDIDriver::get_singleton()) {
  541. MIDIDriver::get_singleton()->open();
  542. } else {
  543. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  544. }
  545. }
  546. void OS::close_midi_inputs() {
  547. if (MIDIDriver::get_singleton()) {
  548. MIDIDriver::get_singleton()->close();
  549. } else {
  550. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  551. }
  552. }
  553. void OS::add_frame_delay(bool p_can_draw) {
  554. const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  555. if (frame_delay) {
  556. // Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
  557. // the actual frame time into account.
  558. // Due to the high fluctuation of the actual sleep duration, it's not recommended
  559. // to use this as a FPS limiter.
  560. delay_usec(frame_delay * 1000);
  561. }
  562. // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
  563. // previous frame time into account for a smoother result.
  564. uint64_t dynamic_delay = 0;
  565. if (is_in_low_processor_usage_mode() || !p_can_draw) {
  566. dynamic_delay = get_low_processor_usage_mode_sleep_usec();
  567. }
  568. const int max_fps = Engine::get_singleton()->get_max_fps();
  569. if (max_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  570. // Override the low processor usage mode sleep delay if the target FPS is lower.
  571. dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / max_fps));
  572. }
  573. if (dynamic_delay > 0) {
  574. target_ticks += dynamic_delay;
  575. uint64_t current_ticks = get_ticks_usec();
  576. if (current_ticks < target_ticks) {
  577. delay_usec(target_ticks - current_ticks);
  578. }
  579. current_ticks = get_ticks_usec();
  580. target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
  581. }
  582. }
  583. Error OS::setup_remote_filesystem(const String &p_server_host, int p_port, const String &p_password, String &r_project_path) {
  584. return default_rfs.synchronize_with_server(p_server_host, p_port, p_password, r_project_path);
  585. }
  586. OS::PreferredTextureFormat OS::get_preferred_texture_format() const {
  587. #if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  588. return PREFERRED_TEXTURE_FORMAT_ETC2_ASTC; // By rule, ARM hardware uses ETC texture compression.
  589. #elif defined(__x86_64__) || defined(_M_X64) || defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)
  590. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // By rule, X86 hardware prefers S3TC and derivatives.
  591. #else
  592. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // Override in platform if needed.
  593. #endif
  594. }
  595. void OS::set_use_benchmark(bool p_use_benchmark) {
  596. use_benchmark = p_use_benchmark;
  597. }
  598. bool OS::is_use_benchmark_set() {
  599. return use_benchmark;
  600. }
  601. void OS::set_benchmark_file(const String &p_benchmark_file) {
  602. benchmark_file = p_benchmark_file;
  603. }
  604. String OS::get_benchmark_file() {
  605. return benchmark_file;
  606. }
  607. void OS::benchmark_begin_measure(const String &p_context, const String &p_what) {
  608. #ifdef TOOLS_ENABLED
  609. Pair<String, String> mark_key(p_context, p_what);
  610. ERR_FAIL_COND_MSG(benchmark_marks_from.has(mark_key), vformat("Benchmark key '%s:%s' already exists.", p_context, p_what));
  611. benchmark_marks_from[mark_key] = OS::get_singleton()->get_ticks_usec();
  612. #endif
  613. }
  614. void OS::benchmark_end_measure(const String &p_context, const String &p_what) {
  615. #ifdef TOOLS_ENABLED
  616. Pair<String, String> mark_key(p_context, p_what);
  617. ERR_FAIL_COND_MSG(!benchmark_marks_from.has(mark_key), vformat("Benchmark key '%s:%s' doesn't exist.", p_context, p_what));
  618. uint64_t total = OS::get_singleton()->get_ticks_usec() - benchmark_marks_from[mark_key];
  619. double total_f = double(total) / double(1000000);
  620. benchmark_marks_final[mark_key] = total_f;
  621. #endif
  622. }
  623. void OS::benchmark_dump() {
  624. #ifdef TOOLS_ENABLED
  625. if (!use_benchmark) {
  626. return;
  627. }
  628. if (!benchmark_file.is_empty()) {
  629. Ref<FileAccess> f = FileAccess::open(benchmark_file, FileAccess::WRITE);
  630. if (f.is_valid()) {
  631. Dictionary benchmark_marks;
  632. for (const KeyValue<Pair<String, String>, double> &E : benchmark_marks_final) {
  633. const String mark_key = vformat("[%s] %s", E.key.first, E.key.second);
  634. benchmark_marks[mark_key] = E.value;
  635. }
  636. Ref<JSON> json;
  637. json.instantiate();
  638. f->store_string(json->stringify(benchmark_marks, "\t", false, true));
  639. }
  640. } else {
  641. HashMap<String, String> results;
  642. for (const KeyValue<Pair<String, String>, double> &E : benchmark_marks_final) {
  643. if (E.key.first == "Startup" && !results.has(E.key.first)) {
  644. results.insert(E.key.first, "", true); // Hack to make sure "Startup" always comes first.
  645. }
  646. results[E.key.first] += vformat("\t\t- %s: %.3f msec.\n", E.key.second, (E.value * 1000));
  647. }
  648. print_line("BENCHMARK:");
  649. for (const KeyValue<String, String> &E : results) {
  650. print_line(vformat("\t[%s]\n%s", E.key, E.value));
  651. }
  652. }
  653. #endif
  654. }
  655. OS::OS() {
  656. singleton = this;
  657. Vector<Logger *> loggers;
  658. loggers.push_back(memnew(StdLogger));
  659. _set_logger(memnew(CompositeLogger(loggers)));
  660. }
  661. OS::~OS() {
  662. if (_logger) {
  663. memdelete(_logger);
  664. }
  665. singleton = nullptr;
  666. }