console.cpp 77 KB

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