Torque2D Reference
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
Public Member Functions | Static Public Member Functions | Protected Types | Protected Attributes | Friends | List of all members
NetObject Class Reference

#include <netObject.h>

+ Inheritance diagram for NetObject:

Public Member Functions

 NetObject ()
 
 ~NetObject ()
 
void setMaskBits (U32 orMask)
 
void clearMaskBits (U32 orMask)
 
void setScopeAlways ()
 
void clearScopeAlways ()
 
virtual F32 getUpdatePriority (CameraScopeQuery *focusObject, U32 updateMask, S32 updateSkips)
 
virtual U32 packUpdate (NetConnection *conn, U32 mask, BitStream *stream)
 
virtual void unpackUpdate (NetConnection *conn, BitStream *stream)
 
virtual void onCameraScopeQuery (NetConnection *cr, CameraScopeQuery *camInfo)
 
U32 getNetIndex ()
 Get the ghost index of this object. More...
 
bool isServerObject () const
 Is this a server object? More...
 
bool isClientObject () const
 Is this a client object? More...
 
bool isGhost () const
 Is this is a ghost? More...
 
bool isScopeLocal () const
 Should this object only be visible to the client which created it? More...
 
bool isScopeable () const
 Is this object subject to scoping? More...
 
bool isGhostable () const
 Is this object ghostable? More...
 
bool isGhostAlways () const
 Should this object always be ghosted? More...
 
- Public Member Functions inherited from SimObject
StringTableEntry getClassNamespace () const
 
StringTableEntry getSuperClassNamespace () const
 
void setClassNamespace (const char *classNamespace)
 
void setSuperClassNamespace (const char *superClassNamespace)
 
void pushScriptCallbackGuard (void)
 
void popScriptCallbackGuard (void)
 
S32 getScriptCallbackGuard (void)
 
virtual SimObjectfindObject (const char *name)
 
NamespacegetNamespace ()
 Return the object's namespace. More...
 
const char * tabComplete (const char *prevText, S32 baseLen, bool)
 
virtual void dump ()
 
virtual void dumpClassHierarchy ()
 
SimObjectclone (const bool copyDynamicFields)
 
virtual void copyTo (SimObject *object)
 
template<typename T >
bool isType (void)
 
virtual bool handlesConsoleMethod (const char *fname, S32 *routingId)
 
 DECLARE_CONOBJECT (SimObject)
 
NotifyremoveNotify (void *ptr, Notify::Type)
 Remove a notification from the list. More...
 
void deleteNotify (SimObject *obj)
 Notify an object when we are deleted. More...
 
void clearNotify (SimObject *obj)
 Notify an object when we are cleared. More...
 
void clearAllNotifications ()
 Remove all notifications for this object. More...
 
void processDeleteNotifies ()
 Send out deletion notifications. More...
 
void registerReference (SimObject **obj)
 
void unregisterReference (SimObject **obj)
 
const char * getDataField (StringTableEntry slotName, const char *array)
 
void setDataField (StringTableEntry slotName, const char *array, const char *value)
 
const char * getPrefixedDataField (StringTableEntry fieldName, const char *array)
 
void setPrefixedDataField (StringTableEntry fieldName, const char *array, const char *value)
 
const char * getPrefixedDynamicDataField (StringTableEntry fieldName, const char *array, const S32 fieldType=-1)
 
void setPrefixedDynamicDataField (StringTableEntry fieldName, const char *array, const char *value, const S32 fieldType=-1)
 
StringTableEntry getDataFieldPrefix (StringTableEntry fieldName)
 
U32 getDataFieldType (StringTableEntry slotName, const char *array)
 
SimFieldDictionarygetFieldDictionary ()
 
void clearDynamicFields (void)
 Clear all dynamic fields. More...
 
void setCanSaveDynamicFields (bool bCanSave)
 Set whether fields created at runtime should be saved. Default is true. More...
 
bool getCanSaveDynamicFields (void) const
 Get whether fields created at runtime should be saved. Default is true. More...
 
void setInternalName (const char *newname)
 
StringTableEntry getInternalName ()
 Get the internal of of this control. More...
 
virtual bool save (const char *pcFilePath, bool bOnlySelected=false)
 Save object as a TorqueScript File. More...
 
virtual bool isMethod (const char *methodName)
 Check if a method exists in the objects current namespace. More...
 
