console.h 53 KB

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