console.h 54 KB

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