consoleFunctions.cpp 109 KB

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