console.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624
  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 "platform/platformTLS.h"
  24. #include "platform/threads/thread.h"
  25. #include "console/console.h"
  26. #include "console/consoleInternal.h"
  27. #include "console/consoleObject.h"
  28. #include "console/consoleParser.h"
  29. #include "core/stream/fileStream.h"
  30. #include "console/ast.h"
  31. #include "core/tAlgorithm.h"
  32. #include "console/consoleTypes.h"
  33. #include "console/telnetDebugger.h"
  34. #include "console/simBase.h"
  35. #include "console/compiler.h"
  36. #include "console/stringStack.h"
  37. #include "console/ICallMethod.h"
  38. #include "console/engineAPI.h"
  39. #include <stdarg.h>
  40. #include "platform/threads/mutex.h"
  41. #include "core/util/journal/journal.h"
  42. #include "cinterface/cinterface.h"
  43. #include "console/consoleValueStack.h"
  44. extern StringStack STR;
  45. extern ConsoleValueStack<4096> gCallStack;
  46. char ConsoleValue::sConversionBuffer[ConversionBufferSize];
  47. void ConsoleValue::init()
  48. {
  49. dMemset(sConversionBuffer, '\0', ConversionBufferSize);
  50. }
  51. char* ConsoleValue::convertToBuffer() const
  52. {
  53. if (type == ConsoleValueType::cvFloat)
  54. dSprintf(sConversionBuffer, ConversionBufferSize, "%.9g", f);
  55. else
  56. dSprintf(sConversionBuffer, ConversionBufferSize, "%lld", i);
  57. return sConversionBuffer;
  58. }
  59. const char* ConsoleValue::getConsoleData() const
  60. {
  61. return Con::getData(type, ct->dataPtr, 0, ct->enumTable);
  62. }
  63. ConsoleDocFragment* ConsoleDocFragment::smFirst;
  64. ExprEvalState gEvalState;
  65. StmtNode *gStatementList;
  66. StmtNode *gAnonFunctionList;
  67. U32 gAnonFunctionID = 0;
  68. ConsoleConstructor *ConsoleConstructor::mFirst = NULL;
  69. bool gWarnUndefinedScriptVariables;
  70. static char scratchBuffer[4096];
  71. CON_DECLARE_PARSER(CMD);
  72. static const char * prependDollar ( const char * name )
  73. {
  74. if(name[0] != '$')
  75. {
  76. S32 len = dStrlen(name);
  77. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  78. scratchBuffer[0] = '$';
  79. dMemcpy(scratchBuffer + 1, name, len + 1);
  80. name = scratchBuffer;
  81. }
  82. return name;
  83. }
  84. static const char * prependPercent ( const char * name )
  85. {
  86. if(name[0] != '%')
  87. {
  88. S32 len = dStrlen(name);
  89. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  90. scratchBuffer[0] = '%';
  91. dMemcpy(scratchBuffer + 1, name, len + 1);
  92. name = scratchBuffer;
  93. }
  94. return name;
  95. }
  96. //--------------------------------------
  97. void ConsoleConstructor::init( const char *cName, const char *fName, const char *usg, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  98. {
  99. mMina = minArgs;
  100. mMaxa = maxArgs;
  101. mFuncName = fName;
  102. mUsage = usg;
  103. mClassName = cName;
  104. mSC = 0; mFC = 0; mVC = 0; mBC = 0; mIC = 0;
  105. mCallback = mGroup = false;
  106. mNext = mFirst;
  107. mNS = false;
  108. mFirst = this;
  109. mToolOnly = isToolOnly;
  110. mHeader = header;
  111. }
  112. void ConsoleConstructor::setup()
  113. {
  114. for(ConsoleConstructor *walk = mFirst; walk; walk = walk->mNext)
  115. {
  116. #ifdef TORQUE_DEBUG
  117. walk->validate();
  118. #endif
  119. if( walk->mSC )
  120. Con::addCommand( walk->mClassName, walk->mFuncName, walk->mSC, walk->mUsage, walk->mMina, walk->mMaxa, walk->mToolOnly, walk->mHeader);
  121. else if( walk->mIC )
  122. Con::addCommand( walk->mClassName, walk->mFuncName, walk->mIC, walk->mUsage, walk->mMina, walk->mMaxa, walk->mToolOnly, walk->mHeader);
  123. else if( walk->mFC )
  124. Con::addCommand( walk->mClassName, walk->mFuncName, walk->mFC, walk->mUsage, walk->mMina, walk->mMaxa, walk->mToolOnly, walk->mHeader);
  125. else if( walk->mVC )
  126. Con::addCommand( walk->mClassName, walk->mFuncName, walk->mVC, walk->mUsage, walk->mMina, walk->mMaxa, walk->mToolOnly, walk->mHeader);
  127. else if( walk->mBC )
  128. Con::addCommand( walk->mClassName, walk->mFuncName, walk->mBC, walk->mUsage, walk->mMina, walk->mMaxa, walk->mToolOnly, walk->mHeader);
  129. else if( walk->mGroup )
  130. Con::markCommandGroup( walk->mClassName, walk->mFuncName, walk->mUsage);
  131. else if( walk->mClassName)
  132. Con::noteScriptCallback( walk->mClassName, walk->mFuncName, walk->mUsage, walk->mHeader);
  133. else if( walk->mNS )
  134. {
  135. Namespace* ns = Namespace::find( StringTable->insert( walk->mClassName) );
  136. if( ns )
  137. ns->mUsage = walk->mUsage;
  138. }
  139. else
  140. {
  141. AssertISV( false, "Found a ConsoleConstructor with an indeterminate type!" );
  142. }
  143. }
  144. }
  145. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, StringCallback sfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  146. {
  147. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  148. mSC = sfunc;
  149. }
  150. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, IntCallback ifunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  151. {
  152. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  153. mIC = ifunc;
  154. }
  155. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, FloatCallback ffunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  156. {
  157. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  158. mFC = ffunc;
  159. }
  160. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, VoidCallback vfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  161. {
  162. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  163. mVC = vfunc;
  164. }
  165. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, BoolCallback bfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  166. {
  167. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  168. mBC = bfunc;
  169. }
  170. ConsoleConstructor::ConsoleConstructor(const char* className, const char* groupName, const char* aUsage)
  171. {
  172. init(className, groupName, mUsage, -1, -2);
  173. mGroup = true;
  174. // Somewhere, the entry list is getting flipped, partially.
  175. // so we have to do tricks to deal with making sure usage
  176. // is properly populated.
  177. // This is probably redundant.
  178. static char * lastUsage = NULL;
  179. if(aUsage)
  180. lastUsage = (char *)aUsage;
  181. mUsage = lastUsage;
  182. }
  183. ConsoleConstructor::ConsoleConstructor(const char *className, const char *callbackName, const char *usage, ConsoleFunctionHeader* header )
  184. {
  185. init( className, callbackName, usage, -2, -3, false, header );
  186. mCallback = true;
  187. mNS = true;
  188. }
  189. void ConsoleConstructor::validate()
  190. {
  191. #ifdef TORQUE_DEBUG
  192. // Don't do the following check if we're not a method/func.
  193. if(mGroup)
  194. return;
  195. // In debug, walk the list and make sure this isn't a duplicate.
  196. for(ConsoleConstructor *walk = mFirst; walk; walk = walk->mNext)
  197. {
  198. // Skip mismatching func/method names.
  199. if(dStricmp(walk->mFuncName, mFuncName))
  200. continue;
  201. // Don't compare functions with methods or vice versa.
  202. if(bool(mClassName) != bool(walk->mClassName))
  203. continue;
  204. // Skip mismatching classnames, if they're present.
  205. if(mClassName && walk->mClassName && dStricmp(walk->mClassName, mClassName))
  206. continue;
  207. // If we encounter ourselves, stop searching; this prevents duplicate
  208. // firing of the assert, instead only firing for the latter encountered
  209. // entry.
  210. if(this == walk)
  211. break;
  212. // Match!
  213. if(mClassName)
  214. {
  215. AssertISV(false, avar("ConsoleConstructor::setup - ConsoleMethod '%s::%s' collides with another of the same name.", mClassName, mFuncName));
  216. }
  217. else
  218. {
  219. AssertISV(false, avar("ConsoleConstructor::setup - ConsoleFunction '%s' collides with another of the same name.", mFuncName));
  220. }
  221. }
  222. #endif
  223. }
  224. // We comment out the implementation of the Con namespace when doxygenizing because
  225. // otherwise Doxygen decides to ignore our docs in console.h
  226. #ifndef DOXYGENIZING
  227. namespace Con
  228. {
  229. static Vector<ConsumerCallback> gConsumers(__FILE__, __LINE__);
  230. static Vector< String > sInstantGroupStack( __FILE__, __LINE__ );
  231. static DataChunker consoleLogChunker;
  232. static Vector<ConsoleLogEntry> consoleLog(__FILE__, __LINE__);
  233. static bool consoleLogLocked;
  234. static bool logBufferEnabled=true;
  235. static S32 printLevel = 10;
  236. static FileStream consoleLogFile;
  237. static const char *defLogFileName = "console.log";
  238. static S32 consoleLogMode = 0;
  239. static bool active = false;
  240. static bool newLogFile;
  241. static const char *logFileName;
  242. static const S32 MaxCompletionBufferSize = 4096;
  243. static char completionBuffer[MaxCompletionBufferSize];
  244. static char tabBuffer[MaxCompletionBufferSize] = {0};
  245. static SimObjectPtr<SimObject> tabObject;
  246. static U32 completionBaseStart;
  247. static U32 completionBaseLen;
  248. String gInstantGroup;
  249. Con::ConsoleInputEvent smConsoleInput;
  250. /// Current script file name and root, these are registered as
  251. /// console variables.
  252. /// @{
  253. ///
  254. StringTableEntry gCurrentFile;
  255. StringTableEntry gCurrentRoot;
  256. /// @}
  257. bool alwaysUseDebugOutput = true;
  258. bool useTimestamp = false;
  259. bool useRealTimestamp = false;
  260. ConsoleFunctionGroupBegin( Clipboard, "Miscellaneous functions to control the clipboard and clear the console.");
  261. DefineEngineFunction( cls, void, (), , "()"
  262. "@brief Clears the console output.\n\n"
  263. "@ingroup Console")
  264. {
  265. if(consoleLogLocked)
  266. return;
  267. consoleLogChunker.freeBlocks();
  268. consoleLog.setSize(0);
  269. };
  270. DefineEngineFunction( getClipboard, const char*, (), , "()"
  271. "@brief Get text from the clipboard.\n\n"
  272. "@internal")
  273. {
  274. return Platform::getClipboard();
  275. };
  276. DefineEngineFunction( setClipboard, bool, (const char* text), , "(string text)"
  277. "@brief Set the system clipboard.\n\n"
  278. "@internal")
  279. {
  280. return Platform::setClipboard(text);
  281. };
  282. ConsoleFunctionGroupEnd( Clipboard );
  283. void postConsoleInput( RawData data );
  284. void init()
  285. {
  286. AssertFatal(active == false, "Con::init should only be called once.");
  287. // Set up general init values.
  288. active = true;
  289. logFileName = NULL;
  290. newLogFile = true;
  291. gWarnUndefinedScriptVariables = false;
  292. // Initialize subsystems.
  293. Namespace::init();
  294. ConsoleConstructor::setup();
  295. // Set up the parser(s)
  296. CON_ADD_PARSER(CMD, TORQUE_SCRIPT_EXTENSION, true); // TorqueScript
  297. // Setup the console types.
  298. ConsoleBaseType::initialize();
  299. ConsoleValue::init();
  300. // And finally, the ACR...
  301. AbstractClassRep::initialize();
  302. // Variables
  303. setVariable("Con::prompt", "% ");
  304. addVariable("Con::logBufferEnabled", TypeBool, &logBufferEnabled, "If true, the log buffer will be enabled.\n"
  305. "@ingroup Console\n");
  306. addVariable("Con::printLevel", TypeS32, &printLevel,
  307. "@brief This is deprecated.\n\n"
  308. "It is no longer in use and does nothing.\n"
  309. "@ingroup Console\n");
  310. addVariable("Con::warnUndefinedVariables", TypeBool, &gWarnUndefinedScriptVariables, "If true, a warning will be displayed in the console whenever a undefined variable is used in script.\n"
  311. "@ingroup Console\n");
  312. addVariable( "instantGroup", TypeRealString, &gInstantGroup, "The group that objects will be added to when they are created.\n"
  313. "@ingroup Console\n");
  314. // Current script file name and root
  315. addVariable( "Con::File", TypeString, &gCurrentFile, "The currently executing script file.\n"
  316. "@ingroup FileSystem\n");
  317. addVariable( "Con::Root", TypeString, &gCurrentRoot, "The mod folder for the currently executing script file.\n"
  318. "@ingroup FileSystem\n" );
  319. // alwaysUseDebugOutput determines whether to send output to the platform's
  320. // "debug" system. see winConsole for an example.
  321. // in ship builds we don't expose this variable to script
  322. // and we set it to false by default (don't want to provide more information
  323. // to potential hackers). platform code should also ifdef out the code that
  324. // pays attention to this in ship builds (see winConsole.cpp)
  325. // note that enabling this can slow down your game
  326. // if you are running from the debugger and printing a lot of console messages.
  327. #ifndef TORQUE_SHIPPING
  328. addVariable("Con::alwaysUseDebugOutput", TypeBool, &alwaysUseDebugOutput,
  329. "@brief Determines whether to send output to the platform's \"debug\" system.\n\n"
  330. "@note This is disabled in shipping builds.\n"
  331. "@ingroup Console");
  332. #else
  333. alwaysUseDebugOutput = false;
  334. #endif
  335. // controls whether a timestamp is prepended to every console message
  336. addVariable("Con::useTimestamp", TypeBool, &useTimestamp, "If true a timestamp is prepended to every console message.\n"
  337. "@ingroup Console\n");
  338. // controls whether a real date and time is prepended to every console message
  339. addVariable("Con::useRealTimestamp", TypeBool, &useRealTimestamp, "If true a date and time will be prepended to every console message.\n"
  340. "@ingroup Console\n");
  341. // Plug us into the journaled console input signal.
  342. smConsoleInput.notify(postConsoleInput);
  343. }
  344. //--------------------------------------
  345. void shutdown()
  346. {
  347. AssertFatal(active == true, "Con::shutdown should only be called once.");
  348. active = false;
  349. smConsoleInput.remove(postConsoleInput);
  350. consoleLogFile.close();
  351. Namespace::shutdown();
  352. AbstractClassRep::shutdown();
  353. Compiler::freeConsoleParserList();
  354. }
  355. bool isActive()
  356. {
  357. return active;
  358. }
  359. bool isMainThread()
  360. {
  361. #ifdef TORQUE_MULTITHREAD
  362. return ThreadManager::isMainThread();
  363. #else
  364. // If we're single threaded we're always in the main thread.
  365. return true;
  366. #endif
  367. }
  368. //--------------------------------------
  369. void getLockLog(ConsoleLogEntry *&log, U32 &size)
  370. {
  371. consoleLogLocked = true;
  372. log = consoleLog.address();
  373. size = consoleLog.size();
  374. }
  375. void unlockLog()
  376. {
  377. consoleLogLocked = false;
  378. }
  379. U32 tabComplete(char* inputBuffer, U32 cursorPos, U32 maxResultLength, bool forwardTab)
  380. {
  381. // Check for null input.
  382. if (!inputBuffer[0])
  383. {
  384. return cursorPos;
  385. }
  386. // Cap the max result length.
  387. if (maxResultLength > MaxCompletionBufferSize)
  388. {
  389. maxResultLength = MaxCompletionBufferSize;
  390. }
  391. // See if this is the same partial text as last checked.
  392. if (String::compare(tabBuffer, inputBuffer))
  393. {
  394. // If not...
  395. // Save it for checking next time.
  396. dStrcpy(tabBuffer, inputBuffer, MaxCompletionBufferSize);
  397. // Scan backward from the cursor position to find the base to complete from.
  398. S32 p = cursorPos;
  399. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '.') && (inputBuffer[p - 1] != '('))
  400. {
  401. p--;
  402. }
  403. completionBaseStart = p;
  404. completionBaseLen = cursorPos - p;
  405. // Is this function being invoked on an object?
  406. if (inputBuffer[p - 1] == '.')
  407. {
  408. // If so...
  409. if (p <= 1)
  410. {
  411. // Bail if no object identifier.
  412. return cursorPos;
  413. }
  414. // Find the object identifier.
  415. S32 objLast = --p;
  416. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '('))
  417. {
  418. p--;
  419. }
  420. if (objLast == p)
  421. {
  422. // Bail if no object identifier.
  423. return cursorPos;
  424. }
  425. // Look up the object identifier.
  426. dStrncpy(completionBuffer, inputBuffer + p, objLast - p);
  427. completionBuffer[objLast - p] = 0;
  428. tabObject = Sim::findObject(completionBuffer);
  429. if (tabObject == NULL)
  430. {
  431. // Bail if not found.
  432. return cursorPos;
  433. }
  434. }
  435. else
  436. {
  437. // Not invoked on an object; we'll use the global namespace.
  438. tabObject = 0;
  439. }
  440. }
  441. // Chop off the input text at the cursor position.
  442. inputBuffer[cursorPos] = 0;
  443. // Try to find a completion in the appropriate namespace.
  444. const char *newText;
  445. if (tabObject != 0)
  446. {
  447. newText = tabObject->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  448. }
  449. else
  450. {
  451. // In the global namespace, we can complete on global vars as well as functions.
  452. if (inputBuffer[completionBaseStart] == '$')
  453. {
  454. newText = gEvalState.globalVars.tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  455. }
  456. else
  457. {
  458. newText = Namespace::global()->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  459. }
  460. }
  461. if (newText)
  462. {
  463. // If we got something, append it to the input text.
  464. S32 len = dStrlen(newText);
  465. if (len + completionBaseStart > maxResultLength)
  466. {
  467. len = maxResultLength - completionBaseStart;
  468. }
  469. dStrncpy(inputBuffer + completionBaseStart, newText, len);
  470. inputBuffer[completionBaseStart + len] = 0;
  471. // And set the cursor after it.
  472. cursorPos = completionBaseStart + len;
  473. }
  474. // Save the modified input buffer for checking next time.
  475. dStrcpy(tabBuffer, inputBuffer, MaxCompletionBufferSize);
  476. // Return the new (maybe) cursor position.
  477. return cursorPos;
  478. }
  479. //------------------------------------------------------------------------------
  480. static void log(const char *string)
  481. {
  482. // Bail if we ain't logging.
  483. if (!consoleLogMode)
  484. {
  485. return;
  486. }
  487. // In mode 1, we open, append, close on each log write.
  488. if ((consoleLogMode & 0x3) == 1)
  489. {
  490. consoleLogFile.open(defLogFileName, Torque::FS::File::ReadWrite);
  491. }
  492. // Write to the log if its status is hunky-dory.
  493. if ((consoleLogFile.getStatus() == Stream::Ok) || (consoleLogFile.getStatus() == Stream::EOS))
  494. {
  495. consoleLogFile.setPosition(consoleLogFile.getStreamSize());
  496. // If this is the first write...
  497. if (newLogFile)
  498. {
  499. // Make a header.
  500. Platform::LocalTime lt;
  501. Platform::getLocalTime(lt);
  502. char buffer[128];
  503. dSprintf(buffer, sizeof(buffer), "//-------------------------- %d/%d/%d -- %02d:%02d:%02d -----\r\n",
  504. lt.month + 1,
  505. lt.monthday,
  506. lt.year + 1900,
  507. lt.hour,
  508. lt.min,
  509. lt.sec);
  510. consoleLogFile.write(dStrlen(buffer), buffer);
  511. newLogFile = false;
  512. if (consoleLogMode & 0x4)
  513. {
  514. // Dump anything that has been printed to the console so far.
  515. consoleLogMode -= 0x4;
  516. U32 size, line;
  517. ConsoleLogEntry *log;
  518. getLockLog(log, size);
  519. for (line = 0; line < size; line++)
  520. {
  521. consoleLogFile.write(dStrlen(log[line].mString), log[line].mString);
  522. consoleLogFile.write(2, "\r\n");
  523. }
  524. unlockLog();
  525. }
  526. }
  527. // Now write what we came here to write.
  528. consoleLogFile.write(dStrlen(string), string);
  529. consoleLogFile.write(2, "\r\n");
  530. }
  531. if ((consoleLogMode & 0x3) == 1)
  532. {
  533. consoleLogFile.close();
  534. }
  535. }
  536. //------------------------------------------------------------------------------
  537. static void _printf(ConsoleLogEntry::Level level, ConsoleLogEntry::Type type, const char* fmt, va_list argptr)
  538. {
  539. if (!active)
  540. return;
  541. Con::active = false;
  542. char buffer[8192];
  543. U32 offset = 0;
  544. if( gEvalState.traceOn && gEvalState.getStackDepth() > 0 )
  545. {
  546. offset = gEvalState.getStackDepth() * 3;
  547. for(U32 i = 0; i < offset; i++)
  548. buffer[i] = ' ';
  549. }
  550. if (useRealTimestamp)
  551. {
  552. Platform::LocalTime lt;
  553. Platform::getLocalTime(lt);
  554. offset += dSprintf(buffer + offset, sizeof(buffer) - offset, "[%d-%d-%d %02d:%02d:%02d]", lt.year + 1900, lt.month + 1, lt.monthday, lt.hour, lt.min, lt.sec);
  555. }
  556. if (useTimestamp)
  557. {
  558. static U32 startTime = Platform::getRealMilliseconds();
  559. U32 curTime = Platform::getRealMilliseconds() - startTime;
  560. offset += dSprintf(buffer + offset, sizeof(buffer) - offset, "[+%4d.%03d]", U32(curTime * 0.001), curTime % 1000);
  561. }
  562. if (useTimestamp || useRealTimestamp) {
  563. offset += dSprintf(buffer + offset, sizeof(buffer) - offset, " ");
  564. }
  565. dVsprintf(buffer + offset, sizeof(buffer) - offset, fmt, argptr);
  566. for(S32 i = 0; i < gConsumers.size(); i++)
  567. gConsumers[i](level, buffer);
  568. if(logBufferEnabled || consoleLogMode)
  569. {
  570. char *pos = buffer;
  571. while(*pos)
  572. {
  573. if(*pos == '\t')
  574. *pos = '^';
  575. pos++;
  576. }
  577. pos = buffer;
  578. for(;;)
  579. {
  580. char *eofPos = dStrchr(pos, '\n');
  581. if(eofPos)
  582. *eofPos = 0;
  583. log(pos);
  584. if(logBufferEnabled && !consoleLogLocked)
  585. {
  586. ConsoleLogEntry entry;
  587. entry.mLevel = level;
  588. entry.mType = type;
  589. #ifndef TORQUE_SHIPPING // this is equivalent to a memory leak, turn it off in ship build
  590. dsize_t logStringLen = dStrlen(pos) + 1;
  591. entry.mString = (const char *)consoleLogChunker.alloc(logStringLen);
  592. dStrcpy(const_cast<char*>(entry.mString), pos, logStringLen);
  593. // This prevents infinite recursion if the console itself needs to
  594. // re-allocate memory to accommodate the new console log entry, and
  595. // LOG_PAGE_ALLOCS is defined. It is kind of a dirty hack, but the
  596. // uses for LOG_PAGE_ALLOCS are limited, and it is not worth writing
  597. // a lot of special case code to support this situation. -patw
  598. const bool save = Con::active;
  599. Con::active = false;
  600. consoleLog.push_back(entry);
  601. Con::active = save;
  602. #endif
  603. }
  604. if(!eofPos)
  605. break;
  606. pos = eofPos + 1;
  607. }
  608. }
  609. Con::active = true;
  610. }
  611. //------------------------------------------------------------------------------
  612. void printf(const char* fmt,...)
  613. {
  614. va_list argptr;
  615. va_start(argptr, fmt);
  616. _printf(ConsoleLogEntry::Normal, ConsoleLogEntry::General, fmt, argptr);
  617. va_end(argptr);
  618. }
  619. void warnf(ConsoleLogEntry::Type type, const char* fmt,...)
  620. {
  621. va_list argptr;
  622. va_start(argptr, fmt);
  623. _printf(ConsoleLogEntry::Warning, type, fmt, argptr);
  624. va_end(argptr);
  625. }
  626. void errorf(ConsoleLogEntry::Type type, const char* fmt,...)
  627. {
  628. va_list argptr;
  629. va_start(argptr, fmt);
  630. _printf(ConsoleLogEntry::Error, type, fmt, argptr);
  631. va_end(argptr);
  632. }
  633. void warnf(const char* fmt,...)
  634. {
  635. va_list argptr;
  636. va_start(argptr, fmt);
  637. _printf(ConsoleLogEntry::Warning, ConsoleLogEntry::General, fmt, argptr);
  638. va_end(argptr);
  639. }
  640. void errorf(const char* fmt,...)
  641. {
  642. va_list argptr;
  643. va_start(argptr, fmt);
  644. _printf(ConsoleLogEntry::Error, ConsoleLogEntry::General, fmt, argptr);
  645. va_end(argptr);
  646. }
  647. //---------------------------------------------------------------------------
  648. bool getVariableObjectField(const char *name, SimObject **object, const char **field)
  649. {
  650. // get the field info from the object..
  651. const char *dot = dStrchr(name, '.');
  652. if(name[0] != '$' && dot)
  653. {
  654. S32 len = dStrlen(name);
  655. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - name too long");
  656. dMemcpy(scratchBuffer, name, len+1);
  657. char * token = dStrtok(scratchBuffer, ".");
  658. SimObject * obj = Sim::findObject(token);
  659. if(!obj)
  660. return false;
  661. token = dStrtok(0, ".\0");
  662. if(!token)
  663. return false;
  664. while(token != NULL)
  665. {
  666. const char * val = obj->getDataField(StringTable->insert(token), 0);
  667. if(!val)
  668. return false;
  669. char *fieldToken = token;
  670. token = dStrtok(0, ".\0");
  671. if(token)
  672. {
  673. obj = Sim::findObject(token);
  674. if(!obj)
  675. return false;
  676. }
  677. else
  678. {
  679. *object = obj;
  680. *field = fieldToken;
  681. return true;
  682. }
  683. }
  684. }
  685. return false;
  686. }
  687. Dictionary::Entry *getLocalVariableEntry(const char *name)
  688. {
  689. name = prependPercent(name);
  690. return gEvalState.getCurrentFrame().lookup(StringTable->insert(name));
  691. }
  692. Dictionary::Entry *getVariableEntry(const char *name)
  693. {
  694. name = prependDollar(name);
  695. return gEvalState.globalVars.lookup(StringTable->insert(name));
  696. }
  697. Dictionary::Entry *addVariableEntry(const char *name)
  698. {
  699. name = prependDollar(name);
  700. return gEvalState.globalVars.add(StringTable->insert(name));
  701. }
  702. Dictionary::Entry *getAddVariableEntry(const char *name)
  703. {
  704. name = prependDollar(name);
  705. StringTableEntry stName = StringTable->insert(name);
  706. Dictionary::Entry *entry = gEvalState.globalVars.lookup(stName);
  707. if (!entry)
  708. entry = gEvalState.globalVars.add(stName);
  709. return entry;
  710. }
  711. Dictionary::Entry *getAddLocalVariableEntry(const char *name)
  712. {
  713. name = prependPercent(name);
  714. StringTableEntry stName = StringTable->insert(name);
  715. Dictionary::Entry *entry = gEvalState.getCurrentFrame().lookup(stName);
  716. if (!entry)
  717. entry = gEvalState.getCurrentFrame().add(stName);
  718. return entry;
  719. }
  720. void setVariable(const char *name, const char *value)
  721. {
  722. SimObject *obj = NULL;
  723. const char *objField = NULL;
  724. if (getVariableObjectField(name, &obj, &objField))
  725. {
  726. obj->setDataField(StringTable->insert(objField), 0, value);
  727. }
  728. else
  729. {
  730. name = prependDollar(name);
  731. gEvalState.globalVars.setVariable(StringTable->insert(name), value);
  732. }
  733. }
  734. void setLocalVariable(const char *name, const char *value)
  735. {
  736. name = prependPercent(name);
  737. gEvalState.getCurrentFrame().setVariable(StringTable->insert(name), value);
  738. }
  739. void setBoolVariable(const char *varName, bool value)
  740. {
  741. SimObject *obj = NULL;
  742. const char *objField = NULL;
  743. if (getVariableObjectField(varName, &obj, &objField))
  744. {
  745. obj->setDataField(StringTable->insert(objField), 0, value ? "1" : "0");
  746. }
  747. else
  748. {
  749. varName = prependDollar(varName);
  750. Dictionary::Entry *entry = getAddVariableEntry(varName);
  751. entry->setStringValue(value ? "1" : "0");
  752. }
  753. }
  754. void setIntVariable(const char *varName, S32 value)
  755. {
  756. SimObject *obj = NULL;
  757. const char *objField = NULL;
  758. if (getVariableObjectField(varName, &obj, &objField))
  759. {
  760. char varBuffer[32];
  761. dSprintf(varBuffer, sizeof(varBuffer), "%d", value);
  762. obj->setDataField(StringTable->insert(objField), 0, varBuffer);
  763. }
  764. else
  765. {
  766. varName = prependDollar(varName);
  767. Dictionary::Entry *entry = getAddVariableEntry(varName);
  768. entry->setIntValue(value);
  769. }
  770. }
  771. void setFloatVariable(const char *varName, F32 value)
  772. {
  773. SimObject *obj = NULL;
  774. const char *objField = NULL;
  775. if (getVariableObjectField(varName, &obj, &objField))
  776. {
  777. char varBuffer[32];
  778. dSprintf(varBuffer, sizeof(varBuffer), "%g", value);
  779. obj->setDataField(StringTable->insert(objField), 0, varBuffer);
  780. }
  781. else
  782. {
  783. varName = prependDollar(varName);
  784. Dictionary::Entry *entry = getAddVariableEntry(varName);
  785. entry->setFloatValue(value);
  786. }
  787. }
  788. //---------------------------------------------------------------------------
  789. void addConsumer(ConsumerCallback consumer)
  790. {
  791. gConsumers.push_back(consumer);
  792. }
  793. // dhc - found this empty -- trying what I think is a reasonable impl.
  794. void removeConsumer(ConsumerCallback consumer)
  795. {
  796. for(S32 i = 0; i < gConsumers.size(); i++)
  797. {
  798. if (gConsumers[i] == consumer)
  799. {
  800. // remove it from the list.
  801. gConsumers.erase(i);
  802. break;
  803. }
  804. }
  805. }
  806. void stripColorChars(char* line)
  807. {
  808. char* c = line;
  809. char cp = *c;
  810. while (cp)
  811. {
  812. if (cp < 18)
  813. {
  814. // Could be a color control character; let's take a closer look.
  815. if ((cp != 8) && (cp != 9) && (cp != 10) && (cp != 13))
  816. {
  817. // Yep... copy following chars forward over this.
  818. char* cprime = c;
  819. char cpp;
  820. do
  821. {
  822. cpp = *++cprime;
  823. *(cprime - 1) = cpp;
  824. }
  825. while (cpp);
  826. // Back up 1 so we'll check this position again post-copy.
  827. c--;
  828. }
  829. }
  830. cp = *++c;
  831. }
  832. }
  833. //
  834. const char *getObjectTokenField(const char *name)
  835. {
  836. const char *dot = dStrchr(name, '.');
  837. if(name[0] != '$' && dot)
  838. {
  839. S32 len = dStrlen(name);
  840. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - object name too long");
  841. dMemcpy(scratchBuffer, name, len+1);
  842. char * token = dStrtok(scratchBuffer, ".");
  843. SimObject * obj = Sim::findObject(token);
  844. if(!obj)
  845. return("");
  846. token = dStrtok(0, ".\0");
  847. if(!token)
  848. return("");
  849. while(token != NULL)
  850. {
  851. const char * val = obj->getDataField(StringTable->insert(token), 0);
  852. if(!val)
  853. return("");
  854. token = dStrtok(0, ".\0");
  855. if(token)
  856. {
  857. obj = Sim::findObject(token);
  858. if(!obj)
  859. return("");
  860. }
  861. else
  862. return(val);
  863. }
  864. }
  865. return NULL;
  866. }
  867. const char *getVariable(const char *name, const char* def)
  868. {
  869. const char *objField = getObjectTokenField(name);
  870. if (objField)
  871. {
  872. return objField;
  873. }
  874. else
  875. {
  876. Dictionary::Entry *entry = getVariableEntry(name);
  877. return entry ? entry->getStringValue() : def;
  878. }
  879. }
  880. const char *getLocalVariable(const char *name)
  881. {
  882. name = prependPercent(name);
  883. return gEvalState.getCurrentFrame().getVariable(StringTable->insert(name));
  884. }
  885. bool getBoolVariable(const char *varName, bool def)
  886. {
  887. const char *objField = getObjectTokenField(varName);
  888. if (objField)
  889. {
  890. return *objField ? dAtob(objField) : def;
  891. }
  892. else
  893. {
  894. Dictionary::Entry *entry = getVariableEntry(varName);
  895. objField = entry ? entry->getStringValue() : "";
  896. return *objField ? dAtob(objField) : def;
  897. }
  898. }
  899. S32 getIntVariable(const char *varName, S32 def)
  900. {
  901. const char *objField = getObjectTokenField(varName);
  902. if (objField)
  903. {
  904. return *objField ? dAtoi(objField) : def;
  905. }
  906. else
  907. {
  908. Dictionary::Entry *entry = getVariableEntry(varName);
  909. return entry ? entry->getIntValue() : def;
  910. }
  911. }
  912. F32 getFloatVariable(const char *varName, F32 def)
  913. {
  914. const char *objField = getObjectTokenField(varName);
  915. if (objField)
  916. {
  917. return *objField ? dAtof(objField) : def;
  918. }
  919. else
  920. {
  921. Dictionary::Entry *entry = getVariableEntry(varName);
  922. return entry ? entry->getFloatValue() : def;
  923. }
  924. }
  925. //---------------------------------------------------------------------------
  926. void addVariable( const char *name,
  927. S32 type,
  928. void *dptr,
  929. const char* usage )
  930. {
  931. gEvalState.globalVars.addVariable( name, type, dptr, usage );
  932. }
  933. void addConstant( const char *name,
  934. S32 type,
  935. const void *dptr,
  936. const char* usage )
  937. {
  938. Dictionary::Entry* entry = gEvalState.globalVars.addVariable( name, type, const_cast< void* >( dptr ), usage );
  939. entry->mIsConstant = true;
  940. }
  941. bool removeVariable(const char *name)
  942. {
  943. name = StringTable->lookup(prependDollar(name));
  944. return name!=0 && gEvalState.globalVars.removeVariable(name);
  945. }
  946. void addVariableNotify( const char *name, const NotifyDelegate &callback )
  947. {
  948. gEvalState.globalVars.addVariableNotify( name, callback );
  949. }
  950. void removeVariableNotify( const char *name, const NotifyDelegate &callback )
  951. {
  952. gEvalState.globalVars.removeVariableNotify( name, callback );
  953. }
  954. //---------------------------------------------------------------------------
  955. void addCommand( const char *nsName, const char *name,StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  956. {
  957. Namespace *ns = lookupNamespace(nsName);
  958. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  959. }
  960. void addCommand( const char *nsName, const char *name,VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  961. {
  962. Namespace *ns = lookupNamespace(nsName);
  963. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  964. }
  965. void addCommand( const char *nsName, const char *name,IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  966. {
  967. Namespace *ns = lookupNamespace(nsName);
  968. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  969. }
  970. void addCommand( const char *nsName, const char *name,FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  971. {
  972. Namespace *ns = lookupNamespace(nsName);
  973. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  974. }
  975. void addCommand( const char *nsName, const char *name,BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  976. {
  977. Namespace *ns = lookupNamespace(nsName);
  978. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  979. }
  980. void noteScriptCallback( const char *className, const char *funcName, const char *usage, ConsoleFunctionHeader* header )
  981. {
  982. Namespace *ns = lookupNamespace(className);
  983. ns->addScriptCallback( StringTable->insert(funcName), usage, header );
  984. }
  985. void markCommandGroup(const char * nsName, const char *name, const char* usage)
  986. {
  987. Namespace *ns = lookupNamespace(nsName);
  988. ns->markGroup(name,usage);
  989. }
  990. void beginCommandGroup(const char * nsName, const char *name, const char* usage)
  991. {
  992. markCommandGroup(nsName, name, usage);
  993. }
  994. void endCommandGroup(const char * nsName, const char *name)
  995. {
  996. markCommandGroup(nsName, name, NULL);
  997. }
  998. void addCommand( const char *name,StringCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  999. {
  1000. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  1001. }
  1002. void addCommand( const char *name,VoidCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  1003. {
  1004. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  1005. }
  1006. void addCommand( const char *name,IntCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  1007. {
  1008. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  1009. }
  1010. void addCommand( const char *name,FloatCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  1011. {
  1012. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  1013. }
  1014. void addCommand( const char *name,BoolCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  1015. {
  1016. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  1017. }
  1018. bool executeFile(const char* fileName, bool noCalls, bool journalScript)
  1019. {
  1020. bool journal = false;
  1021. char scriptFilenameBuffer[1024];
  1022. U32 execDepth = 0;
  1023. U32 journalDepth = 1;
  1024. execDepth++;
  1025. if (journalDepth >= execDepth)
  1026. journalDepth = execDepth + 1;
  1027. else
  1028. journal = true;
  1029. bool ret = false;
  1030. if (journalScript && !journal)
  1031. {
  1032. journal = true;
  1033. journalDepth = execDepth;
  1034. }
  1035. // Determine the filename we actually want...
  1036. Con::expandScriptFilename(scriptFilenameBuffer, sizeof(scriptFilenameBuffer), fileName);
  1037. // since this function expects a script file reference, if it's a .dso
  1038. // lets terminate the string before the dso so it will act like a .tscript
  1039. if (dStrEndsWith(scriptFilenameBuffer, ".dso"))
  1040. {
  1041. scriptFilenameBuffer[dStrlen(scriptFilenameBuffer) - dStrlen(".dso")] = '\0';
  1042. }
  1043. // Figure out where to put DSOs
  1044. StringTableEntry dsoPath = Con::getDSOPath(scriptFilenameBuffer);
  1045. const char *ext = dStrrchr(scriptFilenameBuffer, '.');
  1046. if (!ext)
  1047. {
  1048. // Try appending the default script extension and see if that succeeds
  1049. if (executeFile(fileName + String("." TORQUE_SCRIPT_EXTENSION), noCalls, journalScript))
  1050. {
  1051. return true;
  1052. }
  1053. // We need an extension!
  1054. Con::errorf(ConsoleLogEntry::Script, "exec: invalid script file name %s.", scriptFilenameBuffer);
  1055. execDepth--;
  1056. return false;
  1057. }
  1058. // Check Editor Extensions
  1059. bool isEditorScript = false;
  1060. // If the script file extension is '.ed.tscript' then compile it to a different compiled extension
  1061. if (dStricmp(ext, "." TORQUE_SCRIPT_EXTENSION) == 0)
  1062. {
  1063. const char* ext2 = ext - 3;
  1064. if (dStricmp(ext2, ".ed." TORQUE_SCRIPT_EXTENSION) == 0)
  1065. isEditorScript = true;
  1066. }
  1067. else if (dStricmp(ext, ".gui") == 0)
  1068. {
  1069. const char* ext2 = ext - 3;
  1070. if (dStricmp(ext2, ".ed.gui") == 0)
  1071. isEditorScript = true;
  1072. }
  1073. StringTableEntry scriptFileName = StringTable->insert(scriptFilenameBuffer);
  1074. // Is this a file we should compile? (anything in the prefs path should not be compiled)
  1075. StringTableEntry prefsPath = Platform::getPrefsPath();
  1076. bool compiled = dStricmp(ext, ".mis") && !journal && !Con::getBoolVariable("Scripts::ignoreDSOs");
  1077. // [tom, 12/5/2006] stripBasePath() fucks up if the filename is not in the exe
  1078. // path, current directory or prefs path. Thus, getDSOFilename() will also screw
  1079. // up and so this allows the scripts to still load but without a DSO.
  1080. if (Platform::isFullPath(Platform::stripBasePath(scriptFilenameBuffer)))
  1081. compiled = false;
  1082. // [tom, 11/17/2006] It seems to make sense to not compile scripts that are in the
  1083. // prefs directory. However, getDSOPath() can handle this situation and will put
  1084. // the dso along with the script to avoid name clashes with tools/game dsos.
  1085. if ((dsoPath && *dsoPath == 0) || (prefsPath && prefsPath[0] && dStrnicmp(scriptFileName, prefsPath, dStrlen(prefsPath)) == 0))
  1086. compiled = false;
  1087. // If we're in a journaling mode, then we will read the script
  1088. // from the journal file.
  1089. if (journal && Journal::IsPlaying())
  1090. {
  1091. char fileNameBuf[256];
  1092. bool fileRead = false;
  1093. U32 fileSize;
  1094. Journal::ReadString(fileNameBuf);
  1095. Journal::Read(&fileRead);
  1096. if (!fileRead)
  1097. {
  1098. Con::errorf(ConsoleLogEntry::Script, "Journal script read (failed) for %s", fileNameBuf);
  1099. execDepth--;
  1100. return false;
  1101. }
  1102. Journal::Read(&fileSize);
  1103. char *script = new char[fileSize + 1];
  1104. Journal::Read(fileSize, script);
  1105. script[fileSize] = 0;
  1106. Con::printf("Executing (journal-read) %s.", scriptFileName);
  1107. CodeBlock *newCodeBlock = new CodeBlock();
  1108. newCodeBlock->compileExec(scriptFileName, script, noCalls, 0);
  1109. delete[] script;
  1110. execDepth--;
  1111. return true;
  1112. }
  1113. // Ok, we let's try to load and compile the script.
  1114. Torque::FS::FileNodeRef scriptFile = Torque::FS::GetFileNode(scriptFileName);
  1115. Torque::FS::FileNodeRef dsoFile;
  1116. // ResourceObject *rScr = gResourceManager->find(scriptFileName);
  1117. // ResourceObject *rCom = NULL;
  1118. char nameBuffer[512];
  1119. char* script = NULL;
  1120. U32 version;
  1121. Stream *compiledStream = NULL;
  1122. Torque::Time scriptModifiedTime, dsoModifiedTime;
  1123. // Check here for .edso
  1124. bool edso = false;
  1125. if (dStricmp(ext, ".edso") == 0 && scriptFile != NULL)
  1126. {
  1127. edso = true;
  1128. dsoFile = scriptFile;
  1129. scriptFile = NULL;
  1130. dsoModifiedTime = dsoFile->getModifiedTime();
  1131. dStrcpy(nameBuffer, scriptFileName, 512);
  1132. }
  1133. // If we're supposed to be compiling this file, check to see if there's a DSO
  1134. if (compiled && !edso)
  1135. {
  1136. const char *filenameOnly = dStrrchr(scriptFileName, '/');
  1137. if (filenameOnly)
  1138. ++filenameOnly;
  1139. else
  1140. filenameOnly = scriptFileName;
  1141. char pathAndFilename[1024];
  1142. Platform::makeFullPathName(filenameOnly, pathAndFilename, sizeof(pathAndFilename), dsoPath);
  1143. if (isEditorScript)
  1144. dStrcpyl(nameBuffer, sizeof(nameBuffer), pathAndFilename, ".edso", NULL);
  1145. else
  1146. dStrcpyl(nameBuffer, sizeof(nameBuffer), pathAndFilename, ".dso", NULL);
  1147. dsoFile = Torque::FS::GetFileNode(nameBuffer);
  1148. if (scriptFile != NULL)
  1149. scriptModifiedTime = scriptFile->getModifiedTime();
  1150. if (dsoFile != NULL)
  1151. dsoModifiedTime = dsoFile->getModifiedTime();
  1152. }
  1153. // Let's do a sanity check to complain about DSOs in the future.
  1154. //
  1155. // MM: This doesn't seem to be working correctly for now so let's just not issue
  1156. // the warning until someone knows how to resolve it.
  1157. //
  1158. //if(compiled && rCom && rScr && Platform::compareFileTimes(comModifyTime, scrModifyTime) < 0)
  1159. //{
  1160. //Con::warnf("exec: Warning! Found a DSO from the future! (%s)", nameBuffer);
  1161. //}
  1162. // If we had a DSO, let's check to see if we should be reading from it.
  1163. //MGT: fixed bug with dsos not getting recompiled correctly
  1164. //Note: Using Nathan Martin's version from the forums since its easier to read and understand
  1165. if (compiled && dsoFile != NULL && (scriptFile == NULL || (dsoModifiedTime >= scriptModifiedTime)))
  1166. { //MGT: end
  1167. compiledStream = FileStream::createAndOpen(nameBuffer, Torque::FS::File::Read);
  1168. if (compiledStream)
  1169. {
  1170. // Check the version!
  1171. compiledStream->read(&version);
  1172. if (version != Con::DSOVersion)
  1173. {
  1174. Con::warnf("exec: Found an old DSO (%s, ver %d < %d), ignoring.", nameBuffer, version, Con::DSOVersion);
  1175. delete compiledStream;
  1176. compiledStream = NULL;
  1177. }
  1178. }
  1179. }
  1180. // If we're journalling, let's write some info out.
  1181. if (journal && Journal::IsRecording())
  1182. Journal::WriteString(scriptFileName);
  1183. if (scriptFile != NULL && !compiledStream)
  1184. {
  1185. // If we have source but no compiled version, then we need to compile
  1186. // (and journal as we do so, if that's required).
  1187. void *data;
  1188. U32 dataSize = 0;
  1189. Torque::FS::ReadFile(scriptFileName, data, dataSize, true);
  1190. if (journal && Journal::IsRecording())
  1191. Journal::Write(bool(data != NULL));
  1192. if (data == NULL)
  1193. {
  1194. Con::errorf(ConsoleLogEntry::Script, "exec: invalid script file %s.", scriptFileName);
  1195. execDepth--;
  1196. return false;
  1197. }
  1198. else
  1199. {
  1200. if (!dataSize)
  1201. {
  1202. execDepth--;
  1203. return false;
  1204. }
  1205. script = (char *)data;
  1206. if (journal && Journal::IsRecording())
  1207. {
  1208. Journal::Write(dataSize);
  1209. Journal::Write(dataSize, data);
  1210. }
  1211. }
  1212. #ifndef TORQUE_NO_DSO_GENERATION
  1213. if (compiled)
  1214. {
  1215. // compile this baddie.
  1216. #ifdef TORQUE_DEBUG
  1217. Con::printf("Compiling %s...", scriptFileName);
  1218. #endif
  1219. CodeBlock *code = new CodeBlock();
  1220. code->compile(nameBuffer, scriptFileName, script);
  1221. delete code;
  1222. code = NULL;
  1223. compiledStream = FileStream::createAndOpen(nameBuffer, Torque::FS::File::Read);
  1224. if (compiledStream)
  1225. {
  1226. compiledStream->read(&version);
  1227. }
  1228. else
  1229. {
  1230. // We have to exit out here, as otherwise we get double error reports.
  1231. delete[] script;
  1232. execDepth--;
  1233. return false;
  1234. }
  1235. }
  1236. #endif
  1237. }
  1238. else
  1239. {
  1240. if (journal && Journal::IsRecording())
  1241. Journal::Write(bool(false));
  1242. }
  1243. if (compiledStream)
  1244. {
  1245. // Delete the script object first to limit memory used
  1246. // during recursive execs.
  1247. delete[] script;
  1248. script = 0;
  1249. // We're all compiled, so let's run it.
  1250. #ifdef TORQUE_DEBUG
  1251. Con::printf("Loading compiled script %s.", scriptFileName);
  1252. #endif
  1253. CodeBlock *code = new CodeBlock;
  1254. code->read(scriptFileName, *compiledStream);
  1255. delete compiledStream;
  1256. code->exec(0, scriptFileName, NULL, 0, NULL, noCalls, NULL, 0);
  1257. ret = true;
  1258. }
  1259. else
  1260. if (scriptFile)
  1261. {
  1262. // No compiled script, let's just try executing it
  1263. // directly... this is either a mission file, or maybe
  1264. // we're on a readonly volume.
  1265. #ifdef TORQUE_DEBUG
  1266. Con::printf("Executing %s.", scriptFileName);
  1267. #endif
  1268. CodeBlock *newCodeBlock = new CodeBlock();
  1269. StringTableEntry name = StringTable->insert(scriptFileName);
  1270. newCodeBlock->compileExec(name, script, noCalls, 0);
  1271. ret = true;
  1272. }
  1273. else
  1274. {
  1275. // Don't have anything.
  1276. Con::warnf(ConsoleLogEntry::Script, "Missing file: %s!", scriptFileName);
  1277. ret = false;
  1278. }
  1279. delete[] script;
  1280. execDepth--;
  1281. return ret;
  1282. }
  1283. ConsoleValue evaluate(const char* string, bool echo, const char *fileName)
  1284. {
  1285. ConsoleStackFrameSaver stackSaver;
  1286. stackSaver.save();
  1287. if (echo)
  1288. {
  1289. if (string[0] == '%')
  1290. Con::printf("%s", string);
  1291. else
  1292. Con::printf("%s%s", getVariable( "$Con::Prompt" ), string);
  1293. }
  1294. if(fileName)
  1295. fileName = StringTable->insert(fileName);
  1296. CodeBlock *newCodeBlock = new CodeBlock();
  1297. return std::move(newCodeBlock->compileExec(fileName, string, false, fileName ? -1 : 0));
  1298. }
  1299. //------------------------------------------------------------------------------
  1300. ConsoleValue evaluatef(const char* string, ...)
  1301. {
  1302. ConsoleStackFrameSaver stackSaver;
  1303. stackSaver.save();
  1304. char buffer[4096];
  1305. va_list args;
  1306. va_start(args, string);
  1307. dVsprintf(buffer, sizeof(buffer), string, args);
  1308. va_end(args);
  1309. CodeBlock *newCodeBlock = new CodeBlock();
  1310. return newCodeBlock->compileExec(NULL, buffer, false, 0);
  1311. }
  1312. //------------------------------------------------------------------------------
  1313. // Internal execute for global function which does not save the stack
  1314. ConsoleValue _internalExecute(S32 argc, ConsoleValue argv[])
  1315. {
  1316. StringTableEntry funcName = StringTable->insert(argv[0].getString());
  1317. const char** argv_str = static_cast<const char**>(malloc((argc - 1) * sizeof(char *)));
  1318. for (int i = 0; i < argc - 1; i++)
  1319. {
  1320. argv_str[i] = argv[i + 1].getString();
  1321. }
  1322. bool result;
  1323. const char* methodRes = CInterface::CallFunction(NULL, funcName, argv_str, argc - 1, &result);
  1324. free(argv_str);
  1325. if (result)
  1326. {
  1327. ConsoleValue ret;
  1328. ret.setString(methodRes);
  1329. return std::move(ret);
  1330. }
  1331. Namespace::Entry *ent;
  1332. ent = Namespace::global()->lookup(funcName);
  1333. if(!ent)
  1334. {
  1335. warnf(ConsoleLogEntry::Script, "%s: Unknown command.", funcName);
  1336. STR.clearFunctionOffset();
  1337. return std::move(ConsoleValue());
  1338. }
  1339. return std::move(ent->execute(argc, argv, &gEvalState));
  1340. }
  1341. ConsoleValue execute(S32 argc, ConsoleValue argv[])
  1342. {
  1343. #ifdef TORQUE_MULTITHREAD
  1344. if(isMainThread())
  1345. {
  1346. #endif
  1347. ConsoleStackFrameSaver stackSaver;
  1348. stackSaver.save();
  1349. return _internalExecute(argc, argv);
  1350. #ifdef TORQUE_MULTITHREAD
  1351. }
  1352. else
  1353. {
  1354. SimConsoleThreadExecCallback cb;
  1355. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, false, &cb);
  1356. Sim::postEvent(Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1357. return cb.waitForResult();
  1358. }
  1359. #endif
  1360. }
  1361. ConsoleValue execute(S32 argc, const char *argv[])
  1362. {
  1363. ConsoleStackFrameSaver stackSaver;
  1364. stackSaver.save();
  1365. StringArrayToConsoleValueWrapper args(argc, argv);
  1366. return std::move(execute(args.count(), args));
  1367. }
  1368. //------------------------------------------------------------------------------
  1369. // Internal execute for object method which does not save the stack
  1370. static ConsoleValue _internalExecute(SimObject *object, S32 argc, ConsoleValue argv[], bool thisCallOnly)
  1371. {
  1372. if(argc < 2)
  1373. {
  1374. STR.clearFunctionOffset();
  1375. return std::move(ConsoleValue());
  1376. }
  1377. // [neo, 10/05/2007 - #3010]
  1378. // Make sure we don't get recursive calls, respect the flag!
  1379. // Should we be calling handlesMethod() first?
  1380. if( !thisCallOnly )
  1381. {
  1382. ICallMethod *com = dynamic_cast<ICallMethod *>(object);
  1383. if(com)
  1384. {
  1385. gCallStack.pushFrame(0);
  1386. com->callMethodArgList(argc, argv, false);
  1387. gCallStack.popFrame();
  1388. }
  1389. }
  1390. StringTableEntry funcName = StringTable->insert(argv[0].getString());
  1391. const char** argv_str = static_cast<const char**>(malloc((argc - 2) * sizeof(char *)));
  1392. for (int i = 0; i < argc - 2; i++)
  1393. {
  1394. argv_str[i] = argv[i + 2].getString();
  1395. }
  1396. bool result;
  1397. const char* methodRes = CInterface::CallMethod(object, funcName, argv_str, argc - 2, &result);
  1398. free(argv_str);
  1399. if (result)
  1400. {
  1401. ConsoleValue val;
  1402. val.setString(methodRes);
  1403. return std::move(val);
  1404. }
  1405. if(object->getNamespace())
  1406. {
  1407. U32 ident = object->getId();
  1408. const char* oldIdent = argv[1].getString();
  1409. Namespace::Entry *ent = object->getNamespace()->lookup(funcName);
  1410. if(ent == NULL)
  1411. {
  1412. //warnf(ConsoleLogEntry::Script, "%s: undefined for object '%s' - id %d", funcName, object->getName(), object->getId());
  1413. STR.clearFunctionOffset();
  1414. return std::move(ConsoleValue());
  1415. }
  1416. // Twiddle %this argument
  1417. argv[1].setInt(ident);
  1418. SimObject *save = gEvalState.thisObject;
  1419. gEvalState.thisObject = object;
  1420. ConsoleValue ret = std::move(ent->execute(argc, argv, &gEvalState));
  1421. gEvalState.thisObject = save;
  1422. // Twiddle it back
  1423. argv[1].setString(oldIdent);
  1424. return std::move(ret);
  1425. }
  1426. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), funcName);
  1427. STR.clearFunctionOffset();
  1428. return std::move(ConsoleValue());
  1429. }
  1430. ConsoleValue execute(SimObject *object, S32 argc, ConsoleValue argv[], bool thisCallOnly)
  1431. {
  1432. if(argc < 2)
  1433. {
  1434. STR.clearFunctionOffset();
  1435. return std::move(ConsoleValue());
  1436. }
  1437. ConsoleStackFrameSaver stackSaver;
  1438. stackSaver.save();
  1439. if (object->getNamespace() || !thisCallOnly)
  1440. {
  1441. if (isMainThread())
  1442. {
  1443. return std::move(_internalExecute(object, argc, argv, thisCallOnly));
  1444. }
  1445. else
  1446. {
  1447. SimConsoleThreadExecCallback cb;
  1448. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, true, &cb);
  1449. Sim::postEvent(object, evt, Sim::getCurrentTime());
  1450. }
  1451. }
  1452. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), argv[0].getString());
  1453. STR.clearFunctionOffset();
  1454. return std::move(ConsoleValue());
  1455. }
  1456. ConsoleValue execute(SimObject *object, S32 argc, const char *argv[], bool thisCallOnly)
  1457. {
  1458. ConsoleStackFrameSaver stackSaver;
  1459. stackSaver.save();
  1460. StringArrayToConsoleValueWrapper args(argc, argv);
  1461. return std::move(execute(object, args.count(), args, thisCallOnly));
  1462. }
  1463. inline ConsoleValue _executef(SimObject *obj, S32 checkArgc, S32 argc, ConsoleValue *argv)
  1464. {
  1465. const U32 maxArg = 12;
  1466. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef(SimObject*)");
  1467. AssertFatal(argc <= maxArg - 1, "Too many args passed to Con::_executef(SimObject*). Please update the function to handle more.");
  1468. return std::move(execute(obj, argc, argv));
  1469. }
  1470. //------------------------------------------------------------------------------
  1471. inline ConsoleValue _executef(S32 checkArgc, S32 argc, ConsoleValue *argv)
  1472. {
  1473. const U32 maxArg = 10;
  1474. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef()");
  1475. AssertFatal(argc <= maxArg, "Too many args passed to Con::_executef(). Please update the function to handle more.");
  1476. return std::move(execute(argc, argv));
  1477. }
  1478. //------------------------------------------------------------------------------
  1479. bool isFunction(const char *fn)
  1480. {
  1481. if (CInterface::isMethod(NULL, fn)) return true;
  1482. const char *string = StringTable->lookup(fn);
  1483. if(!string)
  1484. return false;
  1485. else
  1486. return Namespace::global()->lookup(string) != NULL;
  1487. }
  1488. //------------------------------------------------------------------------------
  1489. void setLogMode(S32 newMode)
  1490. {
  1491. if ((newMode & 0x3) != (consoleLogMode & 0x3)) {
  1492. if (newMode && !consoleLogMode) {
  1493. // Enabling logging when it was previously disabled.
  1494. newLogFile = true;
  1495. }
  1496. if ((consoleLogMode & 0x3) == 2) {
  1497. // Changing away from mode 2, must close logfile.
  1498. consoleLogFile.close();
  1499. }
  1500. else if ((newMode & 0x3) == 2) {
  1501. #ifdef _XBOX
  1502. // Xbox is not going to support logging to a file. Use the OutputDebugStr
  1503. // log consumer
  1504. Platform::debugBreak();
  1505. #endif
  1506. // Starting mode 2, must open logfile.
  1507. consoleLogFile.open(defLogFileName, Torque::FS::File::Write);
  1508. }
  1509. consoleLogMode = newMode;
  1510. }
  1511. }
  1512. Namespace *lookupNamespace(const char *ns)
  1513. {
  1514. if(!ns)
  1515. return Namespace::global();
  1516. return Namespace::find(StringTable->insert(ns));
  1517. }
  1518. bool linkNamespaces(const char *parent, const char *child)
  1519. {
  1520. Namespace *pns = lookupNamespace(parent);
  1521. Namespace *cns = lookupNamespace(child);
  1522. if(pns && cns)
  1523. return cns->classLinkTo(pns);
  1524. return false;
  1525. }
  1526. bool unlinkNamespaces(const char *parent, const char *child)
  1527. {
  1528. Namespace *pns = lookupNamespace(parent);
  1529. Namespace *cns = lookupNamespace(child);
  1530. if(pns == cns)
  1531. {
  1532. Con::warnf("Con::unlinkNamespaces - trying to unlink '%s' from itself, aborting.", parent);
  1533. return false;
  1534. }
  1535. if(pns && cns)
  1536. return cns->unlinkClass(pns);
  1537. return false;
  1538. }
  1539. bool classLinkNamespaces(Namespace *parent, Namespace *child)
  1540. {
  1541. if(parent && child)
  1542. return child->classLinkTo(parent);
  1543. return false;
  1544. }
  1545. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, const EnumTable *tbl, BitSet32 flag)
  1546. {
  1547. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1548. AssertFatal(cbt, "Con::setData - could not resolve type ID!");
  1549. cbt->setData((void *) (((const char *)dptr) + index * cbt->getTypeSize()),argc, argv, tbl, flag);
  1550. }
  1551. const char *getData(S32 type, void *dptr, S32 index, const EnumTable *tbl, BitSet32 flag)
  1552. {
  1553. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1554. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1555. return cbt->getData((void *) (((const char *)dptr) + index * cbt->getTypeSize()), tbl, flag);
  1556. }
  1557. const char *getFormattedData(S32 type, const char *data, const EnumTable *tbl, BitSet32 flag)
  1558. {
  1559. ConsoleBaseType *cbt = ConsoleBaseType::getType( type );
  1560. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1561. // Datablock types are just a datablock
  1562. // name and don't ever need formatting.
  1563. if ( cbt->isDatablock() )
  1564. return data;
  1565. bool currWarn = gWarnUndefinedScriptVariables;
  1566. gWarnUndefinedScriptVariables = false;
  1567. const char* globalValue = Con::getVariable(data);
  1568. gWarnUndefinedScriptVariables = currWarn;
  1569. if (dStrlen(globalValue) > 0)
  1570. return globalValue;
  1571. void* variable = cbt->getNativeVariable();
  1572. if (variable)
  1573. {
  1574. Con::setData(type, variable, 0, 1, &data, tbl, flag);
  1575. const char* formattedVal = Con::getData(type, variable, 0, tbl, flag);
  1576. static const U32 bufSize = 2048;
  1577. char* returnBuffer = Con::getReturnBuffer(bufSize);
  1578. dSprintf(returnBuffer, bufSize, "%s\0", formattedVal );
  1579. cbt->deleteNativeVariable(variable);
  1580. return returnBuffer;
  1581. }
  1582. else
  1583. return data;
  1584. }
  1585. //------------------------------------------------------------------------------
  1586. bool isCurrentScriptToolScript()
  1587. {
  1588. // With a player build we ALWAYS return false
  1589. #ifndef TORQUE_TOOLS
  1590. return false;
  1591. #else
  1592. const StringTableEntry cbFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1593. if(cbFullPath == NULL)
  1594. return false;
  1595. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1596. return dStrnicmp(exePath, cbFullPath, dStrlen(exePath)) == 0;
  1597. #endif
  1598. }
  1599. //------------------------------------------------------------------------------
  1600. StringTableEntry getModNameFromPath(const char *path)
  1601. {
  1602. if(path == NULL || *path == 0)
  1603. return NULL;
  1604. char buf[1024];
  1605. buf[0] = 0;
  1606. if(path[0] == '/' || path[1] == ':')
  1607. {
  1608. // It's an absolute path
  1609. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1610. U32 len = dStrlen(exePath);
  1611. if(dStrnicmp(exePath, path, len) == 0)
  1612. {
  1613. const char *ptr = path + len + 1;
  1614. const char *slash = dStrchr(ptr, '/');
  1615. if(slash)
  1616. {
  1617. dStrncpy(buf, ptr, slash - ptr);
  1618. buf[slash - ptr] = 0;
  1619. }
  1620. else
  1621. return NULL;
  1622. }
  1623. else
  1624. return NULL;
  1625. }
  1626. else
  1627. {
  1628. const char *slash = dStrchr(path, '/');
  1629. if(slash)
  1630. {
  1631. dStrncpy(buf, path, slash - path);
  1632. buf[slash - path] = 0;
  1633. }
  1634. else
  1635. return NULL;
  1636. }
  1637. return StringTable->insert(buf);
  1638. }
  1639. void postConsoleInput( RawData data )
  1640. {
  1641. // TODO(JTH): Mem leak
  1642. // Schedule this to happen at the next time event.
  1643. ConsoleValue* argv = new ConsoleValue[2];
  1644. argv[0].setString("eval");
  1645. argv[1].setString(reinterpret_cast<const char*>(data.data));
  1646. Sim::postCurrentEvent(Sim::getRootGroup(), new SimConsoleEvent(2, argv, false));
  1647. }
  1648. //------------------------------------------------------------------------------
  1649. void pushInstantGroup( String name )
  1650. {
  1651. sInstantGroupStack.push_back( gInstantGroup );
  1652. gInstantGroup = name;
  1653. }
  1654. void popInstantGroup()
  1655. {
  1656. if( sInstantGroupStack.empty() )
  1657. gInstantGroup = String::EmptyString;
  1658. else
  1659. {
  1660. gInstantGroup = sInstantGroupStack.last();
  1661. sInstantGroupStack.pop_back();
  1662. }
  1663. }
  1664. typedef HashMap<StringTableEntry, StringTableEntry> typePathExpandoMap;
  1665. static typePathExpandoMap PathExpandos;
  1666. //-----------------------------------------------------------------------------
  1667. void addPathExpando(const char* pExpandoName, const char* pPath)
  1668. {
  1669. // Sanity!
  1670. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1671. AssertFatal(pPath != NULL, "Expando path cannot be NULL.");
  1672. // Fetch expando name.
  1673. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1674. // Fetch the length of the path.
  1675. S32 pathLength = dStrlen(pPath);
  1676. char pathBuffer[1024];
  1677. // Sanity!
  1678. if (pathLength == 0 || pathLength >= sizeof(pathBuffer))
  1679. {
  1680. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1681. return;
  1682. }
  1683. // Strip repeat slashes.
  1684. if (!Con::stripRepeatSlashes(pathBuffer, pPath, sizeof(pathBuffer)))
  1685. {
  1686. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1687. return;
  1688. }
  1689. // Fetch new path length.
  1690. pathLength = dStrlen(pathBuffer);
  1691. // Sanity!
  1692. if (pathLength == 0)
  1693. {
  1694. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1695. return;
  1696. }
  1697. // Remove any terminating slash.
  1698. if (pathBuffer[pathLength - 1] == '/')
  1699. pathBuffer[pathLength - 1] = 0;
  1700. // Fetch expanded path.
  1701. StringTableEntry expandedPath = StringTable->insert(pathBuffer);
  1702. // Info.
  1703. #if defined(TORQUE_DEBUG)
  1704. Con::printf("Adding path expando of '%s' as '%s'.", expandoName, expandedPath);
  1705. #endif
  1706. // Find any existing path expando.
  1707. typePathExpandoMap::iterator expandoItr = PathExpandos.find(pExpandoName);
  1708. // Does the expando exist?
  1709. if (expandoItr != PathExpandos.end())
  1710. {
  1711. // Yes, so modify the path.
  1712. expandoItr->value = expandedPath;
  1713. return;
  1714. }
  1715. // Insert expando.
  1716. PathExpandos.insert(expandoName, expandedPath);
  1717. }
  1718. //-----------------------------------------------------------------------------
  1719. StringTableEntry getPathExpando(const char* pExpandoName)
  1720. {
  1721. // Sanity!
  1722. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1723. // Fetch expando name.
  1724. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1725. // Find any existing path expando.
  1726. typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
  1727. // Does the expando exist?
  1728. if (expandoItr != PathExpandos.end())
  1729. {
  1730. // Yes, so return it.
  1731. return expandoItr->value;
  1732. }
  1733. // Not found.
  1734. return NULL;
  1735. }
  1736. //-----------------------------------------------------------------------------
  1737. void removePathExpando(const char* pExpandoName)
  1738. {
  1739. // Sanity!
  1740. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1741. // Fetch expando name.
  1742. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1743. // Find any existing path expando.
  1744. typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
  1745. // Does the expando exist?
  1746. if (expandoItr == PathExpandos.end())
  1747. {
  1748. // No, so warn.
  1749. #if defined(TORQUE_DEBUG)
  1750. Con::warnf("Removing path expando of '%s' but it does not exist.", expandoName);
  1751. #endif
  1752. return;
  1753. }
  1754. // Info.
  1755. #if defined(TORQUE_DEBUG)
  1756. Con::printf("Removing path expando of '%s' as '%s'.", expandoName, expandoItr->value);
  1757. #endif
  1758. // Remove expando.
  1759. PathExpandos.erase(expandoItr);
  1760. }
  1761. //-----------------------------------------------------------------------------
  1762. bool isPathExpando(const char* pExpandoName)
  1763. {
  1764. // Sanity!
  1765. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1766. // Fetch expando name.
  1767. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1768. return PathExpandos.contains(expandoName);
  1769. }
  1770. //-----------------------------------------------------------------------------
  1771. U32 getPathExpandoCount(void)
  1772. {
  1773. return PathExpandos.size();
  1774. }
  1775. //-----------------------------------------------------------------------------
  1776. StringTableEntry getPathExpandoKey(U32 expandoIndex)
  1777. {
  1778. // Finish if index is out of range.
  1779. if (expandoIndex >= PathExpandos.size())
  1780. return NULL;
  1781. // Find indexed iterator.
  1782. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1783. while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
  1784. return expandoItr->key;
  1785. }
  1786. //-----------------------------------------------------------------------------
  1787. StringTableEntry getPathExpandoValue(U32 expandoIndex)
  1788. {
  1789. // Finish if index is out of range.
  1790. if (expandoIndex >= PathExpandos.size())
  1791. return NULL;
  1792. // Find indexed iterator.
  1793. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1794. while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
  1795. return expandoItr->value;
  1796. }
  1797. //-----------------------------------------------------------------------------
  1798. bool expandPath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint, const bool ensureTrailingSlash)
  1799. {
  1800. char pathBuffer[2048];
  1801. const char* pSrc = pSrcPath;
  1802. char* pSlash;
  1803. // Fetch leading character.
  1804. const char leadingToken = *pSrc;
  1805. // Fetch following token.
  1806. const char followingToken = leadingToken != 0 ? pSrc[1] : 0;
  1807. // Expando.
  1808. if (leadingToken == '^')
  1809. {
  1810. // Initial prefix search.
  1811. const char* pPrefixSrc = pSrc + 1;
  1812. char* pPrefixDst = pathBuffer;
  1813. // Search for end of expando.
  1814. while (*pPrefixSrc != '/' && *pPrefixSrc != 0)
  1815. {
  1816. // Copy prefix character.
  1817. *pPrefixDst++ = *pPrefixSrc++;
  1818. }
  1819. // Yes, so terminate the expando string.
  1820. *pPrefixDst = 0;
  1821. // Fetch the expando path.
  1822. StringTableEntry expandoPath = getPathExpando(pathBuffer);
  1823. // Does the expando exist?
  1824. if (expandoPath == NULL)
  1825. {
  1826. // No, so error.
  1827. Con::errorf("expandPath() : Could not find path expando '%s' for path '%s'.", pathBuffer, pSrcPath);
  1828. // Are we ensuring the trailing slash?
  1829. if (ensureTrailingSlash)
  1830. {
  1831. // Yes, so ensure it.
  1832. Con::ensureTrailingSlash(pDstPath, pSrcPath, size);
  1833. }
  1834. else
  1835. {
  1836. // No, so just use the source path.
  1837. dStrcpy(pDstPath, pSrcPath, size);
  1838. }
  1839. return false;
  1840. }
  1841. // Skip the expando and the following slash.
  1842. pSrc += dStrlen(pathBuffer) + 1;
  1843. // Format the output path.
  1844. dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", expandoPath, pSrc);
  1845. // Are we ensuring the trailing slash?
  1846. if (ensureTrailingSlash)
  1847. {
  1848. // Yes, so ensure it.
  1849. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1850. }
  1851. // Strip repeat slashes.
  1852. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1853. return true;
  1854. }
  1855. // Script-Relative.
  1856. if (leadingToken == '.')
  1857. {
  1858. // Fetch the code-block file-path.
  1859. const StringTableEntry codeblockFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1860. // Do we have a code block full path?
  1861. if (codeblockFullPath == NULL)
  1862. {
  1863. // No, so error.
  1864. Con::errorf("expandPath() : Could not find relative path from code-block for path '%s'.", pSrcPath);
  1865. // Are we ensuring the trailing slash?
  1866. if (ensureTrailingSlash)
  1867. {
  1868. // Yes, so ensure it.
  1869. Con::ensureTrailingSlash(pDstPath, pSrcPath, size);
  1870. }
  1871. else
  1872. {
  1873. // No, so just use the source path.
  1874. dStrcpy(pDstPath, pSrcPath, size);
  1875. }
  1876. return false;
  1877. }
  1878. // Yes, so use it as the prefix.
  1879. dStrncpy(pathBuffer, codeblockFullPath, sizeof(pathBuffer) - 1);
  1880. // Find the final slash in the code-block.
  1881. pSlash = dStrrchr(pathBuffer, '/');
  1882. // Is this a parent directory token?
  1883. if (followingToken == '.')
  1884. {
  1885. // Yes, so terminate after the slash so we include it.
  1886. pSlash[1] = 0;
  1887. }
  1888. else
  1889. {
  1890. // No, it's a current directory token so terminate at the slash so we don't include it.
  1891. pSlash[0] = 0;
  1892. // Skip the current directory token.
  1893. pSrc++;
  1894. }
  1895. // Format the output path.
  1896. dStrncat(pathBuffer, "/", sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1897. dStrncat(pathBuffer, pSrc, sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1898. // Are we ensuring the trailing slash?
  1899. if (ensureTrailingSlash)
  1900. {
  1901. // Yes, so ensure it.
  1902. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1903. }
  1904. // Strip repeat slashes.
  1905. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1906. return true;
  1907. }
  1908. // All else.
  1909. //Using a special case here because the code below barfs on trying to build a full path for apk reading
  1910. #ifdef TORQUE_OS_ANDROID
  1911. if (leadingToken == '/' || strstr(pSrcPath, "/") == NULL)
  1912. Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
  1913. else
  1914. dSprintf(pathBuffer, sizeof(pathBuffer), "/%s", pSrcPath);
  1915. #else
  1916. Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
  1917. #endif
  1918. // Are we ensuring the trailing slash?
  1919. if (ensureTrailingSlash)
  1920. {
  1921. // Yes, so ensure it.
  1922. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1923. }
  1924. // Strip repeat slashes.
  1925. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1926. return true;
  1927. }
  1928. //-----------------------------------------------------------------------------
  1929. bool isBasePath(const char* SrcPath, const char* pBasePath)
  1930. {
  1931. char expandBuffer[1024];
  1932. Con::expandPath(expandBuffer, sizeof(expandBuffer), SrcPath);
  1933. return dStrnicmp(pBasePath, expandBuffer, dStrlen(pBasePath)) == 0;
  1934. }
  1935. //-----------------------------------------------------------------------------
  1936. void collapsePath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint)
  1937. {
  1938. // Check path against expandos. If there are multiple matches, choose the
  1939. // expando that produces the shortest relative path.
  1940. char pathBuffer[2048];
  1941. // Fetch expando count.
  1942. const U32 expandoCount = getPathExpandoCount();
  1943. // Iterate expandos.
  1944. U32 expandoRelativePathLength = U32_MAX;
  1945. for (U32 expandoIndex = 0; expandoIndex < expandoCount; ++expandoIndex)
  1946. {
  1947. // Fetch expando value (path).
  1948. StringTableEntry expandoValue = getPathExpandoValue(expandoIndex);
  1949. // Skip if not the base path.
  1950. if (!isBasePath(pSrcPath, expandoValue))
  1951. continue;
  1952. // Fetch path relative to expando path.
  1953. StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, expandoValue);
  1954. // If the relative path is simply a period
  1955. if (relativePath[0] == '.')
  1956. relativePath++;
  1957. if (dStrlen(relativePath) > expandoRelativePathLength)
  1958. {
  1959. // This expando covers less of the path than any previous one found.
  1960. // We will keep the previous one.
  1961. continue;
  1962. }
  1963. // Keep track of the relative path length
  1964. expandoRelativePathLength = dStrlen(relativePath);
  1965. // Fetch expando key (name).
  1966. StringTableEntry expandoName = getPathExpandoKey(expandoIndex);
  1967. // Format against expando.
  1968. dSprintf(pathBuffer, sizeof(pathBuffer), "^%s/%s", expandoName, relativePath);
  1969. }
  1970. // Check if we've found a suitable expando
  1971. if (expandoRelativePathLength != U32_MAX)
  1972. {
  1973. // Strip repeat slashes.
  1974. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1975. return;
  1976. }
  1977. // Fetch the working directory.
  1978. StringTableEntry workingDirectory = pWorkingDirectoryHint != NULL ? pWorkingDirectoryHint : Platform::getCurrentDirectory();
  1979. // Fetch path relative to current directory.
  1980. StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, workingDirectory);
  1981. // If the relative path is simply a period
  1982. if (relativePath[0] == '.' && relativePath[1] != '.')
  1983. relativePath++;
  1984. // Format against expando.
  1985. dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", workingDirectory, relativePath);
  1986. // Strip repeat slashes.
  1987. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1988. }
  1989. void ensureTrailingSlash(char* pDstPath, const char* pSrcPath, S32 dstSize)
  1990. {
  1991. // Copy to target.
  1992. dStrcpy(pDstPath, pSrcPath, dstSize);
  1993. // Find trailing character index.
  1994. S32 trailIndex = dStrlen(pDstPath);
  1995. // Ignore if empty string.
  1996. if (trailIndex == 0)
  1997. return;
  1998. // Finish if the trailing slash already exists.
  1999. if (pDstPath[trailIndex - 1] == '/')
  2000. return;
  2001. // Add trailing slash.
  2002. pDstPath[trailIndex++] = '/';
  2003. pDstPath[trailIndex] = 0;
  2004. }
  2005. //-----------------------------------------------------------------------------
  2006. StringTableEntry getDSOPath(const char *scriptPath)
  2007. {
  2008. #ifndef TORQUE2D_TOOLS_FIXME
  2009. // [tom, 11/17/2006] Force old behavior for the player. May not want to do this.
  2010. const char *slash = dStrrchr(scriptPath, '/');
  2011. if (slash != NULL)
  2012. return StringTable->insertn(scriptPath, slash - scriptPath, true);
  2013. slash = dStrrchr(scriptPath, ':');
  2014. if (slash != NULL)
  2015. return StringTable->insertn(scriptPath, (slash - scriptPath) + 1, true);
  2016. return "";
  2017. #else
  2018. char relPath[1024], dsoPath[1024];
  2019. bool isPrefs = false;
  2020. // [tom, 11/17/2006] Prefs are handled slightly differently to avoid dso name clashes
  2021. StringTableEntry prefsPath = Platform::getPrefsPath();
  2022. if (dStrnicmp(scriptPath, prefsPath, dStrlen(prefsPath)) == 0)
  2023. {
  2024. relPath[0] = 0;
  2025. isPrefs = true;
  2026. }
  2027. else
  2028. {
  2029. StringTableEntry strippedPath = Platform::stripBasePath(scriptPath);
  2030. dStrcpy(relPath, strippedPath, 1024);
  2031. char *slash = dStrrchr(relPath, '/');
  2032. if (slash)
  2033. *slash = 0;
  2034. }
  2035. const char *overridePath;
  2036. if (!isPrefs)
  2037. overridePath = Con::getVariable("$Scripts::OverrideDSOPath");
  2038. else
  2039. overridePath = prefsPath;
  2040. if (overridePath && *overridePath)
  2041. Platform::makeFullPathName(relPath, dsoPath, sizeof(dsoPath), overridePath);
  2042. else
  2043. {
  2044. char t[1024];
  2045. dSprintf(t, sizeof(t), "compiledScripts/%s", relPath);
  2046. Platform::makeFullPathName(t, dsoPath, sizeof(dsoPath), Platform::getPrefsPath());
  2047. }
  2048. return StringTable->insert(dsoPath);
  2049. #endif
  2050. }
  2051. //-----------------------------------------------------------------------------
  2052. bool stripRepeatSlashes(char* pDstPath, const char* pSrcPath, S32 dstSize)
  2053. {
  2054. // Note original destination.
  2055. char* pOriginalDst = pDstPath;
  2056. // Reset last source character.
  2057. char lastSrcChar = 0;
  2058. // Search source...
  2059. while (dstSize > 0)
  2060. {
  2061. // Fetch characters.
  2062. const char srcChar = *pSrcPath++;
  2063. // Do we have a repeat slash?
  2064. if (srcChar == '/' && lastSrcChar == '/')
  2065. {
  2066. // Yes, so skip it.
  2067. continue;
  2068. }
  2069. // No, so copy character.
  2070. *pDstPath++ = srcChar;
  2071. // Finish if end of source.
  2072. if (srcChar == 0)
  2073. return true;
  2074. // Reduce room left in destination.
  2075. dstSize--;
  2076. // Set last character.
  2077. lastSrcChar = srcChar;
  2078. }
  2079. // Terminate the destination string as we ran out of room.
  2080. *pOriginalDst = 0;
  2081. // Fail!
  2082. return false;
  2083. }
  2084. } // end of Console namespace
  2085. #endif
  2086. //=============================================================================
  2087. // API.
  2088. //=============================================================================
  2089. // MARK: ---- API ----
  2090. //-----------------------------------------------------------------------------
  2091. DefineEngineFunction( log, void, ( const char* message ),,
  2092. "@brief Logs a message to the console.\n\n"
  2093. "@param message The message text.\n"
  2094. "@note By default, messages will appear white in the console.\n"
  2095. "@ingroup Logging")
  2096. {
  2097. Con::printf( "%s", message );
  2098. }
  2099. //-----------------------------------------------------------------------------
  2100. DefineEngineFunction( logError, void, ( const char* message ),,
  2101. "@brief Logs an error message to the console.\n\n"
  2102. "@param message The message text.\n"
  2103. "@note By default, errors will appear red in the console.\n"
  2104. "@ingroup Logging")
  2105. {
  2106. Con::errorf( "%s", message );
  2107. }
  2108. //-----------------------------------------------------------------------------
  2109. DefineEngineFunction( logWarning, void, ( const char* message ),,
  2110. "@brief Logs a warning message to the console.\n\n"
  2111. "@param message The message text.\n\n"
  2112. "@note By default, warnings will appear turquoise in the console.\n"
  2113. "@ingroup Logging")
  2114. {
  2115. Con::warnf( "%s", message );
  2116. }
  2117. //------------------------------------------------------------------------------
  2118. ConsoleValueToStringArrayWrapper::ConsoleValueToStringArrayWrapper(int targc, ConsoleValue *targv)
  2119. {
  2120. argv = new const char*[targc];
  2121. argc = targc;
  2122. for (S32 i = 0; i < targc; i++)
  2123. {
  2124. argv[i] = dStrdup(targv[i].getString());
  2125. }
  2126. }
  2127. ConsoleValueToStringArrayWrapper::~ConsoleValueToStringArrayWrapper()
  2128. {
  2129. for (S32 i = 0; i< argc; i++)
  2130. {
  2131. dFree(argv[i]);
  2132. }
  2133. delete[] argv;
  2134. }
  2135. StringArrayToConsoleValueWrapper::StringArrayToConsoleValueWrapper(int targc, const char** targv)
  2136. {
  2137. argv = new ConsoleValue[targc];
  2138. argc = targc;
  2139. for (int i=0; i<targc; i++)
  2140. {
  2141. argv[i].setString(targv[i]);
  2142. }
  2143. }
  2144. StringArrayToConsoleValueWrapper::~StringArrayToConsoleValueWrapper()
  2145. {
  2146. delete[] argv;
  2147. }
  2148. //------------------------------------------------------------------------------
  2149. ConsoleValue _BaseEngineConsoleCallbackHelper::_exec()
  2150. {
  2151. if( mThis )
  2152. {
  2153. // Cannot invoke callback until object has been registered
  2154. if (mThis->isProperlyAdded())
  2155. {
  2156. ConsoleValue returnValue = Con::_internalExecute( mThis, mArgc, mArgv, false );
  2157. mArgc = mInitialArgc; // reset
  2158. return std::move(returnValue);
  2159. }
  2160. STR.clearFunctionOffset();
  2161. mArgc = mInitialArgc; // reset
  2162. return std::move(ConsoleValue());
  2163. }
  2164. ConsoleValue returnValue = std::move(Con::_internalExecute( mArgc, mArgv ));
  2165. mArgc = mInitialArgc; // reset args
  2166. return std::move(returnValue);
  2167. }
  2168. ConsoleValue _BaseEngineConsoleCallbackHelper::_execLater(SimConsoleThreadExecEvent *evt)
  2169. {
  2170. mArgc = mInitialArgc; // reset args
  2171. Sim::postEvent((SimObject*)Sim::getRootGroup(), evt, Sim::getCurrentTime());
  2172. return std::move(evt->getCB().waitForResult());
  2173. }
  2174. //------------------------------------------------------------------------------
  2175. void ConsoleStackFrameSaver::save()
  2176. {
  2177. gCallStack.pushFrame(0);
  2178. mSaved = true;
  2179. }
  2180. void ConsoleStackFrameSaver::restore()
  2181. {
  2182. if (mSaved)
  2183. {
  2184. gCallStack.popFrame();
  2185. }
  2186. }