console.h 54 KB

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