simObject.h 43 KB

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