Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2015
364
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 27.10 KB | None | 0 0
  1. /*
  2.  *  Copyright (c) 2014, Oculus VR, Inc.
  3.  *  All rights reserved.
  4.  *
  5.  *  This source code is licensed under the BSD-style license found in the
  6.  *  LICENSE file in the root directory of this source tree. An additional grant
  7.  *  of patent rights can be found in the PATENTS file in the same directory.
  8.  *
  9.  */
  10.  
  11. /// \file
  12. /// \brief \b [Internal] Datagram reliable, ordered, unordered and sequenced sends.  Flow control.  Message splitting, reassembly, and coalescence.
  13. ///
  14.  
  15.  
  16. #ifndef __RELIABILITY_LAYER_H
  17. #define __RELIABILITY_LAYER_H
  18.  
  19. #include "RakMemoryOverride.h"
  20. #include "MTUSize.h"
  21. #include "DS_LinkedList.h"
  22. #include "DS_List.h"
  23. #include "SocketLayer.h"
  24. #include "PacketPriority.h"
  25. #include "DS_Queue.h"
  26. #include "BitStream.h"
  27. #include "InternalPacket.h"
  28. #include "RakNetStatistics.h"
  29. #include "DR_SHA1.h"
  30. #include "DS_OrderedList.h"
  31. #include "DS_RangeList.h"
  32. #include "DS_BPlusTree.h"
  33. #include "DS_MemoryPool.h"
  34. #include "RakNetDefines.h"
  35. #include "DS_Heap.h"
  36. #include "BitStream.h"
  37. #include "NativeFeatureIncludes.h"
  38. #include "SecureHandshake.h"
  39. #include "PluginInterface2.h"
  40. #include "Rand.h"
  41. #include "RakNetSocket2.h"
  42.  
  43. #if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1
  44. #include "CCRakNetUDT.h"
  45. #define INCLUDE_TIMESTAMP_WITH_DATAGRAMS 1
  46. #else
  47. #include "CCRakNetSlidingWindow.h"
  48. #define INCLUDE_TIMESTAMP_WITH_DATAGRAMS 0
  49. #endif
  50.  
  51. /// Number of ordered streams available. You can use up to 32 ordered streams
  52. #define NUMBER_OF_ORDERED_STREAMS 32 // 2^5
  53.  
  54. #define RESEND_TREE_ORDER 32
  55.  
  56. namespace RakNet {
  57.  
  58.     /// Forward declarations
  59. class PluginInterface2;
  60. class RakNetRandom;
  61. typedef uint64_t reliabilityHeapWeightType;
  62.  
  63. // int SplitPacketIndexComp( SplitPacketIndexType const &key, InternalPacket* const &data );
  64. struct SplitPacketChannel//<SplitPacketChannel>
  65. {
  66.     CCTimeType lastUpdateTime;
  67.  
  68.     DataStructures::List<InternalPacket*> splitPacketList;
  69.  
  70. #if PREALLOCATE_LARGE_MESSAGES==1
  71.     InternalPacket *returnedPacket;
  72.     bool gotFirstPacket;
  73.     unsigned int stride;
  74.     unsigned int splitPacketsArrived;
  75. #else
  76.     // This is here for progress notifications, since progress notifications return the first packet data, if available
  77.     InternalPacket *firstPacket;
  78. #endif
  79.  
  80. };
  81. int RAK_DLL_EXPORT SplitPacketChannelComp( SplitPacketIdType const &key, SplitPacketChannel* const &data );
  82.  
  83. // Helper class
  84. struct BPSTracker
  85. {
  86.     BPSTracker();
  87.     ~BPSTracker();
  88.     void Reset(const char *file, unsigned int line);
  89.     inline void Push1(CCTimeType time, uint64_t value1) {dataQueue.Push(TimeAndValue2(time,value1),_FILE_AND_LINE_); total1+=value1; lastSec1+=value1;}
  90. //  void Push2(RakNet::TimeUS time, uint64_t value1, uint64_t value2);
  91.     inline uint64_t GetBPS1(CCTimeType time) {(void) time; return lastSec1;}
  92.     inline uint64_t GetBPS1Threadsafe(CCTimeType time) {(void) time; return lastSec1;}
  93. //  uint64_t GetBPS2(RakNetTimeUS time);
  94. //  void GetBPS1And2(RakNetTimeUS time, uint64_t &out1, uint64_t &out2);
  95.     uint64_t GetTotal1(void) const;
  96. //  uint64_t GetTotal2(void) const;
  97.  
  98.     struct TimeAndValue2
  99.     {
  100.         TimeAndValue2();
  101.         ~TimeAndValue2();
  102.         TimeAndValue2(CCTimeType t, uint64_t v1);
  103.     //  TimeAndValue2(RakNet::TimeUS t, uint64_t v1, uint64_t v2);
  104.     //  uint64_t value1, value2;
  105.         uint64_t value1;
  106.         CCTimeType time;
  107.     };
  108.  
  109.     uint64_t total1, lastSec1;
  110. //  uint64_t total2, lastSec2;
  111.     DataStructures::Queue<TimeAndValue2> dataQueue;
  112.     void ClearExpired1(CCTimeType time);
  113. //  void ClearExpired2(RakNet::TimeUS time);
  114. };
  115.  
  116. /// Datagram reliable, ordered, unordered and sequenced sends.  Flow control.  Message splitting, reassembly, and coalescence.
  117. class ReliabilityLayer//<ReliabilityLayer>
  118. {
  119. public:
  120.  
  121.     // Constructor
  122.     ReliabilityLayer();
  123.  
  124.     // Destructor
  125.     ~ReliabilityLayer();
  126.  
  127.     /// Resets the layer for reuse
  128.     void Reset( bool resetVariables, int MTUSize, bool _useSecurity );
  129.  
  130.     /// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable packet
  131.     /// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug.
  132.     /// \param[in] time Time, in MS
  133.     void SetTimeoutTime( RakNet::TimeMS time );
  134.  
  135.     /// Returns the value passed to SetTimeoutTime. or the default if it was never called
  136.     /// \param[out] the value passed to SetTimeoutTime
  137.     RakNet::TimeMS GetTimeoutTime(void);
  138.  
  139.     /// Packets are read directly from the socket layer and skip the reliability layer because unconnected players do not use the reliability layer
  140.     /// This function takes packet data after a player has been confirmed as connected.
  141.     /// \param[in] buffer The socket data
  142.     /// \param[in] length The length of the socket data
  143.     /// \param[in] systemAddress The player that this data is from
  144.     /// \param[in] messageHandlerList A list of registered plugins
  145.     /// \param[in] MTUSize maximum datagram size
  146.     /// \retval true Success
  147.     /// \retval false Modified packet
  148.     bool HandleSocketReceiveFromConnectedPlayer(
  149.         const char *buffer, unsigned int length, SystemAddress &systemAddress, DataStructures::List<PluginInterface2*> &messageHandlerList, int MTUSize,
  150.         RakNetSocket2 *s, RakNetRandom *rnr, CCTimeType timeRead, BitStream &updateBitStream);
  151.  
  152.     /// This allocates bytes and writes a user-level message to those bytes.
  153.     /// \param[out] data The message
  154.     /// \return Returns number of BITS put into the buffer
  155.     BitSize_t Receive( unsigned char**data );
  156.  
  157.     /// Puts data on the send queue
  158.     /// \param[in] data The data to send
  159.     /// \param[in] numberOfBitsToSend The length of \a data in bits
  160.     /// \param[in] priority The priority level for the send
  161.     /// \param[in] reliability The reliability type for the send
  162.     /// \param[in] orderingChannel 0 to 31.  Specifies what channel to use, for relational ordering and sequencing of packets.
  163.     /// \param[in] makeDataCopy If true \a data will be copied.  Otherwise, only a pointer will be stored.
  164.     /// \param[in] MTUSize maximum datagram size
  165.     /// \param[in] currentTime Current time, as per RakNet::GetTimeMS()
  166.     /// \param[in] receipt This number will be returned back with ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS and is only returned with the reliability types that contain RECEIPT in the name
  167.     /// \return True or false for success or failure.
  168.     bool Send( char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, unsigned char orderingChannel, bool makeDataCopy, int MTUSize, CCTimeType currentTime, uint32_t receipt );
  169.  
  170.     /// Call once per game cycle.  Handles internal lists and actually does the send.
  171.     /// \param[in] s the communication  end point
  172.     /// \param[in] systemAddress The Unique Player Identifier who shouldhave sent some packets
  173.     /// \param[in] MTUSize maximum datagram size
  174.     /// \param[in] time current system time
  175.     /// \param[in] maxBitsPerSecond if non-zero, enforces that outgoing bandwidth does not exceed this amount
  176.     /// \param[in] messageHandlerList A list of registered plugins
  177.     void Update( RakNetSocket2 *s, SystemAddress &systemAddress, int MTUSize, CCTimeType time,
  178.         unsigned bitsPerSecondLimit,
  179.         DataStructures::List<PluginInterface2*> &messageHandlerList,
  180.         RakNetRandom *rnr, BitStream &updateBitStream);
  181.    
  182.     /// Were you ever unable to deliver a packet despite retries?
  183.     /// \return true means the connection has been lost.  Otherwise not.
  184.     bool IsDeadConnection( void ) const;
  185.  
  186.     /// Causes IsDeadConnection to return true
  187.     void KillConnection(void);
  188.  
  189.     /// Get Statistics
  190.     /// \return A pointer to a static struct, filled out with current statistical information.
  191.     RakNetStatistics * GetStatistics( RakNetStatistics *rns );
  192.  
  193.     ///Are we waiting for any data to be sent out or be processed by the player?
  194.     bool IsOutgoingDataWaiting(void);
  195.     bool AreAcksWaiting(void);
  196.  
  197.     // Set outgoing lag and packet loss properties
  198.     void ApplyNetworkSimulator( double _maxSendBPS, RakNet::TimeMS _minExtraPing, RakNet::TimeMS _extraPingVariance );
  199.  
  200.     /// Returns if you previously called ApplyNetworkSimulator
  201.     /// \return If you previously called ApplyNetworkSimulator
  202.     bool IsNetworkSimulatorActive( void );
  203.  
  204.     void SetSplitMessageProgressInterval(int interval);
  205.     void SetUnreliableTimeout(RakNet::TimeMS timeoutMS);
  206.     /// Has a lot of time passed since the last ack
  207.     bool AckTimeout(RakNet::Time curTime);
  208.     CCTimeType GetNextSendTime(void) const;
  209.     CCTimeType GetTimeBetweenPackets(void) const;
  210. #if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1
  211.     CCTimeType GetAckPing(void) const;
  212. #endif
  213.     RakNet::TimeMS GetTimeLastDatagramArrived(void) const {return timeLastDatagramArrived;}
  214.  
  215.     // If true, will update time between packets quickly based on ping calculations
  216.     //void SetDoFastThroughputReactions(bool fast);
  217.  
  218.     // Encoded as numMessages[unsigned int], message1BitLength[unsigned int], message1Data (aligned), ...
  219.     //void GetUndeliveredMessages(RakNet::BitStream *messages, int MTUSize);
  220.  
  221. private:
  222.     /// Send the contents of a bitstream to the socket
  223.     /// \param[in] s The socket used for sending data
  224.     /// \param[in] systemAddress The address and port to send to
  225.     /// \param[in] bitStream The data to send.
  226.     void SendBitStream( RakNetSocket2 *s, SystemAddress &systemAddress, RakNet::BitStream *bitStream, RakNetRandom *rnr, CCTimeType currentTime);
  227.  
  228.     ///Parse an internalPacket and create a bitstream to represent this data
  229.     /// \return Returns number of bits used
  230.     BitSize_t WriteToBitStreamFromInternalPacket( RakNet::BitStream *bitStream, const InternalPacket *const internalPacket, CCTimeType curTime );
  231.  
  232.  
  233.     /// Parse a bitstream and create an internal packet to represent this data
  234.     InternalPacket* CreateInternalPacketFromBitStream( RakNet::BitStream *bitStream, CCTimeType time );
  235.  
  236.     /// Does what the function name says
  237.     unsigned RemovePacketFromResendListAndDeleteOlderReliableSequenced( const MessageNumberType messageNumber, CCTimeType time, DataStructures::List<PluginInterface2*> &messageHandlerList, const SystemAddress &systemAddress );
  238.  
  239.     /// Acknowledge receipt of the packet with the specified messageNumber
  240.     void SendAcknowledgementPacket( const DatagramSequenceNumberType messageNumber, CCTimeType time);
  241.  
  242.     /// This will return true if we should not send at this time
  243.     bool IsSendThrottled( int MTUSize );
  244.  
  245.     /// We lost a packet
  246.     void UpdateWindowFromPacketloss( CCTimeType time );
  247.  
  248.     /// Increase the window size
  249.     void UpdateWindowFromAck( CCTimeType time );
  250.  
  251.     /// Parse an internalPacket and figure out how many header bits would be written.  Returns that number
  252.     BitSize_t GetMaxMessageHeaderLengthBits( void );
  253.     BitSize_t GetMessageHeaderLengthBits( const InternalPacket *const internalPacket );
  254.  
  255.     /// Get the SHA1 code
  256.     void GetSHA1( unsigned char * const buffer, unsigned int nbytes, char code[ SHA1_LENGTH ] );
  257.  
  258.     /// Check the SHA1 code
  259.     bool CheckSHA1( char code[ SHA1_LENGTH ], unsigned char * const buffer, unsigned int nbytes );
  260.  
  261.     /// Search the specified list for sequenced packets on the specified ordering channel, optionally skipping those with splitPacketId, and delete them
  262. //  void DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::List<InternalPacket*>&theList, int splitPacketId = -1 );
  263.  
  264.     /// Search the specified list for sequenced packets with a value less than orderingIndex and delete them
  265. //  void DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::Queue<InternalPacket*>&theList );
  266.  
  267.     /// Returns true if newPacketOrderingIndex is older than the waitingForPacketOrderingIndex
  268.     bool IsOlderOrderedPacket( OrderingIndexType newPacketOrderingIndex, OrderingIndexType waitingForPacketOrderingIndex );
  269.  
  270.     /// Split the passed packet into chunks under MTU_SIZE bytes (including headers) and save those new chunks
  271.     void SplitPacket( InternalPacket *internalPacket );
  272.  
  273.     /// Insert a packet into the split packet list
  274.     void InsertIntoSplitPacketList( InternalPacket * internalPacket, CCTimeType time );
  275.  
  276.     /// Take all split chunks with the specified splitPacketId and try to reconstruct a packet. If we can, allocate and return it.  Otherwise return 0
  277.     InternalPacket * BuildPacketFromSplitPacketList( SplitPacketIdType splitPacketId, CCTimeType time,
  278.         RakNetSocket2 *s, SystemAddress &systemAddress, RakNetRandom *rnr, BitStream &updateBitStream);
  279.     InternalPacket * BuildPacketFromSplitPacketList( SplitPacketChannel *splitPacketChannel, CCTimeType time );
  280.  
  281.     /// Delete any unreliable split packets that have long since expired
  282.     //void DeleteOldUnreliableSplitPackets( CCTimeType time );
  283.  
  284.     /// Creates a copy of the specified internal packet with data copied from the original starting at dataByteOffset for dataByteLength bytes.
  285.     /// Does not copy any split data parameters as that information is always generated does not have any reason to be copied
  286.     InternalPacket * CreateInternalPacketCopy( InternalPacket *original, int dataByteOffset, int dataByteLength, CCTimeType time );
  287.  
  288.     /// Get the specified ordering list
  289.     // DataStructures::LinkedList<InternalPacket*> *GetOrderingListAtOrderingStream( unsigned char orderingChannel );
  290.  
  291.     /// Add the internal packet to the ordering list in order based on order index
  292.     // void AddToOrderingList( InternalPacket * internalPacket );
  293.  
  294.     /// Inserts a packet into the resend list in order
  295.     void InsertPacketIntoResendList( InternalPacket *internalPacket, CCTimeType time, bool firstResend, bool modifyUnacknowledgedBytes );
  296.  
  297.     /// Memory handling
  298.     void FreeMemory( bool freeAllImmediately );
  299.  
  300.     /// Memory handling
  301.     void FreeThreadSafeMemory( void );
  302.  
  303.     // Initialize the variables
  304.     void InitializeVariables( void );
  305.  
  306.     /// Given the current time, is this time so old that we should consider it a timeout?
  307.     bool IsExpiredTime(unsigned int input, CCTimeType currentTime) const;
  308.  
  309.     // Make it so we don't do resends within a minimum threshold of time
  310.     void UpdateNextActionTime(void);
  311.  
  312.  
  313.     /// Does this packet number represent a packet that was skipped (out of order?)
  314.     //unsigned int IsReceivedPacketHole(unsigned int input, RakNet::TimeMS currentTime) const;
  315.  
  316.     /// Skip an element in the received packets list
  317.     //unsigned int MakeReceivedPacketHole(unsigned int input) const;
  318.  
  319.     /// How many elements are waiting to be resent?
  320.     unsigned int GetResendListDataSize(void) const;
  321.  
  322.     /// Update all memory which is not threadsafe
  323.     void UpdateThreadedMemory(void);
  324.  
  325.     void CalculateHistogramAckSize(void);
  326.  
  327.     // Used ONLY for RELIABLE_ORDERED
  328.     // RELIABLE_SEQUENCED just returns the newest one
  329.     // DataStructures::List<DataStructures::LinkedList<InternalPacket*>*> orderingList;
  330.     DataStructures::Queue<InternalPacket*> outputQueue;
  331.     int splitMessageProgressInterval;
  332.     CCTimeType unreliableTimeout;
  333.  
  334.     struct MessageNumberNode
  335.     {
  336.         DatagramSequenceNumberType messageNumber;
  337.         MessageNumberNode *next;
  338.     };
  339.     struct DatagramHistoryNode
  340.     {
  341.         DatagramHistoryNode() {}
  342.         DatagramHistoryNode(MessageNumberNode *_head, CCTimeType ts
  343.             ) :
  344.         head(_head), timeSent(ts)
  345.         {}
  346.         MessageNumberNode *head;
  347.         CCTimeType timeSent;
  348.     };
  349.     // Queue length is programmatically restricted to DATAGRAM_MESSAGE_ID_ARRAY_LENGTH
  350.     // This is essentially an O(1) lookup to get a DatagramHistoryNode given an index
  351.     // datagramHistory holds a linked list of MessageNumberNode. Each MessageNumberNode refers to one element in resendList which can be cleared on an ack.
  352.     DataStructures::Queue<DatagramHistoryNode> datagramHistory;
  353.     DataStructures::MemoryPool<MessageNumberNode> datagramHistoryMessagePool;
  354.  
  355.     struct UnreliableWithAckReceiptNode
  356.     {
  357.         UnreliableWithAckReceiptNode() {}
  358.         UnreliableWithAckReceiptNode(DatagramSequenceNumberType _datagramNumber, uint32_t _sendReceiptSerial, RakNet::TimeUS _nextActionTime) :
  359.             datagramNumber(_datagramNumber), sendReceiptSerial(_sendReceiptSerial), nextActionTime(_nextActionTime)
  360.         {}
  361.         DatagramSequenceNumberType datagramNumber;
  362.         uint32_t sendReceiptSerial;
  363.         RakNet::TimeUS nextActionTime;
  364.     };
  365.     DataStructures::List<UnreliableWithAckReceiptNode> unreliableWithAckReceiptHistory;
  366.  
  367.     void RemoveFromDatagramHistory(DatagramSequenceNumberType index);
  368.     MessageNumberNode* GetMessageNumberNodeByDatagramIndex(DatagramSequenceNumberType index, CCTimeType *timeSent);
  369.     void AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, CCTimeType timeSent);
  370.     MessageNumberNode* AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, DatagramSequenceNumberType messageNumber, CCTimeType timeSent);
  371.     MessageNumberNode* AddSubsequentToDatagramHistory(MessageNumberNode *messageNumberNode, DatagramSequenceNumberType messageNumber);
  372.     DatagramSequenceNumberType datagramHistoryPopCount;
  373.    
  374.     DataStructures::MemoryPool<InternalPacket> internalPacketPool;
  375.     // DataStructures::BPlusTree<DatagramSequenceNumberType, InternalPacket*, RESEND_TREE_ORDER> resendTree;
  376.     InternalPacket *resendBuffer[RESEND_BUFFER_ARRAY_LENGTH];
  377.     InternalPacket *resendLinkedListHead;
  378.     InternalPacket *unreliableLinkedListHead;
  379.     void RemoveFromUnreliableLinkedList(InternalPacket *internalPacket);
  380.     void AddToUnreliableLinkedList(InternalPacket *internalPacket);
  381. //  unsigned int numPacketsOnResendBuffer;
  382.     //unsigned int blockWindowIncreaseUntilTime;
  383.     //  DataStructures::RangeList<DatagramSequenceNumberType> acknowlegements;
  384.     // Resend list is a tree of packets we need to resend
  385.  
  386.     // Set to the current time when the resend queue is no longer empty
  387.     // Set to zero when it becomes empty
  388.     // Set to the current time if it is not zero, and we get incoming data
  389.     // If the current time - timeResendQueueNonEmpty is greater than a threshold, we are disconnected
  390. //  CCTimeType timeResendQueueNonEmpty;
  391.     RakNet::TimeMS timeLastDatagramArrived;
  392.  
  393.  
  394.     // If we backoff due to packetloss, don't remeasure until all waiting resends have gone out or else we overcount
  395. //  bool packetlossThisSample;
  396. //  int backoffThisSample;
  397. //  unsigned packetlossThisSampleResendCount;
  398. //  CCTimeType lastPacketlossTime;
  399.  
  400.     //DataStructures::Queue<InternalPacket*> sendPacketSet[ NUMBER_OF_PRIORITIES ];
  401.     DataStructures::Heap<reliabilityHeapWeightType, InternalPacket*, false> outgoingPacketBuffer;
  402.     reliabilityHeapWeightType outgoingPacketBufferNextWeights[NUMBER_OF_PRIORITIES];
  403.     void InitHeapWeights(void);
  404.     reliabilityHeapWeightType GetNextWeight(int priorityLevel);
  405. //  unsigned int messageInSendBuffer[NUMBER_OF_PRIORITIES];
  406. //  double bytesInSendBuffer[NUMBER_OF_PRIORITIES];
  407.  
  408.  
  409.     DataStructures::OrderedList<SplitPacketIdType, SplitPacketChannel*, SplitPacketChannelComp> splitPacketChannelList;
  410.  
  411.     MessageNumberType sendReliableMessageNumberIndex;
  412.     MessageNumberType internalOrderIndex;
  413.     //unsigned int windowSize;
  414.     //RakNet::BitStream updateBitStream;
  415.     bool deadConnection, cheater;
  416.     SplitPacketIdType splitPacketId;
  417.     RakNet::TimeMS timeoutTime; // How long to wait in MS before timing someone out
  418.     //int MAX_AVERAGE_PACKETS_PER_SECOND; // Name says it all
  419. //  int RECEIVED_PACKET_LOG_LENGTH, requestedReceivedPacketLogLength; // How big the receivedPackets array is
  420. //  unsigned int *receivedPackets;
  421.     RakNetStatistics statistics;
  422.  
  423.     // Algorithm for blending ordered and sequenced on the same channel:
  424.     // 1. Each ordered message transmits OrderingIndexType orderedWriteIndex. There are NUMBER_OF_ORDERED_STREAMS independent values of these. The value
  425.     //    starts at 0. Every time an ordered message is sent, the value increments by 1
  426.     // 2. Each sequenced message contains the current value of orderedWriteIndex for that channel, and additionally OrderingIndexType sequencedWriteIndex.
  427.     //    sequencedWriteIndex resets to 0 every time orderedWriteIndex increments. It increments by 1 every time a sequenced message is sent.
  428.     // 3. The receiver maintains the next expected value for the orderedWriteIndex, stored in orderedReadIndex.
  429.     // 4. As messages arrive:
  430.     //    If a message has the current ordering index, and is sequenced, and is < the current highest sequence value, discard
  431.     //    If a message has the current ordering index, and is sequenced, and is >= the current highest sequence value, return immediately
  432.     //    If a message has a greater ordering index, and is sequenced or ordered, buffer it
  433.     //    If a message has the current ordering index, and is ordered, buffer, then push off messages from buffer
  434.     // 5. Pushing off messages from buffer:
  435.     //    Messages in buffer are put in a minheap. The value of each node is calculated such that messages are returned:
  436.     //    A. (lowest ordering index, lowest sequence index)
  437.     //    B. (lowest ordering index, no sequence index)
  438.     //    Messages are pushed off until the heap is empty, or the next message to be returned does not preserve the ordered index
  439.     //    For an empty heap, the heap weight should start at the lowest value based on the next expected ordering index, to avoid variable overflow
  440.  
  441.     // Sender increments this by 1 for every ordered message sent
  442.     OrderingIndexType orderedWriteIndex[NUMBER_OF_ORDERED_STREAMS];
  443.     // Sender increments by 1 for every sequenced message sent. Resets to 0 when an ordered message is sent
  444.     OrderingIndexType sequencedWriteIndex[NUMBER_OF_ORDERED_STREAMS];
  445.     // Next expected index for ordered messages.
  446.     OrderingIndexType orderedReadIndex[NUMBER_OF_ORDERED_STREAMS];
  447.     // Highest value received for sequencedWriteIndex for the current value of orderedReadIndex on the same channel.
  448.     OrderingIndexType highestSequencedReadIndex[NUMBER_OF_ORDERED_STREAMS];
  449.     DataStructures::Heap<reliabilityHeapWeightType, InternalPacket*, false> orderingHeaps[NUMBER_OF_ORDERED_STREAMS];
  450.     OrderingIndexType heapIndexOffsets[NUMBER_OF_ORDERED_STREAMS];
  451.  
  452.    
  453.  
  454.  
  455.  
  456.  
  457.  
  458. //  CCTimeType histogramStart;
  459. //  unsigned histogramBitsSent;
  460.  
  461.  
  462.     /// Memory-efficient receivedPackets algorithm:
  463.     /// receivedPacketsBaseIndex is the packet number we are expecting
  464.     /// Everything under receivedPacketsBaseIndex is a packet we already got
  465.     /// Everything over receivedPacketsBaseIndex is stored in hasReceivedPacketQueue
  466.     /// It stores the time to stop waiting for a particular packet number, where the packet number is receivedPacketsBaseIndex + the index into the queue
  467.     /// If 0, we got got that packet.  Otherwise, the time to give up waiting for that packet.
  468.     /// If we get a packet number where (receivedPacketsBaseIndex-packetNumber) is less than half the range of receivedPacketsBaseIndex then it is a duplicate
  469.     /// Otherwise, it is a duplicate packet (and ignore it).
  470.     // DataStructures::Queue<CCTimeType> hasReceivedPacketQueue;
  471.     DataStructures::Queue<bool> hasReceivedPacketQueue;
  472.     DatagramSequenceNumberType receivedPacketsBaseIndex;
  473.     bool resetReceivedPackets;
  474.  
  475.     CCTimeType lastUpdateTime;
  476.     CCTimeType timeBetweenPackets, nextSendTime;
  477. #if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1
  478.     CCTimeType ackPing;
  479. #endif
  480. //  CCTimeType ackPingSamples[ACK_PING_SAMPLES_SIZE]; // Must be range of unsigned char to wrap ackPingIndex properly
  481.     CCTimeType ackPingSum;
  482.     unsigned char ackPingIndex;
  483.     //CCTimeType nextLowestPingReset;
  484.     RemoteSystemTimeType remoteSystemTime;
  485. //  bool continuousSend;
  486. //  CCTimeType lastTimeBetweenPacketsIncrease,lastTimeBetweenPacketsDecrease;
  487.     // Limit changes in throughput to once per ping - otherwise even if lag starts we don't know about it
  488.     // In the meantime the connection is flooded and overrun.
  489.     CCTimeType nextAllowedThroughputSample;
  490.     bool bandwidthExceededStatistic;
  491.  
  492.     // If Update::maxBitsPerSecond > 0, then throughputCapCountdown is used as a timer to prevent sends for some amount of time after each send, depending on
  493.     // the amount of data sent
  494.     long long throughputCapCountdown;
  495.  
  496.     unsigned receivePacketCount;
  497.  
  498. #ifdef _DEBUG
  499.     struct DataAndTime//<InternalPacket>
  500.     {
  501.         RakNetSocket2 *s;
  502.         char data[ MAXIMUM_MTU_SIZE ];
  503.         unsigned int length;
  504.         RakNet::TimeMS sendTime;
  505.         //  SystemAddress systemAddress;
  506.         unsigned short remotePortRakNetWasStartedOn_PS3;
  507.         unsigned int extraSocketOptions;
  508.     };
  509.     DataStructures::Queue<DataAndTime*> delayList;
  510.  
  511.     // Internet simulator
  512.     double packetloss;
  513.     RakNet::TimeMS minExtraPing, extraPingVariance;
  514. #endif
  515.  
  516.     CCTimeType elapsedTimeSinceLastUpdate;
  517.  
  518.     CCTimeType nextAckTimeToSend;
  519.  
  520.    
  521. #if USE_SLIDING_WINDOW_CONGESTION_CONTROL==1
  522.     RakNet::CCRakNetSlidingWindow congestionManager;
  523. #else
  524.     RakNet::CCRakNetUDT congestionManager;
  525. #endif
  526.  
  527.  
  528.     uint32_t unacknowledgedBytes;
  529.    
  530.     bool ResendBufferOverflow(void) const;
  531.     void ValidateResendList(void) const;
  532.     void ResetPacketsAndDatagrams(void);
  533.     void PushPacket(CCTimeType time, InternalPacket *internalPacket, bool isReliable);
  534.     void PushDatagram(void);
  535.     bool TagMostRecentPushAsSecondOfPacketPair(void);
  536.     void ClearPacketsAndDatagrams(void);
  537.     void MoveToListHead(InternalPacket *internalPacket);
  538.     void RemoveFromList(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes);
  539.     void AddToListTail(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes);
  540.     void PopListHead(bool modifyUnacknowledgedBytes);
  541.     bool IsResendQueueEmpty(void) const;
  542.     void SortSplitPacketList(DataStructures::List<InternalPacket*> &data, unsigned int leftEdge, unsigned int rightEdge) const;
  543.     void SendACKs(RakNetSocket2 *s, SystemAddress &systemAddress, CCTimeType time, RakNetRandom *rnr, BitStream &updateBitStream);
  544.  
  545.     DataStructures::List<InternalPacket*> packetsToSendThisUpdate;
  546.     DataStructures::List<bool> packetsToDeallocThisUpdate;
  547.     // boundary is in packetsToSendThisUpdate, inclusive
  548.     DataStructures::List<unsigned int> packetsToSendThisUpdateDatagramBoundaries;
  549.     DataStructures::List<bool> datagramsToSendThisUpdateIsPair;
  550.     DataStructures::List<unsigned int> datagramSizesInBytes;
  551.     BitSize_t datagramSizeSoFar;
  552.     BitSize_t allDatagramSizesSoFar;
  553.     double totalUserDataBytesAcked;
  554.     CCTimeType timeOfLastContinualSend;
  555.     CCTimeType timeToNextUnreliableCull;
  556.  
  557.     // This doesn't need to be a member, but I do it to avoid reallocations
  558.     DataStructures::RangeList<DatagramSequenceNumberType> incomingAcks;
  559.  
  560.     // Every 16 datagrams, we make sure the 17th datagram goes out the same update tick, and is the same size as the 16th
  561.     int countdownToNextPacketPair;
  562.     InternalPacket* AllocateFromInternalPacketPool(void);
  563.     void ReleaseToInternalPacketPool(InternalPacket *ip);
  564.  
  565.     DataStructures::RangeList<DatagramSequenceNumberType> acknowlegements;
  566.     DataStructures::RangeList<DatagramSequenceNumberType> NAKs;
  567.     bool remoteSystemNeedsBAndAS;
  568.  
  569.     unsigned int GetMaxDatagramSizeExcludingMessageHeaderBytes(void);
  570.     BitSize_t GetMaxDatagramSizeExcludingMessageHeaderBits(void);
  571.  
  572.     // ourOffset refers to a section within externallyAllocatedPtr. Do not deallocate externallyAllocatedPtr until all references are lost
  573.     void AllocInternalPacketData(InternalPacket *internalPacket, InternalPacketRefCountedData **refCounter, unsigned char *externallyAllocatedPtr, unsigned char *ourOffset);
  574.     // Set the data pointer to externallyAllocatedPtr, do not allocate
  575.     void AllocInternalPacketData(InternalPacket *internalPacket, unsigned char *externallyAllocatedPtr);
  576.     // Allocate new
  577.     void AllocInternalPacketData(InternalPacket *internalPacket, unsigned int numBytes, bool allowStack, const char *file, unsigned int line);
  578.     void FreeInternalPacketData(InternalPacket *internalPacket, const char *file, unsigned int line);
  579.     DataStructures::MemoryPool<InternalPacketRefCountedData> refCountedDataPool;
  580.  
  581.     BPSTracker bpsMetrics[RNS_PER_SECOND_METRICS_COUNT];
  582.     CCTimeType lastBpsClear;
  583.  
  584. #if LIBCAT_SECURITY==1
  585. public:
  586.     cat::AuthenticatedEncryption* GetAuthenticatedEncryption(void) { return &auth_enc; }
  587.  
  588. protected:
  589.     cat::AuthenticatedEncryption auth_enc;
  590.     bool useSecurity;
  591. #endif // LIBCAT_SECURITY
  592. };
  593.  
  594. } // namespace RakNet
  595.  
  596. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement