gd_script.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014
  1. /*************************************************************************/
  2. /* gd_script.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 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 "gd_script.h"
  31. #include "gd_compiler.h"
  32. #include "global_constants.h"
  33. #include "io/file_access_encrypted.h"
  34. #include "os/file_access.h"
  35. #include "os/os.h"
  36. #include "project_settings.h"
  37. ///////////////////////////
  38. GDNativeClass::GDNativeClass(const StringName &p_name) {
  39. name = p_name;
  40. }
  41. /*void GDNativeClass::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount){
  42. }*/
  43. bool GDNativeClass::_get(const StringName &p_name, Variant &r_ret) const {
  44. bool ok;
  45. int v = ClassDB::get_integer_constant(name, p_name, &ok);
  46. if (ok) {
  47. r_ret = v;
  48. return true;
  49. } else {
  50. return false;
  51. }
  52. }
  53. void GDNativeClass::_bind_methods() {
  54. ClassDB::bind_method(D_METHOD("new"), &GDNativeClass::_new);
  55. }
  56. Variant GDNativeClass::_new() {
  57. Object *o = instance();
  58. if (!o) {
  59. ERR_EXPLAIN("Class type: '" + String(name) + "' is not instantiable.");
  60. ERR_FAIL_COND_V(!o, Variant());
  61. }
  62. Reference *ref = Object::cast_to<Reference>(o);
  63. if (ref) {
  64. return REF(ref);
  65. } else {
  66. return o;
  67. }
  68. }
  69. Object *GDNativeClass::instance() {
  70. return ClassDB::instance(name);
  71. }
  72. GDInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) {
  73. /* STEP 1, CREATE */
  74. GDInstance *instance = memnew(GDInstance);
  75. instance->base_ref = p_isref;
  76. instance->members.resize(member_indices.size());
  77. instance->script = Ref<GDScript>(this);
  78. instance->owner = p_owner;
  79. #ifdef DEBUG_ENABLED
  80. //needed for hot reloading
  81. for (Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) {
  82. instance->member_indices_cache[E->key()] = E->get().index;
  83. }
  84. #endif
  85. instance->owner->set_script_instance(instance);
  86. /* STEP 2, INITIALIZE AND CONSRTUCT */
  87. #ifndef NO_THREADS
  88. GDScriptLanguage::singleton->lock->lock();
  89. #endif
  90. instances.insert(instance->owner);
  91. #ifndef NO_THREADS
  92. GDScriptLanguage::singleton->lock->unlock();
  93. #endif
  94. initializer->call(instance, p_args, p_argcount, r_error);
  95. if (r_error.error != Variant::CallError::CALL_OK) {
  96. instance->script = Ref<GDScript>();
  97. instance->owner->set_script_instance(NULL);
  98. #ifndef NO_THREADS
  99. GDScriptLanguage::singleton->lock->lock();
  100. #endif
  101. instances.erase(p_owner);
  102. #ifndef NO_THREADS
  103. GDScriptLanguage::singleton->lock->unlock();
  104. #endif
  105. ERR_FAIL_COND_V(r_error.error != Variant::CallError::CALL_OK, NULL); //error constructing
  106. }
  107. //@TODO make thread safe
  108. return instance;
  109. }
  110. Variant GDScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  111. /* STEP 1, CREATE */
  112. if (!valid) {
  113. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  114. return Variant();
  115. }
  116. r_error.error = Variant::CallError::CALL_OK;
  117. REF ref;
  118. Object *owner = NULL;
  119. GDScript *_baseptr = this;
  120. while (_baseptr->_base) {
  121. _baseptr = _baseptr->_base;
  122. }
  123. ERR_FAIL_COND_V(_baseptr->native.is_null(), Variant());
  124. if (_baseptr->native.ptr()) {
  125. owner = _baseptr->native->instance();
  126. } else {
  127. owner = memnew(Reference); //by default, no base means use reference
  128. }
  129. Reference *r = Object::cast_to<Reference>(owner);
  130. if (r) {
  131. ref = REF(r);
  132. }
  133. GDInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error);
  134. if (!instance) {
  135. if (ref.is_null()) {
  136. memdelete(owner); //no owner, sorry
  137. }
  138. return Variant();
  139. }
  140. if (ref.is_valid()) {
  141. return ref;
  142. } else {
  143. return owner;
  144. }
  145. }
  146. bool GDScript::can_instance() const {
  147. //return valid; //any script in GDscript can instance
  148. return valid || (!tool && !ScriptServer::is_scripting_enabled());
  149. }
  150. Ref<Script> GDScript::get_base_script() const {
  151. if (_base) {
  152. return Ref<GDScript>(_base);
  153. } else {
  154. return Ref<Script>();
  155. }
  156. }
  157. StringName GDScript::get_instance_base_type() const {
  158. if (native.is_valid())
  159. return native->get_name();
  160. if (base.is_valid())
  161. return base->get_instance_base_type();
  162. return StringName();
  163. }
  164. struct _GDScriptMemberSort {
  165. int index;
  166. StringName name;
  167. _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort &p_member) const { return index < p_member.index; }
  168. };
  169. #ifdef TOOLS_ENABLED
  170. void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  171. placeholders.erase(p_placeholder);
  172. }
  173. /*
  174. void GDScript::_update_placeholder(PlaceHolderScriptInstance *p_placeholder) {
  175. List<PropertyInfo> plist;
  176. GDScript *scr=this;
  177. Map<StringName,Variant> default_values;
  178. while(scr) {
  179. Vector<_GDScriptMemberSort> msort;
  180. for(Map<StringName,PropertyInfo>::Element *E=scr->member_info.front();E;E=E->next()) {
  181. _GDScriptMemberSort ms;
  182. ERR_CONTINUE(!scr->member_indices.has(E->key()));
  183. ms.index=scr->member_indices[E->key()].index;
  184. ms.name=E->key();
  185. msort.push_back(ms);
  186. }
  187. msort.sort();
  188. msort.invert();
  189. for(int i=0;i<msort.size();i++) {
  190. plist.push_front(scr->member_info[msort[i].name]);
  191. if (scr->member_default_values.has(msort[i].name))
  192. default_values[msort[i].name]=scr->member_default_values[msort[i].name];
  193. else {
  194. Variant::CallError err;
  195. default_values[msort[i].name]=Variant::construct(scr->member_info[msort[i].name].type,NULL,0,err);
  196. }
  197. }
  198. scr=scr->_base;
  199. }
  200. p_placeholder->update(plist,default_values);
  201. }*/
  202. #endif
  203. void GDScript::get_script_method_list(List<MethodInfo> *p_list) const {
  204. for (const Map<StringName, GDFunction *>::Element *E = member_functions.front(); E; E = E->next()) {
  205. MethodInfo mi;
  206. mi.name = E->key();
  207. for (int i = 0; i < E->get()->get_argument_count(); i++) {
  208. PropertyInfo arg;
  209. arg.type = Variant::NIL; //variant
  210. arg.name = E->get()->get_argument_name(i);
  211. mi.arguments.push_back(arg);
  212. }
  213. mi.return_val.name = "Variant";
  214. p_list->push_back(mi);
  215. }
  216. }
  217. void GDScript::get_script_property_list(List<PropertyInfo> *p_list) const {
  218. const GDScript *sptr = this;
  219. List<PropertyInfo> props;
  220. while (sptr) {
  221. Vector<_GDScriptMemberSort> msort;
  222. for (Map<StringName, PropertyInfo>::Element *E = sptr->member_info.front(); E; E = E->next()) {
  223. _GDScriptMemberSort ms;
  224. ERR_CONTINUE(!sptr->member_indices.has(E->key()));
  225. ms.index = sptr->member_indices[E->key()].index;
  226. ms.name = E->key();
  227. msort.push_back(ms);
  228. }
  229. msort.sort();
  230. msort.invert();
  231. for (int i = 0; i < msort.size(); i++) {
  232. props.push_front(sptr->member_info[msort[i].name]);
  233. }
  234. sptr = sptr->_base;
  235. }
  236. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  237. p_list->push_back(E->get());
  238. }
  239. }
  240. bool GDScript::has_method(const StringName &p_method) const {
  241. return member_functions.has(p_method);
  242. }
  243. MethodInfo GDScript::get_method_info(const StringName &p_method) const {
  244. const Map<StringName, GDFunction *>::Element *E = member_functions.find(p_method);
  245. if (!E)
  246. return MethodInfo();
  247. MethodInfo mi;
  248. mi.name = E->key();
  249. for (int i = 0; i < E->get()->get_argument_count(); i++) {
  250. PropertyInfo arg;
  251. arg.type = Variant::NIL; //variant
  252. arg.name = E->get()->get_argument_name(i);
  253. mi.arguments.push_back(arg);
  254. }
  255. mi.return_val.name = "Variant";
  256. return mi;
  257. }
  258. bool GDScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  259. #ifdef TOOLS_ENABLED
  260. /*
  261. for (const Map<StringName,Variant>::Element *I=member_default_values.front();I;I=I->next()) {
  262. print_line("\t"+String(String(I->key())+":"+String(I->get())));
  263. }
  264. */
  265. const Map<StringName, Variant>::Element *E = member_default_values_cache.find(p_property);
  266. if (E) {
  267. r_value = E->get();
  268. return true;
  269. }
  270. if (base_cache.is_valid()) {
  271. return base_cache->get_property_default_value(p_property, r_value);
  272. }
  273. #endif
  274. return false;
  275. }
  276. ScriptInstance *GDScript::instance_create(Object *p_this) {
  277. if (!tool && !ScriptServer::is_scripting_enabled()) {
  278. #ifdef TOOLS_ENABLED
  279. //instance a fake script for editing the values
  280. //plist.invert();
  281. /*print_line("CREATING PLACEHOLDER");
  282. for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
  283. print_line(E->get().name);
  284. }*/
  285. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(), Ref<Script>(this), p_this));
  286. placeholders.insert(si);
  287. //_update_placeholder(si);
  288. _update_exports();
  289. return si;
  290. #else
  291. return NULL;
  292. #endif
  293. }
  294. GDScript *top = this;
  295. while (top->_base)
  296. top = top->_base;
  297. if (top->native.is_valid()) {
  298. if (!ClassDB::is_parent_class(p_this->get_class_name(), top->native->get_name())) {
  299. if (ScriptDebugger::get_singleton()) {
  300. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
  301. }
  302. ERR_EXPLAIN("Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
  303. ERR_FAIL_V(NULL);
  304. }
  305. }
  306. Variant::CallError unchecked_error;
  307. return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this), unchecked_error);
  308. }
  309. bool GDScript::instance_has(const Object *p_this) const {
  310. #ifndef NO_THREADS
  311. GDScriptLanguage::singleton->lock->lock();
  312. #endif
  313. bool hasit = instances.has((Object *)p_this);
  314. #ifndef NO_THREADS
  315. GDScriptLanguage::singleton->lock->unlock();
  316. #endif
  317. return hasit;
  318. }
  319. bool GDScript::has_source_code() const {
  320. return source != "";
  321. }
  322. String GDScript::get_source_code() const {
  323. return source;
  324. }
  325. void GDScript::set_source_code(const String &p_code) {
  326. if (source == p_code)
  327. return;
  328. source = p_code;
  329. #ifdef TOOLS_ENABLED
  330. source_changed_cache = true;
  331. //print_line("SC CHANGED "+get_path());
  332. #endif
  333. }
  334. #ifdef TOOLS_ENABLED
  335. void GDScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  336. if (base_cache.is_valid()) {
  337. base_cache->_update_exports_values(values, propnames);
  338. }
  339. for (Map<StringName, Variant>::Element *E = member_default_values_cache.front(); E; E = E->next()) {
  340. values[E->key()] = E->get();
  341. }
  342. for (List<PropertyInfo>::Element *E = members_cache.front(); E; E = E->next()) {
  343. propnames.push_back(E->get());
  344. }
  345. }
  346. #endif
  347. bool GDScript::_update_exports() {
  348. #ifdef TOOLS_ENABLED
  349. bool changed = false;
  350. if (source_changed_cache) {
  351. //print_line("updating source for "+get_path());
  352. source_changed_cache = false;
  353. changed = true;
  354. String basedir = path;
  355. if (basedir == "")
  356. basedir = get_path();
  357. if (basedir != "")
  358. basedir = basedir.get_base_dir();
  359. GDParser parser;
  360. Error err = parser.parse(source, basedir, true, path);
  361. if (err == OK) {
  362. const GDParser::Node *root = parser.get_parse_tree();
  363. ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, false);
  364. const GDParser::ClassNode *c = static_cast<const GDParser::ClassNode *>(root);
  365. if (base_cache.is_valid()) {
  366. base_cache->inheriters_cache.erase(get_instance_id());
  367. base_cache = Ref<GDScript>();
  368. }
  369. if (c->extends_used && String(c->extends_file) != "" && String(c->extends_file) != get_path()) {
  370. String path = c->extends_file;
  371. if (path.is_rel_path()) {
  372. String base = get_path();
  373. if (base == "" || base.is_rel_path()) {
  374. ERR_PRINT(("Could not resolve relative path for parent class: " + path).utf8().get_data());
  375. } else {
  376. path = base.get_base_dir().plus_file(path);
  377. }
  378. }
  379. if (path != get_path()) {
  380. Ref<GDScript> bf = ResourceLoader::load(path);
  381. if (bf.is_valid()) {
  382. //print_line("parent is: "+bf->get_path());
  383. base_cache = bf;
  384. bf->inheriters_cache.insert(get_instance_id());
  385. //bf->_update_exports(p_instances,true,false);
  386. }
  387. } else {
  388. ERR_PRINT(("Path extending itself in " + path).utf8().get_data());
  389. }
  390. }
  391. members_cache.clear();
  392. member_default_values_cache.clear();
  393. for (int i = 0; i < c->variables.size(); i++) {
  394. if (c->variables[i]._export.type == Variant::NIL)
  395. continue;
  396. members_cache.push_back(c->variables[i]._export);
  397. //print_line("found "+c->variables[i]._export.name);
  398. member_default_values_cache[c->variables[i].identifier] = c->variables[i].default_value;
  399. }
  400. _signals.clear();
  401. for (int i = 0; i < c->_signals.size(); i++) {
  402. _signals[c->_signals[i].name] = c->_signals[i].arguments;
  403. }
  404. }
  405. } else {
  406. //print_line("unchanged is "+get_path());
  407. }
  408. if (base_cache.is_valid()) {
  409. if (base_cache->_update_exports()) {
  410. changed = true;
  411. }
  412. }
  413. if (/*changed &&*/ placeholders.size()) { //hm :(
  414. //print_line("updating placeholders for "+get_path());
  415. //update placeholders if any
  416. Map<StringName, Variant> values;
  417. List<PropertyInfo> propnames;
  418. _update_exports_values(values, propnames);
  419. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  420. E->get()->update(propnames, values);
  421. }
  422. }
  423. return changed;
  424. #else
  425. return false;
  426. #endif
  427. }
  428. void GDScript::update_exports() {
  429. #ifdef TOOLS_ENABLED
  430. _update_exports();
  431. Set<ObjectID> copy = inheriters_cache; //might get modified
  432. //print_line("update exports for "+get_path()+" ic: "+itos(copy.size()));
  433. for (Set<ObjectID>::Element *E = copy.front(); E; E = E->next()) {
  434. Object *id = ObjectDB::get_instance(E->get());
  435. GDScript *s = Object::cast_to<GDScript>(id);
  436. if (!s)
  437. continue;
  438. s->update_exports();
  439. }
  440. #endif
  441. }
  442. void GDScript::_set_subclass_path(Ref<GDScript> &p_sc, const String &p_path) {
  443. p_sc->path = p_path;
  444. for (Map<StringName, Ref<GDScript> >::Element *E = p_sc->subclasses.front(); E; E = E->next()) {
  445. _set_subclass_path(E->get(), p_path);
  446. }
  447. }
  448. Error GDScript::reload(bool p_keep_state) {
  449. #ifndef NO_THREADS
  450. GDScriptLanguage::singleton->lock->lock();
  451. #endif
  452. bool has_instances = instances.size();
  453. #ifndef NO_THREADS
  454. GDScriptLanguage::singleton->lock->unlock();
  455. #endif
  456. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  457. String basedir = path;
  458. if (basedir == "")
  459. basedir = get_path();
  460. if (basedir != "")
  461. basedir = basedir.get_base_dir();
  462. if (source.find("%BASE%") != -1) {
  463. //loading a template, don't parse
  464. return OK;
  465. }
  466. valid = false;
  467. GDParser parser;
  468. Error err = parser.parse(source, basedir, false, path);
  469. if (err) {
  470. if (ScriptDebugger::get_singleton()) {
  471. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), parser.get_error_line(), "Parser Error: " + parser.get_error());
  472. }
  473. _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_error_line(), ("Parse Error: " + parser.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
  474. ERR_FAIL_V(ERR_PARSE_ERROR);
  475. }
  476. bool can_run = ScriptServer::is_scripting_enabled() || parser.is_tool_script();
  477. GDCompiler compiler;
  478. err = compiler.compile(&parser, this, p_keep_state);
  479. if (err) {
  480. if (can_run) {
  481. if (ScriptDebugger::get_singleton()) {
  482. GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), compiler.get_error_line(), "Parser Error: " + compiler.get_error());
  483. }
  484. _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
  485. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  486. } else {
  487. return err;
  488. }
  489. }
  490. valid = true;
  491. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  492. _set_subclass_path(E->get(), path);
  493. }
  494. #ifdef TOOLS_ENABLED
  495. /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
  496. _update_placeholder(E->get());
  497. }*/
  498. #endif
  499. return OK;
  500. }
  501. String GDScript::get_node_type() const {
  502. return ""; // ?
  503. }
  504. ScriptLanguage *GDScript::get_language() const {
  505. return GDScriptLanguage::get_singleton();
  506. }
  507. Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  508. GDScript *top = this;
  509. while (top) {
  510. Map<StringName, GDFunction *>::Element *E = top->member_functions.find(p_method);
  511. if (E) {
  512. if (!E->get()->is_static()) {
  513. WARN_PRINT(String("Can't call non-static function: '" + String(p_method) + "' in script.").utf8().get_data());
  514. }
  515. return E->get()->call(NULL, p_args, p_argcount, r_error);
  516. }
  517. top = top->_base;
  518. }
  519. //none found, regular
  520. return Script::call(p_method, p_args, p_argcount, r_error);
  521. }
  522. bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
  523. {
  524. const GDScript *top = this;
  525. while (top) {
  526. {
  527. const Map<StringName, Variant>::Element *E = top->constants.find(p_name);
  528. if (E) {
  529. r_ret = E->get();
  530. return true;
  531. }
  532. }
  533. {
  534. const Map<StringName, Ref<GDScript> >::Element *E = subclasses.find(p_name);
  535. if (E) {
  536. r_ret = E->get();
  537. return true;
  538. }
  539. }
  540. top = top->_base;
  541. }
  542. if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
  543. r_ret = get_source_code();
  544. return true;
  545. }
  546. }
  547. return false;
  548. }
  549. bool GDScript::_set(const StringName &p_name, const Variant &p_value) {
  550. if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
  551. set_source_code(p_value);
  552. reload();
  553. } else
  554. return false;
  555. return true;
  556. }
  557. void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  558. p_properties->push_back(PropertyInfo(Variant::STRING, "script/source", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
  559. }
  560. void GDScript::_bind_methods() {
  561. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo(Variant::OBJECT, "new"));
  562. ClassDB::bind_method(D_METHOD("get_as_byte_code"), &GDScript::get_as_byte_code);
  563. }
  564. Vector<uint8_t> GDScript::get_as_byte_code() const {
  565. GDTokenizerBuffer tokenizer;
  566. return tokenizer.parse_code_string(source);
  567. };
  568. Error GDScript::load_byte_code(const String &p_path) {
  569. Vector<uint8_t> bytecode;
  570. if (p_path.ends_with("gde")) {
  571. FileAccess *fa = FileAccess::open(p_path, FileAccess::READ);
  572. ERR_FAIL_COND_V(!fa, ERR_CANT_OPEN);
  573. FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
  574. ERR_FAIL_COND_V(!fae, ERR_CANT_OPEN);
  575. Vector<uint8_t> key;
  576. key.resize(32);
  577. for (int i = 0; i < key.size(); i++) {
  578. key[i] = script_encryption_key[i];
  579. }
  580. Error err = fae->open_and_parse(fa, key, FileAccessEncrypted::MODE_READ);
  581. ERR_FAIL_COND_V(err, err);
  582. bytecode.resize(fae->get_len());
  583. fae->get_buffer(bytecode.ptr(), bytecode.size());
  584. memdelete(fae);
  585. } else {
  586. bytecode = FileAccess::get_file_as_array(p_path);
  587. }
  588. ERR_FAIL_COND_V(bytecode.size() == 0, ERR_PARSE_ERROR);
  589. path = p_path;
  590. String basedir = path;
  591. if (basedir == "")
  592. basedir = get_path();
  593. if (basedir != "")
  594. basedir = basedir.get_base_dir();
  595. valid = false;
  596. GDParser parser;
  597. Error err = parser.parse_bytecode(bytecode, basedir, get_path());
  598. if (err) {
  599. _err_print_error("GDScript::load_byte_code", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_error_line(), ("Parse Error: " + parser.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
  600. ERR_FAIL_V(ERR_PARSE_ERROR);
  601. }
  602. GDCompiler compiler;
  603. err = compiler.compile(&parser, this);
  604. if (err) {
  605. _err_print_error("GDScript::load_byte_code", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
  606. ERR_FAIL_V(ERR_COMPILATION_FAILED);
  607. }
  608. valid = true;
  609. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  610. _set_subclass_path(E->get(), path);
  611. }
  612. return OK;
  613. }
  614. Error GDScript::load_source_code(const String &p_path) {
  615. PoolVector<uint8_t> sourcef;
  616. Error err;
  617. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  618. if (err) {
  619. ERR_FAIL_COND_V(err, err);
  620. }
  621. int len = f->get_len();
  622. sourcef.resize(len + 1);
  623. PoolVector<uint8_t>::Write w = sourcef.write();
  624. int r = f->get_buffer(w.ptr(), len);
  625. f->close();
  626. memdelete(f);
  627. ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
  628. w[len] = 0;
  629. String s;
  630. if (s.parse_utf8((const char *)w.ptr())) {
  631. ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode.");
  632. ERR_FAIL_V(ERR_INVALID_DATA);
  633. }
  634. source = s;
  635. #ifdef TOOLS_ENABLED
  636. source_changed_cache = true;
  637. #endif
  638. //print_line("LSC :"+get_path());
  639. path = p_path;
  640. return OK;
  641. }
  642. const Map<StringName, GDFunction *> &GDScript::debug_get_member_functions() const {
  643. return member_functions;
  644. }
  645. StringName GDScript::debug_get_member_by_index(int p_idx) const {
  646. for (const Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) {
  647. if (E->get().index == p_idx)
  648. return E->key();
  649. }
  650. return "<error>";
  651. }
  652. Ref<GDScript> GDScript::get_base() const {
  653. return base;
  654. }
  655. bool GDScript::has_script_signal(const StringName &p_signal) const {
  656. if (_signals.has(p_signal))
  657. return true;
  658. if (base.is_valid()) {
  659. return base->has_script_signal(p_signal);
  660. }
  661. #ifdef TOOLS_ENABLED
  662. else if (base_cache.is_valid()) {
  663. return base_cache->has_script_signal(p_signal);
  664. }
  665. #endif
  666. return false;
  667. }
  668. void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  669. for (const Map<StringName, Vector<StringName> >::Element *E = _signals.front(); E; E = E->next()) {
  670. MethodInfo mi;
  671. mi.name = E->key();
  672. for (int i = 0; i < E->get().size(); i++) {
  673. PropertyInfo arg;
  674. arg.name = E->get()[i];
  675. mi.arguments.push_back(arg);
  676. }
  677. r_signals->push_back(mi);
  678. }
  679. if (base.is_valid()) {
  680. base->get_script_signal_list(r_signals);
  681. }
  682. #ifdef TOOLS_ENABLED
  683. else if (base_cache.is_valid()) {
  684. base_cache->get_script_signal_list(r_signals);
  685. }
  686. #endif
  687. }
  688. GDScript::GDScript()
  689. : script_list(this) {
  690. _static_ref = this;
  691. valid = false;
  692. subclass_count = 0;
  693. initializer = NULL;
  694. _base = NULL;
  695. _owner = NULL;
  696. tool = false;
  697. #ifdef TOOLS_ENABLED
  698. source_changed_cache = false;
  699. #endif
  700. #ifdef DEBUG_ENABLED
  701. if (GDScriptLanguage::get_singleton()->lock) {
  702. GDScriptLanguage::get_singleton()->lock->lock();
  703. }
  704. GDScriptLanguage::get_singleton()->script_list.add(&script_list);
  705. if (GDScriptLanguage::get_singleton()->lock) {
  706. GDScriptLanguage::get_singleton()->lock->unlock();
  707. }
  708. #endif
  709. }
  710. GDScript::~GDScript() {
  711. for (Map<StringName, GDFunction *>::Element *E = member_functions.front(); E; E = E->next()) {
  712. memdelete(E->get());
  713. }
  714. for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
  715. E->get()->_owner = NULL; //bye, you are no longer owned cause I died
  716. }
  717. #ifdef DEBUG_ENABLED
  718. if (GDScriptLanguage::get_singleton()->lock) {
  719. GDScriptLanguage::get_singleton()->lock->lock();
  720. }
  721. GDScriptLanguage::get_singleton()->script_list.remove(&script_list);
  722. if (GDScriptLanguage::get_singleton()->lock) {
  723. GDScriptLanguage::get_singleton()->lock->unlock();
  724. }
  725. #endif
  726. }
  727. //////////////////////////////
  728. // INSTANCE //
  729. //////////////////////////////
  730. bool GDInstance::set(const StringName &p_name, const Variant &p_value) {
  731. //member
  732. {
  733. const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  734. if (E) {
  735. if (E->get().setter) {
  736. const Variant *val = &p_value;
  737. Variant::CallError err;
  738. call(E->get().setter, &val, 1, err);
  739. if (err.error == Variant::CallError::CALL_OK) {
  740. return true; //function exists, call was successful
  741. }
  742. } else
  743. members[E->get().index] = p_value;
  744. return true;
  745. }
  746. }
  747. GDScript *sptr = script.ptr();
  748. while (sptr) {
  749. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
  750. if (E) {
  751. Variant name = p_name;
  752. const Variant *args[2] = { &name, &p_value };
  753. Variant::CallError err;
  754. Variant ret = E->get()->call(this, (const Variant **)args, 2, err);
  755. if (err.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool())
  756. return true;
  757. }
  758. sptr = sptr->_base;
  759. }
  760. return false;
  761. }
  762. bool GDInstance::get(const StringName &p_name, Variant &r_ret) const {
  763. const GDScript *sptr = script.ptr();
  764. while (sptr) {
  765. {
  766. const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
  767. if (E) {
  768. if (E->get().getter) {
  769. Variant::CallError err;
  770. r_ret = const_cast<GDInstance *>(this)->call(E->get().getter, NULL, 0, err);
  771. if (err.error == Variant::CallError::CALL_OK) {
  772. return true;
  773. }
  774. }
  775. r_ret = members[E->get().index];
  776. return true; //index found
  777. }
  778. }
  779. {
  780. const GDScript *sl = sptr;
  781. while (sl) {
  782. const Map<StringName, Variant>::Element *E = sl->constants.find(p_name);
  783. if (E) {
  784. r_ret = E->get();
  785. return true; //index found
  786. }
  787. sl = sl->_base;
  788. }
  789. }
  790. {
  791. const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
  792. if (E) {
  793. Variant name = p_name;
  794. const Variant *args[1] = { &name };
  795. Variant::CallError err;
  796. Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), (const Variant **)args, 1, err);
  797. if (err.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
  798. r_ret = ret;
  799. return true;
  800. }
  801. }
  802. }
  803. sptr = sptr->_base;
  804. }
  805. return false;
  806. }
  807. Variant::Type GDInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  808. const GDScript *sptr = script.ptr();
  809. while (sptr) {
  810. if (sptr->member_info.has(p_name)) {
  811. if (r_is_valid)
  812. *r_is_valid = true;
  813. return sptr->member_info[p_name].type;
  814. }
  815. sptr = sptr->_base;
  816. }
  817. if (r_is_valid)
  818. *r_is_valid = false;
  819. return Variant::NIL;
  820. }
  821. void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  822. // exported members, not doen yet!
  823. const GDScript *sptr = script.ptr();
  824. List<PropertyInfo> props;
  825. while (sptr) {
  826. const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
  827. if (E) {
  828. Variant::CallError err;
  829. Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), NULL, 0, err);
  830. if (err.error == Variant::CallError::CALL_OK) {
  831. if (ret.get_type() != Variant::ARRAY) {
  832. ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries.");
  833. ERR_FAIL();
  834. }
  835. Array arr = ret;
  836. for (int i = 0; i < arr.size(); i++) {
  837. Dictionary d = arr[i];
  838. ERR_CONTINUE(!d.has("name"));
  839. ERR_CONTINUE(!d.has("type"));
  840. PropertyInfo pinfo;
  841. pinfo.type = Variant::Type(d["type"].operator int());
  842. ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX);
  843. pinfo.name = d["name"];
  844. ERR_CONTINUE(pinfo.name == "");
  845. if (d.has("hint"))
  846. pinfo.hint = PropertyHint(d["hint"].operator int());
  847. if (d.has("hint_string"))
  848. pinfo.hint_string = d["hint_string"];
  849. if (d.has("usage"))
  850. pinfo.usage = d["usage"];
  851. props.push_back(pinfo);
  852. }
  853. }
  854. }
  855. //instance a fake script for editing the values
  856. Vector<_GDScriptMemberSort> msort;
  857. for (Map<StringName, PropertyInfo>::Element *E = sptr->member_info.front(); E; E = E->next()) {
  858. _GDScriptMemberSort ms;
  859. ERR_CONTINUE(!sptr->member_indices.has(E->key()));
  860. ms.index = sptr->member_indices[E->key()].index;
  861. ms.name = E->key();
  862. msort.push_back(ms);
  863. }
  864. msort.sort();
  865. msort.invert();
  866. for (int i = 0; i < msort.size(); i++) {
  867. props.push_front(sptr->member_info[msort[i].name]);
  868. }
  869. #if 0
  870. if (sptr->member_functions.has("_get_property_list")) {
  871. Variant::CallError err;
  872. GDFunction *f = const_cast<GDFunction*>(sptr->member_functions["_get_property_list"]);
  873. Variant plv = f->call(const_cast<GDInstance*>(this),NULL,0,err);
  874. if (plv.get_type()!=Variant::ARRAY) {
  875. ERR_PRINT("_get_property_list: expected array returned");
  876. } else {
  877. Array pl=plv;
  878. for(int i=0;i<pl.size();i++) {
  879. Dictionary p = pl[i];
  880. PropertyInfo pinfo;
  881. if (!p.has("name")) {
  882. ERR_PRINT("_get_property_list: expected 'name' key of type string.")
  883. continue;
  884. }
  885. if (!p.has("type")) {
  886. ERR_PRINT("_get_property_list: expected 'type' key of type integer.")
  887. continue;
  888. }
  889. pinfo.name=p["name"];
  890. pinfo.type=Variant::Type(int(p["type"]));
  891. if (p.has("hint"))
  892. pinfo.hint=PropertyHint(int(p["hint"]));
  893. if (p.has("hint_string"))
  894. pinfo.hint_string=p["hint_string"];
  895. if (p.has("usage"))
  896. pinfo.usage=p["usage"];
  897. props.push_back(pinfo);
  898. }
  899. }
  900. }
  901. #endif
  902. sptr = sptr->_base;
  903. }
  904. //props.invert();
  905. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  906. p_properties->push_back(E->get());
  907. }
  908. }
  909. void GDInstance::get_method_list(List<MethodInfo> *p_list) const {
  910. const GDScript *sptr = script.ptr();
  911. while (sptr) {
  912. for (Map<StringName, GDFunction *>::Element *E = sptr->member_functions.front(); E; E = E->next()) {
  913. MethodInfo mi;
  914. mi.name = E->key();
  915. mi.flags |= METHOD_FLAG_FROM_SCRIPT;
  916. for (int i = 0; i < E->get()->get_argument_count(); i++)
  917. mi.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i)));
  918. p_list->push_back(mi);
  919. }
  920. sptr = sptr->_base;
  921. }
  922. }
  923. bool GDInstance::has_method(const StringName &p_method) const {
  924. const GDScript *sptr = script.ptr();
  925. while (sptr) {
  926. const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  927. if (E)
  928. return true;
  929. sptr = sptr->_base;
  930. }
  931. return false;
  932. }
  933. Variant GDInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  934. //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str());
  935. GDScript *sptr = script.ptr();
  936. while (sptr) {
  937. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  938. if (E) {
  939. return E->get()->call(this, p_args, p_argcount, r_error);
  940. }
  941. sptr = sptr->_base;
  942. }
  943. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  944. return Variant();
  945. }
  946. void GDInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  947. GDScript *sptr = script.ptr();
  948. Variant::CallError ce;
  949. while (sptr) {
  950. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  951. if (E) {
  952. E->get()->call(this, p_args, p_argcount, ce);
  953. }
  954. sptr = sptr->_base;
  955. }
  956. }
  957. void GDInstance::_ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount) {
  958. if (sptr->_base)
  959. _ml_call_reversed(sptr->_base, p_method, p_args, p_argcount);
  960. Variant::CallError ce;
  961. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
  962. if (E) {
  963. E->get()->call(this, p_args, p_argcount, ce);
  964. }
  965. }
  966. void GDInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  967. if (script.ptr()) {
  968. _ml_call_reversed(script.ptr(), p_method, p_args, p_argcount);
  969. }
  970. }
  971. void GDInstance::notification(int p_notification) {
  972. //notification is not virtual, it gets called at ALL levels just like in C.
  973. Variant value = p_notification;
  974. const Variant *args[1] = { &value };
  975. GDScript *sptr = script.ptr();
  976. while (sptr) {
  977. Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
  978. if (E) {
  979. Variant::CallError err;
  980. E->get()->call(this, args, 1, err);
  981. if (err.error != Variant::CallError::CALL_OK) {
  982. //print error about notification call
  983. }
  984. }
  985. sptr = sptr->_base;
  986. }
  987. }
  988. Ref<Script> GDInstance::get_script() const {
  989. return script;
  990. }
  991. ScriptLanguage *GDInstance::get_language() {
  992. return GDScriptLanguage::get_singleton();
  993. }
  994. GDInstance::RPCMode GDInstance::get_rpc_mode(const StringName &p_method) const {
  995. const GDScript *cscript = script.ptr();
  996. while (cscript) {
  997. const Map<StringName, GDFunction *>::Element *E = cscript->member_functions.find(p_method);
  998. if (E) {
  999. if (E->get()->get_rpc_mode() != RPC_MODE_DISABLED) {
  1000. return E->get()->get_rpc_mode();
  1001. }
  1002. }
  1003. cscript = cscript->_base;
  1004. }
  1005. return RPC_MODE_DISABLED;
  1006. }
  1007. GDInstance::RPCMode GDInstance::get_rset_mode(const StringName &p_variable) const {
  1008. const GDScript *cscript = script.ptr();
  1009. while (cscript) {
  1010. const Map<StringName, GDScript::MemberInfo>::Element *E = cscript->member_indices.find(p_variable);
  1011. if (E) {
  1012. if (E->get().rpc_mode) {
  1013. return E->get().rpc_mode;
  1014. }
  1015. }
  1016. cscript = cscript->_base;
  1017. }
  1018. return RPC_MODE_DISABLED;
  1019. }
  1020. void GDInstance::reload_members() {
  1021. #ifdef DEBUG_ENABLED
  1022. members.resize(script->member_indices.size()); //resize
  1023. Vector<Variant> new_members;
  1024. new_members.resize(script->member_indices.size());
  1025. //pass the values to the new indices
  1026. for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
  1027. if (member_indices_cache.has(E->key())) {
  1028. Variant value = members[member_indices_cache[E->key()]];
  1029. new_members[E->get().index] = value;
  1030. }
  1031. }
  1032. //apply
  1033. members = new_members;
  1034. //pass the values to the new indices
  1035. member_indices_cache.clear();
  1036. for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
  1037. member_indices_cache[E->key()] = E->get().index;
  1038. }
  1039. #endif
  1040. }
  1041. GDInstance::GDInstance() {
  1042. owner = NULL;
  1043. base_ref = false;
  1044. }
  1045. GDInstance::~GDInstance() {
  1046. if (script.is_valid() && owner) {
  1047. #ifndef NO_THREADS
  1048. GDScriptLanguage::singleton->lock->lock();
  1049. #endif
  1050. script->instances.erase(owner);
  1051. #ifndef NO_THREADS
  1052. GDScriptLanguage::singleton->lock->unlock();
  1053. #endif
  1054. }
  1055. }
  1056. /************* SCRIPT LANGUAGE **************/
  1057. /************* SCRIPT LANGUAGE **************/
  1058. /************* SCRIPT LANGUAGE **************/
  1059. /************* SCRIPT LANGUAGE **************/
  1060. /************* SCRIPT LANGUAGE **************/
  1061. GDScriptLanguage *GDScriptLanguage::singleton = NULL;
  1062. String GDScriptLanguage::get_name() const {
  1063. return "GDScript";
  1064. }
  1065. /* LANGUAGE FUNCTIONS */
  1066. void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) {
  1067. if (globals.has(p_name)) {
  1068. //overwrite existing
  1069. global_array[globals[p_name]] = p_value;
  1070. return;
  1071. }
  1072. globals[p_name] = global_array.size();
  1073. global_array.push_back(p_value);
  1074. _global_array = global_array.ptr();
  1075. }
  1076. void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
  1077. _add_global(p_variable, p_value);
  1078. }
  1079. void GDScriptLanguage::init() {
  1080. //populate global constants
  1081. int gcc = GlobalConstants::get_global_constant_count();
  1082. for (int i = 0; i < gcc; i++) {
  1083. _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)), GlobalConstants::get_global_constant_value(i));
  1084. }
  1085. _add_global(StaticCString::create("PI"), Math_PI);
  1086. _add_global(StaticCString::create("INF"), Math_INF);
  1087. _add_global(StaticCString::create("NAN"), Math_NAN);
  1088. //populate native classes
  1089. List<StringName> class_list;
  1090. ClassDB::get_class_list(&class_list);
  1091. for (List<StringName>::Element *E = class_list.front(); E; E = E->next()) {
  1092. StringName n = E->get();
  1093. String s = String(n);
  1094. if (s.begins_with("_"))
  1095. n = s.substr(1, s.length());
  1096. if (globals.has(n))
  1097. continue;
  1098. Ref<GDNativeClass> nc = memnew(GDNativeClass(E->get()));
  1099. _add_global(n, nc);
  1100. }
  1101. //populate singletons
  1102. List<ProjectSettings::Singleton> singletons;
  1103. ProjectSettings::get_singleton()->get_singletons(&singletons);
  1104. for (List<ProjectSettings::Singleton>::Element *E = singletons.front(); E; E = E->next()) {
  1105. _add_global(E->get().name, E->get().ptr);
  1106. }
  1107. }
  1108. String GDScriptLanguage::get_type() const {
  1109. return "GDScript";
  1110. }
  1111. String GDScriptLanguage::get_extension() const {
  1112. return "gd";
  1113. }
  1114. Error GDScriptLanguage::execute_file(const String &p_path) {
  1115. // ??
  1116. return OK;
  1117. }
  1118. void GDScriptLanguage::finish() {
  1119. }
  1120. void GDScriptLanguage::profiling_start() {
  1121. #ifdef DEBUG_ENABLED
  1122. if (lock) {
  1123. lock->lock();
  1124. }
  1125. SelfList<GDFunction> *elem = function_list.first();
  1126. while (elem) {
  1127. elem->self()->profile.call_count = 0;
  1128. elem->self()->profile.self_time = 0;
  1129. elem->self()->profile.total_time = 0;
  1130. elem->self()->profile.frame_call_count = 0;
  1131. elem->self()->profile.frame_self_time = 0;
  1132. elem->self()->profile.frame_total_time = 0;
  1133. elem->self()->profile.last_frame_call_count = 0;
  1134. elem->self()->profile.last_frame_self_time = 0;
  1135. elem->self()->profile.last_frame_total_time = 0;
  1136. elem = elem->next();
  1137. }
  1138. profiling = true;
  1139. if (lock) {
  1140. lock->unlock();
  1141. }
  1142. #endif
  1143. }
  1144. void GDScriptLanguage::profiling_stop() {
  1145. #ifdef DEBUG_ENABLED
  1146. if (lock) {
  1147. lock->lock();
  1148. }
  1149. profiling = false;
  1150. if (lock) {
  1151. lock->unlock();
  1152. }
  1153. #endif
  1154. }
  1155. int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
  1156. int current = 0;
  1157. #ifdef DEBUG_ENABLED
  1158. if (lock) {
  1159. lock->lock();
  1160. }
  1161. SelfList<GDFunction> *elem = function_list.first();
  1162. while (elem) {
  1163. if (current >= p_info_max)
  1164. break;
  1165. p_info_arr[current].call_count = elem->self()->profile.call_count;
  1166. p_info_arr[current].self_time = elem->self()->profile.self_time;
  1167. p_info_arr[current].total_time = elem->self()->profile.total_time;
  1168. p_info_arr[current].signature = elem->self()->profile.signature;
  1169. elem = elem->next();
  1170. current++;
  1171. }
  1172. if (lock) {
  1173. lock->unlock();
  1174. }
  1175. #endif
  1176. return current;
  1177. }
  1178. int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
  1179. int current = 0;
  1180. #ifdef DEBUG_ENABLED
  1181. if (lock) {
  1182. lock->lock();
  1183. }
  1184. SelfList<GDFunction> *elem = function_list.first();
  1185. while (elem) {
  1186. if (current >= p_info_max)
  1187. break;
  1188. if (elem->self()->profile.last_frame_call_count > 0) {
  1189. p_info_arr[current].call_count = elem->self()->profile.last_frame_call_count;
  1190. p_info_arr[current].self_time = elem->self()->profile.last_frame_self_time;
  1191. p_info_arr[current].total_time = elem->self()->profile.last_frame_total_time;
  1192. p_info_arr[current].signature = elem->self()->profile.signature;
  1193. //print_line(String(elem->self()->profile.signature)+": "+itos(elem->self()->profile.last_frame_call_count));
  1194. current++;
  1195. }
  1196. elem = elem->next();
  1197. }
  1198. if (lock) {
  1199. lock->unlock();
  1200. }
  1201. #endif
  1202. return current;
  1203. }
  1204. struct GDScriptDepSort {
  1205. //must support sorting so inheritance works properly (parent must be reloaded first)
  1206. bool operator()(const Ref<GDScript> &A, const Ref<GDScript> &B) const {
  1207. if (A == B)
  1208. return false; //shouldn't happen but..
  1209. const GDScript *I = B->get_base().ptr();
  1210. while (I) {
  1211. if (I == A.ptr()) {
  1212. // A is a base of B
  1213. return true;
  1214. }
  1215. I = I->get_base().ptr();
  1216. }
  1217. return false; //not a base
  1218. }
  1219. };
  1220. void GDScriptLanguage::reload_all_scripts() {
  1221. #ifdef DEBUG_ENABLED
  1222. print_line("RELOAD ALL SCRIPTS");
  1223. if (lock) {
  1224. lock->lock();
  1225. }
  1226. List<Ref<GDScript> > scripts;
  1227. SelfList<GDScript> *elem = script_list.first();
  1228. while (elem) {
  1229. if (elem->self()->get_path().is_resource_file()) {
  1230. print_line("FOUND: " + elem->self()->get_path());
  1231. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1232. }
  1233. elem = elem->next();
  1234. }
  1235. if (lock) {
  1236. lock->unlock();
  1237. }
  1238. //as scripts are going to be reloaded, must proceed without locking here
  1239. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1240. for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) {
  1241. print_line("RELOADING: " + E->get()->get_path());
  1242. E->get()->load_source_code(E->get()->get_path());
  1243. E->get()->reload(true);
  1244. }
  1245. #endif
  1246. }
  1247. void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  1248. #ifdef DEBUG_ENABLED
  1249. if (lock) {
  1250. lock->lock();
  1251. }
  1252. List<Ref<GDScript> > scripts;
  1253. SelfList<GDScript> *elem = script_list.first();
  1254. while (elem) {
  1255. if (elem->self()->get_path().is_resource_file()) {
  1256. scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  1257. }
  1258. elem = elem->next();
  1259. }
  1260. if (lock) {
  1261. lock->unlock();
  1262. }
  1263. //when someone asks you why dynamically typed languages are easier to write....
  1264. Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > > to_reload;
  1265. //as scripts are going to be reloaded, must proceed without locking here
  1266. scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
  1267. for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) {
  1268. bool reload = E->get() == p_script || to_reload.has(E->get()->get_base());
  1269. if (!reload)
  1270. continue;
  1271. to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant> > >());
  1272. if (!p_soft_reload) {
  1273. //save state and remove script from instances
  1274. Map<ObjectID, List<Pair<StringName, Variant> > > &map = to_reload[E->get()];
  1275. while (E->get()->instances.front()) {
  1276. Object *obj = E->get()->instances.front()->get();
  1277. //save instance info
  1278. List<Pair<StringName, Variant> > state;
  1279. if (obj->get_script_instance()) {
  1280. obj->get_script_instance()->get_property_state(state);
  1281. map[obj->get_instance_id()] = state;
  1282. obj->set_script(RefPtr());
  1283. }
  1284. }
  1285. //same thing for placeholders
  1286. #ifdef TOOLS_ENABLED
  1287. while (E->get()->placeholders.size()) {
  1288. Object *obj = E->get()->placeholders.front()->get()->get_owner();
  1289. //save instance info
  1290. List<Pair<StringName, Variant> > state;
  1291. if (obj->get_script_instance()) {
  1292. obj->get_script_instance()->get_property_state(state);
  1293. map[obj->get_instance_id()] = state;
  1294. obj->set_script(RefPtr());
  1295. } else {
  1296. // no instance found. Let's remove it so we don't loop forever
  1297. E->get()->placeholders.erase(E->get()->placeholders.front()->get());
  1298. }
  1299. }
  1300. #endif
  1301. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) {
  1302. map[F->key()] = F->get(); //pending to reload, use this one instead
  1303. }
  1304. }
  1305. }
  1306. for (Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > >::Element *E = to_reload.front(); E; E = E->next()) {
  1307. Ref<GDScript> scr = E->key();
  1308. scr->reload(p_soft_reload);
  1309. //restore state if saved
  1310. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) {
  1311. Object *obj = ObjectDB::get_instance(F->key());
  1312. if (!obj)
  1313. continue;
  1314. if (!p_soft_reload) {
  1315. //clear it just in case (may be a pending reload state)
  1316. obj->set_script(RefPtr());
  1317. }
  1318. obj->set_script(scr.get_ref_ptr());
  1319. if (!obj->get_script_instance()) {
  1320. //failed, save reload state for next time if not saved
  1321. if (!scr->pending_reload_state.has(obj->get_instance_id())) {
  1322. scr->pending_reload_state[obj->get_instance_id()] = F->get();
  1323. }
  1324. continue;
  1325. }
  1326. for (List<Pair<StringName, Variant> >::Element *G = F->get().front(); G; G = G->next()) {
  1327. obj->get_script_instance()->set(G->get().first, G->get().second);
  1328. }
  1329. scr->pending_reload_state.erase(obj->get_instance_id()); //as it reloaded, remove pending state
  1330. }
  1331. //if instance states were saved, set them!
  1332. }
  1333. #endif
  1334. }
  1335. void GDScriptLanguage::frame() {
  1336. //print_line("calls: "+itos(calls));
  1337. calls = 0;
  1338. #ifdef DEBUG_ENABLED
  1339. if (profiling) {
  1340. if (lock) {
  1341. lock->lock();
  1342. }
  1343. SelfList<GDFunction> *elem = function_list.first();
  1344. while (elem) {
  1345. elem->self()->profile.last_frame_call_count = elem->self()->profile.frame_call_count;
  1346. elem->self()->profile.last_frame_self_time = elem->self()->profile.frame_self_time;
  1347. elem->self()->profile.last_frame_total_time = elem->self()->profile.frame_total_time;
  1348. elem->self()->profile.frame_call_count = 0;
  1349. elem->self()->profile.frame_self_time = 0;
  1350. elem->self()->profile.frame_total_time = 0;
  1351. elem = elem->next();
  1352. }
  1353. if (lock) {
  1354. lock->unlock();
  1355. }
  1356. }
  1357. #endif
  1358. }
  1359. /* EDITOR FUNCTIONS */
  1360. void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
  1361. static const char *_reserved_words[] = {
  1362. // operators
  1363. "and",
  1364. "in",
  1365. "not",
  1366. "or",
  1367. // types and values
  1368. "false",
  1369. "float",
  1370. "int",
  1371. "bool",
  1372. "null",
  1373. "PI",
  1374. "INF",
  1375. "NAN",
  1376. "self",
  1377. "true",
  1378. // functions
  1379. "assert",
  1380. "breakpoint",
  1381. "class",
  1382. "extends",
  1383. "is",
  1384. "func",
  1385. "preload",
  1386. "setget",
  1387. "signal",
  1388. "tool",
  1389. "yield",
  1390. // var
  1391. "const",
  1392. "enum",
  1393. "export",
  1394. "onready",
  1395. "static",
  1396. "var",
  1397. // control flow
  1398. "break",
  1399. "continue",
  1400. "if",
  1401. "elif",
  1402. "else",
  1403. "for",
  1404. "pass",
  1405. "return",
  1406. "match",
  1407. "while",
  1408. "remote",
  1409. "sync",
  1410. "master",
  1411. "slave",
  1412. 0
  1413. };
  1414. const char **w = _reserved_words;
  1415. while (*w) {
  1416. p_words->push_back(*w);
  1417. w++;
  1418. }
  1419. for (int i = 0; i < GDFunctions::FUNC_MAX; i++) {
  1420. p_words->push_back(GDFunctions::get_func_name(GDFunctions::Function(i)));
  1421. }
  1422. }
  1423. GDScriptLanguage::GDScriptLanguage() {
  1424. calls = 0;
  1425. ERR_FAIL_COND(singleton);
  1426. singleton = this;
  1427. strings._init = StaticCString::create("_init");
  1428. strings._notification = StaticCString::create("_notification");
  1429. strings._set = StaticCString::create("_set");
  1430. strings._get = StaticCString::create("_get");
  1431. strings._get_property_list = StaticCString::create("_get_property_list");
  1432. strings._script_source = StaticCString::create("script/source");
  1433. _debug_parse_err_line = -1;
  1434. _debug_parse_err_file = "";
  1435. #ifdef NO_THREADS
  1436. lock = NULL;
  1437. #else
  1438. lock = Mutex::create();
  1439. #endif
  1440. profiling = false;
  1441. script_frame_time = 0;
  1442. _debug_call_stack_pos = 0;
  1443. int dmcs = GLOBAL_DEF("debug/settings/gdscript/max_call_stack", 1024);
  1444. if (ScriptDebugger::get_singleton()) {
  1445. //debugging enabled!
  1446. _debug_max_call_stack = dmcs;
  1447. if (_debug_max_call_stack < 1024)
  1448. _debug_max_call_stack = 1024;
  1449. _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1);
  1450. } else {
  1451. _debug_max_call_stack = 0;
  1452. _call_stack = NULL;
  1453. }
  1454. }
  1455. GDScriptLanguage::~GDScriptLanguage() {
  1456. if (lock) {
  1457. memdelete(lock);
  1458. lock = NULL;
  1459. }
  1460. if (_call_stack) {
  1461. memdelete_arr(_call_stack);
  1462. }
  1463. singleton = NULL;
  1464. }
  1465. /*************** RESOURCE ***************/
  1466. RES ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  1467. if (r_error)
  1468. *r_error = ERR_FILE_CANT_OPEN;
  1469. GDScript *script = memnew(GDScript);
  1470. Ref<GDScript> scriptres(script);
  1471. if (p_path.ends_with(".gde") || p_path.ends_with(".gdc")) {
  1472. script->set_script_path(p_original_path); // script needs this.
  1473. script->set_path(p_original_path);
  1474. Error err = script->load_byte_code(p_path);
  1475. if (err != OK) {
  1476. ERR_FAIL_COND_V(err != OK, RES());
  1477. }
  1478. } else {
  1479. Error err = script->load_source_code(p_path);
  1480. if (err != OK) {
  1481. ERR_FAIL_COND_V(err != OK, RES());
  1482. }
  1483. script->set_script_path(p_original_path); // script needs this.
  1484. script->set_path(p_original_path);
  1485. //script->set_name(p_path.get_file());
  1486. script->reload();
  1487. }
  1488. if (r_error)
  1489. *r_error = OK;
  1490. return scriptres;
  1491. }
  1492. void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
  1493. p_extensions->push_back("gd");
  1494. p_extensions->push_back("gdc");
  1495. p_extensions->push_back("gde");
  1496. }
  1497. bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const {
  1498. return (p_type == "Script" || p_type == "GDScript");
  1499. }
  1500. String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
  1501. String el = p_path.get_extension().to_lower();
  1502. if (el == "gd" || el == "gdc" || el == "gde")
  1503. return "GDScript";
  1504. return "";
  1505. }
  1506. Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1507. Ref<GDScript> sqscr = p_resource;
  1508. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  1509. String source = sqscr->get_source_code();
  1510. Error err;
  1511. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1512. if (err) {
  1513. ERR_FAIL_COND_V(err, err);
  1514. }
  1515. file->store_string(source);
  1516. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  1517. memdelete(file);
  1518. return ERR_CANT_CREATE;
  1519. }
  1520. file->close();
  1521. memdelete(file);
  1522. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  1523. GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, false);
  1524. }
  1525. return OK;
  1526. }
  1527. void ResourceFormatSaverGDScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  1528. if (Object::cast_to<GDScript>(*p_resource)) {
  1529. p_extensions->push_back("gd");
  1530. }
  1531. }
  1532. bool ResourceFormatSaverGDScript::recognize(const RES &p_resource) const {
  1533. return Object::cast_to<GDScript>(*p_resource) != NULL;
  1534. }