os.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. /*************************************************************************/
  2. /* os.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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/os/midi_driver.h"
  36. #include "core/version_generated.gen.h"
  37. #include "servers/audio_server.h"
  38. #include <stdarg.h>
  39. OS *OS::singleton = nullptr;
  40. uint64_t OS::target_ticks = 0;
  41. OS *OS::get_singleton() {
  42. return singleton;
  43. }
  44. uint64_t OS::get_ticks_msec() const {
  45. return get_ticks_usec() / 1000ULL;
  46. }
  47. double OS::get_unix_time() const {
  48. return 0;
  49. }
  50. void OS::debug_break() {
  51. // something
  52. }
  53. void OS::_set_logger(CompositeLogger *p_logger) {
  54. if (_logger) {
  55. memdelete(_logger);
  56. }
  57. _logger = p_logger;
  58. }
  59. void OS::add_logger(Logger *p_logger) {
  60. if (!_logger) {
  61. Vector<Logger *> loggers;
  62. loggers.push_back(p_logger);
  63. _logger = memnew(CompositeLogger(loggers));
  64. } else {
  65. _logger->add_logger(p_logger);
  66. }
  67. }
  68. void OS::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, Logger::ErrorType p_type) {
  69. if (!_stderr_enabled) {
  70. return;
  71. }
  72. _logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_type);
  73. }
  74. void OS::print(const char *p_format, ...) {
  75. if (!_stdout_enabled) {
  76. return;
  77. }
  78. va_list argp;
  79. va_start(argp, p_format);
  80. _logger->logv(p_format, argp, false);
  81. va_end(argp);
  82. }
  83. void OS::printerr(const char *p_format, ...) {
  84. if (!_stderr_enabled) {
  85. return;
  86. }
  87. va_list argp;
  88. va_start(argp, p_format);
  89. _logger->logv(p_format, argp, true);
  90. va_end(argp);
  91. }
  92. void OS::alert(const String &p_alert, const String &p_title) {
  93. fprintf(stderr, "%s: %s\n", p_title.utf8().get_data(), p_alert.utf8().get_data());
  94. }
  95. void OS::set_low_processor_usage_mode(bool p_enabled) {
  96. low_processor_usage_mode = p_enabled;
  97. }
  98. bool OS::is_in_low_processor_usage_mode() const {
  99. return low_processor_usage_mode;
  100. }
  101. void OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
  102. low_processor_usage_mode_sleep_usec = p_usec;
  103. }
  104. int OS::get_low_processor_usage_mode_sleep_usec() const {
  105. return low_processor_usage_mode_sleep_usec;
  106. }
  107. String OS::get_executable_path() const {
  108. return _execpath;
  109. }
  110. int OS::get_process_id() const {
  111. return -1;
  112. }
  113. void OS::vibrate_handheld(int p_duration_ms) {
  114. WARN_PRINT("vibrate_handheld() only works with Android and iOS");
  115. }
  116. bool OS::is_stdout_verbose() const {
  117. return _verbose_stdout;
  118. }
  119. bool OS::is_single_window() const {
  120. return _single_window;
  121. }
  122. bool OS::is_stdout_debug_enabled() const {
  123. return _debug_stdout;
  124. }
  125. bool OS::is_stdout_enabled() const {
  126. return _stdout_enabled;
  127. }
  128. bool OS::is_stderr_enabled() const {
  129. return _stderr_enabled;
  130. }
  131. void OS::set_stdout_enabled(bool p_enabled) {
  132. _stdout_enabled = p_enabled;
  133. }
  134. void OS::set_stderr_enabled(bool p_enabled) {
  135. _stderr_enabled = p_enabled;
  136. }
  137. void OS::dump_memory_to_file(const char *p_file) {
  138. //Memory::dump_static_mem_to_file(p_file);
  139. }
  140. static FileAccess *_OSPRF = nullptr;
  141. static void _OS_printres(Object *p_obj) {
  142. Resource *res = Object::cast_to<Resource>(p_obj);
  143. if (!res) {
  144. return;
  145. }
  146. String str = vformat("%s - %s - %s", res->to_string(), res->get_name(), res->get_path());
  147. if (_OSPRF) {
  148. _OSPRF->store_line(str);
  149. } else {
  150. print_line(str);
  151. }
  152. }
  153. void OS::print_all_resources(String p_to_file) {
  154. ERR_FAIL_COND(p_to_file != "" && _OSPRF);
  155. if (p_to_file != "") {
  156. Error err;
  157. _OSPRF = FileAccess::open(p_to_file, FileAccess::WRITE, &err);
  158. if (err != OK) {
  159. _OSPRF = nullptr;
  160. ERR_FAIL_MSG("Can't print all resources to file: " + String(p_to_file) + ".");
  161. }
  162. }
  163. ObjectDB::debug_objects(_OS_printres);
  164. if (p_to_file != "") {
  165. if (_OSPRF) {
  166. memdelete(_OSPRF);
  167. }
  168. _OSPRF = nullptr;
  169. }
  170. }
  171. void OS::print_resources_in_use(bool p_short) {
  172. ResourceCache::dump(nullptr, p_short);
  173. }
  174. void OS::dump_resources_to_file(const char *p_file) {
  175. ResourceCache::dump(p_file);
  176. }
  177. int OS::get_exit_code() const {
  178. return _exit_code;
  179. }
  180. void OS::set_exit_code(int p_code) {
  181. _exit_code = p_code;
  182. }
  183. String OS::get_locale() const {
  184. return "en";
  185. }
  186. // Helper function to ensure that a dir name/path will be valid on the OS
  187. String OS::get_safe_dir_name(const String &p_dir_name, bool p_allow_dir_separator) const {
  188. Vector<String> invalid_chars = String(": * ? \" < > |").split(" ");
  189. if (p_allow_dir_separator) {
  190. // Dir separators are allowed, but disallow ".." to avoid going up the filesystem
  191. invalid_chars.push_back("..");
  192. } else {
  193. invalid_chars.push_back("/");
  194. }
  195. String safe_dir_name = p_dir_name.replace("\\", "/").strip_edges();
  196. for (int i = 0; i < invalid_chars.size(); i++) {
  197. safe_dir_name = safe_dir_name.replace(invalid_chars[i], "-");
  198. }
  199. return safe_dir_name;
  200. }
  201. // Path to data, config, cache, etc. OS-specific folders
  202. // Get properly capitalized engine name for system paths
  203. String OS::get_godot_dir_name() const {
  204. // Default to lowercase, so only override when different case is needed
  205. return String(VERSION_SHORT_NAME).to_lower();
  206. }
  207. // OS equivalent of XDG_DATA_HOME
  208. String OS::get_data_path() const {
  209. return ".";
  210. }
  211. // OS equivalent of XDG_CONFIG_HOME
  212. String OS::get_config_path() const {
  213. return ".";
  214. }
  215. // OS equivalent of XDG_CACHE_HOME
  216. String OS::get_cache_path() const {
  217. return ".";
  218. }
  219. // Path to macOS .app bundle resources
  220. String OS::get_bundle_resource_dir() const {
  221. return ".";
  222. }
  223. // OS specific path for user://
  224. String OS::get_user_data_dir() const {
  225. return ".";
  226. }
  227. // Absolute path to res://
  228. String OS::get_resource_dir() const {
  229. return ProjectSettings::get_singleton()->get_resource_path();
  230. }
  231. // Access system-specific dirs like Documents, Downloads, etc.
  232. String OS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  233. return ".";
  234. }
  235. Error OS::shell_open(String p_uri) {
  236. return ERR_UNAVAILABLE;
  237. }
  238. // implement these with the canvas?
  239. uint64_t OS::get_static_memory_usage() const {
  240. return Memory::get_mem_usage();
  241. }
  242. uint64_t OS::get_static_memory_peak_usage() const {
  243. return Memory::get_mem_max_usage();
  244. }
  245. Error OS::set_cwd(const String &p_cwd) {
  246. return ERR_CANT_OPEN;
  247. }
  248. uint64_t OS::get_free_static_memory() const {
  249. return Memory::get_mem_available();
  250. }
  251. void OS::yield() {
  252. }
  253. void OS::ensure_user_data_dir() {
  254. String dd = get_user_data_dir();
  255. DirAccess *da = DirAccess::open(dd);
  256. if (da) {
  257. memdelete(da);
  258. return;
  259. }
  260. da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  261. Error err = da->make_dir_recursive(dd);
  262. ERR_FAIL_COND_MSG(err != OK, "Error attempting to create data dir: " + dd + ".");
  263. memdelete(da);
  264. }
  265. String OS::get_model_name() const {
  266. return "GenericDevice";
  267. }
  268. void OS::set_cmdline(const char *p_execpath, const List<String> &p_args) {
  269. _execpath = p_execpath;
  270. _cmdline = p_args;
  271. }
  272. String OS::get_unique_id() const {
  273. ERR_FAIL_V("");
  274. }
  275. int OS::get_processor_count() const {
  276. return 1;
  277. }
  278. bool OS::can_use_threads() const {
  279. #ifdef NO_THREADS
  280. return false;
  281. #else
  282. return true;
  283. #endif
  284. }
  285. void OS::set_has_server_feature_callback(HasServerFeatureCallback p_callback) {
  286. has_server_feature_callback = p_callback;
  287. }
  288. bool OS::has_feature(const String &p_feature) {
  289. // Feature tags are always lowercase for consistency.
  290. if (p_feature == get_name().to_lower()) {
  291. return true;
  292. }
  293. // Catch-all `linuxbsd` feature tag that matches on both Linux and BSD.
  294. // This is the one exposed in the project settings dialog.
  295. if (p_feature == "linuxbsd" && (get_name() == "Linux" || get_name() == "FreeBSD" || get_name() == "NetBSD" || get_name() == "OpenBSD" || get_name() == "BSD")) {
  296. return true;
  297. }
  298. #ifdef DEBUG_ENABLED
  299. if (p_feature == "debug") {
  300. return true;
  301. }
  302. #else
  303. if (p_feature == "release")
  304. return true;
  305. #endif
  306. #ifdef TOOLS_ENABLED
  307. if (p_feature == "editor") {
  308. return true;
  309. }
  310. #else
  311. if (p_feature == "standalone")
  312. return true;
  313. #endif
  314. if (sizeof(void *) == 8 && p_feature == "64") {
  315. return true;
  316. }
  317. if (sizeof(void *) == 4 && p_feature == "32") {
  318. return true;
  319. }
  320. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__)
  321. if (p_feature == "x86_64") {
  322. return true;
  323. }
  324. #elif (defined(__i386) || defined(__i386__))
  325. if (p_feature == "x86") {
  326. return true;
  327. }
  328. #elif defined(__aarch64__)
  329. if (p_feature == "arm64") {
  330. return true;
  331. }
  332. #elif defined(__arm__)
  333. #if defined(__ARM_ARCH_7A__)
  334. if (p_feature == "armv7a" || p_feature == "armv7") {
  335. return true;
  336. }
  337. #endif
  338. #if defined(__ARM_ARCH_7S__)
  339. if (p_feature == "armv7s" || p_feature == "armv7") {
  340. return true;
  341. }
  342. #endif
  343. if (p_feature == "arm") {
  344. return true;
  345. }
  346. #endif
  347. if (_check_internal_feature_support(p_feature)) {
  348. return true;
  349. }
  350. if (has_server_feature_callback && has_server_feature_callback(p_feature)) {
  351. return true;
  352. }
  353. if (ProjectSettings::get_singleton()->has_custom_feature(p_feature)) {
  354. return true;
  355. }
  356. return false;
  357. }
  358. void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) {
  359. restart_on_exit = p_restart;
  360. restart_commandline = p_restart_arguments;
  361. }
  362. bool OS::is_restart_on_exit_set() const {
  363. return restart_on_exit;
  364. }
  365. List<String> OS::get_restart_on_exit_arguments() const {
  366. return restart_commandline;
  367. }
  368. PackedStringArray OS::get_connected_midi_inputs() {
  369. if (MIDIDriver::get_singleton()) {
  370. return MIDIDriver::get_singleton()->get_connected_inputs();
  371. }
  372. PackedStringArray list;
  373. ERR_FAIL_V_MSG(list, vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  374. }
  375. void OS::open_midi_inputs() {
  376. if (MIDIDriver::get_singleton()) {
  377. MIDIDriver::get_singleton()->open();
  378. } else {
  379. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  380. }
  381. }
  382. void OS::close_midi_inputs() {
  383. if (MIDIDriver::get_singleton()) {
  384. MIDIDriver::get_singleton()->close();
  385. } else {
  386. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  387. }
  388. }
  389. void OS::add_frame_delay(bool p_can_draw) {
  390. const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  391. if (frame_delay) {
  392. // Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
  393. // the actual frame time into account.
  394. // Due to the high fluctuation of the actual sleep duration, it's not recommended
  395. // to use this as a FPS limiter.
  396. delay_usec(frame_delay * 1000);
  397. }
  398. // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
  399. // previous frame time into account for a smoother result.
  400. uint64_t dynamic_delay = 0;
  401. if (is_in_low_processor_usage_mode() || !p_can_draw) {
  402. dynamic_delay = get_low_processor_usage_mode_sleep_usec();
  403. }
  404. const int target_fps = Engine::get_singleton()->get_target_fps();
  405. if (target_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  406. // Override the low processor usage mode sleep delay if the target FPS is lower.
  407. dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / target_fps));
  408. }
  409. if (dynamic_delay > 0) {
  410. target_ticks += dynamic_delay;
  411. uint64_t current_ticks = get_ticks_usec();
  412. if (current_ticks < target_ticks) {
  413. delay_usec(target_ticks - current_ticks);
  414. }
  415. current_ticks = get_ticks_usec();
  416. target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
  417. }
  418. }
  419. OS::OS() {
  420. singleton = this;
  421. Vector<Logger *> loggers;
  422. loggers.push_back(memnew(StdLogger));
  423. _set_logger(memnew(CompositeLogger(loggers)));
  424. }
  425. OS::~OS() {
  426. memdelete(_logger);
  427. singleton = nullptr;
  428. }