SimObjectId getId (void) const
 
StringTableEntry getIdString (void) const
 
U32 getType () const
 
const StringTableEntry getName (void) const
 
void setId (SimObjectId id)
 
void assignName (const char *name)
 
SimGroupgetGroup () const
 
bool isChildOfGroup (SimGroup *pGroup)
 
bool isProperlyAdded () const
 
bool isDeleted () const
 
bool isRemoved () const
 
bool isLocked ()
 
void setLocked (bool b)
 
bool isHidden ()
 
void setHidden (bool b)
 
void setProgenitorFile (const char *pFile)
 
StringTableEntry getProgenitorFile (void) const
 
void setPeriodicTimerID (const S32 timerID)
 
S32 getPeriodicTimerID (void) const
 
bool isPeriodicTimerActive (void) const
 
bool isSelected () const
 
bool isExpanded () const
 
void setSelected (bool sel)
 
void setExpanded (bool exp)
 
void setModDynamicFields (bool dyn)
 
void setModStaticFields (bool sta)
 
 SimObject (const U8 namespaceLinkMask=LinkSuperClassName|LinkClassName)
 
virtual ~SimObject ()
 
virtual bool processArguments (S32 argc, const char **argv)
 Process constructor options. (ie, new SimObject(1,2,3)) More...
 
virtual void onGroupAdd ()
 Called when the object is added to a SimGroup. More...
 
virtual void onGroupRemove ()
 Called when the object is removed from a SimGroup. More...
 
virtual void onNameChange (const char *name)
 Called when the object's name is changed. More...
 
virtual void onStaticModified (const char *slotName, const char *newValue=NULL)
 
virtual void inspectPreApply ()
 
virtual void inspectPostApply ()
 
virtual void onDeleteNotify (SimObject *object)
 
virtual void onEditorEnable ()
 Called when the editor is activated. More...
 
virtual void onEditorDisable ()
 Called when the editor is deactivated. More...
 
bool registerObject ()
 
bool registerObject (U32 id)
 
bool registerObject (const char *name)
 
bool registerObject (const char *name, U32 id)
 
void unregisterObject ()
 
void deleteObject ()
 
bool addToSet (SimObjectId)
 
bool addToSet (const char *)
 
bool removeFromSet (SimObjectId)
 
bool removeFromSet (const char *)
 
virtual bool writeField (StringTableEntry fieldname, const char *value)
 
virtual void write (Stream &stream, U32 tabStop, U32 flags=0)
 
virtual void writeFields (Stream &stream, U32 tabStop)
 
virtual bool writeObject (Stream *stream)
 
virtual bool readObject (Stream *stream)
 
virtual void buildFilterList ()
 
void addFieldFilter (const char *fieldName)
 
void removeFieldFilter (const char *fieldName)
 
void clearFieldFilters ()
 
bool isFiltered (const char *fieldName)
 
void assignFieldsFrom (SimObject *obj)
 
void assignDynamicFieldsFrom (SimObject *obj)
 
- Public Member Functions inherited from ConsoleObject
const AbstractClassRep::FieldfindField (StringTableEntry fieldName) const
 Get a reference to a field by name. More...
 
virtual AbstractClassRepgetClassRep () const
 Gets the ClassRep. More...
 
bool setField (const char *fieldName, const char *value)
 Set the value of a field. More...
 
virtual ~ConsoleObject ()
 
const AbstractClassRep::FieldListgetFieldList () const
 Get a list of all the fields. This information cannot be modified. More...
 
AbstractClassRep::FieldListgetModifiableFieldList ()
 
bool & getDynamicGroupExpand ()
 
S32 getClassId (U32 netClassGroup) const
 
const char * getClassName () const
 

Static Public Member Functions

static void collapseDirtyList ()
 
- Static Public Member Functions inherited from SimObject
static void initPersistFields ()
 
- Static Public Member Functions inherited from ConsoleObject
static const char * lookupClassName (const U32 in_classTag)
 Get the classname from a class tag. More...
 
static void initPersistFields ()
 
static void consoleInit ()
 
static ConsoleObjectcreate (const char *in_pClassName)
 
static ConsoleObjectcreate (const U32 groupId, const U32 typeId, const U32 in_classId)
 
static AbstractClassRepgetStaticClassRep ()
 Get the abstract class information for this class. More...
 
