simObject.h 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #ifndef _SIMOBJECT_H_
  27. #define _SIMOBJECT_H_
  28. #ifndef _SIM_H_
  29. #include "console/sim.h"
  30. #endif
  31. #ifndef _CONSOLEOBJECT_H_
  32. #include "console/consoleObject.h"
  33. #endif
  34. #ifndef _BITSET_H_
  35. #include "core/bitSet.h"
  36. #endif
  37. #ifndef _TAML_CALLBACKS_H_
  38. #include "persistence/taml/tamlCallbacks.h"
  39. #endif
  40. class Stream;
  41. class LightManager;
  42. class SimFieldDictionary;
  43. class SimPersistID;
  44. class GuiInspector;
  45. /// Base class for objects involved in the simulation.
  46. ///
  47. /// @section simobject_intro Introduction
  48. ///
  49. /// SimObject is a base class for most of the classes you'll encounter
  50. /// working in Torque. It provides fundamental services allowing "smart"
  51. /// object referencing, creation, destruction, organization, and location.
  52. /// Along with SimEvent, it gives you a flexible event-scheduling system,
  53. /// as well as laying the foundation for the in-game editors, GUI system,
  54. /// and other vital subsystems.
  55. ///
  56. /// @section simobject_subclassing Subclassing
  57. ///
  58. /// You will spend a lot of your time in Torque subclassing, or working
  59. /// with subclasses of, SimObject. SimObject is designed to be easy to
  60. /// subclass.
  61. ///
  62. /// You should not need to override anything in a subclass except:
  63. /// - The constructor/destructor.
  64. /// - processArguments()
  65. /// - onAdd()/onRemove()
  66. /// - onGroupAdd()/onGroupRemove()
  67. /// - onNameChange()
  68. /// - onStaticModified()
  69. /// - onDeleteNotify()
  70. /// - onEditorEnable()/onEditorDisable()
  71. /// - inspectPreApply()/inspectPostApply()
  72. /// - things from ConsoleObject (see ConsoleObject docs for specifics)
  73. ///
  74. /// Of course, if you know what you're doing, go nuts! But in most cases, you
  75. /// shouldn't need to touch things not on that list.
  76. ///
  77. /// When you subclass, you should define a typedef in the class, called Parent,
  78. /// that references the class you're inheriting from.
  79. ///
  80. /// @code
  81. /// class mySubClass : public SimObject {
  82. /// typedef SimObject Parent;
  83. /// ...
  84. /// @endcode
  85. ///
  86. /// Then, when you override a method, put in:
  87. ///
  88. /// @code
  89. /// bool mySubClass::onAdd()
  90. /// {
  91. /// if(!Parent::onAdd())
  92. /// return false;
  93. ///
  94. /// // ... do other things ...
  95. /// }
  96. /// @endcode
  97. ///
  98. /// Of course, you want to replace onAdd with the appropriate method call.
  99. ///
  100. /// @section simobject_lifecycle A SimObject's Life Cycle
  101. ///
  102. /// SimObjects do not live apart. One of the primary benefits of using a
  103. /// SimObject is that you can uniquely identify it and easily find it (using
  104. /// its ID). Torque does this by keeping a global hierarchy of SimGroups -
  105. /// a tree - containing every registered SimObject. You can then query
  106. /// for a given object using Sim::findObject() (or SimSet::findObject() if
  107. /// you want to search only a specific set).
  108. ///
  109. /// @code
  110. /// // Three examples of registering an object.
  111. ///
  112. /// // Method 1:
  113. /// AIClient *aiPlayer = new AIClient();
  114. /// aiPlayer->registerObject();
  115. ///
  116. /// // Method 2:
  117. /// ActionMap* globalMap = new ActionMap;
  118. /// globalMap->registerObject("GlobalActionMap");
  119. ///
  120. /// // Method 3:
  121. /// bool reg = mObj->registerObject(id);
  122. /// @endcode
  123. ///
  124. /// Registering a SimObject performs these tasks:
  125. /// - Marks the object as not cleared and not removed.
  126. /// - Assigns the object a unique SimObjectID if it does not have one already.
  127. /// - Adds the object to the global name and ID dictionaries so it can be found
  128. /// again.
  129. /// - Calls the object's onAdd() method. <b>Note:</b> SimObject::onAdd() performs
  130. /// some important initialization steps. See @ref simobject_subclassing "here
  131. /// for details" on how to properly subclass SimObject.
  132. /// - If onAdd() fails (returns false), it calls unregisterObject().
  133. /// - Checks to make sure that the SimObject was properly initialized (and asserts
  134. /// if not).
  135. ///
  136. /// Calling registerObject() and passing an ID or a name will cause the object to be
  137. /// assigned that name and/or ID before it is registered.
  138. ///
  139. /// Congratulations, you have now registered your object! What now?
  140. ///
  141. /// Well, hopefully, the SimObject will have a long, useful life. But eventually,
  142. /// it must die.
  143. ///
  144. /// There are a two ways a SimObject can die.
  145. /// - First, the game can be shut down. This causes the root SimGroup
  146. /// to be unregistered and deleted. When a SimGroup is unregistered,
  147. /// it unregisters all of its member SimObjects; this results in everything
  148. /// that has been registered with Sim being unregistered, as everything
  149. /// registered with Sim is in the root group.
  150. /// - Second, you can manually kill it off, either by calling unregisterObject()
  151. /// or by calling deleteObject().
  152. ///
  153. /// When you unregister a SimObject, the following tasks are performed:
  154. /// - The object is flagged as removed.
  155. /// - Notifications are cleaned up.
  156. /// - If the object is in a group, then it removes itself from the group.
  157. /// - Delete notifications are sent out.
  158. /// - Finally, the object removes itself from the Sim globals, and tells
  159. /// Sim to get rid of any pending events for it.
  160. ///
  161. /// If you call deleteObject(), all of the above tasks are performed, in addition
  162. /// to some sanity checking to make sure the object was previously added properly,
  163. /// and isn't in the process of being deleted. After the object is unregistered, it
  164. /// deallocates itself.
  165. ///
  166. /// @section simobject_editor Torque Editors
  167. ///
  168. /// SimObjects are one of the building blocks for the in-game editors. They
  169. /// provide a basic interface for the editor to be able to list the fields
  170. /// of the object, update them safely and reliably, and inform the object
  171. /// things have changed.
  172. ///
  173. /// This interface is implemented in the following areas:
  174. /// - onNameChange() is called when the object is renamed.
  175. /// - onStaticModified() is called whenever a static field is modified.
  176. /// - inspectPreApply() is called before the object's fields are updated,
  177. /// when changes are being applied.
  178. /// - inspectPostApply() is called after the object's fields are updated.
  179. /// - onEditorEnable() is called whenever an editor is enabled (for instance,
  180. /// when you hit F11 to bring up the world editor).
  181. /// - onEditorDisable() is called whenever the editor is disabled (for instance,
  182. /// when you hit F11 again to close the world editor).
  183. ///
  184. /// (Note: you can check the variable gEditingMission to see if the mission editor
  185. /// is running; if so, you may want to render special indicators. For instance, the
  186. /// fxFoliageReplicator renders inner and outer radii when the mission editor is
  187. /// runnning.)
  188. ///
  189. /// @section simobject_console The Console
  190. ///
  191. /// SimObject extends ConsoleObject by allowing you to
  192. /// to set arbitrary dynamic fields on the object, as well as
  193. /// statically defined fields. This is done through two methods,
  194. /// setDataField and getDataField, which deal with the complexities of
  195. /// allowing access to two different types of object fields.
  196. ///
  197. /// Static fields take priority over dynamic fields. This is to be
  198. /// expected, as the role of dynamic fields is to allow data to be
  199. /// stored in addition to the predefined fields.
  200. ///
  201. /// The fields in a SimObject are like properties (or fields) in a class.
  202. ///
  203. /// Some fields may be arrays, which is what the array parameter is for; if it's non-null,
  204. /// then it is parsed with dAtoI and used as an index into the array. If you access something
  205. /// as an array which isn't, then you get an empty string.
  206. ///
  207. /// <b>You don't need to read any further than this.</b> Right now,
  208. /// set/getDataField are called a total of 6 times through the entire
  209. /// Torque codebase. Therefore, you probably don't need to be familiar
  210. /// with the details of accessing them. You may want to look at Con::setData
  211. /// instead. Most of the time you will probably be accessing fields directly,
  212. /// or using the scripting language, which in either case means you don't
  213. /// need to do anything special.
  214. ///
  215. /// The functions to get/set these fields are very straightforward:
  216. ///
  217. /// @code
  218. /// setDataField(StringTable->insert("locked", false), NULL, b ? "true" : "false" );
  219. /// curObject->setDataField(curField, curFieldArray, STR.getStringValue());
  220. /// setDataField(slotName, array, value);
  221. /// @endcode
  222. ///
  223. /// <i>For advanced users:</i> There are two flags which control the behavior
  224. /// of these functions. The first is ModStaticFields, which controls whether
  225. /// or not the DataField functions look through the static fields (defined
  226. /// with addField; see ConsoleObject for details) of the class. The second
  227. /// is ModDynamicFields, which controls dynamically defined fields. They are
  228. /// set automatically by the console constructor code.
  229. ///
  230. /// @nosubgrouping
  231. class SimObject: public ConsoleObject, public TamlCallbacks
  232. {
  233. public:
  234. typedef ConsoleObject Parent;
  235. friend class SimManager;
  236. friend class SimGroup;
  237. friend class SimNameDictionary;
  238. friend class SimManagerNameDictionary;
  239. friend class SimIdDictionary;
  240. /// @name Notification
  241. /// @{
  242. struct Notify
  243. {
  244. enum Type
  245. {
  246. ClearNotify, ///< Notified when the object is cleared.
  247. DeleteNotify, ///< Notified when the object is deleted.
  248. ObjectRef, ///< Cleverness to allow tracking of references.
  249. Invalid ///< Mark this notification as unused (used in freeNotify).
  250. } type;
  251. void *ptr; ///< Data (typically referencing or interested object).
  252. Notify *next; ///< Next notification in the linked list.
  253. };
  254. /// @}
  255. /// Flags passed to SimObject::write
  256. enum WriteFlags
  257. {
  258. SelectedOnly = BIT( 0 ), ///< Indicates that only objects marked as selected should be outputted. Used in SimSet.
  259. NoName = BIT( 1 ), ///< Indicates that the object name should not be saved.
  260. IgnoreCanSave = BIT( 2 ), ///< Write out even if CannotSave=true.
  261. };
  262. private:
  263. /// Flags for use in mFlags
  264. enum
  265. {
  266. Deleted = BIT( 0 ), ///< This object is marked for deletion.
  267. Removed = BIT( 1 ), ///< This object has been unregistered from the object system.
  268. Added = BIT( 3 ), ///< This object has been registered with the object system.
  269. Selected = BIT( 4 ), ///< This object has been marked as selected. (in editor)
  270. Expanded = BIT( 5 ), ///< This object has been marked as expanded. (in editor)
  271. ModStaticFields = BIT( 6 ), ///< The object allows you to read/modify static fields
  272. ModDynamicFields = BIT( 7 ), ///< The object allows you to read/modify dynamic fields
  273. AutoDelete = BIT( 8 ), ///< Delete this object when the last ObjectRef is gone.
  274. CannotSave = BIT( 9 ), ///< Object should not be saved.
  275. EditorOnly = BIT( 10 ), ///< This object is for use by the editor only.
  276. NoNameChange = BIT( 11 ), ///< Whether changing the name of this object is allowed.
  277. Hidden = BIT( 12 ), ///< Object is hidden in editors.
  278. Locked = BIT( 13 ), ///< Object is locked in editors.
  279. };
  280. // dictionary information stored on the object
  281. StringTableEntry mObjectName;
  282. StringTableEntry mOriginalName;
  283. SimObject* nextNameObject;
  284. SimObject* nextManagerNameObject;
  285. SimObject* nextIdObject;
  286. /// SimGroup we're contained in, if any.
  287. SimGroup* mGroup;
  288. /// Flags internal to the object management system.
  289. BitSet32 mFlags;
  290. StringTableEntry mProgenitorFile;
  291. /// Object we are copying fields from.
  292. SimObject* mCopySource;
  293. /// Table of dynamic fields assigned to this object.
  294. SimFieldDictionary *mFieldDictionary;
  295. /// Buffer to store textual representation of this object's numeric ID in.
  296. char mIdString[ 11 ];
  297. /// @name Serialization
  298. /// @{
  299. /// Path to file this SimObject was loaded from.
  300. StringTableEntry mFilename;
  301. /// The line number that the object was declared on if it was loaded from a file.
  302. S32 mDeclarationLine;
  303. /// @}
  304. /// @name Notification
  305. /// @{
  306. /// List of notifications added to this object.
  307. Notify* mNotifyList;
  308. static SimObject::Notify *mNotifyFreeList;
  309. static SimObject::Notify *allocNotify(); ///< Get a free Notify structure.
  310. static void freeNotify(SimObject::Notify*); ///< Mark a Notify structure as free.
  311. /// @}
  312. static bool _setCanSave( void* object, const char* index, const char* data );
  313. static const char* _getCanSave( void* object, const char* data );
  314. static const char* _getHidden( void* object, const char* data )
  315. { if( static_cast< SimObject* >( object )->isHidden() ) return "1"; return "0"; }
  316. static const char* _getLocked( void* object, const char* data )
  317. { if( static_cast< SimObject* >( object )->isLocked() ) return "1"; return "0"; }
  318. static bool _setHidden( void* object, const char* index, const char* data )
  319. { static_cast< SimObject* >( object )->setHidden( dAtob( data ) ); return false; }
  320. static bool _setLocked( void* object, const char* index, const char* data )
  321. { static_cast< SimObject* >( object )->setLocked( dAtob( data ) ); return false; }
  322. // Namespace protected set methods
  323. static bool setClass( void *object, const char *index, const char *data )
  324. { static_cast<SimObject*>(object)->setClassNamespace(data); return false; };
  325. static bool setSuperClass(void *object, const char *index, const char *data)
  326. { static_cast<SimObject*>(object)->setSuperClassNamespace(data); return false; };
  327. static bool writeObjectName(void* obj, StringTableEntry pFieldName)
  328. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mObjectName != NULL && simObject->mObjectName != StringTable->EmptyString(); }
  329. static bool writeCanSaveDynamicFields(void* obj, StringTableEntry pFieldName)
  330. { return static_cast<SimObject*>(obj)->mCanSaveFieldDictionary == false; }
  331. static bool writeInternalName(void* obj, StringTableEntry pFieldName)
  332. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mInternalName != NULL && simObject->mInternalName != StringTable->EmptyString(); }
  333. static bool setParentGroup(void* obj, const char* data);
  334. static bool writeParentGroup(void* obj, StringTableEntry pFieldName)
  335. { return static_cast<SimObject*>(obj)->mGroup != NULL; }
  336. static bool writeSuperclass(void* obj, StringTableEntry pFieldName)
  337. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mSuperClassName != NULL && simObject->mSuperClassName != StringTable->EmptyString(); }
  338. static bool writeClass(void* obj, StringTableEntry pFieldName)
  339. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mClassName != NULL && simObject->mClassName != StringTable->EmptyString(); }
  340. static bool writeClassName(void* obj, StringTableEntry pFieldName)
  341. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mClassName != NULL && simObject->mClassName != StringTable->EmptyString(); }
  342. // Group hierarchy protected set method
  343. static bool setProtectedParent(void *object, const char *index, const char *data);
  344. // Object name protected set method
  345. static bool setProtectedName(void *object, const char *index, const char *data);
  346. public:
  347. inline void setProgenitorFile(const char* pFile) { mProgenitorFile = StringTable->insert(pFile); }
  348. inline StringTableEntry getProgenitorFile(void) const { return mProgenitorFile; }
  349. protected:
  350. /// Taml callbacks.
  351. virtual void onTamlPreWrite(void) {}
  352. virtual void onTamlPostWrite(void) {}
  353. virtual void onTamlPreRead(void) {}
  354. virtual void onTamlPostRead(const TamlCustomNodes& customNodes) {}
  355. virtual void onTamlAddParent(SimObject* pParentObject) {}
  356. virtual void onTamlCustomWrite(TamlCustomNodes& customNodes) {}
  357. virtual void onTamlCustomRead(const TamlCustomNodes& customNodes);
  358. /// Id number for this object.
  359. SimObjectId mId;
  360. /// Internal name assigned to the object. Not set by default.
  361. StringTableEntry mInternalName;
  362. static bool smForceId; ///< Force a registered object to use the given Id. Cleared upon use.
  363. static SimObjectId smForcedId; ///< The Id to force upon the object. Poor object.
  364. /// @name Serialization
  365. /// @{
  366. /// Whether dynamic fields should be saved out in serialization. Defaults to true.
  367. bool mCanSaveFieldDictionary;
  368. /// @}
  369. /// @name Persistent IDs
  370. /// @{
  371. /// Persistent ID assigned to this object. Allows to unambiguously refer to this
  372. /// object in serializations regardless of stream object ordering.
  373. SimPersistID* mPersistentId;
  374. static bool _setPersistentID( void* object, const char* index, const char* data );
  375. /// @}
  376. /// @name Namespace management
  377. /// @{
  378. /// The namespace in which method lookup for this object begins.
  379. Namespace* mNameSpace;
  380. /// Name of namespace to use as class namespace.
  381. StringTableEntry mClassName;
  382. /// Name of namespace to use as class super namespace.
  383. StringTableEntry mSuperClassName;
  384. /// Perform namespace linking on this object.
  385. void linkNamespaces();
  386. /// Undo namespace linking on this object.
  387. void unlinkNamespaces();
  388. /// @}
  389. /// Called when the object is selected in the editor.
  390. virtual void _onSelected() {}
  391. /// Called when the object is unselected in the editor.
  392. virtual void _onUnselected() {}
  393. /// We can provide more detail, like object name and id.
  394. virtual String _getLogMessage(const char* fmt, va_list args) const;
  395. DEFINE_CREATE_METHOD
  396. {
  397. T* object = new T;
  398. object->incRefCount();
  399. return object;
  400. }
  401. // EngineObject.
  402. virtual void _destroySelf();
  403. public:
  404. /// @name Cloning
  405. /// @{
  406. /// Return a shallow copy of this object.
  407. virtual SimObject* clone();
  408. /// Return a deep copy of this object.
  409. virtual SimObject* deepClone();
  410. /// @}
  411. /// @name Accessors
  412. /// @{
  413. /// Get the value of a field on the object.
  414. ///
  415. /// See @ref simobject_console "here" for a detailed discussion of what this
  416. /// function does.
  417. ///
  418. /// @param slotName Field to access.
  419. /// @param array String containing index into array
  420. /// (if field is an array); if NULL, it is ignored.
  421. const char *getDataField(StringTableEntry slotName, const char *array);
  422. /// Set the value of a field on the object.
  423. ///
  424. /// See @ref simobject_console "here" for a detailed discussion of what this
  425. /// function does.
  426. ///
  427. /// @param slotName Field to access.
  428. /// @param array String containing index into array; if NULL, it is ignored.
  429. /// @param value Value to store.
  430. void setDataField(StringTableEntry slotName, const char *array, const char *value);
  431. const char *getPrefixedDataField(StringTableEntry fieldName, const char *array);
  432. void setPrefixedDataField(StringTableEntry fieldName, const char *array, const char *value);
  433. const char *getPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const S32 fieldType = -1);
  434. void setPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const char *value, const S32 fieldType = -1);
  435. StringTableEntry getDataFieldPrefix(StringTableEntry fieldName);
  436. /// Get the type of a field on the object.
  437. ///
  438. /// @param slotName Field to access.
  439. /// @param array String containing index into array
  440. /// (if field is an array); if NULL, it is ignored.
  441. U32 getDataFieldType(StringTableEntry slotName, const char *array);
  442. /// Set the type of a *dynamic* field on the object.
  443. ///
  444. /// @param typeName/Id Console base type name/id to assign to a dynamic field.
  445. /// @param slotName Field to access.
  446. /// @param array String containing index into array
  447. /// (if field is an array); if NULL, it is ignored.
  448. void setDataFieldType(const U32 fieldTypeId, StringTableEntry slotName, const char *array);
  449. void setDataFieldType(const char *typeName, StringTableEntry slotName, const char *array);
  450. /// Get reference to the dictionary containing dynamic fields.
  451. ///
  452. /// See @ref simobject_console "here" for a detailed discussion of what this
  453. /// function does.
  454. ///
  455. /// This dictionary can be iterated over using a SimFieldDictionaryIterator.
  456. SimFieldDictionary * getFieldDictionary() {return(mFieldDictionary);}
  457. // Component Information
  458. inline virtual StringTableEntry getComponentName() { return StringTable->insert( getClassName() ); };
  459. /// These functions support internal naming that is not namespace
  460. /// bound for locating child controls in a generic way.
  461. ///
  462. /// Set the internal name of this control (Not linked to a namespace)
  463. void setInternalName(const char* newname);
  464. /// Get the internal name of this control
  465. StringTableEntry getInternalName() const { return mInternalName; }
  466. /// Set the original name of this control
  467. void setOriginalName(const char* originalName);
  468. /// Get the original name of this control
  469. StringTableEntry getOriginalName() const { return mOriginalName; }
  470. /// These functions allow you to set and access the filename
  471. /// where this object was created.
  472. ///
  473. /// Set the filename
  474. void setFilename(const char* file);
  475. /// Get the filename
  476. StringTableEntry getFilename() const { return mFilename; }
  477. /// These functions are used to track the line number (1-based)
  478. /// on which the object was created if it was loaded from script
  479. ///
  480. /// Set the declaration line number
  481. void setDeclarationLine(U32 lineNumber);
  482. /// Get the declaration line number
  483. S32 getDeclarationLine() const { return mDeclarationLine; }
  484. /// Save object as a TorqueScript File.
  485. virtual bool save( const char* pcFilePath, bool bOnlySelected = false, const char *preappend = NULL );
  486. /// Check if a method exists in the objects current namespace.
  487. virtual bool isMethod( const char* methodName );
  488. /// Return true if the field is defined on the object
  489. virtual bool isField( const char* fieldName, bool includeStatic = true, bool includeDynamic = true );
  490. /// @}
  491. /// @name Initialization
  492. /// @{
  493. ///
  494. SimObject();
  495. virtual ~SimObject();
  496. virtual bool processArguments(S32 argc, ConsoleValue *argv); ///< Process constructor options. (ie, new SimObject(1,2,3))
  497. /// @}
  498. /// @name Events
  499. /// @{
  500. /// Called when the object is added to the sim.
  501. virtual bool onAdd();
  502. /// Called when the object is removed from the sim.
  503. virtual void onRemove();
  504. /// Called when the object is added to a SimGroup.
  505. virtual void onGroupAdd();
  506. /// Called when the object is removed from a SimGroup.
  507. virtual void onGroupRemove();
  508. /// Called when the object's name is changed.
  509. virtual void onNameChange(const char *name);
  510. /// Called when the adding of the object to the sim is complete, all sub-objects have been processed as well
  511. // This is a special-case function that only really gets used with Entities/BehaviorObjects.
  512. virtual void onPostAdd() {}
  513. ///
  514. /// Specifically, these are called by setDataField
  515. /// when a static or dynamic field is modified, see
  516. /// @ref simobject_console "the console details".
  517. virtual void onStaticModified(const char* slotName, const char*newValue = NULL); ///< Called when a static field is modified.
  518. virtual void onDynamicModified(const char* slotName, const char*newValue = NULL); ///< Called when a dynamic field is modified.
  519. /// Called before any property of the object is changed in the world editor.
  520. ///
  521. /// The calling order here is:
  522. /// - inspectPreApply()
  523. /// - ...
  524. /// - calls to setDataField()
  525. /// - ...
  526. /// - inspectPostApply()
  527. virtual void inspectPreApply();
  528. /// Called after any property of the object is changed in the world editor.
  529. ///
  530. /// @see inspectPreApply
  531. virtual void inspectPostApply();
  532. /// Called when a SimObject is deleted.
  533. ///
  534. /// When you are on the notification list for another object
  535. /// and it is deleted, this method is called.
  536. virtual void onDeleteNotify(SimObject *object);
  537. /// Called when the editor is activated.
  538. virtual void onEditorEnable(){};
  539. /// Called when the editor is deactivated.
  540. virtual void onEditorDisable(){};
  541. /// Called when the object is inspected via a GuiInspector control
  542. virtual void onInspect(GuiInspector*) {};
  543. /// @}
  544. /// Find a named sub-object of this object.
  545. ///
  546. /// This is subclassed in the SimGroup and SimSet classes.
  547. ///
  548. /// For a single object, it just returns NULL, as normal objects cannot have children.
  549. virtual SimObject *findObject(const char *name);
  550. /// @name Notification
  551. /// @{
  552. Notify *removeNotify(void *ptr, Notify::Type); ///< Remove a notification from the list.
  553. void deleteNotify(SimObject* obj); ///< Notify an object when we are deleted.
  554. void clearNotify(SimObject* obj); ///< Notify an object when we are cleared.
  555. void clearAllNotifications(); ///< Remove all notifications for this object.
  556. void processDeleteNotifies(); ///< Send out deletion notifications.
  557. /// Register a reference to this object.
  558. ///
  559. /// You pass a pointer to your reference to this object.
  560. ///
  561. /// When the object is deleted, it will null your
  562. /// pointer, ensuring you don't access old memory.
  563. ///
  564. /// @param obj Pointer to your reference to the object.
  565. void registerReference(SimObject **obj);
  566. /// Unregister a reference to this object.
  567. ///
  568. /// Remove a reference from the list, so that it won't
  569. /// get nulled inappropriately.
  570. ///
  571. /// Call this when you're done with your reference to
  572. /// the object, especially if you're going to free the
  573. /// memory. Otherwise, you may erroneously get something
  574. /// overwritten.
  575. ///
  576. /// @see registerReference
  577. void unregisterReference(SimObject **obj);
  578. /// @}
  579. /// @name Registration
  580. ///
  581. /// SimObjects must be registered with the object system.
  582. /// @{
  583. /// Register an object with the object system.
  584. ///
  585. /// This must be called if you want to keep the object around.
  586. /// In the rare case that you will delete the object immediately, or
  587. /// don't want to be able to use Sim::findObject to locate it, then
  588. /// you don't need to register it.
  589. ///
  590. /// registerObject adds the object to the global ID and name dictionaries,
  591. /// after first assigning it a new ID number. It calls onAdd(). If onAdd fails,
  592. /// it unregisters the object and returns false.
  593. ///
  594. /// If a subclass's onAdd doesn't eventually call SimObject::onAdd(), it will
  595. /// cause an assertion.
  596. bool registerObject();
  597. /// Register the object, forcing the id.
  598. ///
  599. /// @see registerObject()
  600. /// @param id ID to assign to the object.
  601. bool registerObject(U32 id);
  602. /// Register the object, assigning the name.
  603. ///
  604. /// @see registerObject()
  605. /// @param name Name to assign to the object.
  606. bool registerObject(const char *name);
  607. /// Register the object, assigning a name and ID.
  608. ///
  609. /// @see registerObject()
  610. /// @param name Name to assign to the object.
  611. /// @param id ID to assign to the object.
  612. bool registerObject(const char *name, U32 id);
  613. /// Unregister the object from Sim.
  614. ///
  615. /// This performs several operations:
  616. /// - Sets the removed flag.
  617. /// - Call onRemove()
  618. /// - Clear out notifications.
  619. /// - Remove the object from...
  620. /// - its group, if any. (via getGroup)
  621. /// - Sim::gNameDictionary
  622. /// - Sim::gIDDictionary
  623. /// - Finally, cancel any pending events for this object (as it can't receive them now).
  624. void unregisterObject();
  625. /// Unregister, mark as deleted, and free the object.
  626. void deleteObject();
  627. /// Performs a safe delayed delete of the object using a sim event.
  628. void safeDeleteObject();
  629. /// Special-case deletion behaviors, largely intended for cleanup in particular cases where it wouldn't happen automatically(like cleanup of associated files)
  630. virtual void handleDeleteAction() {}
  631. /// @}
  632. /// @name Accessors
  633. /// @{
  634. /// Return the unique numeric object ID.
  635. SimObjectId getId() const { return mId; }
  636. /// Return the object ID as a string.
  637. const char* getIdString() const { return mIdString; }
  638. /// Return the name of this object.
  639. StringTableEntry getName() const { return mObjectName; }
  640. /// Return the SimGroup that this object is contained in. Never NULL except for
  641. /// RootGroup and unregistered objects.
  642. SimGroup* getGroup() const { return mGroup; }
  643. /// Assign the given name to this object.
  644. void assignName( const char* name );
  645. void setId(SimObjectId id);
  646. static void setForcedId(SimObjectId id) { smForceId = true; smForcedId = id; } ///< Force an Id on the next registered object.
  647. bool isChildOfGroup(SimGroup* pGroup);
  648. bool isProperlyAdded() const { return mFlags.test(Added); }
  649. bool isDeleted() const { return mFlags.test(Deleted); }
  650. bool isRemoved() const { return mFlags.test(Deleted | Removed); }
  651. virtual bool isLocked() const { return mFlags.test( Locked ); }
  652. virtual void setLocked( bool b );
  653. virtual bool isHidden() const { return mFlags.test( Hidden ); }
  654. virtual void setHidden(bool b);
  655. /// @}
  656. /// @name Sets
  657. ///
  658. /// The object must be properly registered before you can add/remove it to/from a set.
  659. ///
  660. /// All these functions accept either a name or ID to identify the set you wish
  661. /// to operate on. Then they call addObject or removeObject on the set, which
  662. /// sets up appropriate notifications.
  663. ///
  664. /// An object may be in multiple sets at a time.
  665. /// @{
  666. bool addToSet(SimObjectId);
  667. bool addToSet(const char *);
  668. bool removeFromSet(SimObjectId);
  669. bool removeFromSet(const char *);
  670. /// @}
  671. /// @name Serialization
  672. /// @{
  673. /// Determine whether or not a field should be written.
  674. ///
  675. /// @param fiedname The name of the field being written.
  676. /// @param value The value of the field.
  677. virtual bool writeField(StringTableEntry fieldname, const char* value);
  678. /// Output the TorqueScript to recreate this object.
  679. ///
  680. /// This calls writeFields internally.
  681. /// @param stream Stream to output to.
  682. /// @param tabStop Indentation level for this object.
  683. /// @param flags If SelectedOnly is passed here, then
  684. /// only objects marked as selected (using setSelected)
  685. /// will output themselves.
  686. virtual void write(Stream &stream, U32 tabStop, U32 flags = 0);
  687. /// Write the fields of this object in TorqueScript.
  688. ///
  689. /// @param stream Stream for output.
  690. /// @param tabStop Indentation level for the fields.
  691. virtual void writeFields(Stream &stream, U32 tabStop);
  692. virtual bool writeObject(Stream *stream);
  693. virtual bool readObject(Stream *stream);
  694. /// Set whether fields created at runtime should be saved. Default is true.
  695. void setCanSaveDynamicFields( bool bCanSave ) { mCanSaveFieldDictionary = bCanSave; }
  696. /// Get whether fields created at runtime should be saved. Default is true.
  697. bool getCanSaveDynamicFields( ) { return mCanSaveFieldDictionary;}
  698. /// Return the object that this object is copying fields from.
  699. SimObject* getCopySource() const { return mCopySource; }
  700. /// Set the object that this object should be copying fields from.
  701. void setCopySource( SimObject* object );
  702. /// Copy fields from another object onto this one.
  703. ///
  704. /// Objects must be of same type. Everything from obj
  705. /// will overwrite what's in this object; extra fields
  706. /// in this object will remain. This includes dynamic
  707. /// fields.
  708. ///
  709. /// @param obj Object to copy from.
  710. void assignFieldsFrom(SimObject *obj);
  711. /// Copy dynamic fields from another object onto this one.
  712. ///
  713. /// Everything from obj will overwrite what's in this
  714. /// object.
  715. ///
  716. /// @param obj Object to copy from.
  717. void assignDynamicFieldsFrom(SimObject *obj);
  718. /// @}
  719. /// Return the object's namespace.
  720. Namespace* getNamespace() { return mNameSpace; }
  721. /// Get next matching item in namespace.
  722. ///
  723. /// This wraps a call to Namespace::tabComplete; it gets the
  724. /// next thing in the namespace, given a starting value
  725. /// and a base length of the string. See
  726. /// Namespace::tabComplete for details.
  727. const char *tabComplete(const char *prevText, S32 baseLen, bool);
  728. /// @name Accessors
  729. /// @{
  730. bool isSelected() const { return mFlags.test(Selected); }
  731. bool isExpanded() const { return mFlags.test(Expanded); }
  732. bool isEditorOnly() const { return mFlags.test( EditorOnly ); }
  733. bool isNameChangeAllowed() const { return !mFlags.test( NoNameChange ); }
  734. bool isAutoDeleted() const { return mFlags.test( AutoDelete ); }
  735. void setSelected(bool sel);
  736. void setExpanded(bool exp) { if(exp) mFlags.set(Expanded); else mFlags.clear(Expanded); }
  737. void setModDynamicFields(bool dyn) { if(dyn) mFlags.set(ModDynamicFields); else mFlags.clear(ModDynamicFields); }
  738. void setModStaticFields(bool sta) { if(sta) mFlags.set(ModStaticFields); else mFlags.clear(ModStaticFields); }
  739. bool canModDynamicFields() { return mFlags.test(ModDynamicFields); }
  740. bool canModStaticFields() { return mFlags.test(ModStaticFields); }
  741. void setAutoDelete( bool val ) { if( val ) mFlags.set( AutoDelete ); else mFlags.clear( AutoDelete ); }
  742. void setEditorOnly( bool val ) { if( val ) mFlags.set( EditorOnly ); else mFlags.clear( EditorOnly ); }
  743. void setNameChangeAllowed( bool val ) { if( val ) mFlags.clear( NoNameChange ); else mFlags.set( NoNameChange ); }
  744. /// Returns boolean specifying if the object can be serialized.
  745. bool getCanSave() const { return !mFlags.test( CannotSave ); }
  746. /// Set serialization flag.
  747. virtual void setCanSave( bool val ) { if( !val ) mFlags.set( CannotSave ); else mFlags.clear( CannotSave ); }
  748. /// Returns true if this object is selected or any group it is a member of is.
  749. bool isSelectedRecursive() const;
  750. /// @}
  751. /// @name Namespace management
  752. /// @{
  753. /// Return name of class namespace set on this object.
  754. StringTableEntry getClassNamespace() const { return mClassName; };
  755. /// Return name of superclass namespace set on this object.
  756. StringTableEntry getSuperClassNamespace() const { return mSuperClassName; };
  757. ///
  758. void setClassNamespace( const char* classNamespace );
  759. ///
  760. void setSuperClassNamespace( const char* superClassNamespace );
  761. /// @}
  762. /// @name Persistent IDs
  763. /// @{
  764. /// Return the persistent ID assigned to this object or NULL.
  765. SimPersistID* getPersistentId() const { return mPersistentId; }
  766. /// Return the persistent ID assigned to this object or assign one to it if it has none.
  767. SimPersistID* getOrCreatePersistentId();
  768. /// @}
  769. /// @name Debugging
  770. /// @{
  771. /// Return a textual description of the object.
  772. virtual String describeSelf() const;
  773. /// Dump the contents of this object to the console. Use the Torque Script dump() and dumpF() functions to
  774. /// call this.
  775. void dumpToConsole( bool includeFunctions=true );
  776. ///added this so that you can print the entire class hierarchy, including script objects,
  777. //from the console or C++.
  778. /// Print the AbstractClassRep hierarchy of this object to the console.
  779. virtual void dumpClassHierarchy();
  780. /// Print the SimGroup hierarchy of this object to the console.
  781. virtual void dumpGroupHierarchy();
  782. /// @}
  783. static void initPersistFields();
  784. /// Copy SimObject to another SimObject (Originally designed for T2D).
  785. virtual void copyTo(SimObject* object);
  786. // Component Console Overrides
  787. virtual bool handlesConsoleMethod(const char * fname, S32 * routingId) { return false; }
  788. virtual void getConsoleMethodData(const char * fname, S32 routingId, S32 * type, S32 * minArgs, S32 * maxArgs, void ** callback, const char ** usage) {}
  789. DECLARE_CONOBJECT( SimObject );
  790. DECLARE_CALLBACK(void, onInspectPostApply, (SimObject* obj));
  791. static SimObject* __findObject( const char* id ) { return Sim::findObject( id ); }
  792. static const char* __getObjectId( ConsoleObject* object )
  793. {
  794. SimObject* simObject = static_cast< SimObject* >( object );
  795. if( !simObject )
  796. return "";
  797. else if( simObject->getName() )
  798. return simObject->getName();
  799. return simObject->getIdString();
  800. }
  801. // EngineObject.
  802. virtual void destroySelf();
  803. protected:
  804. bool is_temp_clone;
  805. public:
  806. /*C*/ SimObject(const SimObject&, bool = false);
  807. bool isTempClone() const { return is_temp_clone; }
  808. virtual bool allowSubstitutions() const { return false; }
  809. public:
  810. static bool preventNameChanging;
  811. void assignDynamicFieldsFrom(SimObject*, const char* filter, bool no_replace=false);
  812. public:
  813. virtual void reloadReset() { }
  814. };
  815. /// Smart SimObject pointer.
  816. ///
  817. /// This class keeps track of the book-keeping necessary
  818. /// to keep a registered reference to a SimObject or subclass
  819. /// thereof.
  820. ///
  821. /// Normally, if you want the SimObject to be aware that you
  822. /// have a reference to it, you must call SimObject::registerReference()
  823. /// when you create the reference, and SimObject::unregisterReference() when
  824. /// you're done. If you change the reference, you must also register/unregister
  825. /// it. This is a big headache, so this class exists to automatically
  826. /// keep track of things for you.
  827. ///
  828. /// @code
  829. /// // Assign an object to the
  830. /// SimObjectPtr<GameBase> mOrbitObject = Sim::findObject("anObject");
  831. ///
  832. /// // Use it as a GameBase*.
  833. /// mOrbitObject->getWorldBox().getCenter(&mPosition);
  834. ///
  835. /// // And reassign it - it will automatically update the references.
  836. /// mOrbitObject = Sim::findObject("anotherObject");
  837. /// @endcode
  838. template< typename T >
  839. class SimObjectPtr : public WeakRefPtr< T >
  840. {
  841. public:
  842. typedef WeakRefPtr< T > Parent;
  843. SimObjectPtr() {}
  844. SimObjectPtr(T *ptr) { this->mReference = NULL; set(ptr); }
  845. SimObjectPtr( const SimObjectPtr& ref ) { this->mReference = NULL; set(ref.mReference); }
  846. T* getObject() const { return Parent::getPointer(); }
  847. ~SimObjectPtr() { set((WeakRefBase::WeakReference*)NULL); }
  848. SimObjectPtr<T>& operator=(const SimObjectPtr ref)
  849. {
  850. set(ref.mReference);
  851. return *this;
  852. }
  853. SimObjectPtr<T>& operator=(T *ptr)
  854. {
  855. set(ptr);
  856. return *this;
  857. }
  858. protected:
  859. void set(WeakRefBase::WeakReference * ref)
  860. {
  861. if( ref == this->mReference )
  862. return;
  863. if( this->mReference )
  864. {
  865. // Auto-delete
  866. T* obj = this->getPointer();
  867. if ( this->mReference->getRefCount() == 2 && obj && obj->isAutoDeleted() )
  868. obj->deleteObject();
  869. this->mReference->decRefCount();
  870. }
  871. this->mReference = NULL;
  872. if( ref )
  873. {
  874. this->mReference = ref;
  875. this->mReference->incRefCount();
  876. }
  877. }
  878. void set(T * obj)
  879. {
  880. set(obj ? obj->getWeakReference() : (WeakRefBase::WeakReference *)NULL);
  881. }
  882. };
  883. #endif // _SIMOBJECT_H_