console.h 54 KB

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