os.cpp 13 KB

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