2
0

simObject.h 42 KB

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