static AbstractClassRepgetParentStaticClassRep ()
 Get the abstract class information for this class's superclass. More...
 

Protected Types

enum  NetFlags {
  IsGhost = BIT(1), ScopeAlways = BIT(6), ScopeLocal = BIT(7), Ghostable = BIT(8),
  MaxNetFlagBit = 15
}
 
- Protected Types inherited from SimObject
enum  SimObjectNSLinkType { LinkClassName = BIT(0), LinkSuperClassName = BIT(1) }
 

Protected Attributes

SimObjectPtr< NetObjectmServerObject
 
BitSet32 mNetFlags
 Flag values from NetFlags. More...
 
U32 mNetIndex
 The index of this ghost in the GhostManager on the server. More...
 
GhostInfomFirstObjectRef
 Head of a linked list storing GhostInfos referencing this NetObject. More...
 
- Protected Attributes inherited from SimObject
SimObjectId mId
 Id number for this object. More...
 
StringTableEntry mIdString
 
NamespacemNameSpace
 
U32 mTypeMask
 
S32 mScriptCallbackGuard
 Whether the object is executing a script callback. More...
 
bool mCanSaveFieldDictionary
 true if dynamic fields (added at runtime) should be saved, defaults to true More...
 
StringTableEntry mInternalName
 Stores object Internal Name. More...
 
StringTableEntry mClassName
 Stores the class name to link script class namespaces. More...
 
StringTableEntry mSuperClassName
 Stores super class name to link script class namespaces. More...
 
U8 mNSLinkMask
 

Friends

class NetConnection
 
struct GhostInfo
 
class NetworkProcessList
 
class GhostAlwaysObjectEvent
 

Miscellaneous

 DECLARE_CONOBJECT (NetObject)
 
bool onAdd ()
 Called when the object is added to the sim. More...
 
void onRemove ()
 Called when the object is removed from the sim. More...
 
static void initPersistFields ()
 

Additional Inherited Members

- Public Types inherited from SimObject
enum  WriteFlags { SelectedOnly = BIT(0) }
 
- Protected Member Functions inherited from SimObject
virtual void onTamlPreWrite (void)
 Taml callbacks. More...
 
virtual void onTamlPostWrite (void)
 Called after Taml has finished writing the object. More...
 
virtual void onTamlPreRead (void)
 Called prior to Taml reading the object. More...
 
virtual void onTamlPostRead (const TamlCustomNodes &customNodes)
 
virtual void onTamlAddParent (SimObject *pParentObject)
 Called after Taml has finished reading the object and has added the object to any parent. More...
 
virtual void onTamlCustomWrite (TamlCustomNodes &customNodes)
 Called during the writing of the object to allow custom properties to be written. More...
 
virtual void onTamlCustomRead (const TamlCustomNodes &customNodes)
 Called during the reading of the object to allow custom properties to be read. More...
 
void linkNamespaces ()
 
void unlinkNamespaces ()
 
- Static Protected Member Functions inherited from SimObject
static bool setClass (void *obj, const char *data)
 
static bool setSuperClass (void *obj, const char *data)
 
static bool writeCanSaveDynamicFields (void *obj, StringTableEntry pFieldName)
 
static bool writeInternalName (void *obj, StringTableEntry pFieldName)
 
static bool setParentGroup (void *obj, const char *data)
 
static bool writeParentGroup (void *obj, StringTableEntry pFieldName)
 
static bool writeSuperclass (void *obj, StringTableEntry pFieldName)
 
static bool writeClass (void *obj, StringTableEntry pFieldName)
 
static SimObject::NotifyallocNotify ()
 Get a free Notify structure. More...
 
static void freeNotify (SimObject::Notify *)
 Mark a Notify structure as free. More...
 
- Static Protected Attributes inherited from SimObject
static SimObject::NotifymNotifyFreeList = NULL
 

Detailed Description

Superclass for ghostable networked objects.

Introduction To NetObject And Ghosting

One of the most powerful aspects of Torque's networking code is its support for ghosting and prioritized, most-recent-state network updates. The way this works is a bit complex, but it is immensely efficient. Let's run through the steps that the server goes through for each client in this part of Torque's networking:

There several significant advantages to using this networking system:

NetConnection contains the Ghost Manager implementation, which deals with transferring data to the appropriate clients and keeping state in synch.

An Example Implementation

