console.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  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. extern StringStack STR;
  42. ConsoleDocFragment* ConsoleDocFragment::smFirst;
  43. ExprEvalState gEvalState;
  44. StmtNode *gStatementList;
  45. ConsoleConstructor *ConsoleConstructor::first = NULL;
  46. bool gWarnUndefinedScriptVariables;
  47. static char scratchBuffer[4096];
  48. CON_DECLARE_PARSER(CMD);
  49. static const char * prependDollar ( const char * name )
  50. {
  51. if(name[0] != '$')
  52. {
  53. S32 len = dStrlen(name);
  54. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  55. scratchBuffer[0] = '$';
  56. dMemcpy(scratchBuffer + 1, name, len + 1);
  57. name = scratchBuffer;
  58. }
  59. return name;
  60. }
  61. static const char * prependPercent ( const char * name )
  62. {
  63. if(name[0] != '%')
  64. {
  65. S32 len = dStrlen(name);
  66. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  67. scratchBuffer[0] = '%';
  68. dMemcpy(scratchBuffer + 1, name, len + 1);
  69. name = scratchBuffer;
  70. }
  71. return name;
  72. }
  73. //--------------------------------------
  74. void ConsoleConstructor::init( const char *cName, const char *fName, const char *usg, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  75. {
  76. mina = minArgs;
  77. maxa = maxArgs;
  78. funcName = fName;
  79. usage = usg;
  80. className = cName;
  81. sc = 0; fc = 0; vc = 0; bc = 0; ic = 0;
  82. callback = group = false;
  83. next = first;
  84. ns = false;
  85. first = this;
  86. toolOnly = isToolOnly;
  87. this->header = header;
  88. }
  89. void ConsoleConstructor::setup()
  90. {
  91. for(ConsoleConstructor *walk = first; walk; walk = walk->next)
  92. {
  93. #ifdef TORQUE_DEBUG
  94. walk->validate();
  95. #endif
  96. if( walk->sc )
  97. Con::addCommand( walk->className, walk->funcName, walk->sc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  98. else if( walk->ic )
  99. Con::addCommand( walk->className, walk->funcName, walk->ic, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  100. else if( walk->fc )
  101. Con::addCommand( walk->className, walk->funcName, walk->fc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  102. else if( walk->vc )
  103. Con::addCommand( walk->className, walk->funcName, walk->vc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  104. else if( walk->bc )
  105. Con::addCommand( walk->className, walk->funcName, walk->bc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  106. else if( walk->group )
  107. Con::markCommandGroup( walk->className, walk->funcName, walk->usage );
  108. else if( walk->callback )
  109. Con::noteScriptCallback( walk->className, walk->funcName, walk->usage, walk->header );
  110. else if( walk->ns )
  111. {
  112. Namespace* ns = Namespace::find( StringTable->insert( walk->className ) );
  113. if( ns )
  114. ns->mUsage = walk->usage;
  115. }
  116. else
  117. {
  118. AssertISV( false, "Found a ConsoleConstructor with an indeterminate type!" );
  119. }
  120. }
  121. }
  122. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, StringCallback sfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  123. {
  124. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  125. sc = sfunc;
  126. }
  127. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, IntCallback ifunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  128. {
  129. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  130. ic = ifunc;
  131. }
  132. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, FloatCallback ffunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  133. {
  134. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  135. fc = ffunc;
  136. }
  137. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, VoidCallback vfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  138. {
  139. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  140. vc = vfunc;
  141. }
  142. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, BoolCallback bfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  143. {
  144. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  145. bc = bfunc;
  146. }
  147. ConsoleConstructor::ConsoleConstructor(const char* className, const char* groupName, const char* aUsage)
  148. {
  149. init(className, groupName, usage, -1, -2);
  150. group = true;
  151. // Somewhere, the entry list is getting flipped, partially.
  152. // so we have to do tricks to deal with making sure usage
  153. // is properly populated.
  154. // This is probably redundant.
  155. static char * lastUsage = NULL;
  156. if(aUsage)
  157. lastUsage = (char *)aUsage;
  158. usage = lastUsage;
  159. }
  160. ConsoleConstructor::ConsoleConstructor(const char *className, const char *callbackName, const char *usage, ConsoleFunctionHeader* header )
  161. {
  162. init( className, callbackName, usage, -2, -3, false, header );
  163. callback = true;
  164. ns = true;
  165. }
  166. void ConsoleConstructor::validate()
  167. {
  168. #ifdef TORQUE_DEBUG
  169. // Don't do the following check if we're not a method/func.
  170. if(this->group)
  171. return;
  172. // In debug, walk the list and make sure this isn't a duplicate.
  173. for(ConsoleConstructor *walk = first; walk; walk = walk->next)
  174. {
  175. // Skip mismatching func/method names.
  176. if(dStricmp(walk->funcName, this->funcName))
  177. continue;
  178. // Don't compare functions with methods or vice versa.
  179. if(bool(this->className) != bool(walk->className))
  180. continue;
  181. // Skip mismatching classnames, if they're present.
  182. if(this->className && walk->className && dStricmp(walk->className, this->className))
  183. continue;
  184. // If we encounter ourselves, stop searching; this prevents duplicate
  185. // firing of the assert, instead only firing for the latter encountered
  186. // entry.
  187. if(this == walk)
  188. break;
  189. // Match!
  190. if(this->className)
  191. {
  192. AssertISV(false, avar("ConsoleConstructor::setup - ConsoleMethod '%s::%s' collides with another of the same name.", this->className, this->funcName));
  193. }
  194. else
  195. {
  196. AssertISV(false, avar("ConsoleConstructor::setup - ConsoleFunction '%s' collides with another of the same name.", this->funcName));
  197. }
  198. }
  199. #endif
  200. }
  201. // We comment out the implementation of the Con namespace when doxygenizing because
  202. // otherwise Doxygen decides to ignore our docs in console.h
  203. #ifndef DOXYGENIZING
  204. namespace Con
  205. {
  206. static Vector<ConsumerCallback> gConsumers(__FILE__, __LINE__);
  207. static Vector< String > sInstantGroupStack( __FILE__, __LINE__ );
  208. static DataChunker consoleLogChunker;
  209. static Vector<ConsoleLogEntry> consoleLog(__FILE__, __LINE__);
  210. static bool consoleLogLocked;
  211. static bool logBufferEnabled=true;
  212. static S32 printLevel = 10;
  213. static FileStream consoleLogFile;
  214. static const char *defLogFileName = "console.log";
  215. static S32 consoleLogMode = 0;
  216. static bool active = false;
  217. static bool newLogFile;
  218. static const char *logFileName;
  219. static const S32 MaxCompletionBufferSize = 4096;
  220. static char completionBuffer[MaxCompletionBufferSize];
  221. static char tabBuffer[MaxCompletionBufferSize] = {0};
  222. static SimObjectPtr<SimObject> tabObject;
  223. static U32 completionBaseStart;
  224. static U32 completionBaseLen;
  225. String gInstantGroup;
  226. Con::ConsoleInputEvent smConsoleInput;
  227. /// Current script file name and root, these are registered as
  228. /// console variables.
  229. /// @{
  230. ///
  231. StringTableEntry gCurrentFile;
  232. StringTableEntry gCurrentRoot;
  233. /// @}
  234. S32 gObjectCopyFailures = -1;
  235. bool alwaysUseDebugOutput = true;
  236. bool useTimestamp = false;
  237. ConsoleFunctionGroupBegin( Clipboard, "Miscellaneous functions to control the clipboard and clear the console.");
  238. ConsoleFunction( cls, void, 1, 1, "()"
  239. "@brief Clears the console output.\n\n"
  240. "@ingroup Console")
  241. {
  242. if(consoleLogLocked)
  243. return;
  244. consoleLogChunker.freeBlocks();
  245. consoleLog.setSize(0);
  246. };
  247. ConsoleFunction( getClipboard, const char*, 1, 1, "()"
  248. "@brief Get text from the clipboard.\n\n"
  249. "@internal")
  250. {
  251. return Platform::getClipboard();
  252. };
  253. ConsoleFunction( setClipboard, bool, 2, 2, "(string text)"
  254. "@brief Set the system clipboard.\n\n"
  255. "@internal")
  256. {
  257. return Platform::setClipboard(argv[1]);
  258. };
  259. ConsoleFunctionGroupEnd( Clipboard );
  260. void postConsoleInput( RawData data );
  261. void init()
  262. {
  263. AssertFatal(active == false, "Con::init should only be called once.");
  264. // Set up general init values.
  265. active = true;
  266. logFileName = NULL;
  267. newLogFile = true;
  268. gWarnUndefinedScriptVariables = false;
  269. // Initialize subsystems.
  270. Namespace::init();
  271. ConsoleConstructor::setup();
  272. // Set up the parser(s)
  273. CON_ADD_PARSER(CMD, "cs", true); // TorqueScript
  274. // Setup the console types.
  275. ConsoleBaseType::initialize();
  276. // And finally, the ACR...
  277. AbstractClassRep::initialize();
  278. // Variables
  279. setVariable("Con::prompt", "% ");
  280. addVariable("Con::logBufferEnabled", TypeBool, &logBufferEnabled, "If true, the log buffer will be enabled.\n"
  281. "@ingroup Console\n");
  282. addVariable("Con::printLevel", TypeS32, &printLevel,
  283. "@brief This is deprecated.\n\n"
  284. "It is no longer in use and does nothing.\n"
  285. "@ingroup Console\n");
  286. addVariable("Con::warnUndefinedVariables", TypeBool, &gWarnUndefinedScriptVariables, "If true, a warning will be displayed in the console whenever a undefined variable is used in script.\n"
  287. "@ingroup Console\n");
  288. addVariable( "instantGroup", TypeRealString, &gInstantGroup, "The group that objects will be added to when they are created.\n"
  289. "@ingroup Console\n");
  290. addVariable("Con::objectCopyFailures", TypeS32, &gObjectCopyFailures, "If greater than zero then it counts the number of object creation "
  291. "failures based on a missing copy object and does not report an error..\n"
  292. "@ingroup Console\n");
  293. // Current script file name and root
  294. addVariable( "Con::File", TypeString, &gCurrentFile, "The currently executing script file.\n"
  295. "@ingroup FileSystem\n");
  296. addVariable( "Con::Root", TypeString, &gCurrentRoot, "The mod folder for the currently executing script file.\n"
  297. "@ingroup FileSystem\n" );
  298. // alwaysUseDebugOutput determines whether to send output to the platform's
  299. // "debug" system. see winConsole for an example.
  300. // in ship builds we don't expose this variable to script
  301. // and we set it to false by default (don't want to provide more information
  302. // to potential hackers). platform code should also ifdef out the code that
  303. // pays attention to this in ship builds (see winConsole.cpp)
  304. // note that enabling this can slow down your game
  305. // if you are running from the debugger and printing a lot of console messages.
  306. #ifndef TORQUE_SHIPPING
  307. addVariable("Con::alwaysUseDebugOutput", TypeBool, &alwaysUseDebugOutput,
  308. "@brief Determines whether to send output to the platform's \"debug\" system.\n\n"
  309. "@note This is disabled in shipping builds.\n"
  310. "@ingroup Console");
  311. #else
  312. alwaysUseDebugOutput = false;
  313. #endif
  314. // controls whether a timestamp is prepended to every console message
  315. addVariable("Con::useTimestamp", TypeBool, &useTimestamp, "If true a timestamp is prepended to every console message.\n"
  316. "@ingroup Console\n");
  317. // Plug us into the journaled console input signal.
  318. smConsoleInput.notify(postConsoleInput);
  319. }
  320. //--------------------------------------
  321. void shutdown()
  322. {
  323. AssertFatal(active == true, "Con::shutdown should only be called once.");
  324. active = false;
  325. smConsoleInput.remove(postConsoleInput);
  326. consoleLogFile.close();
  327. Namespace::shutdown();
  328. AbstractClassRep::shutdown();
  329. Compiler::freeConsoleParserList();
  330. }
  331. bool isActive()
  332. {
  333. return active;
  334. }
  335. bool isMainThread()
  336. {
  337. #ifdef TORQUE_MULTITHREAD
  338. return ThreadManager::isMainThread();
  339. #else
  340. // If we're single threaded we're always in the main thread.
  341. return true;
  342. #endif
  343. }
  344. //--------------------------------------
  345. void getLockLog(ConsoleLogEntry *&log, U32 &size)
  346. {
  347. consoleLogLocked = true;
  348. log = consoleLog.address();
  349. size = consoleLog.size();
  350. }
  351. void unlockLog()
  352. {
  353. consoleLogLocked = false;
  354. }
  355. U32 tabComplete(char* inputBuffer, U32 cursorPos, U32 maxResultLength, bool forwardTab)
  356. {
  357. // Check for null input.
  358. if (!inputBuffer[0])
  359. {
  360. return cursorPos;
  361. }
  362. // Cap the max result length.
  363. if (maxResultLength > MaxCompletionBufferSize)
  364. {
  365. maxResultLength = MaxCompletionBufferSize;
  366. }
  367. // See if this is the same partial text as last checked.
  368. if (dStrcmp(tabBuffer, inputBuffer))
  369. {
  370. // If not...
  371. // Save it for checking next time.
  372. dStrcpy(tabBuffer, inputBuffer);
  373. // Scan backward from the cursor position to find the base to complete from.
  374. S32 p = cursorPos;
  375. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '.') && (inputBuffer[p - 1] != '('))
  376. {
  377. p--;
  378. }
  379. completionBaseStart = p;
  380. completionBaseLen = cursorPos - p;
  381. // Is this function being invoked on an object?
  382. if (inputBuffer[p - 1] == '.')
  383. {
  384. // If so...
  385. if (p <= 1)
  386. {
  387. // Bail if no object identifier.
  388. return cursorPos;
  389. }
  390. // Find the object identifier.
  391. S32 objLast = --p;
  392. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '('))
  393. {
  394. p--;
  395. }
  396. if (objLast == p)
  397. {
  398. // Bail if no object identifier.
  399. return cursorPos;
  400. }
  401. // Look up the object identifier.
  402. dStrncpy(completionBuffer, inputBuffer + p, objLast - p);
  403. completionBuffer[objLast - p] = 0;
  404. tabObject = Sim::findObject(completionBuffer);
  405. if (tabObject == NULL)
  406. {
  407. // Bail if not found.
  408. return cursorPos;
  409. }
  410. }
  411. else
  412. {
  413. // Not invoked on an object; we'll use the global namespace.
  414. tabObject = 0;
  415. }
  416. }
  417. // Chop off the input text at the cursor position.
  418. inputBuffer[cursorPos] = 0;
  419. // Try to find a completion in the appropriate namespace.
  420. const char *newText;
  421. if (tabObject != 0)
  422. {
  423. newText = tabObject->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  424. }
  425. else
  426. {
  427. // In the global namespace, we can complete on global vars as well as functions.
  428. if (inputBuffer[completionBaseStart] == '$')
  429. {
  430. newText = gEvalState.globalVars.tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  431. }
  432. else
  433. {
  434. newText = Namespace::global()->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  435. }
  436. }
  437. if (newText)
  438. {
  439. // If we got something, append it to the input text.
  440. S32 len = dStrlen(newText);
  441. if (len + completionBaseStart > maxResultLength)
  442. {
  443. len = maxResultLength - completionBaseStart;
  444. }
  445. dStrncpy(inputBuffer + completionBaseStart, newText, len);
  446. inputBuffer[completionBaseStart + len] = 0;
  447. // And set the cursor after it.
  448. cursorPos = completionBaseStart + len;
  449. }
  450. // Save the modified input buffer for checking next time.
  451. dStrcpy(tabBuffer, inputBuffer);
  452. // Return the new (maybe) cursor position.
  453. return cursorPos;
  454. }
  455. //------------------------------------------------------------------------------
  456. static void log(const char *string)
  457. {
  458. // Bail if we ain't logging.
  459. if (!consoleLogMode)
  460. {
  461. return;
  462. }
  463. // In mode 1, we open, append, close on each log write.
  464. if ((consoleLogMode & 0x3) == 1)
  465. {
  466. consoleLogFile.open(defLogFileName, Torque::FS::File::ReadWrite);
  467. }
  468. // Write to the log if its status is hunky-dory.
  469. if ((consoleLogFile.getStatus() == Stream::Ok) || (consoleLogFile.getStatus() == Stream::EOS))
  470. {
  471. consoleLogFile.setPosition(consoleLogFile.getStreamSize());
  472. // If this is the first write...
  473. if (newLogFile)
  474. {
  475. // Make a header.
  476. Platform::LocalTime lt;
  477. Platform::getLocalTime(lt);
  478. char buffer[128];
  479. dSprintf(buffer, sizeof(buffer), "//-------------------------- %d/%d/%d -- %02d:%02d:%02d -----\r\n",
  480. lt.month + 1,
  481. lt.monthday,
  482. lt.year + 1900,
  483. lt.hour,
  484. lt.min,
  485. lt.sec);
  486. consoleLogFile.write(dStrlen(buffer), buffer);
  487. newLogFile = false;
  488. if (consoleLogMode & 0x4)
  489. {
  490. // Dump anything that has been printed to the console so far.
  491. consoleLogMode -= 0x4;
  492. U32 size, line;
  493. ConsoleLogEntry *log;
  494. getLockLog(log, size);
  495. for (line = 0; line < size; line++)
  496. {
  497. consoleLogFile.write(dStrlen(log[line].mString), log[line].mString);
  498. consoleLogFile.write(2, "\r\n");
  499. }
  500. unlockLog();
  501. }
  502. }
  503. // Now write what we came here to write.
  504. consoleLogFile.write(dStrlen(string), string);
  505. consoleLogFile.write(2, "\r\n");
  506. }
  507. if ((consoleLogMode & 0x3) == 1)
  508. {
  509. consoleLogFile.close();
  510. }
  511. }
  512. //------------------------------------------------------------------------------
  513. static void _printf(ConsoleLogEntry::Level level, ConsoleLogEntry::Type type, const char* fmt, va_list argptr)
  514. {
  515. if (!active)
  516. return;
  517. Con::active = false;
  518. char buffer[8192];
  519. U32 offset = 0;
  520. if( gEvalState.traceOn && gEvalState.getStackDepth() > 0 )
  521. {
  522. offset = gEvalState.getStackDepth() * 3;
  523. for(U32 i = 0; i < offset; i++)
  524. buffer[i] = ' ';
  525. }
  526. if (useTimestamp)
  527. {
  528. static U32 startTime = Platform::getRealMilliseconds();
  529. U32 curTime = Platform::getRealMilliseconds() - startTime;
  530. offset += dSprintf(buffer + offset, sizeof(buffer) - offset, "[+%4d.%03d]", U32(curTime * 0.001), curTime % 1000);
  531. }
  532. dVsprintf(buffer + offset, sizeof(buffer) - offset, fmt, argptr);
  533. for(S32 i = 0; i < gConsumers.size(); i++)
  534. gConsumers[i](level, buffer);
  535. if(logBufferEnabled || consoleLogMode)
  536. {
  537. char *pos = buffer;
  538. while(*pos)
  539. {
  540. if(*pos == '\t')
  541. *pos = '^';
  542. pos++;
  543. }
  544. pos = buffer;
  545. for(;;)
  546. {
  547. char *eofPos = dStrchr(pos, '\n');
  548. if(eofPos)
  549. *eofPos = 0;
  550. log(pos);
  551. if(logBufferEnabled && !consoleLogLocked)
  552. {
  553. ConsoleLogEntry entry;
  554. entry.mLevel = level;
  555. entry.mType = type;
  556. #ifndef TORQUE_SHIPPING // this is equivalent to a memory leak, turn it off in ship build
  557. entry.mString = (const char *)consoleLogChunker.alloc(dStrlen(pos) + 1);
  558. dStrcpy(const_cast<char*>(entry.mString), pos);
  559. // This prevents infinite recursion if the console itself needs to
  560. // re-allocate memory to accommodate the new console log entry, and
  561. // LOG_PAGE_ALLOCS is defined. It is kind of a dirty hack, but the
  562. // uses for LOG_PAGE_ALLOCS are limited, and it is not worth writing
  563. // a lot of special case code to support this situation. -patw
  564. const bool save = Con::active;
  565. Con::active = false;
  566. consoleLog.push_back(entry);
  567. Con::active = save;
  568. #endif
  569. }
  570. if(!eofPos)
  571. break;
  572. pos = eofPos + 1;
  573. }
  574. }
  575. Con::active = true;
  576. }
  577. //------------------------------------------------------------------------------
  578. void printf(const char* fmt,...)
  579. {
  580. va_list argptr;
  581. va_start(argptr, fmt);
  582. _printf(ConsoleLogEntry::Normal, ConsoleLogEntry::General, fmt, argptr);
  583. va_end(argptr);
  584. }
  585. void warnf(ConsoleLogEntry::Type type, const char* fmt,...)
  586. {
  587. va_list argptr;
  588. va_start(argptr, fmt);
  589. _printf(ConsoleLogEntry::Warning, type, fmt, argptr);
  590. va_end(argptr);
  591. }
  592. void errorf(ConsoleLogEntry::Type type, const char* fmt,...)
  593. {
  594. va_list argptr;
  595. va_start(argptr, fmt);
  596. _printf(ConsoleLogEntry::Error, type, fmt, argptr);
  597. va_end(argptr);
  598. }
  599. void warnf(const char* fmt,...)
  600. {
  601. va_list argptr;
  602. va_start(argptr, fmt);
  603. _printf(ConsoleLogEntry::Warning, ConsoleLogEntry::General, fmt, argptr);
  604. va_end(argptr);
  605. }
  606. void errorf(const char* fmt,...)
  607. {
  608. va_list argptr;
  609. va_start(argptr, fmt);
  610. _printf(ConsoleLogEntry::Error, ConsoleLogEntry::General, fmt, argptr);
  611. va_end(argptr);
  612. }
  613. //---------------------------------------------------------------------------
  614. void setVariable(const char *name, const char *value)
  615. {
  616. // get the field info from the object..
  617. if(name[0] != '$' && dStrchr(name, '.') && !isFunction(name))
  618. {
  619. S32 len = dStrlen(name);
  620. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - name too long");
  621. dMemcpy(scratchBuffer, name, len+1);
  622. char * token = dStrtok(scratchBuffer, ".");
  623. SimObject * obj = Sim::findObject(token);
  624. if(!obj)
  625. return;
  626. token = dStrtok(0, ".\0");
  627. if(!token)
  628. return;
  629. while(token != NULL)
  630. {
  631. const char * val = obj->getDataField(StringTable->insert(token), 0);
  632. if(!val)
  633. return;
  634. char *fieldToken = token;
  635. token = dStrtok(0, ".\0");
  636. if(token)
  637. {
  638. obj = Sim::findObject(token);
  639. if(!obj)
  640. return;
  641. }
  642. else
  643. {
  644. obj->setDataField(StringTable->insert(fieldToken), 0, value);
  645. }
  646. }
  647. }
  648. name = prependDollar(name);
  649. gEvalState.globalVars.setVariable(StringTable->insert(name), value);
  650. }
  651. void setLocalVariable(const char *name, const char *value)
  652. {
  653. name = prependPercent(name);
  654. gEvalState.getCurrentFrame().setVariable(StringTable->insert(name), value);
  655. }
  656. void setBoolVariable(const char *varName, bool value)
  657. {
  658. setVariable(varName, value ? "1" : "0");
  659. }
  660. void setIntVariable(const char *varName, S32 value)
  661. {
  662. char scratchBuffer[32];
  663. dSprintf(scratchBuffer, sizeof(scratchBuffer), "%d", value);
  664. setVariable(varName, scratchBuffer);
  665. }
  666. void setFloatVariable(const char *varName, F32 value)
  667. {
  668. char scratchBuffer[32];
  669. dSprintf(scratchBuffer, sizeof(scratchBuffer), "%g", value);
  670. setVariable(varName, scratchBuffer);
  671. }
  672. //---------------------------------------------------------------------------
  673. void addConsumer(ConsumerCallback consumer)
  674. {
  675. gConsumers.push_back(consumer);
  676. }
  677. // dhc - found this empty -- trying what I think is a reasonable impl.
  678. void removeConsumer(ConsumerCallback consumer)
  679. {
  680. for(S32 i = 0; i < gConsumers.size(); i++)
  681. {
  682. if (gConsumers[i] == consumer)
  683. {
  684. // remove it from the list.
  685. gConsumers.erase(i);
  686. break;
  687. }
  688. }
  689. }
  690. void stripColorChars(char* line)
  691. {
  692. char* c = line;
  693. char cp = *c;
  694. while (cp)
  695. {
  696. if (cp < 18)
  697. {
  698. // Could be a color control character; let's take a closer look.
  699. if ((cp != 8) && (cp != 9) && (cp != 10) && (cp != 13))
  700. {
  701. // Yep... copy following chars forward over this.
  702. char* cprime = c;
  703. char cpp;
  704. do
  705. {
  706. cpp = *++cprime;
  707. *(cprime - 1) = cpp;
  708. }
  709. while (cpp);
  710. // Back up 1 so we'll check this position again post-copy.
  711. c--;
  712. }
  713. }
  714. cp = *++c;
  715. }
  716. }
  717. const char *getVariable(const char *name)
  718. {
  719. // get the field info from the object..
  720. if(name[0] != '$' && dStrchr(name, '.') && !isFunction(name))
  721. {
  722. S32 len = dStrlen(name);
  723. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - name too long");
  724. dMemcpy(scratchBuffer, name, len+1);
  725. char * token = dStrtok(scratchBuffer, ".");
  726. SimObject * obj = Sim::findObject(token);
  727. if(!obj)
  728. return("");
  729. token = dStrtok(0, ".\0");
  730. if(!token)
  731. return("");
  732. while(token != NULL)
  733. {
  734. const char * val = obj->getDataField(StringTable->insert(token), 0);
  735. if(!val)
  736. return("");
  737. token = dStrtok(0, ".\0");
  738. if(token)
  739. {
  740. obj = Sim::findObject(token);
  741. if(!obj)
  742. return("");
  743. }
  744. else
  745. return(val);
  746. }
  747. }
  748. name = prependDollar(name);
  749. return gEvalState.globalVars.getVariable(StringTable->insert(name));
  750. }
  751. const char *getLocalVariable(const char *name)
  752. {
  753. name = prependPercent(name);
  754. return gEvalState.getCurrentFrame().getVariable(StringTable->insert(name));
  755. }
  756. bool getBoolVariable(const char *varName, bool def)
  757. {
  758. const char *value = getVariable(varName);
  759. return *value ? dAtob(value) : def;
  760. }
  761. S32 getIntVariable(const char *varName, S32 def)
  762. {
  763. const char *value = getVariable(varName);
  764. return *value ? dAtoi(value) : def;
  765. }
  766. F32 getFloatVariable(const char *varName, F32 def)
  767. {
  768. const char *value = getVariable(varName);
  769. return *value ? dAtof(value) : def;
  770. }
  771. //---------------------------------------------------------------------------
  772. void addVariable( const char *name,
  773. S32 type,
  774. void *dptr,
  775. const char* usage )
  776. {
  777. gEvalState.globalVars.addVariable( name, type, dptr, usage );
  778. }
  779. void addConstant( const char *name,
  780. S32 type,
  781. const void *dptr,
  782. const char* usage )
  783. {
  784. Dictionary::Entry* entry = gEvalState.globalVars.addVariable( name, type, const_cast< void* >( dptr ), usage );
  785. entry->mIsConstant = true;
  786. }
  787. bool removeVariable(const char *name)
  788. {
  789. name = StringTable->lookup(prependDollar(name));
  790. return name!=0 && gEvalState.globalVars.removeVariable(name);
  791. }
  792. void addVariableNotify( const char *name, const NotifyDelegate &callback )
  793. {
  794. gEvalState.globalVars.addVariableNotify( name, callback );
  795. }
  796. void removeVariableNotify( const char *name, const NotifyDelegate &callback )
  797. {
  798. gEvalState.globalVars.removeVariableNotify( name, callback );
  799. }
  800. //---------------------------------------------------------------------------
  801. void addCommand( const char *nsName, const char *name,StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  802. {
  803. Namespace *ns = lookupNamespace(nsName);
  804. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  805. }
  806. void addCommand( const char *nsName, const char *name,VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  807. {
  808. Namespace *ns = lookupNamespace(nsName);
  809. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  810. }
  811. void addCommand( const char *nsName, const char *name,IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  812. {
  813. Namespace *ns = lookupNamespace(nsName);
  814. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  815. }
  816. void addCommand( const char *nsName, const char *name,FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  817. {
  818. Namespace *ns = lookupNamespace(nsName);
  819. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  820. }
  821. void addCommand( const char *nsName, const char *name,BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  822. {
  823. Namespace *ns = lookupNamespace(nsName);
  824. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  825. }
  826. void noteScriptCallback( const char *className, const char *funcName, const char *usage, ConsoleFunctionHeader* header )
  827. {
  828. Namespace *ns = lookupNamespace(className);
  829. ns->addScriptCallback( StringTable->insert(funcName), usage, header );
  830. }
  831. void markCommandGroup(const char * nsName, const char *name, const char* usage)
  832. {
  833. Namespace *ns = lookupNamespace(nsName);
  834. ns->markGroup(name,usage);
  835. }
  836. void beginCommandGroup(const char * nsName, const char *name, const char* usage)
  837. {
  838. markCommandGroup(nsName, name, usage);
  839. }
  840. void endCommandGroup(const char * nsName, const char *name)
  841. {
  842. markCommandGroup(nsName, name, NULL);
  843. }
  844. void addCommand( const char *name,StringCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  845. {
  846. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  847. }
  848. void addCommand( const char *name,VoidCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  849. {
  850. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  851. }
  852. void addCommand( const char *name,IntCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  853. {
  854. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  855. }
  856. void addCommand( const char *name,FloatCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  857. {
  858. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  859. }
  860. void addCommand( const char *name,BoolCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  861. {
  862. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  863. }
  864. const char *evaluate(const char* string, bool echo, const char *fileName)
  865. {
  866. if (echo)
  867. {
  868. if (string[0] == '%')
  869. Con::printf("%s", string);
  870. else
  871. Con::printf("%s%s", getVariable( "$Con::Prompt" ), string);
  872. }
  873. if(fileName)
  874. fileName = StringTable->insert(fileName);
  875. CodeBlock *newCodeBlock = new CodeBlock();
  876. return newCodeBlock->compileExec(fileName, string, false, fileName ? -1 : 0);
  877. }
  878. //------------------------------------------------------------------------------
  879. const char *evaluatef(const char* string, ...)
  880. {
  881. char buffer[4096];
  882. va_list args;
  883. va_start(args, string);
  884. dVsprintf(buffer, sizeof(buffer), string, args);
  885. CodeBlock *newCodeBlock = new CodeBlock();
  886. return newCodeBlock->compileExec(NULL, buffer, false, 0);
  887. }
  888. const char *execute(S32 argc, const char *argv[])
  889. {
  890. #ifdef TORQUE_MULTITHREAD
  891. if(isMainThread())
  892. {
  893. #endif
  894. Namespace::Entry *ent;
  895. StringTableEntry funcName = StringTable->insert(argv[0]);
  896. ent = Namespace::global()->lookup(funcName);
  897. if(!ent)
  898. {
  899. warnf(ConsoleLogEntry::Script, "%s: Unknown command.", argv[0]);
  900. // Clean up arg buffers, if any.
  901. STR.clearFunctionOffset();
  902. return "";
  903. }
  904. return ent->execute(argc, argv, &gEvalState);
  905. #ifdef TORQUE_MULTITHREAD
  906. }
  907. else
  908. {
  909. SimConsoleThreadExecCallback cb;
  910. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, false, &cb);
  911. Sim::postEvent(Sim::getRootGroup(), evt, Sim::getCurrentTime());
  912. return cb.waitForResult();
  913. }
  914. #endif
  915. }
  916. //------------------------------------------------------------------------------
  917. const char *execute(SimObject *object, S32 argc, const char *argv[], bool thisCallOnly)
  918. {
  919. static char idBuf[16];
  920. if(argc < 2)
  921. return "";
  922. // [neo, 10/05/2007 - #3010]
  923. // Make sure we don't get recursive calls, respect the flag!
  924. // Should we be calling handlesMethod() first?
  925. if( !thisCallOnly )
  926. {
  927. ICallMethod *com = dynamic_cast<ICallMethod *>(object);
  928. if(com)
  929. com->callMethodArgList(argc, argv, false);
  930. }
  931. if(object->getNamespace())
  932. {
  933. dSprintf(idBuf, sizeof(idBuf), "%d", object->getId());
  934. argv[1] = idBuf;
  935. StringTableEntry funcName = StringTable->insert(argv[0]);
  936. Namespace::Entry *ent = object->getNamespace()->lookup(funcName);
  937. if(ent == NULL)
  938. {
  939. //warnf(ConsoleLogEntry::Script, "%s: undefined for object '%s' - id %d", funcName, object->getName(), object->getId());
  940. // Clean up arg buffers, if any.
  941. STR.clearFunctionOffset();
  942. return "";
  943. }
  944. // Twiddle %this argument
  945. const char *oldArg1 = argv[1];
  946. dSprintf(idBuf, sizeof(idBuf), "%d", object->getId());
  947. argv[1] = idBuf;
  948. SimObject *save = gEvalState.thisObject;
  949. gEvalState.thisObject = object;
  950. const char *ret = ent->execute(argc, argv, &gEvalState);
  951. gEvalState.thisObject = save;
  952. // Twiddle it back
  953. argv[1] = oldArg1;
  954. return ret;
  955. }
  956. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), argv[0]);
  957. return "";
  958. }
  959. #define B( a ) const char* a = NULL
  960. #define A const char*
  961. inline const char*_executef(SimObject *obj, S32 checkArgc, S32 argc,
  962. A a, B(b), B(c), B(d), B(e), B(f), B(g), B(h), B(i), B(j), B(k))
  963. {
  964. #undef A
  965. #undef B
  966. const U32 maxArg = 12;
  967. AssertWarn(checkArgc == argc, "Incorrect arg count passed to Con::executef(SimObject*)");
  968. AssertFatal(argc <= maxArg - 1, "Too many args passed to Con::_executef(SimObject*). Please update the function to handle more.");
  969. const char* argv[maxArg];
  970. argv[0] = a;
  971. argv[1] = a;
  972. argv[2] = b;
  973. argv[3] = c;
  974. argv[4] = d;
  975. argv[5] = e;
  976. argv[6] = f;
  977. argv[7] = g;
  978. argv[8] = h;
  979. argv[9] = i;
  980. argv[10] = j;
  981. argv[11] = k;
  982. return execute(obj, argc+1, argv);
  983. }
  984. #define A const char*
  985. #define OBJ SimObject* obj
  986. const char *executef(OBJ, A a) { return _executef(obj, 1, 1, a); }
  987. const char *executef(OBJ, A a, A b) { return _executef(obj, 2, 2, a, b); }
  988. const char *executef(OBJ, A a, A b, A c) { return _executef(obj, 3, 3, a, b, c); }
  989. const char *executef(OBJ, A a, A b, A c, A d) { return _executef(obj, 4, 4, a, b, c, d); }
  990. const char *executef(OBJ, A a, A b, A c, A d, A e) { return _executef(obj, 5, 5, a, b, c, d, e); }
  991. const char *executef(OBJ, A a, A b, A c, A d, A e, A f) { return _executef(obj, 6, 6, a, b, c, d, e, f); }
  992. const char *executef(OBJ, A a, A b, A c, A d, A e, A f, A g) { return _executef(obj, 7, 7, a, b, c, d, e, f, g); }
  993. const char *executef(OBJ, A a, A b, A c, A d, A e, A f, A g, A h) { return _executef(obj, 8, 8, a, b, c, d, e, f, g, h); }
  994. const char *executef(OBJ, A a, A b, A c, A d, A e, A f, A g, A h, A i) { return _executef(obj, 9, 9, a, b, c, d, e, f, g, h, i); }
  995. const char *executef(OBJ, A a, A b, A c, A d, A e, A f, A g, A h, A i, A j) { return _executef(obj,10,10, a, b, c, d, e, f, g, h, i, j); }
  996. const char *executef(OBJ, A a, A b, A c, A d, A e, A f, A g, A h, A i, A j, A k) { return _executef(obj,11,11, a, b, c, d, e, f, g, h, i, j, k); }
  997. #undef A
  998. //------------------------------------------------------------------------------
  999. #define B( a ) const char* a = NULL
  1000. #define A const char*
  1001. inline const char*_executef(S32 checkArgc, S32 argc, A a, B(b), B(c), B(d), B(e), B(f), B(g), B(h), B(i), B(j))
  1002. {
  1003. #undef A
  1004. #undef B
  1005. const U32 maxArg = 10;
  1006. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef()");
  1007. AssertFatal(argc <= maxArg, "Too many args passed to Con::_executef(). Please update the function to handle more.");
  1008. const char* argv[maxArg];
  1009. argv[0] = a;
  1010. argv[1] = b;
  1011. argv[2] = c;
  1012. argv[3] = d;
  1013. argv[4] = e;
  1014. argv[5] = f;
  1015. argv[6] = g;
  1016. argv[7] = h;
  1017. argv[8] = i;
  1018. argv[9] = j;
  1019. return execute(argc, argv);
  1020. }
  1021. #define A const char*
  1022. const char *executef(A a) { return _executef(1, 1, a); }
  1023. const char *executef(A a, A b) { return _executef(2, 2, a, b); }
  1024. const char *executef(A a, A b, A c) { return _executef(3, 3, a, b, c); }
  1025. const char *executef(A a, A b, A c, A d) { return _executef(4, 4, a, b, c, d); }
  1026. const char *executef(A a, A b, A c, A d, A e) { return _executef(5, 5, a, b, c, d, e); }
  1027. const char *executef(A a, A b, A c, A d, A e, A f) { return _executef(6, 6, a, b, c, d, e, f); }
  1028. const char *executef(A a, A b, A c, A d, A e, A f, A g) { return _executef(7, 7, a, b, c, d, e, f, g); }
  1029. const char *executef(A a, A b, A c, A d, A e, A f, A g, A h) { return _executef(8, 8, a, b, c, d, e, f, g, h); }
  1030. const char *executef(A a, A b, A c, A d, A e, A f, A g, A h, A i) { return _executef(9, 9, a, b, c, d, e, f, g, h, i); }
  1031. const char *executef(A a, A b, A c, A d, A e, A f, A g, A h, A i, A j) { return _executef(10,10,a, b, c, d, e, f, g, h, i, j); }
  1032. #undef A
  1033. //------------------------------------------------------------------------------
  1034. bool isFunction(const char *fn)
  1035. {
  1036. const char *string = StringTable->lookup(fn);
  1037. if(!string)
  1038. return false;
  1039. else
  1040. return Namespace::global()->lookup(string) != NULL;
  1041. }
  1042. //------------------------------------------------------------------------------
  1043. void setLogMode(S32 newMode)
  1044. {
  1045. if ((newMode & 0x3) != (consoleLogMode & 0x3)) {
  1046. if (newMode && !consoleLogMode) {
  1047. // Enabling logging when it was previously disabled.
  1048. newLogFile = true;
  1049. }
  1050. if ((consoleLogMode & 0x3) == 2) {
  1051. // Changing away from mode 2, must close logfile.
  1052. consoleLogFile.close();
  1053. }
  1054. else if ((newMode & 0x3) == 2) {
  1055. #ifdef _XBOX
  1056. // Xbox is not going to support logging to a file. Use the OutputDebugStr
  1057. // log consumer
  1058. Platform::debugBreak();
  1059. #endif
  1060. // Starting mode 2, must open logfile.
  1061. consoleLogFile.open(defLogFileName, Torque::FS::File::Write);
  1062. }
  1063. consoleLogMode = newMode;
  1064. }
  1065. }
  1066. Namespace *lookupNamespace(const char *ns)
  1067. {
  1068. if(!ns)
  1069. return Namespace::global();
  1070. return Namespace::find(StringTable->insert(ns));
  1071. }
  1072. bool linkNamespaces(const char *parent, const char *child)
  1073. {
  1074. Namespace *pns = lookupNamespace(parent);
  1075. Namespace *cns = lookupNamespace(child);
  1076. if(pns && cns)
  1077. return cns->classLinkTo(pns);
  1078. return false;
  1079. }
  1080. bool unlinkNamespaces(const char *parent, const char *child)
  1081. {
  1082. Namespace *pns = lookupNamespace(parent);
  1083. Namespace *cns = lookupNamespace(child);
  1084. if(pns == cns)
  1085. {
  1086. Con::warnf("Con::unlinkNamespaces - trying to unlink '%s' from itself, aborting.", parent);
  1087. return false;
  1088. }
  1089. if(pns && cns)
  1090. return cns->unlinkClass(pns);
  1091. return false;
  1092. }
  1093. bool classLinkNamespaces(Namespace *parent, Namespace *child)
  1094. {
  1095. if(parent && child)
  1096. return child->classLinkTo(parent);
  1097. return false;
  1098. }
  1099. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, const EnumTable *tbl, BitSet32 flag)
  1100. {
  1101. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1102. AssertFatal(cbt, "Con::setData - could not resolve type ID!");
  1103. cbt->setData((void *) (((const char *)dptr) + index * cbt->getTypeSize()),argc, argv, tbl, flag);
  1104. }
  1105. const char *getData(S32 type, void *dptr, S32 index, const EnumTable *tbl, BitSet32 flag)
  1106. {
  1107. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1108. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1109. return cbt->getData((void *) (((const char *)dptr) + index * cbt->getTypeSize()), tbl, flag);
  1110. }
  1111. const char *getFormattedData(S32 type, const char *data, const EnumTable *tbl, BitSet32 flag)
  1112. {
  1113. ConsoleBaseType *cbt = ConsoleBaseType::getType( type );
  1114. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1115. // Datablock types are just a datablock
  1116. // name and don't ever need formatting.
  1117. if ( cbt->isDatablock() )
  1118. return data;
  1119. bool currWarn = gWarnUndefinedScriptVariables;
  1120. gWarnUndefinedScriptVariables = false;
  1121. const char* globalValue = Con::getVariable(data);
  1122. gWarnUndefinedScriptVariables = currWarn;
  1123. if (dStrlen(globalValue) > 0)
  1124. return globalValue;
  1125. void* variable = cbt->getNativeVariable();
  1126. if (variable)
  1127. {
  1128. Con::setData(type, variable, 0, 1, &data, tbl, flag);
  1129. const char* formattedVal = Con::getData(type, variable, 0, tbl, flag);
  1130. static const U32 bufSize = 2048;
  1131. char* returnBuffer = Con::getReturnBuffer(bufSize);
  1132. dSprintf(returnBuffer, bufSize, "%s\0", formattedVal );
  1133. cbt->deleteNativeVariable(variable);
  1134. return returnBuffer;
  1135. }
  1136. else
  1137. return data;
  1138. }
  1139. //------------------------------------------------------------------------------
  1140. bool isCurrentScriptToolScript()
  1141. {
  1142. // With a player build we ALWAYS return false
  1143. #ifndef TORQUE_TOOLS
  1144. return false;
  1145. #else
  1146. const StringTableEntry cbFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1147. if(cbFullPath == NULL)
  1148. return false;
  1149. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1150. return dStrnicmp(exePath, cbFullPath, dStrlen(exePath)) == 0;
  1151. #endif
  1152. }
  1153. //------------------------------------------------------------------------------
  1154. StringTableEntry getModNameFromPath(const char *path)
  1155. {
  1156. if(path == NULL || *path == 0)
  1157. return NULL;
  1158. char buf[1024];
  1159. buf[0] = 0;
  1160. if(path[0] == '/' || path[1] == ':')
  1161. {
  1162. // It's an absolute path
  1163. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1164. U32 len = dStrlen(exePath);
  1165. if(dStrnicmp(exePath, path, len) == 0)
  1166. {
  1167. const char *ptr = path + len + 1;
  1168. const char *slash = dStrchr(ptr, '/');
  1169. if(slash)
  1170. {
  1171. dStrncpy(buf, ptr, slash - ptr);
  1172. buf[slash - ptr] = 0;
  1173. }
  1174. else
  1175. return NULL;
  1176. }
  1177. else
  1178. return NULL;
  1179. }
  1180. else
  1181. {
  1182. const char *slash = dStrchr(path, '/');
  1183. if(slash)
  1184. {
  1185. dStrncpy(buf, path, slash - path);
  1186. buf[slash - path] = 0;
  1187. }
  1188. else
  1189. return NULL;
  1190. }
  1191. return StringTable->insert(buf);
  1192. }
  1193. void postConsoleInput( RawData data )
  1194. {
  1195. // Schedule this to happen at the next time event.
  1196. char *argv[2];
  1197. argv[0] = "eval";
  1198. argv[1] = ( char* ) data.data;
  1199. Sim::postCurrentEvent(Sim::getRootGroup(), new SimConsoleEvent(2, const_cast<const char**>(argv), false));
  1200. }
  1201. //------------------------------------------------------------------------------
  1202. void pushInstantGroup( String name )
  1203. {
  1204. sInstantGroupStack.push_back( gInstantGroup );
  1205. gInstantGroup = name;
  1206. }
  1207. void popInstantGroup()
  1208. {
  1209. if( sInstantGroupStack.empty() )
  1210. gInstantGroup = String::EmptyString;
  1211. else
  1212. {
  1213. gInstantGroup = sInstantGroupStack.last();
  1214. sInstantGroupStack.pop_back();
  1215. }
  1216. }
  1217. } // end of Console namespace
  1218. #endif
  1219. //=============================================================================
  1220. // API.
  1221. //=============================================================================
  1222. // MARK: ---- API ----
  1223. //-----------------------------------------------------------------------------
  1224. DefineEngineFunction( log, void, ( const char* message ),,
  1225. "@brief Logs a message to the console.\n\n"
  1226. "@param message The message text.\n"
  1227. "@note By default, messages will appear white in the console.\n"
  1228. "@ingroup Logging")
  1229. {
  1230. Con::printf( "%s", message );
  1231. }
  1232. //-----------------------------------------------------------------------------
  1233. DefineEngineFunction( logError, void, ( const char* message ),,
  1234. "@brief Logs an error message to the console.\n\n"
  1235. "@param message The message text.\n"
  1236. "@note By default, errors will appear red in the console.\n"
  1237. "@ingroup Logging")
  1238. {
  1239. Con::errorf( "%s", message );
  1240. }
  1241. //-----------------------------------------------------------------------------
  1242. DefineEngineFunction( logWarning, void, ( const char* message ),,
  1243. "@brief Logs a warning message to the console.\n\n"
  1244. "@param message The message text.\n\n"
  1245. "@note By default, warnings will appear turquoise in the console.\n"
  1246. "@ingroup Logging")
  1247. {
  1248. Con::warnf( "%s", message );
  1249. }