core_bind.cpp 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452
  1. /*************************************************************************/
  2. /* core_bind.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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 "core_bind.h"
  31. #include "core/crypto/crypto_core.h"
  32. #include "core/io/file_access_compressed.h"
  33. #include "core/io/file_access_encrypted.h"
  34. #include "core/io/json.h"
  35. #include "core/io/marshalls.h"
  36. #include "core/math/geometry.h"
  37. #include "core/os/keyboard.h"
  38. #include "core/os/os.h"
  39. #include "core/project_settings.h"
  40. /**
  41. * Time constants borrowed from loc_time.h
  42. */
  43. #define EPOCH_YR 1970 /* EPOCH = Jan 1 1970 00:00:00 */
  44. #define SECS_DAY (24L * 60L * 60L)
  45. #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400)))
  46. #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
  47. #define SECOND_KEY "second"
  48. #define MINUTE_KEY "minute"
  49. #define HOUR_KEY "hour"
  50. #define DAY_KEY "day"
  51. #define MONTH_KEY "month"
  52. #define YEAR_KEY "year"
  53. #define WEEKDAY_KEY "weekday"
  54. #define DST_KEY "dst"
  55. /// Table of number of days in each month (for regular year and leap year)
  56. static const unsigned int MONTH_DAYS_TABLE[2][12] = {
  57. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
  58. { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
  59. };
  60. ////// _ResourceLoader //////
  61. _ResourceLoader *_ResourceLoader::singleton = nullptr;
  62. Error _ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads) {
  63. return ResourceLoader::load_threaded_request(p_path, p_type_hint, p_use_sub_threads);
  64. }
  65. _ResourceLoader::ThreadLoadStatus _ResourceLoader::load_threaded_get_status(const String &p_path, Array r_progress) {
  66. float progress = 0;
  67. ResourceLoader::ThreadLoadStatus tls = ResourceLoader::load_threaded_get_status(p_path, &progress);
  68. r_progress.resize(1);
  69. r_progress[0] = progress;
  70. return (ThreadLoadStatus)tls;
  71. }
  72. RES _ResourceLoader::load_threaded_get(const String &p_path) {
  73. Error error;
  74. RES res = ResourceLoader::load_threaded_get(p_path, &error);
  75. return res;
  76. }
  77. RES _ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache) {
  78. Error err = OK;
  79. RES ret = ResourceLoader::load(p_path, p_type_hint, p_no_cache, &err);
  80. ERR_FAIL_COND_V_MSG(err != OK, ret, "Error loading resource: '" + p_path + "'.");
  81. return ret;
  82. }
  83. Vector<String> _ResourceLoader::get_recognized_extensions_for_type(const String &p_type) {
  84. List<String> exts;
  85. ResourceLoader::get_recognized_extensions_for_type(p_type, &exts);
  86. Vector<String> ret;
  87. for (List<String>::Element *E = exts.front(); E; E = E->next()) {
  88. ret.push_back(E->get());
  89. }
  90. return ret;
  91. }
  92. void _ResourceLoader::set_abort_on_missing_resources(bool p_abort) {
  93. ResourceLoader::set_abort_on_missing_resources(p_abort);
  94. }
  95. PackedStringArray _ResourceLoader::get_dependencies(const String &p_path) {
  96. List<String> deps;
  97. ResourceLoader::get_dependencies(p_path, &deps);
  98. PackedStringArray ret;
  99. for (List<String>::Element *E = deps.front(); E; E = E->next()) {
  100. ret.push_back(E->get());
  101. }
  102. return ret;
  103. }
  104. bool _ResourceLoader::has_cached(const String &p_path) {
  105. String local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  106. return ResourceCache::has(local_path);
  107. }
  108. bool _ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  109. return ResourceLoader::exists(p_path, p_type_hint);
  110. }
  111. void _ResourceLoader::_bind_methods() {
  112. ClassDB::bind_method(D_METHOD("load_threaded_request", "path", "type_hint", "use_sub_threads"), &_ResourceLoader::load_threaded_request, DEFVAL(""), DEFVAL(false));
  113. ClassDB::bind_method(D_METHOD("load_threaded_get_status", "path", "progress"), &_ResourceLoader::load_threaded_get_status, DEFVAL(Array()));
  114. ClassDB::bind_method(D_METHOD("load_threaded_get", "path"), &_ResourceLoader::load_threaded_get);
  115. ClassDB::bind_method(D_METHOD("load", "path", "type_hint", "no_cache"), &_ResourceLoader::load, DEFVAL(""), DEFVAL(false));
  116. ClassDB::bind_method(D_METHOD("get_recognized_extensions_for_type", "type"), &_ResourceLoader::get_recognized_extensions_for_type);
  117. ClassDB::bind_method(D_METHOD("set_abort_on_missing_resources", "abort"), &_ResourceLoader::set_abort_on_missing_resources);
  118. ClassDB::bind_method(D_METHOD("get_dependencies", "path"), &_ResourceLoader::get_dependencies);
  119. ClassDB::bind_method(D_METHOD("has_cached", "path"), &_ResourceLoader::has_cached);
  120. ClassDB::bind_method(D_METHOD("exists", "path", "type_hint"), &_ResourceLoader::exists, DEFVAL(""));
  121. BIND_ENUM_CONSTANT(THREAD_LOAD_INVALID_RESOURCE);
  122. BIND_ENUM_CONSTANT(THREAD_LOAD_IN_PROGRESS);
  123. BIND_ENUM_CONSTANT(THREAD_LOAD_FAILED);
  124. BIND_ENUM_CONSTANT(THREAD_LOAD_LOADED);
  125. }
  126. ////// _ResourceSaver //////
  127. Error _ResourceSaver::save(const String &p_path, const RES &p_resource, SaverFlags p_flags) {
  128. ERR_FAIL_COND_V_MSG(p_resource.is_null(), ERR_INVALID_PARAMETER, "Can't save empty resource to path '" + String(p_path) + "'.");
  129. return ResourceSaver::save(p_path, p_resource, p_flags);
  130. }
  131. Vector<String> _ResourceSaver::get_recognized_extensions(const RES &p_resource) {
  132. ERR_FAIL_COND_V_MSG(p_resource.is_null(), Vector<String>(), "It's not a reference to a valid Resource object.");
  133. List<String> exts;
  134. ResourceSaver::get_recognized_extensions(p_resource, &exts);
  135. Vector<String> ret;
  136. for (List<String>::Element *E = exts.front(); E; E = E->next()) {
  137. ret.push_back(E->get());
  138. }
  139. return ret;
  140. }
  141. _ResourceSaver *_ResourceSaver::singleton = nullptr;
  142. void _ResourceSaver::_bind_methods() {
  143. ClassDB::bind_method(D_METHOD("save", "path", "resource", "flags"), &_ResourceSaver::save, DEFVAL(0));
  144. ClassDB::bind_method(D_METHOD("get_recognized_extensions", "type"), &_ResourceSaver::get_recognized_extensions);
  145. BIND_ENUM_CONSTANT(FLAG_RELATIVE_PATHS);
  146. BIND_ENUM_CONSTANT(FLAG_BUNDLE_RESOURCES);
  147. BIND_ENUM_CONSTANT(FLAG_CHANGE_PATH);
  148. BIND_ENUM_CONSTANT(FLAG_OMIT_EDITOR_PROPERTIES);
  149. BIND_ENUM_CONSTANT(FLAG_SAVE_BIG_ENDIAN);
  150. BIND_ENUM_CONSTANT(FLAG_COMPRESS);
  151. BIND_ENUM_CONSTANT(FLAG_REPLACE_SUBRESOURCE_PATHS);
  152. }
  153. ////// _OS //////
  154. PackedStringArray _OS::get_connected_midi_inputs() {
  155. return OS::get_singleton()->get_connected_midi_inputs();
  156. }
  157. void _OS::open_midi_inputs() {
  158. OS::get_singleton()->open_midi_inputs();
  159. }
  160. void _OS::close_midi_inputs() {
  161. OS::get_singleton()->close_midi_inputs();
  162. }
  163. void _OS::set_use_file_access_save_and_swap(bool p_enable) {
  164. FileAccess::set_backup_save(p_enable);
  165. }
  166. void _OS::set_low_processor_usage_mode(bool p_enabled) {
  167. OS::get_singleton()->set_low_processor_usage_mode(p_enabled);
  168. }
  169. bool _OS::is_in_low_processor_usage_mode() const {
  170. return OS::get_singleton()->is_in_low_processor_usage_mode();
  171. }
  172. void _OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
  173. OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(p_usec);
  174. }
  175. int _OS::get_low_processor_usage_mode_sleep_usec() const {
  176. return OS::get_singleton()->get_low_processor_usage_mode_sleep_usec();
  177. }
  178. String _OS::get_executable_path() const {
  179. return OS::get_singleton()->get_executable_path();
  180. }
  181. Error _OS::shell_open(String p_uri) {
  182. if (p_uri.begins_with("res://")) {
  183. WARN_PRINT("Attempting to open an URL with the \"res://\" protocol. Use `ProjectSettings.globalize_path()` to convert a Godot-specific path to a system path before opening it with `OS.shell_open()`.");
  184. } else if (p_uri.begins_with("user://")) {
  185. WARN_PRINT("Attempting to open an URL with the \"user://\" protocol. Use `ProjectSettings.globalize_path()` to convert a Godot-specific path to a system path before opening it with `OS.shell_open()`.");
  186. }
  187. return OS::get_singleton()->shell_open(p_uri);
  188. }
  189. int _OS::execute(const String &p_path, const Vector<String> &p_arguments, bool p_blocking, Array p_output, bool p_read_stderr) {
  190. OS::ProcessID pid = -2;
  191. int exitcode = 0;
  192. List<String> args;
  193. for (int i = 0; i < p_arguments.size(); i++) {
  194. args.push_back(p_arguments[i]);
  195. }
  196. String pipe;
  197. Error err = OS::get_singleton()->execute(p_path, args, p_blocking, &pid, &pipe, &exitcode, p_read_stderr);
  198. p_output.clear();
  199. p_output.push_back(pipe);
  200. if (err != OK) {
  201. return -1;
  202. } else if (p_blocking) {
  203. return exitcode;
  204. } else {
  205. return pid;
  206. }
  207. }
  208. Error _OS::kill(int p_pid) {
  209. return OS::get_singleton()->kill(p_pid);
  210. }
  211. int _OS::get_process_id() const {
  212. return OS::get_singleton()->get_process_id();
  213. }
  214. bool _OS::has_environment(const String &p_var) const {
  215. return OS::get_singleton()->has_environment(p_var);
  216. }
  217. String _OS::get_environment(const String &p_var) const {
  218. return OS::get_singleton()->get_environment(p_var);
  219. }
  220. String _OS::get_name() const {
  221. return OS::get_singleton()->get_name();
  222. }
  223. Vector<String> _OS::get_cmdline_args() {
  224. List<String> cmdline = OS::get_singleton()->get_cmdline_args();
  225. Vector<String> cmdlinev;
  226. for (List<String>::Element *E = cmdline.front(); E; E = E->next()) {
  227. cmdlinev.push_back(E->get());
  228. }
  229. return cmdlinev;
  230. }
  231. String _OS::get_locale() const {
  232. return OS::get_singleton()->get_locale();
  233. }
  234. String _OS::get_model_name() const {
  235. return OS::get_singleton()->get_model_name();
  236. }
  237. Error _OS::set_thread_name(const String &p_name) {
  238. return Thread::set_name(p_name);
  239. }
  240. bool _OS::has_feature(const String &p_feature) const {
  241. return OS::get_singleton()->has_feature(p_feature);
  242. }
  243. uint64_t _OS::get_static_memory_usage() const {
  244. return OS::get_singleton()->get_static_memory_usage();
  245. }
  246. uint64_t _OS::get_static_memory_peak_usage() const {
  247. return OS::get_singleton()->get_static_memory_peak_usage();
  248. }
  249. int _OS::get_exit_code() const {
  250. return OS::get_singleton()->get_exit_code();
  251. }
  252. void _OS::set_exit_code(int p_code) {
  253. if (p_code < 0 || p_code > 125) {
  254. WARN_PRINT("For portability reasons, the exit code should be set between 0 and 125 (inclusive).");
  255. }
  256. OS::get_singleton()->set_exit_code(p_code);
  257. }
  258. /**
  259. * Get current datetime with consideration for utc and
  260. * dst
  261. */
  262. Dictionary _OS::get_datetime(bool utc) const {
  263. Dictionary dated = get_date(utc);
  264. Dictionary timed = get_time(utc);
  265. List<Variant> keys;
  266. timed.get_key_list(&keys);
  267. for (int i = 0; i < keys.size(); i++) {
  268. dated[keys[i]] = timed[keys[i]];
  269. }
  270. return dated;
  271. }
  272. Dictionary _OS::get_date(bool utc) const {
  273. OS::Date date = OS::get_singleton()->get_date(utc);
  274. Dictionary dated;
  275. dated[YEAR_KEY] = date.year;
  276. dated[MONTH_KEY] = date.month;
  277. dated[DAY_KEY] = date.day;
  278. dated[WEEKDAY_KEY] = date.weekday;
  279. dated[DST_KEY] = date.dst;
  280. return dated;
  281. }
  282. Dictionary _OS::get_time(bool utc) const {
  283. OS::Time time = OS::get_singleton()->get_time(utc);
  284. Dictionary timed;
  285. timed[HOUR_KEY] = time.hour;
  286. timed[MINUTE_KEY] = time.min;
  287. timed[SECOND_KEY] = time.sec;
  288. return timed;
  289. }
  290. /**
  291. * Get an epoch time value from a dictionary of time values
  292. * @p datetime must be populated with the following keys:
  293. * day, hour, minute, month, second, year. (dst is ignored).
  294. *
  295. * You can pass the output from
  296. * get_datetime_from_unix_time directly into this function
  297. *
  298. * @param datetime dictionary of date and time values to convert
  299. *
  300. * @return epoch calculated
  301. */
  302. int64_t _OS::get_unix_time_from_datetime(Dictionary datetime) const {
  303. // Bunch of conversion constants
  304. static const unsigned int SECONDS_PER_MINUTE = 60;
  305. static const unsigned int MINUTES_PER_HOUR = 60;
  306. static const unsigned int HOURS_PER_DAY = 24;
  307. static const unsigned int SECONDS_PER_HOUR = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;
  308. static const unsigned int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY;
  309. // Get all time values from the dictionary, set to zero if it doesn't exist.
  310. // Risk incorrect calculation over throwing errors
  311. unsigned int second = ((datetime.has(SECOND_KEY)) ? static_cast<unsigned int>(datetime[SECOND_KEY]) : 0);
  312. unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast<unsigned int>(datetime[MINUTE_KEY]) : 0);
  313. unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast<unsigned int>(datetime[HOUR_KEY]) : 0);
  314. unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast<unsigned int>(datetime[DAY_KEY]) : 1);
  315. unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast<unsigned int>(datetime[MONTH_KEY]) : 1);
  316. unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast<unsigned int>(datetime[YEAR_KEY]) : 0);
  317. /// How many days come before each month (0-12)
  318. static const unsigned short int DAYS_PAST_THIS_YEAR_TABLE[2][13] = {
  319. /* Normal years. */
  320. { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
  321. /* Leap years. */
  322. { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
  323. };
  324. ERR_FAIL_COND_V_MSG(second > 59, 0, "Invalid second value of: " + itos(second) + ".");
  325. ERR_FAIL_COND_V_MSG(minute > 59, 0, "Invalid minute value of: " + itos(minute) + ".");
  326. ERR_FAIL_COND_V_MSG(hour > 23, 0, "Invalid hour value of: " + itos(hour) + ".");
  327. ERR_FAIL_COND_V_MSG(month > 12 || month == 0, 0, "Invalid month value of: " + itos(month) + ".");
  328. // Do this check after month is tested as valid
  329. ERR_FAIL_COND_V_MSG(day > MONTH_DAYS_TABLE[LEAPYEAR(year)][month - 1] || day == 0, 0, "Invalid day value of '" + itos(day) + "' which is larger than '" + itos(MONTH_DAYS_TABLE[LEAPYEAR(year)][month - 1]) + "' or 0.");
  330. // Calculate all the seconds from months past in this year
  331. uint64_t SECONDS_FROM_MONTHS_PAST_THIS_YEAR = DAYS_PAST_THIS_YEAR_TABLE[LEAPYEAR(year)][month - 1] * SECONDS_PER_DAY;
  332. int64_t SECONDS_FROM_YEARS_PAST = 0;
  333. if (year >= EPOCH_YR) {
  334. for (unsigned int iyear = EPOCH_YR; iyear < year; iyear++) {
  335. SECONDS_FROM_YEARS_PAST += YEARSIZE(iyear) * SECONDS_PER_DAY;
  336. }
  337. } else {
  338. for (unsigned int iyear = EPOCH_YR - 1; iyear >= year; iyear--) {
  339. SECONDS_FROM_YEARS_PAST -= YEARSIZE(iyear) * SECONDS_PER_DAY;
  340. }
  341. }
  342. int64_t epoch =
  343. second +
  344. minute * SECONDS_PER_MINUTE +
  345. hour * SECONDS_PER_HOUR +
  346. // Subtract 1 from day, since the current day isn't over yet
  347. // and we cannot count all 24 hours.
  348. (day - 1) * SECONDS_PER_DAY +
  349. SECONDS_FROM_MONTHS_PAST_THIS_YEAR +
  350. SECONDS_FROM_YEARS_PAST;
  351. return epoch;
  352. }
  353. /**
  354. * Get a dictionary of time values when given epoch time
  355. *
  356. * Dictionary Time values will be a union if values from #get_time
  357. * and #get_date dictionaries (with the exception of dst =
  358. * day light standard time, as it cannot be determined from epoch)
  359. *
  360. * @param unix_time_val epoch time to convert
  361. *
  362. * @return dictionary of date and time values
  363. */
  364. Dictionary _OS::get_datetime_from_unix_time(int64_t unix_time_val) const {
  365. OS::Date date;
  366. OS::Time time;
  367. long dayclock, dayno;
  368. int year = EPOCH_YR;
  369. if (unix_time_val >= 0) {
  370. dayno = unix_time_val / SECS_DAY;
  371. dayclock = unix_time_val % SECS_DAY;
  372. /* day 0 was a thursday */
  373. date.weekday = static_cast<OS::Weekday>((dayno + 4) % 7);
  374. while (dayno >= YEARSIZE(year)) {
  375. dayno -= YEARSIZE(year);
  376. year++;
  377. }
  378. } else {
  379. dayno = (unix_time_val - SECS_DAY + 1) / SECS_DAY;
  380. dayclock = unix_time_val - dayno * SECS_DAY;
  381. date.weekday = static_cast<OS::Weekday>((dayno - 3) % 7 + 7);
  382. do {
  383. year--;
  384. dayno += YEARSIZE(year);
  385. } while (dayno < 0);
  386. }
  387. time.sec = dayclock % 60;
  388. time.min = (dayclock % 3600) / 60;
  389. time.hour = dayclock / 3600;
  390. date.year = year;
  391. size_t imonth = 0;
  392. while ((unsigned long)dayno >= MONTH_DAYS_TABLE[LEAPYEAR(year)][imonth]) {
  393. dayno -= MONTH_DAYS_TABLE[LEAPYEAR(year)][imonth];
  394. imonth++;
  395. }
  396. /// Add 1 to month to make sure months are indexed starting at 1
  397. date.month = static_cast<OS::Month>(imonth + 1);
  398. date.day = dayno + 1;
  399. Dictionary timed;
  400. timed[HOUR_KEY] = time.hour;
  401. timed[MINUTE_KEY] = time.min;
  402. timed[SECOND_KEY] = time.sec;
  403. timed[YEAR_KEY] = date.year;
  404. timed[MONTH_KEY] = date.month;
  405. timed[DAY_KEY] = date.day;
  406. timed[WEEKDAY_KEY] = date.weekday;
  407. return timed;
  408. }
  409. Dictionary _OS::get_time_zone_info() const {
  410. OS::TimeZoneInfo info = OS::get_singleton()->get_time_zone_info();
  411. Dictionary infod;
  412. infod["bias"] = info.bias;
  413. infod["name"] = info.name;
  414. return infod;
  415. }
  416. uint64_t _OS::get_unix_time() const {
  417. return OS::get_singleton()->get_unix_time();
  418. }
  419. uint64_t _OS::get_system_time_secs() const {
  420. return OS::get_singleton()->get_system_time_secs();
  421. }
  422. uint64_t _OS::get_system_time_msecs() const {
  423. return OS::get_singleton()->get_system_time_msecs();
  424. }
  425. void _OS::delay_usec(uint32_t p_usec) const {
  426. OS::get_singleton()->delay_usec(p_usec);
  427. }
  428. void _OS::delay_msec(uint32_t p_msec) const {
  429. OS::get_singleton()->delay_usec(int64_t(p_msec) * 1000);
  430. }
  431. uint32_t _OS::get_ticks_msec() const {
  432. return OS::get_singleton()->get_ticks_msec();
  433. }
  434. uint64_t _OS::get_ticks_usec() const {
  435. return OS::get_singleton()->get_ticks_usec();
  436. }
  437. uint32_t _OS::get_splash_tick_msec() const {
  438. return OS::get_singleton()->get_splash_tick_msec();
  439. }
  440. bool _OS::can_use_threads() const {
  441. return OS::get_singleton()->can_use_threads();
  442. }
  443. bool _OS::is_userfs_persistent() const {
  444. return OS::get_singleton()->is_userfs_persistent();
  445. }
  446. int _OS::get_processor_count() const {
  447. return OS::get_singleton()->get_processor_count();
  448. }
  449. bool _OS::is_stdout_verbose() const {
  450. return OS::get_singleton()->is_stdout_verbose();
  451. }
  452. void _OS::dump_memory_to_file(const String &p_file) {
  453. OS::get_singleton()->dump_memory_to_file(p_file.utf8().get_data());
  454. }
  455. struct _OSCoreBindImg {
  456. String path;
  457. Size2 size;
  458. int fmt;
  459. ObjectID id;
  460. int vram;
  461. bool operator<(const _OSCoreBindImg &p_img) const { return vram == p_img.vram ? id < p_img.id : vram > p_img.vram; }
  462. };
  463. void _OS::print_all_textures_by_size() {
  464. List<_OSCoreBindImg> imgs;
  465. int total = 0;
  466. {
  467. List<Ref<Resource>> rsrc;
  468. ResourceCache::get_cached_resources(&rsrc);
  469. for (List<Ref<Resource>>::Element *E = rsrc.front(); E; E = E->next()) {
  470. if (!E->get()->is_class("ImageTexture")) {
  471. continue;
  472. }
  473. Size2 size = E->get()->call("get_size");
  474. int fmt = E->get()->call("get_format");
  475. _OSCoreBindImg img;
  476. img.size = size;
  477. img.fmt = fmt;
  478. img.path = E->get()->get_path();
  479. img.vram = Image::get_image_data_size(img.size.width, img.size.height, Image::Format(img.fmt));
  480. img.id = E->get()->get_instance_id();
  481. total += img.vram;
  482. imgs.push_back(img);
  483. }
  484. }
  485. imgs.sort();
  486. for (List<_OSCoreBindImg>::Element *E = imgs.front(); E; E = E->next()) {
  487. total -= E->get().vram;
  488. }
  489. }
  490. void _OS::print_resources_by_type(const Vector<String> &p_types) {
  491. Map<String, int> type_count;
  492. List<Ref<Resource>> resources;
  493. ResourceCache::get_cached_resources(&resources);
  494. List<Ref<Resource>> rsrc;
  495. ResourceCache::get_cached_resources(&rsrc);
  496. for (List<Ref<Resource>>::Element *E = rsrc.front(); E; E = E->next()) {
  497. Ref<Resource> r = E->get();
  498. bool found = false;
  499. for (int i = 0; i < p_types.size(); i++) {
  500. if (r->is_class(p_types[i])) {
  501. found = true;
  502. }
  503. }
  504. if (!found) {
  505. continue;
  506. }
  507. if (!type_count.has(r->get_class())) {
  508. type_count[r->get_class()] = 0;
  509. }
  510. type_count[r->get_class()]++;
  511. }
  512. }
  513. void _OS::print_all_resources(const String &p_to_file) {
  514. OS::get_singleton()->print_all_resources(p_to_file);
  515. }
  516. void _OS::print_resources_in_use(bool p_short) {
  517. OS::get_singleton()->print_resources_in_use(p_short);
  518. }
  519. void _OS::dump_resources_to_file(const String &p_file) {
  520. OS::get_singleton()->dump_resources_to_file(p_file.utf8().get_data());
  521. }
  522. String _OS::get_user_data_dir() const {
  523. return OS::get_singleton()->get_user_data_dir();
  524. }
  525. bool _OS::is_debug_build() const {
  526. #ifdef DEBUG_ENABLED
  527. return true;
  528. #else
  529. return false;
  530. #endif
  531. }
  532. String _OS::get_system_dir(SystemDir p_dir) const {
  533. return OS::get_singleton()->get_system_dir(OS::SystemDir(p_dir));
  534. }
  535. String _OS::get_keycode_string(uint32_t p_code) const {
  536. return keycode_get_string(p_code);
  537. }
  538. bool _OS::is_keycode_unicode(uint32_t p_unicode) const {
  539. return keycode_has_unicode(p_unicode);
  540. }
  541. int _OS::find_keycode_from_string(const String &p_code) const {
  542. return find_keycode(p_code);
  543. }
  544. bool _OS::request_permission(const String &p_name) {
  545. return OS::get_singleton()->request_permission(p_name);
  546. }
  547. bool _OS::request_permissions() {
  548. return OS::get_singleton()->request_permissions();
  549. }
  550. Vector<String> _OS::get_granted_permissions() const {
  551. return OS::get_singleton()->get_granted_permissions();
  552. }
  553. String _OS::get_unique_id() const {
  554. return OS::get_singleton()->get_unique_id();
  555. }
  556. int _OS::get_tablet_driver_count() const {
  557. return OS::get_singleton()->get_tablet_driver_count();
  558. }
  559. String _OS::get_tablet_driver_name(int p_driver) const {
  560. return OS::get_singleton()->get_tablet_driver_name(p_driver);
  561. }
  562. String _OS::get_current_tablet_driver() const {
  563. return OS::get_singleton()->get_current_tablet_driver();
  564. }
  565. void _OS::set_current_tablet_driver(const String &p_driver) {
  566. OS::get_singleton()->set_current_tablet_driver(p_driver);
  567. }
  568. _OS *_OS::singleton = nullptr;
  569. void _OS::_bind_methods() {
  570. ClassDB::bind_method(D_METHOD("get_connected_midi_inputs"), &_OS::get_connected_midi_inputs);
  571. ClassDB::bind_method(D_METHOD("open_midi_inputs"), &_OS::open_midi_inputs);
  572. ClassDB::bind_method(D_METHOD("close_midi_inputs"), &_OS::close_midi_inputs);
  573. ClassDB::bind_method(D_METHOD("set_low_processor_usage_mode", "enable"), &_OS::set_low_processor_usage_mode);
  574. ClassDB::bind_method(D_METHOD("is_in_low_processor_usage_mode"), &_OS::is_in_low_processor_usage_mode);
  575. ClassDB::bind_method(D_METHOD("set_low_processor_usage_mode_sleep_usec", "usec"), &_OS::set_low_processor_usage_mode_sleep_usec);
  576. ClassDB::bind_method(D_METHOD("get_low_processor_usage_mode_sleep_usec"), &_OS::get_low_processor_usage_mode_sleep_usec);
  577. ClassDB::bind_method(D_METHOD("get_processor_count"), &_OS::get_processor_count);
  578. ClassDB::bind_method(D_METHOD("get_executable_path"), &_OS::get_executable_path);
  579. ClassDB::bind_method(D_METHOD("execute", "path", "arguments", "blocking", "output", "read_stderr"), &_OS::execute, DEFVAL(true), DEFVAL(Array()), DEFVAL(false));
  580. ClassDB::bind_method(D_METHOD("kill", "pid"), &_OS::kill);
  581. ClassDB::bind_method(D_METHOD("shell_open", "uri"), &_OS::shell_open);
  582. ClassDB::bind_method(D_METHOD("get_process_id"), &_OS::get_process_id);
  583. ClassDB::bind_method(D_METHOD("get_environment", "environment"), &_OS::get_environment);
  584. ClassDB::bind_method(D_METHOD("has_environment", "environment"), &_OS::has_environment);
  585. ClassDB::bind_method(D_METHOD("get_name"), &_OS::get_name);
  586. ClassDB::bind_method(D_METHOD("get_cmdline_args"), &_OS::get_cmdline_args);
  587. ClassDB::bind_method(D_METHOD("get_datetime", "utc"), &_OS::get_datetime, DEFVAL(false));
  588. ClassDB::bind_method(D_METHOD("get_date", "utc"), &_OS::get_date, DEFVAL(false));
  589. ClassDB::bind_method(D_METHOD("get_time", "utc"), &_OS::get_time, DEFVAL(false));
  590. ClassDB::bind_method(D_METHOD("get_time_zone_info"), &_OS::get_time_zone_info);
  591. ClassDB::bind_method(D_METHOD("get_unix_time"), &_OS::get_unix_time);
  592. ClassDB::bind_method(D_METHOD("get_datetime_from_unix_time", "unix_time_val"), &_OS::get_datetime_from_unix_time);
  593. ClassDB::bind_method(D_METHOD("get_unix_time_from_datetime", "datetime"), &_OS::get_unix_time_from_datetime);
  594. ClassDB::bind_method(D_METHOD("get_system_time_secs"), &_OS::get_system_time_secs);
  595. ClassDB::bind_method(D_METHOD("get_system_time_msecs"), &_OS::get_system_time_msecs);
  596. ClassDB::bind_method(D_METHOD("get_exit_code"), &_OS::get_exit_code);
  597. ClassDB::bind_method(D_METHOD("set_exit_code", "code"), &_OS::set_exit_code);
  598. ClassDB::bind_method(D_METHOD("delay_usec", "usec"), &_OS::delay_usec);
  599. ClassDB::bind_method(D_METHOD("delay_msec", "msec"), &_OS::delay_msec);
  600. ClassDB::bind_method(D_METHOD("get_ticks_msec"), &_OS::get_ticks_msec);
  601. ClassDB::bind_method(D_METHOD("get_ticks_usec"), &_OS::get_ticks_usec);
  602. ClassDB::bind_method(D_METHOD("get_splash_tick_msec"), &_OS::get_splash_tick_msec);
  603. ClassDB::bind_method(D_METHOD("get_locale"), &_OS::get_locale);
  604. ClassDB::bind_method(D_METHOD("get_model_name"), &_OS::get_model_name);
  605. ClassDB::bind_method(D_METHOD("is_userfs_persistent"), &_OS::is_userfs_persistent);
  606. ClassDB::bind_method(D_METHOD("is_stdout_verbose"), &_OS::is_stdout_verbose);
  607. ClassDB::bind_method(D_METHOD("can_use_threads"), &_OS::can_use_threads);
  608. ClassDB::bind_method(D_METHOD("is_debug_build"), &_OS::is_debug_build);
  609. ClassDB::bind_method(D_METHOD("dump_memory_to_file", "file"), &_OS::dump_memory_to_file);
  610. ClassDB::bind_method(D_METHOD("dump_resources_to_file", "file"), &_OS::dump_resources_to_file);
  611. ClassDB::bind_method(D_METHOD("print_resources_in_use", "short"), &_OS::print_resources_in_use, DEFVAL(false));
  612. ClassDB::bind_method(D_METHOD("print_all_resources", "tofile"), &_OS::print_all_resources, DEFVAL(""));
  613. ClassDB::bind_method(D_METHOD("get_static_memory_usage"), &_OS::get_static_memory_usage);
  614. ClassDB::bind_method(D_METHOD("get_static_memory_peak_usage"), &_OS::get_static_memory_peak_usage);
  615. ClassDB::bind_method(D_METHOD("get_user_data_dir"), &_OS::get_user_data_dir);
  616. ClassDB::bind_method(D_METHOD("get_system_dir", "dir"), &_OS::get_system_dir);
  617. ClassDB::bind_method(D_METHOD("get_unique_id"), &_OS::get_unique_id);
  618. ClassDB::bind_method(D_METHOD("print_all_textures_by_size"), &_OS::print_all_textures_by_size);
  619. ClassDB::bind_method(D_METHOD("print_resources_by_type", "types"), &_OS::print_resources_by_type);
  620. ClassDB::bind_method(D_METHOD("get_keycode_string", "code"), &_OS::get_keycode_string);
  621. ClassDB::bind_method(D_METHOD("is_keycode_unicode", "code"), &_OS::is_keycode_unicode);
  622. ClassDB::bind_method(D_METHOD("find_keycode_from_string", "string"), &_OS::find_keycode_from_string);
  623. ClassDB::bind_method(D_METHOD("set_use_file_access_save_and_swap", "enabled"), &_OS::set_use_file_access_save_and_swap);
  624. ClassDB::bind_method(D_METHOD("set_thread_name", "name"), &_OS::set_thread_name);
  625. ClassDB::bind_method(D_METHOD("has_feature", "tag_name"), &_OS::has_feature);
  626. ClassDB::bind_method(D_METHOD("request_permission", "name"), &_OS::request_permission);
  627. ClassDB::bind_method(D_METHOD("request_permissions"), &_OS::request_permissions);
  628. ClassDB::bind_method(D_METHOD("get_granted_permissions"), &_OS::get_granted_permissions);
  629. ClassDB::bind_method(D_METHOD("get_tablet_driver_count"), &_OS::get_tablet_driver_count);
  630. ClassDB::bind_method(D_METHOD("get_tablet_driver_name", "idx"), &_OS::get_tablet_driver_name);
  631. ClassDB::bind_method(D_METHOD("get_current_tablet_driver"), &_OS::get_current_tablet_driver);
  632. ClassDB::bind_method(D_METHOD("set_current_tablet_driver", "name"), &_OS::set_current_tablet_driver);
  633. ADD_PROPERTY(PropertyInfo(Variant::INT, "exit_code"), "set_exit_code", "get_exit_code");
  634. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "low_processor_usage_mode"), "set_low_processor_usage_mode", "is_in_low_processor_usage_mode");
  635. ADD_PROPERTY(PropertyInfo(Variant::INT, "low_processor_usage_mode_sleep_usec"), "set_low_processor_usage_mode_sleep_usec", "get_low_processor_usage_mode_sleep_usec");
  636. ADD_PROPERTY(PropertyInfo(Variant::STRING, "tablet_driver"), "set_current_tablet_driver", "get_current_tablet_driver");
  637. // Those default values need to be specified for the docs generator,
  638. // to avoid using values from the documentation writer's own OS instance.
  639. ADD_PROPERTY_DEFAULT("exit_code", 0);
  640. ADD_PROPERTY_DEFAULT("low_processor_usage_mode", false);
  641. ADD_PROPERTY_DEFAULT("low_processor_usage_mode_sleep_usec", 6900);
  642. BIND_ENUM_CONSTANT(VIDEO_DRIVER_GLES2);
  643. BIND_ENUM_CONSTANT(VIDEO_DRIVER_VULKAN);
  644. BIND_ENUM_CONSTANT(DAY_SUNDAY);
  645. BIND_ENUM_CONSTANT(DAY_MONDAY);
  646. BIND_ENUM_CONSTANT(DAY_TUESDAY);
  647. BIND_ENUM_CONSTANT(DAY_WEDNESDAY);
  648. BIND_ENUM_CONSTANT(DAY_THURSDAY);
  649. BIND_ENUM_CONSTANT(DAY_FRIDAY);
  650. BIND_ENUM_CONSTANT(DAY_SATURDAY);
  651. BIND_ENUM_CONSTANT(MONTH_JANUARY);
  652. BIND_ENUM_CONSTANT(MONTH_FEBRUARY);
  653. BIND_ENUM_CONSTANT(MONTH_MARCH);
  654. BIND_ENUM_CONSTANT(MONTH_APRIL);
  655. BIND_ENUM_CONSTANT(MONTH_MAY);
  656. BIND_ENUM_CONSTANT(MONTH_JUNE);
  657. BIND_ENUM_CONSTANT(MONTH_JULY);
  658. BIND_ENUM_CONSTANT(MONTH_AUGUST);
  659. BIND_ENUM_CONSTANT(MONTH_SEPTEMBER);
  660. BIND_ENUM_CONSTANT(MONTH_OCTOBER);
  661. BIND_ENUM_CONSTANT(MONTH_NOVEMBER);
  662. BIND_ENUM_CONSTANT(MONTH_DECEMBER);
  663. BIND_ENUM_CONSTANT(SYSTEM_DIR_DESKTOP);
  664. BIND_ENUM_CONSTANT(SYSTEM_DIR_DCIM);
  665. BIND_ENUM_CONSTANT(SYSTEM_DIR_DOCUMENTS);
  666. BIND_ENUM_CONSTANT(SYSTEM_DIR_DOWNLOADS);
  667. BIND_ENUM_CONSTANT(SYSTEM_DIR_MOVIES);
  668. BIND_ENUM_CONSTANT(SYSTEM_DIR_MUSIC);
  669. BIND_ENUM_CONSTANT(SYSTEM_DIR_PICTURES);
  670. BIND_ENUM_CONSTANT(SYSTEM_DIR_RINGTONES);
  671. }
  672. ////// _Geometry //////
  673. _Geometry *_Geometry::singleton = nullptr;
  674. _Geometry *_Geometry::get_singleton() {
  675. return singleton;
  676. }
  677. Vector<Plane> _Geometry::build_box_planes(const Vector3 &p_extents) {
  678. return Geometry::build_box_planes(p_extents);
  679. }
  680. Vector<Plane> _Geometry::build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis) {
  681. return Geometry::build_cylinder_planes(p_radius, p_height, p_sides, p_axis);
  682. }
  683. Vector<Plane> _Geometry::build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  684. return Geometry::build_capsule_planes(p_radius, p_height, p_sides, p_lats, p_axis);
  685. }
  686. bool _Geometry::is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  687. return Geometry::is_point_in_circle(p_point, p_circle_pos, p_circle_radius);
  688. }
  689. real_t _Geometry::segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  690. return Geometry::segment_intersects_circle(p_from, p_to, p_circle_pos, p_circle_radius);
  691. }
  692. Variant _Geometry::segment_intersects_segment_2d(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b) {
  693. Vector2 result;
  694. if (Geometry::segment_intersects_segment_2d(p_from_a, p_to_a, p_from_b, p_to_b, &result)) {
  695. return result;
  696. } else {
  697. return Variant();
  698. }
  699. }
  700. Variant _Geometry::line_intersects_line_2d(const Vector2 &p_from_a, const Vector2 &p_dir_a, const Vector2 &p_from_b, const Vector2 &p_dir_b) {
  701. Vector2 result;
  702. if (Geometry::line_intersects_line_2d(p_from_a, p_dir_a, p_from_b, p_dir_b, result)) {
  703. return result;
  704. } else {
  705. return Variant();
  706. }
  707. }
  708. Vector<Vector2> _Geometry::get_closest_points_between_segments_2d(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2) {
  709. Vector2 r1, r2;
  710. Geometry::get_closest_points_between_segments(p1, q1, p2, q2, r1, r2);
  711. Vector<Vector2> r;
  712. r.resize(2);
  713. r.set(0, r1);
  714. r.set(1, r2);
  715. return r;
  716. }
  717. Vector<Vector3> _Geometry::get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2) {
  718. Vector3 r1, r2;
  719. Geometry::get_closest_points_between_segments(p1, p2, q1, q2, r1, r2);
  720. Vector<Vector3> r;
  721. r.resize(2);
  722. r.set(0, r1);
  723. r.set(1, r2);
  724. return r;
  725. }
  726. Vector2 _Geometry::get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b) {
  727. Vector2 s[2] = { p_a, p_b };
  728. return Geometry::get_closest_point_to_segment_2d(p_point, s);
  729. }
  730. Vector3 _Geometry::get_closest_point_to_segment(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b) {
  731. Vector3 s[2] = { p_a, p_b };
  732. return Geometry::get_closest_point_to_segment(p_point, s);
  733. }
  734. Vector2 _Geometry::get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b) {
  735. Vector2 s[2] = { p_a, p_b };
  736. return Geometry::get_closest_point_to_segment_uncapped_2d(p_point, s);
  737. }
  738. Vector3 _Geometry::get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b) {
  739. Vector3 s[2] = { p_a, p_b };
  740. return Geometry::get_closest_point_to_segment_uncapped(p_point, s);
  741. }
  742. Variant _Geometry::ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2) {
  743. Vector3 res;
  744. if (Geometry::ray_intersects_triangle(p_from, p_dir, p_v0, p_v1, p_v2, &res)) {
  745. return res;
  746. } else {
  747. return Variant();
  748. }
  749. }
  750. Variant _Geometry::segment_intersects_triangle(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2) {
  751. Vector3 res;
  752. if (Geometry::segment_intersects_triangle(p_from, p_to, p_v0, p_v1, p_v2, &res)) {
  753. return res;
  754. } else {
  755. return Variant();
  756. }
  757. }
  758. bool _Geometry::point_is_inside_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) const {
  759. return Geometry::is_point_in_triangle(s, a, b, c);
  760. }
  761. Vector<Vector3> _Geometry::segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius) {
  762. Vector<Vector3> r;
  763. Vector3 res, norm;
  764. if (!Geometry::segment_intersects_sphere(p_from, p_to, p_sphere_pos, p_sphere_radius, &res, &norm)) {
  765. return r;
  766. }
  767. r.resize(2);
  768. r.set(0, res);
  769. r.set(1, norm);
  770. return r;
  771. }
  772. Vector<Vector3> _Geometry::segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius) {
  773. Vector<Vector3> r;
  774. Vector3 res, norm;
  775. if (!Geometry::segment_intersects_cylinder(p_from, p_to, p_height, p_radius, &res, &norm)) {
  776. return r;
  777. }
  778. r.resize(2);
  779. r.set(0, res);
  780. r.set(1, norm);
  781. return r;
  782. }
  783. Vector<Vector3> _Geometry::segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Vector<Plane> &p_planes) {
  784. Vector<Vector3> r;
  785. Vector3 res, norm;
  786. if (!Geometry::segment_intersects_convex(p_from, p_to, p_planes.ptr(), p_planes.size(), &res, &norm)) {
  787. return r;
  788. }
  789. r.resize(2);
  790. r.set(0, res);
  791. r.set(1, norm);
  792. return r;
  793. }
  794. bool _Geometry::is_polygon_clockwise(const Vector<Vector2> &p_polygon) {
  795. return Geometry::is_polygon_clockwise(p_polygon);
  796. }
  797. bool _Geometry::is_point_in_polygon(const Point2 &p_point, const Vector<Vector2> &p_polygon) {
  798. return Geometry::is_point_in_polygon(p_point, p_polygon);
  799. }
  800. Vector<int> _Geometry::triangulate_polygon(const Vector<Vector2> &p_polygon) {
  801. return Geometry::triangulate_polygon(p_polygon);
  802. }
  803. Vector<int> _Geometry::triangulate_delaunay_2d(const Vector<Vector2> &p_points) {
  804. return Geometry::triangulate_delaunay_2d(p_points);
  805. }
  806. Vector<Point2> _Geometry::convex_hull_2d(const Vector<Point2> &p_points) {
  807. return Geometry::convex_hull_2d(p_points);
  808. }
  809. Vector<Vector3> _Geometry::clip_polygon(const Vector<Vector3> &p_points, const Plane &p_plane) {
  810. return Geometry::clip_polygon(p_points, p_plane);
  811. }
  812. Array _Geometry::merge_polygons_2d(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
  813. Vector<Vector<Point2>> polys = Geometry::merge_polygons_2d(p_polygon_a, p_polygon_b);
  814. Array ret;
  815. for (int i = 0; i < polys.size(); ++i) {
  816. ret.push_back(polys[i]);
  817. }
  818. return ret;
  819. }
  820. Array _Geometry::clip_polygons_2d(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
  821. Vector<Vector<Point2>> polys = Geometry::clip_polygons_2d(p_polygon_a, p_polygon_b);
  822. Array ret;
  823. for (int i = 0; i < polys.size(); ++i) {
  824. ret.push_back(polys[i]);
  825. }
  826. return ret;
  827. }
  828. Array _Geometry::intersect_polygons_2d(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
  829. Vector<Vector<Point2>> polys = Geometry::intersect_polygons_2d(p_polygon_a, p_polygon_b);
  830. Array ret;
  831. for (int i = 0; i < polys.size(); ++i) {
  832. ret.push_back(polys[i]);
  833. }
  834. return ret;
  835. }
  836. Array _Geometry::exclude_polygons_2d(const Vector<Vector2> &p_polygon_a, const Vector<Vector2> &p_polygon_b) {
  837. Vector<Vector<Point2>> polys = Geometry::exclude_polygons_2d(p_polygon_a, p_polygon_b);
  838. Array ret;
  839. for (int i = 0; i < polys.size(); ++i) {
  840. ret.push_back(polys[i]);
  841. }
  842. return ret;
  843. }
  844. Array _Geometry::clip_polyline_with_polygon_2d(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  845. Vector<Vector<Point2>> polys = Geometry::clip_polyline_with_polygon_2d(p_polyline, p_polygon);
  846. Array ret;
  847. for (int i = 0; i < polys.size(); ++i) {
  848. ret.push_back(polys[i]);
  849. }
  850. return ret;
  851. }
  852. Array _Geometry::intersect_polyline_with_polygon_2d(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  853. Vector<Vector<Point2>> polys = Geometry::intersect_polyline_with_polygon_2d(p_polyline, p_polygon);
  854. Array ret;
  855. for (int i = 0; i < polys.size(); ++i) {
  856. ret.push_back(polys[i]);
  857. }
  858. return ret;
  859. }
  860. Array _Geometry::offset_polygon_2d(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
  861. Vector<Vector<Point2>> polys = Geometry::offset_polygon_2d(p_polygon, p_delta, Geometry::PolyJoinType(p_join_type));
  862. Array ret;
  863. for (int i = 0; i < polys.size(); ++i) {
  864. ret.push_back(polys[i]);
  865. }
  866. return ret;
  867. }
  868. Array _Geometry::offset_polyline_2d(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  869. Vector<Vector<Point2>> polys = Geometry::offset_polyline_2d(p_polygon, p_delta, Geometry::PolyJoinType(p_join_type), Geometry::PolyEndType(p_end_type));
  870. Array ret;
  871. for (int i = 0; i < polys.size(); ++i) {
  872. ret.push_back(polys[i]);
  873. }
  874. return ret;
  875. }
  876. Dictionary _Geometry::make_atlas(const Vector<Size2> &p_rects) {
  877. Dictionary ret;
  878. Vector<Size2i> rects;
  879. for (int i = 0; i < p_rects.size(); i++) {
  880. rects.push_back(p_rects[i]);
  881. }
  882. Vector<Point2i> result;
  883. Size2i size;
  884. Geometry::make_atlas(rects, result, size);
  885. Size2 r_size = size;
  886. Vector<Point2> r_result;
  887. for (int i = 0; i < result.size(); i++) {
  888. r_result.push_back(result[i]);
  889. }
  890. ret["points"] = r_result;
  891. ret["size"] = r_size;
  892. return ret;
  893. }
  894. int _Geometry::get_uv84_normal_bit(const Vector3 &p_vector) {
  895. return Geometry::get_uv84_normal_bit(p_vector);
  896. }
  897. void _Geometry::_bind_methods() {
  898. ClassDB::bind_method(D_METHOD("build_box_planes", "extents"), &_Geometry::build_box_planes);
  899. ClassDB::bind_method(D_METHOD("build_cylinder_planes", "radius", "height", "sides", "axis"), &_Geometry::build_cylinder_planes, DEFVAL(Vector3::AXIS_Z));
  900. ClassDB::bind_method(D_METHOD("build_capsule_planes", "radius", "height", "sides", "lats", "axis"), &_Geometry::build_capsule_planes, DEFVAL(Vector3::AXIS_Z));
  901. ClassDB::bind_method(D_METHOD("is_point_in_circle", "point", "circle_position", "circle_radius"), &_Geometry::is_point_in_circle);
  902. ClassDB::bind_method(D_METHOD("segment_intersects_circle", "segment_from", "segment_to", "circle_position", "circle_radius"), &_Geometry::segment_intersects_circle);
  903. ClassDB::bind_method(D_METHOD("segment_intersects_segment_2d", "from_a", "to_a", "from_b", "to_b"), &_Geometry::segment_intersects_segment_2d);
  904. ClassDB::bind_method(D_METHOD("line_intersects_line_2d", "from_a", "dir_a", "from_b", "dir_b"), &_Geometry::line_intersects_line_2d);
  905. ClassDB::bind_method(D_METHOD("get_closest_points_between_segments_2d", "p1", "q1", "p2", "q2"), &_Geometry::get_closest_points_between_segments_2d);
  906. ClassDB::bind_method(D_METHOD("get_closest_points_between_segments", "p1", "p2", "q1", "q2"), &_Geometry::get_closest_points_between_segments);
  907. ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_2d", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment_2d);
  908. ClassDB::bind_method(D_METHOD("get_closest_point_to_segment", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment);
  909. ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped_2d", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment_uncapped_2d);
  910. ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment_uncapped);
  911. ClassDB::bind_method(D_METHOD("get_uv84_normal_bit", "normal"), &_Geometry::get_uv84_normal_bit);
  912. ClassDB::bind_method(D_METHOD("ray_intersects_triangle", "from", "dir", "a", "b", "c"), &_Geometry::ray_intersects_triangle);
  913. ClassDB::bind_method(D_METHOD("segment_intersects_triangle", "from", "to", "a", "b", "c"), &_Geometry::segment_intersects_triangle);
  914. ClassDB::bind_method(D_METHOD("segment_intersects_sphere", "from", "to", "sphere_position", "sphere_radius"), &_Geometry::segment_intersects_sphere);
  915. ClassDB::bind_method(D_METHOD("segment_intersects_cylinder", "from", "to", "height", "radius"), &_Geometry::segment_intersects_cylinder);
  916. ClassDB::bind_method(D_METHOD("segment_intersects_convex", "from", "to", "planes"), &_Geometry::segment_intersects_convex);
  917. ClassDB::bind_method(D_METHOD("point_is_inside_triangle", "point", "a", "b", "c"), &_Geometry::point_is_inside_triangle);
  918. ClassDB::bind_method(D_METHOD("is_polygon_clockwise", "polygon"), &_Geometry::is_polygon_clockwise);
  919. ClassDB::bind_method(D_METHOD("is_point_in_polygon", "point", "polygon"), &_Geometry::is_point_in_polygon);
  920. ClassDB::bind_method(D_METHOD("triangulate_polygon", "polygon"), &_Geometry::triangulate_polygon);
  921. ClassDB::bind_method(D_METHOD("triangulate_delaunay_2d", "points"), &_Geometry::triangulate_delaunay_2d);
  922. ClassDB::bind_method(D_METHOD("convex_hull_2d", "points"), &_Geometry::convex_hull_2d);
  923. ClassDB::bind_method(D_METHOD("clip_polygon", "points", "plane"), &_Geometry::clip_polygon);
  924. ClassDB::bind_method(D_METHOD("merge_polygons_2d", "polygon_a", "polygon_b"), &_Geometry::merge_polygons_2d);
  925. ClassDB::bind_method(D_METHOD("clip_polygons_2d", "polygon_a", "polygon_b"), &_Geometry::clip_polygons_2d);
  926. ClassDB::bind_method(D_METHOD("intersect_polygons_2d", "polygon_a", "polygon_b"), &_Geometry::intersect_polygons_2d);
  927. ClassDB::bind_method(D_METHOD("exclude_polygons_2d", "polygon_a", "polygon_b"), &_Geometry::exclude_polygons_2d);
  928. ClassDB::bind_method(D_METHOD("clip_polyline_with_polygon_2d", "polyline", "polygon"), &_Geometry::clip_polyline_with_polygon_2d);
  929. ClassDB::bind_method(D_METHOD("intersect_polyline_with_polygon_2d", "polyline", "polygon"), &_Geometry::intersect_polyline_with_polygon_2d);
  930. ClassDB::bind_method(D_METHOD("offset_polygon_2d", "polygon", "delta", "join_type"), &_Geometry::offset_polygon_2d, DEFVAL(JOIN_SQUARE));
  931. ClassDB::bind_method(D_METHOD("offset_polyline_2d", "polyline", "delta", "join_type", "end_type"), &_Geometry::offset_polyline_2d, DEFVAL(JOIN_SQUARE), DEFVAL(END_SQUARE));
  932. ClassDB::bind_method(D_METHOD("make_atlas", "sizes"), &_Geometry::make_atlas);
  933. BIND_ENUM_CONSTANT(OPERATION_UNION);
  934. BIND_ENUM_CONSTANT(OPERATION_DIFFERENCE);
  935. BIND_ENUM_CONSTANT(OPERATION_INTERSECTION);
  936. BIND_ENUM_CONSTANT(OPERATION_XOR);
  937. BIND_ENUM_CONSTANT(JOIN_SQUARE);
  938. BIND_ENUM_CONSTANT(JOIN_ROUND);
  939. BIND_ENUM_CONSTANT(JOIN_MITER);
  940. BIND_ENUM_CONSTANT(END_POLYGON);
  941. BIND_ENUM_CONSTANT(END_JOINED);
  942. BIND_ENUM_CONSTANT(END_BUTT);
  943. BIND_ENUM_CONSTANT(END_SQUARE);
  944. BIND_ENUM_CONSTANT(END_ROUND);
  945. }
  946. ////// _File //////
  947. Error _File::open_encrypted(const String &p_path, ModeFlags p_mode_flags, const Vector<uint8_t> &p_key) {
  948. Error err = open(p_path, p_mode_flags);
  949. if (err) {
  950. return err;
  951. }
  952. FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
  953. err = fae->open_and_parse(f, p_key, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ);
  954. if (err) {
  955. memdelete(fae);
  956. close();
  957. return err;
  958. }
  959. f = fae;
  960. return OK;
  961. }
  962. Error _File::open_encrypted_pass(const String &p_path, ModeFlags p_mode_flags, const String &p_pass) {
  963. Error err = open(p_path, p_mode_flags);
  964. if (err) {
  965. return err;
  966. }
  967. FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
  968. err = fae->open_and_parse_password(f, p_pass, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ);
  969. if (err) {
  970. memdelete(fae);
  971. close();
  972. return err;
  973. }
  974. f = fae;
  975. return OK;
  976. }
  977. Error _File::open_compressed(const String &p_path, ModeFlags p_mode_flags, CompressionMode p_compress_mode) {
  978. FileAccessCompressed *fac = memnew(FileAccessCompressed);
  979. fac->configure("GCPF", (Compression::Mode)p_compress_mode);
  980. Error err = fac->_open(p_path, p_mode_flags);
  981. if (err) {
  982. memdelete(fac);
  983. return err;
  984. }
  985. f = fac;
  986. return OK;
  987. }
  988. Error _File::open(const String &p_path, ModeFlags p_mode_flags) {
  989. close();
  990. Error err;
  991. f = FileAccess::open(p_path, p_mode_flags, &err);
  992. if (f) {
  993. f->set_endian_swap(eswap);
  994. }
  995. return err;
  996. }
  997. void _File::close() {
  998. if (f) {
  999. memdelete(f);
  1000. }
  1001. f = nullptr;
  1002. }
  1003. bool _File::is_open() const {
  1004. return f != nullptr;
  1005. }
  1006. String _File::get_path() const {
  1007. ERR_FAIL_COND_V_MSG(!f, "", "File must be opened before use.");
  1008. return f->get_path();
  1009. }
  1010. String _File::get_path_absolute() const {
  1011. ERR_FAIL_COND_V_MSG(!f, "", "File must be opened before use.");
  1012. return f->get_path_absolute();
  1013. }
  1014. void _File::seek(int64_t p_position) {
  1015. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1016. f->seek(p_position);
  1017. }
  1018. void _File::seek_end(int64_t p_position) {
  1019. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1020. f->seek_end(p_position);
  1021. }
  1022. int64_t _File::get_position() const {
  1023. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1024. return f->get_position();
  1025. }
  1026. int64_t _File::get_len() const {
  1027. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1028. return f->get_len();
  1029. }
  1030. bool _File::eof_reached() const {
  1031. ERR_FAIL_COND_V_MSG(!f, false, "File must be opened before use.");
  1032. return f->eof_reached();
  1033. }
  1034. uint8_t _File::get_8() const {
  1035. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1036. return f->get_8();
  1037. }
  1038. uint16_t _File::get_16() const {
  1039. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1040. return f->get_16();
  1041. }
  1042. uint32_t _File::get_32() const {
  1043. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1044. return f->get_32();
  1045. }
  1046. uint64_t _File::get_64() const {
  1047. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1048. return f->get_64();
  1049. }
  1050. float _File::get_float() const {
  1051. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1052. return f->get_float();
  1053. }
  1054. double _File::get_double() const {
  1055. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1056. return f->get_double();
  1057. }
  1058. real_t _File::get_real() const {
  1059. ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use.");
  1060. return f->get_real();
  1061. }
  1062. Vector<uint8_t> _File::get_buffer(int p_length) const {
  1063. Vector<uint8_t> data;
  1064. ERR_FAIL_COND_V_MSG(!f, data, "File must be opened before use.");
  1065. ERR_FAIL_COND_V_MSG(p_length < 0, data, "Length of buffer cannot be smaller than 0.");
  1066. if (p_length == 0) {
  1067. return data;
  1068. }
  1069. Error err = data.resize(p_length);
  1070. ERR_FAIL_COND_V_MSG(err != OK, data, "Can't resize data to " + itos(p_length) + " elements.");
  1071. uint8_t *w = data.ptrw();
  1072. int len = f->get_buffer(&w[0], p_length);
  1073. ERR_FAIL_COND_V(len < 0, Vector<uint8_t>());
  1074. if (len < p_length) {
  1075. data.resize(p_length);
  1076. }
  1077. return data;
  1078. }
  1079. String _File::get_as_text() const {
  1080. ERR_FAIL_COND_V_MSG(!f, String(), "File must be opened before use.");
  1081. String text;
  1082. size_t original_pos = f->get_position();
  1083. f->seek(0);
  1084. String l = get_line();
  1085. while (!eof_reached()) {
  1086. text += l + "\n";
  1087. l = get_line();
  1088. }
  1089. text += l;
  1090. f->seek(original_pos);
  1091. return text;
  1092. }
  1093. String _File::get_md5(const String &p_path) const {
  1094. return FileAccess::get_md5(p_path);
  1095. }
  1096. String _File::get_sha256(const String &p_path) const {
  1097. return FileAccess::get_sha256(p_path);
  1098. }
  1099. String _File::get_line() const {
  1100. ERR_FAIL_COND_V_MSG(!f, String(), "File must be opened before use.");
  1101. return f->get_line();
  1102. }
  1103. Vector<String> _File::get_csv_line(const String &p_delim) const {
  1104. ERR_FAIL_COND_V_MSG(!f, Vector<String>(), "File must be opened before use.");
  1105. return f->get_csv_line(p_delim);
  1106. }
  1107. /**< use this for files WRITTEN in _big_ endian machines (ie, amiga/mac)
  1108. * It's not about the current CPU type but file formats.
  1109. * this flags get reset to false (little endian) on each open
  1110. */
  1111. void _File::set_endian_swap(bool p_swap) {
  1112. eswap = p_swap;
  1113. if (f) {
  1114. f->set_endian_swap(p_swap);
  1115. }
  1116. }
  1117. bool _File::get_endian_swap() {
  1118. return eswap;
  1119. }
  1120. Error _File::get_error() const {
  1121. if (!f) {
  1122. return ERR_UNCONFIGURED;
  1123. }
  1124. return f->get_error();
  1125. }
  1126. void _File::store_8(uint8_t p_dest) {
  1127. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1128. f->store_8(p_dest);
  1129. }
  1130. void _File::store_16(uint16_t p_dest) {
  1131. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1132. f->store_16(p_dest);
  1133. }
  1134. void _File::store_32(uint32_t p_dest) {
  1135. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1136. f->store_32(p_dest);
  1137. }
  1138. void _File::store_64(uint64_t p_dest) {
  1139. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1140. f->store_64(p_dest);
  1141. }
  1142. void _File::store_float(float p_dest) {
  1143. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1144. f->store_float(p_dest);
  1145. }
  1146. void _File::store_double(double p_dest) {
  1147. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1148. f->store_double(p_dest);
  1149. }
  1150. void _File::store_real(real_t p_real) {
  1151. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1152. f->store_real(p_real);
  1153. }
  1154. void _File::store_string(const String &p_string) {
  1155. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1156. f->store_string(p_string);
  1157. }
  1158. void _File::store_pascal_string(const String &p_string) {
  1159. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1160. f->store_pascal_string(p_string);
  1161. }
  1162. String _File::get_pascal_string() {
  1163. ERR_FAIL_COND_V_MSG(!f, "", "File must be opened before use.");
  1164. return f->get_pascal_string();
  1165. }
  1166. void _File::store_line(const String &p_string) {
  1167. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1168. f->store_line(p_string);
  1169. }
  1170. void _File::store_csv_line(const Vector<String> &p_values, const String &p_delim) {
  1171. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1172. f->store_csv_line(p_values, p_delim);
  1173. }
  1174. void _File::store_buffer(const Vector<uint8_t> &p_buffer) {
  1175. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1176. int len = p_buffer.size();
  1177. if (len == 0) {
  1178. return;
  1179. }
  1180. const uint8_t *r = p_buffer.ptr();
  1181. f->store_buffer(&r[0], len);
  1182. }
  1183. bool _File::file_exists(const String &p_name) const {
  1184. return FileAccess::exists(p_name);
  1185. }
  1186. void _File::store_var(const Variant &p_var, bool p_full_objects) {
  1187. ERR_FAIL_COND_MSG(!f, "File must be opened before use.");
  1188. int len;
  1189. Error err = encode_variant(p_var, nullptr, len, p_full_objects);
  1190. ERR_FAIL_COND_MSG(err != OK, "Error when trying to encode Variant.");
  1191. Vector<uint8_t> buff;
  1192. buff.resize(len);
  1193. uint8_t *w = buff.ptrw();
  1194. err = encode_variant(p_var, &w[0], len, p_full_objects);
  1195. ERR_FAIL_COND_MSG(err != OK, "Error when trying to encode Variant.");
  1196. store_32(len);
  1197. store_buffer(buff);
  1198. }
  1199. Variant _File::get_var(bool p_allow_objects) const {
  1200. ERR_FAIL_COND_V_MSG(!f, Variant(), "File must be opened before use.");
  1201. uint32_t len = get_32();
  1202. Vector<uint8_t> buff = get_buffer(len);
  1203. ERR_FAIL_COND_V((uint32_t)buff.size() != len, Variant());
  1204. const uint8_t *r = buff.ptr();
  1205. Variant v;
  1206. Error err = decode_variant(v, &r[0], len, nullptr, p_allow_objects);
  1207. ERR_FAIL_COND_V_MSG(err != OK, Variant(), "Error when trying to encode Variant.");
  1208. return v;
  1209. }
  1210. uint64_t _File::get_modified_time(const String &p_file) const {
  1211. return FileAccess::get_modified_time(p_file);
  1212. }
  1213. void _File::_bind_methods() {
  1214. ClassDB::bind_method(D_METHOD("open_encrypted", "path", "mode_flags", "key"), &_File::open_encrypted);
  1215. ClassDB::bind_method(D_METHOD("open_encrypted_with_pass", "path", "mode_flags", "pass"), &_File::open_encrypted_pass);
  1216. ClassDB::bind_method(D_METHOD("open_compressed", "path", "mode_flags", "compression_mode"), &_File::open_compressed, DEFVAL(0));
  1217. ClassDB::bind_method(D_METHOD("open", "path", "flags"), &_File::open);
  1218. ClassDB::bind_method(D_METHOD("close"), &_File::close);
  1219. ClassDB::bind_method(D_METHOD("get_path"), &_File::get_path);
  1220. ClassDB::bind_method(D_METHOD("get_path_absolute"), &_File::get_path_absolute);
  1221. ClassDB::bind_method(D_METHOD("is_open"), &_File::is_open);
  1222. ClassDB::bind_method(D_METHOD("seek", "position"), &_File::seek);
  1223. ClassDB::bind_method(D_METHOD("seek_end", "position"), &_File::seek_end, DEFVAL(0));
  1224. ClassDB::bind_method(D_METHOD("get_position"), &_File::get_position);
  1225. ClassDB::bind_method(D_METHOD("get_len"), &_File::get_len);
  1226. ClassDB::bind_method(D_METHOD("eof_reached"), &_File::eof_reached);
  1227. ClassDB::bind_method(D_METHOD("get_8"), &_File::get_8);
  1228. ClassDB::bind_method(D_METHOD("get_16"), &_File::get_16);
  1229. ClassDB::bind_method(D_METHOD("get_32"), &_File::get_32);
  1230. ClassDB::bind_method(D_METHOD("get_64"), &_File::get_64);
  1231. ClassDB::bind_method(D_METHOD("get_float"), &_File::get_float);
  1232. ClassDB::bind_method(D_METHOD("get_double"), &_File::get_double);
  1233. ClassDB::bind_method(D_METHOD("get_real"), &_File::get_real);
  1234. ClassDB::bind_method(D_METHOD("get_buffer", "len"), &_File::get_buffer);
  1235. ClassDB::bind_method(D_METHOD("get_line"), &_File::get_line);
  1236. ClassDB::bind_method(D_METHOD("get_csv_line", "delim"), &_File::get_csv_line, DEFVAL(","));
  1237. ClassDB::bind_method(D_METHOD("get_as_text"), &_File::get_as_text);
  1238. ClassDB::bind_method(D_METHOD("get_md5", "path"), &_File::get_md5);
  1239. ClassDB::bind_method(D_METHOD("get_sha256", "path"), &_File::get_sha256);
  1240. ClassDB::bind_method(D_METHOD("get_endian_swap"), &_File::get_endian_swap);
  1241. ClassDB::bind_method(D_METHOD("set_endian_swap", "enable"), &_File::set_endian_swap);
  1242. ClassDB::bind_method(D_METHOD("get_error"), &_File::get_error);
  1243. ClassDB::bind_method(D_METHOD("get_var", "allow_objects"), &_File::get_var, DEFVAL(false));
  1244. ClassDB::bind_method(D_METHOD("store_8", "value"), &_File::store_8);
  1245. ClassDB::bind_method(D_METHOD("store_16", "value"), &_File::store_16);
  1246. ClassDB::bind_method(D_METHOD("store_32", "value"), &_File::store_32);
  1247. ClassDB::bind_method(D_METHOD("store_64", "value"), &_File::store_64);
  1248. ClassDB::bind_method(D_METHOD("store_float", "value"), &_File::store_float);
  1249. ClassDB::bind_method(D_METHOD("store_double", "value"), &_File::store_double);
  1250. ClassDB::bind_method(D_METHOD("store_real", "value"), &_File::store_real);
  1251. ClassDB::bind_method(D_METHOD("store_buffer", "buffer"), &_File::store_buffer);
  1252. ClassDB::bind_method(D_METHOD("store_line", "line"), &_File::store_line);
  1253. ClassDB::bind_method(D_METHOD("store_csv_line", "values", "delim"), &_File::store_csv_line, DEFVAL(","));
  1254. ClassDB::bind_method(D_METHOD("store_string", "string"), &_File::store_string);
  1255. ClassDB::bind_method(D_METHOD("store_var", "value", "full_objects"), &_File::store_var, DEFVAL(false));
  1256. ClassDB::bind_method(D_METHOD("store_pascal_string", "string"), &_File::store_pascal_string);
  1257. ClassDB::bind_method(D_METHOD("get_pascal_string"), &_File::get_pascal_string);
  1258. ClassDB::bind_method(D_METHOD("file_exists", "path"), &_File::file_exists);
  1259. ClassDB::bind_method(D_METHOD("get_modified_time", "file"), &_File::get_modified_time);
  1260. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "endian_swap"), "set_endian_swap", "get_endian_swap");
  1261. BIND_ENUM_CONSTANT(READ);
  1262. BIND_ENUM_CONSTANT(WRITE);
  1263. BIND_ENUM_CONSTANT(READ_WRITE);
  1264. BIND_ENUM_CONSTANT(WRITE_READ);
  1265. BIND_ENUM_CONSTANT(COMPRESSION_FASTLZ);
  1266. BIND_ENUM_CONSTANT(COMPRESSION_DEFLATE);
  1267. BIND_ENUM_CONSTANT(COMPRESSION_ZSTD);
  1268. BIND_ENUM_CONSTANT(COMPRESSION_GZIP);
  1269. }
  1270. _File::~_File() {
  1271. if (f) {
  1272. memdelete(f);
  1273. }
  1274. }
  1275. ////// _Directory //////
  1276. Error _Directory::open(const String &p_path) {
  1277. Error err;
  1278. DirAccess *alt = DirAccess::open(p_path, &err);
  1279. if (!alt) {
  1280. return err;
  1281. }
  1282. if (d) {
  1283. memdelete(d);
  1284. }
  1285. d = alt;
  1286. return OK;
  1287. }
  1288. Error _Directory::list_dir_begin(bool p_skip_navigational, bool p_skip_hidden) {
  1289. ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory must be opened before use.");
  1290. _list_skip_navigational = p_skip_navigational;
  1291. _list_skip_hidden = p_skip_hidden;
  1292. return d->list_dir_begin();
  1293. }
  1294. String _Directory::get_next() {
  1295. ERR_FAIL_COND_V_MSG(!d, "", "Directory must be opened before use.");
  1296. String next = d->get_next();
  1297. while (next != "" && ((_list_skip_navigational && (next == "." || next == "..")) || (_list_skip_hidden && d->current_is_hidden()))) {
  1298. next = d->get_next();
  1299. }
  1300. return next;
  1301. }
  1302. bool _Directory::current_is_dir() const {
  1303. ERR_FAIL_COND_V_MSG(!d, false, "Directory must be opened before use.");
  1304. return d->current_is_dir();
  1305. }
  1306. void _Directory::list_dir_end() {
  1307. ERR_FAIL_COND_MSG(!d, "Directory must be opened before use.");
  1308. d->list_dir_end();
  1309. }
  1310. int _Directory::get_drive_count() {
  1311. ERR_FAIL_COND_V_MSG(!d, 0, "Directory must be opened before use.");
  1312. return d->get_drive_count();
  1313. }
  1314. String _Directory::get_drive(int p_drive) {
  1315. ERR_FAIL_COND_V_MSG(!d, "", "Directory must be opened before use.");
  1316. return d->get_drive(p_drive);
  1317. }
  1318. int _Directory::get_current_drive() {
  1319. ERR_FAIL_COND_V_MSG(!d, 0, "Directory must be opened before use.");
  1320. return d->get_current_drive();
  1321. }
  1322. Error _Directory::change_dir(String p_dir) {
  1323. ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory must be opened before use.");
  1324. return d->change_dir(p_dir);
  1325. }
  1326. String _Directory::get_current_dir() {
  1327. ERR_FAIL_COND_V_MSG(!d, "", "Directory must be opened before use.");
  1328. return d->get_current_dir();
  1329. }
  1330. Error _Directory::make_dir(String p_dir) {
  1331. ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory must be opened before use.");
  1332. if (!p_dir.is_rel_path()) {
  1333. DirAccess *d = DirAccess::create_for_path(p_dir);
  1334. Error err = d->make_dir(p_dir);
  1335. memdelete(d);
  1336. return err;
  1337. }
  1338. return d->make_dir(p_dir);
  1339. }
  1340. Error _Directory::make_dir_recursive(String p_dir) {
  1341. ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory must be opened before use.");
  1342. if (!p_dir.is_rel_path()) {
  1343. DirAccess *d = DirAccess::create_for_path(p_dir);
  1344. Error err = d->make_dir_recursive(p_dir);
  1345. memdelete(d);
  1346. return err;
  1347. }
  1348. return d->make_dir_recursive(p_dir);
  1349. }
  1350. bool _Directory::file_exists(String p_file) {
  1351. ERR_FAIL_COND_V_MSG(!d, false, "Directory must be opened before use.");
  1352. if (!p_file.is_rel_path()) {
  1353. return FileAccess::exists(p_file);
  1354. }
  1355. return d->file_exists(p_file);
  1356. }
  1357. bool _Directory::dir_exists(String p_dir) {
  1358. ERR_FAIL_COND_V_MSG(!d, false, "Directory must be opened before use.");
  1359. if (!p_dir.is_rel_path()) {
  1360. DirAccess *d = DirAccess::create_for_path(p_dir);
  1361. bool exists = d->dir_exists(p_dir);
  1362. memdelete(d);
  1363. return exists;
  1364. } else {
  1365. return d->dir_exists(p_dir);
  1366. }
  1367. }
  1368. int _Directory::get_space_left() {
  1369. ERR_FAIL_COND_V_MSG(!d, 0, "Directory must be opened before use.");
  1370. return d->get_space_left() / 1024 * 1024; //return value in megabytes, given binding is int
  1371. }
  1372. Error _Directory::copy(String p_from, String p_to) {
  1373. ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory must be opened before use.");
  1374. return d->copy(p_from, p_to);
  1375. }
  1376. Error _Directory::rename(String p_from, String p_to) {
  1377. ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory must be opened before use.");
  1378. if (!p_from.is_rel_path()) {
  1379. DirAccess *d = DirAccess::create_for_path(p_from);
  1380. Error err = d->rename(p_from, p_to);
  1381. memdelete(d);
  1382. return err;
  1383. }
  1384. return d->rename(p_from, p_to);
  1385. }
  1386. Error _Directory::remove(String p_name) {
  1387. ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory must be opened before use.");
  1388. if (!p_name.is_rel_path()) {
  1389. DirAccess *d = DirAccess::create_for_path(p_name);
  1390. Error err = d->remove(p_name);
  1391. memdelete(d);
  1392. return err;
  1393. }
  1394. return d->remove(p_name);
  1395. }
  1396. void _Directory::_bind_methods() {
  1397. ClassDB::bind_method(D_METHOD("open", "path"), &_Directory::open);
  1398. ClassDB::bind_method(D_METHOD("list_dir_begin", "skip_navigational", "skip_hidden"), &_Directory::list_dir_begin, DEFVAL(false), DEFVAL(false));
  1399. ClassDB::bind_method(D_METHOD("get_next"), &_Directory::get_next);
  1400. ClassDB::bind_method(D_METHOD("current_is_dir"), &_Directory::current_is_dir);
  1401. ClassDB::bind_method(D_METHOD("list_dir_end"), &_Directory::list_dir_end);
  1402. ClassDB::bind_method(D_METHOD("get_drive_count"), &_Directory::get_drive_count);
  1403. ClassDB::bind_method(D_METHOD("get_drive", "idx"), &_Directory::get_drive);
  1404. ClassDB::bind_method(D_METHOD("get_current_drive"), &_Directory::get_current_drive);
  1405. ClassDB::bind_method(D_METHOD("change_dir", "todir"), &_Directory::change_dir);
  1406. ClassDB::bind_method(D_METHOD("get_current_dir"), &_Directory::get_current_dir);
  1407. ClassDB::bind_method(D_METHOD("make_dir", "path"), &_Directory::make_dir);
  1408. ClassDB::bind_method(D_METHOD("make_dir_recursive", "path"), &_Directory::make_dir_recursive);
  1409. ClassDB::bind_method(D_METHOD("file_exists", "path"), &_Directory::file_exists);
  1410. ClassDB::bind_method(D_METHOD("dir_exists", "path"), &_Directory::dir_exists);
  1411. //ClassDB::bind_method(D_METHOD("get_modified_time","file"),&_Directory::get_modified_time);
  1412. ClassDB::bind_method(D_METHOD("get_space_left"), &_Directory::get_space_left);
  1413. ClassDB::bind_method(D_METHOD("copy", "from", "to"), &_Directory::copy);
  1414. ClassDB::bind_method(D_METHOD("rename", "from", "to"), &_Directory::rename);
  1415. ClassDB::bind_method(D_METHOD("remove", "path"), &_Directory::remove);
  1416. }
  1417. _Directory::_Directory() {
  1418. d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  1419. }
  1420. _Directory::~_Directory() {
  1421. if (d) {
  1422. memdelete(d);
  1423. }
  1424. }
  1425. ////// _Marshalls //////
  1426. _Marshalls *_Marshalls::singleton = nullptr;
  1427. _Marshalls *_Marshalls::get_singleton() {
  1428. return singleton;
  1429. }
  1430. String _Marshalls::variant_to_base64(const Variant &p_var, bool p_full_objects) {
  1431. int len;
  1432. Error err = encode_variant(p_var, nullptr, len, p_full_objects);
  1433. ERR_FAIL_COND_V_MSG(err != OK, "", "Error when trying to encode Variant.");
  1434. Vector<uint8_t> buff;
  1435. buff.resize(len);
  1436. uint8_t *w = buff.ptrw();
  1437. err = encode_variant(p_var, &w[0], len, p_full_objects);
  1438. ERR_FAIL_COND_V_MSG(err != OK, "", "Error when trying to encode Variant.");
  1439. String ret = CryptoCore::b64_encode_str(&w[0], len);
  1440. ERR_FAIL_COND_V(ret == "", ret);
  1441. return ret;
  1442. }
  1443. Variant _Marshalls::base64_to_variant(const String &p_str, bool p_allow_objects) {
  1444. int strlen = p_str.length();
  1445. CharString cstr = p_str.ascii();
  1446. Vector<uint8_t> buf;
  1447. buf.resize(strlen / 4 * 3 + 1);
  1448. uint8_t *w = buf.ptrw();
  1449. size_t len = 0;
  1450. ERR_FAIL_COND_V(CryptoCore::b64_decode(&w[0], buf.size(), &len, (unsigned char *)cstr.get_data(), strlen) != OK, Variant());
  1451. Variant v;
  1452. Error err = decode_variant(v, &w[0], len, nullptr, p_allow_objects);
  1453. ERR_FAIL_COND_V_MSG(err != OK, Variant(), "Error when trying to decode Variant.");
  1454. return v;
  1455. }
  1456. String _Marshalls::raw_to_base64(const Vector<uint8_t> &p_arr) {
  1457. String ret = CryptoCore::b64_encode_str(p_arr.ptr(), p_arr.size());
  1458. ERR_FAIL_COND_V(ret == "", ret);
  1459. return ret;
  1460. }
  1461. Vector<uint8_t> _Marshalls::base64_to_raw(const String &p_str) {
  1462. int strlen = p_str.length();
  1463. CharString cstr = p_str.ascii();
  1464. size_t arr_len = 0;
  1465. Vector<uint8_t> buf;
  1466. {
  1467. buf.resize(strlen / 4 * 3 + 1);
  1468. uint8_t *w = buf.ptrw();
  1469. ERR_FAIL_COND_V(CryptoCore::b64_decode(&w[0], buf.size(), &arr_len, (unsigned char *)cstr.get_data(), strlen) != OK, Vector<uint8_t>());
  1470. }
  1471. buf.resize(arr_len);
  1472. return buf;
  1473. }
  1474. String _Marshalls::utf8_to_base64(const String &p_str) {
  1475. CharString cstr = p_str.utf8();
  1476. String ret = CryptoCore::b64_encode_str((unsigned char *)cstr.get_data(), cstr.length());
  1477. ERR_FAIL_COND_V(ret == "", ret);
  1478. return ret;
  1479. }
  1480. String _Marshalls::base64_to_utf8(const String &p_str) {
  1481. int strlen = p_str.length();
  1482. CharString cstr = p_str.ascii();
  1483. Vector<uint8_t> buf;
  1484. buf.resize(strlen / 4 * 3 + 1 + 1);
  1485. uint8_t *w = buf.ptrw();
  1486. size_t len = 0;
  1487. ERR_FAIL_COND_V(CryptoCore::b64_decode(&w[0], buf.size(), &len, (unsigned char *)cstr.get_data(), strlen) != OK, String());
  1488. w[len] = 0;
  1489. String ret = String::utf8((char *)&w[0]);
  1490. return ret;
  1491. }
  1492. void _Marshalls::_bind_methods() {
  1493. ClassDB::bind_method(D_METHOD("variant_to_base64", "variant", "full_objects"), &_Marshalls::variant_to_base64, DEFVAL(false));
  1494. ClassDB::bind_method(D_METHOD("base64_to_variant", "base64_str", "allow_objects"), &_Marshalls::base64_to_variant, DEFVAL(false));
  1495. ClassDB::bind_method(D_METHOD("raw_to_base64", "array"), &_Marshalls::raw_to_base64);
  1496. ClassDB::bind_method(D_METHOD("base64_to_raw", "base64_str"), &_Marshalls::base64_to_raw);
  1497. ClassDB::bind_method(D_METHOD("utf8_to_base64", "utf8_str"), &_Marshalls::utf8_to_base64);
  1498. ClassDB::bind_method(D_METHOD("base64_to_utf8", "base64_str"), &_Marshalls::base64_to_utf8);
  1499. }
  1500. ////// _Semaphore //////
  1501. void _Semaphore::wait() {
  1502. semaphore.wait();
  1503. }
  1504. Error _Semaphore::try_wait() {
  1505. return semaphore.try_wait() ? OK : ERR_BUSY;
  1506. }
  1507. void _Semaphore::post() {
  1508. semaphore.post();
  1509. }
  1510. void _Semaphore::_bind_methods() {
  1511. ClassDB::bind_method(D_METHOD("wait"), &_Semaphore::wait);
  1512. ClassDB::bind_method(D_METHOD("try_wait"), &_Semaphore::try_wait);
  1513. ClassDB::bind_method(D_METHOD("post"), &_Semaphore::post);
  1514. }
  1515. ////// _Mutex //////
  1516. void _Mutex::lock() {
  1517. mutex.lock();
  1518. }
  1519. Error _Mutex::try_lock() {
  1520. return mutex.try_lock();
  1521. }
  1522. void _Mutex::unlock() {
  1523. mutex.unlock();
  1524. }
  1525. void _Mutex::_bind_methods() {
  1526. ClassDB::bind_method(D_METHOD("lock"), &_Mutex::lock);
  1527. ClassDB::bind_method(D_METHOD("try_lock"), &_Mutex::try_lock);
  1528. ClassDB::bind_method(D_METHOD("unlock"), &_Mutex::unlock);
  1529. }
  1530. ////// _Thread //////
  1531. void _Thread::_start_func(void *ud) {
  1532. Ref<_Thread> *tud = (Ref<_Thread> *)ud;
  1533. Ref<_Thread> t = *tud;
  1534. memdelete(tud);
  1535. Callable::CallError ce;
  1536. const Variant *arg[1] = { &t->userdata };
  1537. Thread::set_name(t->target_method);
  1538. t->ret = t->target_instance->call(t->target_method, arg, 1, ce);
  1539. if (ce.error != Callable::CallError::CALL_OK) {
  1540. String reason;
  1541. switch (ce.error) {
  1542. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  1543. reason = "Invalid Argument #" + itos(ce.argument);
  1544. } break;
  1545. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: {
  1546. reason = "Too Many Arguments";
  1547. } break;
  1548. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: {
  1549. reason = "Too Few Arguments";
  1550. } break;
  1551. case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
  1552. reason = "Method Not Found";
  1553. } break;
  1554. default: {
  1555. }
  1556. }
  1557. ERR_FAIL_MSG("Could not call function '" + t->target_method.operator String() + "' to start thread " + t->get_id() + ": " + reason + ".");
  1558. }
  1559. }
  1560. Error _Thread::start(Object *p_instance, const StringName &p_method, const Variant &p_userdata, Priority p_priority) {
  1561. ERR_FAIL_COND_V_MSG(active, ERR_ALREADY_IN_USE, "Thread already started.");
  1562. ERR_FAIL_COND_V(!p_instance, ERR_INVALID_PARAMETER);
  1563. ERR_FAIL_COND_V(p_method == StringName(), ERR_INVALID_PARAMETER);
  1564. ERR_FAIL_INDEX_V(p_priority, PRIORITY_MAX, ERR_INVALID_PARAMETER);
  1565. ret = Variant();
  1566. target_method = p_method;
  1567. target_instance = p_instance;
  1568. userdata = p_userdata;
  1569. active = true;
  1570. Ref<_Thread> *ud = memnew(Ref<_Thread>(this));
  1571. Thread::Settings s;
  1572. s.priority = (Thread::Priority)p_priority;
  1573. thread = Thread::create(_start_func, ud, s);
  1574. if (!thread) {
  1575. active = false;
  1576. target_method = StringName();
  1577. target_instance = nullptr;
  1578. userdata = Variant();
  1579. return ERR_CANT_CREATE;
  1580. }
  1581. return OK;
  1582. }
  1583. String _Thread::get_id() const {
  1584. if (!thread) {
  1585. return String();
  1586. }
  1587. return itos(thread->get_id());
  1588. }
  1589. bool _Thread::is_active() const {
  1590. return active;
  1591. }
  1592. Variant _Thread::wait_to_finish() {
  1593. ERR_FAIL_COND_V_MSG(!thread, Variant(), "Thread must exist to wait for its completion.");
  1594. ERR_FAIL_COND_V_MSG(!active, Variant(), "Thread must be active to wait for its completion.");
  1595. Thread::wait_to_finish(thread);
  1596. Variant r = ret;
  1597. active = false;
  1598. target_method = StringName();
  1599. target_instance = nullptr;
  1600. userdata = Variant();
  1601. if (thread) {
  1602. memdelete(thread);
  1603. }
  1604. thread = nullptr;
  1605. return r;
  1606. }
  1607. void _Thread::_bind_methods() {
  1608. ClassDB::bind_method(D_METHOD("start", "instance", "method", "userdata", "priority"), &_Thread::start, DEFVAL(Variant()), DEFVAL(PRIORITY_NORMAL));
  1609. ClassDB::bind_method(D_METHOD("get_id"), &_Thread::get_id);
  1610. ClassDB::bind_method(D_METHOD("is_active"), &_Thread::is_active);
  1611. ClassDB::bind_method(D_METHOD("wait_to_finish"), &_Thread::wait_to_finish);
  1612. BIND_ENUM_CONSTANT(PRIORITY_LOW);
  1613. BIND_ENUM_CONSTANT(PRIORITY_NORMAL);
  1614. BIND_ENUM_CONSTANT(PRIORITY_HIGH);
  1615. }
  1616. _Thread::~_Thread() {
  1617. ERR_FAIL_COND_MSG(active, "Reference to a Thread object was lost while the thread is still running...");
  1618. }
  1619. ////// _ClassDB //////
  1620. PackedStringArray _ClassDB::get_class_list() const {
  1621. List<StringName> classes;
  1622. ClassDB::get_class_list(&classes);
  1623. PackedStringArray ret;
  1624. ret.resize(classes.size());
  1625. int idx = 0;
  1626. for (List<StringName>::Element *E = classes.front(); E; E = E->next()) {
  1627. ret.set(idx++, E->get());
  1628. }
  1629. return ret;
  1630. }
  1631. PackedStringArray _ClassDB::get_inheriters_from_class(const StringName &p_class) const {
  1632. List<StringName> classes;
  1633. ClassDB::get_inheriters_from_class(p_class, &classes);
  1634. PackedStringArray ret;
  1635. ret.resize(classes.size());
  1636. int idx = 0;
  1637. for (List<StringName>::Element *E = classes.front(); E; E = E->next()) {
  1638. ret.set(idx++, E->get());
  1639. }
  1640. return ret;
  1641. }
  1642. StringName _ClassDB::get_parent_class(const StringName &p_class) const {
  1643. return ClassDB::get_parent_class(p_class);
  1644. }
  1645. bool _ClassDB::class_exists(const StringName &p_class) const {
  1646. return ClassDB::class_exists(p_class);
  1647. }
  1648. bool _ClassDB::is_parent_class(const StringName &p_class, const StringName &p_inherits) const {
  1649. return ClassDB::is_parent_class(p_class, p_inherits);
  1650. }
  1651. bool _ClassDB::can_instance(const StringName &p_class) const {
  1652. return ClassDB::can_instance(p_class);
  1653. }
  1654. Variant _ClassDB::instance(const StringName &p_class) const {
  1655. Object *obj = ClassDB::instance(p_class);
  1656. if (!obj) {
  1657. return Variant();
  1658. }
  1659. Reference *r = Object::cast_to<Reference>(obj);
  1660. if (r) {
  1661. return REF(r);
  1662. } else {
  1663. return obj;
  1664. }
  1665. }
  1666. bool _ClassDB::has_signal(StringName p_class, StringName p_signal) const {
  1667. return ClassDB::has_signal(p_class, p_signal);
  1668. }
  1669. Dictionary _ClassDB::get_signal(StringName p_class, StringName p_signal) const {
  1670. MethodInfo signal;
  1671. if (ClassDB::get_signal(p_class, p_signal, &signal)) {
  1672. return signal.operator Dictionary();
  1673. } else {
  1674. return Dictionary();
  1675. }
  1676. }
  1677. Array _ClassDB::get_signal_list(StringName p_class, bool p_no_inheritance) const {
  1678. List<MethodInfo> signals;
  1679. ClassDB::get_signal_list(p_class, &signals, p_no_inheritance);
  1680. Array ret;
  1681. for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
  1682. ret.push_back(E->get().operator Dictionary());
  1683. }
  1684. return ret;
  1685. }
  1686. Array _ClassDB::get_property_list(StringName p_class, bool p_no_inheritance) const {
  1687. List<PropertyInfo> plist;
  1688. ClassDB::get_property_list(p_class, &plist, p_no_inheritance);
  1689. Array ret;
  1690. for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
  1691. ret.push_back(E->get().operator Dictionary());
  1692. }
  1693. return ret;
  1694. }
  1695. Variant _ClassDB::get_property(Object *p_object, const StringName &p_property) const {
  1696. Variant ret;
  1697. ClassDB::get_property(p_object, p_property, ret);
  1698. return ret;
  1699. }
  1700. Error _ClassDB::set_property(Object *p_object, const StringName &p_property, const Variant &p_value) const {
  1701. Variant ret;
  1702. bool valid;
  1703. if (!ClassDB::set_property(p_object, p_property, p_value, &valid)) {
  1704. return ERR_UNAVAILABLE;
  1705. } else if (!valid) {
  1706. return ERR_INVALID_DATA;
  1707. }
  1708. return OK;
  1709. }
  1710. bool _ClassDB::has_method(StringName p_class, StringName p_method, bool p_no_inheritance) const {
  1711. return ClassDB::has_method(p_class, p_method, p_no_inheritance);
  1712. }
  1713. Array _ClassDB::get_method_list(StringName p_class, bool p_no_inheritance) const {
  1714. List<MethodInfo> methods;
  1715. ClassDB::get_method_list(p_class, &methods, p_no_inheritance);
  1716. Array ret;
  1717. for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
  1718. #ifdef DEBUG_METHODS_ENABLED
  1719. ret.push_back(E->get().operator Dictionary());
  1720. #else
  1721. Dictionary dict;
  1722. dict["name"] = E->get().name;
  1723. ret.push_back(dict);
  1724. #endif
  1725. }
  1726. return ret;
  1727. }
  1728. PackedStringArray _ClassDB::get_integer_constant_list(const StringName &p_class, bool p_no_inheritance) const {
  1729. List<String> constants;
  1730. ClassDB::get_integer_constant_list(p_class, &constants, p_no_inheritance);
  1731. PackedStringArray ret;
  1732. ret.resize(constants.size());
  1733. int idx = 0;
  1734. for (List<String>::Element *E = constants.front(); E; E = E->next()) {
  1735. ret.set(idx++, E->get());
  1736. }
  1737. return ret;
  1738. }
  1739. bool _ClassDB::has_integer_constant(const StringName &p_class, const StringName &p_name) const {
  1740. bool success;
  1741. ClassDB::get_integer_constant(p_class, p_name, &success);
  1742. return success;
  1743. }
  1744. int _ClassDB::get_integer_constant(const StringName &p_class, const StringName &p_name) const {
  1745. bool found;
  1746. int c = ClassDB::get_integer_constant(p_class, p_name, &found);
  1747. ERR_FAIL_COND_V(!found, 0);
  1748. return c;
  1749. }
  1750. StringName _ClassDB::get_category(const StringName &p_node) const {
  1751. return ClassDB::get_category(p_node);
  1752. }
  1753. bool _ClassDB::is_class_enabled(StringName p_class) const {
  1754. return ClassDB::is_class_enabled(p_class);
  1755. }
  1756. void _ClassDB::_bind_methods() {
  1757. ClassDB::bind_method(D_METHOD("get_class_list"), &_ClassDB::get_class_list);
  1758. ClassDB::bind_method(D_METHOD("get_inheriters_from_class", "class"), &_ClassDB::get_inheriters_from_class);
  1759. ClassDB::bind_method(D_METHOD("get_parent_class", "class"), &_ClassDB::get_parent_class);
  1760. ClassDB::bind_method(D_METHOD("class_exists", "class"), &_ClassDB::class_exists);
  1761. ClassDB::bind_method(D_METHOD("is_parent_class", "class", "inherits"), &_ClassDB::is_parent_class);
  1762. ClassDB::bind_method(D_METHOD("can_instance", "class"), &_ClassDB::can_instance);
  1763. ClassDB::bind_method(D_METHOD("instance", "class"), &_ClassDB::instance);
  1764. ClassDB::bind_method(D_METHOD("class_has_signal", "class", "signal"), &_ClassDB::has_signal);
  1765. ClassDB::bind_method(D_METHOD("class_get_signal", "class", "signal"), &_ClassDB::get_signal);
  1766. ClassDB::bind_method(D_METHOD("class_get_signal_list", "class", "no_inheritance"), &_ClassDB::get_signal_list, DEFVAL(false));
  1767. ClassDB::bind_method(D_METHOD("class_get_property_list", "class", "no_inheritance"), &_ClassDB::get_property_list, DEFVAL(false));
  1768. ClassDB::bind_method(D_METHOD("class_get_property", "object", "property"), &_ClassDB::get_property);
  1769. ClassDB::bind_method(D_METHOD("class_set_property", "object", "property", "value"), &_ClassDB::set_property);
  1770. ClassDB::bind_method(D_METHOD("class_has_method", "class", "method", "no_inheritance"), &_ClassDB::has_method, DEFVAL(false));
  1771. ClassDB::bind_method(D_METHOD("class_get_method_list", "class", "no_inheritance"), &_ClassDB::get_method_list, DEFVAL(false));
  1772. ClassDB::bind_method(D_METHOD("class_get_integer_constant_list", "class", "no_inheritance"), &_ClassDB::get_integer_constant_list, DEFVAL(false));
  1773. ClassDB::bind_method(D_METHOD("class_has_integer_constant", "class", "name"), &_ClassDB::has_integer_constant);
  1774. ClassDB::bind_method(D_METHOD("class_get_integer_constant", "class", "name"), &_ClassDB::get_integer_constant);
  1775. ClassDB::bind_method(D_METHOD("class_get_category", "class"), &_ClassDB::get_category);
  1776. ClassDB::bind_method(D_METHOD("is_class_enabled", "class"), &_ClassDB::is_class_enabled);
  1777. }
  1778. ////// _Engine //////
  1779. void _Engine::set_iterations_per_second(int p_ips) {
  1780. Engine::get_singleton()->set_iterations_per_second(p_ips);
  1781. }
  1782. int _Engine::get_iterations_per_second() const {
  1783. return Engine::get_singleton()->get_iterations_per_second();
  1784. }
  1785. void _Engine::set_physics_jitter_fix(float p_threshold) {
  1786. Engine::get_singleton()->set_physics_jitter_fix(p_threshold);
  1787. }
  1788. float _Engine::get_physics_jitter_fix() const {
  1789. return Engine::get_singleton()->get_physics_jitter_fix();
  1790. }
  1791. float _Engine::get_physics_interpolation_fraction() const {
  1792. return Engine::get_singleton()->get_physics_interpolation_fraction();
  1793. }
  1794. void _Engine::set_target_fps(int p_fps) {
  1795. Engine::get_singleton()->set_target_fps(p_fps);
  1796. }
  1797. int _Engine::get_target_fps() const {
  1798. return Engine::get_singleton()->get_target_fps();
  1799. }
  1800. float _Engine::get_frames_per_second() const {
  1801. return Engine::get_singleton()->get_frames_per_second();
  1802. }
  1803. uint64_t _Engine::get_physics_frames() const {
  1804. return Engine::get_singleton()->get_physics_frames();
  1805. }
  1806. uint64_t _Engine::get_idle_frames() const {
  1807. return Engine::get_singleton()->get_idle_frames();
  1808. }
  1809. void _Engine::set_time_scale(float p_scale) {
  1810. Engine::get_singleton()->set_time_scale(p_scale);
  1811. }
  1812. float _Engine::get_time_scale() {
  1813. return Engine::get_singleton()->get_time_scale();
  1814. }
  1815. int _Engine::get_frames_drawn() {
  1816. return Engine::get_singleton()->get_frames_drawn();
  1817. }
  1818. MainLoop *_Engine::get_main_loop() const {
  1819. //needs to remain in OS, since it's actually OS that interacts with it, but it's better exposed here
  1820. return OS::get_singleton()->get_main_loop();
  1821. }
  1822. Dictionary _Engine::get_version_info() const {
  1823. return Engine::get_singleton()->get_version_info();
  1824. }
  1825. Dictionary _Engine::get_author_info() const {
  1826. return Engine::get_singleton()->get_author_info();
  1827. }
  1828. Array _Engine::get_copyright_info() const {
  1829. return Engine::get_singleton()->get_copyright_info();
  1830. }
  1831. Dictionary _Engine::get_donor_info() const {
  1832. return Engine::get_singleton()->get_donor_info();
  1833. }
  1834. Dictionary _Engine::get_license_info() const {
  1835. return Engine::get_singleton()->get_license_info();
  1836. }
  1837. String _Engine::get_license_text() const {
  1838. return Engine::get_singleton()->get_license_text();
  1839. }
  1840. bool _Engine::is_in_physics_frame() const {
  1841. return Engine::get_singleton()->is_in_physics_frame();
  1842. }
  1843. bool _Engine::has_singleton(const String &p_name) const {
  1844. return Engine::get_singleton()->has_singleton(p_name);
  1845. }
  1846. Object *_Engine::get_singleton_object(const String &p_name) const {
  1847. return Engine::get_singleton()->get_singleton_object(p_name);
  1848. }
  1849. void _Engine::set_editor_hint(bool p_enabled) {
  1850. Engine::get_singleton()->set_editor_hint(p_enabled);
  1851. }
  1852. bool _Engine::is_editor_hint() const {
  1853. return Engine::get_singleton()->is_editor_hint();
  1854. }
  1855. void _Engine::_bind_methods() {
  1856. ClassDB::bind_method(D_METHOD("set_iterations_per_second", "iterations_per_second"), &_Engine::set_iterations_per_second);
  1857. ClassDB::bind_method(D_METHOD("get_iterations_per_second"), &_Engine::get_iterations_per_second);
  1858. ClassDB::bind_method(D_METHOD("set_physics_jitter_fix", "physics_jitter_fix"), &_Engine::set_physics_jitter_fix);
  1859. ClassDB::bind_method(D_METHOD("get_physics_jitter_fix"), &_Engine::get_physics_jitter_fix);
  1860. ClassDB::bind_method(D_METHOD("get_physics_interpolation_fraction"), &_Engine::get_physics_interpolation_fraction);
  1861. ClassDB::bind_method(D_METHOD("set_target_fps", "target_fps"), &_Engine::set_target_fps);
  1862. ClassDB::bind_method(D_METHOD("get_target_fps"), &_Engine::get_target_fps);
  1863. ClassDB::bind_method(D_METHOD("set_time_scale", "time_scale"), &_Engine::set_time_scale);
  1864. ClassDB::bind_method(D_METHOD("get_time_scale"), &_Engine::get_time_scale);
  1865. ClassDB::bind_method(D_METHOD("get_frames_drawn"), &_Engine::get_frames_drawn);
  1866. ClassDB::bind_method(D_METHOD("get_frames_per_second"), &_Engine::get_frames_per_second);
  1867. ClassDB::bind_method(D_METHOD("get_physics_frames"), &_Engine::get_physics_frames);
  1868. ClassDB::bind_method(D_METHOD("get_idle_frames"), &_Engine::get_idle_frames);
  1869. ClassDB::bind_method(D_METHOD("get_main_loop"), &_Engine::get_main_loop);
  1870. ClassDB::bind_method(D_METHOD("get_version_info"), &_Engine::get_version_info);
  1871. ClassDB::bind_method(D_METHOD("get_author_info"), &_Engine::get_author_info);
  1872. ClassDB::bind_method(D_METHOD("get_copyright_info"), &_Engine::get_copyright_info);
  1873. ClassDB::bind_method(D_METHOD("get_donor_info"), &_Engine::get_donor_info);
  1874. ClassDB::bind_method(D_METHOD("get_license_info"), &_Engine::get_license_info);
  1875. ClassDB::bind_method(D_METHOD("get_license_text"), &_Engine::get_license_text);
  1876. ClassDB::bind_method(D_METHOD("is_in_physics_frame"), &_Engine::is_in_physics_frame);
  1877. ClassDB::bind_method(D_METHOD("has_singleton", "name"), &_Engine::has_singleton);
  1878. ClassDB::bind_method(D_METHOD("get_singleton", "name"), &_Engine::get_singleton_object);
  1879. ClassDB::bind_method(D_METHOD("set_editor_hint", "enabled"), &_Engine::set_editor_hint);
  1880. ClassDB::bind_method(D_METHOD("is_editor_hint"), &_Engine::is_editor_hint);
  1881. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editor_hint"), "set_editor_hint", "is_editor_hint");
  1882. ADD_PROPERTY(PropertyInfo(Variant::INT, "iterations_per_second"), "set_iterations_per_second", "get_iterations_per_second");
  1883. ADD_PROPERTY(PropertyInfo(Variant::INT, "target_fps"), "set_target_fps", "get_target_fps");
  1884. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_scale"), "set_time_scale", "get_time_scale");
  1885. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "physics_jitter_fix"), "set_physics_jitter_fix", "get_physics_jitter_fix");
  1886. }
  1887. _Engine *_Engine::singleton = nullptr;
  1888. ////// _JSON //////
  1889. void JSONParseResult::_bind_methods() {
  1890. ClassDB::bind_method(D_METHOD("get_error"), &JSONParseResult::get_error);
  1891. ClassDB::bind_method(D_METHOD("get_error_string"), &JSONParseResult::get_error_string);
  1892. ClassDB::bind_method(D_METHOD("get_error_line"), &JSONParseResult::get_error_line);
  1893. ClassDB::bind_method(D_METHOD("get_result"), &JSONParseResult::get_result);
  1894. ClassDB::bind_method(D_METHOD("set_error", "error"), &JSONParseResult::set_error);
  1895. ClassDB::bind_method(D_METHOD("set_error_string", "error_string"), &JSONParseResult::set_error_string);
  1896. ClassDB::bind_method(D_METHOD("set_error_line", "error_line"), &JSONParseResult::set_error_line);
  1897. ClassDB::bind_method(D_METHOD("set_result", "result"), &JSONParseResult::set_result);
  1898. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "error", PROPERTY_HINT_NONE, "Error", PROPERTY_USAGE_CLASS_IS_ENUM), "set_error", "get_error");
  1899. ADD_PROPERTY(PropertyInfo(Variant::STRING, "error_string"), "set_error_string", "get_error_string");
  1900. ADD_PROPERTY(PropertyInfo(Variant::INT, "error_line"), "set_error_line", "get_error_line");
  1901. ADD_PROPERTY(PropertyInfo(Variant::NIL, "result", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NIL_IS_VARIANT), "set_result", "get_result");
  1902. }
  1903. void JSONParseResult::set_error(Error p_error) {
  1904. error = p_error;
  1905. }
  1906. Error JSONParseResult::get_error() const {
  1907. return error;
  1908. }
  1909. void JSONParseResult::set_error_string(const String &p_error_string) {
  1910. error_string = p_error_string;
  1911. }
  1912. String JSONParseResult::get_error_string() const {
  1913. return error_string;
  1914. }
  1915. void JSONParseResult::set_error_line(int p_error_line) {
  1916. error_line = p_error_line;
  1917. }
  1918. int JSONParseResult::get_error_line() const {
  1919. return error_line;
  1920. }
  1921. void JSONParseResult::set_result(const Variant &p_result) {
  1922. result = p_result;
  1923. }
  1924. Variant JSONParseResult::get_result() const {
  1925. return result;
  1926. }
  1927. void _JSON::_bind_methods() {
  1928. ClassDB::bind_method(D_METHOD("print", "value", "indent", "sort_keys"), &_JSON::print, DEFVAL(String()), DEFVAL(false));
  1929. ClassDB::bind_method(D_METHOD("parse", "json"), &_JSON::parse);
  1930. }
  1931. String _JSON::print(const Variant &p_value, const String &p_indent, bool p_sort_keys) {
  1932. return JSON::print(p_value, p_indent, p_sort_keys);
  1933. }
  1934. Ref<JSONParseResult> _JSON::parse(const String &p_json) {
  1935. Ref<JSONParseResult> result;
  1936. result.instance();
  1937. result->error = JSON::parse(p_json, result->result, result->error_string, result->error_line);
  1938. if (result->error != OK) {
  1939. ERR_PRINT(vformat("Error parsing JSON at line %s: %s", result->error_line, result->error_string));
  1940. }
  1941. return result;
  1942. }
  1943. _JSON *_JSON::singleton = nullptr;