consoleFunctions.cpp 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "console/console.h"
  24. #include "console/consoleInternal.h"
  25. #include "console/engineAPI.h"
  26. #include "console/ast.h"
  27. #include "core/strings/findMatch.h"
  28. #include "core/strings/stringUnit.h"
  29. #include "core/strings/unicode.h"
  30. #include "core/stream/fileStream.h"
  31. #include "console/compiler.h"
  32. #include "platform/platformInput.h"
  33. #include "core/util/journal/journal.h"
  34. #include "core/util/uuid.h"
  35. // This is a temporary hack to get tools using the library to
  36. // link in this module which contains no other references.
  37. bool LinkConsoleFunctions = false;
  38. // Buffer for expanding script filenames.
  39. static char scriptFilenameBuffer[1024];
  40. //=============================================================================
  41. // String Functions.
  42. //=============================================================================
  43. // MARK: ---- String Functions ----
  44. //-----------------------------------------------------------------------------
  45. DefineConsoleFunction( strasc, int, ( const char* chr ),,
  46. "Return the integer character code value corresponding to the first character in the given string.\n"
  47. "@param chr a (one-character) string.\n"
  48. "@return the UTF32 code value for the first character in the given string.\n"
  49. "@ingroup Strings" )
  50. {
  51. return oneUTF8toUTF32( chr );
  52. }
  53. //-----------------------------------------------------------------------------
  54. DefineConsoleFunction( strformat, const char*, ( const char* format, const char* value ),,
  55. "Format the given value as a string using printf-style formatting.\n"
  56. "@param format A printf-style format string.\n"
  57. "@param value The value argument matching the given format string.\n\n"
  58. "@tsexample\n"
  59. "// Convert the given integer value to a string in a hex notation.\n"
  60. "%hex = strformat( \"%x\", %value );\n"
  61. "@endtsexample\n"
  62. "@ingroup Strings\n"
  63. "@see http://en.wikipedia.org/wiki/Printf" )
  64. {
  65. static const U32 bufSize = 64;
  66. char* pBuffer = Con::getReturnBuffer(bufSize);
  67. const char *pch = format;
  68. pBuffer[0] = '\0';
  69. while (*pch != '\0' && *pch !='%')
  70. pch++;
  71. while (*pch != '\0' && !dIsalpha(*pch))
  72. pch++;
  73. if (*pch == '\0')
  74. {
  75. Con::errorf("strFormat: Invalid format string!\n");
  76. return pBuffer;
  77. }
  78. switch(*pch)
  79. {
  80. case 'c':
  81. case 'C':
  82. case 'd':
  83. case 'i':
  84. case 'o':
  85. case 'u':
  86. case 'x':
  87. case 'X':
  88. dSprintf( pBuffer, bufSize, format, dAtoi( value ) );
  89. break;
  90. case 'e':
  91. case 'E':
  92. case 'f':
  93. case 'g':
  94. case 'G':
  95. dSprintf( pBuffer, bufSize, format, dAtof( value ) );
  96. break;
  97. default:
  98. Con::errorf("strFormat: Invalid format string!\n");
  99. break;
  100. }
  101. return pBuffer;
  102. }
  103. //-----------------------------------------------------------------------------
  104. DefineConsoleFunction( strcmp, S32, ( const char* str1, const char* str2 ),,
  105. "Compares two strings using case-<b>sensitive</b> comparison.\n"
  106. "@param str1 The first string.\n"
  107. "@param str2 The second string.\n"
  108. "@return 0 if both strings are equal, a value <0 if the first character different in str1 has a smaller character code "
  109. "value than the character at the same position in str2, and a value >1 otherwise.\n\n"
  110. "@tsexample\n"
  111. "if( strcmp( %var, \"foobar\" ) == 0 )\n"
  112. " echo( \"%var is equal to 'foobar'\" );\n"
  113. "@endtsexample\n"
  114. "@see stricmp\n"
  115. "@see strnatcmp\n"
  116. "@ingroup Strings" )
  117. {
  118. return dStrcmp( str1, str2 );
  119. }
  120. //-----------------------------------------------------------------------------
  121. DefineConsoleFunction( stricmp, S32, ( const char* str1, const char* str2 ),,
  122. "Compares two strings using case-<b>insensitive</b> comparison.\n"
  123. "@param str1 The first string.\n"
  124. "@param str2 The second string.\n"
  125. "@return 0 if both strings are equal, a value <0 if the first character different in str1 has a smaller character code "
  126. "value than the character at the same position in str2, and a value >0 otherwise.\n\n"
  127. "@tsexample\n"
  128. "if( stricmp( \"FOObar\", \"foobar\" ) == 0 )\n"
  129. " echo( \"this is always true\" );\n"
  130. "@endtsexample\n"
  131. "@see strcmp\n"
  132. "@see strinatcmp\n"
  133. "@ingroup Strings" )
  134. {
  135. return dStricmp( str1, str2 );
  136. }
  137. //-----------------------------------------------------------------------------
  138. DefineConsoleFunction( strnatcmp, S32, ( const char* str1, const char* str2 ),,
  139. "Compares two strings using \"natural order\" case-<b>sensitive</b> comparison.\n"
  140. "Natural order means that rather than solely comparing single character code values, strings are ordered in a "
  141. "natural way. For example, the string \"hello10\" is considered greater than the string \"hello2\" even though "
  142. "the first numeric character in \"hello10\" actually has a smaller character value than the corresponding character "
  143. "in \"hello2\". However, since 10 is greater than 2, strnatcmp will put \"hello10\" after \"hello2\".\n"
  144. "@param str1 The first string.\n"
  145. "@param str2 The second string.\n\n"
  146. "@return 0 if the strings are equal, a value >0 if @a str1 comes after @a str2 in a natural order, and a value "
  147. "<0 if @a str1 comes before @a str2 in a natural order.\n\n"
  148. "@tsexample\n"
  149. "// Bubble sort 10 elements of %array using natural order\n"
  150. "do\n"
  151. "{\n"
  152. " %swapped = false;\n"
  153. " for( %i = 0; %i < 10 - 1; %i ++ )\n"
  154. " if( strnatcmp( %array[ %i ], %array[ %i + 1 ] ) > 0 )\n"
  155. " {\n"
  156. " %temp = %array[ %i ];\n"
  157. " %array[ %i ] = %array[ %i + 1 ];\n"
  158. " %array[ %i + 1 ] = %temp;\n"
  159. " %swapped = true;\n"
  160. " }\n"
  161. "}\n"
  162. "while( %swapped );\n"
  163. "@endtsexample\n"
  164. "@see strcmp\n"
  165. "@see strinatcmp\n"
  166. "@ingroup Strings" )
  167. {
  168. return dStrnatcmp( str1, str2 );
  169. }
  170. //-----------------------------------------------------------------------------
  171. DefineConsoleFunction( strinatcmp, S32, ( const char* str1, const char* str2 ),,
  172. "Compares two strings using \"natural order\" case-<b>insensitive</b> comparison.\n"
  173. "Natural order means that rather than solely comparing single character code values, strings are ordered in a "
  174. "natural way. For example, the string \"hello10\" is considered greater than the string \"hello2\" even though "
  175. "the first numeric character in \"hello10\" actually has a smaller character value than the corresponding character "
  176. "in \"hello2\". However, since 10 is greater than 2, strnatcmp will put \"hello10\" after \"hello2\".\n"
  177. "@param str1 The first string.\n"
  178. "@param str2 The second string.\n"
  179. "@return 0 if the strings are equal, a value >0 if @a str1 comes after @a str2 in a natural order, and a value "
  180. "<0 if @a str1 comes before @a str2 in a natural order.\n\n"
  181. "@tsexample\n\n"
  182. "// Bubble sort 10 elements of %array using natural order\n"
  183. "do\n"
  184. "{\n"
  185. " %swapped = false;\n"
  186. " for( %i = 0; %i < 10 - 1; %i ++ )\n"
  187. " if( strnatcmp( %array[ %i ], %array[ %i + 1 ] ) > 0 )\n"
  188. " {\n"
  189. " %temp = %array[ %i ];\n"
  190. " %array[ %i ] = %array[ %i + 1 ];\n"
  191. " %array[ %i + 1 ] = %temp;\n"
  192. " %swapped = true;\n"
  193. " }\n"
  194. "}\n"
  195. "while( %swapped );\n"
  196. "@endtsexample\n"
  197. "@see stricmp\n"
  198. "@see strnatcmp\n"
  199. "@ingroup Strings" )
  200. {
  201. return dStrnatcasecmp( str1, str2 );
  202. }
  203. //-----------------------------------------------------------------------------
  204. DefineConsoleFunction( strlen, S32, ( const char* str ),,
  205. "Get the length of the given string in bytes.\n"
  206. "@note This does <b>not</b> return a true character count for strings with multi-byte characters!\n"
  207. "@param str A string.\n"
  208. "@return The length of the given string in bytes.\n"
  209. "@ingroup Strings" )
  210. {
  211. return dStrlen( str );
  212. }
  213. //-----------------------------------------------------------------------------
  214. DefineConsoleFunction( strstr, S32, ( const char* string, const char* substring ),,
  215. "Find the start of @a substring in the given @a string searching from left to right.\n"
  216. "@param string The string to search.\n"
  217. "@param substring The string to search for.\n"
  218. "@return The index into @a string at which the first occurrence of @a substring was found or -1 if @a substring could not be found.\n\n"
  219. "@tsexample\n"
  220. "strstr( \"abcd\", \"c\" ) // Returns 2.\n"
  221. "@endtsexample\n"
  222. "@ingroup Strings" )
  223. {
  224. const char* retpos = dStrstr( string, substring );
  225. if( !retpos )
  226. return -1;
  227. return retpos - string;
  228. }
  229. //-----------------------------------------------------------------------------
  230. DefineConsoleFunction( strpos, S32, ( const char* haystack, const char* needle, S32 offset ), ( 0 ),
  231. "Find the start of @a needle in @a haystack searching from left to right beginning at the given offset.\n"
  232. "@param haystack The string to search.\n"
  233. "@param needle The string to search for.\n"
  234. "@return The index at which the first occurrence of @a needle was found in @a haystack or -1 if no match was found.\n\n"
  235. "@tsexample\n"
  236. "strpos( \"b ab\", \"b\", 1 ) // Returns 3.\n"
  237. "@endtsexample\n"
  238. "@ingroup Strings" )
  239. {
  240. S32 start = offset;
  241. U32 sublen = dStrlen( needle );
  242. U32 strlen = dStrlen( haystack );
  243. if(start < 0)
  244. return -1;
  245. if(sublen + start > strlen)
  246. return -1;
  247. for(; start + sublen <= strlen; start++)
  248. if(!dStrncmp(haystack + start, needle, sublen))
  249. return start;
  250. return -1;
  251. }
  252. //-----------------------------------------------------------------------------
  253. DefineConsoleFunction( ltrim, const char*, ( const char* str ),,
  254. "Remove leading whitespace from the string.\n"
  255. "@param str A string.\n"
  256. "@return A string that is the same as @a str but with any leading (i.e. leftmost) whitespace removed.\n\n"
  257. "@tsexample\n"
  258. "ltrim( \" string \" ); // Returns \"string \".\n"
  259. "@endtsexample\n"
  260. "@see rtrim\n"
  261. "@see trim\n"
  262. "@ingroup Strings" )
  263. {
  264. const char *ret = str;
  265. while(*ret == ' ' || *ret == '\n' || *ret == '\t')
  266. ret++;
  267. return ret;
  268. }
  269. //-----------------------------------------------------------------------------
  270. DefineConsoleFunction( rtrim, const char*, ( const char* str ),,
  271. "Remove trailing whitespace from the string.\n"
  272. "@param str A string.\n"
  273. "@return A string that is the same as @a str but with any trailing (i.e. rightmost) whitespace removed.\n\n"
  274. "@tsexample\n"
  275. "rtrim( \" string \" ); // Returns \" string\".\n"
  276. "@endtsexample\n"
  277. "@see ltrim\n"
  278. "@see trim\n"
  279. "@ingroup Strings" )
  280. {
  281. S32 firstWhitespace = 0;
  282. S32 pos = 0;
  283. while(str[pos])
  284. {
  285. if(str[pos] != ' ' && str[pos] != '\n' && str[pos] != '\t')
  286. firstWhitespace = pos + 1;
  287. pos++;
  288. }
  289. char *ret = Con::getReturnBuffer(firstWhitespace + 1);
  290. dStrncpy(ret, str, firstWhitespace);
  291. ret[firstWhitespace] = 0;
  292. return ret;
  293. }
  294. //-----------------------------------------------------------------------------
  295. DefineConsoleFunction( trim, const char*, ( const char* str ),,
  296. "Remove leading and trailing whitespace from the string.\n"
  297. "@param str A string.\n"
  298. "@return A string that is the same as @a str but with any leading (i.e. leftmost) and trailing (i.e. rightmost) whitespace removed.\n\n"
  299. "@tsexample\n"
  300. "trim( \" string \" ); // Returns \"string\".\n"
  301. "@endtsexample\n"
  302. "@ingroup Strings" )
  303. {
  304. const char *ptr = str;
  305. while(*ptr == ' ' || *ptr == '\n' || *ptr == '\t')
  306. ptr++;
  307. S32 firstWhitespace = 0;
  308. S32 pos = 0;
  309. while(ptr[pos])
  310. {
  311. if(ptr[pos] != ' ' && ptr[pos] != '\n' && ptr[pos] != '\t')
  312. firstWhitespace = pos + 1;
  313. pos++;
  314. }
  315. char *ret = Con::getReturnBuffer(firstWhitespace + 1);
  316. dStrncpy(ret, ptr, firstWhitespace);
  317. ret[firstWhitespace] = 0;
  318. return ret;
  319. }
  320. //-----------------------------------------------------------------------------
  321. DefineConsoleFunction( stripChars, const char*, ( const char* str, const char* chars ),,
  322. "Remove all occurrences of characters contained in @a chars from @a str.\n"
  323. "@param str The string to filter characters out from.\n"
  324. "@param chars A string of characters to filter out from @a str.\n"
  325. "@return A version of @a str with all occurrences of characters contained in @a chars filtered out.\n\n"
  326. "@tsexample\n"
  327. "stripChars( \"teststring\", \"se\" ); // Returns \"tttring\"."
  328. "@endtsexample\n"
  329. "@ingroup Strings" )
  330. {
  331. char* ret = Con::getReturnBuffer( dStrlen( str ) + 1 );
  332. dStrcpy( ret, str );
  333. U32 pos = dStrcspn( ret, chars );
  334. while ( pos < dStrlen( ret ) )
  335. {
  336. dStrcpy( ret + pos, ret + pos + 1 );
  337. pos = dStrcspn( ret, chars );
  338. }
  339. return( ret );
  340. }
  341. //-----------------------------------------------------------------------------
  342. DefineConsoleFunction( strlwr, const char*, ( const char* str ),,
  343. "Return an all lower-case version of the given string.\n"
  344. "@param str A string.\n"
  345. "@return A version of @a str with all characters converted to lower-case.\n\n"
  346. "@tsexample\n"
  347. "strlwr( \"TesT1\" ) // Returns \"test1\"\n"
  348. "@endtsexample\n"
  349. "@see strupr\n"
  350. "@ingroup Strings" )
  351. {
  352. char *ret = Con::getReturnBuffer(dStrlen(str) + 1);
  353. dStrcpy(ret, str);
  354. return dStrlwr(ret);
  355. }
  356. //-----------------------------------------------------------------------------
  357. DefineConsoleFunction( strupr, const char*, ( const char* str ),,
  358. "Return an all upper-case version of the given string.\n"
  359. "@param str A string.\n"
  360. "@return A version of @a str with all characters converted to upper-case.\n\n"
  361. "@tsexample\n"
  362. "strupr( \"TesT1\" ) // Returns \"TEST1\"\n"
  363. "@endtsexample\n"
  364. "@see strlwr\n"
  365. "@ingroup Strings" )
  366. {
  367. char *ret = Con::getReturnBuffer(dStrlen(str) + 1);
  368. dStrcpy(ret, str);
  369. return dStrupr(ret);
  370. }
  371. //-----------------------------------------------------------------------------
  372. DefineConsoleFunction( strchr, const char*, ( const char* str, const char* chr ),,
  373. "Find the first occurrence of the given character in @a str.\n"
  374. "@param str The string to search.\n"
  375. "@param chr The character to search for. Only the first character from the string is taken.\n"
  376. "@return The remainder of the input string starting with the given character or the empty string if the character could not be found.\n\n"
  377. "@see strrchr\n"
  378. "@ingroup Strings" )
  379. {
  380. const char *ret = dStrchr( str, chr[ 0 ] );
  381. return ret ? ret : "";
  382. }
  383. //-----------------------------------------------------------------------------
  384. DefineConsoleFunction( strrchr, const char*, ( const char* str, const char* chr ),,
  385. "Find the last occurrence of the given character in @a str."
  386. "@param str The string to search.\n"
  387. "@param chr The character to search for. Only the first character from the string is taken.\n"
  388. "@return The remainder of the input string starting with the given character or the empty string if the character could not be found.\n\n"
  389. "@see strchr\n"
  390. "@ingroup Strings" )
  391. {
  392. const char *ret = dStrrchr( str, chr[ 0 ] );
  393. return ret ? ret : "";
  394. }
  395. //-----------------------------------------------------------------------------
  396. DefineConsoleFunction( strreplace, const char*, ( const char* source, const char* from, const char* to ),,
  397. "Replace all occurrences of @a from in @a source with @a to.\n"
  398. "@param source The string in which to replace the occurrences of @a from.\n"
  399. "@param from The string to replace in @a source.\n"
  400. "@param to The string with which to replace occurrences of @from.\n"
  401. "@return A string with all occurrences of @a from in @a source replaced by @a to.\n\n"
  402. "@tsexample\n"
  403. "strreplace( \"aabbccbb\", \"bb\", \"ee\" ) // Returns \"aaeeccee\".\n"
  404. "@endtsexample\n"
  405. "@ingroup Strings" )
  406. {
  407. S32 fromLen = dStrlen( from );
  408. if(!fromLen)
  409. return source;
  410. S32 toLen = dStrlen( to );
  411. S32 count = 0;
  412. const char *scan = source;
  413. while(scan)
  414. {
  415. scan = dStrstr(scan, from);
  416. if(scan)
  417. {
  418. scan += fromLen;
  419. count++;
  420. }
  421. }
  422. char *ret = Con::getReturnBuffer(dStrlen(source) + 1 + (toLen - fromLen) * count);
  423. U32 scanp = 0;
  424. U32 dstp = 0;
  425. for(;;)
  426. {
  427. const char *scan = dStrstr(source + scanp, from);
  428. if(!scan)
  429. {
  430. dStrcpy(ret + dstp, source + scanp);
  431. break;
  432. }
  433. U32 len = scan - (source + scanp);
  434. dStrncpy(ret + dstp, source + scanp, len);
  435. dstp += len;
  436. dStrcpy(ret + dstp, to);
  437. dstp += toLen;
  438. scanp += len + fromLen;
  439. }
  440. return ret;
  441. }
  442. //-----------------------------------------------------------------------------
  443. DefineConsoleFunction( strrepeat, const char*, ( const char* str, S32 numTimes, const char* delimiter ), ( "" ),
  444. "Return a string that repeats @a str @a numTimes number of times delimiting each occurrence with @a delimiter.\n"
  445. "@param str The string to repeat multiple times.\n"
  446. "@param numTimes The number of times to repeat @a str in the result string.\n"
  447. "@param delimiter The string to put between each repetition of @a str.\n"
  448. "@return A string containing @a str repeated @a numTimes times.\n\n"
  449. "@tsexample\n"
  450. "strrepeat( \"a\", 5, \"b\" ) // Returns \"ababababa\".\n"
  451. "@endtsexample\n"
  452. "@ingroup Strings" )
  453. {
  454. StringBuilder result;
  455. bool isFirst = false;
  456. for( U32 i = 0; i < numTimes; ++ i )
  457. {
  458. if( !isFirst )
  459. result.append( delimiter );
  460. result.append( str );
  461. isFirst = false;
  462. }
  463. return Con::getReturnBuffer( result );
  464. }
  465. //-----------------------------------------------------------------------------
  466. DefineConsoleFunction( getSubStr, const char*, ( const char* str, S32 start, S32 numChars ), ( -1 ),
  467. "@brief Return a substring of @a str starting at @a start and continuing either through to the end of @a str "
  468. "(if @a numChars is -1) or for @a numChars characters (except if this would exceed the actual source "
  469. "string length).\n"
  470. "@param str The string from which to extract a substring.\n"
  471. "@param start The offset at which to start copying out characters.\n"
  472. "@param numChars Optional argument to specify the number of characters to copy. If this is -1, all characters up the end "
  473. "of the input string are copied.\n"
  474. "@return A string that contains the given portion of the input string.\n\n"
  475. "@tsexample\n"
  476. "getSubStr( \"foobar\", 1, 2 ) // Returns \"oo\".\n"
  477. "@endtsexample\n\n"
  478. "@ingroup Strings" )
  479. {
  480. S32 baseLen = dStrlen( str );
  481. if( numChars == -1 )
  482. numChars = baseLen - start;
  483. if (start < 0 || numChars < 0) {
  484. Con::errorf(ConsoleLogEntry::Script, "getSubStr(...): error, starting position and desired length must be >= 0: (%d, %d)", start, numChars);
  485. return "";
  486. }
  487. if (baseLen < start)
  488. return "";
  489. U32 actualLen = numChars;
  490. if (start + numChars > baseLen)
  491. actualLen = baseLen - start;
  492. char *ret = Con::getReturnBuffer(actualLen + 1);
  493. dStrncpy(ret, str + start, actualLen);
  494. ret[actualLen] = '\0';
  495. return ret;
  496. }
  497. //-----------------------------------------------------------------------------
  498. DefineConsoleFunction( strIsMatchExpr, bool, ( const char* pattern, const char* str, bool caseSensitive ), ( false ),
  499. "Match a pattern against a string.\n"
  500. "@param pattern The wildcard pattern to match against. The pattern can include characters, '*' to match "
  501. "any number of characters and '?' to match a single character.\n"
  502. "@param str The string which should be matched against @a pattern.\n"
  503. "@param caseSensitive If true, characters in the pattern are matched in case-sensitive fashion against "
  504. "this string. If false, differences in casing are ignored.\n"
  505. "@return True if @a str matches the given @a pattern.\n\n"
  506. "@tsexample\n"
  507. "strIsMatchExpr( \"f?o*R\", \"foobar\" ) // Returns true.\n"
  508. "@endtsexample\n"
  509. "@see strIsMatchMultipleExpr\n"
  510. "@ingroup Strings" )
  511. {
  512. return FindMatch::isMatch( pattern, str, caseSensitive );
  513. }
  514. //-----------------------------------------------------------------------------
  515. DefineConsoleFunction( strIsMatchMultipleExpr, bool, ( const char* patterns, const char* str, bool caseSensitive ), ( false ),
  516. "Match a multiple patterns against a single string.\n"
  517. "@param patterns A tab-separated list of patterns. Each pattern can include charaters, '*' to match "
  518. "any number of characters and '?' to match a single character. Each of the patterns is tried in turn.\n"
  519. "@param str The string which should be matched against @a patterns.\n"
  520. "@param caseSensitive If true, characters in the pattern are matched in case-sensitive fashion against "
  521. "this string. If false, differences in casing are ignored.\n"
  522. "@return True if @a str matches any of the given @a patterns.\n\n"
  523. "@tsexample\n"
  524. "strIsMatchMultipleExpr( \"*.cs *.gui *.mis\", \"mymission.mis\" ) // Returns true.\n"
  525. "@endtsexample\n"
  526. "@see strIsMatchExpr\n"
  527. "@ingroup Strings" )
  528. {
  529. return FindMatch::isMatchMultipleExprs( patterns, str, caseSensitive );
  530. }
  531. //-----------------------------------------------------------------------------
  532. DefineConsoleFunction( getTrailingNumber, S32, ( const char* str ),,
  533. "Get the numeric suffix of the given input string.\n"
  534. "@param str The string from which to read out the numeric suffix.\n"
  535. "@return The numeric value of the number suffix of @a str or -1 if @a str has no such suffix.\n\n"
  536. "@tsexample\n"
  537. "getTrailingNumber( \"test123\" ) // Returns '123'.\n"
  538. "@endtsexample\n\n"
  539. "@see stripTrailingNumber\n"
  540. "@ingroup Strings" )
  541. {
  542. S32 suffix = -1;
  543. String outStr( String::GetTrailingNumber( str, suffix ) );
  544. return suffix;
  545. }
  546. //-----------------------------------------------------------------------------
  547. DefineConsoleFunction( stripTrailingNumber, String, ( const char* str ),,
  548. "Strip a numeric suffix from the given string.\n"
  549. "@param str The string from which to strip its numeric suffix.\n"
  550. "@return The string @a str without its number suffix or the original string @a str if it has no such suffix.\n\n"
  551. "@tsexample\n"
  552. "stripTrailingNumber( \"test123\" ) // Returns \"test\".\n"
  553. "@endtsexample\n\n"
  554. "@see getTrailingNumber\n"
  555. "@ingroup Strings" )
  556. {
  557. S32 suffix;
  558. return String::GetTrailingNumber( str, suffix );
  559. }
  560. //----------------------------------------------------------------
  561. DefineConsoleFunction( isspace, bool, ( const char* str, S32 index ),,
  562. "Test whether the character at the given position is a whitespace character.\n"
  563. "Characters such as tab, space, or newline are considered whitespace.\n"
  564. "@param str The string to test.\n"
  565. "@param index The index of a character in @a str.\n"
  566. "@return True if the character at the given index in @a str is a whitespace character; false otherwise.\n\n"
  567. "@see isalnum\n"
  568. "@ingroup Strings" )
  569. {
  570. if( index >= 0 && index < dStrlen( str ) )
  571. return dIsspace( str[ index ] );
  572. else
  573. return false;
  574. }
  575. //----------------------------------------------------------------
  576. DefineConsoleFunction( isalnum, bool, ( const char* str, S32 index ),,
  577. "Test whether the character at the given position is an alpha-numeric character.\n"
  578. "Alpha-numeric characters are characters that are either alphabetic (a-z, A-Z) or numbers (0-9).\n"
  579. "@param str The string to test.\n"
  580. "@param index The index of a character in @a str.\n"
  581. "@return True if the character at the given index in @a str is an alpha-numeric character; false otherwise.\n\n"
  582. "@see isspace\n"
  583. "@ingroup Strings" )
  584. {
  585. if( index >= 0 && index < dStrlen( str ) )
  586. return dIsalnum( str[ index ] );
  587. else
  588. return false;
  589. }
  590. //----------------------------------------------------------------
  591. DefineConsoleFunction( startsWith, bool, ( const char* str, const char* prefix, bool caseSensitive ), ( false ),
  592. "Test whether the given string begins with the given prefix.\n"
  593. "@param str The string to test.\n"
  594. "@param prefix The potential prefix of @a str.\n"
  595. "@param caseSensitive If true, the comparison will be case-sensitive; if false, differences in casing will "
  596. "not be taken into account.\n"
  597. "@return True if the first characters in @a str match the complete contents of @a prefix; false otherwise.\n\n"
  598. "@tsexample\n"
  599. "startsWith( \"TEST123\", \"test\" ) // Returns true.\n"
  600. "@endtsexample\n"
  601. "@see endsWith\n"
  602. "@ingroup Strings" )
  603. {
  604. // if the target string is empty, return true (all strings start with the empty string)
  605. S32 srcLen = dStrlen( str );
  606. S32 targetLen = dStrlen( prefix );
  607. if( targetLen == 0 )
  608. return true;
  609. // else if the src string is empty, return false (empty src does not start with non-empty target)
  610. else if( srcLen == 0 )
  611. return false;
  612. if( caseSensitive )
  613. return ( dStrncmp( str, prefix, targetLen ) == 0 );
  614. // both src and target are non empty, create temp buffers for lowercase operation
  615. char* srcBuf = new char[ srcLen + 1 ];
  616. char* targetBuf = new char[ targetLen + 1 ];
  617. // copy src and target into buffers
  618. dStrcpy( srcBuf, str );
  619. dStrcpy( targetBuf, prefix );
  620. // reassign src/target pointers to lowercase versions
  621. str = dStrlwr( srcBuf );
  622. prefix = dStrlwr( targetBuf );
  623. // do the comparison
  624. bool startsWith = dStrncmp( str, prefix, targetLen ) == 0;
  625. // delete temp buffers
  626. delete [] srcBuf;
  627. delete [] targetBuf;
  628. return startsWith;
  629. }
  630. //----------------------------------------------------------------
  631. DefineConsoleFunction( endsWith, bool, ( const char* str, const char* suffix, bool caseSensitive ), ( false ),
  632. "@brief Test whether the given string ends with the given suffix.\n\n"
  633. "@param str The string to test.\n"
  634. "@param suffix The potential suffix of @a str.\n"
  635. "@param caseSensitive If true, the comparison will be case-sensitive; if false, differences in casing will "
  636. "not be taken into account.\n"
  637. "@return True if the last characters in @a str match the complete contents of @a suffix; false otherwise.\n\n"
  638. "@tsexample\n"
  639. "startsWith( \"TEST123\", \"123\" ) // Returns true.\n"
  640. "@endtsexample\n\n"
  641. "@see startsWith\n"
  642. "@ingroup Strings" )
  643. {
  644. // if the target string is empty, return true (all strings end with the empty string)
  645. S32 srcLen = dStrlen( str );
  646. S32 targetLen = dStrlen( suffix );
  647. if (targetLen == 0)
  648. return true;
  649. // else if the src string is empty, return false (empty src does not end with non-empty target)
  650. else if (srcLen == 0)
  651. return false;
  652. else if( targetLen > srcLen )
  653. return false;
  654. if( caseSensitive )
  655. return ( dStrcmp( &str[ srcLen - targetLen ], suffix ) == 0 );
  656. // both src and target are non empty, create temp buffers for lowercase operation
  657. char* srcBuf = new char[ srcLen + 1 ];
  658. char* targetBuf = new char[ targetLen + 1 ];
  659. // copy src and target into buffers
  660. dStrcpy( srcBuf, str );
  661. dStrcpy( targetBuf, suffix );
  662. // reassign src/target pointers to lowercase versions
  663. str = dStrlwr( srcBuf );
  664. suffix = dStrlwr( targetBuf );
  665. // set the src pointer to the appropriate place to check the end of the string
  666. str += srcLen - targetLen;
  667. // do the comparison
  668. bool endsWith = dStrcmp( str, suffix ) == 0;
  669. // delete temp buffers
  670. delete [] srcBuf;
  671. delete [] targetBuf;
  672. return endsWith;
  673. }
  674. //----------------------------------------------------------------
  675. DefineConsoleFunction( strchrpos, S32, ( const char* str, const char* chr, S32 start ), ( 0 ),
  676. "Find the first occurrence of the given character in the given string.\n"
  677. "@param str The string to search.\n"
  678. "@param chr The character to look for. Only the first character of this string will be searched for.\n"
  679. "@param start The index into @a str at which to start searching for the given character.\n"
  680. "@return The index of the first occurrence of @a chr in @a str or -1 if @a str does not contain the given character.\n\n"
  681. "@tsexample\n"
  682. "strchrpos( \"test\", \"s\" ) // Returns 2.\n"
  683. "@endtsexample\n"
  684. "@ingroup Strings" )
  685. {
  686. if( start != 0 && start >= dStrlen( str ) )
  687. return -1;
  688. const char* ret = dStrchr( &str[ start ], chr[ 0 ] );
  689. return ret ? ret - str : -1;
  690. }
  691. //----------------------------------------------------------------
  692. DefineConsoleFunction( strrchrpos, S32, ( const char* str, const char* chr, S32 start ), ( 0 ),
  693. "Find the last occurrence of the given character in the given string.\n"
  694. "@param str The string to search.\n"
  695. "@param chr The character to look for. Only the first character of this string will be searched for.\n"
  696. "@param start The index into @a str at which to start searching for the given character.\n"
  697. "@return The index of the last occurrence of @a chr in @a str or -1 if @a str does not contain the given character.\n\n"
  698. "@tsexample\n"
  699. "strrchrpos( \"test\", \"t\" ) // Returns 3.\n"
  700. "@endtsexample\n"
  701. "@ingroup Strings" )
  702. {
  703. if( start != 0 && start >= dStrlen( str ) )
  704. return -1;
  705. const char* ret = dStrrchr( str, chr[ 0 ] );
  706. if( !ret )
  707. return -1;
  708. S32 index = ret - str;
  709. if( index < start )
  710. return -1;
  711. return index;
  712. }
  713. //=============================================================================
  714. // Field Manipulators.
  715. //=============================================================================
  716. // MARK: ---- Field Manipulators ----
  717. //-----------------------------------------------------------------------------
  718. DefineConsoleFunction( getWord, const char*, ( const char* text, S32 index ),,
  719. "Extract the word at the given @a index in the whitespace-separated list in @a text.\n"
  720. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  721. "@param text A whitespace-separated list of words.\n"
  722. "@param index The zero-based index of the word to extract.\n"
  723. "@return The word at the given index or \"\" if the index is out of range.\n\n"
  724. "@tsexample\n"
  725. "getWord( \"a b c\", 1 ) // Returns \"b\"\n"
  726. "@endtsexample\n\n"
  727. "@see getWords\n"
  728. "@see getWordCount\n"
  729. "@see getField\n"
  730. "@see getRecord\n"
  731. "@ingroup FieldManip" )
  732. {
  733. return Con::getReturnBuffer( StringUnit::getUnit( text, index, " \t\n") );
  734. }
  735. //-----------------------------------------------------------------------------
  736. DefineConsoleFunction( getWords, const char*, ( const char* text, S32 startIndex, S32 endIndex ), ( -1 ),
  737. "Extract a range of words from the given @a startIndex onwards thru @a endIndex.\n"
  738. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  739. "@param text A whitespace-separated list of words.\n"
  740. "@param startIndex The zero-based index of the first word to extract from @a text.\n"
  741. "@param endIndex The zero-based index of the last word to extract from @a text. If this is -1, all words beginning "
  742. "with @a startIndex are extracted from @a text.\n"
  743. "@return A string containing the specified range of words from @a text or \"\" if @a startIndex "
  744. "is out of range or greater than @a endIndex.\n\n"
  745. "@tsexample\n"
  746. "getWords( \"a b c d\", 1, 2, ) // Returns \"b c\"\n"
  747. "@endtsexample\n\n"
  748. "@see getWord\n"
  749. "@see getWordCount\n"
  750. "@see getFields\n"
  751. "@see getRecords\n"
  752. "@ingroup FieldManip" )
  753. {
  754. if( endIndex < 0 )
  755. endIndex = 1000000;
  756. return Con::getReturnBuffer( StringUnit::getUnits( text, startIndex, endIndex, " \t\n" ) );
  757. }
  758. //-----------------------------------------------------------------------------
  759. DefineConsoleFunction( setWord, const char*, ( const char* text, S32 index, const char* replacement ),,
  760. "Replace the word in @a text at the given @a index with @a replacement.\n"
  761. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  762. "@param text A whitespace-separated list of words.\n"
  763. "@param index The zero-based index of the word to replace.\n"
  764. "@param replacement The string with which to replace the word.\n"
  765. "@return A new string with the word at the given @a index replaced by @a replacement or the original "
  766. "string if @a index is out of range.\n\n"
  767. "@tsexample\n"
  768. "setWord( \"a b c d\", 2, \"f\" ) // Returns \"a b f d\"\n"
  769. "@endtsexample\n\n"
  770. "@see getWord\n"
  771. "@see setField\n"
  772. "@see setRecord\n"
  773. "@ingroup FieldManip" )
  774. {
  775. return Con::getReturnBuffer( StringUnit::setUnit( text, index, replacement, " \t\n") );
  776. }
  777. //-----------------------------------------------------------------------------
  778. DefineConsoleFunction( removeWord, const char*, ( const char* text, S32 index ),,
  779. "Remove the word in @a text at the given @a index.\n"
  780. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  781. "@param text A whitespace-separated list of words.\n"
  782. "@param index The zero-based index of the word in @a text.\n"
  783. "@return A new string with the word at the given index removed or the original string if @a index is "
  784. "out of range.\n\n"
  785. "@tsexample\n"
  786. "removeWord( \"a b c d\", 2 ) // Returns \"a b d\"\n"
  787. "@endtsexample\n\n"
  788. "@see removeField\n"
  789. "@see removeRecord\n"
  790. "@ingroup FieldManip" )
  791. {
  792. return Con::getReturnBuffer( StringUnit::removeUnit( text, index, " \t\n" ) );
  793. }
  794. //-----------------------------------------------------------------------------
  795. DefineConsoleFunction( getWordCount, S32, ( const char* text ),,
  796. "Return the number of whitespace-separated words in @a text.\n"
  797. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  798. "@param text A whitespace-separated list of words.\n"
  799. "@return The number of whitespace-separated words in @a text.\n\n"
  800. "@tsexample\n"
  801. "getWordCount( \"a b c d e\" ) // Returns 5\n"
  802. "@endtsexample\n\n"
  803. "@see getFieldCount\n"
  804. "@see getRecordCount\n"
  805. "@ingroup FieldManip" )
  806. {
  807. return StringUnit::getUnitCount( text, " \t\n" );
  808. }
  809. //-----------------------------------------------------------------------------
  810. DefineConsoleFunction( getField, const char*, ( const char* text, S32 index ),,
  811. "Extract the field at the given @a index in the newline and/or tab separated list in @a text.\n"
  812. "Fields in @a text must be separated by newlines and/or tabs.\n"
  813. "@param text A list of fields separated by newlines and/or tabs.\n"
  814. "@param index The zero-based index of the field to extract.\n"
  815. "@return The field at the given index or \"\" if the index is out of range.\n\n"
  816. "@tsexample\n"
  817. "getField( \"a b\" TAB \"c d\" TAB \"e f\", 1 ) // Returns \"c d\"\n"
  818. "@endtsexample\n\n"
  819. "@see getFields\n"
  820. "@see getFieldCount\n"
  821. "@see getWord\n"
  822. "@see getRecord\n"
  823. "@ingroup FieldManip" )
  824. {
  825. return Con::getReturnBuffer( StringUnit::getUnit( text, index, "\t\n" ) );
  826. }
  827. //-----------------------------------------------------------------------------
  828. DefineConsoleFunction( getFields, const char*, ( const char* text, S32 startIndex, S32 endIndex ), ( -1 ),
  829. "Extract a range of fields from the given @a startIndex onwards thru @a endIndex.\n"
  830. "Fields in @a text must be separated by newlines and/or tabs.\n"
  831. "@param text A list of fields separated by newlines and/or tabs.\n"
  832. "@param startIndex The zero-based index of the first field to extract from @a text.\n"
  833. "@param endIndex The zero-based index of the last field to extract from @a text. If this is -1, all fields beginning "
  834. "with @a startIndex are extracted from @a text.\n"
  835. "@return A string containing the specified range of fields from @a text or \"\" if @a startIndex "
  836. "is out of range or greater than @a endIndex.\n\n"
  837. "@tsexample\n"
  838. "getFields( \"a b\" TAB \"c d\" TAB \"e f\", 1 ) // Returns \"c d\" TAB \"e f\"\n"
  839. "@endtsexample\n\n"
  840. "@see getField\n"
  841. "@see getFieldCount\n"
  842. "@see getWords\n"
  843. "@see getRecords\n"
  844. "@ingroup FieldManip" )
  845. {
  846. if( endIndex < 0 )
  847. endIndex = 1000000;
  848. return Con::getReturnBuffer( StringUnit::getUnits( text, startIndex, endIndex, "\t\n" ) );
  849. }
  850. //-----------------------------------------------------------------------------
  851. DefineConsoleFunction( setField, const char*, ( const char* text, S32 index, const char* replacement ),,
  852. "Replace the field in @a text at the given @a index with @a replacement.\n"
  853. "Fields in @a text must be separated by newlines and/or tabs.\n"
  854. "@param text A list of fields separated by newlines and/or tabs.\n"
  855. "@param index The zero-based index of the field to replace.\n"
  856. "@param replacement The string with which to replace the field.\n"
  857. "@return A new string with the field at the given @a index replaced by @a replacement or the original "
  858. "string if @a index is out of range.\n\n"
  859. "@tsexample\n"
  860. "setField( \"a b\" TAB \"c d\" TAB \"e f\", 1, \"g h\" ) // Returns \"a b\" TAB \"g h\" TAB \"e f\"\n"
  861. "@endtsexample\n\n"
  862. "@see getField\n"
  863. "@see setWord\n"
  864. "@see setRecord\n"
  865. "@ingroup FieldManip" )
  866. {
  867. return Con::getReturnBuffer( StringUnit::setUnit( text, index, replacement, "\t\n" ) );
  868. }
  869. //-----------------------------------------------------------------------------
  870. DefineConsoleFunction( removeField, const char*, ( const char* text, S32 index ),,
  871. "Remove the field in @a text at the given @a index.\n"
  872. "Fields in @a text must be separated by newlines and/or tabs.\n"
  873. "@param text A list of fields separated by newlines and/or tabs.\n"
  874. "@param index The zero-based index of the field in @a text.\n"
  875. "@return A new string with the field at the given index removed or the original string if @a index is "
  876. "out of range.\n\n"
  877. "@tsexample\n"
  878. "removeField( \"a b\" TAB \"c d\" TAB \"e f\", 1 ) // Returns \"a b\" TAB \"e f\"\n"
  879. "@endtsexample\n\n"
  880. "@see removeWord\n"
  881. "@see removeRecord\n"
  882. "@ingroup FieldManip" )
  883. {
  884. return Con::getReturnBuffer( StringUnit::removeUnit( text, index, "\t\n" ) );
  885. }
  886. //-----------------------------------------------------------------------------
  887. DefineConsoleFunction( getFieldCount, S32, ( const char* text ),,
  888. "Return the number of newline and/or tab separated fields in @a text.\n"
  889. "@param text A list of fields separated by newlines and/or tabs.\n"
  890. "@return The number of newline and/or tab sepearated elements in @a text.\n\n"
  891. "@tsexample\n"
  892. "getFieldCount( \"a b\" TAB \"c d\" TAB \"e f\" ) // Returns 3\n"
  893. "@endtsexample\n\n"
  894. "@see getWordCount\n"
  895. "@see getRecordCount\n"
  896. "@ingroup FieldManip" )
  897. {
  898. return StringUnit::getUnitCount( text, "\t\n" );
  899. }
  900. //-----------------------------------------------------------------------------
  901. DefineConsoleFunction( getRecord, const char*, ( const char* text, S32 index ),,
  902. "Extract the record at the given @a index in the newline-separated list in @a text.\n"
  903. "Records in @a text must be separated by newlines.\n"
  904. "@param text A list of records separated by newlines.\n"
  905. "@param index The zero-based index of the record to extract.\n"
  906. "@return The record at the given index or \"\" if @a index is out of range.\n\n"
  907. "@tsexample\n"
  908. "getRecord( \"a b\" NL \"c d\" NL \"e f\", 1 ) // Returns \"c d\"\n"
  909. "@endtsexample\n\n"
  910. "@see getRecords\n"
  911. "@see getRecordCount\n"
  912. "@see getWord\n"
  913. "@see getField\n"
  914. "@ingroup FieldManip" )
  915. {
  916. return Con::getReturnBuffer( StringUnit::getUnit( text, index, "\n" ) );
  917. }
  918. //-----------------------------------------------------------------------------
  919. DefineConsoleFunction( getRecords, const char*, ( const char* text, S32 startIndex, S32 endIndex ), ( -1 ),
  920. "Extract a range of records from the given @a startIndex onwards thru @a endIndex.\n"
  921. "Records in @a text must be separated by newlines.\n"
  922. "@param text A list of records separated by newlines.\n"
  923. "@param startIndex The zero-based index of the first record to extract from @a text.\n"
  924. "@param endIndex The zero-based index of the last record to extract from @a text. If this is -1, all records beginning "
  925. "with @a startIndex are extracted from @a text.\n"
  926. "@return A string containing the specified range of records from @a text or \"\" if @a startIndex "
  927. "is out of range or greater than @a endIndex.\n\n"
  928. "@tsexample\n"
  929. "getRecords( \"a b\" NL \"c d\" NL \"e f\", 1 ) // Returns \"c d\" NL \"e f\"\n"
  930. "@endtsexample\n\n"
  931. "@see getRecord\n"
  932. "@see getRecordCount\n"
  933. "@see getWords\n"
  934. "@see getFields\n"
  935. "@ingroup FieldManip" )
  936. {
  937. if( endIndex < 0 )
  938. endIndex = 1000000;
  939. return Con::getReturnBuffer( StringUnit::getUnits( text, startIndex, endIndex, "\n" ) );
  940. }
  941. //-----------------------------------------------------------------------------
  942. DefineConsoleFunction( setRecord, const char*, ( const char* text, S32 index, const char* replacement ),,
  943. "Replace the record in @a text at the given @a index with @a replacement.\n"
  944. "Records in @a text must be separated by newlines.\n"
  945. "@param text A list of records separated by newlines.\n"
  946. "@param index The zero-based index of the record to replace.\n"
  947. "@param replacement The string with which to replace the record.\n"
  948. "@return A new string with the record at the given @a index replaced by @a replacement or the original "
  949. "string if @a index is out of range.\n\n"
  950. "@tsexample\n"
  951. "setRecord( \"a b\" NL \"c d\" NL \"e f\", 1, \"g h\" ) // Returns \"a b\" NL \"g h\" NL \"e f\"\n"
  952. "@endtsexample\n\n"
  953. "@see getRecord\n"
  954. "@see setWord\n"
  955. "@see setField\n"
  956. "@ingroup FieldManip" )
  957. {
  958. return Con::getReturnBuffer( StringUnit::setUnit( text, index, replacement, "\n" ) );
  959. }
  960. //-----------------------------------------------------------------------------
  961. DefineConsoleFunction( removeRecord, const char*, ( const char* text, S32 index ),,
  962. "Remove the record in @a text at the given @a index.\n"
  963. "Records in @a text must be separated by newlines.\n"
  964. "@param text A list of records separated by newlines.\n"
  965. "@param index The zero-based index of the record in @a text.\n"
  966. "@return A new string with the record at the given @a index removed or the original string if @a index is "
  967. "out of range.\n\n"
  968. "@tsexample\n"
  969. "removeRecord( \"a b\" NL \"c d\" NL \"e f\", 1 ) // Returns \"a b\" NL \"e f\"\n"
  970. "@endtsexample\n\n"
  971. "@see removeWord\n"
  972. "@see removeField\n"
  973. "@ingroup FieldManip" )
  974. {
  975. return Con::getReturnBuffer( StringUnit::removeUnit( text, index, "\n" ) );
  976. }
  977. //-----------------------------------------------------------------------------
  978. DefineConsoleFunction( getRecordCount, S32, ( const char* text ),,
  979. "Return the number of newline-separated records in @a text.\n"
  980. "@param text A list of records separated by newlines.\n"
  981. "@return The number of newline-sepearated elements in @a text.\n\n"
  982. "@tsexample\n"
  983. "getRecordCount( \"a b\" NL \"c d\" NL \"e f\" ) // Returns 3\n"
  984. "@endtsexample\n\n"
  985. "@see getWordCount\n"
  986. "@see getFieldCount\n"
  987. "@ingroup FieldManip" )
  988. {
  989. return StringUnit::getUnitCount( text, "\n" );
  990. }
  991. //-----------------------------------------------------------------------------
  992. DefineConsoleFunction( firstWord, const char*, ( const char* text ),,
  993. "Return the first word in @a text.\n"
  994. "@param text A list of words separated by newlines, spaces, and/or tabs.\n"
  995. "@return The word at index 0 in @a text or \"\" if @a text is empty.\n\n"
  996. "@note This is equal to \n"
  997. "@tsexample_nopar\n"
  998. "getWord( text, 0 )\n"
  999. "@endtsexample\n\n"
  1000. "@see getWord\n"
  1001. "@ingroup FieldManip" )
  1002. {
  1003. return Con::getReturnBuffer( StringUnit::getUnit( text, 0, " \t\n" ) );
  1004. }
  1005. //-----------------------------------------------------------------------------
  1006. DefineConsoleFunction( restWords, const char*, ( const char* text ),,
  1007. "Return all but the first word in @a text.\n"
  1008. "@param text A list of words separated by newlines, spaces, and/or tabs.\n"
  1009. "@return @a text with the first word removed.\n\n"
  1010. "@note This is equal to \n"
  1011. "@tsexample_nopar\n"
  1012. "getWords( text, 1 )\n"
  1013. "@endtsexample\n\n"
  1014. "@see getWords\n"
  1015. "@ingroup FieldManip" )
  1016. {
  1017. const char* ptr = text;
  1018. while( *ptr && *ptr != ' ' && *ptr != '\t' && *ptr != '\n' )
  1019. ptr ++;
  1020. // Skip separator.
  1021. if( *ptr )
  1022. ptr ++;
  1023. return Con::getReturnBuffer( ptr );
  1024. }
  1025. //-----------------------------------------------------------------------------
  1026. static bool isInSet(char c, const char *set)
  1027. {
  1028. if (set)
  1029. while (*set)
  1030. if (c == *set++)
  1031. return true;
  1032. return false;
  1033. }
  1034. DefineConsoleFunction( nextToken, const char*, ( const char* str1, const char* token, const char* delim), , "( string str, string token, string delimiters ) "
  1035. "Tokenize a string using a set of delimiting characters.\n"
  1036. "This function first skips all leading charaters in @a str that are contained in @a delimiters. "
  1037. "From that position, it then scans for the next character in @a str that is contained in @a delimiters and stores all characters "
  1038. "from the starting position up to the first delimiter in a variable in the current scope called @a token. Finally, it "
  1039. "skips all characters in @a delimiters after the token and then returns the remaining string contents in @a str.\n\n"
  1040. "To scan out all tokens in a string, call this function repeatedly by passing the result it returns each time as the new @a str "
  1041. "until the function returns \"\".\n\n"
  1042. "@param str A string.\n"
  1043. "@param token The name of the variable in which to store the current token. This variable is set in the "
  1044. "scope in which nextToken is called.\n"
  1045. "@param delimiters A string of characters. Each character is considered a delimiter.\n"
  1046. "@return The remainder of @a str after the token has been parsed out or \"\" if no more tokens were found in @a str.\n\n"
  1047. "@tsexample\n"
  1048. "// Prints:\n"
  1049. "// a\n"
  1050. "// b\n"
  1051. "// c\n"
  1052. "%str = \"a b c\";\n"
  1053. "while ( %str !$= \"\" )\n"
  1054. "{\n"
  1055. " // First time, stores \"a\" in the variable %token and sets %str to \"b c\".\n"
  1056. " %str = nextToken( %str, \"token\", \" \" );\n"
  1057. " echo( %token );\n"
  1058. "}\n"
  1059. "@endtsexample\n\n"
  1060. "@ingroup Strings" )
  1061. {
  1062. char buffer[4096];
  1063. dStrncpy(buffer, str1, 4096);
  1064. char *str = buffer;
  1065. if( str[0] )
  1066. {
  1067. // skip over any characters that are a member of delim
  1068. // no need for special '\0' check since it can never be in delim
  1069. while (isInSet(*str, delim))
  1070. str++;
  1071. // skip over any characters that are NOT a member of delim
  1072. const char *tmp = str;
  1073. while (*str && !isInSet(*str, delim))
  1074. str++;
  1075. // terminate the token
  1076. if (*str)
  1077. *str++ = 0;
  1078. // set local variable if inside a function
  1079. if (gEvalState.getStackDepth() > 0 &&
  1080. gEvalState.getCurrentFrame().scopeName)
  1081. Con::setLocalVariable(token,tmp);
  1082. else
  1083. Con::setVariable(token,tmp);
  1084. // advance str past the 'delim space'
  1085. while (isInSet(*str, delim))
  1086. str++;
  1087. }
  1088. U32 returnLen = dStrlen(str)+1;
  1089. char *ret = Con::getReturnBuffer(returnLen);
  1090. dStrncpy(ret, str, returnLen);
  1091. return ret;
  1092. }
  1093. //=============================================================================
  1094. // Tagged Strings.
  1095. //=============================================================================
  1096. // MARK: ---- Tagged Strings ----
  1097. //-----------------------------------------------------------------------------
  1098. DefineEngineFunction( detag, const char*, ( const char* str ),,
  1099. "@brief Returns the string from a tag string.\n\n"
  1100. "Should only be used within the context of a function that receives a tagged "
  1101. "string, and is not meant to be used outside of this context. Use getTaggedString() "
  1102. "to convert a tagged string ID back into a regular string at any time.\n\n"
  1103. "@tsexample\n"
  1104. "// From scripts/client/message.cs\n"
  1105. "function clientCmdChatMessage(%sender, %voice, %pitch, %msgString, %a1, %a2, %a3, %a4, %a5, %a6, %a7, %a8, %a9, %a10)\n"
  1106. "{\n"
  1107. " onChatMessage(detag(%msgString), %voice, %pitch);\n"
  1108. "}\n"
  1109. "@endtsexample\n\n"
  1110. "@see \\ref syntaxDataTypes under Tagged %Strings\n"
  1111. "@see getTag()\n"
  1112. "@see getTaggedString()\n"
  1113. "@ingroup Networking")
  1114. {
  1115. if( str[ 0 ] == StringTagPrefixByte )
  1116. {
  1117. const char* word = dStrchr( str, ' ' );
  1118. if( word == NULL )
  1119. return "";
  1120. char* ret = Con::getReturnBuffer( dStrlen( word + 1 ) + 1 );
  1121. dStrcpy( ret, word + 1 );
  1122. return ret;
  1123. }
  1124. else
  1125. return str;
  1126. }
  1127. DefineConsoleFunction( getTag, const char*, ( const char* textTagString ), , "( string textTagString ) "
  1128. "@brief Extracts the tag from a tagged string\n\n"
  1129. "Should only be used within the context of a function that receives a tagged "
  1130. "string, and is not meant to be used outside of this context.\n\n"
  1131. "@param textTagString The tagged string to extract.\n"
  1132. "@returns The tag ID of the string.\n"
  1133. "@see \\ref syntaxDataTypes under Tagged %Strings\n"
  1134. "@see detag()\n"
  1135. "@ingroup Networking")
  1136. {
  1137. if(textTagString[0] == StringTagPrefixByte)
  1138. {
  1139. const char * space = dStrchr(textTagString, ' ');
  1140. U64 len;
  1141. if(space)
  1142. len = space - textTagString;
  1143. else
  1144. len = dStrlen(textTagString) + 1;
  1145. char * ret = Con::getReturnBuffer(len);
  1146. dStrncpy(ret, textTagString + 1, len - 1);
  1147. ret[len - 1] = 0;
  1148. return(ret);
  1149. }
  1150. else
  1151. return(textTagString);
  1152. }
  1153. //=============================================================================
  1154. // Output.
  1155. //=============================================================================
  1156. // MARK: ---- Output ----
  1157. //-----------------------------------------------------------------------------
  1158. ConsoleFunction( echo, void, 2, 0, "( string message... ) "
  1159. "@brief Logs a message to the console.\n\n"
  1160. "Concatenates all given arguments to a single string and prints the string to the console. "
  1161. "A newline is added automatically after the text.\n\n"
  1162. "@param message Any number of string arguments.\n\n"
  1163. "@ingroup Logging" )
  1164. {
  1165. U32 len = 0;
  1166. S32 i;
  1167. for(i = 1; i < argc; i++)
  1168. len += dStrlen(argv[i]);
  1169. char *ret = Con::getReturnBuffer(len + 1);
  1170. ret[0] = 0;
  1171. for(i = 1; i < argc; i++)
  1172. dStrcat(ret, argv[i]);
  1173. Con::printf("%s", ret);
  1174. ret[0] = 0;
  1175. }
  1176. //-----------------------------------------------------------------------------
  1177. ConsoleFunction( warn, void, 2, 0, "( string message... ) "
  1178. "@brief Logs a warning message to the console.\n\n"
  1179. "Concatenates all given arguments to a single string and prints the string to the console as a warning "
  1180. "message (in the in-game console, these will show up using a turquoise font by default). "
  1181. "A newline is added automatically after the text.\n\n"
  1182. "@param message Any number of string arguments.\n\n"
  1183. "@ingroup Logging" )
  1184. {
  1185. U32 len = 0;
  1186. S32 i;
  1187. for(i = 1; i < argc; i++)
  1188. len += dStrlen(argv[i]);
  1189. char *ret = Con::getReturnBuffer(len + 1);
  1190. ret[0] = 0;
  1191. for(i = 1; i < argc; i++)
  1192. dStrcat(ret, argv[i]);
  1193. Con::warnf(ConsoleLogEntry::General, "%s", ret);
  1194. ret[0] = 0;
  1195. }
  1196. //-----------------------------------------------------------------------------
  1197. ConsoleFunction( error, void, 2, 0, "( string message... ) "
  1198. "@brief Logs an error message to the console.\n\n"
  1199. "Concatenates all given arguments to a single string and prints the string to the console as an error "
  1200. "message (in the in-game console, these will show up using a red font by default). "
  1201. "A newline is added automatically after the text.\n\n"
  1202. "@param message Any number of string arguments.\n\n"
  1203. "@ingroup Logging" )
  1204. {
  1205. U32 len = 0;
  1206. S32 i;
  1207. for(i = 1; i < argc; i++)
  1208. len += dStrlen(argv[i]);
  1209. char *ret = Con::getReturnBuffer(len + 1);
  1210. ret[0] = 0;
  1211. for(i = 1; i < argc; i++)
  1212. dStrcat(ret, argv[i]);
  1213. Con::errorf(ConsoleLogEntry::General, "%s", ret);
  1214. ret[0] = 0;
  1215. }
  1216. //-----------------------------------------------------------------------------
  1217. DefineEngineFunction( debugv, void, ( const char* variableName ),,
  1218. "@brief Logs the value of the given variable to the console.\n\n"
  1219. "Prints a string of the form \"<variableName> = <variable value>\" to the console.\n\n"
  1220. "@param variableName Name of the local or global variable to print.\n\n"
  1221. "@tsexample\n"
  1222. "%var = 1;\n"
  1223. "debugv( \"%var\" ); // Prints \"%var = 1\"\n"
  1224. "@endtsexample\n\n"
  1225. "@ingroup Debugging" )
  1226. {
  1227. if( variableName[ 0 ] == '%' )
  1228. Con::errorf( "%s = %s", variableName, Con::getLocalVariable( variableName ) );
  1229. else
  1230. Con::errorf( "%s = %s", variableName, Con::getVariable( variableName ) );
  1231. }
  1232. //-----------------------------------------------------------------------------
  1233. DefineConsoleFunction( expandEscape, const char*, ( const char* text ),,
  1234. "@brief Replace all characters in @a text that need to be escaped for the string to be a valid string literal with their "
  1235. "respective escape sequences.\n\n"
  1236. "All characters in @a text that cannot appear in a string literal will be replaced by an escape sequence (\\\\n, \\\\t, etc).\n\n"
  1237. "The primary use of this function is for converting strings suitable for being passed as string literals "
  1238. "to the TorqueScript compiler.\n\n"
  1239. "@param text A string\n"
  1240. "@return A duplicate of the text parameter with all unescaped characters that cannot appear in string literals replaced by their respective "
  1241. "escape sequences.\n\n"
  1242. "@tsxample\n"
  1243. "expandEscape( \"str\" NL \"ing\" ) // Returns \"str\\ning\".\n"
  1244. "@endtsxample\n\n"
  1245. "@see collapseEscape\n"
  1246. "@ingroup Strings")
  1247. {
  1248. char* ret = Con::getReturnBuffer(dStrlen( text ) * 2 + 1 ); // worst case situation
  1249. expandEscape( ret, text );
  1250. return ret;
  1251. }
  1252. //-----------------------------------------------------------------------------
  1253. DefineConsoleFunction( collapseEscape, const char*, ( const char* text ),,
  1254. "Replace all escape sequences in @a text with their respective character codes.\n\n"
  1255. "This function replaces all escape sequences (\\\\n, \\\\t, etc) in the given string "
  1256. "with the respective characters they represent.\n\n"
  1257. "The primary use of this function is for converting strings from their literal form into "
  1258. "their compiled/translated form, as is normally done by the TorqueScript compiler.\n\n"
  1259. "@param text A string.\n"
  1260. "@return A duplicate of @a text with all escape sequences replaced by their respective character codes.\n\n"
  1261. "@tsexample\n"
  1262. "// Print:\n"
  1263. "//\n"
  1264. "// str\n"
  1265. "// ing\n"
  1266. "//\n"
  1267. "// to the console. Note how the backslash in the string must be escaped here\n"
  1268. "// in order to prevent the TorqueScript compiler from collapsing the escape\n"
  1269. "// sequence in the resulting string.\n"
  1270. "echo( collapseEscape( \"str\\ning\" ) );\n"
  1271. "@endtsexample\n\n"
  1272. "@see expandEscape\n\n"
  1273. "@ingroup Strings" )
  1274. {
  1275. char* ret = Con::getReturnBuffer( text );
  1276. collapseEscape( ret );
  1277. return ret;
  1278. }
  1279. //-----------------------------------------------------------------------------
  1280. DefineEngineFunction( setLogMode, void, ( S32 mode ),,
  1281. "@brief Determines how log files are written.\n\n"
  1282. "Sets the operational mode of the console logging system.\n\n"
  1283. "@param mode Parameter specifying the logging mode. This can be:\n"
  1284. "- 1: Open and close the console log file for each seperate string of output. This will ensure that all "
  1285. "parts get written out to disk and that no parts remain in intermediate buffers even if the process crashes.\n"
  1286. "- 2: Keep the log file open and write to it continuously. This will make the system operate faster but "
  1287. "if the process crashes, parts of the output may not have been written to disk yet and will be missing from "
  1288. "the log.\n\n"
  1289. "Additionally, when changing the log mode and thus opening a new log file, either of the two mode values may be "
  1290. "combined by binary OR with 0x4 to cause the logging system to flush all console log messages that had already been "
  1291. "issued to the console system into the newly created log file.\n\n"
  1292. "@note Xbox 360 does not support logging to a file. Use Platform::OutputDebugStr in C++ instead."
  1293. "@ingroup Logging" )
  1294. {
  1295. Con::setLogMode( mode );
  1296. }
  1297. //=============================================================================
  1298. // Misc.
  1299. //=============================================================================
  1300. // MARK: ---- Misc ----
  1301. //-----------------------------------------------------------------------------
  1302. DefineConsoleFunction( quit, void, ( ),,
  1303. "Shut down the engine and exit its process.\n"
  1304. "This function cleanly uninitializes the engine and then exits back to the system with a process "
  1305. "exit status indicating a clean exit.\n\n"
  1306. "@see quitWithErrorMessage\n\n"
  1307. "@ingroup Platform" )
  1308. {
  1309. Platform::postQuitMessage(0);
  1310. }
  1311. //-----------------------------------------------------------------------------
  1312. DefineConsoleFunction( realQuit, void, (), , "")
  1313. {
  1314. Platform::postQuitMessage(0);
  1315. }
  1316. //-----------------------------------------------------------------------------
  1317. DefineConsoleFunction( quitWithErrorMessage, void, ( const char* message, S32 status ), (0),
  1318. "Display an error message box showing the given @a message and then shut down the engine and exit its process.\n"
  1319. "This function cleanly uninitialized the engine and then exits back to the system with a process "
  1320. "exit status indicating an error.\n\n"
  1321. "@param message The message to log to the console and show in an error message box.\n"
  1322. "@param status The status code to return to the OS.\n\n"
  1323. "@see quit\n\n"
  1324. "@ingroup Platform" )
  1325. {
  1326. Con::errorf( message );
  1327. Platform::AlertOK( "Error", message );
  1328. // [rene 03/30/10] This was previously using forceShutdown which is a bad thing
  1329. // as the script code should not be allowed to pretty much hard-crash the engine
  1330. // and prevent proper shutdown. Changed this to use postQuitMessage.
  1331. Platform::postQuitMessage( status );
  1332. }
  1333. //-----------------------------------------------------------------------------
  1334. DefineConsoleFunction( quitWithStatus, void, ( S32 status ), (0),
  1335. "Shut down the engine and exit its process.\n"
  1336. "This function cleanly uninitializes the engine and then exits back to the system with a given "
  1337. "return status code.\n\n"
  1338. "@param status The status code to return to the OS.\n\n"
  1339. "@see quitWithErrorMessage\n\n"
  1340. "@ingroup Platform" )
  1341. {
  1342. Platform::postQuitMessage(status);
  1343. }
  1344. //-----------------------------------------------------------------------------
  1345. DefineEngineFunction( gotoWebPage, void, ( const char* address ),,
  1346. "Open the given URL or file in the user's web browser.\n\n"
  1347. "@param address The address to open. If this is not prefixed by a protocol specifier (\"...://\"), then "
  1348. "the function checks whether the address refers to a file or directory and if so, prepends \"file://\" "
  1349. "to @a adress; if the file check fails, \"http://\" is prepended to @a address.\n\n"
  1350. "@tsexample\n"
  1351. "gotoWebPage( \"http://www.garagegames.com\" );\n"
  1352. "@endtsexample\n\n"
  1353. "@ingroup Platform" )
  1354. {
  1355. // If there's a protocol prefix in the address, just invoke
  1356. // the browser on the given address.
  1357. char* protocolSep = dStrstr( address,"://");
  1358. if( protocolSep != NULL )
  1359. {
  1360. Platform::openWebBrowser( address );
  1361. return;
  1362. }
  1363. // If we don't see a protocol seperator, then we know that some bullethead
  1364. // sent us a bad url. We'll first check to see if a file inside the sandbox
  1365. // with that name exists, then we'll just glom "http://" onto the front of
  1366. // the bogus url, and hope for the best.
  1367. String addr;
  1368. if( Platform::isFile( address ) || Platform::isDirectory( address ) )
  1369. {
  1370. #ifdef TORQUE2D_TOOLS_FIXME
  1371. addr = String::ToString( "file://%s", address );
  1372. #else
  1373. addr = String::ToString( "file://%s/%s", Platform::getCurrentDirectory(), address );
  1374. #endif
  1375. }
  1376. else
  1377. addr = String::ToString( "http://%s", address );
  1378. Platform::openWebBrowser( addr );
  1379. return;
  1380. }
  1381. //-----------------------------------------------------------------------------
  1382. DefineEngineFunction( displaySplashWindow, bool, (const char* path), ("art/gui/splash.bmp"),
  1383. "Display a startup splash window suitable for showing while the engine still starts up.\n\n"
  1384. "@note This is currently only implemented on Windows.\n\n"
  1385. "@return True if the splash window could be successfully initialized.\n\n"
  1386. "@ingroup Platform" )
  1387. {
  1388. return Platform::displaySplashWindow(path);
  1389. }
  1390. DefineEngineFunction( closeSplashWindow, void, (),,
  1391. "Close our startup splash window.\n\n"
  1392. "@note This is currently only implemented on Windows.\n\n"
  1393. "@ingroup Platform" )
  1394. {
  1395. Platform::closeSplashWindow();
  1396. }
  1397. //-----------------------------------------------------------------------------
  1398. DefineEngineFunction( getWebDeployment, bool, (),,
  1399. "Test whether Torque is running in web-deployment mode.\n"
  1400. "In this mode, Torque will usually run within a browser and certain restrictions apply (e.g. Torque will not "
  1401. "be able to enter fullscreen exclusive mode).\n"
  1402. "@return True if Torque is running in web-deployment mode.\n"
  1403. "@ingroup Platform" )
  1404. {
  1405. return Platform::getWebDeployment();
  1406. }
  1407. //-----------------------------------------------------------------------------
  1408. DefineEngineFunction( countBits, S32, ( S32 v ),,
  1409. "Count the number of bits that are set in the given 32 bit integer.\n"
  1410. "@param v An integer value.\n\n"
  1411. "@return The number of bits that are set in @a v.\n\n"
  1412. "@ingroup Utilities" )
  1413. {
  1414. S32 c = 0;
  1415. // from
  1416. // http://graphics.stanford.edu/~seander/bithacks.html
  1417. // for at most 32-bit values in v:
  1418. c = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
  1419. c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) %
  1420. 0x1f;
  1421. c += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
  1422. #ifndef TORQUE_SHIPPING
  1423. // since the above isn't very obvious, for debugging compute the count in a more
  1424. // traditional way and assert if it is different
  1425. {
  1426. S32 c2 = 0;
  1427. S32 v2 = v;
  1428. for (c2 = 0; v2; v2 >>= 1)
  1429. {
  1430. c2 += v2 & 1;
  1431. }
  1432. if (c2 != c)
  1433. Con::errorf("countBits: Uh oh bit count mismatch");
  1434. AssertFatal(c2 == c, "countBits: uh oh, bit count mismatch");
  1435. }
  1436. #endif
  1437. return c;
  1438. }
  1439. //-----------------------------------------------------------------------------
  1440. DefineEngineFunction( generateUUID, Torque::UUID, (),,
  1441. "Generate a new universally unique identifier (UUID).\n\n"
  1442. "@return A newly generated UUID.\n\n"
  1443. "@ingroup Utilities" )
  1444. {
  1445. Torque::UUID uuid;
  1446. uuid.generate();
  1447. return uuid;
  1448. }
  1449. //=============================================================================
  1450. // Meta Scripting.
  1451. //=============================================================================
  1452. // MARK: ---- Meta Scripting ----
  1453. //-----------------------------------------------------------------------------
  1454. ConsoleFunction( call, const char *, 2, 0, "( string functionName, string args... ) "
  1455. "Apply the given arguments to the specified global function and return the result of the call.\n\n"
  1456. "@param functionName The name of the function to call. This function must be in the global namespace, i.e. "
  1457. "you cannot call a function in a namespace through #call. Use eval() for that.\n"
  1458. "@return The result of the function call.\n\n"
  1459. "@tsexample\n"
  1460. "function myFunction( %arg )\n"
  1461. "{\n"
  1462. " return ( %arg SPC \"World!\" );\n"
  1463. "}\n"
  1464. "\n"
  1465. "echo( call( \"myFunction\", \"Hello\" ) ); // Prints \"Hello World!\" to the console.\n"
  1466. "@endtsexample\n\n"
  1467. "@ingroup Scripting" )
  1468. {
  1469. return Con::execute( argc - 1, argv + 1 );
  1470. }
  1471. //-----------------------------------------------------------------------------
  1472. static U32 execDepth = 0;
  1473. static U32 journalDepth = 1;
  1474. static StringTableEntry getDSOPath(const char *scriptPath)
  1475. {
  1476. #ifndef TORQUE2D_TOOLS_FIXME
  1477. // [tom, 11/17/2006] Force old behavior for the player. May not want to do this.
  1478. const char *slash = dStrrchr(scriptPath, '/');
  1479. if(slash != NULL)
  1480. return StringTable->insertn(scriptPath, slash - scriptPath, true);
  1481. slash = dStrrchr(scriptPath, ':');
  1482. if(slash != NULL)
  1483. return StringTable->insertn(scriptPath, (slash - scriptPath) + 1, true);
  1484. return "";
  1485. #else
  1486. char relPath[1024], dsoPath[1024];
  1487. bool isPrefs = false;
  1488. // [tom, 11/17/2006] Prefs are handled slightly differently to avoid dso name clashes
  1489. StringTableEntry prefsPath = Platform::getPrefsPath();
  1490. if(dStrnicmp(scriptPath, prefsPath, dStrlen(prefsPath)) == 0)
  1491. {
  1492. relPath[0] = 0;
  1493. isPrefs = true;
  1494. }
  1495. else
  1496. {
  1497. StringTableEntry strippedPath = Platform::stripBasePath(scriptPath);
  1498. dStrcpy(relPath, strippedPath);
  1499. char *slash = dStrrchr(relPath, '/');
  1500. if(slash)
  1501. *slash = 0;
  1502. }
  1503. const char *overridePath;
  1504. if(! isPrefs)
  1505. overridePath = Con::getVariable("$Scripts::OverrideDSOPath");
  1506. else
  1507. overridePath = prefsPath;
  1508. if(overridePath && *overridePath)
  1509. Platform::makeFullPathName(relPath, dsoPath, sizeof(dsoPath), overridePath);
  1510. else
  1511. {
  1512. char t[1024];
  1513. dSprintf(t, sizeof(t), "compiledScripts/%s", relPath);
  1514. Platform::makeFullPathName(t, dsoPath, sizeof(dsoPath), Platform::getPrefsPath());
  1515. }
  1516. return StringTable->insert(dsoPath);
  1517. #endif
  1518. }
  1519. DefineConsoleFunction( getDSOPath, const char*, ( const char* scriptFileName ),,
  1520. "Get the absolute path to the file in which the compiled code for the given script file will be stored.\n"
  1521. "@param scriptFileName %Path to the .cs script file.\n"
  1522. "@return The absolute path to the .dso file for the given script file.\n\n"
  1523. "@note The compiler will store newly compiled DSOs in the prefs path but pre-existing DSOs will be loaded "
  1524. "from the current paths.\n\n"
  1525. "@see compile\n"
  1526. "@see getPrefsPath\n"
  1527. "@ingroup Scripting" )
  1528. {
  1529. Con::expandScriptFilename( scriptFilenameBuffer, sizeof(scriptFilenameBuffer), scriptFileName );
  1530. const char* filename = getDSOPath(scriptFilenameBuffer);
  1531. if(filename == NULL || *filename == 0)
  1532. return "";
  1533. return filename;
  1534. }
  1535. //-----------------------------------------------------------------------------
  1536. DefineEngineFunction( compile, bool, ( const char* fileName, bool overrideNoDSO ), ( false ),
  1537. "Compile a file to bytecode.\n\n"
  1538. "This function will read the TorqueScript code in the specified file, compile it to internal bytecode, and, "
  1539. "if DSO generation is enabled or @a overrideNoDDSO is true, will store the compiled code in a .dso file "
  1540. "in the current DSO path mirrorring the path of @a fileName.\n\n"
  1541. "@param fileName Path to the file to compile to bytecode.\n"
  1542. "@param overrideNoDSO If true, force generation of DSOs even if the engine is compiled to not "
  1543. "generate write compiled code to DSO files.\n\n"
  1544. "@return True if the file was successfully compiled, false if not.\n\n"
  1545. "@note The definitions contained in the given file will not be made available and no code will actually "
  1546. "be executed. Use exec() for that.\n\n"
  1547. "@see getDSOPath\n"
  1548. "@see exec\n"
  1549. "@ingroup Scripting" )
  1550. {
  1551. Con::expandScriptFilename( scriptFilenameBuffer, sizeof( scriptFilenameBuffer ), fileName );
  1552. // Figure out where to put DSOs
  1553. StringTableEntry dsoPath = getDSOPath(scriptFilenameBuffer);
  1554. if(dsoPath && *dsoPath == 0)
  1555. return false;
  1556. // If the script file extention is '.ed.cs' then compile it to a different compiled extention
  1557. bool isEditorScript = false;
  1558. const char *ext = dStrrchr( scriptFilenameBuffer, '.' );
  1559. if( ext && ( dStricmp( ext, ".cs" ) == 0 ) )
  1560. {
  1561. const char* ext2 = ext - 3;
  1562. if( dStricmp( ext2, ".ed.cs" ) == 0 )
  1563. isEditorScript = true;
  1564. }
  1565. else if( ext && ( dStricmp( ext, ".gui" ) == 0 ) )
  1566. {
  1567. const char* ext2 = ext - 3;
  1568. if( dStricmp( ext2, ".ed.gui" ) == 0 )
  1569. isEditorScript = true;
  1570. }
  1571. const char *filenameOnly = dStrrchr(scriptFilenameBuffer, '/');
  1572. if(filenameOnly)
  1573. ++filenameOnly;
  1574. else
  1575. filenameOnly = scriptFilenameBuffer;
  1576. char nameBuffer[512];
  1577. if( isEditorScript )
  1578. dStrcpyl(nameBuffer, sizeof(nameBuffer), dsoPath, "/", filenameOnly, ".edso", NULL);
  1579. else
  1580. dStrcpyl(nameBuffer, sizeof(nameBuffer), dsoPath, "/", filenameOnly, ".dso", NULL);
  1581. void *data = NULL;
  1582. U32 dataSize = 0;
  1583. Torque::FS::ReadFile(scriptFilenameBuffer, data, dataSize, true);
  1584. if(data == NULL)
  1585. {
  1586. Con::errorf(ConsoleLogEntry::Script, "compile: invalid script file %s.", scriptFilenameBuffer);
  1587. return false;
  1588. }
  1589. const char *script = static_cast<const char *>(data);
  1590. #ifdef TORQUE_DEBUG
  1591. Con::printf("Compiling %s...", scriptFilenameBuffer);
  1592. #endif
  1593. CodeBlock *code = new CodeBlock();
  1594. code->compile(nameBuffer, scriptFilenameBuffer, script, overrideNoDSO);
  1595. delete code;
  1596. delete[] script;
  1597. return true;
  1598. }
  1599. //-----------------------------------------------------------------------------
  1600. DefineEngineFunction( exec, bool, ( const char* fileName, bool noCalls, bool journalScript ), ( false, false ),
  1601. "Execute the given script file.\n"
  1602. "@param fileName Path to the file to execute\n"
  1603. "@param noCalls Deprecated\n"
  1604. "@param journalScript Deprecated\n"
  1605. "@return True if the script was successfully executed, false if not.\n\n"
  1606. "@tsexample\n"
  1607. "// Execute the init.cs script file found in the same directory as the current script file.\n"
  1608. "exec( \"./init.cs\" );\n"
  1609. "@endtsexample\n\n"
  1610. "@see compile\n"
  1611. "@see eval\n"
  1612. "@ingroup Scripting" )
  1613. {
  1614. bool journal = false;
  1615. execDepth++;
  1616. if(journalDepth >= execDepth)
  1617. journalDepth = execDepth + 1;
  1618. else
  1619. journal = true;
  1620. bool ret = false;
  1621. if( journalScript && !journal )
  1622. {
  1623. journal = true;
  1624. journalDepth = execDepth;
  1625. }
  1626. // Determine the filename we actually want...
  1627. Con::expandScriptFilename( scriptFilenameBuffer, sizeof( scriptFilenameBuffer ), fileName );
  1628. // since this function expects a script file reference, if it's a .dso
  1629. // lets terminate the string before the dso so it will act like a .cs
  1630. if(dStrEndsWith(scriptFilenameBuffer, ".dso"))
  1631. {
  1632. scriptFilenameBuffer[dStrlen(scriptFilenameBuffer) - dStrlen(".dso")] = '\0';
  1633. }
  1634. // Figure out where to put DSOs
  1635. StringTableEntry dsoPath = getDSOPath(scriptFilenameBuffer);
  1636. const char *ext = dStrrchr(scriptFilenameBuffer, '.');
  1637. if(!ext)
  1638. {
  1639. // We need an extension!
  1640. Con::errorf(ConsoleLogEntry::Script, "exec: invalid script file name %s.", scriptFilenameBuffer);
  1641. execDepth--;
  1642. return false;
  1643. }
  1644. // Check Editor Extensions
  1645. bool isEditorScript = false;
  1646. // If the script file extension is '.ed.cs' then compile it to a different compiled extension
  1647. if( dStricmp( ext, ".cs" ) == 0 )
  1648. {
  1649. const char* ext2 = ext - 3;
  1650. if( dStricmp( ext2, ".ed.cs" ) == 0 )
  1651. isEditorScript = true;
  1652. }
  1653. else if( dStricmp( ext, ".gui" ) == 0 )
  1654. {
  1655. const char* ext2 = ext - 3;
  1656. if( dStricmp( ext2, ".ed.gui" ) == 0 )
  1657. isEditorScript = true;
  1658. }
  1659. StringTableEntry scriptFileName = StringTable->insert(scriptFilenameBuffer);
  1660. #ifndef TORQUE_OS_XENON
  1661. // Is this a file we should compile? (anything in the prefs path should not be compiled)
  1662. StringTableEntry prefsPath = Platform::getPrefsPath();
  1663. bool compiled = dStricmp(ext, ".mis") && !journal && !Con::getBoolVariable("Scripts::ignoreDSOs");
  1664. // [tom, 12/5/2006] stripBasePath() fucks up if the filename is not in the exe
  1665. // path, current directory or prefs path. Thus, getDSOFilename() will also screw
  1666. // up and so this allows the scripts to still load but without a DSO.
  1667. if(Platform::isFullPath(Platform::stripBasePath(scriptFilenameBuffer)))
  1668. compiled = false;
  1669. // [tom, 11/17/2006] It seems to make sense to not compile scripts that are in the
  1670. // prefs directory. However, getDSOPath() can handle this situation and will put
  1671. // the dso along with the script to avoid name clashes with tools/game dsos.
  1672. if( (dsoPath && *dsoPath == 0) || (prefsPath && prefsPath[ 0 ] && dStrnicmp(scriptFileName, prefsPath, dStrlen(prefsPath)) == 0) )
  1673. compiled = false;
  1674. #else
  1675. bool compiled = false; // Don't try to compile things on the 360, ignore DSO's when debugging
  1676. // because PC prefs will screw up stuff like SFX.
  1677. #endif
  1678. // If we're in a journaling mode, then we will read the script
  1679. // from the journal file.
  1680. if(journal && Journal::IsPlaying())
  1681. {
  1682. char fileNameBuf[256];
  1683. bool fileRead = false;
  1684. U32 fileSize;
  1685. Journal::ReadString(fileNameBuf);
  1686. Journal::Read(&fileRead);
  1687. if(!fileRead)
  1688. {
  1689. Con::errorf(ConsoleLogEntry::Script, "Journal script read (failed) for %s", fileNameBuf);
  1690. execDepth--;
  1691. return false;
  1692. }
  1693. Journal::Read(&fileSize);
  1694. char *script = new char[fileSize + 1];
  1695. Journal::Read(fileSize, script);
  1696. script[fileSize] = 0;
  1697. Con::printf("Executing (journal-read) %s.", scriptFileName);
  1698. CodeBlock *newCodeBlock = new CodeBlock();
  1699. newCodeBlock->compileExec(scriptFileName, script, noCalls, 0);
  1700. delete [] script;
  1701. execDepth--;
  1702. return true;
  1703. }
  1704. // Ok, we let's try to load and compile the script.
  1705. Torque::FS::FileNodeRef scriptFile = Torque::FS::GetFileNode(scriptFileName);
  1706. Torque::FS::FileNodeRef dsoFile;
  1707. // ResourceObject *rScr = gResourceManager->find(scriptFileName);
  1708. // ResourceObject *rCom = NULL;
  1709. char nameBuffer[512];
  1710. char* script = NULL;
  1711. U32 version;
  1712. Stream *compiledStream = NULL;
  1713. Torque::Time scriptModifiedTime, dsoModifiedTime;
  1714. // Check here for .edso
  1715. bool edso = false;
  1716. if( dStricmp( ext, ".edso" ) == 0 && scriptFile != NULL )
  1717. {
  1718. edso = true;
  1719. dsoFile = scriptFile;
  1720. scriptFile = NULL;
  1721. dsoModifiedTime = dsoFile->getModifiedTime();
  1722. dStrcpy( nameBuffer, scriptFileName );
  1723. }
  1724. // If we're supposed to be compiling this file, check to see if there's a DSO
  1725. if(compiled && !edso)
  1726. {
  1727. const char *filenameOnly = dStrrchr(scriptFileName, '/');
  1728. if(filenameOnly)
  1729. ++filenameOnly;
  1730. else
  1731. filenameOnly = scriptFileName;
  1732. char pathAndFilename[1024];
  1733. Platform::makeFullPathName(filenameOnly, pathAndFilename, sizeof(pathAndFilename), dsoPath);
  1734. if( isEditorScript )
  1735. dStrcpyl(nameBuffer, sizeof(nameBuffer), pathAndFilename, ".edso", NULL);
  1736. else
  1737. dStrcpyl(nameBuffer, sizeof(nameBuffer), pathAndFilename, ".dso", NULL);
  1738. dsoFile = Torque::FS::GetFileNode(nameBuffer);
  1739. if(scriptFile != NULL)
  1740. scriptModifiedTime = scriptFile->getModifiedTime();
  1741. if(dsoFile != NULL)
  1742. dsoModifiedTime = dsoFile->getModifiedTime();
  1743. }
  1744. // Let's do a sanity check to complain about DSOs in the future.
  1745. //
  1746. // MM: This doesn't seem to be working correctly for now so let's just not issue
  1747. // the warning until someone knows how to resolve it.
  1748. //
  1749. //if(compiled && rCom && rScr && Platform::compareFileTimes(comModifyTime, scrModifyTime) < 0)
  1750. //{
  1751. //Con::warnf("exec: Warning! Found a DSO from the future! (%s)", nameBuffer);
  1752. //}
  1753. // If we had a DSO, let's check to see if we should be reading from it.
  1754. //MGT: fixed bug with dsos not getting recompiled correctly
  1755. //Note: Using Nathan Martin's version from the forums since its easier to read and understand
  1756. if(compiled && dsoFile != NULL && (scriptFile == NULL|| (dsoModifiedTime >= scriptModifiedTime)))
  1757. { //MGT: end
  1758. compiledStream = FileStream::createAndOpen( nameBuffer, Torque::FS::File::Read );
  1759. if (compiledStream)
  1760. {
  1761. // Check the version!
  1762. compiledStream->read(&version);
  1763. if(version != Con::DSOVersion)
  1764. {
  1765. Con::warnf("exec: Found an old DSO (%s, ver %d < %d), ignoring.", nameBuffer, version, Con::DSOVersion);
  1766. delete compiledStream;
  1767. compiledStream = NULL;
  1768. }
  1769. }
  1770. }
  1771. // If we're journalling, let's write some info out.
  1772. if(journal && Journal::IsRecording())
  1773. Journal::WriteString(scriptFileName);
  1774. if(scriptFile != NULL && !compiledStream)
  1775. {
  1776. // If we have source but no compiled version, then we need to compile
  1777. // (and journal as we do so, if that's required).
  1778. void *data;
  1779. U32 dataSize = 0;
  1780. Torque::FS::ReadFile(scriptFileName, data, dataSize, true);
  1781. if(journal && Journal::IsRecording())
  1782. Journal::Write(bool(data != NULL));
  1783. if( data == NULL )
  1784. {
  1785. Con::errorf(ConsoleLogEntry::Script, "exec: invalid script file %s.", scriptFileName);
  1786. execDepth--;
  1787. return false;
  1788. }
  1789. else
  1790. {
  1791. if( !dataSize )
  1792. {
  1793. execDepth --;
  1794. return false;
  1795. }
  1796. script = (char *)data;
  1797. if(journal && Journal::IsRecording())
  1798. {
  1799. Journal::Write(dataSize);
  1800. Journal::Write(dataSize, data);
  1801. }
  1802. }
  1803. #ifndef TORQUE_NO_DSO_GENERATION
  1804. if(compiled)
  1805. {
  1806. // compile this baddie.
  1807. #ifdef TORQUE_DEBUG
  1808. Con::printf("Compiling %s...", scriptFileName);
  1809. #endif
  1810. CodeBlock *code = new CodeBlock();
  1811. code->compile(nameBuffer, scriptFileName, script);
  1812. delete code;
  1813. code = NULL;
  1814. compiledStream = FileStream::createAndOpen( nameBuffer, Torque::FS::File::Read );
  1815. if(compiledStream)
  1816. {
  1817. compiledStream->read(&version);
  1818. }
  1819. else
  1820. {
  1821. // We have to exit out here, as otherwise we get double error reports.
  1822. delete [] script;
  1823. execDepth--;
  1824. return false;
  1825. }
  1826. }
  1827. #endif
  1828. }
  1829. else
  1830. {
  1831. if(journal && Journal::IsRecording())
  1832. Journal::Write(bool(false));
  1833. }
  1834. if(compiledStream)
  1835. {
  1836. // Delete the script object first to limit memory used
  1837. // during recursive execs.
  1838. delete [] script;
  1839. script = 0;
  1840. // We're all compiled, so let's run it.
  1841. #ifdef TORQUE_DEBUG
  1842. Con::printf("Loading compiled script %s.", scriptFileName);
  1843. #endif
  1844. CodeBlock *code = new CodeBlock;
  1845. code->read(scriptFileName, *compiledStream);
  1846. delete compiledStream;
  1847. code->exec(0, scriptFileName, NULL, 0, NULL, noCalls, NULL, 0);
  1848. ret = true;
  1849. }
  1850. else
  1851. if(scriptFile)
  1852. {
  1853. // No compiled script, let's just try executing it
  1854. // directly... this is either a mission file, or maybe
  1855. // we're on a readonly volume.
  1856. #ifdef TORQUE_DEBUG
  1857. Con::printf("Executing %s.", scriptFileName);
  1858. #endif
  1859. CodeBlock *newCodeBlock = new CodeBlock();
  1860. StringTableEntry name = StringTable->insert(scriptFileName);
  1861. newCodeBlock->compileExec(name, script, noCalls, 0);
  1862. ret = true;
  1863. }
  1864. else
  1865. {
  1866. // Don't have anything.
  1867. Con::warnf(ConsoleLogEntry::Script, "Missing file: %s!", scriptFileName);
  1868. ret = false;
  1869. }
  1870. delete [] script;
  1871. execDepth--;
  1872. return ret;
  1873. }
  1874. DefineConsoleFunction( eval, const char*, ( const char* consoleString ), , "eval(consoleString)" )
  1875. {
  1876. return Con::evaluate(consoleString, false, NULL);
  1877. }
  1878. DefineConsoleFunction( getVariable, const char*, ( const char* varName ), , "(string varName)\n"
  1879. "@brief Returns the value of the named variable or an empty string if not found.\n\n"
  1880. "@varName Name of the variable to search for\n"
  1881. "@return Value contained by varName, \"\" if the variable does not exist\n"
  1882. "@ingroup Scripting")
  1883. {
  1884. return Con::getVariable(varName);
  1885. }
  1886. DefineConsoleFunction( setVariable, void, ( const char* varName, const char* value ), , "(string varName, string value)\n"
  1887. "@brief Sets the value of the named variable.\n\n"
  1888. "@param varName Name of the variable to locate\n"
  1889. "@param value New value of the variable\n"
  1890. "@return True if variable was successfully found and set\n"
  1891. "@ingroup Scripting")
  1892. {
  1893. return Con::setVariable(varName, value);
  1894. }
  1895. DefineConsoleFunction( isFunction, bool, ( const char* funcName ), , "(string funcName)"
  1896. "@brief Determines if a function exists or not\n\n"
  1897. "@param funcName String containing name of the function\n"
  1898. "@return True if the function exists, false if not\n"
  1899. "@ingroup Scripting")
  1900. {
  1901. return Con::isFunction(funcName);
  1902. }
  1903. DefineConsoleFunction( getFunctionPackage, const char*, ( const char* funcName ), , "(string funcName)"
  1904. "@brief Provides the name of the package the function belongs to\n\n"
  1905. "@param funcName String containing name of the function\n"
  1906. "@return The name of the function's package\n"
  1907. "@ingroup Packages")
  1908. {
  1909. Namespace::Entry* nse = Namespace::global()->lookup( StringTable->insert( funcName ) );
  1910. if( !nse )
  1911. return "";
  1912. return nse->mPackage;
  1913. }
  1914. DefineConsoleFunction( isMethod, bool, ( const char* nameSpace, const char* method ), , "(string namespace, string method)"
  1915. "@brief Determines if a class/namespace method exists\n\n"
  1916. "@param namespace Class or namespace, such as Player\n"
  1917. "@param method Name of the function to search for\n"
  1918. "@return True if the method exists, false if not\n"
  1919. "@ingroup Scripting\n")
  1920. {
  1921. Namespace* ns = Namespace::find( StringTable->insert( nameSpace ) );
  1922. Namespace::Entry* nse = ns->lookup( StringTable->insert( method ) );
  1923. if( !nse )
  1924. return false;
  1925. return true;
  1926. }
  1927. DefineConsoleFunction( getMethodPackage, const char*, ( const char* nameSpace, const char* method ), , "(string namespace, string method)"
  1928. "@brief Provides the name of the package the method belongs to\n\n"
  1929. "@param namespace Class or namespace, such as Player\n"
  1930. "@param method Name of the funciton to search for\n"
  1931. "@return The name of the method's package\n"
  1932. "@ingroup Packages")
  1933. {
  1934. Namespace* ns = Namespace::find( StringTable->insert( nameSpace ) );
  1935. if( !ns )
  1936. return "";
  1937. Namespace::Entry* nse = ns->lookup( StringTable->insert( method ) );
  1938. if( !nse )
  1939. return "";
  1940. return nse->mPackage;
  1941. }
  1942. DefineConsoleFunction( isDefined, bool, ( const char* varName, const char* varValue ), ("") , "(string varName)"
  1943. "@brief Determines if a variable exists and contains a value\n"
  1944. "@param varName Name of the variable to search for\n"
  1945. "@return True if the variable was defined in script, false if not\n"
  1946. "@tsexample\n"
  1947. "isDefined( \"$myVar\" );\n"
  1948. "@endtsexample\n\n"
  1949. "@ingroup Scripting")
  1950. {
  1951. if(dStrIsEmpty(varName))
  1952. {
  1953. Con::errorf("isDefined() - did you forget to put quotes around the variable name?");
  1954. return false;
  1955. }
  1956. StringTableEntry name = StringTable->insert(varName);
  1957. // Deal with <var>.<value>
  1958. if (dStrchr(name, '.'))
  1959. {
  1960. static char scratchBuffer[4096];
  1961. S32 len = dStrlen(name);
  1962. AssertFatal(len < sizeof(scratchBuffer)-1, "isDefined() - name too long");
  1963. dMemcpy(scratchBuffer, name, len+1);
  1964. char * token = dStrtok(scratchBuffer, ".");
  1965. if (!token || token[0] == '\0')
  1966. return false;
  1967. StringTableEntry objName = StringTable->insert(token);
  1968. // Attempt to find the object
  1969. SimObject * obj = Sim::findObject(objName);
  1970. // If we didn't find the object then we can safely
  1971. // assume that the field variable doesn't exist
  1972. if (!obj)
  1973. return false;
  1974. // Get the name of the field
  1975. token = dStrtok(0, ".\0");
  1976. if (!token)
  1977. return false;
  1978. while (token != NULL)
  1979. {
  1980. StringTableEntry valName = StringTable->insert(token);
  1981. // Store these so we can restore them after we search for the variable
  1982. bool saveModStatic = obj->canModStaticFields();
  1983. bool saveModDyn = obj->canModDynamicFields();
  1984. // Set this so that we can search both static and dynamic fields
  1985. obj->setModStaticFields(true);
  1986. obj->setModDynamicFields(true);
  1987. const char* value = obj->getDataField(valName, 0);
  1988. // Restore our mod flags to be safe
  1989. obj->setModStaticFields(saveModStatic);
  1990. obj->setModDynamicFields(saveModDyn);
  1991. if (!value)
  1992. {
  1993. obj->setDataField(valName, 0, varValue);
  1994. return false;
  1995. }
  1996. else
  1997. {
  1998. // See if we are field on a field
  1999. token = dStrtok(0, ".\0");
  2000. if (token)
  2001. {
  2002. // The previous field must be an object
  2003. obj = Sim::findObject(value);
  2004. if (!obj)
  2005. return false;
  2006. }
  2007. else
  2008. {
  2009. if (dStrlen(value) > 0)
  2010. return true;
  2011. else if (!dStrIsEmpty(varValue))
  2012. {
  2013. obj->setDataField(valName, 0, varValue);
  2014. }
  2015. }
  2016. }
  2017. }
  2018. }
  2019. else if (name[0] == '%')
  2020. {
  2021. // Look up a local variable
  2022. if( gEvalState.getStackDepth() > 0 )
  2023. {
  2024. Dictionary::Entry* ent = gEvalState.getCurrentFrame().lookup(name);
  2025. if (ent)
  2026. return true;
  2027. else if (!dStrIsEmpty(varValue))
  2028. {
  2029. gEvalState.getCurrentFrame().setVariable(name, varValue);
  2030. }
  2031. }
  2032. else
  2033. Con::errorf("%s() - no local variable frame.", __FUNCTION__);
  2034. }
  2035. else if (name[0] == '$')
  2036. {
  2037. // Look up a global value
  2038. Dictionary::Entry* ent = gEvalState.globalVars.lookup(name);
  2039. if (ent)
  2040. return true;
  2041. else if (!dStrIsEmpty(varValue))
  2042. {
  2043. gEvalState.globalVars.setVariable(name, varValue);
  2044. }
  2045. }
  2046. else
  2047. {
  2048. // Is it an object?
  2049. if (dStrcmp(varName, "0") && dStrcmp(varName, "") && (Sim::findObject(varName) != NULL))
  2050. return true;
  2051. else if (!dStrIsEmpty(varValue))
  2052. {
  2053. Con::errorf("%s() - can't assign a value to a variable of the form \"%s\"", __FUNCTION__, varValue);
  2054. }
  2055. }
  2056. return false;
  2057. }
  2058. //-----------------------------------------------------------------------------
  2059. DefineConsoleFunction( isCurrentScriptToolScript, bool, (), , "()"
  2060. "Returns true if the calling script is a tools script.\n"
  2061. "@hide")
  2062. {
  2063. return Con::isCurrentScriptToolScript();
  2064. }
  2065. DefineConsoleFunction( getModNameFromPath, const char *, ( const char* path ), , "(string path)"
  2066. "@brief Attempts to extract a mod directory from path. Returns empty string on failure.\n\n"
  2067. "@param File path of mod folder\n"
  2068. "@note This is no longer relevant in Torque 3D (which does not use mod folders), should be deprecated\n"
  2069. "@internal")
  2070. {
  2071. StringTableEntry modPath = Con::getModNameFromPath(path);
  2072. return modPath ? modPath : "";
  2073. }
  2074. //-----------------------------------------------------------------------------
  2075. DefineConsoleFunction( pushInstantGroup, void, ( String group ),("") , "([group])"
  2076. "@brief Pushes the current $instantGroup on a stack "
  2077. "and sets it to the given value (or clears it).\n\n"
  2078. "@note Currently only used for editors\n"
  2079. "@ingroup Editors\n"
  2080. "@internal")
  2081. {
  2082. if( group.size() > 0 )
  2083. Con::pushInstantGroup( group );
  2084. else
  2085. Con::pushInstantGroup();
  2086. }
  2087. DefineConsoleFunction( popInstantGroup, void, (), , "()"
  2088. "@brief Pop and restore the last setting of $instantGroup off the stack.\n\n"
  2089. "@note Currently only used for editors\n\n"
  2090. "@ingroup Editors\n"
  2091. "@internal")
  2092. {
  2093. Con::popInstantGroup();
  2094. }
  2095. //-----------------------------------------------------------------------------
  2096. DefineConsoleFunction( getPrefsPath, const char *, ( const char* relativeFileName ), (""), "([relativeFileName])"
  2097. "@note Appears to be useless in Torque 3D, should be deprecated\n"
  2098. "@internal")
  2099. {
  2100. const char *filename = Platform::getPrefsPath(relativeFileName);
  2101. if(filename == NULL || *filename == 0)
  2102. return "";
  2103. return filename;
  2104. }
  2105. //-----------------------------------------------------------------------------
  2106. ConsoleFunction( execPrefs, bool, 2, 4, "( string relativeFileName, bool noCalls=false, bool journalScript=false )"
  2107. "@brief Manually execute a special script file that contains game or editor preferences\n\n"
  2108. "@param relativeFileName Name and path to file from project folder\n"
  2109. "@param noCalls Deprecated\n"
  2110. "@param journalScript Deprecated\n"
  2111. "@return True if script was successfully executed\n"
  2112. "@note Appears to be useless in Torque 3D, should be deprecated\n"
  2113. "@ingroup Scripting")
  2114. {
  2115. const char *filename = Platform::getPrefsPath(argv[1]);
  2116. if(filename == NULL || *filename == 0)
  2117. return false;
  2118. // Scripts do this a lot, so we may as well help them out
  2119. if(! Platform::isFile(filename) && ! Torque::FS::IsFile(filename))
  2120. return true;
  2121. argv[0] = "exec";
  2122. argv[1] = filename;
  2123. return dAtob(Con::execute(argc, argv));
  2124. }
  2125. //-----------------------------------------------------------------------------
  2126. DefineConsoleFunction( export, void, ( const char* pattern, const char* filename, bool append ), ( "", false ),
  2127. "Write out the definitions of all global variables matching the given name @a pattern.\n"
  2128. "If @a fileName is not \"\", the variable definitions are written to the specified file. Otherwise the "
  2129. "definitions will be printed to the console.\n\n"
  2130. "The output are valid TorqueScript statements that can be executed to restore the global variable "
  2131. "values.\n\n"
  2132. "@param pattern A global variable name pattern. Must begin with '$'.\n"
  2133. "@param filename %Path of the file to which to write the definitions or \"\" to write the definitions "
  2134. "to the console.\n"
  2135. "@param append If true and @a fileName is not \"\", then the definitions are appended to the specified file. "
  2136. "Otherwise existing contents of the file (if any) will be overwritten.\n\n"
  2137. "@tsexample\n"
  2138. "// Write out all preference variables to a prefs.cs file.\n"
  2139. "export( \"$prefs::*\", \"prefs.cs\" );\n"
  2140. "@endtsexample\n\n"
  2141. "@ingroup Scripting" )
  2142. {
  2143. if( filename && filename[ 0 ] )
  2144. {
  2145. #ifndef TORQUE2D_TOOLS_FIXME
  2146. if(Con::expandScriptFilename(scriptFilenameBuffer, sizeof(scriptFilenameBuffer), filename))
  2147. filename = scriptFilenameBuffer;
  2148. #else
  2149. filename = Platform::getPrefsPath( filename );
  2150. if(filename == NULL || *filename == 0)
  2151. return;
  2152. #endif
  2153. }
  2154. else
  2155. filename = NULL;
  2156. gEvalState.globalVars.exportVariables( pattern, filename, append );
  2157. }
  2158. //-----------------------------------------------------------------------------
  2159. DefineEngineFunction( deleteVariables, void, ( const char* pattern ),,
  2160. "Undefine all global variables matching the given name @a pattern.\n"
  2161. "@param pattern A global variable name pattern. Must begin with '$'.\n"
  2162. "@tsexample\n"
  2163. "// Define a global variable in the \"My\" namespace.\n"
  2164. "$My::Variable = \"value\";\n\n"
  2165. "// Undefine all variable in the \"My\" namespace.\n"
  2166. "deleteVariables( \"$My::*\" );\n"
  2167. "@endtsexample\n\n"
  2168. "@see strIsMatchExpr\n"
  2169. "@ingroup Scripting" )
  2170. {
  2171. gEvalState.globalVars.deleteVariables( pattern );
  2172. }
  2173. //-----------------------------------------------------------------------------
  2174. DefineConsoleFunction( trace, void, ( bool enable ), ( true ),
  2175. "Enable or disable tracing in the script code VM.\n\n"
  2176. "When enabled, the script code runtime will trace the invocation and returns "
  2177. "from all functions that are called and log them to the console. This is helpful in "
  2178. "observing the flow of the script program.\n\n"
  2179. "@param enable New setting for script trace execution, on by default.\n"
  2180. "@ingroup Debugging" )
  2181. {
  2182. gEvalState.traceOn = enable;
  2183. Con::printf( "Console trace %s", gEvalState.traceOn ? "enabled." : "disabled." );
  2184. }
  2185. //-----------------------------------------------------------------------------
  2186. #if defined(TORQUE_DEBUG) || !defined(TORQUE_SHIPPING)
  2187. DefineConsoleFunction( debug, void, (),,
  2188. "Drops the engine into the native C++ debugger.\n\n"
  2189. "This function triggers a debug break and drops the process into the IDE's debugger. If the process is not "
  2190. "running with a debugger attached it will generate a runtime error on most platforms.\n\n"
  2191. "@note This function is not available in shipping builds."
  2192. "@ingroup Debugging" )
  2193. {
  2194. Platform::debugBreak();
  2195. }
  2196. #endif
  2197. //-----------------------------------------------------------------------------
  2198. DefineEngineFunction( isShippingBuild, bool, (),,
  2199. "Test whether the engine has been compiled with TORQUE_SHIPPING, i.e. in a form meant for final release.\n\n"
  2200. "@return True if this is a shipping build; false otherwise.\n\n"
  2201. "@ingroup Platform" )
  2202. {
  2203. #ifdef TORQUE_SHIPPING
  2204. return true;
  2205. #else
  2206. return false;
  2207. #endif
  2208. }
  2209. //-----------------------------------------------------------------------------
  2210. DefineEngineFunction( isDebugBuild, bool, (),,
  2211. "Test whether the engine has been compiled with TORQUE_DEBUG, i.e. if it includes debugging functionality.\n\n"
  2212. "@return True if this is a debug build; false otherwise.\n\n"
  2213. "@ingroup Platform" )
  2214. {
  2215. #ifdef TORQUE_DEBUG
  2216. return true;
  2217. #else
  2218. return false;
  2219. #endif
  2220. }
  2221. //-----------------------------------------------------------------------------
  2222. DefineEngineFunction( isToolBuild, bool, (),,
  2223. "Test whether the engine has been compiled with TORQUE_TOOLS, i.e. if it includes tool-related functionality.\n\n"
  2224. "@return True if this is a tool build; false otherwise.\n\n"
  2225. "@ingroup Platform" )
  2226. {
  2227. #ifdef TORQUE_TOOLS
  2228. return true;
  2229. #else
  2230. return false;
  2231. #endif
  2232. }