The basis of the ghost implementation in Torque is NetObject. It tracks the dirty flags for the various states that the object trackers, and does some other book-keeping to allow more efficient operation of the networking layer.

Using a NetObject is very simple; let's go through a simple example implementation:

class SimpleNetObject : public NetObject
{
public:
typedef NetObject Parent;

Above is the standard boilerplate code for a Torque class. You can find out more about this in SimObject.

char message1[256];
char message2[256];
enum States {
Message1Mask = BIT(0),
Message2Mask = BIT(1),
};

For our example, we're having two "states" that we keep track of, message1 and message2. In a real object, we might map our states to health and position, or some other set of fields. You have 32 bits to work with, so it's possible to be very specific when defining states. In general, you should try to use as few states as possible (you never know when you'll need to expand your object's functionality!), and in fact, most of your fields will end up changing all at once, so it's not worth it to be too fine-grained. (As an example, position and velocity on Player are controlled by the same bit, as one rarely changes without the other changing, too.)

{
// in order for an object to be considered by the network system,
// the Ghostable net flag must be set.
// the ScopeAlways flag indicates that the object is always scoped
// on all active connections.
dStrcpy(message1, "Hello World 1!");
dStrcpy(message2, "Hello World 2!");
}

Here is the constructor. Here, you see that we initialize our net flags to show that we should always be scoped, and that we're to be taken into consideration for ghosting. We also provide some initial values for the message fields.

U32 packUpdate(NetConnection *, U32 mask, BitStream *stream)
{
// check which states need to be updated, and update them
if(stream->writeFlag(mask & Message1Mask))
stream->writeString(message1);
if(stream->writeFlag(mask & Message2Mask))
stream->writeString(message2);
// the return value from packUpdate can set which states still
// need to be updated for this object.
return 0;
}

Here's half of the meat of the networking code, the packUpdate() function. (The other half, unpackUpdate(), we'll get to in a second.) The comments in the code pretty much explain everything, however, notice that the code follows a pattern of if(writeFlag(mask & StateMask)) { ... write data ... }. The packUpdate()/unpackUpdate() functions are responsible for reading and writing the dirty bits to the bitstream by themselves.

{
// the unpackUpdate function must be symmetrical to packUpdate
if(stream->readFlag())
{
stream->readString(message1);
Con::printf("Got message1: %s", message1);
}
if(stream->readFlag())
{
stream->readString(message2);
Con::printf("Got message2: %s", message2);
}
}

The other half of the networking code in any NetObject, unpackUpdate(). In our simple example, all that the code does is print the new messages to the console; however, in a more advanced object, you might trigger animations, update complex object properties, or even spawn new objects, based on what packet data you unpack.

void setMessage1(const char *msg)
{
setMaskBits(Message1Mask);
dStrcpy(message1, msg);
}
void setMessage2(const char *msg)
{
setMaskBits(Message2Mask);
dStrcpy(message2, msg);
}

Here are the accessors for the two properties. It is good to encapsulate your state variables, so that you don't have to remember to make a call to setMaskBits every time you change anything; the accessors can do it for you. In a more complex object, you might need to set multiple mask bits when you change something; this can be done using the | operator, for instance, setMaskBits( Message1Mask | Message2Mask ); if you changed both messages.

IMPLEMENT_CO_NETOBJECT_V1(SimpleNetObject);
ConsoleMethod(SimpleNetObject, setMessage1, void, 3, 3, "(string msg) Set message 1.")
{
object->setMessage1(argv[2]);
}
ConsoleMethod(SimpleNetObject, setMessage2, void, 3, 3, "(string msg) Set message 2.")
{
object->setMessage2(argv[2]);
}

Finally, we use the NetObject implementation macro, IMPLEMENT_CO_NETOBJECT_V1(), to implement our NetObject. It is important that we use this, as it makes Torque perform certain initialization tasks that allow us to send the object over the network. IMPLEMENT_CONOBJECT() doesn't perform these tasks, see the documentation on AbstractClassRep for more details.

Member Enumeration Documentation

enum NetFlags
protected
Enumerator
IsGhost 

This is a ghost.

ScopeAlways 

Object always ghosts to clients.

ScopeLocal 

Ghost only to local client.

Ghostable 

Set if this object CAN ghost.

MaxNetFlagBit 

Constructor & Destructor Documentation

NetObject ( )
~NetObject ( )

Member Function Documentation

void clearMaskBits ( U32  orMask)

