gd_script.cpp 48 KB

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