os.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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 (.icns file).
  253. String OS::get_bundle_icon_path() const {
  254. return String();
  255. }
  256. // Name of macOS .app bundle embedded icon (Liquid Glass asset name).
  257. String OS::get_bundle_icon_name() const {
  258. return String();
  259. }
  260. // OS specific path for user://
  261. String OS::get_user_data_dir(const String &p_user_dir) const {
  262. return ".";
  263. }
  264. String OS::get_user_data_dir() const {
  265. String appname = get_safe_dir_name(GLOBAL_GET("application/config/name"));
  266. if (!appname.is_empty()) {
  267. bool use_custom_dir = GLOBAL_GET("application/config/use_custom_user_dir");
  268. if (use_custom_dir) {
  269. String custom_dir = get_safe_dir_name(GLOBAL_GET("application/config/custom_user_dir_name"), true);
  270. if (custom_dir.is_empty()) {
  271. custom_dir = appname;
  272. }
  273. return get_user_data_dir(custom_dir);
  274. } else {
  275. return get_user_data_dir(get_godot_dir_name().path_join("app_userdata").path_join(appname));
  276. }
  277. } else {
  278. return get_user_data_dir(get_godot_dir_name().path_join("app_userdata").path_join("[unnamed project]"));
  279. }
  280. }
  281. // Absolute path to res://
  282. String OS::get_resource_dir() const {
  283. return ProjectSettings::get_singleton()->get_resource_path();
  284. }
  285. // Access system-specific dirs like Documents, Downloads, etc.
  286. String OS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  287. return ".";
  288. }
  289. void OS::create_lock_file() {
  290. if (Engine::get_singleton()->is_recovery_mode_hint()) {
  291. return;
  292. }
  293. String lock_file_path = get_user_data_dir().path_join(".recovery_mode_lock");
  294. Ref<FileAccess> lock_file = FileAccess::open(lock_file_path, FileAccess::WRITE);
  295. if (lock_file.is_valid()) {
  296. lock_file->close();
  297. }
  298. }
  299. void OS::remove_lock_file() {
  300. String lock_file_path = get_user_data_dir().path_join(".recovery_mode_lock");
  301. DirAccess::remove_absolute(lock_file_path);
  302. }
  303. Error OS::shell_open(const String &p_uri) {
  304. return ERR_UNAVAILABLE;
  305. }
  306. Error OS::shell_show_in_file_manager(String p_path, bool p_open_folder) {
  307. p_path = p_path.trim_prefix("file://");
  308. if (!DirAccess::dir_exists_absolute(p_path)) {
  309. p_path = p_path.get_base_dir();
  310. }
  311. p_path = String("file://") + p_path;
  312. return shell_open(p_path);
  313. }
  314. // implement these with the canvas?
  315. uint64_t OS::get_static_memory_usage() const {
  316. return Memory::get_mem_usage();
  317. }
  318. uint64_t OS::get_static_memory_peak_usage() const {
  319. return Memory::get_mem_max_usage();
  320. }
  321. Error OS::set_cwd(const String &p_cwd) {
  322. return ERR_CANT_OPEN;
  323. }
  324. Dictionary OS::get_memory_info() const {
  325. Dictionary meminfo;
  326. meminfo["physical"] = -1;
  327. meminfo["free"] = -1;
  328. meminfo["available"] = -1;
  329. meminfo["stack"] = -1;
  330. return meminfo;
  331. }
  332. void OS::yield() {
  333. }
  334. void OS::ensure_user_data_dir() {
  335. String dd = get_user_data_dir();
  336. if (DirAccess::exists(dd)) {
  337. return;
  338. }
  339. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  340. Error err = da->make_dir_recursive(dd);
  341. ERR_FAIL_COND_MSG(err != OK, vformat("Error attempting to create data dir: %s.", dd));
  342. }
  343. String OS::get_model_name() const {
  344. return "GenericDevice";
  345. }
  346. void OS::set_cmdline(const char *p_execpath, const List<String> &p_args, const List<String> &p_user_args) {
  347. _execpath = String::utf8(p_execpath);
  348. _cmdline = p_args;
  349. _user_args = p_user_args;
  350. }
  351. String OS::get_unique_id() const {
  352. return "";
  353. }
  354. int OS::get_processor_count() const {
  355. return THREADING_NAMESPACE::thread::hardware_concurrency();
  356. }
  357. String OS::get_processor_name() const {
  358. return "";
  359. }
  360. void OS::set_has_server_feature_callback(HasServerFeatureCallback p_callback) {
  361. has_server_feature_callback = p_callback;
  362. }
  363. bool OS::has_feature(const String &p_feature) {
  364. // Feature tags are always lowercase for consistency.
  365. if (p_feature == get_identifier()) {
  366. return true;
  367. }
  368. if (p_feature == "movie") {
  369. return _writing_movie;
  370. }
  371. #ifdef DEBUG_ENABLED
  372. if (p_feature == "debug") {
  373. return true;
  374. }
  375. #endif // DEBUG_ENABLED
  376. #ifdef TOOLS_ENABLED
  377. if (p_feature == "editor") {
  378. return true;
  379. }
  380. if (p_feature == "editor_hint") {
  381. return _in_editor;
  382. } else if (p_feature == "editor_runtime") {
  383. return !_in_editor;
  384. } else if (p_feature == "embedded_in_editor") {
  385. return _embedded_in_editor;
  386. }
  387. #else
  388. if (p_feature == "template") {
  389. return true;
  390. }
  391. #ifdef DEBUG_ENABLED
  392. if (p_feature == "template_debug") {
  393. return true;
  394. }
  395. #else
  396. if (p_feature == "template_release" || p_feature == "release") {
  397. return true;
  398. }
  399. #endif // DEBUG_ENABLED
  400. #endif // TOOLS_ENABLED
  401. #ifdef REAL_T_IS_DOUBLE
  402. if (p_feature == "double") {
  403. return true;
  404. }
  405. #else
  406. if (p_feature == "single") {
  407. return true;
  408. }
  409. #endif // REAL_T_IS_DOUBLE
  410. if (sizeof(void *) == 8 && p_feature == "64") {
  411. return true;
  412. }
  413. if (sizeof(void *) == 4 && p_feature == "32") {
  414. return true;
  415. }
  416. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(_M_X64)
  417. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64)
  418. #if defined(MACOS_ENABLED)
  419. if (p_feature == "universal") {
  420. return true;
  421. }
  422. #endif
  423. if (p_feature == "x86_64") {
  424. return true;
  425. }
  426. #elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
  427. if (p_feature == "x86_32") {
  428. return true;
  429. }
  430. #endif
  431. if (p_feature == "x86") {
  432. return true;
  433. }
  434. #elif defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  435. #if defined(__aarch64__) || defined(_M_ARM64)
  436. #if defined(MACOS_ENABLED)
  437. if (p_feature == "universal") {
  438. return true;
  439. }
  440. #endif
  441. if (p_feature == "arm64") {
  442. return true;
  443. }
  444. #elif defined(__arm__) || defined(_M_ARM)
  445. if (p_feature == "arm32") {
  446. return true;
  447. }
  448. #endif
  449. #if defined(__ARM_ARCH_7A__)
  450. if (p_feature == "armv7a" || p_feature == "armv7") {
  451. return true;
  452. }
  453. #endif
  454. #if defined(__ARM_ARCH_7S__)
  455. if (p_feature == "armv7s" || p_feature == "armv7") {
  456. return true;
  457. }
  458. #endif
  459. if (p_feature == "arm") {
  460. return true;
  461. }
  462. #elif defined(__riscv)
  463. #if __riscv_xlen == 8
  464. if (p_feature == "rv64") {
  465. return true;
  466. }
  467. #endif
  468. if (p_feature == "riscv") {
  469. return true;
  470. }
  471. #elif defined(__powerpc__)
  472. #if defined(__powerpc64__)
  473. if (p_feature == "ppc64") {
  474. return true;
  475. }
  476. #endif
  477. if (p_feature == "ppc") {
  478. return true;
  479. }
  480. #elif defined(__wasm__)
  481. #if defined(__wasm64__)
  482. if (p_feature == "wasm64") {
  483. return true;
  484. }
  485. #elif defined(__wasm32__)
  486. if (p_feature == "wasm32") {
  487. return true;
  488. }
  489. #endif
  490. if (p_feature == "wasm") {
  491. return true;
  492. }
  493. #elif defined(__loongarch64)
  494. if (p_feature == "loongarch64") {
  495. return true;
  496. }
  497. #endif
  498. #if defined(IOS_SIMULATOR) || defined(VISIONOS_SIMULATOR)
  499. if (p_feature == "simulator") {
  500. return true;
  501. }
  502. #endif
  503. if (p_feature == "threads") {
  504. #ifdef THREADS_ENABLED
  505. return true;
  506. #else
  507. return false;
  508. #endif
  509. }
  510. if (p_feature == "nothreads") {
  511. #ifdef THREADS_ENABLED
  512. return false;
  513. #else
  514. return true;
  515. #endif
  516. }
  517. if (_check_internal_feature_support(p_feature)) {
  518. return true;
  519. }
  520. if (has_server_feature_callback && has_server_feature_callback(p_feature)) {
  521. return true;
  522. }
  523. if (ProjectSettings::get_singleton()->has_custom_feature(p_feature)) {
  524. return true;
  525. }
  526. return false;
  527. }
  528. bool OS::is_sandboxed() const {
  529. return false;
  530. }
  531. void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) {
  532. restart_on_exit = p_restart;
  533. restart_commandline = p_restart_arguments;
  534. }
  535. bool OS::is_restart_on_exit_set() const {
  536. return restart_on_exit;
  537. }
  538. List<String> OS::get_restart_on_exit_arguments() const {
  539. return restart_commandline;
  540. }
  541. PackedStringArray OS::get_connected_midi_inputs() {
  542. if (MIDIDriver::get_singleton()) {
  543. return MIDIDriver::get_singleton()->get_connected_inputs();
  544. }
  545. PackedStringArray list;
  546. ERR_FAIL_V_MSG(list, vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  547. }
  548. void OS::open_midi_inputs() {
  549. if (MIDIDriver::get_singleton()) {
  550. MIDIDriver::get_singleton()->open();
  551. } else {
  552. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  553. }
  554. }
  555. void OS::close_midi_inputs() {
  556. if (MIDIDriver::get_singleton()) {
  557. MIDIDriver::get_singleton()->close();
  558. } else {
  559. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  560. }
  561. }
  562. uint64_t OS::get_frame_delay(bool p_can_draw) const {
  563. const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  564. // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
  565. // previous frame time into account for a smoother result.
  566. uint64_t dynamic_delay = 0;
  567. if (is_in_low_processor_usage_mode() || !p_can_draw) {
  568. dynamic_delay = get_low_processor_usage_mode_sleep_usec();
  569. }
  570. const int max_fps = Engine::get_singleton()->get_max_fps();
  571. if (max_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  572. // Override the low processor usage mode sleep delay if the target FPS is lower.
  573. dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / max_fps));
  574. }
  575. return frame_delay + dynamic_delay;
  576. }
  577. void OS::add_frame_delay(bool p_can_draw, bool p_wake_for_events) {
  578. const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  579. if (frame_delay) {
  580. // Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
  581. // the actual frame time into account.
  582. // Due to the high fluctuation of the actual sleep duration, it's not recommended
  583. // to use this as a FPS limiter.
  584. delay_usec(frame_delay * 1000);
  585. }
  586. // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
  587. // previous frame time into account for a smoother result.
  588. uint64_t dynamic_delay = 0;
  589. if (is_in_low_processor_usage_mode() || !p_can_draw) {
  590. dynamic_delay = get_low_processor_usage_mode_sleep_usec();
  591. }
  592. const int max_fps = Engine::get_singleton()->get_max_fps();
  593. if (max_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  594. // Override the low processor usage mode sleep delay if the target FPS is lower.
  595. dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / max_fps));
  596. }
  597. if (dynamic_delay > 0) {
  598. target_ticks += dynamic_delay;
  599. uint64_t current_ticks = get_ticks_usec();
  600. if (current_ticks < target_ticks) {
  601. delay_usec(target_ticks - current_ticks);
  602. }
  603. current_ticks = get_ticks_usec();
  604. target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
  605. }
  606. }
  607. Error OS::setup_remote_filesystem(const String &p_server_host, int p_port, const String &p_password, String &r_project_path) {
  608. return default_rfs.synchronize_with_server(p_server_host, p_port, p_password, r_project_path);
  609. }
  610. OS::PreferredTextureFormat OS::get_preferred_texture_format() const {
  611. #if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  612. return PREFERRED_TEXTURE_FORMAT_ETC2_ASTC; // By rule, ARM hardware uses ETC texture compression.
  613. #elif defined(__x86_64__) || defined(_M_X64) || defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)
  614. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // By rule, X86 hardware prefers S3TC and derivatives.
  615. #else
  616. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // Override in platform if needed.
  617. #endif
  618. }
  619. void OS::set_use_benchmark(bool p_use_benchmark) {
  620. use_benchmark = p_use_benchmark;
  621. }
  622. bool OS::is_use_benchmark_set() {
  623. return use_benchmark;
  624. }
  625. void OS::set_benchmark_file(const String &p_benchmark_file) {
  626. benchmark_file = p_benchmark_file;
  627. }
  628. String OS::get_benchmark_file() {
  629. return benchmark_file;
  630. }
  631. void OS::benchmark_begin_measure(const String &p_context, const String &p_what) {
  632. #ifdef TOOLS_ENABLED
  633. Pair<String, String> mark_key(p_context, p_what);
  634. ERR_FAIL_COND_MSG(benchmark_marks_from.has(mark_key), vformat("Benchmark key '%s:%s' already exists.", p_context, p_what));
  635. benchmark_marks_from[mark_key] = OS::get_singleton()->get_ticks_usec();
  636. #endif
  637. }
  638. void OS::benchmark_end_measure(const String &p_context, const String &p_what) {
  639. #ifdef TOOLS_ENABLED
  640. Pair<String, String> mark_key(p_context, p_what);
  641. ERR_FAIL_COND_MSG(!benchmark_marks_from.has(mark_key), vformat("Benchmark key '%s:%s' doesn't exist.", p_context, p_what));
  642. uint64_t total = OS::get_singleton()->get_ticks_usec() - benchmark_marks_from[mark_key];
  643. double total_f = double(total) / double(1000000);
  644. benchmark_marks_final[mark_key] = total_f;
  645. #endif
  646. }
  647. void OS::benchmark_dump() {
  648. #ifdef TOOLS_ENABLED
  649. if (!use_benchmark) {
  650. return;
  651. }
  652. if (!benchmark_file.is_empty()) {
  653. Ref<FileAccess> f = FileAccess::open(benchmark_file, FileAccess::WRITE);
  654. if (f.is_valid()) {
  655. Dictionary benchmark_marks;
  656. for (const KeyValue<Pair<String, String>, double> &E : benchmark_marks_final) {
  657. const String mark_key = vformat("[%s] %s", E.key.first, E.key.second);
  658. benchmark_marks[mark_key] = E.value;
  659. }
  660. Ref<JSON> json;
  661. json.instantiate();
  662. f->store_string(json->stringify(benchmark_marks, "\t", false, true));
  663. }
  664. } else {
  665. HashMap<String, String> results;
  666. for (const KeyValue<Pair<String, String>, double> &E : benchmark_marks_final) {
  667. if (E.key.first == "Startup" && !results.has(E.key.first)) {
  668. results.insert(E.key.first, "", true); // Hack to make sure "Startup" always comes first.
  669. }
  670. results[E.key.first] += vformat("\t\t- %s: %.3f msec.\n", E.key.second, (E.value * 1000));
  671. }
  672. print_line("BENCHMARK:");
  673. for (const KeyValue<String, String> &E : results) {
  674. print_line(vformat("\t[%s]\n%s", E.key, E.value));
  675. }
  676. }
  677. #endif
  678. }
  679. OS::OS() {
  680. singleton = this;
  681. Vector<Logger *> loggers;
  682. loggers.push_back(memnew(StdLogger));
  683. _set_logger(memnew(CompositeLogger(loggers)));
  684. }
  685. OS::~OS() {
  686. if (_logger) {
  687. memdelete(_logger);
  688. }
  689. singleton = nullptr;
  690. }