console.h 54 KB

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