/
net_main.c
1165 lines (1013 loc) · 30.6 KB
/
net_main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* DE1: $Id$
* Copyright (C) 2003 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not: http://www.opensource.org/
*/
/*
* net_main.c: Network Subsystem
*
* Client/server networking. Player number zero is always the server.
* In single-player games there is only the server present.
*
* Once upon a time based on Hexen's peer-to-peer network code.
*/
// HEADER FILES ------------------------------------------------------------
#include <stdlib.h> // for atoi()
#include "de_base.h"
#include "de_console.h"
#include "de_system.h"
#include "de_network.h"
#include "de_play.h"
#include "de_graphics.h"
#include "de_misc.h"
#include "de_ui.h"
// MACROS ------------------------------------------------------------------
#define OBSOLETE CVF_NO_ARCHIVE|CVF_HIDE // Old ccmds.
// The threshold is the average ack time * mul.
#define ACK_THRESHOLD_MUL 4
// Never wait a too short time for acks.
#define ACK_MINIMUM_THRESHOLD 50
// Clients don't send commands on every tic.
#define CLIENT_TICCMD_INTERVAL 2
// TYPES -------------------------------------------------------------------
// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------
extern void ST_NetProgress(void);
extern void ST_NetDone(void);
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
// EXTERNAL DATA DECLARATIONS ----------------------------------------------
extern int net_skewdampen; // In frames.
extern boolean net_showskew;
//extern int latest_frame_size;
//extern netdata_t latest_frame_packet;
// PUBLIC DATA DEFINITIONS -------------------------------------------------
byte *localticcmds;
int numlocal; // Number of cmds in the buffer.
ddplayer_t players[MAXPLAYERS];
client_t clients[MAXPLAYERS];// All network data for the players.
int netgame; // true if a netgame is in progress
int isServer; // true if this computer is an open server.
int isClient; // true if this computer is a client
int consoleplayer;
int displayplayer;
int gametic;
int lasttime, availabletics, realtics;
// Gotframe is true if a frame packet has been received.
int gotframe = false;
boolean firstNetUpdate = true;
boolean monitorSendQueue = false;
boolean net_showlatencies = false;
boolean net_dev = false;
int net_dontsleep = false;
int net_ticsync = true;
float net_connecttime;
int net_coordtime = 10;
float net_connecttimeout = 10;
// Local packets are stored into this buffer.
boolean reboundpacket;
netbuffer_t reboundstore;
cvar_t netCVars[] =
{
"net_MSQ", OBSOLETE, CVT_BYTE, &monitorSendQueue, 0, 1, "Monitor send queue.",
"net_Latencies", OBSOLETE, CVT_BYTE, &net_showlatencies, 0, 1, "Show client latencies.",
"net_Dev", OBSOLETE, CVT_BYTE, &net_dev, 0, 1, "Network development mode.",
"net_DontSleep", OBSOLETE, CVT_BYTE, &net_dontsleep, 0, 1, "1=Don't sleep while waiting for tics.",
"net_FrameInterval", OBSOLETE|CVF_NO_MAX, CVT_INT, &frameInterval, 0, 0, "Minimum number of tics between sent frames.",
"net_Password", OBSOLETE, CVT_CHARPTR, &net_password, 0, 0, "Password for remote login.",
//--------------------------------------------------------------------------
// Some of these are obsolete...
//--------------------------------------------------------------------------
"net-queue-show", 0, CVT_BYTE, &monitorSendQueue, 0, 1, "Monitor send queue.",
"net-dev", 0, CVT_BYTE, &net_dev, 0, 1, "Network development mode.",
"net-nosleep", 0, CVT_BYTE, &net_dontsleep, 0, 1, "1=Don't sleep while waiting for tics.",
"client-pos-interval", CVF_NO_MAX, CVT_INT, &net_coordtime, 0, 0, "Number of tics between client coord packets.",
"client-connect-timeout", CVF_NO_MAX, CVT_FLOAT, &net_connecttimeout, 0, 0, "Maximum number of seconds to attempt connecting to a server.",
"server-password", 0, CVT_CHARPTR, &net_password, 0, 0, "Password for remote login.",
"server-latencies", 0, CVT_BYTE, &net_showlatencies, 0, 1, "Show client latencies.",
"server-frame-interval", CVF_NO_MAX, CVT_INT, &frameInterval, 0, 0, "Minimum number of tics between sent frames.",
"server-player-limit", 0, CVT_INT, &sv_maxPlayers, 0, MAXPLAYERS, "Maximum number of players on the server.",
NULL
};
// PRIVATE DATA DEFINITIONS ------------------------------------------------
static int coordTimer = 0;
// CODE --------------------------------------------------------------------
//===========================================================================
// Net_Init
//===========================================================================
void Net_Init(void)
{
Net_AllocArrays();
memset(&netbuffer, 0, sizeof(netbuffer));
netbuffer.headerLength = netbuffer.msg.data - (byte*) &netbuffer.msg;
// The game is always started in single-player mode.
netgame = false;
}
//===========================================================================
// Net_Shutdown
//===========================================================================
void Net_Shutdown(void)
{
netgame = false;
N_Shutdown();
Net_DestroyArrays();
}
//===========================================================================
// Net_GetPlayerName
// Returns the name of the specified player.
//===========================================================================
char *Net_GetPlayerName(int player)
{
return clients[player].name;
}
//===========================================================================
// Net_GetPlayerID
//===========================================================================
id_t Net_GetPlayerID(int player)
{
if(!clients[player].connected) return 0;
return clients[player].id;
}
//===========================================================================
// Net_SendBuffer
// Sends the contents of the netbuffer.
//===========================================================================
void Net_SendBuffer(int to_player, int sp_flags)
{
// Don't send anything during demo playback.
if(playback) return;
// Update the length of the message.
netbuffer.length = netbuffer.cursor - netbuffer.msg.data;
netbuffer.player = to_player;
// A rebound packet?
if(sp_flags & SPF_REBOUND)
{
reboundstore = netbuffer;
reboundpacket = true;
return;
}
Demo_WritePacket(to_player);
// Can we send the packet?
if(sp_flags & SPF_DONT_SEND) return;
// Send the packet to the network.
N_SendPacket(sp_flags);
}
// Returns false if there are no packets waiting.
boolean Net_GetPacket(void)
{
if(reboundpacket) // Local packets rebound.
{
netbuffer = reboundstore;
netbuffer.player = consoleplayer;
netbuffer.cursor = netbuffer.msg.data;
reboundpacket = false;
return true;
}
if(playback)
{
// We're playing a demo. This overrides all other packets.
return Demo_ReadPacket();
}
if(!netgame)
{
// Packets cannot be received.
return false;
}
if(!N_GetPacket()) return false;
// Are we recording a demo?
if(isClient && clients[consoleplayer].recording)
Demo_WritePacket(consoleplayer);
// Reset the cursor for Msg_* routines.
netbuffer.cursor = netbuffer.msg.data;
return true;
}
/*boolean Net_GetLatestFramePacket(void)
{
if(!isClient || !latest_frame_size) return false;
// Place the latest frame packet to the netbuffer.
memcpy(&netbuffer.msg, &latest_frame_packet, latest_frame_size);
netbuffer.cursor = netbuffer.msg.data;
netbuffer.length = latest_frame_size - netbuffer.headerLength;
// Clear the buffer.
latest_frame_size = 0;
return true;
}*/
//===========================================================================
// Net_SendPacket
// This is the public interface of the message sender.
//===========================================================================
void Net_SendPacket(int to_player, int type, void *data, int length)
{
int flags = 0;
// What kind of delivery to use?
if(to_player & DDSP_CONFIRM) flags |= SPF_CONFIRM;
if(to_player & DDSP_ORDERED) flags |= SPF_ORDERED;
Msg_Begin(type);
if(data) Msg_Write(data, length);
if(isClient)
{
// As a client we can only send messages to the server.
Net_SendBuffer(0, flags);
}
else
{
// The server can send packets to any player.
// Only allow sending to the sixteen possible players.
Net_SendBuffer(to_player & DDSP_ALL_PLAYERS? NSP_BROADCAST
: (to_player & 0xf), flags);
}
}
//===========================================================================
// Net_ShowChatMessage
// Prints the message in the console.
//===========================================================================
void Net_ShowChatMessage()
{
// The current packet in the netbuffer is a chat message,
// let's unwrap and show it.
Con_FPrintf(CBLF_GREEN, "%s: %s\n",
clients[netbuffer.msg.data[0]].name,
netbuffer.msg.data + 3);
}
// All arguments are sent out as a chat message.
int CCmdChat(int argc, char **argv)
{
char buffer[100];
int i, mode = !stricmp(argv[0], "chat") || !stricmp(argv[0], "say")? 0
: !stricmp(argv[0], "chatNum") || !stricmp(argv[0], "sayNum")? 1 : 2;
unsigned short mask = 0;
if(argc == 1)
{
Con_Printf("Usage: %s %s(text)\n", argv[0],
!mode? "" : mode==1? "(plr#) " : "(name) ");
Con_Printf("Chat messages are max. 80 characters long.\n");
Con_Printf("Use quotes to get around arg processing.\n");
return true;
}
// Chatting is only possible when connected.
if(!netgame) return false;
// Too few arguments?
if(mode && argc < 3) return false;
// Assemble the chat message.
strcpy(buffer, argv[!mode? 1 : 2]);
for(i = (!mode? 2 : 3); i < argc; i++)
{
strcat(buffer, " ");
strncat(buffer, argv[i], 80 - (strlen(buffer)+strlen(argv[i])+1));
}
buffer[80] = 0;
// Send the message.
switch(mode)
{
case 0: // chat
mask = ~0;
break;
case 1: // chatNum
mask = 1 << atoi(argv[1]);
break;
case 2: // chatTo
for(i = 0; i < MAXPLAYERS; i++)
if(!stricmp(clients[i].name, argv[1]))
{
mask = 1 << i;
break;
}
}
Msg_Begin(pkt_chat);
Msg_WriteByte(consoleplayer);
Msg_WriteShort(mask);
Msg_Write(buffer, strlen(buffer) + 1);
if(!isClient)
{
if(mask == (unsigned short) ~0)
{
Net_SendBuffer(NSP_BROADCAST, SPF_ORDERED);
}
else
{
for(i = 1; i < MAXPLAYERS; i++)
if(players[i].ingame && mask & (1 << i))
Net_SendBuffer(i, SPF_ORDERED);
}
}
else
{
Net_SendBuffer(0, SPF_ORDERED);
}
// Show the message locally.
Net_ShowChatMessage();
// Inform the game, too.
gx.NetPlayerEvent(consoleplayer, DDPE_CHAT_MESSAGE, buffer);
return true;
}
// Returns a pointer to a new local ticcmd so it can be built.
// Returns NULL if the buffer is full.
ticcmd_t *Net_LocalCmd()
{
// Check that the localtics buffer still has room.
if(numlocal == LOCALTICS) return NULL;
// One more command. The counter is cleared when the cmds are sent.
return (ticcmd_t*) &localticcmds[TICCMD_IDX(numlocal++)];
}
/*
* After a long period with no updates (map setup), calling this will
* reset the tictimer so that no time seems to have passed.
*/
void Net_ResetTimer(void)
{
lasttime = Sys_GetTime();
}
/*
* Build ticcmds for console player, sends out a packet.
*/
void Net_Update(void)
{
static int ticSendTimer = 0;
int nowtime;
int newtics;
int i;
// Check time.
nowtime = Sys_GetTime();
// Synchronize tics with game time, not the clock?
if(!net_ticsync) nowtime = gametic;
if(firstNetUpdate)
{
firstNetUpdate = false;
lasttime = nowtime;
}
newtics = nowtime - lasttime;
if(newtics <= 0) goto listen; // Nothing new to update.
lasttime = nowtime;
// Realtics counts the actual time that has passed.
realtics += newtics;
// Build new ticcmds for console player.
for(i = 0; i < newtics; i++)
{
DD_StartTic();
DD_ProcessEvents();
/*Con_Printf("mktic:%i gt:%i newtics:%i >> %i\n",
maketic, gametic, newtics, maketic-gametic);*/
if(playback)
{
numlocal = 0;
if(availabletics < LOCALTICS) availabletics++;
}
else if(!isDedicated && !ui_active)
{
// Place the new ticcmd in the local ticcmds buffer.
ticcmd_t *cmd = Net_LocalCmd();
if(cmd)
{
gx.BuildTicCmd(cmd);
// Set the time stamp. Only the lowest byte is stored.
//cmd->time = gametic + availabletics;
// Availabletics counts the tics that have cmds.
availabletics++;
if(isClient)
{
// When not playing a demo, this is the last command.
// It is used in local movement prediction.
memcpy(clients[consoleplayer].lastcmd, cmd, sizeof(*cmd));
}
}
}
}
// This is as far as dedicated servers go.
if(isDedicated) goto listen;
// Clients don't send commands on every tic.
ticSendTimer += newtics;
if(!isClient || ticSendTimer > CLIENT_TICCMD_INTERVAL)
{
byte *msg;
ticSendTimer = 0;
// The game will pack the commands into a buffer. The returned
// pointer points to a buffer that contains its size and the
// packed commands.
msg = (byte*) gx.NetPlayerEvent(numlocal, DDPE_WRITE_COMMANDS,
localticcmds);
Msg_Begin(pcl_commands);
Msg_Write(msg + 2, *(ushort*) msg);
// Send the packet to the server, i.e. player zero.
Net_SendBuffer(0, isClient? 0 : SPF_REBOUND);
// The buffer is cleared.
numlocal = 0;
}
// Clients will periodically send their coordinates to the server so
// any prediction errors can be fixed. Client movement is almost
// entirely local.
coordTimer -= newtics;
if(isClient && allowFrames && coordTimer < 0
&& players[consoleplayer].mo)
{
mobj_t *mo = players[consoleplayer].mo;
coordTimer = net_coordtime; // 35/2
Msg_Begin(pkt_coords);
Msg_WriteShort(mo->x >> 16);
Msg_WriteShort(mo->y >> 16);
if(mo->z == mo->floorz)
{
// This'll keep us on the floor even in fast moving sectors.
Msg_WriteShort(DDMININT >> 16);
}
else
{
Msg_WriteShort(mo->z >> 16);
}
Net_SendBuffer(0, 0);
}
listen:
// Listen for packets. Call the correct packet handler.
if(isClient)
Cl_GetPackets();
else // Single-player or server.
Sv_GetPackets();
}
//===========================================================================
// Net_AllocArrays
// Called from Net_Init to initialize the ticcmd arrays.
//===========================================================================
void Net_AllocArrays(void)
{
int i;
// Local ticcmds are stored into this array before they're copied
// to netplayer[0]'s ticcmds buffer.
localticcmds = calloc(LOCALTICS, TICCMD_SIZE);
numlocal = 0; // Nothing in the buffer.
for(i = 0; i < MAXPLAYERS; i++)
{
memset(clients+i, 0, sizeof(clients[i]));
// The server stores ticcmds sent by the clients to these
// buffers.
clients[i].ticcmds = calloc(BACKUPTICS, TICCMD_SIZE);
// The last cmd that was executed is stored here.
clients[i].lastcmd = calloc(1, TICCMD_SIZE);
clients[i].runTime = -1;
}
}
void Net_DestroyArrays(void)
{
int i;
free(localticcmds);
localticcmds = NULL;
for(i = 0; i < MAXPLAYERS; i++)
{
free(clients[i].ticcmds);
free(clients[i].lastcmd);
clients[i].ticcmds = NULL;
clients[i].lastcmd = NULL;
}
}
//
// This is the network one-time initialization.
// (into single-player mode)
//
void Net_InitGame (void)
{
Cl_InitID();
// In single-player mode there is only player number zero.
consoleplayer = displayplayer = 0;
// We're in server mode if we aren't a client.
isServer = true;
// Netgame is true when we're aware of the network (i.e. other players).
netgame = false;
players[0].ingame = true;
players[0].flags |= DDPF_LOCAL;
clients[0].id = clientID;
clients[0].ready = true;
clients[0].connected = true;
clients[0].viewConsole = 0;
clients[0].lastTransmit = -1;
// Are we timing a demo here?
if(ArgCheck("-timedemo")) net_ticsync = false;
}
//===========================================================================
// Net_StopGame
//===========================================================================
void Net_StopGame(void)
{
int i;
if(isServer)
{
// We are an open server. This means we should inform all the
// connected clients that the server is about to close.
Msg_Begin(psv_server_close);
Net_SendBuffer(NSP_BROADCAST, SPF_CONFIRM);
}
else
{
// Must stop recording, we're disconnecting.
Demo_StopRecording(consoleplayer);
Cl_CleanUp();
isClient = false;
}
// Netgame has ended.
netgame = false;
isServer = true;
// No more remote users.
net_remoteuser = 0;
netLoggedIn = false;
// All remote players are forgotten.
for(i = 0; i < MAXPLAYERS; i++)
{
players[i].ingame = false;
clients[i].ready = clients[i].connected = false;
players[i].flags &= ~(DDPF_CAMERA | DDPF_LOCAL);
}
// We're about to become player zero, so update it's view angles to
// match our current ones.
if(players[0].mo)
{
players[0].mo->angle = players[consoleplayer].clAngle;
players[0].lookdir = players[consoleplayer].clLookDir;
}
consoleplayer = displayplayer = 0;
players[0].ingame = true;
clients[0].ready = true;
clients[0].connected = true;
clients[0].viewConsole = 0;
players[0].flags |= DDPF_LOCAL;
}
// Returns delta based on 'now' (- future, + past).
int Net_TimeDelta(byte now, byte then)
{
int delta;
if(now >= then)
{
// Simple case.
delta = now - then;
}
else
{
// There's a wraparound.
delta = 256 - then + now;
}
// The time can be in the future. We'll allow one second.
if(delta > 220) delta -= 256;
return delta;
}
//===========================================================================
// Net_GetTicCmd
// This is a bit complicated and quite possibly unnecessarily so. The
// idea is, however, that because the ticcmds sent by clients arrive in
// bursts, we'll preserve the motion by 'executing' the commands in the
// same order in which they were generated. If the client's connection
// lags a lot, the difference between the serverside and clientside
// positions will be *large*, especially when the client is running.
// If too many commands are buffered, the client's coord announcements
// will be processed before the actual movement commands, resulting in
// serverside warping (which is perceived by all other clients).
//===========================================================================
int Net_GetTicCmd(void *pCmd, int player)
{
client_t *client = &clients[player];
ticcmd_t *cmd = pCmd;
/* int doMerge = false;
int future;*/
if(client->numtics <= 0)
{
// No more commands for this player.
return false;
}
// Return the next ticcmd from the buffer.
// There will be one less tic in the buffer after this.
client->numtics--;
memcpy(cmd, &client->ticcmds[ TICCMD_IDX(client->firsttic++) ],
TICCMD_SIZE);
// This is the new last command.
memcpy(client->lastcmd, cmd, TICCMD_SIZE);
// Make sure the firsttic index is in range.
client->firsttic %= BACKUPTICS;
return true;
#if 0
//Con_Printf("GetTicCmd: Cl=%i, GT=%i (%i)...\n", player, gametic, (byte)gametic);
// Check the lag stress.
/* if(cl->lagStress > net_stressmargin)
{
// Command lag should be increased, we're running out of cmds.
cl->lagStress -= net_stressmargin;
memcpy(cmd, cl->lastcmd, TICCMD_SIZE); // Repeat lastcmd.
//Con_Printf(" Increasing lag\n");
return true;
}
else if(cl->lagStress < -net_stressmargin)
{
// Command lag should be decreased.
cl->lagStress += net_stressmargin;
cl->runTime++;
//Con_Printf(" Decreasing lag\n");
}*/
for(;;)
{
if(Net_TimeDelta(gametic, cl->runTime) <= 0)
{
//Con_Printf(" Running in the future! Rt=%i\n", cl->runTime);
future = true;
//cl->lagStress++;
}
else
{
future = false;
}
// Are there any commands left for this player?
if(!cl->numtics)
{
cl->lagStress++;
// Reuse the last command.
memcpy(cmd, cl->lastcmd, TICCMD_SIZE);
// Runtime advances.
if(!future) cl->runTime++;
//Con_Printf(" Out of Cmds! Rt set to %i\n", cl->runTime);
return false;
}
// There's at least one command in the buffer.
// There will be one less tic in the buffer after this.
cl->numtics--;
memcpy(cmd, &cl->ticcmds[TICCMD_IDX(cl->firsttic++)], TICCMD_SIZE);
// Make sure the firsttic iterator is in range.
if(cl->firsttic >= BACKUPTICS) cl->firsttic = 0;
// Do we need to do any merging?
if(doMerge && gx.DiscardTicCmd) gx.DiscardTicCmd(cl->lastcmd, cmd);
// This is the new last command.
memcpy(cl->lastcmd, cmd, TICCMD_SIZE);
// Check that the command is valid (not if its tick has already passed).
if(Net_TimeDelta(cl->runTime, cmd->time) >= 0)
{
//Con_Printf(" Obsolete Cmd! Rt=%i Ct=%i\n", cl->runTime, cmd->time);
// Cmd is too old. Go to next command and merge this one with it.
doMerge = true;
continue;
}
cl->runTime = cmd->time;
// Note command lag.
cl->lag = Sv_Latency(cmd->time);
// The local player doesn't need lag stress, because we know it's
// always running exactly synced with the server, i.e. itself.
if(player && cl->numtics > 1) cl->lagStress--;
//Con_Printf(" CmdLag=%i\n", cl->lag);
break;
}
return true;
#endif
}
//===========================================================================
// Net_Drawer
// Does drawing for the engine's HUD, not just the net.
//===========================================================================
void Net_Drawer(void)
{
char buf[160], tmp[40];
int i, c;
boolean show_blink_r = false;
for(i = 0; i < MAXPLAYERS; i++)
if(players[i].ingame && clients[i].recording)
show_blink_r = true;
if(!net_dev && !show_blink_r && !consoleShowFPS) return;
// Go into screen projection mode.
gl.MatrixMode(DGL_PROJECTION);
gl.PushMatrix();
gl.LoadIdentity();
gl.Ortho(0, 0, screenWidth, screenHeight, -1, 1);
if(show_blink_r && gametic & 8)
{
strcpy(buf, "[");
for(i = c = 0; i < MAXPLAYERS; i++)
{
if(!players[i].ingame || !clients[i].recording) continue;
if(c++) strcat(buf, ",");
sprintf(tmp, "%i:%s", i, clients[i].recordpaused? "-P-" : "REC");
strcat(buf, tmp);
}
strcat(buf, "]");
i = screenWidth - FR_TextWidth(buf);
gl.Color3f(0, 0, 0);
FR_TextOut(buf, i - 8, 12);
gl.Color3f(1, 1, 1);
FR_TextOut(buf, i - 10, 10);
}
if(net_dev)
{
/* gl.Color3f(1, 1, 1);
sprintf(buf, "G%i", gametic);
FR_TextOut(buf, 10, 10);
for(i = 0, cl = clients; i<MAXPLAYERS; i++, cl++)
if(players[i].ingame)
{
sprintf(buf, "%02i:%+04i[%+03i](%02d/%03i) pf:%x", i, cl->lag,
cl->lagStress, cl->numtics, cl->runTime,
players[i].flags);
FR_TextOut(buf, 10, 10+10*(i+1));
}*/
}
if(consoleShowFPS)
{
int x, y = 30, w, h;
sprintf(buf, "%i FPS", DD_GetFrameRate());
w = FR_TextWidth(buf) + 16;
h = FR_TextHeight(buf) + 16;
x = screenWidth - w - 10;
UI_GradientEx(x, y, w, h, 6,
UI_COL(UIC_BG_MEDIUM), UI_COL(UIC_BG_LIGHT), .5f, .5f);
UI_DrawRectEx(x, y, w, h, 6, false,
UI_COL(UIC_BRD_HI), NULL, .5f, -1);
UI_Color(UI_COL(UIC_TEXT));
UI_TextOutEx(buf, x + 8, y + h/2, false, true, UI_COL(UIC_TEXT), 1);
}
// Restore original matrix.
gl.MatrixMode(DGL_PROJECTION);
gl.PopMatrix();
}
/*
* Maintain the ack threshold average.
*/
void Net_SetAckTime(int clientNumber, uint period)
{
client_t *client = &clients[clientNumber];
// Add the new time into the array.
client->ackTimes[ client->ackIdx++ ] = period;
client->ackIdx %= NUM_ACK_TIMES;
}
/*
* Returns the average ack time of the client.
*/
uint Net_GetAckTime(int clientNumber)
{
client_t *client = &clients[clientNumber];
uint average = 0;
int i;
// Calculate the average.
for(i = 0; i < NUM_ACK_TIMES; i++)
{
average += client->ackTimes[i];
}
return average / NUM_ACK_TIMES;
}
/*
* Sets all the ack times. Used to initial the ack times for new clients.
*/
void Net_SetInitialAckTime(int clientNumber, uint period)
{
int i;
for(i = 0; i < NUM_ACK_TIMES; i++)
{
clients[clientNumber].ackTimes[i] = period;
}
}
/*
* The ack threshold is the maximum period of time to wait before
* deciding an ack is not coming. The minimum threshold is 50 ms.
*/
uint Net_GetAckThreshold(int clientNumber)
{
uint threshold = Net_GetAckTime(clientNumber) * ACK_THRESHOLD_MUL;
if(threshold < ACK_MINIMUM_THRESHOLD)
{
threshold = ACK_MINIMUM_THRESHOLD;
}
return threshold;
}
int Sv_GetRegisteredMobj(pool_t*, thid_t, mobjdelta_t*);
//===========================================================================
// Net_Ticker
//===========================================================================
void Net_Ticker(void)
{
int i;
client_t *cl;
static int monitorCount = 0;
static int dampenCount = 0;
N_Ticker();
if(net_dev)
{
static int printTimer = 0;
if(printTimer++ > TICSPERSEC)
{
printTimer = 0;
for(i = 0; i < MAXPLAYERS; i++)
{
if(Sv_IsFrameTarget(i))
{
Con_Message("%i(rdy%i): avg=%05ims thres=%05ims bwr=%05i (adj:%i) "
"maxfs=%05ib\n",
i, clients[i].ready, Net_GetAckTime(i),
Net_GetAckThreshold(i),
clients[i].bandwidthRating,
clients[i].bwrAdjustTime,
Sv_GetMaxFrameSize(i));
}
if(players[i].ingame)
Con_Message("%i: cmds=%i\n", i, clients[i].numtics);
}
}
}
// The following stuff is only for netgames.
if(!netgame) return;
// Check the pingers.
for(i = 0, cl = clients; i < MAXPLAYERS; i++, cl++)
{
// Clients can only ping the server.
if(isClient && i || i == consoleplayer) continue;
if(cl->ping.sent)
{
// The pinger is active.
if(Sys_GetRealTime() - cl->ping.sent > PING_TIMEOUT) // Timed out?
{
cl->ping.times[cl->ping.current] = -1;
Net_SendPing(i, 0);
}
}
}
}
//===========================================================================
// CCmdKick
//===========================================================================
int CCmdKick(int argc, char **argv)
{
int num;
if(argc != 2)
{
Con_Printf("Usage: %s (num)\n", argv[0]);
Con_Printf("Server can use this command to kick clients out of the game.\n");
return true;
}
if(!netgame)
{
Con_Printf("This is not a netgame.\n");
return false;
}
if(!isServer)
{
Con_Printf("This command is for the server only.\n");
return false;
}
num = atoi(argv[1]);
if(num < 1 || num >= MAXPLAYERS)
{
Con_Printf("Invalid client number.\n");
return false;
}
if(net_remoteuser == num)
{
Con_Printf("Can't kick the client who's logged in.\n");
return false;
}
Sv_Kick(num);
return true;
}
//===========================================================================
// CCmdSetName
//===========================================================================
int CCmdSetName(int argc, char **argv)
{