os.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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/input/input.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/json.h"
  36. #include "core/os/midi_driver.h"
  37. #include "core/version_generated.gen.h"
  38. #include <stdarg.h>
  39. #ifdef MINGW_ENABLED
  40. #define MINGW_STDTHREAD_REDUNDANCY_WARNING
  41. #include "thirdparty/mingw-std-threads/mingw.thread.h"
  42. #define THREADING_NAMESPACE mingw_stdthread
  43. #else
  44. #include <thread>
  45. #define THREADING_NAMESPACE std
  46. #endif
  47. OS *OS::singleton = nullptr;
  48. uint64_t OS::target_ticks = 0;
  49. OS *OS::get_singleton() {
  50. return singleton;
  51. }
  52. uint64_t OS::get_ticks_msec() const {
  53. return get_ticks_usec() / 1000ULL;
  54. }
  55. double OS::get_unix_time() const {
  56. return 0;
  57. }
  58. void OS::_set_logger(CompositeLogger *p_logger) {
  59. if (_logger) {
  60. memdelete(_logger);
  61. }
  62. _logger = p_logger;
  63. }
  64. void OS::add_logger(Logger *p_logger) {
  65. if (!_logger) {
  66. Vector<Logger *> loggers;
  67. loggers.push_back(p_logger);
  68. _logger = memnew(CompositeLogger(loggers));
  69. } else {
  70. _logger->add_logger(p_logger);
  71. }
  72. }
  73. String OS::get_identifier() const {
  74. return get_name().to_lower();
  75. }
  76. 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) {
  77. if (!_stderr_enabled) {
  78. return;
  79. }
  80. if (_logger) {
  81. _logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type);
  82. }
  83. }
  84. void OS::print(const char *p_format, ...) {
  85. if (!_stdout_enabled) {
  86. return;
  87. }
  88. va_list argp;
  89. va_start(argp, p_format);
  90. if (_logger) {
  91. _logger->logv(p_format, argp, false);
  92. }
  93. va_end(argp);
  94. }
  95. void OS::print_rich(const char *p_format, ...) {
  96. if (!_stdout_enabled) {
  97. return;
  98. }
  99. va_list argp;
  100. va_start(argp, p_format);
  101. if (_logger) {
  102. _logger->logv(p_format, argp, false);
  103. }
  104. va_end(argp);
  105. }
  106. void OS::printerr(const char *p_format, ...) {
  107. if (!_stderr_enabled) {
  108. return;
  109. }
  110. va_list argp;
  111. va_start(argp, p_format);
  112. if (_logger) {
  113. _logger->logv(p_format, argp, true);
  114. }
  115. va_end(argp);
  116. }
  117. void OS::alert(const String &p_alert, const String &p_title) {
  118. fprintf(stderr, "%s: %s\n", p_title.utf8().get_data(), p_alert.utf8().get_data());
  119. }
  120. void OS::set_low_processor_usage_mode(bool p_enabled) {
  121. low_processor_usage_mode = p_enabled;
  122. }
  123. bool OS::is_in_low_processor_usage_mode() const {
  124. return low_processor_usage_mode;
  125. }
  126. void OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
  127. low_processor_usage_mode_sleep_usec = p_usec;
  128. }
  129. int OS::get_low_processor_usage_mode_sleep_usec() const {
  130. return low_processor_usage_mode_sleep_usec;
  131. }
  132. void OS::set_delta_smoothing(bool p_enabled) {
  133. _delta_smoothing_enabled = p_enabled;
  134. }
  135. bool OS::is_delta_smoothing_enabled() const {
  136. return _delta_smoothing_enabled;
  137. }
  138. String OS::get_executable_path() const {
  139. return _execpath;
  140. }
  141. int OS::get_process_id() const {
  142. return -1;
  143. }
  144. bool OS::is_stdout_verbose() const {
  145. return _verbose_stdout;
  146. }
  147. bool OS::is_stdout_debug_enabled() const {
  148. return _debug_stdout;
  149. }
  150. bool OS::is_stdout_enabled() const {
  151. return _stdout_enabled;
  152. }
  153. bool OS::is_stderr_enabled() const {
  154. return _stderr_enabled;
  155. }
  156. void OS::set_stdout_enabled(bool p_enabled) {
  157. _stdout_enabled = p_enabled;
  158. }
  159. void OS::set_stderr_enabled(bool p_enabled) {
  160. _stderr_enabled = p_enabled;
  161. }
  162. int OS::get_exit_code() const {
  163. return _exit_code;
  164. }
  165. void OS::set_exit_code(int p_code) {
  166. _exit_code = p_code;
  167. }
  168. String OS::get_locale() const {
  169. return "en";
  170. }
  171. // Non-virtual helper to extract the 2 or 3-letter language code from
  172. // `get_locale()` in a way that's consistent for all platforms.
  173. String OS::get_locale_language() const {
  174. return get_locale().left(3).replace("_", "");
  175. }
  176. // Embedded PCK offset.
  177. uint64_t OS::get_embedded_pck_offset() const {
  178. return 0;
  179. }
  180. // Helper function to ensure that a dir name/path will be valid on the OS
  181. String OS::get_safe_dir_name(const String &p_dir_name, bool p_allow_paths) const {
  182. String safe_dir_name = p_dir_name;
  183. Vector<String> invalid_chars = String(": * ? \" < > |").split(" ");
  184. if (p_allow_paths) {
  185. // Dir separators are allowed, but disallow ".." to avoid going up the filesystem
  186. invalid_chars.push_back("..");
  187. safe_dir_name = safe_dir_name.replace("\\", "/").strip_edges();
  188. } else {
  189. invalid_chars.push_back("/");
  190. invalid_chars.push_back("\\");
  191. safe_dir_name = safe_dir_name.strip_edges();
  192. // These directory names are invalid.
  193. if (safe_dir_name == ".") {
  194. safe_dir_name = "dot";
  195. } else if (safe_dir_name == "..") {
  196. safe_dir_name = "twodots";
  197. }
  198. }
  199. for (int i = 0; i < invalid_chars.size(); i++) {
  200. safe_dir_name = safe_dir_name.replace(invalid_chars[i], "-");
  201. }
  202. return safe_dir_name;
  203. }
  204. // Path to data, config, cache, etc. OS-specific folders
  205. // Get properly capitalized engine name for system paths
  206. String OS::get_godot_dir_name() const {
  207. // Default to lowercase, so only override when different case is needed
  208. return String(VERSION_SHORT_NAME).to_lower();
  209. }
  210. // OS equivalent of XDG_DATA_HOME
  211. String OS::get_data_path() const {
  212. return ".";
  213. }
  214. // OS equivalent of XDG_CONFIG_HOME
  215. String OS::get_config_path() const {
  216. return ".";
  217. }
  218. // OS equivalent of XDG_CACHE_HOME
  219. String OS::get_cache_path() const {
  220. return ".";
  221. }
  222. // Path to macOS .app bundle resources
  223. String OS::get_bundle_resource_dir() const {
  224. return ".";
  225. }
  226. // Path to macOS .app bundle embedded icon
  227. String OS::get_bundle_icon_path() const {
  228. return String();
  229. }
  230. // OS specific path for user://
  231. String OS::get_user_data_dir() const {
  232. return ".";
  233. }
  234. // Absolute path to res://
  235. String OS::get_resource_dir() const {
  236. return ProjectSettings::get_singleton()->get_resource_path();
  237. }
  238. // Access system-specific dirs like Documents, Downloads, etc.
  239. String OS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  240. return ".";
  241. }
  242. Error OS::shell_open(String p_uri) {
  243. return ERR_UNAVAILABLE;
  244. }
  245. Error OS::shell_show_in_file_manager(String p_path, bool p_open_folder) {
  246. p_path = p_path.trim_prefix("file://");
  247. if (!DirAccess::dir_exists_absolute(p_path)) {
  248. p_path = p_path.get_base_dir();
  249. }
  250. p_path = String("file://") + p_path;
  251. return shell_open(p_path);
  252. }
  253. // implement these with the canvas?
  254. uint64_t OS::get_static_memory_usage() const {
  255. return Memory::get_mem_usage();
  256. }
  257. uint64_t OS::get_static_memory_peak_usage() const {
  258. return Memory::get_mem_max_usage();
  259. }
  260. Error OS::set_cwd(const String &p_cwd) {
  261. return ERR_CANT_OPEN;
  262. }
  263. Dictionary OS::get_memory_info() const {
  264. Dictionary meminfo;
  265. meminfo["physical"] = -1;
  266. meminfo["free"] = -1;
  267. meminfo["available"] = -1;
  268. meminfo["stack"] = -1;
  269. return meminfo;
  270. }
  271. void OS::yield() {
  272. }
  273. void OS::ensure_user_data_dir() {
  274. String dd = get_user_data_dir();
  275. if (DirAccess::exists(dd)) {
  276. return;
  277. }
  278. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  279. Error err = da->make_dir_recursive(dd);
  280. ERR_FAIL_COND_MSG(err != OK, "Error attempting to create data dir: " + dd + ".");
  281. }
  282. String OS::get_model_name() const {
  283. return "GenericDevice";
  284. }
  285. void OS::set_cmdline(const char *p_execpath, const List<String> &p_args, const List<String> &p_user_args) {
  286. _execpath = String::utf8(p_execpath);
  287. _cmdline = p_args;
  288. _user_args = p_user_args;
  289. }
  290. String OS::get_unique_id() const {
  291. return "";
  292. }
  293. int OS::get_processor_count() const {
  294. return THREADING_NAMESPACE::thread::hardware_concurrency();
  295. }
  296. String OS::get_processor_name() const {
  297. return "";
  298. }
  299. void OS::set_has_server_feature_callback(HasServerFeatureCallback p_callback) {
  300. has_server_feature_callback = p_callback;
  301. }
  302. bool OS::has_feature(const String &p_feature) {
  303. // Feature tags are always lowercase for consistency.
  304. if (p_feature == get_identifier()) {
  305. return true;
  306. }
  307. if (p_feature == "movie") {
  308. return _writing_movie;
  309. }
  310. #ifdef DEBUG_ENABLED
  311. if (p_feature == "debug") {
  312. return true;
  313. }
  314. #endif // DEBUG_ENABLED
  315. #ifdef TOOLS_ENABLED
  316. if (p_feature == "editor") {
  317. return true;
  318. }
  319. #else
  320. if (p_feature == "template") {
  321. return true;
  322. }
  323. #ifdef DEBUG_ENABLED
  324. if (p_feature == "template_debug") {
  325. return true;
  326. }
  327. #else
  328. if (p_feature == "template_release" || p_feature == "release") {
  329. return true;
  330. }
  331. #endif // DEBUG_ENABLED
  332. #endif // TOOLS_ENABLED
  333. #ifdef REAL_T_IS_DOUBLE
  334. if (p_feature == "double") {
  335. return true;
  336. }
  337. #else
  338. if (p_feature == "single") {
  339. return true;
  340. }
  341. #endif // REAL_T_IS_DOUBLE
  342. if (sizeof(void *) == 8 && p_feature == "64") {
  343. return true;
  344. }
  345. if (sizeof(void *) == 4 && p_feature == "32") {
  346. return true;
  347. }
  348. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(_M_X64)
  349. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64)
  350. if (p_feature == "x86_64") {
  351. return true;
  352. }
  353. #elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
  354. if (p_feature == "x86_32") {
  355. return true;
  356. }
  357. #endif
  358. if (p_feature == "x86") {
  359. return true;
  360. }
  361. #elif defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  362. #if defined(__aarch64__) || defined(_M_ARM64)
  363. if (p_feature == "arm64") {
  364. return true;
  365. }
  366. #elif defined(__arm__) || defined(_M_ARM)
  367. if (p_feature == "arm32") {
  368. return true;
  369. }
  370. #endif
  371. #if defined(__ARM_ARCH_7A__)
  372. if (p_feature == "armv7a" || p_feature == "armv7") {
  373. return true;
  374. }
  375. #endif
  376. #if defined(__ARM_ARCH_7S__)
  377. if (p_feature == "armv7s" || p_feature == "armv7") {
  378. return true;
  379. }
  380. #endif
  381. if (p_feature == "arm") {
  382. return true;
  383. }
  384. #elif defined(__riscv)
  385. #if __riscv_xlen == 8
  386. if (p_feature == "rv64") {
  387. return true;
  388. }
  389. #endif
  390. if (p_feature == "riscv") {
  391. return true;
  392. }
  393. #elif defined(__powerpc__)
  394. #if defined(__powerpc64__)
  395. if (p_feature == "ppc64") {
  396. return true;
  397. }
  398. #endif
  399. if (p_feature == "ppc") {
  400. return true;
  401. }
  402. #elif defined(__wasm__)
  403. #if defined(__wasm64__)
  404. if (p_feature == "wasm64") {
  405. return true;
  406. }
  407. #elif defined(__wasm32__)
  408. if (p_feature == "wasm32") {
  409. return true;
  410. }
  411. #endif
  412. if (p_feature == "wasm") {
  413. return true;
  414. }
  415. #endif
  416. #if defined(IOS_SIMULATOR)
  417. if (p_feature == "simulator") {
  418. return true;
  419. }
  420. #endif
  421. if (_check_internal_feature_support(p_feature)) {
  422. return true;
  423. }
  424. if (has_server_feature_callback && has_server_feature_callback(p_feature)) {
  425. return true;
  426. }
  427. if (ProjectSettings::get_singleton()->has_custom_feature(p_feature)) {
  428. return true;
  429. }
  430. return false;
  431. }
  432. bool OS::is_sandboxed() const {
  433. return false;
  434. }
  435. void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) {
  436. restart_on_exit = p_restart;
  437. restart_commandline = p_restart_arguments;
  438. }
  439. bool OS::is_restart_on_exit_set() const {
  440. return restart_on_exit;
  441. }
  442. List<String> OS::get_restart_on_exit_arguments() const {
  443. return restart_commandline;
  444. }
  445. PackedStringArray OS::get_connected_midi_inputs() {
  446. if (MIDIDriver::get_singleton()) {
  447. return MIDIDriver::get_singleton()->get_connected_inputs();
  448. }
  449. PackedStringArray list;
  450. ERR_FAIL_V_MSG(list, vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  451. }
  452. void OS::open_midi_inputs() {
  453. if (MIDIDriver::get_singleton()) {
  454. MIDIDriver::get_singleton()->open();
  455. } else {
  456. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  457. }
  458. }
  459. void OS::close_midi_inputs() {
  460. if (MIDIDriver::get_singleton()) {
  461. MIDIDriver::get_singleton()->close();
  462. } else {
  463. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  464. }
  465. }
  466. void OS::add_frame_delay(bool p_can_draw) {
  467. const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  468. if (frame_delay) {
  469. // Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
  470. // the actual frame time into account.
  471. // Due to the high fluctuation of the actual sleep duration, it's not recommended
  472. // to use this as a FPS limiter.
  473. delay_usec(frame_delay * 1000);
  474. }
  475. // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
  476. // previous frame time into account for a smoother result.
  477. uint64_t dynamic_delay = 0;
  478. if (is_in_low_processor_usage_mode() || !p_can_draw) {
  479. dynamic_delay = get_low_processor_usage_mode_sleep_usec();
  480. }
  481. const int max_fps = Engine::get_singleton()->get_max_fps();
  482. if (max_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  483. // Override the low processor usage mode sleep delay if the target FPS is lower.
  484. dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / max_fps));
  485. }
  486. if (dynamic_delay > 0) {
  487. target_ticks += dynamic_delay;
  488. uint64_t current_ticks = get_ticks_usec();
  489. if (current_ticks < target_ticks) {
  490. delay_usec(target_ticks - current_ticks);
  491. }
  492. current_ticks = get_ticks_usec();
  493. target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
  494. }
  495. }
  496. Error OS::setup_remote_filesystem(const String &p_server_host, int p_port, const String &p_password, String &r_project_path) {
  497. return default_rfs.synchronize_with_server(p_server_host, p_port, p_password, r_project_path);
  498. }
  499. OS::PreferredTextureFormat OS::get_preferred_texture_format() const {
  500. #if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  501. return PREFERRED_TEXTURE_FORMAT_ETC2_ASTC; // By rule, ARM hardware uses ETC texture compression.
  502. #elif defined(__x86_64__) || defined(_M_X64) || defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)
  503. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // By rule, X86 hardware prefers S3TC and derivatives.
  504. #else
  505. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // Override in platform if needed.
  506. #endif
  507. }
  508. void OS::set_use_benchmark(bool p_use_benchmark) {
  509. use_benchmark = p_use_benchmark;
  510. }
  511. bool OS::is_use_benchmark_set() {
  512. return use_benchmark;
  513. }
  514. void OS::set_benchmark_file(const String &p_benchmark_file) {
  515. benchmark_file = p_benchmark_file;
  516. }
  517. String OS::get_benchmark_file() {
  518. return benchmark_file;
  519. }
  520. void OS::benchmark_begin_measure(const String &p_what) {
  521. #ifdef TOOLS_ENABLED
  522. start_benchmark_from[p_what] = OS::get_singleton()->get_ticks_usec();
  523. #endif
  524. }
  525. void OS::benchmark_end_measure(const String &p_what) {
  526. #ifdef TOOLS_ENABLED
  527. uint64_t total = OS::get_singleton()->get_ticks_usec() - start_benchmark_from[p_what];
  528. double total_f = double(total) / double(1000000);
  529. startup_benchmark_json[p_what] = total_f;
  530. #endif
  531. }
  532. void OS::benchmark_dump() {
  533. #ifdef TOOLS_ENABLED
  534. if (!use_benchmark) {
  535. return;
  536. }
  537. if (!benchmark_file.is_empty()) {
  538. Ref<FileAccess> f = FileAccess::open(benchmark_file, FileAccess::WRITE);
  539. if (f.is_valid()) {
  540. Ref<JSON> json;
  541. json.instantiate();
  542. f->store_string(json->stringify(startup_benchmark_json, "\t", false, true));
  543. }
  544. } else {
  545. List<Variant> keys;
  546. startup_benchmark_json.get_key_list(&keys);
  547. print_line("BENCHMARK:");
  548. for (const Variant &K : keys) {
  549. print_line("\t-", K, ": ", startup_benchmark_json[K], +" sec.");
  550. }
  551. }
  552. #endif
  553. }
  554. OS::OS() {
  555. singleton = this;
  556. Vector<Logger *> loggers;
  557. loggers.push_back(memnew(StdLogger));
  558. _set_logger(memnew(CompositeLogger(loggers)));
  559. }
  560. OS::~OS() {
  561. if (_logger) {
  562. memdelete(_logger);
  563. }
  564. singleton = nullptr;
  565. }