gameBase.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 _GAMEBASE_H_
  27. #define _GAMEBASE_H_
  28. #ifndef _SCENEOBJECT_H_
  29. #include "scene/sceneObject.h"
  30. #endif
  31. #ifndef _PROCESSLIST_H_
  32. #include "T3D/gameBase/processList.h"
  33. #endif
  34. #ifndef _TICKCACHE_H_
  35. #include "T3D/gameBase/tickCache.h"
  36. #endif
  37. #ifndef _DYNAMIC_CONSOLETYPES_H_
  38. #include "console/dynamicTypes.h"
  39. #endif
  40. #ifndef __SCENEMANAGER_H__
  41. #include "scene/sceneManager.h"
  42. #define __SCENEMANAGER_H__
  43. #endif
  44. #ifndef _IDISPLAYDEVICE_H_
  45. #include "platform/output/IDisplayDevice.h"
  46. #endif
  47. class NetConnection;
  48. class ProcessList;
  49. class GameBase;
  50. struct Move;
  51. //----------------------------------------------------------------------------
  52. //----------------------------------------------------------------------------
  53. /// Scriptable, demo-able datablock.
  54. ///
  55. /// This variant of SimDataBlock performs these additional tasks:
  56. /// - Linking datablock's namepsaces to the namespace of their C++ class, so
  57. /// that datablocks can expose script functionality.
  58. /// - Linking datablocks to a user defined scripting namespace, by setting the
  59. /// 'class' field at datablock definition time.
  60. /// - Adds a category field; this is used by the world creator in the editor to
  61. /// classify creatable shapes. Creatable shapes are placed under the Shapes
  62. /// node in the treeview for this; additional levels are created, named after
  63. /// the category fields.
  64. /// - Adds support for demo stream recording. This support takes the form
  65. /// of the member variable packed. When a demo is being recorded by a client,
  66. /// data is unpacked, then packed again to the data stream, then, in the case
  67. /// of datablocks, preload() is called to process the data. It is occasionally
  68. /// the case that certain references in the datablock stream cannot be resolved
  69. /// until preload is called, in which case a raw ID field is stored in the variable
  70. /// which will eventually be used to store a pointer to the object. However, if
  71. /// packData() is called before we resolve this ID, trying to call getID() on the
  72. /// objecct ID would be a fatal error. Therefore, in these cases, we test packed;
  73. /// if it is true, then we know we have to write the raw data, instead of trying
  74. /// to resolve an ID.
  75. ///
  76. /// @see SimDataBlock for further details about datablocks.
  77. /// @see http://hosted.tribalwar.com/t2faq/datablocks.shtml for an excellent
  78. /// explanation of the basics of datablocks from a scripting perspective.
  79. /// @nosubgrouping
  80. struct GameBaseData : public SimDataBlock
  81. {
  82. private:
  83. typedef SimDataBlock Parent;
  84. public:
  85. bool mPacked;
  86. StringTableEntry mCategory;
  87. // Signal triggered when this datablock is modified.
  88. // GameBase objects referencing this datablock notify with this signal.
  89. Signal<void(void)> mReloadSignal;
  90. // Triggers the reload signal.
  91. void inspectPostApply();
  92. bool onAdd();
  93. // The derived class should provide the following:
  94. DECLARE_CONOBJECT(GameBaseData);
  95. GameBaseData();
  96. static void initPersistFields();
  97. bool preload(bool server, String &errorStr);
  98. void unpackData(BitStream* stream);
  99. /// @name Callbacks
  100. /// @{
  101. DECLARE_CALLBACK( void, onAdd, ( GameBase* obj ) );
  102. DECLARE_CALLBACK( void, onRemove, ( GameBase* obj ) );
  103. DECLARE_CALLBACK( void, onNewDataBlock, ( GameBase* obj ) );
  104. DECLARE_CALLBACK( void, onMount, ( SceneObject* obj, SceneObject* mountObj, S32 node ) );
  105. DECLARE_CALLBACK( void, onUnmount, ( SceneObject* obj, SceneObject* mountObj, S32 node ) );
  106. /// @}
  107. public:
  108. GameBaseData(const GameBaseData&, bool = false);
  109. };
  110. //----------------------------------------------------------------------------
  111. // A few utility methods for sending datablocks over the net
  112. //----------------------------------------------------------------------------
  113. bool UNPACK_DB_ID(BitStream *, U32 & id);
  114. bool PACK_DB_ID(BitStream *, U32 id);
  115. bool PRELOAD_DB(U32 & id, SimDataBlock **, bool server, const char * clientMissing = NULL, const char * serverMissing = NULL);
  116. //----------------------------------------------------------------------------
  117. class GameConnection;
  118. class WaterObject;
  119. class MoveList;
  120. // For truly it is written: "The wise man extends GameBase for his purposes,
  121. // while the fool has the ability to eject shell casings from the belly of his
  122. // dragon." -- KillerBunny
  123. /// Base class for game objects which use datablocks, networking, are editable,
  124. /// and need to process ticks.
  125. ///
  126. /// @section GameBase_process GameBase and ProcessList
  127. ///
  128. /// GameBase adds two kinds of time-based updates. Torque works off of a concept
  129. /// of ticks. Ticks are slices of time 32 milliseconds in length. There are three
  130. /// methods which are used to update GameBase objects that are registered with
  131. /// the ProcessLists:
  132. /// - processTick(Move*) is called on each object once for every tick, regardless
  133. /// of the "real" framerate.
  134. /// - interpolateTick(float) is called on client objects when they need to interpolate
  135. /// to match the next tick.
  136. /// - advanceTime(float) is called on client objects so they can do time-based behaviour,
  137. /// like updating animations.
  138. ///
  139. /// Torque maintains a server and a client processing list; in a local game, both
  140. /// are populated, while in multiplayer situations, either one or the other is
  141. /// populated.
  142. ///
  143. /// You can control whether an object is considered for ticking by means of the
  144. /// setProcessTick() method.
  145. ///
  146. /// @section GameBase_datablock GameBase and Datablocks
  147. ///
  148. /// GameBase adds support for datablocks. Datablocks are secondary classes which store
  149. /// static data for types of game elements. For instance, this means that all "light human
  150. /// male armor" type Players share the same datablock. Datablocks typically store not only
  151. /// raw data, but perform precalculations, like finding nodes in the game model, or
  152. /// validating movement parameters.
  153. ///
  154. /// There are three parts to the datablock interface implemented in GameBase:
  155. /// - <b>getDataBlock()</b>, which gets a pointer to the current datablock. This is
  156. /// mostly for external use; for in-class use, it's better to directly access the
  157. /// mDataBlock member.
  158. /// - <b>setDataBlock()</b>, which sets mDataBlock to point to a new datablock; it
  159. /// uses the next part of the interface to inform subclasses of this.
  160. /// - <b>onNewDataBlock()</b> is called whenever a new datablock is assigned to a GameBase.
  161. ///
  162. /// Datablocks are also usable through the scripting language.
  163. ///
  164. /// @see SimDataBlock for more details.
  165. ///
  166. /// @section GameBase_networking GameBase and Networking
  167. ///
  168. /// writePacketData() and readPacketData() are called to transfer information needed for client
  169. /// side prediction. They are usually used when updating a client of its control object state.
  170. ///
  171. /// Subclasses of GameBase usually transmit positional and basic status data in the packUpdate()
  172. /// functions, while giving velocity, momentum, and similar state information in the writePacketData().
  173. ///
  174. /// writePacketData()/readPacketData() are called <i>in addition</i> to packUpdate/unpackUpdate().
  175. ///
  176. /// @nosubgrouping
  177. class GameBase : public SceneObject
  178. {
  179. typedef SceneObject Parent;
  180. /// @name Datablock
  181. /// @{
  182. GameBaseData* mDataBlock;
  183. /// @}
  184. TickCache mTickCache;
  185. // Control interface
  186. GameConnection* mControllingClient;
  187. public:
  188. static bool gShowBoundingBox; ///< Should we render bounding boxes?
  189. protected:
  190. F32 mCameraFov;
  191. /// The WaterObject we are currently within.
  192. WaterObject *mCurrentWaterObject;
  193. static bool setDataBlockProperty( void *object, const char *index, const char *data );
  194. #ifdef TORQUE_DEBUG_NET_MOVES
  195. U32 mLastMoveId;
  196. U32 mTicksSinceLastMove;
  197. bool mIsAiControlled;
  198. #endif
  199. public:
  200. GameBase();
  201. ~GameBase();
  202. enum GameBaseMasks {
  203. DataBlockMask = Parent::NextFreeMask << 0,
  204. ExtendedInfoMask = Parent::NextFreeMask << 1,
  205. ScopeIdMask = Parent::NextFreeMask << 2,
  206. NextFreeMask = Parent::NextFreeMask << 3,
  207. };
  208. // net flags added by game base
  209. enum
  210. {
  211. NetOrdered = BIT(Parent::MaxNetFlagBit+1), /// Process in same order on client and server.
  212. NetNearbyAdded = BIT(Parent::MaxNetFlagBit+2), /// Is set during client catchup when neighbors have been checked.
  213. GhostUpdated = BIT(Parent::MaxNetFlagBit+3), /// Is set whenever ghost updated (and reset) on the client, for hifi objects.
  214. TickLast = BIT(Parent::MaxNetFlagBit+4), /// Tick this object after all others.
  215. NewGhost = BIT(Parent::MaxNetFlagBit+5), /// This ghost was just added during the last update.
  216. HiFiPassive = BIT(Parent::MaxNetFlagBit+6), /// Do not interact with other hifi passive objects.
  217. MaxNetFlagBit = Parent::MaxNetFlagBit+6
  218. };
  219. /// @name Inherited Functionality.
  220. /// @{
  221. bool onAdd();
  222. void onRemove();
  223. void inspectPostApply();
  224. static void initPersistFields();
  225. static void consoleInit();
  226. /// @}
  227. ///@name Datablock
  228. ///@{
  229. /// Assigns this object a datablock and loads attributes with onNewDataBlock.
  230. ///
  231. /// @see onNewDataBlock
  232. /// @param dptr Datablock
  233. bool setDataBlock( GameBaseData *dptr );
  234. /// Returns the datablock for this object.
  235. GameBaseData* getDataBlock() { return mDataBlock; }
  236. /// Called when a new datablock is set. This allows subclasses to
  237. /// appropriately handle new datablocks.
  238. ///
  239. /// @see setDataBlock()
  240. /// @param dptr New datablock
  241. /// @param reload Is this a new datablock or are we reloading one
  242. /// we already had.
  243. virtual bool onNewDataBlock( GameBaseData *dptr, bool reload );
  244. ///@}
  245. /// @name Script
  246. /// The scriptOnXX methods are invoked by the leaf classes
  247. /// @{
  248. /// Executes the 'onAdd' script function for this object.
  249. /// @note This must be called after everything is ready
  250. void scriptOnAdd();
  251. /// Executes the 'onNewDataBlock' script function for this object.
  252. ///
  253. /// @note This must be called after everything is loaded.
  254. void scriptOnNewDataBlock();
  255. /// Executes the 'onRemove' script function for this object.
  256. /// @note This must be called while the object is still valid
  257. void scriptOnRemove();
  258. /// @}
  259. // ProcessObject override
  260. void processTick( const Move *move );
  261. /// @name GameBase NetFlags & Hifi-Net Interface
  262. /// @{
  263. /// Set or clear the GhostUpdated bit in our NetFlags.
  264. /// @see GhostUpdated
  265. void setGhostUpdated( bool b ) { if (b) mNetFlags.set(GhostUpdated); else mNetFlags.clear(GhostUpdated); }
  266. /// Returns true if the GhostUpdated bit in our NetFlags is set.
  267. /// @see GhostUpdated
  268. bool isGhostUpdated() const { return mNetFlags.test(GhostUpdated); }
  269. /// Set or clear the NewGhost bit in our NetFlags.
  270. /// @see NewGhost
  271. void setNewGhost( bool n ) { if (n) mNetFlags.set(NewGhost); else mNetFlags.clear(NewGhost); }
  272. /// Returns true if the NewGhost bit in out NetFlags is set.
  273. /// @see NewGhost
  274. bool isNewGhost() const { return mNetFlags.test(NewGhost); }
  275. /// Set or clear the NetNearbyAdded bit in our NetFlags.
  276. /// @see NetNearbyAdded
  277. void setNetNearbyAdded( bool b ) { if (b) mNetFlags.set(NetNearbyAdded); else mNetFlags.clear(NetNearbyAdded); }
  278. /// Returns true if the NetNearby bit in our NetFlags is set.
  279. /// @see NetNearbyAdded
  280. bool isNetNearbyAdded() const { return mNetFlags.test(NetNearbyAdded); }
  281. /// Returns true if the HiFiPassive bit in our NetFlags is set.
  282. /// @see HiFiPassive
  283. bool isHifiPassive() const { return mNetFlags.test(HiFiPassive); }
  284. /// Returns true if the TickLast bit in our NetFlags is set.
  285. /// @see TickLast
  286. bool isTickLast() const { return mNetFlags.test(TickLast); }
  287. /// Returns true if the NetOrdered bit in our NetFlags is set.
  288. /// @see NetOrdered
  289. bool isNetOrdered() const { return mNetFlags.test(NetOrdered); }
  290. /// Called during client catchup under the hifi-net model.
  291. virtual void computeNetSmooth( F32 backDelta ) {}
  292. /// Returns TickCache used under the hifi-net model.
  293. TickCache& getTickCache() { return mTickCache; }
  294. /// @}
  295. /// @name Network
  296. /// @see NetObject, NetConnection
  297. /// @{
  298. void interpolateTick(F32 dt);
  299. F32 getUpdatePriority( CameraScopeQuery *focusObject, U32 updateMask, S32 updateSkips );
  300. U32 packUpdate ( NetConnection *conn, U32 mask, BitStream *stream );
  301. void unpackUpdate( NetConnection *conn, BitStream *stream );
  302. /// Write state information necessary to perform client side prediction of an object.
  303. ///
  304. /// This information is sent only to the controlling object. For example, if you are a client
  305. /// controlling a Player, the server uses writePacketData() instead of packUpdate() to
  306. /// generate the data you receive.
  307. ///
  308. /// @param conn Connection for which we're generating this data.
  309. /// @param stream Bitstream for output.
  310. virtual void writePacketData( GameConnection *conn, BitStream *stream );
  311. /// Read data written with writePacketData() and update the object state.
  312. ///
  313. /// @param conn Connection for which we're generating this data.
  314. /// @param stream Bitstream to read.
  315. virtual void readPacketData( GameConnection *conn, BitStream *stream );
  316. /// Gets the checksum for packet data.
  317. ///
  318. /// Basically writes a packet, does a CRC check on it, and returns
  319. /// that CRC.
  320. ///
  321. /// @see writePacketData
  322. /// @param conn Game connection
  323. virtual U32 getPacketDataChecksum( GameConnection *conn );
  324. ///@}
  325. /// @name Mounted objects ( overrides )
  326. /// @{
  327. public:
  328. virtual void onMount( SceneObject *obj, S32 node );
  329. virtual void onUnmount( SceneObject *obj,S32 node );
  330. /// @}
  331. /// @name User control
  332. /// @{
  333. /// Returns the client controlling this object
  334. GameConnection *getControllingClient() { return mControllingClient; }
  335. const GameConnection *getControllingClient() const { return mControllingClient; }
  336. /// Returns the MoveList of the client controlling this object.
  337. /// If there is no client it returns NULL;
  338. MoveList* getMoveList();
  339. /// Sets the client controlling this object
  340. /// @param client Client that is now controlling this object
  341. virtual void setControllingClient( GameConnection *client );
  342. virtual GameBase * getControllingObject() { return NULL; }
  343. virtual GameBase * getControlObject() { return NULL; }
  344. virtual void setControlObject( GameBase * ) { }
  345. /// @}
  346. virtual F32 getDefaultCameraFov() { return 90.f; }
  347. virtual F32 getCameraFov() { return 90.f; }
  348. virtual void setCameraFov( F32 fov ) { }
  349. virtual bool isValidCameraFov( F32 fov ) { return true; }
  350. virtual bool useObjsEyePoint() const { return false; }
  351. virtual bool onlyFirstPerson() const { return false; }
  352. virtual F32 getDamageFlash() const { return 0.0f; }
  353. virtual F32 getWhiteOut() const { return 0.0f; }
  354. // Not implemented here, but should return the Camera to world transformation matrix
  355. virtual void getCameraTransform (F32 *pos, MatrixF *mat ) { *mat = MatrixF::Identity; }
  356. virtual void getEyeCameraTransform ( IDisplayDevice *device, U32 eyeId, MatrixF *mat ) { *mat = MatrixF::Identity; }
  357. /// Returns the water object we are colliding with, it is up to derived
  358. /// classes to actually set this object.
  359. virtual WaterObject* getCurrentWaterObject() { return mCurrentWaterObject; }
  360. #ifdef TORQUE_DEBUG_NET_MOVES
  361. bool isAIControlled() const { return mIsAiControlled; }
  362. #endif
  363. DECLARE_CONOBJECT (GameBase );
  364. /// @name Callbacks
  365. /// @{
  366. DECLARE_CALLBACK( void, setControl, ( bool controlled ) );
  367. /// @}
  368. private:
  369. /// This is called by the reload signal in our datablock when it is
  370. /// modified in the editor.
  371. ///
  372. /// This method is private and is not virtual. To handle a datablock-modified
  373. /// even in a child-class specific way you should override onNewDatablock
  374. /// and handle the reload( true ) case.
  375. ///
  376. /// Warning: For local-client, editor situations only.
  377. ///
  378. /// Warning: Do not attempt to call .remove or .notify on mDataBlock->mReloadSignal
  379. /// within this callback.
  380. ///
  381. void _onDatablockModified();
  382. protected:
  383. void onScopeIdChange() { setMaskBits(ScopeIdMask); }
  384. };
  385. #endif // _GAMEBASE_H_