/
ServerGameState.cpp
7244 lines (5973 loc) · 174 KB
/
ServerGameState.cpp
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
#include <StdInc.h>
#include <GameServer.h>
#include <state/ServerGameState.h>
#include <optional>
#include <charconv>
#include <NetBuffer.h>
#include <lz4.h>
#include <lz4hc.h>
#include <tbb/concurrent_queue.h>
#include <tbb/parallel_for_each.h>
#include <thread_pool.hpp>
#include <EASTL/fixed_set.h>
#include <EASTL/fixed_vector.h>
#include <state/Pool.h>
#include <IteratorView.h>
#include <ResourceEventComponent.h>
#include <ResourceManager.h>
#include <ServerEventComponent.h>
#include <boost/range/adaptors.hpp>
#include <boost/math/constants/constants.hpp>
#include <OneSyncVars.h>
#include <DebugAlias.h>
#include <StateBagComponent.h>
#include <citizen_util/object_pool.h>
#include <citizen_util/shared_reference.h>
#ifdef STATE_FIVE
static constexpr int kNetObjectTypeBitLength = 4;
#elif defined(STATE_RDR3)
static constexpr int kNetObjectTypeBitLength = 5;
#endif
static constexpr int kSyncPacketMaxLength = 2400;
static constexpr int kPacketWarnLength = 1300;
namespace rl
{
bool MessageBuffer::GetLengthHackState()
{
return fx::IsLengthHack();
}
}
CPool<fx::ScriptGuid>* g_scriptHandlePool;
std::shared_mutex g_scriptHandlePoolMutex;
enum class RequestControlFilterMode : int
{
// Default is currently equivalent to FilterPlayer
Default = -1,
// NoFilter will not filter any control requests
NoFilter = 0,
// FilterPlayerSettled will filter control requests targeting player-controlled settled entities
FilterPlayerSettled,
// FilterPlayer will filter control requests targeting any player-controlled entities
FilterPlayer,
// FilterPlayerPlusNonPlayerSettled will filter control requests targeting player-controlled entities, or settled entities
FilterPlayerPlusNonPlayerSettled,
// FilterAll will filter all control requests, i.e. allow none
FilterAll,
};
std::shared_ptr<ConVar<bool>> g_oneSyncEnabledVar;
std::shared_ptr<ConVar<bool>> g_oneSyncCulling;
std::shared_ptr<ConVar<bool>> g_oneSyncVehicleCulling;
std::shared_ptr<ConVar<bool>> g_oneSyncForceMigration;
std::shared_ptr<ConVar<bool>> g_oneSyncRadiusFrequency;
std::shared_ptr<ConVar<std::string>> g_oneSyncLogVar;
std::shared_ptr<ConVar<bool>> g_oneSyncWorkaround763185;
std::shared_ptr<ConVar<bool>> g_oneSyncBigMode;
std::shared_ptr<ConVar<bool>> g_oneSyncLengthHack;
std::shared_ptr<ConVar<fx::OneSyncState>> g_oneSyncVar;
std::shared_ptr<ConVar<bool>> g_oneSyncPopulation;
std::shared_ptr<ConVar<bool>> g_oneSyncARQ;
static std::shared_ptr<ConVar<int>> g_requestControlVar;
static std::shared_ptr<ConVar<int>> g_requestControlSettleVar;
static RequestControlFilterMode g_requestControlFilterState;
static int g_requestControlSettleDelay;
static uint32_t MakeHandleUniqifierPair(uint16_t objectId, uint16_t uniqifier)
{
return ((uint32_t)objectId << 16) | (uint32_t)uniqifier;
}
static std::tuple<uint16_t, uint16_t> DeconstructHandleUniqifierPair(uint32_t pair)
{
return {
(uint16_t)(pair >> 16),
(uint16_t)pair
};
}
namespace fx
{
ClientEntityData::ClientEntityData(const sync::SyncEntityPtr& entity, uint64_t lastSent, bool isCreated)
: entityWeak(entity), lastSent(lastSent), isCreated(isCreated)
{
}
sync::SyncEntityPtr ClientEntityData::GetEntity(fx::ServerGameState* sgs) const
{
return entityWeak.lock();
}
}
extern tbb::concurrent_unordered_map<uint32_t, fx::EntityCreationState> g_entityCreationList;
static tbb::concurrent_queue<std::string> g_logQueue;
static std::condition_variable g_consoleCondVar;
static std::mutex g_consoleMutex;
static std::once_flag g_logOnceFlag;
static void Logv(const char* format, fmt::printf_args argumentList)
{
if (!g_oneSyncLogVar->GetValue().empty())
{
std::call_once(g_logOnceFlag, []()
{
std::thread([]()
{
while (true)
{
{
std::unique_lock<std::mutex> lock(g_consoleMutex);
g_consoleCondVar.wait(lock);
}
static std::string lastLogFile;
static FILE* file;
if (lastLogFile != g_oneSyncLogVar->GetValue())
{
if (file)
{
fclose(file);
file = nullptr;
}
if (!g_oneSyncLogVar->GetValue().empty())
{
file = _pfopen(MakeRelativeCitPath(g_oneSyncLogVar->GetValue()).c_str(), _P("w"));
}
lastLogFile = g_oneSyncLogVar->GetValue();
}
std::string str;
while (g_logQueue.try_pop(str))
{
if (file)
{
fprintf(file, "%s", str.c_str());
}
}
}
}).detach();
});
if (strchr(format, '\n'))
{
g_logQueue.push(fmt::sprintf("[% 10d] ", msec().count()));
}
g_logQueue.push(fmt::vsprintf(format, argumentList));
g_consoleCondVar.notify_all();
}
}
template<typename... TArgs>
inline void Log(const char* msg, const TArgs&... args)
{
Logv(msg, fmt::make_printf_args(args...));
}
#define GS_LOG(x, ...) \
do \
{ \
if (!g_oneSyncLogVar->GetValue().empty()) \
{ \
Log(x, __VA_ARGS__); \
} \
} while (false)
namespace fx
{
static const glm::mat4x4 g_projectionMatrix = glm::perspective(90.0f, 4.f / 3.f, 0.1f, 1000.f);
struct ViewClips
{
glm::vec4 nearClip;
glm::vec4 farClip;
glm::vec4 topClip;
glm::vec4 bottomClip;
glm::vec4 leftClip;
glm::vec4 rightClip;
ViewClips(const glm::mat4x4& matrix)
{
auto tpmatrix = glm::transpose(matrix);
leftClip = tpmatrix * glm::vec4{ 1.0f, 0.0f, 0.0f, 1.0f };
rightClip = tpmatrix * glm::vec4{ -1.0f, 0.0f, 0.0f, 1.0f };
bottomClip = tpmatrix * glm::vec4{ 0.0f, 1.0f, 0.0f, 1.0f };
topClip = tpmatrix * glm::vec4{ 0.0f, -1.0f, 0.0f, 1.0f };
nearClip = tpmatrix * glm::vec4{ 0.0f, 0.0f, 1.0f, 1.0f };
farClip = tpmatrix * glm::vec4{ 0.0f, 0.0f, -1.0f, 1.0f };
}
};
static const ViewClips g_projectionClips{ g_projectionMatrix };
static bool IsInFrustum(const glm::vec3& pos, float radius, const glm::mat4x4& viewMatrix)
{
auto viewCoords = viewMatrix * glm::vec4{ pos, 1.0f };
auto testPlane = [&viewCoords, &radius](const glm::vec4& plane)
{
glm::vec3 mcoords = viewCoords * plane;
return (mcoords.x + mcoords.y + mcoords.z + plane.w + radius) >= 0.0f;
};
return (testPlane(g_projectionClips.nearClip)
&& testPlane(g_projectionClips.bottomClip)
&& testPlane(g_projectionClips.topClip)
&& testPlane(g_projectionClips.leftClip)
&& testPlane(g_projectionClips.rightClip)
&& testPlane(g_projectionClips.farClip));
}
sync::SyncEntityState::SyncEntityState()
: deleting(false), lastOutOfBandTimestamp(0)
{
}
static void CreateSyncData(ServerGameState* state, const fx::ClientSharedPtr& client)
{
fx::ClientWeakPtr weakClient(client);
auto data = std::make_shared<GameStateClientData>();
data->client = weakClient;
std::weak_ptr<GameStateClientData> weakData(data);
auto setupBag = [weakClient, weakData, state]()
{
auto client = weakClient.lock();
auto data = weakData.lock();
if (client && data)
{
data->playerBag = state->GetStateBags()->RegisterStateBag(fmt::sprintf("player:%d", client->GetNetId()));
if (fx::IsBigMode())
{
data->playerBag->AddRoutingTarget(client->GetSlotId());
}
data->playerBag->SetOwningPeer(client->GetSlotId());
}
};
if (client->GetNetId() < 0xFFFF)
{
setupBag();
}
else
{
client->OnAssignNetId.Connect([setupBag]()
{
setupBag();
},
INT32_MAX);
}
client->SetSyncData(data);
client->OnDrop.Connect([weakClient, state]()
{
auto client = weakClient.lock();
if (client)
{
auto slotId = client->GetSlotId();
auto netId = client->GetNetId();
gscomms_execute_callback_on_sync_thread([state, client, slotId, netId]()
{
state->HandleClientDrop(client, netId, slotId);
});
}
});
}
inline std::shared_ptr<GameStateClientData> GetClientDataUnlocked(ServerGameState* state, const fx::ClientSharedPtr& client)
{
// NOTE: static_pointer_cast typically will lead to an unneeded refcount increment+decrement
// Doing this makes it so that there's only *one* increment for the fast case.
#ifndef _MSC_VER
auto data = std::static_pointer_cast<GameStateClientData>(client->GetSyncData());
#else
auto data = std::shared_ptr<GameStateClientData>{ reinterpret_cast<std::shared_ptr<GameStateClientData>&&>(client->GetSyncData()) };
#endif
return data;
}
inline std::tuple<std::unique_lock<std::mutex>, std::shared_ptr<GameStateClientData>> GetClientData(ServerGameState* state, const fx::ClientSharedPtr& client)
{
auto val = GetClientDataUnlocked(state, client);
std::unique_lock<std::mutex> lock(val->selfMutex);
return { std::move(lock), val };
}
inline uint32_t MakeEntityHandle(uint16_t objectId)
{
return objectId;
}
std::tuple<std::unique_lock<std::mutex>, std::shared_ptr<GameStateClientData>> ServerGameState::ExternalGetClientData(const fx::ClientSharedPtr& client)
{
return GetClientData(this, client);
}
static const char* PopTypeToString(fx::sync::ePopType type)
{
using namespace fx;
switch (type)
{
case fx::sync::POPTYPE_UNKNOWN:
return "POPTYPE_UNKNOWN";
case fx::sync::POPTYPE_RANDOM_PERMANENT:
return "POPTYPE_RANDOM_PERMANENT";
case fx::sync::POPTYPE_RANDOM_PARKED:
return "POPTYPE_RANDOM_PARKED";
case fx::sync::POPTYPE_RANDOM_PATROL:
return "POPTYPE_RANDOM_PATROL";
case fx::sync::POPTYPE_RANDOM_SCENARIO:
return "POPTYPE_RANDOM_SCENARIO";
case fx::sync::POPTYPE_RANDOM_AMBIENT:
return "POPTYPE_RANDOM_AMBIENT";
case fx::sync::POPTYPE_PERMANENT:
return "POPTYPE_PERMANENT";
case fx::sync::POPTYPE_MISSION:
return "POPTYPE_MISSION";
case fx::sync::POPTYPE_REPLAY:
return "POPTYPE_REPLAY";
case fx::sync::POPTYPE_CACHE:
return "POPTYPE_CACHE";
case fx::sync::POPTYPE_TOOL:
return "POPTYPE_TOOL";
default:
return "";
}
}
static const char* TypeToString(fx::sync::NetObjEntityType type)
{
using namespace fx;
switch (type)
{
case sync::NetObjEntityType::Automobile:
return "Automobile";
case sync::NetObjEntityType::Bike:
return "Bike";
case sync::NetObjEntityType::Boat:
return "Boat";
case sync::NetObjEntityType::Door:
return "Door";
case sync::NetObjEntityType::Heli:
return "Heli";
case sync::NetObjEntityType::Object:
return "Object";
case sync::NetObjEntityType::Ped:
return "Ped";
case sync::NetObjEntityType::Pickup:
return "Pickup";
case sync::NetObjEntityType::PickupPlacement:
return "PickupPlacement";
case sync::NetObjEntityType::Plane:
return "Plane";
case sync::NetObjEntityType::Submarine:
return "Submarine";
case sync::NetObjEntityType::Player:
return "Player";
case sync::NetObjEntityType::Trailer:
return "Trailer";
case sync::NetObjEntityType::Train:
return "Train";
}
return "UNKNOWN";
}
struct EntityImpl : sync::Entity
{
EntityImpl(const sync::SyncEntityPtr& ent)
: ent(ent)
{
}
bool IsPlayer() override
{
return ent->type == sync::NetObjEntityType::Player;
}
fx::ClientSharedPtr GetOwner() override
{
return ent->GetClient();
}
glm::vec3 GetPosition() override
{
if (ent->syncTree)
{
float positionFloat[3];
ent->syncTree->GetPosition(positionFloat);
return { positionFloat[0], positionFloat[1], positionFloat[2] };
}
return {};
}
private:
sync::SyncEntityPtr ent;
// Inherited via Entity
virtual uint32_t GetId() override
{
return ent->handle;
}
virtual std::string GetPopType() override
{
auto popType = fx::sync::POPTYPE_UNKNOWN;
if (ent->syncTree)
{
ent->syncTree->GetPopulationType(&popType);
}
return PopTypeToString(popType);
}
virtual uint32_t GetModel() override
{
uint32_t model = 0;
if (ent->syncTree)
{
ent->syncTree->GetModelHash(&model);
}
return model;
}
virtual std::string GetType() override
{
return TypeToString(ent->type);
}
};
void ServerGameState::ForAllEntities(const std::function<void(sync::Entity*)>& cb)
{
std::shared_lock _(m_entityListMutex);
for (auto& entity : m_entityList)
{
EntityImpl ent(entity);
cb(&ent);
}
}
uint32_t ServerGameState::MakeScriptHandle(const fx::sync::SyncEntityPtr& ptr)
{
// only one unique lock here since we can't upgrade from reader to writer
std::unique_lock<std::shared_mutex> guidLock(ptr->guidMutex);
if (!ptr->guid)
{
{
std::shared_lock<std::shared_mutex> _(g_scriptHandlePoolMutex);
// find an existing handle (transformed TempEntity?)
for (int i = 0; i < g_scriptHandlePool->m_Size; i++)
{
auto hdl = g_scriptHandlePool->GetAt(i);
if (hdl && !hdl->reference && hdl->type == ScriptGuid::Type::Entity && hdl->entity.handle == ptr->handle)
{
hdl->reference = ptr.get();
ptr->guid = hdl;
break;
}
}
}
if (!ptr->guid)
{
std::unique_lock<std::shared_mutex> _(g_scriptHandlePoolMutex);
auto guid = new ScriptGuid();
guid->type = ScriptGuid::Type::Entity;
guid->entity.handle = ptr->handle;
guid->reference = ptr.get();
ptr->guid = guid;
}
}
#ifdef VALIDATE_SCRIPT_GUIDS
if (ptr->guid->entity.handle != ptr->handle)
{
__debugbreak();
}
#endif
{
std::shared_lock<std::shared_mutex> _(g_scriptHandlePoolMutex);
auto guid = g_scriptHandlePool->GetIndex(ptr->guid) + 0x20000;
#ifdef VALIDATE_SCRIPT_GUIDS
if (!g_scriptHandlePool->AtHandle(guid - 0x20000) || guid & 0x80)
{
__debugbreak();
}
bool bad = false;
fx::ClientSharedPtr badClient;
m_instance->GetComponent<fx::ClientRegistry>()->ForAllClients([&](const fx::ClientSharedPtr& client)
{
try
{
if (fx::AnyCast<uint32_t>(client->GetData("playerEntity")) == guid)
{
bad = true;
badClient = client;
}
}
catch (std::bad_any_cast&)
{
}
});
if (bad && ptr->type != sync::NetObjEntityType::Player)
{
__debugbreak();
}
#endif
return guid;
}
}
using FocusResult = eastl::fixed_vector<glm::vec3, 5>;
FocusResult GetPlayerFocusPos(const fx::sync::SyncEntityPtr& entity)
{
auto syncTree = entity->syncTree;
if (!syncTree)
{
return {};
}
float playerPos[3];
syncTree->GetPosition(playerPos);
auto camData = syncTree->GetPlayerCamera();
if (!camData)
{
return { { playerPos[0], playerPos[1], playerPos[2] } };
}
switch (camData->camMode)
{
case 0:
default:
return { { playerPos[0], playerPos[1], playerPos[2] } };
case 1:
return {
{ playerPos[0], playerPos[1], playerPos[2] },
{ camData->freeCamPosX, camData->freeCamPosY, camData->freeCamPosZ }
};
case 2:
return {
{ playerPos[0], playerPos[1], playerPos[2] },
{ playerPos[0] + camData->camOffX, playerPos[1] + camData->camOffY, playerPos[2] + camData->camOffZ }
};
}
}
ServerGameState::ServerGameState()
: m_frameIndex(1), m_entitiesById(MaxObjectId), m_entityLockdownMode(EntityLockdownMode::Inactive)
{
#ifdef USE_ASYNC_SCL_POSTING
m_tg = std::make_unique<ThreadPool>();
#endif
fx::g_serverGameState = this;
}
fx::sync::SyncEntityPtr ServerGameState::GetEntity(uint8_t playerId, uint16_t objectId)
{
if (objectId >= m_entitiesById.size() || objectId < 0)
{
return {};
}
uint16_t objIdAlias = objectId;
debug::Alias(&objIdAlias);
std::shared_lock _lock(m_entitiesByIdMutex);
return m_entitiesById[objectId].lock();
}
fx::sync::SyncEntityPtr ServerGameState::GetEntity(uint32_t guid)
{
// subtract the minimum index GUID
guid -= 0x20000;
// get the pool entry
std::shared_lock<std::shared_mutex> _(g_scriptHandlePoolMutex);
auto guidData = g_scriptHandlePool->AtHandle(guid);
if (guidData)
{
if (guidData->type == ScriptGuid::Type::Entity)
{
std::shared_lock _lock(m_entitiesByIdMutex);
return m_entitiesById[guidData->entity.handle].lock();
}
}
return {};
}
namespace sync
{
SyncEntityState::~SyncEntityState()
{
if (guid)
{
std::unique_lock<std::shared_mutex> _(g_scriptHandlePoolMutex);
delete guid;
guid = nullptr;
}
}
}
struct FrameIndex
{
union
{
struct
{
uint64_t lastFragment : 1;
uint64_t currentFragment : 7;
uint64_t frameIndex : 56;
};
uint64_t full;
};
FrameIndex()
: full(0)
{
}
FrameIndex(uint64_t idx)
: full(idx)
{
}
};
static void FlushBuffer(rl::MessageBuffer& buffer, uint32_t msgType, uint64_t frameIndex, const fx::ClientSharedPtr& client, uint32_t* fragmentIndex = nullptr, bool finalFlush = false)
{
// condition is commented out to indicate this *was* there before without having to dig through commit history
// not sending any blank frames to clients leads to them not ACKing any frames, which will lead to an infinite buildup of frame states on server
//if (buffer.GetDataLength() > 0)
{
// end
buffer.Write(3, 7);
// compress and send
std::vector<char> outData(LZ4_compressBound(buffer.GetDataLength()) + 4 + 8);
int len = LZ4_compress_default(reinterpret_cast<const char*>(buffer.GetBuffer().data()), outData.data() + 4 + 8, buffer.GetDataLength(), outData.size() - 4 - 8);
FrameIndex newFrame{};
newFrame.frameIndex = frameIndex;
if (fragmentIndex != nullptr)
{
newFrame.lastFragment = finalFlush;
newFrame.currentFragment = ++*fragmentIndex;
}
*(uint32_t*)(outData.data()) = msgType;
*(uint64_t*)(outData.data() + 4) = newFrame.full;
int bufferLen = len + 4 + 8;
net::Buffer netBuffer(reinterpret_cast<uint8_t*>(outData.data()), bufferLen);
netBuffer.Seek(bufferLen); // since the buffer constructor doesn't actually set the offset
if (bufferLen >= kPacketWarnLength)
{
console::DPrintf("net", "Sending a large packet (%d compressed bytes) to client %d, report if there will be any sync issues\n", bufferLen, client->GetNetId());
}
GS_LOG("flushBuffer: sending %d bytes to %d\n", bufferLen, client->GetNetId());
client->SendPacket(1, netBuffer, NetPacketType_Unreliable);
size_t oldCurrentBit = buffer.GetCurrentBit();
debug::Alias(&oldCurrentBit);
debug::Alias(&len);
buffer.SetCurrentBit(0);
}
}
static void MaybeFlushBuffer(rl::MessageBuffer& buffer, uint32_t msgType, uint64_t frameIndex, const fx::ClientSharedPtr& client, size_t size = 0, uint32_t* fragmentIndex = nullptr)
{
if (LZ4_compressBound(buffer.GetDataLength() + (size / 8)) > (1100 - 12 - 12))
{
FlushBuffer(buffer, msgType, frameIndex, client, fragmentIndex);
}
}
void GameStateClientData::FlushAcks()
{
auto clientRef = client.lock();
if (clientRef)
{
FlushBuffer(ackBuffer, HashRageString("msgPackedAcks"), 0, clientRef);
}
}
void GameStateClientData::MaybeFlushAcks()
{
auto clientRef = client.lock();
if (clientRef)
{
MaybeFlushBuffer(ackBuffer, HashRageString("msgPackedAcks"), 0, clientRef);
}
}
void sync::SyncCommandList::Execute(const fx::ClientSharedPtr& client)
{
static thread_local SyncCommandState scs(16384);
auto& scsSelf = scs;
scs.frameIndex = frameIndex;
scs.client = client;
uint32_t fragmentIndex = 0;
scs.flushBuffer = [this, &scsSelf, &client, &fragmentIndex](bool finalFlush)
{
FlushBuffer(scsSelf.cloneBuffer, HashRageString("msgPackedClones"), frameIndex, client, &fragmentIndex, true);
};
scs.maybeFlushBuffer = [this, &scsSelf, &client, &fragmentIndex](size_t plannedBits)
{
MaybeFlushBuffer(scsSelf.cloneBuffer, HashRageString("msgPackedClones"), frameIndex, client, plannedBits, &fragmentIndex);
};
auto c_key = commands.flush();
while (c_key != nullptr)
{
auto to_run = c_key->get(&sync::SyncCommand::commandKey);
c_key = c_key->next;
to_run->callback(scs);
syncPool.destruct(to_run);
}
scs.flushBuffer(true);
scs.Reset();
}
#ifdef STATE_FIVE
static auto GetTrain(fx::ServerGameState* sgs, uint32_t objectId) -> fx::sync::SyncEntityPtr
{
if (objectId != 0)
{
auto entity = sgs->GetEntity(0, objectId);
if (entity && entity->type == sync::NetObjEntityType::Train && entity->syncTree)
{
return entity;
}
}
return {};
};
static auto GetNextTrain(fx::ServerGameState* sgs, const fx::sync::SyncEntityPtr& entity) -> fx::sync::SyncEntityPtr
{
if (auto trainState = entity->syncTree->GetTrainState())
{
return GetTrain(sgs, trainState->linkedToBackwardId);
}
return {};
};
#endif
void ServerGameState::Tick(fx::ServerInstanceBase* instance)
{
// #TOOD1SBIG: limit tick rate divisor somewhat more sanely (currently it's 'only' 12.5ms as tick rate was upped from 30fps to 50fps)
static uint32_t ticks = 0;
ticks++;
int tickMul = 1;
auto gs = m_instance->GetComponent<fx::GameServer>();
if (!gs->UseAccurateSends())
{
tickMul = 2;
}
if ((ticks % (3 * tickMul)) != 1)
{
return;
}
if (g_oneSyncARQ->GetValue())
{
m_syncStyle = SyncStyle::ARQ;
}
else
{
m_syncStyle = SyncStyle::NAK;
}
// approximate amount of ticks per second, 120 is svSync from GameServer.cpp
int effectiveTicksPerSecond = (120 / (3 * tickMul));
UpdateWorldGrid(instance);
UpdateEntities();
fwRefContainer<ServerEventComponent> sec = m_instance->GetComponent<ServerEventComponent>();
fwRefContainer<fx::ResourceManager> resMan = m_instance->GetComponent<fx::ResourceManager>();
fwRefContainer<fx::ResourceEventManagerComponent> evMan = resMan->GetComponent<fx::ResourceEventManagerComponent>();
// cache entities so we don't have to iterate the concurrent_map for each client
static std::tuple<
fx::sync::SyncEntityPtr,
glm::vec3,
sync::CVehicleGameStateNodeData*,
fx::ClientWeakPtr
> relevantEntities[MaxObjectId + 1];
int maxValidEntity = 0;
{
std::unique_lock _(m_entityListMutex);
for (auto entityIt = m_entityList.begin(), entityEnd = m_entityList.end(); entityIt != entityEnd;)
{
auto entity = *entityIt;
auto entityItOld = entityIt;
++entityIt;
entity->frameIndex = m_frameIndex;
if (!entity->syncTree)
{
continue;
}
// if entity relevant to nobody
{
std::lock_guard _(entity->guidMutex);
if (entity->relevantTo.none())
{
// entity was requested as delete, nobody knows of it anymore: finalize
if (entity->deleting)
{
FinalizeClone({}, entity, entity->handle, 0, "Requested deletion");
continue;
}
// it's a client-owned entity, let's check for a few things
else if (entity->IsOwnedByClientScript())
{
// is the original owner offline?
if (entity->firstOwnerDropped)
{
// we can delete
FinalizeClone({}, entity, entity->handle, 0, "First owner dropped");
continue;
}
}
// it's a script-less entity, we can collect it.
else if (!entity->IsOwnedByScript() && (entity->type != sync::NetObjEntityType::Player || !entity->GetClient()))
{
FinalizeClone({}, entity, entity->handle, 0, "Regular entity GC");
continue;
}
}
}
float position[3];
entity->syncTree->GetPosition(position);
glm::vec3 entityPosition(position[0], position[1], position[2]);
GS_LOG("found relevant entity %d for %d clients with position (%f, %f, %f)\n", entity->handle, entity->relevantTo.count(), entityPosition.x, entityPosition.y, entityPosition.z);
sync::CVehicleGameStateNodeData* vehicleData = nullptr;
if (entity->type == sync::NetObjEntityType::Automobile ||
entity->type == sync::NetObjEntityType::Bike ||
entity->type == sync::NetObjEntityType::Boat ||
entity->type == sync::NetObjEntityType::Heli ||
entity->type == sync::NetObjEntityType::Plane ||
entity->type == sync::NetObjEntityType::Submarine ||
entity->type == sync::NetObjEntityType::Trailer ||
#ifdef STATE_RDR3
entity->type == sync::NetObjEntityType::DraftVeh ||
#endif
entity->type == sync::NetObjEntityType::Train)
{
vehicleData = entity->syncTree->GetVehicleGameState();
}
relevantEntities[maxValidEntity] = { entity, entityPosition, vehicleData, entity->GetClient() };
maxValidEntity++;
}
}
auto creg = instance->GetComponent<fx::ClientRegistry>();
int initSlot = ((fx::IsBigMode()) ? MAX_CLIENTS : 129) - 1;
static int lastUpdateSlot = initSlot;
int iterations = 0;
int slot = lastUpdateSlot;
while (iterations < ((fx::IsBigMode() ? 8 : 16) * tickMul))
{
iterations++;
fx::ClientSharedPtr client;
while (!client)
{
client = creg->GetClientBySlotID(slot);
slot--;
if (slot < 0)
{
slot = initSlot;
}
if (slot == lastUpdateSlot)
{
break;
}
}
if (!client)
{
break;
}
auto clientDataUnlocked = GetClientDataUnlocked(this, client);