consoleFunctions.cpp 93 KB

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