console.cpp 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632
  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 std::move(val);
  1410. }
  1411. if(object->getNamespace())
  1412. {
  1413. U32 ident = object->getId();
  1414. const char* oldIdent = 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. return std::move(ret);
  1431. }
  1432. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), funcName);
  1433. STR.clearFunctionOffset();
  1434. return std::move(ConsoleValue());
  1435. }
  1436. ConsoleValue execute(SimObject *object, S32 argc, ConsoleValue argv[], bool thisCallOnly)
  1437. {
  1438. if(argc < 2)
  1439. {
  1440. STR.clearFunctionOffset();
  1441. return std::move(ConsoleValue());
  1442. }
  1443. ConsoleStackFrameSaver stackSaver;
  1444. stackSaver.save();
  1445. if (object->getNamespace() || !thisCallOnly)
  1446. {
  1447. if (isMainThread())
  1448. {
  1449. return std::move(_internalExecute(object, argc, argv, thisCallOnly));
  1450. }
  1451. else
  1452. {
  1453. SimConsoleThreadExecCallback cb;
  1454. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, true, &cb);
  1455. Sim::postEvent(object, evt, Sim::getCurrentTime());
  1456. }
  1457. }
  1458. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), argv[0].getString());
  1459. STR.clearFunctionOffset();
  1460. return std::move(ConsoleValue());
  1461. }
  1462. ConsoleValue execute(SimObject *object, S32 argc, const char *argv[], bool thisCallOnly)
  1463. {
  1464. ConsoleStackFrameSaver stackSaver;
  1465. stackSaver.save();
  1466. StringArrayToConsoleValueWrapper args(argc, argv);
  1467. return std::move(execute(object, args.count(), args, thisCallOnly));
  1468. }
  1469. inline ConsoleValue _executef(SimObject *obj, S32 checkArgc, S32 argc, ConsoleValue *argv)
  1470. {
  1471. const U32 maxArg = 12;
  1472. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef(SimObject*)");
  1473. AssertFatal(argc <= maxArg - 1, "Too many args passed to Con::_executef(SimObject*). Please update the function to handle more.");
  1474. return std::move(execute(obj, argc, argv));
  1475. }
  1476. //------------------------------------------------------------------------------
  1477. inline ConsoleValue _executef(S32 checkArgc, S32 argc, ConsoleValue *argv)
  1478. {
  1479. const U32 maxArg = 10;
  1480. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef()");
  1481. AssertFatal(argc <= maxArg, "Too many args passed to Con::_executef(). Please update the function to handle more.");
  1482. return std::move(execute(argc, argv));
  1483. }
  1484. //------------------------------------------------------------------------------
  1485. bool isFunction(const char *fn)
  1486. {
  1487. if (CInterface::isMethod(NULL, fn)) return true;
  1488. const char *string = StringTable->lookup(fn);
  1489. if(!string)
  1490. return false;
  1491. else
  1492. return Namespace::global()->lookup(string) != NULL;
  1493. }
  1494. //------------------------------------------------------------------------------
  1495. void setLogMode(S32 newMode)
  1496. {
  1497. if ((newMode & 0x3) != (consoleLogMode & 0x3)) {
  1498. if (newMode && !consoleLogMode) {
  1499. // Enabling logging when it was previously disabled.
  1500. newLogFile = true;
  1501. }
  1502. if ((consoleLogMode & 0x3) == 2) {
  1503. // Changing away from mode 2, must close logfile.
  1504. consoleLogFile.close();
  1505. }
  1506. else if ((newMode & 0x3) == 2) {
  1507. #ifdef _XBOX
  1508. // Xbox is not going to support logging to a file. Use the OutputDebugStr
  1509. // log consumer
  1510. Platform::debugBreak();
  1511. #endif
  1512. // Starting mode 2, must open logfile.
  1513. consoleLogFile.open(defLogFileName, Torque::FS::File::Write);
  1514. }
  1515. consoleLogMode = newMode;
  1516. }
  1517. }
  1518. Namespace *lookupNamespace(const char *ns)
  1519. {
  1520. if(!ns)
  1521. return Namespace::global();
  1522. return Namespace::find(StringTable->insert(ns));
  1523. }
  1524. bool linkNamespaces(const char *parent, const char *child)
  1525. {
  1526. Namespace *pns = lookupNamespace(parent);
  1527. Namespace *cns = lookupNamespace(child);
  1528. if(pns && cns)
  1529. return cns->classLinkTo(pns);
  1530. return false;
  1531. }
  1532. bool unlinkNamespaces(const char *parent, const char *child)
  1533. {
  1534. Namespace *pns = lookupNamespace(parent);
  1535. Namespace *cns = lookupNamespace(child);
  1536. if(pns == cns)
  1537. {
  1538. Con::warnf("Con::unlinkNamespaces - trying to unlink '%s' from itself, aborting.", parent);
  1539. return false;
  1540. }
  1541. if(pns && cns)
  1542. return cns->unlinkClass(pns);
  1543. return false;
  1544. }
  1545. bool classLinkNamespaces(Namespace *parent, Namespace *child)
  1546. {
  1547. if(parent && child)
  1548. return child->classLinkTo(parent);
  1549. return false;
  1550. }
  1551. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, const EnumTable *tbl, BitSet32 flag)
  1552. {
  1553. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1554. AssertFatal(cbt, "Con::setData - could not resolve type ID!");
  1555. cbt->setData((void *) (((const char *)dptr) + index * cbt->getTypeSize()),argc, argv, tbl, flag);
  1556. }
  1557. const char *getData(S32 type, void *dptr, S32 index, const EnumTable *tbl, BitSet32 flag)
  1558. {
  1559. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1560. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1561. return cbt->getData((void *) (((const char *)dptr) + index * cbt->getTypeSize()), tbl, flag);
  1562. }
  1563. const char *getFormattedData(S32 type, const char *data, const EnumTable *tbl, BitSet32 flag)
  1564. {
  1565. ConsoleBaseType *cbt = ConsoleBaseType::getType( type );
  1566. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1567. // Datablock types are just a datablock
  1568. // name and don't ever need formatting.
  1569. if ( cbt->isDatablock() )
  1570. return data;
  1571. bool currWarn = gWarnUndefinedScriptVariables;
  1572. gWarnUndefinedScriptVariables = false;
  1573. const char* globalValue = Con::getVariable(data);
  1574. gWarnUndefinedScriptVariables = currWarn;
  1575. if (dStrlen(globalValue) > 0)
  1576. return globalValue;
  1577. void* variable = cbt->getNativeVariable();
  1578. if (variable)
  1579. {
  1580. Con::setData(type, variable, 0, 1, &data, tbl, flag);
  1581. const char* formattedVal = Con::getData(type, variable, 0, tbl, flag);
  1582. static const U32 bufSize = 2048;
  1583. char* returnBuffer = Con::getReturnBuffer(bufSize);
  1584. dSprintf(returnBuffer, bufSize, "%s\0", formattedVal );
  1585. cbt->deleteNativeVariable(variable);
  1586. return returnBuffer;
  1587. }
  1588. else
  1589. return data;
  1590. }
  1591. //------------------------------------------------------------------------------
  1592. bool isCurrentScriptToolScript()
  1593. {
  1594. // With a player build we ALWAYS return false
  1595. #ifndef TORQUE_TOOLS
  1596. return false;
  1597. #else
  1598. const StringTableEntry cbFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1599. if(cbFullPath == NULL)
  1600. return false;
  1601. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1602. return dStrnicmp(exePath, cbFullPath, dStrlen(exePath)) == 0;
  1603. #endif
  1604. }
  1605. //------------------------------------------------------------------------------
  1606. StringTableEntry getModNameFromPath(const char *path)
  1607. {
  1608. if(path == NULL || *path == 0)
  1609. return NULL;
  1610. char buf[1024];
  1611. buf[0] = 0;
  1612. if(path[0] == '/' || path[1] == ':')
  1613. {
  1614. // It's an absolute path
  1615. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1616. U32 len = dStrlen(exePath);
  1617. if(dStrnicmp(exePath, path, len) == 0)
  1618. {
  1619. const char *ptr = path + len + 1;
  1620. const char *slash = dStrchr(ptr, '/');
  1621. if(slash)
  1622. {
  1623. dStrncpy(buf, ptr, slash - ptr);
  1624. buf[slash - ptr] = 0;
  1625. }
  1626. else
  1627. return NULL;
  1628. }
  1629. else
  1630. return NULL;
  1631. }
  1632. else
  1633. {
  1634. const char *slash = dStrchr(path, '/');
  1635. if(slash)
  1636. {
  1637. dStrncpy(buf, path, slash - path);
  1638. buf[slash - path] = 0;
  1639. }
  1640. else
  1641. return NULL;
  1642. }
  1643. return StringTable->insert(buf);
  1644. }
  1645. void postConsoleInput( RawData data )
  1646. {
  1647. // Schedule this to happen at the next time event.
  1648. ConsoleValue argv[2];
  1649. argv[0].setString("eval");
  1650. argv[1].setString(reinterpret_cast<const char*>(data.data));
  1651. Sim::postCurrentEvent(Sim::getRootGroup(), new SimConsoleEvent(2, argv, false));
  1652. }
  1653. //------------------------------------------------------------------------------
  1654. void pushInstantGroup( String name )
  1655. {
  1656. sInstantGroupStack.push_back( gInstantGroup );
  1657. gInstantGroup = name;
  1658. }
  1659. void popInstantGroup()
  1660. {
  1661. if( sInstantGroupStack.empty() )
  1662. gInstantGroup = String::EmptyString;
  1663. else
  1664. {
  1665. gInstantGroup = sInstantGroupStack.last();
  1666. sInstantGroupStack.pop_back();
  1667. }
  1668. }
  1669. typedef HashMap<StringTableEntry, StringTableEntry> typePathExpandoMap;
  1670. static typePathExpandoMap PathExpandos;
  1671. //-----------------------------------------------------------------------------
  1672. void addPathExpando(const char* pExpandoName, const char* pPath)
  1673. {
  1674. // Sanity!
  1675. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1676. AssertFatal(pPath != NULL, "Expando path cannot be NULL.");
  1677. // Fetch expando name.
  1678. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1679. // Fetch the length of the path.
  1680. S32 pathLength = dStrlen(pPath);
  1681. char pathBuffer[1024];
  1682. // Sanity!
  1683. if (pathLength == 0 || pathLength >= sizeof(pathBuffer))
  1684. {
  1685. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1686. return;
  1687. }
  1688. // Strip repeat slashes.
  1689. if (!Con::stripRepeatSlashes(pathBuffer, pPath, sizeof(pathBuffer)))
  1690. {
  1691. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1692. return;
  1693. }
  1694. // Fetch new path length.
  1695. pathLength = dStrlen(pathBuffer);
  1696. // Sanity!
  1697. if (pathLength == 0)
  1698. {
  1699. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1700. return;
  1701. }
  1702. // Remove any terminating slash.
  1703. if (pathBuffer[pathLength - 1] == '/')
  1704. pathBuffer[pathLength - 1] = 0;
  1705. // Fetch expanded path.
  1706. StringTableEntry expandedPath = StringTable->insert(pathBuffer);
  1707. // Info.
  1708. #if defined(TORQUE_DEBUG)
  1709. Con::printf("Adding path expando of '%s' as '%s'.", expandoName, expandedPath);
  1710. #endif
  1711. // Find any existing path expando.
  1712. typePathExpandoMap::iterator expandoItr = PathExpandos.find(pExpandoName);
  1713. // Does the expando exist?
  1714. if (expandoItr != PathExpandos.end())
  1715. {
  1716. // Yes, so modify the path.
  1717. expandoItr->value = expandedPath;
  1718. return;
  1719. }
  1720. // Insert expando.
  1721. PathExpandos.insert(expandoName, expandedPath);
  1722. }
  1723. //-----------------------------------------------------------------------------
  1724. StringTableEntry getPathExpando(const char* pExpandoName)
  1725. {
  1726. // Sanity!
  1727. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1728. // Fetch expando name.
  1729. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1730. // Find any existing path expando.
  1731. typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
  1732. // Does the expando exist?
  1733. if (expandoItr != PathExpandos.end())
  1734. {
  1735. // Yes, so return it.
  1736. return expandoItr->value;
  1737. }
  1738. // Not found.
  1739. return NULL;
  1740. }
  1741. //-----------------------------------------------------------------------------
  1742. void removePathExpando(const char* pExpandoName)
  1743. {
  1744. // Sanity!
  1745. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1746. // Fetch expando name.
  1747. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1748. // Find any existing path expando.
  1749. typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
  1750. // Does the expando exist?
  1751. if (expandoItr == PathExpandos.end())
  1752. {
  1753. // No, so warn.
  1754. #if defined(TORQUE_DEBUG)
  1755. Con::warnf("Removing path expando of '%s' but it does not exist.", expandoName);
  1756. #endif
  1757. return;
  1758. }
  1759. // Info.
  1760. #if defined(TORQUE_DEBUG)
  1761. Con::printf("Removing path expando of '%s' as '%s'.", expandoName, expandoItr->value);
  1762. #endif
  1763. // Remove expando.
  1764. PathExpandos.erase(expandoItr);
  1765. }
  1766. //-----------------------------------------------------------------------------
  1767. bool isPathExpando(const char* pExpandoName)
  1768. {
  1769. // Sanity!
  1770. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1771. // Fetch expando name.
  1772. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1773. return PathExpandos.contains(expandoName);
  1774. }
  1775. //-----------------------------------------------------------------------------
  1776. U32 getPathExpandoCount(void)
  1777. {
  1778. return PathExpandos.size();
  1779. }
  1780. //-----------------------------------------------------------------------------
  1781. StringTableEntry getPathExpandoKey(U32 expandoIndex)
  1782. {
  1783. // Finish if index is out of range.
  1784. if (expandoIndex >= PathExpandos.size())
  1785. return NULL;
  1786. // Find indexed iterator.
  1787. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1788. while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
  1789. return expandoItr->key;
  1790. }
  1791. //-----------------------------------------------------------------------------
  1792. StringTableEntry getPathExpandoValue(U32 expandoIndex)
  1793. {
  1794. // Finish if index is out of range.
  1795. if (expandoIndex >= PathExpandos.size())
  1796. return NULL;
  1797. // Find indexed iterator.
  1798. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1799. while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
  1800. return expandoItr->value;
  1801. }
  1802. //-----------------------------------------------------------------------------
  1803. bool expandPath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint, const bool ensureTrailingSlash)
  1804. {
  1805. char pathBuffer[2048];
  1806. const char* pSrc = pSrcPath;
  1807. char* pSlash;
  1808. // Fetch leading character.
  1809. const char leadingToken = *pSrc;
  1810. // Fetch following token.
  1811. const char followingToken = leadingToken != 0 ? pSrc[1] : 0;
  1812. // Expando.
  1813. if (leadingToken == '^')
  1814. {
  1815. // Initial prefix search.
  1816. const char* pPrefixSrc = pSrc + 1;
  1817. char* pPrefixDst = pathBuffer;
  1818. // Search for end of expando.
  1819. while (*pPrefixSrc != '/' && *pPrefixSrc != 0)
  1820. {
  1821. // Copy prefix character.
  1822. *pPrefixDst++ = *pPrefixSrc++;
  1823. }
  1824. // Yes, so terminate the expando string.
  1825. *pPrefixDst = 0;
  1826. // Fetch the expando path.
  1827. StringTableEntry expandoPath = getPathExpando(pathBuffer);
  1828. // Does the expando exist?
  1829. if (expandoPath == NULL)
  1830. {
  1831. // No, so error.
  1832. Con::errorf("expandPath() : Could not find path expando '%s' for path '%s'.", pathBuffer, pSrcPath);
  1833. // Are we ensuring the trailing slash?
  1834. if (ensureTrailingSlash)
  1835. {
  1836. // Yes, so ensure it.
  1837. Con::ensureTrailingSlash(pDstPath, pSrcPath, size);
  1838. }
  1839. else
  1840. {
  1841. // No, so just use the source path.
  1842. dStrcpy(pDstPath, pSrcPath, size);
  1843. }
  1844. return false;
  1845. }
  1846. // Skip the expando and the following slash.
  1847. pSrc += dStrlen(pathBuffer) + 1;
  1848. // Format the output path.
  1849. dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", expandoPath, pSrc);
  1850. // Are we ensuring the trailing slash?
  1851. if (ensureTrailingSlash)
  1852. {
  1853. // Yes, so ensure it.
  1854. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1855. }
  1856. // Strip repeat slashes.
  1857. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1858. return true;
  1859. }
  1860. // Script-Relative.
  1861. if (leadingToken == '.')
  1862. {
  1863. // Fetch the code-block file-path.
  1864. const StringTableEntry codeblockFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1865. // Do we have a code block full path?
  1866. if (codeblockFullPath == NULL)
  1867. {
  1868. // No, so error.
  1869. Con::errorf("expandPath() : Could not find relative path from code-block for path '%s'.", pSrcPath);
  1870. // Are we ensuring the trailing slash?
  1871. if (ensureTrailingSlash)
  1872. {
  1873. // Yes, so ensure it.
  1874. Con::ensureTrailingSlash(pDstPath, pSrcPath, size);
  1875. }
  1876. else
  1877. {
  1878. // No, so just use the source path.
  1879. dStrcpy(pDstPath, pSrcPath, size);
  1880. }
  1881. return false;
  1882. }
  1883. // Yes, so use it as the prefix.
  1884. dStrncpy(pathBuffer, codeblockFullPath, sizeof(pathBuffer) - 1);
  1885. // Find the final slash in the code-block.
  1886. pSlash = dStrrchr(pathBuffer, '/');
  1887. // Is this a parent directory token?
  1888. if (followingToken == '.')
  1889. {
  1890. // Yes, so terminate after the slash so we include it.
  1891. pSlash[1] = 0;
  1892. }
  1893. else
  1894. {
  1895. // No, it's a current directory token so terminate at the slash so we don't include it.
  1896. pSlash[0] = 0;
  1897. // Skip the current directory token.
  1898. pSrc++;
  1899. }
  1900. // Format the output path.
  1901. dStrncat(pathBuffer, "/", sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1902. dStrncat(pathBuffer, pSrc, sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1903. // Are we ensuring the trailing slash?
  1904. if (ensureTrailingSlash)
  1905. {
  1906. // Yes, so ensure it.
  1907. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1908. }
  1909. // Strip repeat slashes.
  1910. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1911. return true;
  1912. }
  1913. // All else.
  1914. //Using a special case here because the code below barfs on trying to build a full path for apk reading
  1915. #ifdef TORQUE_OS_ANDROID
  1916. if (leadingToken == '/' || strstr(pSrcPath, "/") == NULL)
  1917. Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
  1918. else
  1919. dSprintf(pathBuffer, sizeof(pathBuffer), "/%s", pSrcPath);
  1920. #else
  1921. Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
  1922. #endif
  1923. // Are we ensuring the trailing slash?
  1924. if (ensureTrailingSlash)
  1925. {
  1926. // Yes, so ensure it.
  1927. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1928. }
  1929. // Strip repeat slashes.
  1930. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1931. return true;
  1932. }
  1933. //-----------------------------------------------------------------------------
  1934. bool isBasePath(const char* SrcPath, const char* pBasePath)
  1935. {
  1936. char expandBuffer[1024], expandBaseBuffer[1024];
  1937. Con::expandPath(expandBuffer, sizeof(expandBuffer), SrcPath);
  1938. Con::expandPath(expandBaseBuffer, sizeof(expandBaseBuffer), pBasePath);
  1939. return dStrnicmp(expandBaseBuffer, expandBuffer, dStrlen(expandBaseBuffer)) == 0;
  1940. }
  1941. //-----------------------------------------------------------------------------
  1942. void collapsePath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint)
  1943. {
  1944. // Check path against expandos. If there are multiple matches, choose the
  1945. // expando that produces the shortest relative path.
  1946. char pathBuffer[2048];
  1947. // Fetch expando count.
  1948. const U32 expandoCount = getPathExpandoCount();
  1949. // Iterate expandos.
  1950. U32 expandoRelativePathLength = U32_MAX;
  1951. for (U32 expandoIndex = 0; expandoIndex < expandoCount; ++expandoIndex)
  1952. {
  1953. // Fetch expando value (path).
  1954. StringTableEntry expandoValue = getPathExpandoValue(expandoIndex);
  1955. // Skip if not the base path.
  1956. if (!isBasePath(pSrcPath, expandoValue))
  1957. continue;
  1958. // Fetch path relative to expando path.
  1959. StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, expandoValue);
  1960. // If the relative path is simply a period
  1961. if (relativePath[0] == '.')
  1962. relativePath++;
  1963. if (dStrlen(relativePath) > expandoRelativePathLength)
  1964. {
  1965. // This expando covers less of the path than any previous one found.
  1966. // We will keep the previous one.
  1967. continue;
  1968. }
  1969. // Keep track of the relative path length
  1970. expandoRelativePathLength = dStrlen(relativePath);
  1971. // Fetch expando key (name).
  1972. StringTableEntry expandoName = getPathExpandoKey(expandoIndex);
  1973. // Format against expando.
  1974. dSprintf(pathBuffer, sizeof(pathBuffer), "^%s/%s", expandoName, relativePath);
  1975. }
  1976. // Check if we've found a suitable expando
  1977. if (expandoRelativePathLength != U32_MAX)
  1978. {
  1979. // Strip repeat slashes.
  1980. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1981. return;
  1982. }
  1983. // Fetch the working directory.
  1984. StringTableEntry workingDirectory = pWorkingDirectoryHint != NULL ? pWorkingDirectoryHint : Platform::getCurrentDirectory();
  1985. // Fetch path relative to current directory.
  1986. StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, workingDirectory);
  1987. // If the relative path is simply a period
  1988. if (relativePath[0] == '.' && relativePath[1] != '.')
  1989. relativePath++;
  1990. // Format against expando.
  1991. dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", workingDirectory, relativePath);
  1992. // Strip repeat slashes.
  1993. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1994. }
  1995. void ensureTrailingSlash(char* pDstPath, const char* pSrcPath, S32 dstSize)
  1996. {
  1997. // Copy to target.
  1998. dStrcpy(pDstPath, pSrcPath, dstSize);
  1999. // Find trailing character index.
  2000. S32 trailIndex = dStrlen(pDstPath);
  2001. // Ignore if empty string.
  2002. if (trailIndex == 0)
  2003. return;
  2004. // Finish if the trailing slash already exists.
  2005. if (pDstPath[trailIndex - 1] == '/')
  2006. return;
  2007. // Add trailing slash.
  2008. pDstPath[trailIndex++] = '/';
  2009. pDstPath[trailIndex] = 0;
  2010. }
  2011. //-----------------------------------------------------------------------------
  2012. StringTableEntry getDSOPath(const char *scriptPath)
  2013. {
  2014. #ifndef TORQUE2D_TOOLS_FIXME
  2015. // [tom, 11/17/2006] Force old behavior for the player. May not want to do this.
  2016. const char *slash = dStrrchr(scriptPath, '/');
  2017. if (slash != NULL)
  2018. return StringTable->insertn(scriptPath, slash - scriptPath, true);
  2019. slash = dStrrchr(scriptPath, ':');
  2020. if (slash != NULL)
  2021. return StringTable->insertn(scriptPath, (slash - scriptPath) + 1, true);
  2022. return "";
  2023. #else
  2024. char relPath[1024], dsoPath[1024];
  2025. bool isPrefs = false;
  2026. // [tom, 11/17/2006] Prefs are handled slightly differently to avoid dso name clashes
  2027. StringTableEntry prefsPath = Platform::getPrefsPath();
  2028. if (dStrnicmp(scriptPath, prefsPath, dStrlen(prefsPath)) == 0)
  2029. {
  2030. relPath[0] = 0;
  2031. isPrefs = true;
  2032. }
  2033. else
  2034. {
  2035. StringTableEntry strippedPath = Platform::stripBasePath(scriptPath);
  2036. dStrcpy(relPath, strippedPath, 1024);
  2037. char *slash = dStrrchr(relPath, '/');
  2038. if (slash)
  2039. *slash = 0;
  2040. }
  2041. const char *overridePath;
  2042. if (!isPrefs)
  2043. overridePath = Con::getVariable("$Scripts::OverrideDSOPath");
  2044. else
  2045. overridePath = prefsPath;
  2046. if (overridePath && *overridePath)
  2047. Platform::makeFullPathName(relPath, dsoPath, sizeof(dsoPath), overridePath);
  2048. else
  2049. {
  2050. char t[1024];
  2051. dSprintf(t, sizeof(t), "compiledScripts/%s", relPath);
  2052. Platform::makeFullPathName(t, dsoPath, sizeof(dsoPath), Platform::getPrefsPath());
  2053. }
  2054. return StringTable->insert(dsoPath);
  2055. #endif
  2056. }
  2057. //-----------------------------------------------------------------------------
  2058. bool stripRepeatSlashes(char* pDstPath, const char* pSrcPath, S32 dstSize)
  2059. {
  2060. // Note original destination.
  2061. char* pOriginalDst = pDstPath;
  2062. // Reset last source character.
  2063. char lastSrcChar = 0;
  2064. // Search source...
  2065. while (dstSize > 0)
  2066. {
  2067. // Fetch characters.
  2068. const char srcChar = *pSrcPath++;
  2069. // Do we have a repeat slash?
  2070. if (srcChar == '/' && lastSrcChar == '/')
  2071. {
  2072. // Yes, so skip it.
  2073. continue;
  2074. }
  2075. // No, so copy character.
  2076. *pDstPath++ = srcChar;
  2077. // Finish if end of source.
  2078. if (srcChar == 0)
  2079. return true;
  2080. // Reduce room left in destination.
  2081. dstSize--;
  2082. // Set last character.
  2083. lastSrcChar = srcChar;
  2084. }
  2085. // Terminate the destination string as we ran out of room.
  2086. *pOriginalDst = 0;
  2087. // Fail!
  2088. return false;
  2089. }
  2090. } // end of Console namespace
  2091. #endif
  2092. //=============================================================================
  2093. // API.
  2094. //=============================================================================
  2095. // MARK: ---- API ----
  2096. //-----------------------------------------------------------------------------
  2097. DefineEngineFunction( log, void, ( const char* message ),,
  2098. "@brief Logs a message to the console.\n\n"
  2099. "@param message The message text.\n"
  2100. "@note By default, messages will appear white in the console.\n"
  2101. "@ingroup Logging")
  2102. {
  2103. Con::printf( "%s", message );
  2104. }
  2105. //-----------------------------------------------------------------------------
  2106. DefineEngineFunction( logError, void, ( const char* message ),,
  2107. "@brief Logs an error message to the console.\n\n"
  2108. "@param message The message text.\n"
  2109. "@note By default, errors will appear red in the console.\n"
  2110. "@ingroup Logging")
  2111. {
  2112. Con::errorf( "%s", message );
  2113. }
  2114. //-----------------------------------------------------------------------------
  2115. DefineEngineFunction( logWarning, void, ( const char* message ),,
  2116. "@brief Logs a warning message to the console.\n\n"
  2117. "@param message The message text.\n\n"
  2118. "@note By default, warnings will appear turquoise in the console.\n"
  2119. "@ingroup Logging")
  2120. {
  2121. Con::warnf( "%s", message );
  2122. }
  2123. //------------------------------------------------------------------------------
  2124. ConsoleValueToStringArrayWrapper::ConsoleValueToStringArrayWrapper(int targc, ConsoleValue *targv)
  2125. {
  2126. argv = new const char*[targc];
  2127. argc = targc;
  2128. for (S32 i = 0; i < targc; i++)
  2129. {
  2130. argv[i] = dStrdup(targv[i].getString());
  2131. }
  2132. }
  2133. ConsoleValueToStringArrayWrapper::~ConsoleValueToStringArrayWrapper()
  2134. {
  2135. for (S32 i = 0; i< argc; i++)
  2136. {
  2137. dFree(argv[i]);
  2138. }
  2139. delete[] argv;
  2140. }
  2141. StringArrayToConsoleValueWrapper::StringArrayToConsoleValueWrapper(int targc, const char** targv)
  2142. {
  2143. argv = new ConsoleValue[targc]();
  2144. argc = targc;
  2145. for (int i=0; i<targc; i++)
  2146. {
  2147. argv[i].setString(targv[i]);
  2148. }
  2149. }
  2150. StringArrayToConsoleValueWrapper::~StringArrayToConsoleValueWrapper()
  2151. {
  2152. delete[] argv;
  2153. }
  2154. //------------------------------------------------------------------------------
  2155. ConsoleValue _BaseEngineConsoleCallbackHelper::_exec()
  2156. {
  2157. if( mThis )
  2158. {
  2159. // Cannot invoke callback until object has been registered
  2160. if (mThis->isProperlyAdded())
  2161. {
  2162. ConsoleValue returnValue = Con::_internalExecute( mThis, mArgc, mArgv, false );
  2163. mArgc = mInitialArgc; // reset
  2164. return std::move(returnValue);
  2165. }
  2166. STR.clearFunctionOffset();
  2167. mArgc = mInitialArgc; // reset
  2168. return std::move(ConsoleValue());
  2169. }
  2170. ConsoleValue returnValue = std::move(Con::_internalExecute( mArgc, mArgv ));
  2171. mArgc = mInitialArgc; // reset args
  2172. return std::move(returnValue);
  2173. }
  2174. ConsoleValue _BaseEngineConsoleCallbackHelper::_execLater(SimConsoleThreadExecEvent *evt)
  2175. {
  2176. mArgc = mInitialArgc; // reset args
  2177. Sim::postEvent((SimObject*)Sim::getRootGroup(), evt, Sim::getCurrentTime());
  2178. return std::move(evt->getCB().waitForResult());
  2179. }
  2180. //------------------------------------------------------------------------------
  2181. void ConsoleStackFrameSaver::save()
  2182. {
  2183. gCallStack.pushFrame(0);
  2184. mSaved = true;
  2185. }
  2186. void ConsoleStackFrameSaver::restore()
  2187. {
  2188. if (mSaved)
  2189. {
  2190. gCallStack.popFrame();
  2191. }
  2192. }