console.h 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  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. #ifndef _CONSOLE_H_
  23. #define _CONSOLE_H_
  24. #ifndef _PLATFORM_H_
  25. #include "platform/platform.h"
  26. #endif
  27. #ifndef _BITSET_H_
  28. #include "core/bitSet.h"
  29. #endif
  30. #ifndef _REFBASE_H_
  31. #include "core/util/refBase.h"
  32. #endif
  33. #include <stdarg.h>
  34. #include "core/util/str.h"
  35. #include "core/util/journal/journaledSignal.h"
  36. #include "core/stringTable.h"
  37. #include <iostream>
  38. class SimObject;
  39. class Namespace;
  40. struct ConsoleFunctionHeader;
  41. class EngineEnumTable;
  42. typedef EngineEnumTable EnumTable;
  43. typedef U32 StringStackPtr;
  44. template< typename T > S32 TYPEID();
  45. /// @defgroup console_system Console System
  46. /// The Console system is the basis for logging, SimObject, and TorqueScript itself.
  47. ///
  48. /// @{
  49. /// Indicates that warnings about undefined script variables should be displayed.
  50. ///
  51. /// @note This is set and controlled by script.
  52. extern bool gWarnUndefinedScriptVariables;
  53. enum StringTableConstants
  54. {
  55. StringTagPrefixByte = 0x01 ///< Magic value prefixed to tagged strings.
  56. };
  57. /// Represents an entry in the log.
  58. struct ConsoleLogEntry
  59. {
  60. /// This field indicates the severity of the log entry.
  61. ///
  62. /// Log entries are filtered and displayed differently based on
  63. /// their severity. Errors are highlighted red, while normal entries
  64. /// are displayed as normal text. Often times, the engine will be
  65. /// configured to hide all log entries except warnings or errors,
  66. /// or to perform a special notification when it encounters an error.
  67. enum Level
  68. {
  69. Normal = 0,
  70. Warning,
  71. Error,
  72. NUM_CLASS
  73. } mLevel;
  74. /// Used to associate a log entry with a module.
  75. ///
  76. /// Log entries can come from different sources; for instance,
  77. /// the scripting engine, or the network code. This allows the
  78. /// logging system to be aware of where different log entries
  79. /// originated from.
  80. enum Type
  81. {
  82. General = 0,
  83. Assert,
  84. Script,
  85. GUI,
  86. Network,
  87. GGConnect,
  88. NUM_TYPE
  89. } mType;
  90. /// Indicates the actual log entry.
  91. ///
  92. /// This contains a description of the event being logged.
  93. /// For instance, "unable to access file", or "player connected
  94. /// successfully", or nearly anything else you might imagine.
  95. ///
  96. /// Typically, the description should contain a concise, descriptive
  97. /// string describing whatever is being logged. Whenever possible,
  98. /// include useful details like the name of the file being accessed,
  99. /// or the id of the player or GuiControl, so that if a log needs
  100. /// to be used to locate a bug, it can be done as painlessly as
  101. /// possible.
  102. const char *mString;
  103. };
  104. typedef const char *StringTableEntry;
  105. enum ConsoleValueType
  106. {
  107. cvNULL = -5,
  108. cvInteger = -4,
  109. cvFloat = -3,
  110. cvString = -2,
  111. cvSTEntry = -1,
  112. cvConsoleValueType = 0
  113. };
  114. class ConsoleValue
  115. {
  116. public:
  117. #pragma warning( push )
  118. #pragma warning( disable : 4201 ) // warning C4201: nonstandard extension used : nameless struct/union
  119. union
  120. {
  121. struct
  122. {
  123. F64 f;
  124. S64 i;
  125. char* s;
  126. };
  127. struct
  128. {
  129. void* dataPtr;
  130. EnumTable* enumTable;
  131. };
  132. };
  133. S32 type;
  134. U32 bufferLen;
  135. static DataChunker sConversionAllocator;
  136. char* convertToBuffer() const;
  137. const char* getConsoleData() const;
  138. TORQUE_FORCEINLINE void cleanupData()
  139. {
  140. if (type <= cvString && bufferLen > 0)
  141. {
  142. dFree(s);
  143. bufferLen = 0;
  144. }
  145. s = const_cast<char*>(StringTable->EmptyString());
  146. type = ConsoleValueType::cvNULL;
  147. }
  148. ConsoleValue()
  149. {
  150. type = ConsoleValueType::cvSTEntry;
  151. s = const_cast<char*>(StringTable->EmptyString());
  152. bufferLen = 0;
  153. }
  154. ConsoleValue(const ConsoleValue& ref)
  155. {
  156. type = ConsoleValueType::cvSTEntry;
  157. s = const_cast<char*>(StringTable->EmptyString());
  158. bufferLen = 0;
  159. switch (ref.type)
  160. {
  161. case cvNULL:
  162. std::cout << "Ref already cleared!";
  163. break;
  164. case cvInteger:
  165. setInt(ref.i);
  166. break;
  167. case cvFloat:
  168. setFloat(ref.f);
  169. break;
  170. case cvSTEntry:
  171. setStringTableEntry(ref.s);
  172. break;
  173. case cvString:
  174. setString(ref.s);
  175. break;
  176. default:
  177. setConsoleData(ref.type, ref.dataPtr, ref.enumTable);
  178. break;
  179. }
  180. }
  181. ConsoleValue& operator=(const ConsoleValue& ref)
  182. {
  183. switch (ref.type)
  184. {
  185. case cvNULL:
  186. std::cout << "Ref already cleared!";
  187. break;
  188. case cvInteger:
  189. setInt(ref.i);
  190. break;
  191. case cvFloat:
  192. setFloat(ref.f);
  193. break;
  194. case cvSTEntry:
  195. setStringTableEntry(ref.s);
  196. break;
  197. case cvString:
  198. setString(ref.s);
  199. break;
  200. default:
  201. setConsoleData(ref.type, ref.dataPtr, ref.enumTable);
  202. break;
  203. }
  204. return *this;
  205. }
  206. TORQUE_FORCEINLINE ~ConsoleValue()
  207. {
  208. cleanupData();
  209. }
  210. TORQUE_FORCEINLINE void reset()
  211. {
  212. setEmptyString();
  213. }
  214. TORQUE_FORCEINLINE F64 getFloat() const
  215. {
  216. if (type == ConsoleValueType::cvFloat)
  217. return f;
  218. if (type == ConsoleValueType::cvInteger)
  219. return i;
  220. if (type == ConsoleValueType::cvSTEntry)
  221. return s == StringTable->EmptyString() ? 0.0f : dAtof(s);
  222. if (type == ConsoleValueType::cvString)
  223. return dStrcmp(s, "") == 0 ? 0.0f : dAtof(s);
  224. return dAtof(getConsoleData());
  225. }
  226. TORQUE_FORCEINLINE S64 getInt() const
  227. {
  228. if (type == ConsoleValueType::cvInteger)
  229. return i;
  230. if (type == ConsoleValueType::cvFloat)
  231. return f;
  232. if (type == ConsoleValueType::cvSTEntry)
  233. return s == StringTable->EmptyString() ? 0 : dAtoi(s);
  234. if (type == ConsoleValueType::cvString)
  235. return dStrcmp(s, "") == 0 ? 0 : dAtoi(s);
  236. return dAtoi(getConsoleData());
  237. }
  238. TORQUE_FORCEINLINE const char* getString() const
  239. {
  240. if (isStringType())
  241. return s;
  242. if (isNumberType())
  243. return convertToBuffer();
  244. return getConsoleData();
  245. }
  246. TORQUE_FORCEINLINE operator const char* () const
  247. {
  248. return getString();
  249. }
  250. TORQUE_FORCEINLINE bool getBool() const
  251. {
  252. if (type == ConsoleValueType::cvInteger)
  253. return (bool)i;
  254. if (type == ConsoleValueType::cvFloat)
  255. return (bool)f;
  256. if (type == ConsoleValueType::cvSTEntry)
  257. return s == StringTable->EmptyString() ? false : dAtob(s);
  258. if (type == ConsoleValueType::cvString)
  259. return dStrcmp(s, "") == 0 ? false : dAtob(s);
  260. return dAtob(getConsoleData());
  261. }
  262. TORQUE_FORCEINLINE void setFloat(const F64 val)
  263. {
  264. cleanupData();
  265. type = ConsoleValueType::cvFloat;
  266. f = val;
  267. }
  268. TORQUE_FORCEINLINE void setInt(const S64 val)
  269. {
  270. cleanupData();
  271. type = ConsoleValueType::cvInteger;
  272. i = val;
  273. }
  274. TORQUE_FORCEINLINE void setString(const char* val)
  275. {
  276. setString(val, val != NULL ? dStrlen(val) : 0);
  277. }
  278. TORQUE_FORCEINLINE void setString(const char* val, S32 len)
  279. {
  280. if (len == 0)
  281. {
  282. setEmptyString();
  283. return;
  284. }
  285. cleanupData();
  286. type = ConsoleValueType::cvString;
  287. s = (char*)dMalloc(len + 1);
  288. bufferLen = len + 1;
  289. s[len] = '\0';
  290. dStrcpy(s, val, len + 1);
  291. }
  292. TORQUE_FORCEINLINE void setStringRef(const char* ref, S32 len)
  293. {
  294. cleanupData();
  295. type = ConsoleValueType::cvString;
  296. s = (char*)std::move(ref);
  297. bufferLen = len;
  298. }
  299. TORQUE_FORCEINLINE void setBool(const bool val)
  300. {
  301. cleanupData();
  302. type = ConsoleValueType::cvInteger;
  303. i = (int)val;
  304. }
  305. TORQUE_FORCEINLINE void setStringTableEntry(StringTableEntry val)
  306. {
  307. cleanupData();
  308. type = ConsoleValueType::cvSTEntry;
  309. s = (char*)(StringTable->insert(val));
  310. bufferLen = 0;
  311. }
  312. TORQUE_FORCEINLINE void setEmptyString()
  313. {
  314. setStringTableEntry(StringTable->EmptyString());
  315. }
  316. TORQUE_FORCEINLINE void setConsoleData(S32 inConsoleType, void* inDataPtr, const EnumTable* inEnumTable)
  317. {
  318. cleanupData();
  319. type = inConsoleType;
  320. dataPtr = inDataPtr;
  321. enumTable = const_cast<EnumTable*>(inEnumTable);
  322. };
  323. TORQUE_FORCEINLINE S32 getType() const
  324. {
  325. return type;
  326. }
  327. TORQUE_FORCEINLINE bool isStringType() const
  328. {
  329. return type == ConsoleValueType::cvString || type == ConsoleValueType::cvSTEntry;
  330. }
  331. TORQUE_FORCEINLINE bool isNumberType() const
  332. {
  333. return type == ConsoleValueType::cvFloat || type == ConsoleValueType::cvInteger;
  334. }
  335. TORQUE_FORCEINLINE bool isConsoleType() const
  336. {
  337. return type >= ConsoleValueType::cvConsoleValueType;
  338. }
  339. TORQUE_FORCEINLINE S32 getConsoleType() const
  340. {
  341. if(type >= ConsoleValueType::cvConsoleValueType)
  342. {
  343. return type;
  344. }
  345. else
  346. {
  347. return NULL;
  348. }
  349. }
  350. TORQUE_FORCEINLINE void setFastFloat(F64 flt)
  351. {
  352. type = ConsoleValueType::cvFloat;
  353. f = flt;
  354. }
  355. TORQUE_FORCEINLINE F64 getFastFloat() const
  356. {
  357. return f;
  358. }
  359. TORQUE_FORCEINLINE void setFastInt(S64 flt)
  360. {
  361. type = ConsoleValueType::cvInteger;
  362. i = flt;
  363. }
  364. TORQUE_FORCEINLINE S64 getFastInt() const
  365. {
  366. return i;
  367. }
  368. static void init();
  369. static void resetConversionBuffer();
  370. };
  371. // Transparently converts ConsoleValue[] to const char**
  372. class ConsoleValueToStringArrayWrapper
  373. {
  374. public:
  375. const char **argv;
  376. S32 argc;
  377. ConsoleValueToStringArrayWrapper(int targc, ConsoleValue* targv);
  378. ~ConsoleValueToStringArrayWrapper();
  379. const char* operator[](S32 idx) { return argv[idx]; }
  380. operator const char**() { return argv; }
  381. S32 count() { return argc; }
  382. };
  383. // Transparently converts const char** to ConsoleValue
  384. class StringArrayToConsoleValueWrapper
  385. {
  386. public:
  387. ConsoleValue *argv;
  388. S32 argc;
  389. StringArrayToConsoleValueWrapper(int targc, const char **targv);
  390. ~StringArrayToConsoleValueWrapper();
  391. ConsoleValue& operator[](int idx) { return argv[idx]; }
  392. operator ConsoleValue*() { return argv; }
  393. S32 count() { return argc; }
  394. };
  395. /// @defgroup console_callbacks Scripting Engine Callbacks
  396. ///
  397. /// The scripting engine makes heavy use of callbacks to represent
  398. /// function exposed to the scripting language. StringCallback,
  399. /// IntCallback, FloatCallback, VoidCallback, and BoolCallback all
  400. /// represent exposed script functions returning different types.
  401. ///
  402. /// ConsumerCallback is used with the function Con::addConsumer; functions
  403. /// registered with Con::addConsumer are called whenever something is outputted
  404. /// to the console. For instance, the TelnetConsole registers itself with the
  405. /// console so it can echo the console over the network.
  406. ///
  407. /// @note Callbacks to the scripting language - for instance, onExit(), which is
  408. /// a script function called when the engine is shutting down - are handled
  409. /// using Con::executef() and kin.
  410. /// @{
  411. ///
  412. typedef const char * (*StringCallback)(SimObject *obj, S32 argc, ConsoleValue argv[]);
  413. typedef S32(*IntCallback)(SimObject *obj, S32 argc, ConsoleValue argv[]);
  414. typedef F32(*FloatCallback)(SimObject *obj, S32 argc, ConsoleValue argv[]);
  415. typedef void(*VoidCallback)(SimObject *obj, S32 argc, ConsoleValue argv[]); // We have it return a value so things don't break..
  416. typedef bool(*BoolCallback)(SimObject *obj, S32 argc, ConsoleValue argv[]);
  417. typedef void(*ConsumerCallback)(U32 level, const char *consoleLine);
  418. /// @}
  419. /// @defgroup console_types Scripting Engine Type Functions
  420. ///
  421. /// @see Con::registerType
  422. /// @{
  423. typedef const char* (*GetDataFunction)(void *dptr, EnumTable *tbl, BitSet32 flag);
  424. typedef void(*SetDataFunction)(void *dptr, S32 argc, const char **argv, EnumTable *tbl, BitSet32 flag);
  425. /// @}
  426. /// This namespace contains the core of the console functionality.
  427. ///
  428. /// @section con_intro Introduction
  429. ///
  430. /// The console is a key part of Torque's architecture. It allows direct run-time control
  431. /// of many aspects of the engine.
  432. ///
  433. /// @nosubgrouping
  434. namespace Con
  435. {
  436. /// Various configuration constants.
  437. enum Constants
  438. {
  439. /// This is the version number associated with DSO files.
  440. ///
  441. /// If you make any changes to the way the scripting language works
  442. /// (such as DSO format changes, adding/removing op-codes) that would
  443. /// break compatibility, then you should increment this.
  444. ///
  445. /// If you make a really major change, increment it to the next multiple
  446. /// of ten.
  447. ///
  448. /// 12/29/04 - BJG - 33->34 Removed some opcodes, part of namespace upgrade.
  449. /// 12/30/04 - BJG - 34->35 Reordered some things, further general shuffling.
  450. /// 11/03/05 - BJG - 35->36 Integrated new debugger code.
  451. /// 09/08/06 - THB - 36->37 New opcode for internal names
  452. /// 09/15/06 - THB - 37->38 Added unit conversions
  453. /// 11/23/06 - THB - 38->39 Added recursive internal name operator
  454. /// 02/15/07 - THB - 39->40 Bumping to 40 for TGB since the console has been
  455. /// majorly hacked without the version number being bumped
  456. /// 02/16/07 - THB - 40->41 newmsg operator
  457. /// 06/15/07 - THB - 41->42 script types
  458. /// 07/31/07 - THB - 42->43 Patch from Andreas Kirsch: Added opcode to support nested new declarations.
  459. /// 09/12/07 - CAF - 43->44 remove newmsg operator
  460. /// 09/27/07 - RDB - 44->45 Patch from Andreas Kirsch: Added opcode to support correct void return
  461. /// 01/13/09 - TMS - 45->46 Added script assert
  462. /// 09/07/14 - jamesu - 46->47 64bit support
  463. /// 10/14/14 - jamesu - 47->48 Added opcodes to reduce reliance on strings in function calls
  464. /// 10/07/17 - JTH - 48->49 Added opcode for function pointers and revamp of interpreter
  465. /// from switch to function calls.
  466. /// 09/04/21 - JTH - 49->50 Rewrite of interpreter
  467. DSOVersion = 50,
  468. MaxLineLength = 512, ///< Maximum length of a line of console input.
  469. MaxDataTypes = 256 ///< Maximum number of registered data types.
  470. };
  471. /// @name Control Functions
  472. ///
  473. /// The console must be initialized and shutdown appropriately during the
  474. /// lifetime of the app. These functions are used to manage this behavior.
  475. ///
  476. /// @note Torque deals with this aspect of console management, so you don't need
  477. /// to call these functions in normal usage of the engine.
  478. /// @{
  479. /// Initializes the console.
  480. ///
  481. /// This performs the following steps:
  482. /// - Calls Namespace::init() to initialize the scripting namespace hierarchy.
  483. /// - Calls ConsoleConstructor::setup() to initialize globally defined console
  484. /// methods and functions.
  485. /// - Registers some basic global script variables.
  486. /// - Calls AbstractClassRep::init() to initialize Torque's class database.
  487. /// - Registers some basic global script functions that couldn't usefully
  488. /// be defined anywhere else.
  489. void init();
  490. /// Shuts down the console.
  491. ///
  492. /// This performs the following steps:
  493. /// - Closes the console log file.
  494. /// - Calls Namespace::shutdown() to shut down the scripting namespace hierarchy.
  495. void shutdown();
  496. /// Is the console active at this time?
  497. bool isActive();
  498. /// @}
  499. /// @name Console Consumers
  500. ///
  501. /// The console distributes its output through Torque by using
  502. /// consumers. Every time a new line is printed to the console,
  503. /// all the ConsumerCallbacks registered using addConsumer are
  504. /// called, in order.
  505. ///
  506. /// @note The GuiConsole control, which provides the on-screen
  507. /// in-game console, uses a different technique to render
  508. /// the console. It calls getLockLog() to lock the Vector
  509. /// of on-screen console entries, then it renders them as
  510. /// needed. While the Vector is locked, the console will
  511. /// not change the Vector. When the GuiConsole control is
  512. /// done with the console entries, it calls unlockLog()
  513. /// to tell the console that it is again safe to modify
  514. /// the Vector.
  515. ///
  516. /// @see TelnetConsole
  517. /// @see TelnetDebugger
  518. /// @see WinConsole
  519. /// @see MacCarbConsole
  520. /// @see StdConsole
  521. /// @see ConsoleLogger
  522. ///
  523. /// @{
  524. ///
  525. void addConsumer(ConsumerCallback cb);
  526. void removeConsumer(ConsumerCallback cb);
  527. typedef JournaledSignal<void(RawData)> ConsoleInputEvent;
  528. /// Called from the native consoles to provide lines of console input
  529. /// to process. This will schedule it for execution ASAP.
  530. extern ConsoleInputEvent smConsoleInput;
  531. /// @}
  532. /// @name Miscellaneous
  533. /// @{
  534. /// Remove color marking information from a string.
  535. ///
  536. /// @note It does this in-place, so be careful! It may
  537. /// potentially blast data if you're not careful.
  538. /// When in doubt, make a copy of the string first.
  539. void stripColorChars(char* line);
  540. /// Convert from a relative script path to an absolute script path.
  541. ///
  542. /// This is used in (among other places) the exec() script function, which
  543. /// takes a parameter indicating a script file and executes it. Script paths
  544. /// can be one of:
  545. /// - <b>Absolute:</b> <i>fps/foo/bar.tscript</i> Paths of this sort are passed
  546. /// through.
  547. /// - <b>Mod-relative:</b> <i>~/foo/bar.tscript</i> Paths of this sort have their
  548. /// replaced with the name of the current mod.
  549. /// - <b>File-relative:</b> <i>./baz/blip.tscript</i> Paths of this sort are
  550. /// calculated relative to the path of the current scripting file.
  551. ///
  552. /// @note This function determines paths relative to the currently executing
  553. /// CodeBlock. Calling it outside of script execution will result in
  554. /// it directly copying src to filename, since it won't know to what the
  555. /// path is relative!
  556. ///
  557. /// @param filename Pointer to string buffer to fill with absolute path.
  558. /// @param size Size of buffer pointed to by filename.
  559. /// @param src Original, possibly relative script path.
  560. bool expandScriptFilename(char *filename, U32 size, const char *src);
  561. bool expandGameScriptFilename(char *filename, U32 size, const char *src);
  562. bool expandToolScriptFilename(char *filename, U32 size, const char *src);
  563. bool collapseScriptFilename(char *filename, U32 size, const char *src);
  564. bool expandPath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint = NULL, const bool ensureTrailingSlash = false);
  565. void collapsePath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint = NULL);
  566. bool isBasePath(const char* SrcPath, const char* pBasePath);
  567. void ensureTrailingSlash(char* pDstPath, const char* pSrcPath, S32 dstSize);
  568. bool stripRepeatSlashes(char* pDstPath, const char* pSrcPath, S32 dstSize);
  569. StringTableEntry getDSOPath(const char *scriptPath);
  570. void addPathExpando(const char* pExpandoName, const char* pPath);
  571. void removePathExpando(const char* pExpandoName);
  572. bool isPathExpando(const char* pExpandoName);
  573. StringTableEntry getPathExpando(const char* pExpandoName);
  574. U32 getPathExpandoCount(void);
  575. StringTableEntry getPathExpandoKey(U32 expandoIndex);
  576. StringTableEntry getPathExpandoValue(U32 expandoIndex);
  577. bool isCurrentScriptToolScript();
  578. bool isScriptFile(const char* path);
  579. StringTableEntry getModNameFromPath(const char *path);
  580. /// Returns true if fn is a global scripting function.
  581. ///
  582. /// This looks in the global namespace. It also checks to see if fn
  583. /// is in the StringTable; if not, it returns false.
  584. bool isFunction(const char *fn);
  585. /// This is the basis for tab completion in the console.
  586. ///
  587. /// @note This is an internally used function. You probably don't
  588. /// care much about how this works.
  589. ///
  590. /// This function does some basic parsing to try to ascertain the namespace in which
  591. /// we are attempting to do tab completion, then bumps control off to the appropriate
  592. /// tabComplete function, either in SimObject or Namespace.
  593. ///
  594. /// @param inputBuffer Pointer to buffer containing starting data, or last result.
  595. /// @param cursorPos Location of cursor in this buffer. This is used to indicate
  596. /// what part of the string should be kept and what part should
  597. /// be advanced to the next match if any.
  598. /// @param maxResultLength Maximum amount of result data to put into inputBuffer. This
  599. /// is capped by MaxCompletionBufferSize.
  600. /// @param forwardTab Should we go forward to next match or backwards to previous
  601. /// match? True indicates forward.
  602. U32 tabComplete(char* inputBuffer, U32 cursorPos, U32 maxResultLength, bool forwardTab);
  603. /// @}
  604. /// @name Variable Management
  605. /// @{
  606. /// The delegate signature for the variable assignment notifications.
  607. ///
  608. /// @see addVariableNotify, removeVariableNotify
  609. typedef Delegate<void()> NotifyDelegate;
  610. /// Add a console variable that references the value of a variable in C++ code.
  611. ///
  612. /// If a value is assigned to the console variable the C++ variable is updated,
  613. /// and vice-versa.
  614. ///
  615. /// @param name Global console variable name to create.
  616. /// @param type The type of the C++ variable; see the ConsoleDynamicTypes enum for a complete list.
  617. /// @param pointer Pointer to the variable.
  618. /// @param usage Documentation string.
  619. ///
  620. /// @see ConsoleDynamicTypes
  621. void addVariable(const char *name,
  622. S32 type,
  623. void *pointer,
  624. const char* usage = NULL);
  625. /// Add a console constant that references the value of a constant in C++ code.
  626. ///
  627. /// @param name Global console constant name to create.
  628. /// @param type The type of the C++ constant; see the ConsoleDynamicTypes enum for a complete list.
  629. /// @param pointer Pointer to the constant.
  630. /// @param usage Documentation string.
  631. ///
  632. /// @see ConsoleDynamicTypes
  633. void addConstant(const char *name,
  634. S32 type,
  635. const void *pointer,
  636. const char* usage = NULL);
  637. /// Remove a console variable.
  638. ///
  639. /// @param name Global console variable name to remove
  640. /// @return true if variable existed before removal.
  641. bool removeVariable(const char *name);
  642. /// Add a callback for notification when a variable
  643. /// is assigned a new value.
  644. ///
  645. /// @param name An existing global console variable name.
  646. /// @param callback The notification delegate function.
  647. ///
  648. void addVariableNotify(const char *name, const NotifyDelegate &callback);
  649. /// Remove an existing variable assignment notification callback.
  650. ///
  651. /// @param name An existing global console variable name.
  652. /// @param callback The notification delegate function.
  653. ///
  654. void removeVariableNotify(const char *name, const NotifyDelegate &callback);
  655. /// Retrieve the string value to a locally scoped console variable
  656. ///
  657. /// @note The context of the variable is determined by gEvalState; that is,
  658. /// by the currently executing code.
  659. ///
  660. /// @param name Local console variable name to get
  661. const char* getLocalVariable(const char* name);
  662. /// @}
  663. /// @name Global Variable Accessors
  664. /// @{
  665. /// Assign a string value to a global console variable
  666. /// @param name Global console variable name to set
  667. /// @param value String value to assign to this variable.
  668. void setVariable(const char *name, const char *value);
  669. /// Retrieve the string value of a global console variable
  670. /// @param name Global Console variable name to query
  671. /// @return The string value of the variable or "" if the variable does not exist.
  672. const char* getVariable(const char* name, const char* def = "");
  673. /// Retrieve the string value of an object field
  674. /// @param name "object.field" string to query
  675. /// @return The string value of the variable or NULL if no object is specified
  676. const char* getObjectField(const char* name);
  677. /// Same as setVariable(), but for bools.
  678. void setBoolVariable(const char* name, bool var);
  679. /// Same as getVariable(), but for bools.
  680. ///
  681. /// @param name Name of the variable.
  682. /// @param def Default value to supply if no matching variable is found.
  683. bool getBoolVariable(const char* name, bool def = false);
  684. /// Same as setVariable(), but for ints.
  685. void setIntVariable(const char* name, S32 var);
  686. /// Same as getVariable(), but for ints.
  687. ///
  688. /// @param name Name of the variable.
  689. /// @param def Default value to supply if no matching variable is found.
  690. S32 getIntVariable(const char* name, S32 def = 0);
  691. /// Same as setVariable(), but for floats.
  692. void setFloatVariable(const char* name, F32 var);
  693. /// Same as getVariable(), but for floats.
  694. ///
  695. /// @param name Name of the variable.
  696. /// @param def Default value to supply if no matching variable is found.
  697. F32 getFloatVariable(const char* name, F32 def = .0f);
  698. /// @}
  699. /// @name Global Function Registration
  700. /// @{
  701. /// Register a C++ function with the console making it a global function callable from the scripting engine.
  702. ///
  703. /// @param name Name of the new function.
  704. /// @param cb Pointer to the function implementing the scripting call; a console callback function returning a specific type value.
  705. /// @param usage Documentation for this function. @ref console_autodoc
  706. /// @param minArgs Minimum number of arguments this function accepts
  707. /// @param maxArgs Maximum number of arguments this function accepts
  708. /// @param toolOnly Wether this is a TORQUE_TOOLS only function.
  709. /// @param header The extended function header.
  710. void addCommand(const char* name, StringCallback cb, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  711. void addCommand(const char* name, IntCallback cb, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  712. void addCommand(const char* name, FloatCallback cb, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  713. void addCommand(const char* name, VoidCallback cb, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  714. void addCommand(const char* name, BoolCallback cb, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  715. /// @}
  716. /// @name Namespace Function Registration
  717. /// @{
  718. /// Register a C++ function with the console making it callable
  719. /// as a method of the given namespace from the scripting engine.
  720. ///
  721. /// @param nameSpace Name of the namespace to associate the new function with; this is usually the name of a class.
  722. /// @param name Name of the new function.
  723. /// @param cb Pointer to the function implementing the scripting call; a console callback function returning a specific type value.
  724. /// @param usage Documentation for this function. @ref console_autodoc
  725. /// @param minArgs Minimum number of arguments this function accepts
  726. /// @param maxArgs Maximum number of arguments this function accepts
  727. /// @param toolOnly Wether this is a TORQUE_TOOLS only function.
  728. /// @param header The extended function header.
  729. void addCommand(const char *nameSpace, const char *name, StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  730. void addCommand(const char *nameSpace, const char *name, IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char*, const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  731. void addCommand(const char *nameSpace, const char *name, FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char*, const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  732. void addCommand(const char *nameSpace, const char *name, VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char*, const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  733. void addCommand(const char *nameSpace, const char *name, BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char*, const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  734. /// @}
  735. /// @name Special Purpose Registration
  736. ///
  737. /// These are special-purpose functions that exist to allow commands to be grouped, so
  738. /// that when we generate console docs, they can be more meaningfully presented.
  739. ///
  740. /// @ref console_autodoc "Click here for more information about console docs and grouping."
  741. ///
  742. /// @{
  743. void markCommandGroup(const char * nsName, const char *name, const char* usage = NULL);
  744. void beginCommandGroup(const char * nsName, const char *name, const char* usage);
  745. void endCommandGroup(const char * nsName, const char *name);
  746. void noteScriptCallback(const char *className, const char *funcName, const char *usage, ConsoleFunctionHeader* header = NULL);
  747. /// @}
  748. /// @name Console Output
  749. ///
  750. /// These functions process the formatted string and pass it to all the ConsumerCallbacks that are
  751. /// currently registered. The console log file and the console window callbacks are installed by default.
  752. ///
  753. /// @see addConsumer()
  754. /// @see removeConsumer()
  755. /// @{
  756. /// @param _format A stdlib printf style formatted out put string
  757. /// @param ... Variables to be written
  758. void printf(const char *_format, ...);
  759. /// @note The console window colors warning text as LIGHT GRAY.
  760. /// @param _format A stdlib printf style formatted out put string
  761. /// @param ... Variables to be written
  762. void warnf(const char *_format, ...);
  763. /// @note The console window colors warning text as RED.
  764. /// @param _format A stdlib printf style formatted out put string
  765. /// @param ... Variables to be written
  766. void errorf(const char *_format, ...);
  767. /// @note The console window colors warning text as LIGHT GRAY.
  768. /// @param type Allows you to associate the warning message with an internal module.
  769. /// @param _format A stdlib printf style formatted out put string
  770. /// @param ... Variables to be written
  771. /// @see Con::warnf()
  772. void warnf(ConsoleLogEntry::Type type, const char *_format, ...);
  773. /// @note The console window colors warning text as RED.
  774. /// @param type Allows you to associate the warning message with an internal module.
  775. /// @param _format A stdlib printf style formatted out put string
  776. /// @param ... Variables to be written
  777. /// @see Con::errorf()
  778. void errorf(ConsoleLogEntry::Type type, const char *_format, ...);
  779. //some additions from t2d
  780. /// Prints a separator to the console.
  781. inline void printSeparator(void) { printf("--------------------------------------------------------------------------------"); }
  782. /// Prints a separator to the console.
  783. inline void printBlankLine(void) { printf(""); }
  784. /// @}
  785. /// Returns true when called from the main thread, false otherwise
  786. bool isMainThread();
  787. /// @name Console Execution
  788. ///
  789. /// These are functions relating to the execution of script code.
  790. ///
  791. /// @{
  792. /// Call a script function from C/C++ code.
  793. ///
  794. /// @param argc Number of elements in the argv parameter
  795. /// @param argv A character string array containing the name of the function
  796. /// to call followed by the arguments to that function.
  797. /// @code
  798. /// // Call a Torque script function called mAbs, having one parameter.
  799. /// char* argv[] = {"abs", "-9"};
  800. /// char* result = execute(2, argv);
  801. /// @endcode
  802. /// NOTE: this function restores the console stack on return.
  803. ConsoleValue execute(S32 argc, const char* argv[]);
  804. ConsoleValue execute(S32 argc, ConsoleValue argv[]);
  805. /// Call a Torque Script member function of a SimObject from C/C++ code.
  806. /// @param object Object on which to execute the method call.
  807. /// @param argc Number of elements in the argv parameter (must be >2, see argv)
  808. /// @param argv A character string array containing the name of the member function
  809. /// to call followed by an empty parameter (gets filled with object ID)
  810. /// followed by arguments to that function.
  811. /// @code
  812. /// // Call the method setMode() on an object, passing it one parameter.
  813. ///
  814. /// char* argv[] = {"setMode", "", "2"};
  815. /// char* result = execute(mysimobject, 3, argv);
  816. /// @endcode
  817. /// NOTE: this function restores the console stack on return.
  818. ConsoleValue execute(SimObject *object, S32 argc, const char* argv[], bool thisCallOnly = false);
  819. ConsoleValue execute(SimObject *object, S32 argc, ConsoleValue argv[], bool thisCallOnly = false);
  820. /// @}
  821. /// @name Console Function Implementation Helpers
  822. ///
  823. /// The functions Con::getIntArg, Con::getFloatArg and Con::getArgBuffer(size) are used to
  824. /// allocate on the console stack string variables that will be passed into the next console
  825. // function called. This allows the console to avoid copying some data.
  826. ///
  827. /// getReturnBuffer lets you allocate stack space to return data in.
  828. /// @{
  829. ///
  830. char* getReturnBuffer(U32 bufferSize);
  831. char* getReturnBuffer(const char *stringToCopy);
  832. char* getReturnBuffer(const String& str);
  833. char* getReturnBuffer(const StringBuilder& str);
  834. char* getArgBuffer(U32 bufferSize);
  835. char* getFloatArg(F64 arg);
  836. char* getIntArg(S32 arg);
  837. char* getBoolArg(bool arg);
  838. char* getStringArg(const char* arg);
  839. char* getStringArg(const String& arg);
  840. /// @}
  841. /// @name Namespaces
  842. /// @{
  843. Namespace *lookupNamespace(const char *nsName);
  844. bool linkNamespaces(const char *parentName, const char *childName);
  845. bool unlinkNamespaces(const char *parentName, const char *childName);
  846. /// @note This should only be called from consoleObject.h
  847. bool classLinkNamespaces(Namespace *parent, Namespace *child);
  848. const char *getNamespaceList(Namespace *ns);
  849. /// @}
  850. /// @name Logging
  851. /// @{
  852. void getLockLog(ConsoleLogEntry * &log, U32 &size);
  853. void unlockLog(void);
  854. void setLogMode(S32 mode);
  855. /// @}
  856. /// @name Instant Group
  857. /// @{
  858. void pushInstantGroup(String name = String());
  859. void popInstantGroup();
  860. /// @}
  861. /// @name Dynamic Type System
  862. /// @{
  863. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, const EnumTable *tbl = NULL, BitSet32 flag = 0);
  864. const char *getData(S32 type, void *dptr, S32 index, const EnumTable *tbl = NULL, BitSet32 flag = 0);
  865. const char *getFormattedData(S32 type, const char *data, const EnumTable *tbl = NULL, BitSet32 flag = 0);
  866. /// @}
  867. };
  868. struct _EngineConsoleCallbackHelper;
  869. template<typename P1> struct _EngineConsoleExecCallbackHelper;
  870. namespace Con
  871. {
  872. /// @name Console Execution - executef
  873. /// {
  874. ///
  875. /// Implements a script function thunk which automatically converts parameters to relevant console types.
  876. /// Can be used as follows:
  877. /// - Con::executef("functionName", ...);
  878. /// - Con::executef(mySimObject, "functionName", ...);
  879. ///
  880. /// NOTE: if you get a rather cryptic template error coming through here, most likely you are trying to
  881. /// convert a parameter which EngineMarshallType does not have a specialization for.
  882. /// Another problem can occur if you do not include "console/simBase.h" and "console/engineAPI.h"
  883. /// since _EngineConsoleExecCallbackHelper and SimConsoleThreadExecCallback are required.
  884. ///
  885. /// @see _EngineConsoleExecCallbackHelper
  886. ///
  887. template<typename R, typename ...ArgTs>
  888. ConsoleValue executef(R r, ArgTs ...argTs)
  889. {
  890. _EngineConsoleExecCallbackHelper<R> callback(r);
  891. return (callback.template call<ConsoleValue>(argTs...));
  892. }
  893. /// }
  894. };
  895. extern void expandEscape(char *dest, const char *src);
  896. extern bool collapseEscape(char *buf);
  897. extern U32 HashPointer(StringTableEntry ptr);
  898. /// Extended information about a console function.
  899. struct ConsoleFunctionHeader
  900. {
  901. /// Return type string.
  902. const char* mReturnString;
  903. /// List of arguments taken by the function. Used for documentation.
  904. const char* mArgString;
  905. /// List of default argument values. Used for documentation.
  906. const char* mDefaultArgString;
  907. /// Whether this is a static method in a class.
  908. bool mIsStatic;
  909. ConsoleFunctionHeader(
  910. const char* returnString,
  911. const char* argString,
  912. const char* defaultArgString,
  913. bool isStatic = false)
  914. : mReturnString(returnString),
  915. mArgString(argString),
  916. mDefaultArgString(defaultArgString),
  917. mIsStatic(isStatic) {}
  918. };
  919. /// This is the backend for the ConsoleMethod()/ConsoleFunction() macros.
  920. ///
  921. /// See the group ConsoleConstructor Innards for specifics on how this works.
  922. ///
  923. /// @see @ref console_autodoc
  924. /// @nosubgrouping
  925. class ConsoleConstructor
  926. {
  927. public:
  928. /// @name Entry Type Fields
  929. ///
  930. /// One of these is set based on the type of entry we want
  931. /// inserted in the console.
  932. ///
  933. /// @ref console_autodoc
  934. /// @{
  935. StringCallback mSC; ///< A function/method that returns a string.
  936. IntCallback mIC; ///< A function/method that returns an int.
  937. FloatCallback mFC; ///< A function/method that returns a float.
  938. VoidCallback mVC; ///< A function/method that returns nothing.
  939. BoolCallback mBC; ///< A function/method that returns a bool.
  940. bool mGroup; ///< Indicates that this is a group marker.
  941. bool mNS; ///< Indicates that this is a namespace marker.
  942. /// @deprecated Unused.
  943. bool mCallback; ///< Is this a callback into script?
  944. /// @}
  945. /// Minimum number of arguments expected by the function.
  946. S32 mMina;
  947. /// Maximum number of arguments accepted by the funtion. Zero for varargs.
  948. S32 mMaxa;
  949. /// Name of the function/method.
  950. const char* mFuncName;
  951. /// Name of the class namespace to which to add the method.
  952. const char* mClassName;
  953. /// Usage string for documentation.
  954. const char* mUsage;
  955. /// Whether this is a TORQUE_TOOLS only function.
  956. bool mToolOnly;
  957. /// The extended function header.
  958. ConsoleFunctionHeader* mHeader;
  959. /// @name ConsoleConstructor Innards
  960. ///
  961. /// The ConsoleConstructor class is used as the backend for the ConsoleFunction() and
  962. /// ConsoleMethod() macros. The way it works takes advantage of several properties of
  963. /// C++.
  964. ///
  965. /// The ConsoleFunction()/ConsoleMethod() macros wrap the declaration of a ConsoleConstructor.
  966. ///
  967. /// @code
  968. /// // The definition of a ConsoleFunction using the macro
  969. /// ConsoleFunction(ExpandFilename, const char*, 2, 2, "(string filename)")
  970. /// {
  971. /// argc;
  972. /// char* ret = Con::getReturnBuffer( 1024 );
  973. /// Con::expandScriptFilename(ret, 1024, argv[1]);
  974. /// return ret;
  975. /// }
  976. ///
  977. /// // Resulting code
  978. /// static const char* cExpandFilename(SimObject *, S32, const char **argv);
  979. /// static ConsoleConstructor
  980. /// gExpandFilenameobj(NULL,"ExpandFilename", cExpandFilename,
  981. /// "(string filename)", 2, 2);
  982. /// static const char* cExpandFilename(SimObject *, S32 argc, const char **argv)
  983. /// {
  984. /// argc;
  985. /// char* ret = Con::getReturnBuffer( 1024 );
  986. /// Con::expandScriptFilename(ret, 1024, argv[1]);
  987. /// return ret;
  988. /// }
  989. ///
  990. /// // A similar thing happens when you do a ConsoleMethod.
  991. /// @endcode
  992. ///
  993. /// As you can see, several global items are defined when you use the ConsoleFunction method.
  994. /// The macro constructs the name of these items from the parameters you passed it. Your
  995. /// implementation of the console function is is placed in a function with a name based on
  996. /// the actual name of the console funnction. In addition, a ConsoleConstructor is declared.
  997. ///
  998. /// Because it is defined as a global, the constructor for the ConsoleConstructor is called
  999. /// before execution of main() is started. The constructor is called once for each global
  1000. /// ConsoleConstructor variable, in the order in which they were defined (this property only holds true
  1001. /// within file scope).
  1002. ///
  1003. /// We have ConsoleConstructor create a linked list at constructor time, by storing a static
  1004. /// pointer to the head of the list, and keeping a pointer to the next item in each instance
  1005. /// of ConsoleConstructor. init() is a helper function in this process, automatically filling
  1006. /// in commonly used fields and updating first and next as needed. In this way, a list of
  1007. /// items to add to the console is assemble in memory, ready for use, before we start
  1008. /// execution of the program proper.
  1009. ///
  1010. /// In Con::init(), ConsoleConstructor::setup() is called to process this prepared list. Each
  1011. /// item in the list is iterated over, and the appropriate Con namespace functions (usually
  1012. /// Con::addCommand) are invoked to register the ConsoleFunctions and ConsoleMethods in
  1013. /// the appropriate namespaces.
  1014. ///
  1015. /// @see Namespace
  1016. /// @see Con
  1017. /// @{
  1018. ///
  1019. ConsoleConstructor *mNext;
  1020. static ConsoleConstructor *mFirst;
  1021. void init(const char* cName, const char* fName, const char *usg, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1022. static void setup();
  1023. /// Validate there are no duplicate entries for this item.
  1024. void validate();
  1025. /// @}
  1026. /// @name Basic Console Constructors
  1027. /// @{
  1028. ConsoleConstructor(const char* className, const char* funcName, StringCallback sfunc, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1029. ConsoleConstructor(const char* className, const char* funcName, IntCallback ifunc, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1030. ConsoleConstructor(const char* className, const char* funcName, FloatCallback ffunc, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1031. ConsoleConstructor(const char* className, const char* funcName, VoidCallback vfunc, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1032. ConsoleConstructor(const char* className, const char* funcName, BoolCallback bfunc, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1033. /// @}
  1034. /// @name Magic Console Constructors
  1035. ///
  1036. /// These perform various pieces of "magic" related to consoleDoc functionality.
  1037. /// @ref console_autodoc
  1038. /// @{
  1039. /// Indicates a group marker. (A doxygen illusion)
  1040. ///
  1041. /// @see Con::markCommandGroup
  1042. /// @ref console_autodoc
  1043. ConsoleConstructor(const char *className, const char *groupName, const char* usage);
  1044. /// Indicates a callback declared with the DECLARE_SCRIPT_CALLBACK macro and friends.
  1045. ConsoleConstructor(const char *className, const char *callbackName, const char *usage, ConsoleFunctionHeader* header);
  1046. /// @}
  1047. };
  1048. /// An arbitrary fragment of auto-doc text for the script reference.
  1049. struct ConsoleDocFragment
  1050. {
  1051. /// The class in which to put the fragment. If NULL, the fragment
  1052. /// will be placed globally.
  1053. const char* mClass;
  1054. /// The definition to output for this fragment. NULL for fragments
  1055. /// not associated with a definition.
  1056. const char* mDefinition;
  1057. /// The documentation text.
  1058. const char* mText;
  1059. /// Next fragment in the global link chain.
  1060. ConsoleDocFragment* mNext;
  1061. /// First fragment in the global link chain.
  1062. static ConsoleDocFragment* smFirst;
  1063. ConsoleDocFragment(const char* text, const char* inClass = NULL, const char* definition = NULL)
  1064. : mClass(inClass),
  1065. mDefinition(definition),
  1066. mText(text),
  1067. mNext(smFirst)
  1068. {
  1069. smFirst = this;
  1070. }
  1071. };
  1072. /// Utility class to save and restore the current console stack frame
  1073. ///
  1074. class ConsoleStackFrameSaver
  1075. {
  1076. public:
  1077. bool mSaved;
  1078. ConsoleStackFrameSaver() : mSaved(false)
  1079. {
  1080. }
  1081. ~ConsoleStackFrameSaver()
  1082. {
  1083. restore();
  1084. }
  1085. void save();
  1086. void restore();
  1087. };
  1088. /// @name Global Console Definition Macros
  1089. ///
  1090. /// @note If TORQUE_DEBUG is defined, then we gather documentation information, and
  1091. /// do some extra sanity checks.
  1092. ///
  1093. /// @see ConsoleConstructor
  1094. /// @ref console_autodoc
  1095. /// @{
  1096. /// Define a C++ method that calls back to script on an object.
  1097. ///
  1098. /// @see consoleCallback.h
  1099. #define DECLARE_CALLBACK( returnType, name, args ) \
  1100. virtual returnType name ## _callback args
  1101. // O hackery of hackeries
  1102. #define conmethod_return_const return (const
  1103. #define conmethod_return_S32 return (S32
  1104. #define conmethod_return_F32 return (F32
  1105. #define conmethod_nullify(val)
  1106. #define conmethod_return_void conmethod_nullify(void
  1107. #define conmethod_return_bool return (bool
  1108. #if !defined(TORQUE_SHIPPING)
  1109. // Console function macros
  1110. # define ConsoleFunctionGroupBegin(groupName, usage) \
  1111. static ConsoleConstructor cfg_ConsoleFunctionGroup_##groupName##_GroupBegin(NULL,#groupName,usage)
  1112. # define ConsoleToolFunction(name,returnType,minArgs,maxArgs,usage1) \
  1113. returnType ctf_##name(SimObject *, S32, ConsoleValue *argv); \
  1114. ConsoleConstructor cc_##name##_obj(NULL,#name,ctf_##name,usage1,minArgs,maxArgs, true); \
  1115. returnType ctf_##name(SimObject *, S32 argc, ConsoleValue *argv)
  1116. # define ConsoleFunctionGroupEnd(groupName) \
  1117. static ConsoleConstructor cfg_##groupName##_GroupEnd(NULL,#groupName,NULL)
  1118. // Console method macros
  1119. # define ConsoleNamespace(className, usage) \
  1120. ConsoleConstructor cc_##className##_Namespace(#className, usage)
  1121. # define ConsoleMethodGroupBegin(className, groupName, usage) \
  1122. static ConsoleConstructor cc_##className##_##groupName##_GroupBegin(#className,#groupName,usage)
  1123. # define ConsoleMethodGroupEnd(className, groupName) \
  1124. static ConsoleConstructor cc_##className##_##groupName##_GroupEnd(#className,#groupName,NULL)
  1125. /// Add a fragment of auto-doc text to the console API reference.
  1126. /// @note There can only be one ConsoleDoc per source file.
  1127. # define ConsoleDoc( text ) \
  1128. namespace { \
  1129. ConsoleDocFragment _sDocFragment( text ); \
  1130. }
  1131. #else
  1132. // These do nothing if we don't want doc information.
  1133. # define ConsoleFunctionGroupBegin(groupName, usage)
  1134. # define ConsoleFunctionGroupEnd(groupName)
  1135. # define ConsoleNamespace(className, usage)
  1136. # define ConsoleMethodGroupBegin(className, groupName, usage)
  1137. # define ConsoleMethodGroupEnd(className, groupName)
  1138. // These are identical to what's above, we just want to null out the usage strings.
  1139. # define ConsoleFunction(name,returnType,minArgs,maxArgs,usage1) \
  1140. static returnType c##name(SimObject *, S32, ConsoleValue*); \
  1141. static ConsoleConstructor g##name##obj(NULL,#name,c##name,"",minArgs,maxArgs);\
  1142. static returnType c##name(SimObject *, S32 argc, ConsoleValue *argv)
  1143. # define ConsoleToolFunction(name,returnType,minArgs,maxArgs,usage1) \
  1144. static returnType c##name(SimObject *, S32, ConsoleValue*); \
  1145. static ConsoleConstructor g##name##obj(NULL,#name,c##name,"",minArgs,maxArgs, true);\
  1146. static returnType c##name(SimObject *, S32 argc, ConsoleValue *argv)
  1147. # define ConsoleMethod(className,name,returnType,minArgs,maxArgs,usage1) \
  1148. static inline returnType c##className##name(className *, S32, ConsoleValue *argv); \
  1149. static returnType c##className##name##caster(SimObject *object, S32 argc, ConsoleValue *argv) { \
  1150. conmethod_return_##returnType ) c##className##name(static_cast<className*>(object),argc,argv); \
  1151. }; \
  1152. static ConsoleConstructor \
  1153. className##name##obj(#className,#name,c##className##name##caster,"",minArgs,maxArgs); \
  1154. static inline returnType c##className##name(className *object, S32 argc, ConsoleValue *argv)
  1155. #define ConsoleDoc( text )
  1156. #endif
  1157. /// @}
  1158. /// @}
  1159. #endif // _CONSOLE_H_