gameBase.h 18 KB

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