Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

922 lines
22 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. //===========================================================================//
  6. #include "NetChannel.h"
  7. #include "UDP_Socket.h"
  8. #include "tier1/utlbuffer.h"
  9. #include "networksystem/inetworkmessage.h"
  10. #include "networksystem.h"
  11. // memdbgon must be the last include file in a .cpp file!!!
  12. #include "tier0/memdbgon.h"
  13. //-----------------------------------------------------------------------------
  14. // Construction/Destruction
  15. //-----------------------------------------------------------------------------
  16. CNetChannel::CNetChannel()
  17. {
  18. m_pSocket = NULL; // invalid
  19. remote_address.Clear();
  20. last_received = 0;
  21. connect_time = 0;
  22. m_ConnectionState = CONNECTION_STATE_DISCONNECTED;
  23. Q_strncpy( m_Name, "", sizeof(m_Name) );
  24. m_MessageHandler = NULL;
  25. m_StreamUnreliable.StartWriting(m_UnreliableDataBuffer, sizeof(m_UnreliableDataBuffer));
  26. m_StreamUnreliable.SetDebugName( "netchan_t::unreliabledata" );
  27. m_StreamReliable.StartWriting(m_ReliableDataBuffer, sizeof(m_ReliableDataBuffer));
  28. m_StreamReliable.SetDebugName( "netchan_t::reliabledata" );
  29. m_Rate = DEFAULT_RATE;
  30. m_Timeout = SIGNON_TIME_OUT;
  31. m_PacketDrop = 0;
  32. // Prevent the first message from getting dropped after connection is set up.
  33. m_nOutSequenceNr = 1; // otherwise it looks like a
  34. m_nInSequenceNr = 0;
  35. m_nOutSequenceNrAck = 0;
  36. m_nOutReliableState = 0; // our current reliable state
  37. m_nInReliableState = 0; // last remote reliable state
  38. // FlowReset();
  39. }
  40. CNetChannel::~CNetChannel()
  41. {
  42. Shutdown( "NetChannel removed." );
  43. }
  44. //-----------------------------------------------------------------------------
  45. // called to open a channel to a remote system
  46. //-----------------------------------------------------------------------------
  47. void CNetChannel::Setup( bool serverSide, const netadr_t *adr, CUDPSocket *sendSocket, char const *name, INetworkMessageHandler *handler )
  48. {
  49. Assert( name );
  50. Assert( handler );
  51. Assert( adr );
  52. m_pSocket = sendSocket;
  53. // remote_address may be NULL for fake channels (demo playback etc)
  54. remote_address = *adr;
  55. last_received = g_pNetworkSystemImp->GetTime();
  56. connect_time = last_received;
  57. Q_strncpy( m_Name, name, sizeof(m_Name) );
  58. m_MessageHandler = handler;
  59. m_StreamUnreliable.StartWriting(m_UnreliableDataBuffer, sizeof(m_UnreliableDataBuffer));
  60. m_StreamUnreliable.SetDebugName( "netchan_t::unreliabledata" );
  61. m_ReliableDataBufferMP.EnsureCapacity( NET_MAX_PAYLOAD );
  62. m_StreamReliable.StartWriting( m_ReliableDataBufferMP.Base(), NET_MAX_PAYLOAD );
  63. m_StreamReliable.SetDebugName( "netchan_t::reliabledata" );
  64. m_Rate = DEFAULT_RATE;
  65. m_Timeout = SIGNON_TIME_OUT;
  66. m_PacketDrop = 0;
  67. // Prevent the first message from getting dropped after connection is set up.
  68. m_nOutSequenceNr = 1; // otherwise it looks like a
  69. m_nInSequenceNr = 0;
  70. m_nOutSequenceNrAck = 0;
  71. m_nOutReliableState = 0; // our current reliable state
  72. m_nInReliableState = 0; // last remote reliable state
  73. m_nChokedPackets = 0;
  74. m_fClearTime = 0.0;
  75. m_ConnectionState = CONNECTION_STATE_CONNECTED;
  76. // FlowReset();
  77. // tell message handler to register know netmessages
  78. m_MessageHandler->OnConnectionStarted( this );
  79. }
  80. void CNetChannel::Shutdown( const char *pReason )
  81. {
  82. // send discconect
  83. if ( !m_pSocket )
  84. return;
  85. Clear(); // free all buffers (reliable & unreliable)
  86. if ( pReason )
  87. {
  88. // send disconnect message
  89. WriteSystemNetworkMessage( m_StreamUnreliable, net_disconnect );
  90. m_StreamUnreliable.WriteString( pReason );
  91. Transmit(); // push message out
  92. }
  93. m_pSocket = NULL; // signals that netchannel isn't valid anymore
  94. remote_address.Clear();
  95. m_ConnectionState = CONNECTION_STATE_DISCONNECTED;
  96. if ( m_MessageHandler )
  97. {
  98. m_MessageHandler->OnConnectionClosing( this, pReason );
  99. m_MessageHandler = NULL;
  100. }
  101. }
  102. //-----------------------------------------------------------------------------
  103. // Channel connection state
  104. //-----------------------------------------------------------------------------
  105. ConnectionStatus_t CNetChannel::GetConnectionState( )
  106. {
  107. return m_ConnectionState;
  108. }
  109. void CNetChannel::SetConnectionState( ConnectionStatus_t state )
  110. {
  111. m_ConnectionState = state;
  112. }
  113. /*
  114. void CNetChannel::GetSequenceData( int &nOutSequenceNr, int &nInSequenceNr, int &nOutSequenceNrAck )
  115. {
  116. nOutSequenceNr = m_nOutSequenceNr;
  117. nInSequenceNr = m_nInSequenceNr;
  118. nOutSequenceNrAck = m_nOutSequenceNrAck;
  119. }
  120. void CNetChannel::SetSequenceData( int nOutSequenceNr, int nInSequenceNr, int nOutSequenceNrAck )
  121. {
  122. Assert( IsPlayback() );
  123. m_nOutSequenceNr = nOutSequenceNr;
  124. m_nInSequenceNr = nInSequenceNr;
  125. m_nOutSequenceNrAck = nOutSequenceNrAck;
  126. }
  127. */
  128. void CNetChannel::SetTimeout(float seconds)
  129. {
  130. m_Timeout = seconds;
  131. if ( m_Timeout > 3600.0f )
  132. {
  133. m_Timeout = 3600.0f; // 1 hour maximum
  134. }
  135. else if ( m_Timeout < CONNECTION_PROBLEM_TIME )
  136. {
  137. m_Timeout = CONNECTION_PROBLEM_TIME; // allow at least this minimum
  138. }
  139. }
  140. void CNetChannel::SetDataRate(float rate)
  141. {
  142. m_Rate = clamp( rate, (float)MIN_RATE, (float)MAX_RATE );
  143. }
  144. const char * CNetChannel::GetName() const
  145. {
  146. return m_Name;
  147. }
  148. const char * CNetChannel::GetAddress() const
  149. {
  150. return remote_address.ToString();
  151. }
  152. /*
  153. int CNetChannel::GetDropNumber() const
  154. {
  155. return m_PacketDrop;
  156. }
  157. */
  158. /*
  159. ===============
  160. CNetChannel::CanSendPacket
  161. Returns true if the bandwidth choke isn't active
  162. ================
  163. */
  164. bool CNetChannel::CanSendPacket () const
  165. {
  166. return m_fClearTime < g_pNetworkSystemImp->GetTime();
  167. }
  168. /*
  169. void CNetChannel::FlowReset( void )
  170. {
  171. Q_memset( m_DataFlow, 0, sizeof( m_DataFlow ) );
  172. Q_memset( m_MsgStats, 0, sizeof( m_MsgStats ) );
  173. }
  174. void CNetChannel::FlowNewPacket(int flow, int seqnr, int acknr, int nChoked, int nSize )
  175. {
  176. netflow_t * pflow = &m_DataFlow[ flow ];
  177. // if frame_number != ( current + 1 ) mark frames between as invalid
  178. netframe_t *pframe = NULL;
  179. if ( seqnr > pflow->currentindex )
  180. {
  181. for ( int i = pflow->currentindex+1; i <= seqnr; i++ )
  182. {
  183. pframe = &pflow->frames[ i & NET_FRAMES_MASK ];
  184. pframe->time = GetTime(); // now
  185. pframe->valid = false;
  186. pframe->size = 0;
  187. pframe->latency = -1.0f; // not acknowledged yet
  188. pframe->choked = 0; // not acknowledged yet
  189. Q_memset( &pframe->msggroups, 0, sizeof(pframe->msggroups) );
  190. }
  191. pframe->choked = nChoked;
  192. pframe->size = nSize;
  193. pframe->valid = true;
  194. }
  195. else
  196. {
  197. Assert( seqnr > pflow->currentindex );
  198. }
  199. pflow->totalpackets++;
  200. pflow->currentindex = seqnr;
  201. pflow->currentframe = pframe;
  202. // updated ping for acknowledged packet
  203. int aflow = (flow==FLOW_OUTGOING) ? FLOW_INCOMING : FLOW_OUTGOING;
  204. if ( acknr <= (m_DataFlow[aflow].currentindex - NET_FRAMES_BACKUP) )
  205. return; // acknowledged packet isn't in backup buffer anymore
  206. netframe_t * aframe = &m_DataFlow[aflow].frames[ acknr & NET_FRAMES_MASK ];
  207. if ( aframe->valid && aframe->latency == -1.0f )
  208. {
  209. // update ping for acknowledged packet, if not already acknowledged before
  210. aframe->latency = GetTime() - aframe->time;
  211. if ( aframe->latency < 0.0f )
  212. aframe->latency = 0.0f;
  213. }
  214. }
  215. void CNetChannel::FlowUpdate(int flow, int addbytes)
  216. {
  217. netflow_t * pflow = &m_DataFlow[ flow ];
  218. pflow->totalbytes += addbytes;
  219. if ( pflow->nextcompute > GetTime() )
  220. return;
  221. pflow->nextcompute = GetTime() + FLOW_INTERVAL;
  222. int totalvalid = 0;
  223. int totalinvalid = 0;
  224. int totalbytes = 0;
  225. float totallatency = 0.0f;
  226. int totallatencycount = 0;
  227. int totalchoked = 0;
  228. float starttime = FLT_MAX;
  229. float endtime = 0.0f;
  230. netframe_t *pprev = &pflow->frames[ NET_FRAMES_BACKUP-1 ];
  231. for ( int i = 0; i < NET_FRAMES_BACKUP; i++ )
  232. {
  233. // Most recent message then backward from there
  234. netframe_t * pcurr = &pflow->frames[ i ];
  235. if ( pcurr->valid )
  236. {
  237. if ( pcurr->time < starttime )
  238. starttime = pcurr->time;
  239. if ( pcurr->time > endtime )
  240. endtime = pcurr->time;
  241. totalvalid++;
  242. totalchoked += pcurr->choked;
  243. totalbytes += pcurr->size;
  244. if ( pcurr->latency > -1.0f )
  245. {
  246. totallatency += pcurr->latency;
  247. totallatencycount++;
  248. }
  249. }
  250. else
  251. {
  252. totalinvalid++;
  253. }
  254. pprev = pcurr;
  255. }
  256. float totaltime = endtime - starttime;
  257. if ( totaltime > 0.0f )
  258. {
  259. pflow->avgbytespersec *= FLOW_AVG;
  260. pflow->avgbytespersec += ( 1.0f - FLOW_AVG ) * ((float)totalbytes / totaltime);
  261. pflow->avgpacketspersec *= FLOW_AVG;
  262. pflow->avgpacketspersec += ( 1.0f - FLOW_AVG ) * ((float)totalvalid / totaltime);
  263. }
  264. int totalPackets = totalvalid + totalinvalid;
  265. if ( totalPackets > 0 )
  266. {
  267. pflow->avgloss *= FLOW_AVG;
  268. pflow->avgloss += ( 1.0f - FLOW_AVG ) * ((float)(totalinvalid-totalchoked)/totalPackets);
  269. if ( pflow->avgloss < 0 )
  270. pflow->avgloss = 0;
  271. pflow->avgchoke *= FLOW_AVG;
  272. pflow->avgchoke += ( 1.0f - FLOW_AVG ) * ((float)totalchoked/totalPackets);
  273. }
  274. if ( totallatencycount>0 )
  275. {
  276. float newping = totallatency / totallatencycount ;
  277. pflow->latency = newping;
  278. pflow->avglatency*= FLOW_AVG;
  279. pflow->avglatency += ( 1.0f - FLOW_AVG ) * newping;
  280. }
  281. }
  282. */
  283. void CNetChannel::SetChoked( void )
  284. {
  285. m_nOutSequenceNr++; // sends to be done since move command use sequence number
  286. m_nChokedPackets++;
  287. }
  288. bool CNetChannel::Transmit( bool onlyReliable /* =false */ )
  289. {
  290. if ( onlyReliable )
  291. {
  292. m_StreamUnreliable.Reset();
  293. }
  294. return ( SendDatagram( NULL ) != 0 );
  295. }
  296. /*
  297. ===============
  298. CNetChannel::TransmitBits
  299. tries to send an unreliable message to a connection, and handles the
  300. transmition / retransmition of the reliable messages.
  301. A 0 length will still generate a packet and deal with the reliable messages.
  302. ================
  303. */
  304. int CNetChannel::SendDatagram( bf_write *datagram )
  305. {
  306. byte send_buf[ NET_MAX_MESSAGE ];
  307. // first increase out sequence number
  308. // check, if fake client, then fake send also
  309. if ( remote_address.GetType() == NA_NULL )
  310. {
  311. // this is a demo channel, fake sending all data
  312. m_fClearTime = 0.0; // no bandwidth delay
  313. m_nChokedPackets = 0; // Reset choke state
  314. m_StreamReliable.Reset(); // clear current reliable buffer
  315. m_StreamUnreliable.Reset(); // clear current unrelaible buffer
  316. m_nOutSequenceNr++;
  317. return m_nOutSequenceNr-1;
  318. }
  319. // process all new and pending reliable data, return true if reliable data should
  320. // been send with this packet
  321. if ( m_StreamReliable.IsOverflowed() )
  322. {
  323. Msg ("%s:send reliable stream overflow\n" ,remote_address.ToString());
  324. return 0;
  325. }
  326. bf_write send( "CNetChannel_TransmitBits->send", send_buf, sizeof(send_buf) );
  327. // Prepare the packet header
  328. // build packet flags
  329. unsigned char flags = 0;
  330. // start writing packet
  331. send.WriteLong ( m_nOutSequenceNr );
  332. send.WriteLong ( m_nInSequenceNr );
  333. bf_write flagsPos = send; // remember flags byte position
  334. send.WriteByte ( 0 ); // write correct flags value later
  335. send.WriteByte ( m_nInReliableState );
  336. if ( m_nChokedPackets > 0 )
  337. {
  338. flags |= PACKET_FLAG_CHOKED;
  339. send.WriteByte ( m_nChokedPackets & 0xFF ); // send number of choked packets
  340. }
  341. /*
  342. if ( SendSubChannelData( send ) )
  343. {
  344. flags |= PACKET_FLAG_RELIABLE;
  345. }
  346. */
  347. // Is there room for given datagram data. the datagram data
  348. // is somewhat more important than the normal unreliable data
  349. // this is done to allow some kind of snapshot behaviour
  350. // weather all data in datagram is transmitted or none.
  351. if ( datagram )
  352. {
  353. if( datagram->GetNumBitsWritten() < send.GetNumBitsLeft() )
  354. {
  355. send.WriteBits( datagram->GetData(), datagram->GetNumBitsWritten() );
  356. }
  357. else
  358. {
  359. DevMsg("CNetChannel::SendDatagram: data would overfow, ignoring\n");
  360. }
  361. }
  362. // Is there room for the unreliable payload?
  363. if ( m_StreamUnreliable.GetNumBitsWritten() < send.GetNumBitsLeft() )
  364. {
  365. send.WriteBits(m_StreamUnreliable.GetData(), m_StreamUnreliable.GetNumBitsWritten() );
  366. }
  367. else
  368. {
  369. DevMsg("CNetChannel::SendDatagram: Unreliable would overfow, ignoring\n");
  370. }
  371. m_StreamUnreliable.Reset(); // clear unreliable data buffer
  372. // Deal with packets that are too small for some networks
  373. while ( send.GetNumBytesWritten() < MIN_ROUTEABLE_PACKET )
  374. {
  375. // Go ahead and pad some bits as long as needed
  376. WriteSystemNetworkMessage( send, net_nop );
  377. }
  378. // fill last bits in last byte with NOP if necessary
  379. int nRemainingBits = send.GetNumBitsWritten() % 8;
  380. int nHeaderSize = g_pNetworkSystemImp->GetGroupBitCount() + g_pNetworkSystemImp->GetTypeBitCount();
  381. while ( nRemainingBits > 0 && nRemainingBits <= ( 8 - nHeaderSize ) )
  382. {
  383. WriteSystemNetworkMessage( send, net_nop );
  384. nRemainingBits += nHeaderSize;
  385. }
  386. flagsPos.WriteByte( flags ); // write correct flags value
  387. // Send the datagram
  388. m_pSocket->SendTo( remote_address, send.GetData(), send.GetNumBytesWritten() );
  389. // update stats
  390. int nTotalSize = send.GetNumBytesWritten() + UDP_HEADER_SIZE;
  391. // FlowNewPacket( FLOW_OUTGOING, m_nOutSequenceNr, m_nInSequenceNr, m_nChokedPackets, nTotalSize );
  392. // FlowUpdate( FLOW_OUTGOING, nTotalSize );
  393. float flTime = g_pNetworkSystemImp->GetTime();
  394. if ( m_fClearTime < flTime )
  395. {
  396. m_fClearTime = flTime;
  397. }
  398. // calc cleantime when channel will be ready for next packet
  399. Assert( m_Rate != 0.0f );
  400. m_fClearTime += (float)( nTotalSize ) / (float) m_Rate;
  401. m_nChokedPackets = 0;
  402. m_nOutSequenceNr++;
  403. return m_nOutSequenceNr-1; // return send seq nr
  404. }
  405. bool CNetChannel::ProcessControlMessage( int cmd, bf_read &buf )
  406. {
  407. switch( cmd )
  408. {
  409. case net_nop:
  410. return true;
  411. case net_disconnect:
  412. {
  413. char pReason[1024];
  414. buf.ReadString( pReason, sizeof(pReason) );
  415. Shutdown( pReason );
  416. }
  417. return false;
  418. default:
  419. Msg( "CNetChannel: received bad control cmd %i from %s.\n", cmd, remote_address.ToString() );
  420. return false;
  421. }
  422. }
  423. bool CNetChannel::ProcessMessages( bf_read &buf )
  424. {
  425. //int startbit = buf.GetNumBitsRead();
  426. int nGroupCount = g_pNetworkSystemImp->GetGroupBitCount();
  427. int nTypeCount = g_pNetworkSystemImp->GetTypeBitCount();
  428. while ( true )
  429. {
  430. if ( buf.IsOverflowed() )
  431. return false;
  432. // Are we at the end?
  433. if ( buf.GetNumBitsLeft() < ( nGroupCount + nTypeCount ) )
  434. break;
  435. unsigned int group = buf.ReadUBitLong( nGroupCount );
  436. unsigned int type = buf.ReadUBitLong( nTypeCount );
  437. if ( group == net_group_networksystem )
  438. {
  439. if ( !ProcessControlMessage( type, buf ) )
  440. return g_pNetworkSystemImp->IsNetworkEventCreated(); // disconnect or error
  441. continue;
  442. }
  443. // see if we have a registered message object for this type
  444. INetworkMessage *pNetMessage = g_pNetworkSystemImp->FindNetworkMessage( group, type );
  445. if ( !pNetMessage )
  446. {
  447. Msg( "Netchannel: unknown net message (%i:%i) from %s.\n", group, type, remote_address.ToString() );
  448. Assert ( 0 );
  449. return false;
  450. }
  451. // Attach it to the correct netchannel
  452. pNetMessage->SetNetChannel( this );
  453. // let message parse itself from buffe
  454. const char *pGroupName = pNetMessage->GetGroupName();
  455. const char *pMessageName = pNetMessage->GetName();
  456. //int startbit = buf.GetNumBitsRead();
  457. if ( !pNetMessage->ReadFromBuffer( buf ) )
  458. {
  459. Msg( "Netchannel: failed reading message %s [%s] from %s.\n", pMessageName, pGroupName, remote_address.ToString() );
  460. Assert ( 0 );
  461. return false;
  462. }
  463. // UpdateMessageStats( netmsg->GetGroup(), buf.GetNumBitsRead() - startbit );
  464. // Create a network event
  465. NetworkMessageReceivedEvent_t *pReceived = g_pNetworkSystemImp->CreateNetworkEvent< NetworkMessageReceivedEvent_t >( );
  466. pReceived->m_nType = NETWORK_EVENT_MESSAGE_RECEIVED;
  467. pReceived->m_pChannel = this;
  468. pReceived->m_pNetworkMessage = pNetMessage;
  469. return true; // ok fine
  470. }
  471. return false; // ok fine, but don't keep processing this packet
  472. }
  473. int CNetChannel::ProcessPacketHeader( bf_read& message )
  474. {
  475. // get sequence numbers
  476. int sequence = message.ReadLong();
  477. int sequence_ack= message.ReadLong();
  478. int flags = message.ReadByte();
  479. int relState = message.ReadByte(); // reliable state of 8 subchannels
  480. int nChoked = 0; // read later if choked flag is set
  481. //int i,j;
  482. NOTE_UNUSED( relState );
  483. if ( flags & PACKET_FLAG_CHOKED )
  484. nChoked = message.ReadByte();
  485. // discard stale or duplicated packets
  486. if (sequence <= m_nInSequenceNr )
  487. {
  488. /*
  489. if ( net_showdrop.GetInt() )
  490. {
  491. if ( sequence == m_nInSequenceNr )
  492. {
  493. Msg ("%s:duplicate packet %i at %i\n"
  494. , remote_address.ToString ()
  495. , sequence
  496. , m_nInSequenceNr);
  497. }
  498. else
  499. {
  500. Msg ("%s:out of order packet %i at %i\n"
  501. , remote_address.ToString ()
  502. , sequence
  503. , m_nInSequenceNr);
  504. }
  505. }
  506. */
  507. return -1;
  508. }
  509. //
  510. // dropped packets don't keep the message from being used
  511. //
  512. m_PacketDrop = sequence - (m_nInSequenceNr + nChoked + 1);
  513. if ( m_PacketDrop > 0 )
  514. {
  515. /*
  516. if ( net_showdrop.GetInt() )
  517. {
  518. Msg ("%s:Dropped %i packets at %i\n"
  519. ,remote_address.ToString(), m_PacketDrop, sequence );
  520. }
  521. */
  522. }
  523. m_nInSequenceNr = sequence;
  524. m_nOutSequenceNrAck = sequence_ack;
  525. // Update data flow stats
  526. // FlowNewPacket( FLOW_INCOMING, m_nInSequenceNr, m_nOutSequenceNrAck, nChoked, packet->size + UDP_HEADER_SIZE );
  527. return flags;
  528. }
  529. //-----------------------------------------------------------------------------
  530. // CNetChannel::ProcessPacket
  531. //
  532. // called when a new packet has arrived for this netchannel
  533. // sequence numbers are extracted, fragments/file streams stripped
  534. // and then the netmessages processed
  535. //-----------------------------------------------------------------------------
  536. bool CNetChannel::StartProcessingPacket( CNetPacket *packet )
  537. {
  538. if ( !m_MessageHandler )
  539. return false;
  540. netadr_t from = packet->m_From;
  541. if ( remote_address.IsValid() && !from.CompareAdr ( remote_address ) )
  542. return false;
  543. // Update data flow stats
  544. //FlowUpdate( FLOW_INCOMING, msg.TellPut() + UDP_HEADER_SIZE );
  545. int flags = ProcessPacketHeader( packet->m_Message );
  546. if ( flags == -1 )
  547. return false; // invalid header/packet
  548. /*
  549. if ( net_showudp.GetInt() && net_showudp.GetInt() != 3 )
  550. {
  551. Msg ("UDP <- %s: sz=%i seq=%i ack=%i rel=%i tm=%f\n"
  552. , GetName()
  553. , packet->m_nSizeInBytes
  554. , m_nInSequenceNr & 63
  555. , m_nOutSequenceNrAck & 63
  556. , flags & PACKET_FLAG_RELIABLE ? 1 : 0
  557. , GetTime() );
  558. }
  559. */
  560. last_received = g_pNetworkSystemImp->GetTime();
  561. // tell message handler that a new packet has arrived
  562. m_MessageHandler->OnPacketStarted( m_nInSequenceNr, m_nOutSequenceNrAck );
  563. if ( flags & PACKET_FLAG_RELIABLE )
  564. {
  565. /*
  566. int i, bit = 1<<msg.ReadUBitLong( 3 );
  567. for ( i=0; i<MAX_STREAMS; i++ )
  568. {
  569. if ( msg.ReadOneBit() != 0 )
  570. {
  571. if ( !ReadSubChannelData( msg, i ) )
  572. return false; // error while reading fragments, drop whole packet
  573. }
  574. }
  575. // flip subChannel bit to signal successfull receiving
  576. FLIPBIT(m_nInReliableState, bit);
  577. for ( i=0; i<MAX_STREAMS; i++ )
  578. {
  579. if ( !CheckReceivingList( i ) )
  580. return false; // error while processing
  581. }
  582. */
  583. }
  584. return true;
  585. }
  586. bool CNetChannel::ProcessPacket( CNetPacket *packet )
  587. {
  588. return ProcessMessages( packet->m_Message );
  589. }
  590. void CNetChannel::EndProcessingPacket( CNetPacket *packet )
  591. {
  592. // tell message handler that packet is completely parsed
  593. if ( m_MessageHandler )
  594. {
  595. m_MessageHandler->OnPacketFinished();
  596. }
  597. }
  598. bool CNetChannel::AddNetMsg( INetworkMessage *msg, bool bForceReliable )
  599. {
  600. if ( msg->IsReliable() || bForceReliable )
  601. {
  602. WriteNetworkMessage( m_StreamReliable, msg );
  603. if ( m_StreamReliable.IsOverflowed() )
  604. return false;
  605. return msg->WriteToBuffer( m_StreamReliable );
  606. }
  607. WriteNetworkMessage( m_StreamUnreliable, msg );
  608. if ( m_StreamUnreliable.IsOverflowed() )
  609. return false;
  610. return msg->WriteToBuffer( m_StreamUnreliable );
  611. }
  612. bool CNetChannel::AddData( bf_write &msg, bool bReliable )
  613. {
  614. // Always queue any pending reliable data ahead of the fragmentation buffer
  615. if ( msg.GetNumBitsWritten() <= 0 )
  616. return true;
  617. bf_write * buf = bReliable ? &m_StreamReliable : &m_StreamUnreliable;
  618. if ( msg.GetNumBitsWritten() > buf->GetNumBitsLeft() )
  619. {
  620. if ( bReliable )
  621. {
  622. Msg( "ERROR! SendData reliabe data too big (%i)", msg.GetNumBytesWritten() );
  623. }
  624. return false;
  625. }
  626. return buf->WriteBits( msg.GetData(), msg.GetNumBitsWritten() );
  627. }
  628. int CNetChannel::GetDataRate() const
  629. {
  630. return m_Rate;
  631. }
  632. bool CNetChannel::HasPendingReliableData( void )
  633. {
  634. return ( m_StreamReliable.GetNumBitsWritten() > 0 );
  635. }
  636. float CNetChannel::GetTimeConnected() const
  637. {
  638. float t = g_pNetworkSystemImp->GetTime() - connect_time;
  639. return (t>0.0f) ? t : 0.0f ;
  640. }
  641. const netadr_t & CNetChannel::GetRemoteAddress() const
  642. {
  643. return remote_address;
  644. }
  645. bool CNetChannel::IsTimedOut() const
  646. {
  647. if ( m_Timeout == -1.0f )
  648. return false;
  649. else
  650. return ( last_received + m_Timeout ) < g_pNetworkSystemImp->GetTime();
  651. }
  652. bool CNetChannel::IsTimingOut() const
  653. {
  654. if ( m_Timeout == -1.0f )
  655. return false;
  656. else
  657. return (last_received + CONNECTION_PROBLEM_TIME) < g_pNetworkSystemImp->GetTime();
  658. }
  659. float CNetChannel::GetTimeSinceLastReceived() const
  660. {
  661. float t = g_pNetworkSystemImp->GetTime() - last_received;
  662. return (t>0.0f) ? t : 0.0f ;
  663. }
  664. bool CNetChannel::IsOverflowed() const
  665. {
  666. return m_StreamReliable.IsOverflowed();
  667. }
  668. void CNetChannel::Clear()
  669. {
  670. Reset();
  671. }
  672. void CNetChannel::Reset()
  673. {
  674. // FlowReset();
  675. m_StreamUnreliable.Reset(); // clear any pending unreliable data messages
  676. m_StreamReliable.Reset(); // clear any pending reliable data messages
  677. m_fClearTime = 0.0; // ready to send
  678. m_nChokedPackets = 0;
  679. }
  680. CUDPSocket *CNetChannel::GetSocket()
  681. {
  682. return m_pSocket;
  683. }
  684. float CNetChannel::GetAvgData( int flow ) const
  685. {
  686. return 0.0f;
  687. // return m_DataFlow[flow].avgbytespersec;
  688. }
  689. float CNetChannel::GetAvgPackets( int flow ) const
  690. {
  691. return 0.0f;
  692. // return m_DataFlow[flow].avgpacketspersec;
  693. }
  694. //-----------------------------------------------------------------------------
  695. // Purpose:
  696. // Input : *chan -
  697. //-----------------------------------------------------------------------------
  698. int CNetChannel::GetTotalData(int flow ) const
  699. {
  700. return 0;
  701. // return m_DataFlow[flow].totalbytes;
  702. }
  703. /*
  704. int CNetChannel::GetSequenceNr( int flow ) const
  705. {
  706. if ( flow == FLOW_OUTGOING )
  707. {
  708. return m_nOutSequenceNr;
  709. }
  710. else if ( flow == FLOW_INCOMING )
  711. {
  712. return m_nInSequenceNr;
  713. }
  714. return 0;
  715. }
  716. */
  717. float CNetChannel::GetLatency( int flow ) const
  718. {
  719. return 0.0f;
  720. // return m_DataFlow[flow].latency;
  721. }
  722. float CNetChannel::GetAvgChoke( int flow ) const
  723. {
  724. return 0.0f;
  725. //return m_DataFlow[flow].avgchoke;
  726. }
  727. float CNetChannel::GetAvgLatency( int flow ) const
  728. {
  729. return 0.0f;
  730. //return m_DataFlow[flow].avglatency;
  731. }
  732. float CNetChannel::GetAvgLoss( int flow ) const
  733. {
  734. return 0.0f;
  735. //return m_DataFlow[flow].avgloss;
  736. }