core_bind.cpp 88 KB

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