console.cpp 76 KB

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