console.h 53 KB

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