Clear the specified bits from the dirty mask.

Parameters
orMaskBits to clear
void clearScopeAlways ( )

Stop scoping the object to all connections.

The object's ScopeAlways flag is cleared and the object is removed from all current active connections.

void collapseDirtyList ( )
static
DECLARE_CONOBJECT ( NetObject  )
U32 getNetIndex ( )
inline

Get the ghost index of this object.

F32 getUpdatePriority ( CameraScopeQuery focusObject,
U32  updateMask,
S32  updateSkips 
)
virtual

This returns a value which is used to prioritize which objects need to be updated.

In NetObject, our returned priority is 0.1 * updateSkips, so that less recently updated objects are more likely to be updated.

In subclasses, this can be adjusted. For instance, ShapeBase provides priority based on proximity to the camera.

Parameters
focusObjectInformation from a previous call to onCameraScopeQuery.
updateMaskCurrent update mask.
updateSkipsNumber of ticks we haven't been updated for.
Returns
A floating point value indicating priority. These are typically < 5.0.
void initPersistFields ( void  )
static
bool isClientObject ( ) const
inline

Is this a client object?

bool isGhost ( ) const
inline

Is this is a ghost?

bool isGhostable ( ) const
inline

Is this object ghostable?

bool isGhostAlways ( ) const
inline

Should this object always be ghosted?

bool isScopeable ( ) const
inline

Is this object subject to scoping?

bool isScopeLocal ( ) const
inline

Should this object only be visible to the client which created it?

bool isServerObject ( ) const
inline

Is this a server object?

bool onAdd ( void  )
virtual

Called when the object is added to the sim.

Reimplemented from SimObject.

void onCameraScopeQuery ( NetConnection cr,
CameraScopeQuery camInfo 
)
virtual

Queries the object about information used to determine scope.

Something that is 'in scope' is somehow interesting to the client.

If we are a NetConnection's scope object, it calls this method to determine how things should be scoped; basically, we tell it our field of view with camInfo, and have the opportunity to manually mark items as "in scope" as we see fit.

By default, we just mark all ghostable objects as in scope.

Parameters
crNet connection requesting scope information.
camInfoInformation about what this object can see.
void onRemove ( )
virtual

Called when the object is removed from the sim.

Reimplemented from SimObject.

U32 packUpdate ( NetConnection conn,
U32  mask,
BitStream stream 
)
virtual

Instructs this object to pack its state for transfer over the network.

Parameters
connNet connection being used
maskMask indicating fields to transmit.
streamBitstream to pack data to
Returns
Any bits which were not dealt with. The value is stored by the networking system. Don't set bits you weren't passed.

Reimplemented in SimpleNetObject.

void setMaskBits ( U32  orMask)

Used to mark a bit as dirty; ie, that its corresponding set of fields need to be transmitted next update.

Parameters
orMaskBit(s) to set
void setScopeAlways ( )

Scope the object to all connections.

The object is marked as ScopeAlways and is immediately ghosted to all active connections. This function has no effect if the object is not marked as Ghostable.

void unpackUpdate ( NetConnection conn,
BitStream stream 
)
virtual

Instructs this object to read state data previously packed with packUpdate.

Parameters
connNet connection being used
streamstream to read from

Reimplemented in SimpleNetObject.

Friends And Related Function Documentation

friend class GhostAlwaysObjectEvent
friend
friend struct GhostInfo
friend
friend class NetConnection
friend
friend class NetworkProcessList
friend

Member Data Documentation

GhostInfo* mFirstObjectRef
protected

Head of a linked list storing GhostInfos referencing this NetObject.

BitSet32 mNetFlags
protected

Flag values from NetFlags.

U32 mNetIndex
protected

The index of this ghost in the GhostManager on the server.

SimObjectPtr<NetObject> mServerObject
protected

Pointer to the server object; used only when we are doing "short-circuited" networking.

When we are running with client and server on the same system (which can happen be either when we are doing a single player game, or if we're hosting a multiplayer game and having someone playing on the same instance), we can do some short circuited code to enhance performance.

This variable is used to make it simpler; if we are running in short-circuited mode, it's set to the object on the server that this NetObject is ghosting.

Note
"Premature optimization is the root of all evil" - Donald Knuth. The current codebase uses this feature in three small places, mostly for non-speed-related purposes.

The documentation for this class was generated from the following files: