console.cpp 77 KB

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