console.cpp 80 KB

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