-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathClientThread.cpp
More file actions
1558 lines (1317 loc) · 54.5 KB
/
Copy pathClientThread.cpp
File metadata and controls
1558 lines (1317 loc) · 54.5 KB
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
/*=====================================================================
ClientThread.cpp
----------------
Copyright Glare Technologies Limited 2024 -
=====================================================================*/
#include "ClientThread.h"
#include "ClientSenderThread.h"
#include "WorldState.h"
#include "ThreadMessages.h"
#include "../shared/Protocol.h"
#include "../shared/ProtocolStructs.h"
#include "../shared/Parcel.h"
#include "../shared/WorldDetails.h"
#include <networking/MySocket.h>
#include <networking/TLSSocket.h>
#include <networking/Networking.h>
#include <maths/vec3.h>
#include <utils/SocketBufferOutStream.h>
#include <utils/Exception.h>
#include <utils/StringUtils.h>
#include <utils/PlatformUtils.h>
#include <utils/ConPrint.h>
#include <utils/Clock.h>
#include <utils/FastPoolAllocator.h>
#include <utils/Timer.h>
#include <utils/BufferViewInStream.h>
#include <zstd.h>
#if EMSCRIPTEN
#include <networking/EmscriptenWebSocket.h>
#endif
#include <tracy/Tracy.hpp>
static const size_t MAX_STRING_LEN = 10000;
ClientThread::ClientThread(ThreadSafeQueue<Reference<ThreadMessage> >* out_msg_queue_, const std::string& hostname_, int port_,
const std::string& initial_world_name_, struct tls_config* config_, const Reference<glare::FastPoolAllocator>& world_ob_pool_allocator_, Reference<WorldState> world_state_)
: out_msg_queue(out_msg_queue_),
hostname(hostname_),
port(port_),
initial_world_name(initial_world_name_),
config(config_),
world_ob_pool_allocator(world_ob_pool_allocator_),
send_data_to_socket(false),
dstream(nullptr),
world_state(world_state_)
{
#if !defined(EMSCRIPTEN)
MySocketRef mysocket = new MySocket();
mysocket->setUseNetworkByteOrder(false);
socket = mysocket;
#endif
dstream = ZSTD_createDStream();
if(!dstream)
throw glare::Exception("ZSTD_createDStream failed.");
}
ClientThread::~ClientThread()
{
if(dstream)
ZSTD_freeDStream(dstream);
}
void ClientThread::kill()
{
#if EMSCRIPTEN
if(socket.nonNull())
socket->startGracefulShutdown();
#endif
client_sender_thread_manager.killThreadsNonBlocking();
should_die = glare::atomic_int(1);
event_fd.notify(); // Make the blocking readable call stop.
}
// This executes in the ClientThread context.
// We call ungracefulShutdown() on the socket. This results in any current blocking call returning with WSAEINTR ('blocking operation was interrupted by a call to WSACancelBlockingCall')
#if defined(_WIN32)
static void asyncProcedure(uint64 data)
{
ClientThread* client_thread = (ClientThread*)data;
if(client_thread->socket.nonNull())
client_thread->socket->ungracefulShutdown();
client_thread->decRefCount();
}
#endif
void ClientThread::killConnection()
{
#if defined(_WIN32)
this->incRefCount();
QueueUserAPC(asyncProcedure, this->getHandle(), /*data=*/(ULONG_PTR)this);
#else
if(socket.nonNull())
socket->ungracefulShutdown();
#endif
}
WorldObjectRef ClientThread::allocWorldObject()
{
glare::FastPoolAllocator::AllocResult alloc_res = this->world_ob_pool_allocator->alloc();
WorldObject* ob_ptr = new (alloc_res.ptr) WorldObject(); // construct with placement new
ob_ptr->allocator = this->world_ob_pool_allocator.ptr();
ob_ptr->allocation_index = alloc_res.index;
return ob_ptr;
}
static void decompressWithZstdTo(const void* src, size_t src_len, glare::AllocatorVector<unsigned char, 16>& decompressed_buf_out)
{
const uint64 decompressed_size = ZSTD_getFrameContentSize(src, src_len);
if(decompressed_size == ZSTD_CONTENTSIZE_UNKNOWN || decompressed_size == ZSTD_CONTENTSIZE_ERROR)
throw glare::Exception("Failed to get decompressed_size");
decompressed_buf_out.resizeNoCopy(decompressed_size);
const size_t res = ZSTD_decompress(/*dest=*/decompressed_buf_out.data(), /*dest capacity =*/decompressed_buf_out.size(), /*source=*/src, /*compressed size=*/src_len);
if(ZSTD_isError(res))
throw glare::Exception("Decompression of buffer failed: " + std::string(ZSTD_getErrorName(res)));
if(res < decompressed_size)
throw glare::Exception("Decompression of buffer failed: not enough bytes in result");
}
void ClientThread::handleObjectInitialSend(RandomAccessInStream& msg_stream)
{
// NOTE: currently same code/semantics as ObjectCreated
//conPrint("ObjectInitialSend");
const UID object_uid = readUIDFromStream(msg_stream);
// Read from stream
WorldObjectRef ob = allocWorldObject();
ob->uid = object_uid;
readWorldObjectFromNetworkStreamGivenUID(msg_stream, *ob);
if(!isFinite(ob->angle))
ob->angle = 0;
if(!ob->axis.isFinite())
ob->axis = Vec3f(1,0,0);
ob->state = WorldObject::State_InitialSend;
ob->from_remote_other_dirty = true;
ob->setTransformAndHistory(ob->pos, ob->axis, ob->angle);
// TEMP HACK: set a smaller max loading distance for CV features
const char* feature_prefix = "CryptoVoxels Feature, uuid: ";
if(hasPrefix(ob->content, feature_prefix))
ob->max_load_dist2 = Maths::square(100.f);
// Insert into world state.
{
::Lock lock(world_state->mutex);
// When a client moves and a new cell comes into proximity, a QueryObjects message is sent to the server.
// The server replies with ObjectInitialSend messages.
// This means that the client may already have the object inserted, when moving back into a cell previously in proximity.
// We want to make sure not to add the object twice or load it into the graphics engine twice.
const bool added = world_state->objects.insert(object_uid, ob);
if(added)
world_state->dirty_from_remote_objects.insert(ob);
}
}
void ClientThread::readAndHandleMessage(const uint32 peer_protocol_version)
{
ZoneScopedN("ClientThread::readAndHandleMessage"); // Tracy profiler
// Read msg type and length
uint32 msg_type_and_len[2];
const size_t msg_header_size_B = sizeof(uint32) * 2;
socket->readData(msg_type_and_len, msg_header_size_B);
const uint32 msg_type = msg_type_and_len[0];
const uint32 msg_len = msg_type_and_len[1]; // Total message length, including the message header.
// conPrint("ClientThread: Read message header: id: " + toString(msg_type) + ", len: " + toString(msg_len));
#ifdef TRACY_ENABLE
const std::string zone_text = "msg type: " + toString(msg_type) + ", len: " + toString(msg_len) + " B";
ZoneText(zone_text.c_str(), zone_text.size());
#endif
if(msg_len < msg_header_size_B)
throw glare::Exception("Invalid message size: " + toString(msg_len));
// Handle ObjectInitialSendCompressed specially since we do a streaming read and decompression of its body.
if(msg_type == Protocol::ObjectInitialSendCompressed)
{
// Do streaming decompression of objects
ZoneScopedN("ClientThread: handling ObjectInitialSendCompressed"); // Tracy profiler
Timer timer;
out_msg_queue->enqueue(new LogMessage("ClientThread: starting ObjectInitialSendCompressed handling..."));
if(msg_len < msg_header_size_B + sizeof(uint64)) // Message should contain decompressed_size uint64.
throw glare::Exception("Invalid message size: " + toString(msg_len));
const uint64 decompressed_size = socket->readUInt64();
const size_t compressed_size = msg_len - (msg_header_size_B + sizeof(uint64)); // Compressed data is the rest of the message after the header and decompressed size
if(decompressed_size > 300'000'000)
throw glare::Exception("ObjectInitialSendCompressed: decompressed_size is too large: " + toString(decompressed_size));
if(compressed_size > 100000000)
throw glare::Exception("ObjectInitialSendCompressed: compressed_size is too large: " + toString(compressed_size));
ZSTD_initDStream(dstream); // Call before new decompression operation using same DStream
js::Vector<uint8, 16> compressed_buffer(compressed_size);
js::Vector<uint8, 16> decompressed_buffer(decompressed_size);
ZSTD_outBuffer out_buffer;
out_buffer.dst = decompressed_buffer.data(); // start of output buffer
out_buffer.size = decompressed_size; // size of output buffer
out_buffer.pos = 0; // position where writing stopped. Will be updated. Necessarily 0 <= pos <= size
ZSTD_inBuffer in_buffer;
in_buffer.src = compressed_buffer.data(); // start of input buffer
in_buffer.size = 0; // size of input buffer
in_buffer.pos = 0; // position where reading stopped. Will be updated. Necessarily 0 <= pos <= size
size_t next_ob_send_msg_start_i = 0; // Byte index in decompressed_buffer where the next ObjectInitialSend message will start.
size_t num_obs_decoded = 0;
const size_t max_read_chunk_size = 32768; // max number of bytes to read per socket read call. The first zstd decoded data arrives after ~= 32768 input bytes, so no point reading much smaller amounts.
for(size_t read_i=0; read_i<compressed_size; read_i += max_read_chunk_size)
{
// Read some data from network to compressed_buffer
const size_t read_chunk_end = myMin(read_i + max_read_chunk_size, compressed_size);
const size_t read_chunk_actual_size = read_chunk_end - read_i;
socket->readData(/*dest buf=*/compressed_buffer.data() + read_i, /*num bytes=*/read_chunk_actual_size);
in_buffer.size = read_chunk_end;
// Do some decompression
size_t res = ZSTD_decompressStream(dstream, &out_buffer, &in_buffer);
if(ZSTD_isError(res))
throw glare::Exception("Error from ZSTD_decompressStream(): " + std::string(ZSTD_getErrorName(res)));
if(read_chunk_end == compressed_size) // If we have read all data from socket into compressed_buffer, make sure decompression is finished.
{
// We may need to call ZSTD_decompressStream one or more times to flush remaining data. See https://facebook.github.io/zstd/zstd_manual.html#Chapter9
int max_num_flush_iters = 1024;
int iter = 0;
while(out_buffer.pos < out_buffer.size)
{
res = ZSTD_decompressStream(dstream, &out_buffer, &in_buffer);
if(ZSTD_isError(res))
throw glare::Exception("Error from ZSTD_decompressStream(): " + std::string(ZSTD_getErrorName(res)));
iter++;
runtimeCheck(iter < max_num_flush_iters); // Avoid infinite loops on zstd failure or incorrect API usage.
}
}
// conPrint("Read " + toString(read_chunk_end) + " / " + toString(compressed_size) + " B of compressed data, decoded " + toString(num_obs_decoded) + " obs");
// Process any complete ObjectInitialSend messages in our decompressed data
while(1)
{
if((out_buffer.pos - next_ob_send_msg_start_i) >= sizeof(uint32) * 2) // If we have read at least the header of the next ObjectInitialSend message:
{
uint32 sub_msg_header[2];
std::memcpy(sub_msg_header, decompressed_buffer.data() + next_ob_send_msg_start_i, sizeof(uint32) * 2);
if(sub_msg_header[0] != Protocol::ObjectInitialSend)
throw glare::Exception("invalid sub-msg in ObjectInitialSendCompressed");
const size_t sub_msg_len = sub_msg_header[1];
if((sub_msg_len < msg_header_size_B) || (sub_msg_len > 1000000))
throw glare::Exception("Invalid sub-message size: " + toString(sub_msg_len));
if((next_ob_send_msg_start_i + sub_msg_len) <= out_buffer.pos) // If we have decompressed this entire sub-message:
{
// Process it
BufferViewInStream sub_msg_buffer_view(ArrayRef<uint8>(decompressed_buffer.data() + next_ob_send_msg_start_i, sub_msg_len));
sub_msg_buffer_view.advanceReadIndex(sizeof(uint32) * 2); // Skip header
handleObjectInitialSend(sub_msg_buffer_view);
num_obs_decoded++;
next_ob_send_msg_start_i += sub_msg_len;
}
else
break;
}
else
break;
}
}
// conPrint("ObjectInitialSendCompressed: Final num objects decoded: " + toString(num_obs_decoded));
out_msg_queue->enqueue(new LogMessage("ClientThread ObjectInitialSendCompressed handling: read " + toString(num_obs_decoded) +
" objects from " + uInt64ToStringCommaSeparated(compressed_size) + " B (compressed), " +
uInt64ToStringCommaSeparated(decompressed_size) + " B (decompressed) in " + timer.elapsedStringNPlaces(3)));
return;
}
if(msg_len > 1000000)
throw glare::Exception("Invalid message size: " + toString(msg_len));
// Read entire message
msg_buffer.buf.resizeNoCopy(msg_len);
msg_buffer.read_index = sizeof(uint32) * 2;
socket->readData(msg_buffer.buf.data() + sizeof(uint32) * 2, msg_len - sizeof(uint32) * 2); // Read rest of message, store in msg_buffer.
switch(msg_type)
{
case Protocol::AllObjectsSent:
{
// This message has no payload.
break;
}
case Protocol::AudioStreamToServerStarted:
{
// conPrint("ClientThread: received Protocol::AudioStreamToServerStarted");
const UID avatar_uid = readUIDFromStream(msg_buffer);
const uint32 sampling_rate = msg_buffer.readUInt32();
const uint32 flags = msg_buffer.readUInt32();
const uint32 stream_id = msg_buffer.readUInt32();
out_msg_queue->enqueue(new RemoteClientAudioStreamToServerStarted(avatar_uid, sampling_rate, flags, stream_id)); // Inform MainWindow
break;
}
case Protocol::AudioStreamToServerEnded:
{
// conPrint("ClientThread: received Protocol::AudioStreamToServerEnded");
const UID avatar_uid = readUIDFromStream(msg_buffer);
out_msg_queue->enqueue(new RemoteClientAudioStreamToServerEnded(avatar_uid)); // Inform MainWindow
break;
}
case Protocol::AvatarTransformUpdate:
{
//conPrint("AvatarTransformUpdate");
const UID avatar_uid = readUIDFromStream(msg_buffer);
const Vec3d pos = readVec3FromStream<double>(msg_buffer);
const Vec3f rotation = readVec3FromStream<float>(msg_buffer);
const uint32 anim_state_and_input_bitflags = msg_buffer.readUInt32();
// Look up existing avatar in world state
{
Lock lock(world_state->mutex);
auto res = world_state->avatars.find(avatar_uid);
if(res != world_state->avatars.end())
{
Avatar* avatar = res->second.getPointer();
avatar->pos = pos;
avatar->rotation = rotation;
avatar->anim_state = anim_state_and_input_bitflags & 0xFF;
avatar->last_physics_input_bitflags = anim_state_and_input_bitflags >> 16;
avatar->transform_dirty = true;
//conPrint("updated avatar transform");
avatar->pos_snapshots [Maths::intMod(avatar->next_snapshot_i, Avatar::HISTORY_BUF_SIZE)] = pos;
avatar->rotation_snapshots [Maths::intMod(avatar->next_snapshot_i, Avatar::HISTORY_BUF_SIZE)] = rotation;
avatar->snapshot_times [Maths::intMod(avatar->next_snapshot_i, Avatar::HISTORY_BUF_SIZE)] = Clock::getTimeSinceInit();
//avatar->last_snapshot_time = Clock::getCurTimeRealSec();
avatar->next_snapshot_i++;
}
}
break;
}
case Protocol::AvatarFullUpdate:
{
// conPrint("received Protocol::AvatarFullUpdate");
const UID avatar_uid = readUIDFromStream(msg_buffer);
Avatar temp_avatar;
readAvatarFromNetworkStreamGivenUID(msg_buffer, temp_avatar); // Read message data before grabbing lock
// Look up existing avatar in world state
{
Lock lock(world_state->mutex);
auto res = world_state->avatars.find(avatar_uid);
if(res != world_state->avatars.end())
{
Avatar* avatar = res->second.getPointer();
avatar->copyNetworkStateFrom(temp_avatar);
avatar->generatePseudoRandomNameColour();
avatar->other_dirty = true;
}
}
break;
}
case Protocol::AvatarIsHere:
{
// conPrint("received Protocol::AvatarIsHere");
const UID avatar_uid = readUIDFromStream(msg_buffer);
Avatar temp_avatar;
readAvatarFromNetworkStreamGivenUID(msg_buffer, temp_avatar); // Read message data before grabbing lock
// Look up existing avatar in world state
{
::Lock lock(world_state->mutex);
auto res = world_state->avatars.find(avatar_uid);
if(res == world_state->avatars.end())
{
// Avatar for UID not already created, create it now.
AvatarRef avatar = new Avatar();
avatar->uid = avatar_uid;
avatar->our_avatar = this->client_avatar_uid == avatar_uid;
avatar->copyNetworkStateFrom(temp_avatar);
avatar->state = Avatar::State_JustCreated;
avatar->other_dirty = true;
avatar->generatePseudoRandomNameColour();
world_state->avatars.insert(std::make_pair(avatar_uid, avatar));
avatar->setTransformAndHistory(temp_avatar.pos, temp_avatar.rotation);
out_msg_queue->enqueue(new AvatarIsHereMessage(avatar_uid)); // Inform MainWindow
}
}
break;
}
case Protocol::AvatarCreated:
{
// conPrint("received Protocol::AvatarCreated");
const UID avatar_uid = readUIDFromStream(msg_buffer);
Avatar temp_avatar;
readAvatarFromNetworkStreamGivenUID(msg_buffer, temp_avatar); // Read message data before grabbing lock
// Look up existing avatar in world state
{
::Lock lock(world_state->mutex);
auto res = world_state->avatars.find(avatar_uid);
if(res == world_state->avatars.end())
{
// Avatar for UID not already created, create it now.
AvatarRef avatar = new Avatar();
avatar->uid = avatar_uid;
avatar->our_avatar = this->client_avatar_uid == avatar_uid;
avatar->copyNetworkStateFrom(temp_avatar);
avatar->state = Avatar::State_JustCreated;
avatar->other_dirty = true;
avatar->generatePseudoRandomNameColour();
world_state->avatars.insert(std::make_pair(avatar_uid, avatar));
avatar->setTransformAndHistory(temp_avatar.pos, temp_avatar.rotation);
out_msg_queue->enqueue(new AvatarCreatedMessage(avatar_uid)); // Inform MainWindow
}
}
break;
}
case Protocol::AvatarDestroyed:
{
// conPrint("AvatarDestroyed");
const UID avatar_uid = readUIDFromStream(msg_buffer);
// Mark avatar as dead
{
Lock lock(world_state->mutex);
auto res = world_state->avatars.find(avatar_uid);
if(res != world_state->avatars.end())
{
Avatar* avatar = res->second.getPointer();
avatar->state = Avatar::State_Dead;
avatar->other_dirty = true;
}
}
break;
}
case Protocol::AvatarPerformGesture:
{
//conPrint("AvatarPerformGesture");
const UID avatar_uid = readUIDFromStream(msg_buffer);
const std::string gesture_name = msg_buffer.readStringLengthFirst(10000);
URLString gesture_URL;
if(!msg_buffer.endOfStream())
gesture_URL = URLString(msg_buffer.readStringLengthFirst(10000));
uint32 flags = 0;
if(!msg_buffer.endOfStream())
flags = msg_buffer.readUInt32();
double start_global_time = 0;
if(!msg_buffer.endOfStream())
start_global_time = msg_buffer.readDouble();
//conPrint("Received AvatarPerformGesture: '" + gesture_name + "'");
Reference<AvatarPerformGestureMessage> gesture_msg = new AvatarPerformGestureMessage(avatar_uid, gesture_name);
gesture_msg->gesture_URL = gesture_URL;
gesture_msg->flags = flags;
gesture_msg->start_global_time = start_global_time;
out_msg_queue->enqueue(gesture_msg);
break;
}
case Protocol::AvatarStopGesture:
{
//conPrint("AvatarStopGesture");
const UID avatar_uid = readUIDFromStream(msg_buffer);
out_msg_queue->enqueue(new AvatarStopGestureMessage(avatar_uid));
break;
}
case Protocol::AvatarEnteredVehicle:
{
// conPrint("AvatarEnteredVehicle");
const UID avatar_uid = readUIDFromStream(msg_buffer);
const UID vehicle_ob_uid = readUIDFromStream(msg_buffer);
const uint32 seat_index = msg_buffer.readUInt32();
/*const uint32 flags =*/ msg_buffer.readUInt32();
if(avatar_uid != this->client_avatar_uid) // Discard AvatarEnteredVehicle messages we sent.
{
Lock lock(world_state->mutex);
auto res = world_state->avatars.find(avatar_uid);
if(res != world_state->avatars.end())
{
Avatar* avatar = res->second.getPointer();
auto res2 = world_state->objects.find(vehicle_ob_uid);
if(res2 != world_state->objects.end())
{
if(avatar->entered_vehicle != res2.getValue()) // If this avatar is not already in the vehicle (AvatarEnteredVehicle messages are sent repeatedly)
{
avatar->entered_vehicle = res2.getValue();
avatar->vehicle_seat_index = seat_index;
avatar->pending_vehicle_transition = Avatar::EnterVehicle;
}
}
}
}
break;
}
case Protocol::AvatarExitedVehicle:
{
// conPrint("AvatarExitedVehicle");
const UID avatar_uid = readUIDFromStream(msg_buffer);
if(avatar_uid != this->client_avatar_uid) // Discard AvatarExitedVehicle messages we sent.
{
Lock lock(world_state->mutex);
auto res = world_state->avatars.find(avatar_uid);
if(res != world_state->avatars.end())
{
Avatar* avatar = res->second.getPointer();
avatar->pending_vehicle_transition = Avatar::ExitVehicle;
}
}
break;
}
case Protocol::AvatarSatOnSeat:
{
// conPrint("AvatarSatOnSeat");
const UID avatar_uid = readUIDFromStream(msg_buffer);
const UID seat_ob_uid = readUIDFromStream(msg_buffer);
if(avatar_uid != this->client_avatar_uid) // Discard AvatarSatOnSeat messages we sent.
{
Lock lock(world_state->mutex);
auto res = world_state->avatars.find(avatar_uid);
if(res != world_state->avatars.end())
{
Avatar* avatar = res->second.getPointer();
avatar->pending_seat_uid = seat_ob_uid;
avatar->pending_seat_transition = Avatar::SitOnSeat;
}
}
break;
}
case Protocol::AvatarGotUpFromSeat:
{
// conPrint("AvatarGotUpFromSeat");
const UID avatar_uid = readUIDFromStream(msg_buffer);
if(avatar_uid != this->client_avatar_uid) // Discard AvatarGotUpFromSeat messages we sent.
{
Lock lock(world_state->mutex);
auto res = world_state->avatars.find(avatar_uid);
if(res != world_state->avatars.end())
{
Avatar* avatar = res->second.getPointer();
avatar->pending_seat_transition = Avatar::GetUpFromSeat;
}
}
break;
}
case Protocol::ObjectTransformUpdate:
{
//conPrint("ObjectTransformUpdate");
const UID object_uid = readUIDFromStream(msg_buffer);
const Vec3d pos = readVec3FromStream<double>(msg_buffer);
const Vec3f axis = readVec3FromStream<float>(msg_buffer);
const float angle = msg_buffer.readFloat();
const Vec3f scale = readVec3FromStream<float>(msg_buffer);
// Read transform_update_avatar_uid, added during protocol version 36.
uint32 transform_update_avatar_uid = std::numeric_limits<uint32>::max();
if(!msg_buffer.endOfStream())
transform_update_avatar_uid = msg_buffer.readUInt32();
// conPrint("ClientThread: received ObjectTransformUpdate, transform_update_avatar_uid: " + toString(transform_update_avatar_uid));
if(transform_update_avatar_uid != (uint32)this->client_avatar_uid.value()) // Discard ObjectTransformUpdate messages we sent.
{
// Look up existing object in world state
Lock lock(world_state->mutex);
auto res = world_state->objects.find(object_uid);
if(res != world_state->objects.end())
{
WorldObject* ob = res.getValue().ptr();
#if GUI_CLIENT
if(!ob->is_selected) // Don't update the selected object - we will consider the local client control authoritative while the object is selected.
#endif
{
//conPrint("ObjectTransformUpdate: setting ob pos to " + pos.toString());
#if GUI_CLIENT
//ob->last_pos = ob->pos;
#endif
ob->pos = pos;
ob->axis = axis;
ob->angle = angle;
ob->scale = scale;
// If we had physics snapshots, reset snapshots.
if(ob->snapshots_are_physics_snapshots)
{
// conPrint("Resetting snapshots.");
ob->next_insertable_snapshot_i = 0;
ob->next_snapshot_i = 0;
}
ob->snapshots_are_physics_snapshots = false;
ob->snapshots[ob->next_snapshot_i % (uint32)WorldObject::HISTORY_BUF_SIZE] =
WorldObject::Snapshot({pos.toVec4fPoint(), Quatf::fromAxisAndAngle(normalise(axis), angle), /*linear vel=*/Vec4f(0.f), /*angular_vel=*/Vec4f(0.f), /*client time=*/0.0, /*local time=*/Clock::getTimeSinceInit()});
ob->next_snapshot_i++;
ob->from_remote_transform_dirty = true;
world_state->dirty_from_remote_objects.insert(ob);
//conPrint("updated object transform");
}
}
}
else
{
// conPrint("\tDiscarding ObjectTransformUpdate message, as we sent it.");
}
break;
}
case Protocol::SummonObject:
{
// conPrint("ClientThread: received SummonObject message.");
SummonObjectMessageServerToClient summon_msg;
msg_buffer.readData(&summon_msg, sizeof(SummonObjectMessageServerToClient));
if(summon_msg.transform_update_avatar_uid != (uint32)this->client_avatar_uid.value()) // Discard SummonObject messages we sent.
{
// Look up existing object in world state
Lock lock(world_state->mutex);
auto res = world_state->objects.find(summon_msg.object_uid);
if(res != world_state->objects.end())
{
WorldObject* ob = res.getValue().ptr();
#if GUI_CLIENT
if(!ob->is_selected) // Don't update the selected object - we will consider the local client control authoritative while the object is selected.
#endif
{
ob->setTransformAndHistory(summon_msg.pos, summon_msg.axis, summon_msg.angle);
ob->transformChanged();
ob->next_insertable_snapshot_i = 0;
ob->next_snapshot_i = 0;
ob->snapshots_are_physics_snapshots = false;
ob->from_remote_summoned_dirty = true;
world_state->dirty_from_remote_objects.insert(ob);
}
}
}
break;
}
case Protocol::ObjectPhysicsTransformUpdate:
{
const UID object_uid = readUIDFromStream(msg_buffer);
const Vec3d pos = readVec3FromStream<double>(msg_buffer);
Quatf rot;
msg_buffer.readData(rot.v.x, sizeof(float) * 4);
Vec4f linear_vel(0.f);
msg_buffer.readData(linear_vel.x, sizeof(float) * 3);
Vec4f angular_vel(0.f);
msg_buffer.readData(angular_vel.x, sizeof(float) * 3);
const uint32 transform_update_avatar_uid = msg_buffer.readUInt32();
const double transform_client_time = msg_buffer.readDouble();
//conPrint("ClientThread: received ObjectPhysicsTransformUpdate, transform_update_avatar_uid: " + toString(transform_update_avatar_uid));
//conPrint("transform_client_time: " + toString(transform_client_time) + ", cur global time: " + toString(world_state->getCurrentGlobalTime()));
if(transform_update_avatar_uid != (uint32)this->client_avatar_uid.value()) // Discard ObjectPhysicsTransformUpdate messages we sent.
{
// Look up existing object in world state
Lock lock(world_state->mutex);
auto res = world_state->objects.find(object_uid);
if(res != world_state->objects.end())
{
WorldObject* ob = res.getValue().ptr();
if(ob->physics_owner_id == transform_update_avatar_uid) // Only process messages that are from the physics owner of this object, discard others.
{
// If we had non-physics snapshots, reset snapshots.
if(!ob->snapshots_are_physics_snapshots)
{
// conPrint("Resetting snapshots.");
ob->next_insertable_snapshot_i = 0;
ob->next_snapshot_i = 0;
}
ob->snapshots_are_physics_snapshots = true;
const double local_time = Clock::getTimeSinceInit();
ob->snapshots[ob->next_snapshot_i % (uint32)WorldObject::HISTORY_BUF_SIZE] = WorldObject::Snapshot({pos.toVec4fPoint(), rot, linear_vel, angular_vel, transform_client_time, local_time});
ob->next_snapshot_i++;
// conPrint("ClientThread: Added snapshot " + toString(ob->next_snapshot_i));
//NEW: Compute transmission_time_offset: An estimate of local_clock_time - sending_clock_time.
// TODO: Handle a different client taking over sending messages.
/*if(ob->transmission_time_offset == std::numeric_limits<double>::infinity())
{
ob->transmission_time_offset = Clock::getTimeSinceInit() - last_transform_client_time;
conPrint("Storing new ob->transmission_time_offset: " + doubleToString(ob->transmission_time_offset));
}*/
ob->from_remote_physics_transform_dirty = true;
world_state->dirty_from_remote_objects.insert(ob);
}
else
{
// conPrint("\tDiscarding ObjectPhysicsTransformUpdate message as not from physics owner of object.");
}
}
}
else
{
// conPrint("\tDiscarding ObjectPhysicsTransformUpdate message as we sent it.");
}
break;
}
case Protocol::ObjectFullUpdate:
{
//conPrint("ObjectFullUpdate");
const UID object_uid = readUIDFromStream(msg_buffer);
// Look up existing object in world state
{
bool read = false;
Lock lock(world_state->mutex);
auto res = world_state->objects.find(object_uid);
if(res != world_state->objects.end())
{
WorldObject* ob = res.getValue().ptr();
#if GUI_CLIENT
if(!ob->is_selected) // Don't update the selected object - we will consider the local client control authoritative while the object is selected.
#endif
{
readWorldObjectFromNetworkStreamGivenUID(msg_buffer, *ob);
read = true;
ob->from_remote_other_dirty = true;
world_state->dirty_from_remote_objects.insert(ob);
}
}
// Make sure we have read the whole object from the network stream
if(!read)
{
WorldObject dummy;
readWorldObjectFromNetworkStreamGivenUID(msg_buffer, dummy);
}
}
break;
}
case Protocol::ObjectLightmapURLChanged:
{
//conPrint("ObjectLightmapURLChanged");
const UID object_uid = readUIDFromStream(msg_buffer);
const std::string new_lightmap_url = msg_buffer.readStringLengthFirst(WorldObject::MAX_URL_SIZE);
//conPrint("new_lightmap_url: " + new_lightmap_url);
// Look up existing object in world state
{
Lock lock(world_state->mutex);
auto res = world_state->objects.find(object_uid);
if(res != world_state->objects.end())
{
WorldObject* ob = res.getValue().ptr();
ob->lightmap_url = new_lightmap_url;
ob->from_remote_lightmap_url_dirty = true;
world_state->dirty_from_remote_objects.insert(ob);
}
}
break;
}
case Protocol::ObjectModelURLChanged:
{
//conPrint("ObjectModelURLChanged");
const UID object_uid = readUIDFromStream(msg_buffer);
const std::string new_model_url = msg_buffer.readStringLengthFirst(WorldObject::MAX_URL_SIZE);
//conPrint("new_model_url: " + new_model_url);
// Look up existing object in world state
{
Lock lock(world_state->mutex);
auto res = world_state->objects.find(object_uid);
if(res != world_state->objects.end())
{
WorldObject* ob = res.getValue().ptr();
ob->model_url = new_model_url;
ob->from_remote_model_url_dirty = true;
world_state->dirty_from_remote_objects.insert(ob);
}
}
break;
}
case Protocol::ObjectContentChanged:
{
//conPrint("ObjectContentChanged");
const UID object_uid = readUIDFromStream(msg_buffer);
const std::string new_content = msg_buffer.readStringLengthFirst(WorldObject::MAX_CONTENT_SIZE);
//conPrint("new_model_url: " + new_model_url);
// Look up existing object in world state
{
Lock lock(world_state->mutex);
auto res = world_state->objects.find(object_uid);
if(res != world_state->objects.end())
{
WorldObject* ob = res.getValue().ptr();
ob->content = new_content;
ob->from_remote_content_dirty = true;
world_state->dirty_from_remote_objects.insert(ob);
}
}
break;
}
case Protocol::ObjectFlagsChanged:
{
const UID object_uid = readUIDFromStream(msg_buffer);
const uint32 flags = msg_buffer.readUInt32();
//conPrint("ObjectFlagsChanged: read flags " + toString(flags) + " for ob with UID " + object_uid.toString());
// Look up existing object in world state
{
Lock lock(world_state->mutex);
auto res = world_state->objects.find(object_uid);
if(res != world_state->objects.end())
{
WorldObject* ob = res.getValue().ptr();
ob->flags = flags; // Copy flags
ob->from_remote_other_dirty = true;
world_state->dirty_from_remote_objects.insert(ob);
}
}
break;
}
case Protocol::VideoWatchPartyState:
{
const UID object_uid = readUIDFromStream(msg_buffer);
const bool active = msg_buffer.readUInt32() != 0;
const uint32 owner_user_id = msg_buffer.readUInt32();
const double start_global_time = msg_buffer.readDouble();
const double start_video_time = msg_buffer.readDouble();
bool is_playing = true;
try
{
is_playing = (msg_buffer.readUInt32() != 0); // Optional, for backward compatibility with older server packets.
}
catch(glare::Exception&)
{}
{
Lock lock(world_state->mutex);
auto res = world_state->objects.find(object_uid);
if(res != world_state->objects.end())
{
WorldObject* ob = res.getValue().ptr();
ob->video_watch_party_active = active;
ob->video_watch_party_owner_user_id = owner_user_id;
ob->video_watch_party_start_global_time = start_global_time;
ob->video_watch_party_start_video_time = start_video_time;
ob->video_watch_party_is_playing = is_playing;
ob->from_remote_video_watch_party_dirty = true;
world_state->dirty_from_remote_objects.insert(ob);
}
}
break;
}
case Protocol::ObjectPhysicsOwnershipTaken:
{
const UID object_uid = readUIDFromStream(msg_buffer);
const uint32 physics_owner_id = msg_buffer.readUInt32();
const double last_physics_ownership_change_global_time = msg_buffer.readDouble();
const uint32 flags = msg_buffer.readUInt32();
const bool renewal = BitUtils::isBitSet(flags, 0x1u); // See if flag bit is set which indicated this message is renewing ownership.
// conPrint("ClientThread: Received ObjectPhysicsOwnershipTaken, object_uid: " + object_uid.toString() + ", physics_owner_id: " + toString(physics_owner_id) + ", last_physics_ownership_change_global_time: " +
// toString(last_physics_ownership_change_global_time) + ", renewal: " + boolToString(renewal));
// Look up existing object in world state
{
Lock lock(world_state->mutex);
auto res = world_state->objects.find(object_uid);
if(res != world_state->objects.end())
{
WorldObject* ob = res.getValue().ptr();
if(last_physics_ownership_change_global_time > ob->last_physics_ownership_change_global_time)
{
ob->physics_owner_id = physics_owner_id;
ob->last_physics_ownership_change_global_time = last_physics_ownership_change_global_time;
ob->from_remote_physics_ownership_dirty = true;
world_state->dirty_from_remote_objects.insert(ob);
if(renewal)
{
if(ob->transmission_time_offset == 0) // If we haven't computed transmission_time_offset yet, because we received info about the object after another client became physics owner of it
// (e.g. we just connected to server)
ob->transmission_time_offset = world_state->getCurrentGlobalTime() - last_physics_ownership_change_global_time; // Compute it.
}
else
{
ob->transmission_time_offset = world_state->getCurrentGlobalTime() - last_physics_ownership_change_global_time;
// conPrint("Storing new ob->transmission_time_offset: " + doubleToString(ob->transmission_time_offset));
ob->next_insertable_snapshot_i = ob->next_snapshot_i; // Effectively remove queued snapshots.
}
}
}
}
break;
}
case Protocol::ObjectCreated:
{
//conPrint("ObjectCreated");
const UID object_uid = readUIDFromStream(msg_buffer);
// Read from network
WorldObjectRef ob = allocWorldObject();
ob->uid = object_uid;
readWorldObjectFromNetworkStreamGivenUID(msg_buffer, *ob);
ob->state = WorldObject::State_JustCreated;
ob->from_remote_other_dirty = true;
ob->setTransformAndHistory(ob->pos, ob->axis, ob->angle);