simObject.h 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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. StringTableEntry mInheritFrom;
  287. /// SimGroup we're contained in, if any.
  288. SimGroup* mGroup;
  289. /// Flags internal to the object management system.
  290. BitSet32 mFlags;
  291. StringTableEntry mProgenitorFile;
  292. /// Object we are copying fields from.
  293. SimObject* mCopySource;
  294. /// Table of dynamic fields assigned to this object.
  295. SimFieldDictionary *mFieldDictionary;
  296. /// Buffer to store textual representation of this object's numeric ID in.
  297. char mIdString[ 11 ];
  298. /// @name Serialization
  299. /// @{
  300. /// Path to file this SimObject was loaded from.
  301. StringTableEntry mFilename;
  302. /// The line number that the object was declared on if it was loaded from a file.
  303. S32 mDeclarationLine;
  304. /// @}
  305. /// @name Notification
  306. /// @{
  307. /// List of notifications added to this object.
  308. Notify* mNotifyList;
  309. static SimObject::Notify *mNotifyFreeList;
  310. static SimObject::Notify *allocNotify(); ///< Get a free Notify structure.
  311. static void freeNotify(SimObject::Notify*); ///< Mark a Notify structure as free.
  312. /// @}
  313. static bool _setCanSave( void* object, const char* index, const char* data );
  314. static const char* _getCanSave( void* object, const char* data );
  315. static const char* _getHidden( void* object, const char* data )
  316. { if( static_cast< SimObject* >( object )->isHidden() ) return "1"; return "0"; }
  317. static const char* _getLocked( void* object, const char* data )
  318. { if( static_cast< SimObject* >( object )->isLocked() ) return "1"; return "0"; }
  319. static bool _setHidden( void* object, const char* index, const char* data )
  320. { static_cast< SimObject* >( object )->setHidden( dAtob( data ) ); return false; }
  321. static bool _setLocked( void* object, const char* index, const char* data )
  322. { static_cast< SimObject* >( object )->setLocked( dAtob( data ) ); return false; }
  323. // Namespace protected set methods
  324. static bool setClass( void *object, const char *index, const char *data )
  325. { static_cast<SimObject*>(object)->setClassNamespace(data); return false; };
  326. static bool setSuperClass(void *object, const char *index, const char *data)
  327. { static_cast<SimObject*>(object)->setSuperClassNamespace(data); return false; };
  328. static bool writeObjectName(void* obj, StringTableEntry pFieldName)
  329. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mObjectName != NULL && simObject->mObjectName != StringTable->EmptyString(); }
  330. static bool writeCanSaveDynamicFields(void* obj, StringTableEntry pFieldName)
  331. { return static_cast<SimObject*>(obj)->mCanSaveFieldDictionary == false; }
  332. static bool writeInternalName(void* obj, StringTableEntry pFieldName)
  333. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mInternalName != NULL && simObject->mInternalName != StringTable->EmptyString(); }
  334. static bool setParentGroup(void* obj, const char* data);
  335. static bool writeParentGroup(void* obj, StringTableEntry pFieldName)
  336. { return static_cast<SimObject*>(obj)->mGroup != NULL; }
  337. static bool writeSuperclass(void* obj, StringTableEntry pFieldName)
  338. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mSuperClassName != NULL && simObject->mSuperClassName != StringTable->EmptyString(); }
  339. static bool writeClass(void* obj, StringTableEntry pFieldName)
  340. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mClassName != NULL && simObject->mClassName != StringTable->EmptyString(); }
  341. static bool writeClassName(void* obj, StringTableEntry pFieldName)
  342. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mClassName != NULL && simObject->mClassName != StringTable->EmptyString(); }
  343. // Group hierarchy protected set method
  344. static bool setProtectedParent(void *object, const char *index, const char *data);
  345. // Object name protected set method
  346. static bool setProtectedName(void *object, const char *index, const char *data);
  347. // Sets object to inherit default values from
  348. static bool setInheritFrom(void* object, const char* index, const char* data);
  349. public:
  350. inline void setProgenitorFile(const char* pFile) { mProgenitorFile = StringTable->insert(pFile); }
  351. inline StringTableEntry getProgenitorFile(void) const { return mProgenitorFile; }
  352. protected:
  353. /// Taml callbacks.
  354. virtual void onTamlPreWrite(void) {}
  355. virtual void onTamlPostWrite(void) {}
  356. virtual void onTamlPreRead(void) {}
  357. virtual void onTamlPostRead(const TamlCustomNodes& customNodes) {}
  358. virtual void onTamlAddParent(SimObject* pParentObject) {}
  359. virtual void onTamlCustomWrite(TamlCustomNodes& customNodes) {}
  360. virtual void onTamlCustomRead(const TamlCustomNodes& customNodes);
  361. /// Id number for this object.
  362. SimObjectId mId;
  363. /// Internal name assigned to the object. Not set by default.
  364. StringTableEntry mInternalName;
  365. static bool smForceId; ///< Force a registered object to use the given Id. Cleared upon use.
  366. static SimObjectId smForcedId; ///< The Id to force upon the object. Poor object.
  367. /// @name Serialization
  368. /// @{
  369. /// Whether dynamic fields should be saved out in serialization. Defaults to true.
  370. bool mCanSaveFieldDictionary;
  371. /// @}
  372. /// @name Persistent IDs
  373. /// @{
  374. /// Persistent ID assigned to this object. Allows to unambiguously refer to this
  375. /// object in serializations regardless of stream object ordering.
  376. SimPersistID* mPersistentId;
  377. static bool _setPersistentID( void* object, const char* index, const char* data );
  378. /// @}
  379. /// @name Namespace management
  380. /// @{
  381. /// The namespace in which method lookup for this object begins.
  382. Namespace* mNameSpace;
  383. /// Name of namespace to use as class namespace.
  384. StringTableEntry mClassName;
  385. /// Name of namespace to use as class super namespace.
  386. StringTableEntry mSuperClassName;
  387. /// Perform namespace linking on this object.
  388. void linkNamespaces();
  389. /// Undo namespace linking on this object.
  390. void unlinkNamespaces();
  391. /// @}
  392. /// Called when the object is selected in the editor.
  393. virtual void _onSelected() {}
  394. /// Called when the object is unselected in the editor.
  395. virtual void _onUnselected() {}
  396. /// We can provide more detail, like object name and id.
  397. virtual String _getLogMessage(const char* fmt, va_list args) const;
  398. DEFINE_CREATE_METHOD
  399. {
  400. T* object = new T;
  401. object->incRefCount();
  402. return object;
  403. }
  404. // EngineObject.
  405. virtual void _destroySelf();
  406. public:
  407. /// @name Cloning
  408. /// @{
  409. /// Return a shallow copy of this object.
  410. virtual SimObject* clone();
  411. /// Return a deep copy of this object.
  412. virtual SimObject* deepClone();
  413. /// @}
  414. /// @name Accessors
  415. /// @{
  416. /// Get the value of a field on the object.
  417. ///
  418. /// See @ref simobject_console "here" for a detailed discussion of what this
  419. /// function does.
  420. ///
  421. /// @param slotName Field to access.
  422. /// @param array String containing index into array
  423. /// (if field is an array); if NULL, it is ignored.
  424. const char *getDataField(StringTableEntry slotName, const char *array);
  425. /// Set the value of a field on the object.
  426. ///
  427. /// See @ref simobject_console "here" for a detailed discussion of what this
  428. /// function does.
  429. ///
  430. /// @param slotName Field to access.
  431. /// @param array String containing index into array; if NULL, it is ignored.
  432. /// @param value Value to store.
  433. void setDataField(StringTableEntry slotName, const char *array, const char *value);
  434. const char *getPrefixedDataField(StringTableEntry fieldName, const char *array);
  435. void setPrefixedDataField(StringTableEntry fieldName, const char *array, const char *value);
  436. const char *getPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const S32 fieldType = -1);
  437. void setPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const char *value, const S32 fieldType = -1);
  438. StringTableEntry getDataFieldPrefix(StringTableEntry fieldName);
  439. /// Get the type of a field on the object.
  440. ///
  441. /// @param slotName Field to access.
  442. /// @param array String containing index into array
  443. /// (if field is an array); if NULL, it is ignored.
  444. U32 getDataFieldType(StringTableEntry slotName, const char *array);
  445. /// Set the type of a *dynamic* field on the object.
  446. ///
  447. /// @param typeName/Id Console base type name/id to assign to a dynamic field.
  448. /// @param slotName Field to access.
  449. /// @param array String containing index into array
  450. /// (if field is an array); if NULL, it is ignored.
  451. void setDataFieldType(const U32 fieldTypeId, StringTableEntry slotName, const char *array);
  452. void setDataFieldType(const char *typeName, StringTableEntry slotName, const char *array);
  453. /// Get reference to the dictionary containing dynamic fields.
  454. ///
  455. /// See @ref simobject_console "here" for a detailed discussion of what this
  456. /// function does.
  457. ///
  458. /// This dictionary can be iterated over using a SimFieldDictionaryIterator.
  459. SimFieldDictionary * getFieldDictionary() {return(mFieldDictionary);}
  460. // Component Information
  461. inline virtual StringTableEntry getComponentName() { return StringTable->insert( getClassName() ); };
  462. /// These functions support internal naming that is not namespace
  463. /// bound for locating child controls in a generic way.
  464. ///
  465. /// Set the internal name of this control (Not linked to a namespace)
  466. void setInternalName(const char* newname);
  467. /// Get the internal name of this control
  468. StringTableEntry getInternalName() const { return mInternalName; }
  469. /// Set the original name of this control
  470. void setOriginalName(const char* originalName);
  471. /// Get the original name of this control
  472. StringTableEntry getOriginalName() const { return mOriginalName; }
  473. /// These functions allow you to set and access the filename
  474. /// where this object was created.
  475. ///
  476. /// Set the filename
  477. void setFilename(const char* file);
  478. /// Get the filename
  479. StringTableEntry getFilename() const { return mFilename; }
  480. /// These functions are used to track the line number (1-based)
  481. /// on which the object was created if it was loaded from script
  482. ///
  483. /// Set the declaration line number
  484. void setDeclarationLine(U32 lineNumber);
  485. /// Get the declaration line number
  486. S32 getDeclarationLine() const { return mDeclarationLine; }
  487. /// Save object as a TorqueScript File.
  488. virtual bool save( const char* pcFilePath, bool bOnlySelected = false, const char *preappend = NULL );
  489. /// Check if a method exists in the objects current namespace.
  490. virtual bool isMethod( const char* methodName );
  491. /// Return true if the field is defined on the object
  492. virtual bool isField( const char* fieldName, bool includeStatic = true, bool includeDynamic = true );
  493. /// @}
  494. /// @name Initialization
  495. /// @{
  496. ///
  497. SimObject();
  498. virtual ~SimObject();
  499. virtual bool processArguments(S32 argc, ConsoleValue *argv); ///< Process constructor options. (ie, new SimObject(1,2,3))
  500. /// @}
  501. /// @name Events
  502. /// @{
  503. /// Called when the object is added to the sim.
  504. virtual bool onAdd();
  505. /// Called when the object is removed from the sim.
  506. virtual void onRemove();
  507. /// Called when the object is added to a SimGroup.
  508. virtual void onGroupAdd();
  509. /// Called when the object is removed from a SimGroup.
  510. virtual void onGroupRemove();
  511. /// Called when the object's name is changed.
  512. virtual void onNameChange(const char *name);
  513. /// Called when the adding of the object to the sim is complete, all sub-objects have been processed as well
  514. // This is a special-case function that only really gets used with Entities/BehaviorObjects.
  515. virtual void onPostAdd() {}
  516. ///
  517. /// Specifically, these are called by setDataField
  518. /// when a static or dynamic field is modified, see
  519. /// @ref simobject_console "the console details".
  520. virtual void onStaticModified(const char* slotName, const char*newValue = NULL); ///< Called when a static field is modified.
  521. virtual void onDynamicModified(const char* slotName, const char*newValue = NULL); ///< Called when a dynamic field is modified.
  522. /// Called before any property of the object is changed in the world editor.
  523. ///
  524. /// The calling order here is:
  525. /// - inspectPreApply()
  526. /// - ...
  527. /// - calls to setDataField()
  528. /// - ...
  529. /// - inspectPostApply()
  530. virtual void inspectPreApply();
  531. /// Called after any property of the object is changed in the world editor.
  532. ///
  533. /// @see inspectPreApply
  534. virtual void inspectPostApply();
  535. /// Called when a SimObject is deleted.
  536. ///
  537. /// When you are on the notification list for another object
  538. /// and it is deleted, this method is called.
  539. virtual void onDeleteNotify(SimObject *object);
  540. /// Called when the editor is activated.
  541. virtual void onEditorEnable(){};
  542. /// Called when the editor is deactivated.
  543. virtual void onEditorDisable(){};
  544. /// Called when the object is inspected via a GuiInspector control
  545. virtual void onInspect(GuiInspector*) {};
  546. /// @}
  547. /// Find a named sub-object of this object.
  548. ///
  549. /// This is subclassed in the SimGroup and SimSet classes.
  550. ///
  551. /// For a single object, it just returns NULL, as normal objects cannot have children.
  552. virtual SimObject *findObject(const char *name);
  553. /// @name Notification
  554. /// @{
  555. Notify *removeNotify(void *ptr, Notify::Type); ///< Remove a notification from the list.
  556. void deleteNotify(SimObject* obj); ///< Notify an object when we are deleted.
  557. void clearNotify(SimObject* obj); ///< Notify an object when we are cleared.
  558. void clearAllNotifications(); ///< Remove all notifications for this object.
  559. void processDeleteNotifies(); ///< Send out deletion notifications.
  560. /// Register a reference to this object.
  561. ///
  562. /// You pass a pointer to your reference to this object.
  563. ///
  564. /// When the object is deleted, it will null your
  565. /// pointer, ensuring you don't access old memory.
  566. ///
  567. /// @param obj Pointer to your reference to the object.
  568. void registerReference(SimObject **obj);
  569. /// Unregister a reference to this object.
  570. ///
  571. /// Remove a reference from the list, so that it won't
  572. /// get nulled inappropriately.
  573. ///
  574. /// Call this when you're done with your reference to
  575. /// the object, especially if you're going to free the
  576. /// memory. Otherwise, you may erroneously get something
  577. /// overwritten.
  578. ///
  579. /// @see registerReference
  580. void unregisterReference(SimObject **obj);
  581. /// @}
  582. /// @name Registration
  583. ///
  584. /// SimObjects must be registered with the object system.
  585. /// @{
  586. /// Register an object with the object system.
  587. ///
  588. /// This must be called if you want to keep the object around.
  589. /// In the rare case that you will delete the object immediately, or
  590. /// don't want to be able to use Sim::findObject to locate it, then
  591. /// you don't need to register it.
  592. ///
  593. /// registerObject adds the object to the global ID and name dictionaries,
  594. /// after first assigning it a new ID number. It calls onAdd(). If onAdd fails,
  595. /// it unregisters the object and returns false.
  596. ///
  597. /// If a subclass's onAdd doesn't eventually call SimObject::onAdd(), it will
  598. /// cause an assertion.
  599. bool registerObject();
  600. /// Register the object, forcing the id.
  601. ///
  602. /// @see registerObject()
  603. /// @param id ID to assign to the object.
  604. bool registerObject(U32 id);
  605. /// Register the object, assigning the name.
  606. ///
  607. /// @see registerObject()
  608. /// @param name Name to assign to the object.
  609. bool registerObject(const char *name);
  610. /// Register the object, assigning a name and ID.
  611. ///
  612. /// @see registerObject()
  613. /// @param name Name to assign to the object.
  614. /// @param id ID to assign to the object.
  615. bool registerObject(const char *name, U32 id);
  616. /// Unregister the object from Sim.
  617. ///
  618. /// This performs several operations:
  619. /// - Sets the removed flag.
  620. /// - Call onRemove()
  621. /// - Clear out notifications.
  622. /// - Remove the object from...
  623. /// - its group, if any. (via getGroup)
  624. /// - Sim::gNameDictionary
  625. /// - Sim::gIDDictionary
  626. /// - Finally, cancel any pending events for this object (as it can't receive them now).
  627. void unregisterObject();
  628. /// Unregister, mark as deleted, and free the object.
  629. void deleteObject();
  630. /// Performs a safe delayed delete of the object using a sim event.
  631. void safeDeleteObject();
  632. /// Special-case deletion behaviors, largely intended for cleanup in particular cases where it wouldn't happen automatically(like cleanup of associated files)
  633. virtual void handleDeleteAction() {}
  634. /// @}
  635. /// @name Accessors
  636. /// @{
  637. /// Return the unique numeric object ID.
  638. SimObjectId getId() const { return mId; }
  639. /// Return the object ID as a string.
  640. const char* getIdString() const { return mIdString; }
  641. /// Return the name of this object.
  642. StringTableEntry getName() const { return mObjectName; }
  643. /// Return the SimGroup that this object is contained in. Never NULL except for
  644. /// RootGroup and unregistered objects.
  645. SimGroup* getGroup() const { return mGroup; }
  646. /// Assign the given name to this object.
  647. void assignName( const char* name );
  648. void setId(SimObjectId id);
  649. static void setForcedId(SimObjectId id) { smForceId = true; smForcedId = id; } ///< Force an Id on the next registered object.
  650. bool isChildOfGroup(SimGroup* pGroup);
  651. bool isProperlyAdded() const { return mFlags.test(Added); }
  652. bool isDeleted() const { return mFlags.test(Deleted); }
  653. bool isRemoved() const { return mFlags.test(Deleted | Removed); }
  654. virtual bool isLocked() const { return mFlags.test( Locked ); }
  655. virtual void setLocked( bool b );
  656. virtual bool isHidden() const { return mFlags.test( Hidden ); }
  657. virtual void setHidden(bool b);
  658. /// @}
  659. /// @name Sets
  660. ///
  661. /// The object must be properly registered before you can add/remove it to/from a set.
  662. ///
  663. /// All these functions accept either a name or ID to identify the set you wish
  664. /// to operate on. Then they call addObject or removeObject on the set, which
  665. /// sets up appropriate notifications.
  666. ///
  667. /// An object may be in multiple sets at a time.
  668. /// @{
  669. bool addToSet(SimObjectId);
  670. bool addToSet(const char *);
  671. bool removeFromSet(SimObjectId);
  672. bool removeFromSet(const char *);
  673. /// @}
  674. /// @name Serialization
  675. /// @{
  676. /// Determine whether or not a field should be written.
  677. ///
  678. /// @param fiedname The name of the field being written.
  679. /// @param value The value of the field.
  680. virtual bool writeField(StringTableEntry fieldname, const char* value);
  681. /// Output the TorqueScript to recreate this object.
  682. ///
  683. /// This calls writeFields internally.
  684. /// @param stream Stream to output to.
  685. /// @param tabStop Indentation level for this object.
  686. /// @param flags If SelectedOnly is passed here, then
  687. /// only objects marked as selected (using setSelected)
  688. /// will output themselves.
  689. virtual void write(Stream &stream, U32 tabStop, U32 flags = 0);
  690. /// Write the fields of this object in TorqueScript.
  691. ///
  692. /// @param stream Stream for output.
  693. /// @param tabStop Indentation level for the fields.
  694. virtual void writeFields(Stream &stream, U32 tabStop);
  695. virtual bool writeObject(Stream *stream);
  696. virtual bool readObject(Stream *stream);
  697. /// Set whether fields created at runtime should be saved. Default is true.
  698. void setCanSaveDynamicFields( bool bCanSave ) { mCanSaveFieldDictionary = bCanSave; }
  699. /// Get whether fields created at runtime should be saved. Default is true.
  700. bool getCanSaveDynamicFields( ) { return mCanSaveFieldDictionary;}
  701. /// Return the object that this object is copying fields from.
  702. SimObject* getCopySource() const { return mCopySource; }
  703. /// Set the object that this object should be copying fields from.
  704. void setCopySource( SimObject* object );
  705. /// Copy fields from another object onto this one.
  706. ///
  707. /// Objects must be of same type. Everything from obj
  708. /// will overwrite what's in this object; extra fields
  709. /// in this object will remain. This includes dynamic
  710. /// fields.
  711. ///
  712. /// @param obj Object to copy from.
  713. void assignFieldsFrom(SimObject *obj);
  714. /// Copy dynamic fields from another object onto this one.
  715. ///
  716. /// Everything from obj will overwrite what's in this
  717. /// object.
  718. ///
  719. /// @param obj Object to copy from.
  720. void assignDynamicFieldsFrom(SimObject *obj);
  721. /// @}
  722. /// Return the object's namespace.
  723. Namespace* getNamespace() { return mNameSpace; }
  724. /// Get next matching item in namespace.
  725. ///
  726. /// This wraps a call to Namespace::tabComplete; it gets the
  727. /// next thing in the namespace, given a starting value
  728. /// and a base length of the string. See
  729. /// Namespace::tabComplete for details.
  730. const char *tabComplete(const char *prevText, S32 baseLen, bool);
  731. /// @name Accessors
  732. /// @{
  733. bool isSelected() const { return mFlags.test(Selected); }
  734. bool isExpanded() const { return mFlags.test(Expanded); }
  735. bool isEditorOnly() const { return mFlags.test( EditorOnly ); }
  736. bool isNameChangeAllowed() const { return !mFlags.test( NoNameChange ); }
  737. bool isAutoDeleted() const { return mFlags.test( AutoDelete ); }
  738. void setSelected(bool sel);
  739. void setExpanded(bool exp) { if(exp) mFlags.set(Expanded); else mFlags.clear(Expanded); }
  740. void setModDynamicFields(bool dyn) { if(dyn) mFlags.set(ModDynamicFields); else mFlags.clear(ModDynamicFields); }
  741. void setModStaticFields(bool sta) { if(sta) mFlags.set(ModStaticFields); else mFlags.clear(ModStaticFields); }
  742. bool canModDynamicFields() { return mFlags.test(ModDynamicFields); }
  743. bool canModStaticFields() { return mFlags.test(ModStaticFields); }
  744. void setAutoDelete( bool val ) { if( val ) mFlags.set( AutoDelete ); else mFlags.clear( AutoDelete ); }
  745. void setEditorOnly( bool val ) { if( val ) mFlags.set( EditorOnly ); else mFlags.clear( EditorOnly ); }
  746. void setNameChangeAllowed( bool val ) { if( val ) mFlags.clear( NoNameChange ); else mFlags.set( NoNameChange ); }
  747. /// Returns boolean specifying if the object can be serialized.
  748. bool getCanSave() const { return !mFlags.test( CannotSave ); }
  749. /// Set serialization flag.
  750. virtual void setCanSave( bool val ) { if( !val ) mFlags.set( CannotSave ); else mFlags.clear( CannotSave ); }
  751. /// Returns true if this object is selected or any group it is a member of is.
  752. bool isSelectedRecursive() const;
  753. /// @}
  754. /// @name Namespace management
  755. /// @{
  756. /// Return name of class namespace set on this object.
  757. StringTableEntry getClassNamespace() const { return mClassName; };
  758. /// Return name of superclass namespace set on this object.
  759. StringTableEntry getSuperClassNamespace() const { return mSuperClassName; };
  760. ///
  761. void setClassNamespace( const char* classNamespace );
  762. ///
  763. void setSuperClassNamespace( const char* superClassNamespace );
  764. /// @}
  765. /// @name Persistent IDs
  766. /// @{
  767. /// Return the persistent ID assigned to this object or NULL.
  768. SimPersistID* getPersistentId() const { return mPersistentId; }
  769. /// Return the persistent ID assigned to this object or assign one to it if it has none.
  770. SimPersistID* getOrCreatePersistentId();
  771. /// @}
  772. /// @name Debugging
  773. /// @{
  774. /// Return a textual description of the object.
  775. virtual String describeSelf() const;
  776. /// Dump the contents of this object to the console. Use the Torque Script dump() and dumpF() functions to
  777. /// call this.
  778. void dumpToConsole( bool includeFunctions=true );
  779. ///added this so that you can print the entire class hierarchy, including script objects,
  780. //from the console or C++.
  781. /// Print the AbstractClassRep hierarchy of this object to the console.
  782. virtual void dumpClassHierarchy();
  783. /// Print the SimGroup hierarchy of this object to the console.
  784. virtual void dumpGroupHierarchy();
  785. /// @}
  786. static void initPersistFields();
  787. /// Copy SimObject to another SimObject (Originally designed for T2D).
  788. virtual void copyTo(SimObject* object);
  789. // Component Console Overrides
  790. virtual bool handlesConsoleMethod(const char * fname, S32 * routingId) { return false; }
  791. virtual void getConsoleMethodData(const char * fname, S32 routingId, S32 * type, S32 * minArgs, S32 * maxArgs, void ** callback, const char ** usage) {}
  792. DECLARE_CONOBJECT( SimObject );
  793. DECLARE_CALLBACK(void, onInspectPostApply, (SimObject* obj));
  794. static SimObject* __findObject( const char* id ) { return Sim::findObject( id ); }
  795. static const char* __getObjectId( ConsoleObject* object )
  796. {
  797. SimObject* simObject = static_cast< SimObject* >( object );
  798. if( !simObject )
  799. return "";
  800. else if( simObject->getName() )
  801. return simObject->getName();
  802. return simObject->getIdString();
  803. }
  804. // EngineObject.
  805. virtual void destroySelf();
  806. protected:
  807. bool is_temp_clone;
  808. public:
  809. /*C*/ SimObject(const SimObject&, bool = false);
  810. bool isTempClone() const { return is_temp_clone; }
  811. virtual bool allowSubstitutions() const { return false; }
  812. public:
  813. static bool preventNameChanging;
  814. void assignDynamicFieldsFrom(SimObject*, const char* filter, bool no_replace=false);
  815. public:
  816. virtual void reloadReset() { }
  817. };
  818. /// Smart SimObject pointer.
  819. ///
  820. /// This class keeps track of the book-keeping necessary
  821. /// to keep a registered reference to a SimObject or subclass
  822. /// thereof.
  823. ///
  824. /// Normally, if you want the SimObject to be aware that you
  825. /// have a reference to it, you must call SimObject::registerReference()
  826. /// when you create the reference, and SimObject::unregisterReference() when
  827. /// you're done. If you change the reference, you must also register/unregister
  828. /// it. This is a big headache, so this class exists to automatically
  829. /// keep track of things for you.
  830. ///
  831. /// @code
  832. /// // Assign an object to the
  833. /// SimObjectPtr<GameBase> mOrbitObject = Sim::findObject("anObject");
  834. ///
  835. /// // Use it as a GameBase*.
  836. /// mOrbitObject->getWorldBox().getCenter(&mPosition);
  837. ///
  838. /// // And reassign it - it will automatically update the references.
  839. /// mOrbitObject = Sim::findObject("anotherObject");
  840. /// @endcode
  841. template< typename T >
  842. class SimObjectPtr : public WeakRefPtr< T >
  843. {
  844. public:
  845. typedef WeakRefPtr< T > Parent;
  846. SimObjectPtr() {}
  847. SimObjectPtr(T *ptr) { this->mReference = NULL; set(ptr); }
  848. SimObjectPtr( const SimObjectPtr& ref ) { this->mReference = NULL; set(ref.mReference); }
  849. T* getObject() const { return Parent::getPointer(); }
  850. ~SimObjectPtr() { set((WeakRefBase::WeakReference*)NULL); }
  851. SimObjectPtr<T>& operator=(const SimObjectPtr ref)
  852. {
  853. set(ref.mReference);
  854. return *this;
  855. }
  856. SimObjectPtr<T>& operator=(T *ptr)
  857. {
  858. set(ptr);
  859. return *this;
  860. }
  861. protected:
  862. void set(WeakRefBase::WeakReference * ref)
  863. {
  864. if( ref == this->mReference )
  865. return;
  866. if( this->mReference )
  867. {
  868. // Auto-delete
  869. T* obj = this->getPointer();
  870. if ( this->mReference->getRefCount() == 2 && obj && obj->isAutoDeleted() )
  871. obj->deleteObject();
  872. this->mReference->decRefCount();
  873. }
  874. this->mReference = NULL;
  875. if( ref )
  876. {
  877. this->mReference = ref;
  878. this->mReference->incRefCount();
  879. }
  880. }
  881. void set(T * obj)
  882. {
  883. set(obj ? obj->getWeakReference() : (WeakRefBase::WeakReference *)NULL);
  884. }
  885. };
  886. #endif // _SIMOBJECT_H_