console.h

Engine/source/console/console.h

More...

Classes:

class

This is the backend for the ConsoleMethod()/ConsoleFunction() macros.

class

An arbitrary fragment of auto-doc text for the script reference.

class

Extended information about a console function.

class

Represents an entry in the log.

class

Utility class to save and restore the current console stack frame.

Namespaces:

namespace

This namespace contains the core of the console functionality.

Global Console Definition Macros

note:

If TORQUE_DEBUG is defined, then we gather documentation information, and do some extra sanity checks.

see:

ConsoleConstructor console_autodoc

define
define
conmethod_return_bool() return (bool
define
define
define
define
ConsoleDoc(text)       namespace {                                           \
          _sDocFragment( text );           \
      }

Add a fragment of auto-doc text to the console API reference.

define
ConsoleFunctionGroupBegin(groupName, usage)       static  cfg_ConsoleFunctionGroup_##groupName##_GroupBegin(,#groupName,usage)
define
ConsoleFunctionGroupEnd(groupName)       static  cfg_##groupName##_GroupEnd(,#groupName,)
define
ConsoleMethodGroupBegin(className, groupName, usage)    static  cc_##className##_##groupName##_GroupBegin(#className,#groupName,usage)
define
ConsoleMethodGroupEnd(className, groupName)    static  cc_##className##_##groupName##_GroupEnd(#className,#groupName,)
define
ConsoleNamespace(className, usage)     cc_##className##_Namespace(#className, usage)
define
ConsoleToolFunction(name, returnType, minArgs, maxArgs, usage1)    returnType ctf_##name( *, ,  *argv); \
    cc_##name##_obj(,#name,ctf_##name,usage1,minArgs,maxArgs, true); \
   returnType ctf_##name( *,  argc,  *argv)
define
DECLARE_CALLBACK(returnType, name, args)    virtual returnType name ## _callback args

Define a C++ method that calls back to script on an object.

Public Enumerations

enum
StringTableConstants {  StringTagPrefixByte = 0x01
}

Public Typedefs

bool(*
BoolCallback )(SimObject *obj, S32 argc, ConsoleValueRef argv[])
void(*
ConsumerCallback )(U32 level, const char *consoleLine)
EnumTable 
F32(*
FloatCallback )(SimObject *obj, S32 argc, ConsoleValueRef argv[])
const char *(*
GetDataFunction )(void *dptr, EnumTable *tbl, BitSet32 flag)
S32(*
IntCallback )(SimObject *obj, S32 argc, ConsoleValueRef argv[])
void(*
SetDataFunction )(void *dptr, S32 argc, const char **argv, EnumTable *tbl, BitSet32 flag)
const char *(*
StringCallback )(SimObject *obj, S32 argc, ConsoleValueRef argv[])
StringStackPtr 
const char *
StringTableEntry 
void(*
VoidCallback )(SimObject *obj, S32 argc, ConsoleValueRef argv[])

Public Variables

bool

Indicates that warnings about undefined script variables should be displayed.

Public Functions

bool
collapseEscape(char * buf)
bool
expandEscape(char * dest, const char * src)

Return the type ID for the primary console type associated with the given native type.

Detailed Description

Global Console Definition Macros

note:

If TORQUE_DEBUG is defined, then we gather documentation information, and do some extra sanity checks.

see:

ConsoleConstructor console_autodoc

conmethod_nullify(val) 
conmethod_return_bool() return (bool
conmethod_return_const() return (
conmethod_return_F32() return (
conmethod_return_S32() return (
conmethod_return_void() (
ConsoleDoc(text)       namespace {                                           \
          _sDocFragment( text );           \
      }

Add a fragment of auto-doc text to the console API reference.

note:

There can only be one ConsoleDoc per source file.

ConsoleFunctionGroupBegin(groupName, usage)       static  cfg_ConsoleFunctionGroup_##groupName##_GroupBegin(,#groupName,usage)
ConsoleFunctionGroupEnd(groupName)       static  cfg_##groupName##_GroupEnd(,#groupName,)
ConsoleMethodGroupBegin(className, groupName, usage)    static  cc_##className##_##groupName##_GroupBegin(#className,#groupName,usage)
ConsoleMethodGroupEnd(className, groupName)    static  cc_##className##_##groupName##_GroupEnd(#className,#groupName,)
ConsoleNamespace(className, usage)     cc_##className##_Namespace(#className, usage)
ConsoleToolFunction(name, returnType, minArgs, maxArgs, usage1)    returnType ctf_##name( *, ,  *argv); \
    cc_##name##_obj(,#name,ctf_##name,usage1,minArgs,maxArgs, true); \
   returnType ctf_##name( *,  argc,  *argv)
DECLARE_CALLBACK(returnType, name, args)    virtual returnType name ## _callback args

Define a C++ method that calls back to script on an object.

see:

consoleCallback.h

Public Enumerations

StringTableConstants

Enumerator

StringTagPrefixByte = 0x01

Magic value prefixed to tagged strings.

Public Typedefs

typedef bool(* BoolCallback )(SimObject *obj, S32 argc, ConsoleValueRef argv[])
typedef void(* ConsumerCallback )(U32 level, const char *consoleLine)
typedef EngineEnumTable EnumTable 
typedef F32(* FloatCallback )(SimObject *obj, S32 argc, ConsoleValueRef argv[])
typedef const char *(* GetDataFunction )(void *dptr, EnumTable *tbl, BitSet32 flag)
typedef S32(* IntCallback )(SimObject *obj, S32 argc, ConsoleValueRef argv[])
typedef void(* SetDataFunction )(void *dptr, S32 argc, const char **argv, EnumTable *tbl, BitSet32 flag)
typedef const char *(* StringCallback )(SimObject *obj, S32 argc, ConsoleValueRef argv[])
typedef U32 StringStackPtr 
typedef const char * StringTableEntry 
typedef void(* VoidCallback )(SimObject *obj, S32 argc, ConsoleValueRef argv[])

Public Variables

bool gWarnUndefinedScriptVariables 

Indicates that warnings about undefined script variables should be displayed.

note:

This is set and controlled by script.

char * typeValueEmpty 

Public Functions

collapseEscape(char * buf)

dAtob(ConsoleValue & ref)

dAtof(ConsoleValueRef & ref)

dAtoi(ConsoleValueRef & ref)

expandEscape(char * dest, const char * src)

HashPointer(StringTableEntry ptr)

TYPEID()

Return the type ID for the primary console type associated with the given native type.

There can only be one console type associated with a C++ type. This is referred to as the primary console type.

return:

The type ID of the primary console type for "T".

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