console.h 54 KB

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