gameBase.h 17 KB

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