simSet.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 _SIMSET_H_
  23. #define _SIMSET_H_
  24. #ifndef _SIMOBJECT_H_
  25. #include "console/simObject.h"
  26. #endif
  27. #ifndef _SIMOBJECTLIST_H_
  28. #include "console/simObjectList.h"
  29. #endif
  30. #ifndef _SIMDICTIONARY_H_
  31. #include "console/simDictionary.h"
  32. #endif
  33. #ifndef _TSIGNAL_H_
  34. #include "core/util/tSignal.h"
  35. #endif
  36. #include "persistence/taml/tamlChildren.h"
  37. //---------------------------------------------------------------------------
  38. /// A set of SimObjects.
  39. ///
  40. /// It is often necessary to keep track of an arbitrary set of SimObjects.
  41. /// For instance, Torque's networking code needs to not only keep track of
  42. /// the set of objects which need to be ghosted, but also the set of objects
  43. /// which must <i>always</i> be ghosted. It does this by working with two
  44. /// sets. The first of these is the RootGroup (which is actually a SimGroup)
  45. /// and the second is the GhostAlwaysSet, which contains objects which must
  46. /// always be ghosted to the client.
  47. ///
  48. /// Some general notes on SimSets:
  49. /// - Membership is not exclusive. A SimObject may be a member of multiple
  50. /// SimSets.
  51. /// - A SimSet does not destroy subobjects when it is destroyed.
  52. /// - A SimSet may hold an arbitrary number of objects.
  53. ///
  54. /// Using SimSets, the code to work with these two sets becomes
  55. /// relatively straightforward:
  56. ///
  57. /// @code
  58. /// // (Example from netObject.cc)
  59. /// // To iterate over all the objects in the Sim:
  60. /// for (SimSetIterator obj(Sim::getRootGroup()); *obj; ++obj)
  61. /// {
  62. /// NetObject* nobj = dynamic_cast<NetObject*>(*obj);
  63. ///
  64. /// if (nobj)
  65. /// {
  66. /// // ... do things ...
  67. /// }
  68. /// }
  69. ///
  70. /// // (Example from netGhost.cc)
  71. /// // To iterate over the ghostAlways set.
  72. /// SimSet* ghostAlwaysSet = Sim::getGhostAlwaysSet();
  73. /// SimSet::iterator i;
  74. ///
  75. /// U32 sz = ghostAlwaysSet->size();
  76. /// S32 j;
  77. ///
  78. /// for(i = ghostAlwaysSet->begin(); i != ghostAlwaysSet->end(); i++)
  79. /// {
  80. /// NetObject *obj = (NetObject *)(*i);
  81. ///
  82. /// /// ... do things with obj...
  83. /// }
  84. /// @endcode
  85. ///
  86. class SimSet : public SimObject, public TamlChildren
  87. {
  88. public:
  89. typedef SimObject Parent;
  90. typedef SimObject Children;
  91. enum SetModification
  92. {
  93. SetCleared,
  94. SetObjectAdded,
  95. SetObjectRemoved
  96. };
  97. /// Signal for letting observers know when objects are added to or removed from
  98. /// the set.
  99. ///
  100. /// @param modification In what way the set has been modified.
  101. /// @param set The set that has been modified.
  102. /// @param object If #modification is #SetObjectAdded or #SetObjectRemoved, this is
  103. /// the object that has been added or removed. Otherwise NULL.
  104. typedef Signal< void( SetModification modification, SimSet* set, SimObject* object ) > SetModificationSignal;
  105. protected:
  106. SimObjectList mObjectList;
  107. void *mMutex;
  108. /// Signal that is triggered when objects are added or removed from the set.
  109. SetModificationSignal mSetModificationSignal;
  110. /// @name Callbacks
  111. /// @{
  112. DECLARE_CALLBACK( void, onObjectAdded, ( SimObject* object ) );
  113. DECLARE_CALLBACK( void, onObjectRemoved, ( SimObject* object ) );
  114. /// @}
  115. public:
  116. SimSet();
  117. ~SimSet();
  118. /// Return the signal that is triggered when an object is added to or removed
  119. /// from the set.
  120. const SetModificationSignal& getSetModificationSignal() const { return mSetModificationSignal; }
  121. SetModificationSignal& getSetModificationSignal() { return mSetModificationSignal; }
  122. /// @name STL Interface
  123. /// @{
  124. ///
  125. typedef SimObjectList::iterator iterator;
  126. typedef SimObjectList::value_type value;
  127. SimObject* front() { return mObjectList.front(); }
  128. SimObject* first() { return mObjectList.first(); }
  129. SimObject* last() { return mObjectList.last(); }
  130. bool empty() const { return mObjectList.empty(); }
  131. S32 size() const { return mObjectList.size(); }
  132. iterator begin() { return mObjectList.begin(); }
  133. iterator end() { return mObjectList.end(); }
  134. value operator[] (S32 index) { return mObjectList[U32(index)]; }
  135. inline iterator find( iterator first, iterator last, SimObject *obj)
  136. { return T3D::find(first, last, obj); }
  137. inline iterator find(SimObject *obj)
  138. { return T3D::find(begin(), end(), obj); }
  139. /// Reorder the position of "obj" to either be the last object in the list or, if
  140. /// "target" is given, to come before "target" in the list of children.
  141. virtual bool reOrder( SimObject *obj, SimObject *target=0 );
  142. /// Return the object at the given index.
  143. SimObject* at(S32 index) const { return mObjectList.at(index); }
  144. /// Remove all objects from this set.
  145. virtual void clear();
  146. /// @}
  147. /// @name Set Management
  148. /// @{
  149. /// Add the given object to the set.
  150. /// @param object Object to add to the set.
  151. virtual void addObject( SimObject* object );
  152. /// Remove the given object from the set.
  153. /// @param object Object to remove from the set.
  154. virtual void removeObject( SimObject* object );
  155. /// Add the given object to the end of the object list of this set.
  156. /// @param object Object to add to the set.
  157. virtual void pushObject( SimObject* object );
  158. /// Return true if this set accepts the given object as a child.
  159. /// This method should be overridden for set classes that restrict membership.
  160. virtual bool acceptsAsChild( SimObject* object ) const { return true; }
  161. /// Deletes all the objects in the set.
  162. void deleteAllObjects();
  163. /// Remove an object from the end of the list.
  164. virtual void popObject();
  165. void bringObjectToFront(SimObject* obj) { reOrder(obj, front()); }
  166. void pushObjectToBack(SimObject* obj) { reOrder(obj, NULL); }
  167. /// Performs a sort of the objects in the set using a script
  168. /// callback function to do the comparison.
  169. ///
  170. /// An example script sort callback:
  171. ///
  172. /// @code
  173. /// function sortByName( %object1, %object2 )
  174. /// {
  175. /// return strcmp( %object1.getName(), %object2.getName() );
  176. /// }
  177. /// @endcode
  178. ///
  179. /// Note: You should never modify the SimSet itself while in
  180. /// the sort callback function as it can cause a deadlock.
  181. ///
  182. void scriptSort( const String &scriptCallbackFn );
  183. /// @}
  184. void callOnChildren( const String &method, S32 argc, ConsoleValue argv[], bool executeOnChildGroups = true );
  185. /// Return the number of objects in this set as well as all sets that are contained
  186. /// in this set and its children.
  187. ///
  188. /// @note The child sets themselves count towards the total too.
  189. U32 sizeRecursive();
  190. virtual SimObject* findObjectByInternalName(StringTableEntry internalName, bool searchChildren = false);
  191. SimObject* findObjectByLineNumber(const char* fileName, S32 declarationLine, bool searchChildren = false);
  192. /// Find the given object in this set. Returns NULL if the object
  193. /// is not part of this set.
  194. SimObject* findObject( SimObject* object );
  195. /// Add all child objects ( including children of children ) to the foundObjects
  196. /// Vector which are of type T.
  197. template< class T >
  198. void findObjectByType( Vector<T*> &foundObjects );
  199. /// Add all child objects ( including children of children ) to the foundObjects
  200. /// Vector which are of type T and for which DecideAddObjectCallback return true;
  201. template< class T >
  202. void findObjectByCallback( bool ( *fn )( T* ), Vector<T*>& foundObjects );
  203. SimObject* getRandom();
  204. inline void lock()
  205. {
  206. #ifdef TORQUE_MULTITHREAD
  207. Mutex::lockMutex(mMutex);
  208. #endif
  209. }
  210. void unlock()
  211. {
  212. #ifdef TORQUE_MULTITHREAD
  213. Mutex::unlockMutex(mMutex);
  214. #endif
  215. }
  216. #ifdef TORQUE_DEBUG_GUARD
  217. inline void _setVectorAssoc( const char *file, const U32 line )
  218. {
  219. mObjectList.setFileAssociation( file, line );
  220. }
  221. #endif
  222. // SimObject.
  223. DECLARE_CONOBJECT( SimSet );
  224. virtual void onRemove();
  225. virtual void onDeleteNotify(SimObject *object);
  226. virtual SimObject* findObject( const char* name );
  227. virtual void write(Stream &stream, U32 tabStop, U32 flags = 0);
  228. virtual bool writeObject(Stream *stream);
  229. virtual bool readObject(Stream *stream);
  230. virtual SimSet* clone();
  231. // TamlChildren
  232. virtual U32 getTamlChildCount(void) const
  233. {
  234. return (U32)size();
  235. }
  236. virtual SimObject* getTamlChild(const U32 childIndex) const
  237. {
  238. // Sanity!
  239. AssertFatal(childIndex < (U32)size(), "SimSet::getTamlChild() - Child index is out of range.");
  240. // For when the assert is not used.
  241. if (childIndex >= (U32)size())
  242. return NULL;
  243. return at(childIndex);
  244. }
  245. virtual void addTamlChild(SimObject* pSimObject)
  246. {
  247. // Sanity!
  248. AssertFatal(pSimObject != NULL, "SimSet::addTamlChild() - Cannot add a NULL child object.");
  249. addObject(pSimObject);
  250. }
  251. };
  252. #ifdef TORQUE_DEBUG_GUARD
  253. # define SIMSET_SET_ASSOCIATION( x ) x._setVectorAssoc( __FILE__, __LINE__ )
  254. #else
  255. # define SIMSET_SET_ASSOCIATION( x )
  256. #endif
  257. template< class T >
  258. void SimSet::findObjectByType( Vector<T*> &foundObjects )
  259. {
  260. T *curObj;
  261. SimSet *curSet;
  262. lock();
  263. // Loop through our child objects.
  264. SimObjectList::iterator itr = mObjectList.begin();
  265. for ( ; itr != mObjectList.end(); itr++ )
  266. {
  267. curObj = dynamic_cast<T*>( *itr );
  268. curSet = dynamic_cast<SimSet*>( *itr );
  269. // If child object is a set, call recursively into it.
  270. if ( curSet && curSet->size() != 0)
  271. curSet->findObjectByType( foundObjects );
  272. // Add this child object if appropriate.
  273. if ( curObj )
  274. foundObjects.push_back( curObj );
  275. }
  276. // Add this object if appropriate.
  277. curObj = dynamic_cast<T*>(this);
  278. if ( curObj )
  279. foundObjects.push_back( curObj );
  280. unlock();
  281. }
  282. template< class T >
  283. void SimSet::findObjectByCallback( bool ( *fn )( T* ), Vector<T*> &foundObjects )
  284. {
  285. T *curObj;
  286. SimSet *curSet;
  287. lock();
  288. // Loop through our child objects.
  289. SimObjectList::iterator itr = mObjectList.begin();
  290. for ( ; itr != mObjectList.end(); itr++ )
  291. {
  292. curObj = dynamic_cast<T*>( *itr );
  293. curSet = dynamic_cast<SimSet*>( *itr );
  294. // If child object is a set, call recursively into it.
  295. if ( curSet )
  296. curSet->findObjectByCallback( fn, foundObjects );
  297. // Add this child object if appropriate.
  298. if ( curObj && ( fn == NULL || fn( curObj ) ) )
  299. foundObjects.push_back( curObj );
  300. }
  301. // Add this object if appropriate.
  302. curObj = dynamic_cast<T*>(this);
  303. if ( curObj && ( fn == NULL || fn( curObj ) ) )
  304. foundObjects.push_back( curObj );
  305. unlock();
  306. }
  307. /// An iterator that recursively and exhaustively traverses the contents
  308. /// of a SimSet.
  309. ///
  310. /// @see SimSet
  311. class SimSetIterator
  312. {
  313. protected:
  314. struct Entry {
  315. SimSet* set;
  316. SimSet::iterator itr;
  317. };
  318. class Stack: public Vector<Entry> {
  319. public:
  320. void push_back(SimSet*);
  321. };
  322. Stack stack;
  323. public:
  324. SimSetIterator(SimSet*);
  325. SimObject* operator++();
  326. SimObject* operator*() {
  327. return stack.empty()? 0: *stack.last().itr;
  328. }
  329. };
  330. //---------------------------------------------------------------------------
  331. /// A group of SimObjects.
  332. ///
  333. /// A SimGroup is a stricter form of SimSet. SimObjects may only be a member
  334. /// of a single SimGroup at a time.
  335. ///
  336. /// The SimGroup will automatically enforce the single-group-membership rule.
  337. ///
  338. /// @code
  339. /// // From engine/sim/simPath.cc - getting a pointer to a SimGroup
  340. /// SimGroup* pMissionGroup = dynamic_cast<SimGroup*>(Sim::findObject("MissionGroup"));
  341. ///
  342. /// // From game/trigger.cc:46 - iterating over a SimObject's group.
  343. /// SimObject* trigger = ...;
  344. /// SimGroup* pGroup = trigger->getGroup();
  345. /// for (SimGroup::iterator itr = pGroup->begin(); itr != pGroup->end(); itr++)
  346. /// {
  347. /// // do something with *itr
  348. /// }
  349. /// @endcode
  350. class SimGroup: public SimSet
  351. {
  352. public:
  353. typedef SimSet Parent;
  354. friend class SimManager;
  355. friend class SimObject;
  356. private:
  357. SimNameDictionary mNameDictionary;
  358. void _addObject( SimObject* object, bool forcePushBack = false );
  359. void _removeObjectNoLock( SimObject* );
  360. public:
  361. ~SimGroup();
  362. void addObject( SimObject* object, SimObjectId id);
  363. void addObject( SimObject* object, const char* name );
  364. // SimSet.
  365. virtual void addObject( SimObject* object );
  366. virtual void removeObject( SimObject* object );
  367. virtual void pushObject( SimObject* object );
  368. virtual void popObject();
  369. virtual void clear();
  370. virtual SimGroup* clone();
  371. virtual SimGroup* deepClone();
  372. virtual SimObject* findObject(const char* name);
  373. virtual void onRemove();
  374. virtual bool processArguments( S32 argc, ConsoleValue *argv );
  375. virtual SimObject* getObject(const S32& index);
  376. DECLARE_CONOBJECT( SimGroup );
  377. };
  378. inline void SimGroup::addObject(SimObject* obj, SimObjectId id)
  379. {
  380. obj->mId = id;
  381. dSprintf( obj->mIdString, sizeof( obj->mIdString ), "%u", obj->mId );
  382. addObject( obj );
  383. }
  384. inline void SimGroup::addObject(SimObject *obj, const char *name)
  385. {
  386. addObject( obj );
  387. obj->assignName(name);
  388. }
  389. /// An iterator that recursively and exhaustively traverses all objects
  390. /// in an SimGroup object tree.
  391. class SimGroupIterator: public SimSetIterator
  392. {
  393. public:
  394. SimGroupIterator(SimGroup* grp): SimSetIterator(grp) {}
  395. SimObject* operator++();
  396. };
  397. #endif // _SIMSET_H_