-
Notifications
You must be signed in to change notification settings - Fork 178
/
ActorManager.cpp
1649 lines (1437 loc) · 59 KB
/
ActorManager.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
/*
This source file is part of Rigs of Rods
Copyright 2005-2012 Pierre-Michel Ricordel
Copyright 2007-2012 Thomas Fischer
Copyright 2013-2020 Petr Ohlidal
For more information, see http://www.rigsofrods.org/
Rigs of Rods is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3, as
published by the Free Software Foundation.
Rigs of Rods 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 Rigs of Rods. If not, see <http://www.gnu.org/licenses/>.
*/
/// @file
/// @author Thomas Fischer (thomas{AT}thomasfischer{DOT}biz)
/// @date 24th of August 2009
#include "ActorManager.h"
#include "Application.h"
#include "Actor.h"
#include "CacheSystem.h"
#include "ContentManager.h"
#include "ChatSystem.h"
#include "Collisions.h"
#include "DashBoardManager.h"
#include "DynamicCollisions.h"
#include "EngineSim.h"
#include "GameContext.h"
#include "GfxScene.h"
#include "GUIManager.h"
#include "Console.h"
#include "GUI_TopMenubar.h"
#include "InputEngine.h"
#include "Language.h"
#include "MovableText.h"
#include "Network.h"
#include "PointColDetector.h"
#include "Replay.h"
#include "RigDef_Validator.h"
#include "ActorSpawner.h"
#include "ScriptEngine.h"
#include "SoundScriptManager.h"
#include "Terrain.h"
#include "ThreadPool.h"
#include "TuneupFileFormat.h"
#include "Utils.h"
#include "VehicleAI.h"
using namespace Ogre;
using namespace RoR;
static ActorInstanceID_t m_actor_counter = 1;
const ActorPtr ActorManager::ACTORPTR_NULL; // Dummy value to be returned as const reference.
ActorManager::ActorManager()
: m_dt_remainder(0.0f)
, m_forced_awake(false)
, m_physics_steps(2000)
, m_simulation_speed(1.0f)
{
// Create worker thread (used for physics calculations)
m_sim_thread_pool = std::unique_ptr<ThreadPool>(new ThreadPool(1));
}
ActorManager::~ActorManager()
{
this->SyncWithSimThread(); // Wait for sim task to finish
}
ActorPtr ActorManager::CreateNewActor(ActorSpawnRequest rq, RigDef::DocumentPtr def)
{
ActorPtr actor = new Actor(m_actor_counter++, static_cast<int>(m_actors.size()), def, rq);
if (App::mp_state->getEnum<MpState>() == MpState::CONNECTED && rq.asr_origin != ActorSpawnRequest::Origin::NETWORK)
{
actor->sendStreamSetup();
}
LOG(" == Spawning vehicle: " + def->name);
ActorSpawner spawner;
spawner.ConfigureSections(actor->m_section_config, def);
spawner.ConfigureAddonParts(actor->m_working_tuneup_def);
spawner.ConfigureAssetPacks(actor, def);
spawner.ProcessNewActor(actor, rq, def);
if (App::diag_actor_dump->getBool())
{
actor->WriteDiagnosticDump(actor->ar_filename + "_dump_raw.txt"); // Saves file to 'logs'
}
/* POST-PROCESSING */
actor->ar_initial_node_positions.resize(actor->ar_num_nodes);
actor->ar_initial_beam_defaults.resize(actor->ar_num_beams);
actor->ar_initial_node_masses.resize(actor->ar_num_nodes);
actor->UpdateBoundingBoxes(); // (records the unrotated dimensions for 'veh_aab_size')
// Apply spawn position & spawn rotation
for (int i = 0; i < actor->ar_num_nodes; i++)
{
actor->ar_nodes[i].AbsPosition = rq.asr_position + rq.asr_rotation * (actor->ar_nodes[i].AbsPosition - rq.asr_position);
actor->ar_nodes[i].RelPosition = actor->ar_nodes[i].AbsPosition - actor->ar_origin;
};
/* Place correctly */
if (spawner.GetMemoryRequirements().num_fixes == 0)
{
Ogre::Vector3 vehicle_position = rq.asr_position;
// check if over-sized
actor->UpdateBoundingBoxes();
vehicle_position.x += vehicle_position.x - actor->ar_bounding_box.getCenter().x;
vehicle_position.z += vehicle_position.z - actor->ar_bounding_box.getCenter().z;
float miny = 0.0f;
if (!actor->m_preloaded_with_terrain)
{
miny = vehicle_position.y;
}
if (rq.asr_spawnbox != nullptr)
{
miny = rq.asr_spawnbox->relo.y + rq.asr_spawnbox->center.y;
}
if (rq.asr_free_position)
actor->resetPosition(vehicle_position, true);
else
actor->resetPosition(vehicle_position.x, vehicle_position.z, true, miny);
if (rq.asr_spawnbox != nullptr)
{
bool inside = true;
for (int i = 0; i < actor->ar_num_nodes; i++)
inside = (inside && App::GetGameContext()->GetTerrain()->GetCollisions()->isInside(actor->ar_nodes[i].AbsPosition, rq.asr_spawnbox, 0.2f));
if (!inside)
{
Vector3 gpos = Vector3(vehicle_position.x, 0.0f, vehicle_position.z);
gpos -= rq.asr_rotation * Vector3((rq.asr_spawnbox->hi.x - rq.asr_spawnbox->lo.x + actor->ar_bounding_box.getMaximum().x - actor->ar_bounding_box.getMinimum().x) * 0.6f, 0.0f, 0.0f);
actor->resetPosition(gpos.x, gpos.z, true, miny);
}
}
}
else
{
actor->resetPosition(rq.asr_position, true);
}
actor->UpdateBoundingBoxes();
//compute final mass
actor->RecalculateNodeMasses(actor->m_dry_mass);
actor->ar_initial_total_mass = actor->m_total_mass;
for (int i = 0; i < actor->ar_num_nodes; i++)
{
actor->ar_initial_node_masses[i] = actor->ar_nodes[i].mass;
}
//setup default sounds
if (!actor->m_disable_default_sounds)
{
ActorSpawner::SetupDefaultSoundSources(actor);
}
//compute node connectivity graph
actor->calcNodeConnectivityGraph();
actor->UpdateBoundingBoxes();
actor->calculateAveragePosition();
// calculate minimum camera radius
actor->calculateAveragePosition();
for (int i = 0; i < actor->ar_num_nodes; i++)
{
Real dist = actor->ar_nodes[i].AbsPosition.squaredDistance(actor->m_avg_node_position);
if (dist > actor->m_min_camera_radius)
{
actor->m_min_camera_radius = dist;
}
}
actor->m_min_camera_radius = std::sqrt(actor->m_min_camera_radius) * 1.2f; // twenty percent buffer
// fix up submesh collision model
std::string subMeshGroundModelName = spawner.GetSubmeshGroundmodelName();
if (!subMeshGroundModelName.empty())
{
actor->ar_submesh_ground_model = App::GetGameContext()->GetTerrain()->GetCollisions()->getGroundModelByString(subMeshGroundModelName);
if (!actor->ar_submesh_ground_model)
{
actor->ar_submesh_ground_model = App::GetGameContext()->GetTerrain()->GetCollisions()->defaultgm;
}
}
// Set beam defaults
for (int i = 0; i < actor->ar_num_beams; i++)
{
actor->ar_beams[i].initial_beam_strength = actor->ar_beams[i].strength;
actor->ar_beams[i].default_beam_deform = actor->ar_beams[i].minmaxposnegstress;
actor->ar_initial_beam_defaults[i] = std::make_pair(actor->ar_beams[i].k, actor->ar_beams[i].d);
}
actor->m_spawn_rotation = actor->getRotation();
TRIGGER_EVENT_ASYNC(SE_GENERIC_NEW_TRUCK, actor->ar_instance_id);
actor->NotifyActorCameraChanged(); // setup sounds properly
// calculate the number of wheel nodes
actor->m_wheel_node_count = 0;
for (int i = 0; i < actor->ar_num_nodes; i++)
{
if (actor->ar_nodes[i].nd_tyre_node)
actor->m_wheel_node_count++;
}
// search m_net_first_wheel_node
actor->m_net_first_wheel_node = actor->ar_num_nodes;
for (int i = 0; i < actor->ar_num_nodes; i++)
{
if (actor->ar_nodes[i].nd_tyre_node || actor->ar_nodes[i].nd_rim_node)
{
actor->m_net_first_wheel_node = i;
break;
}
}
// Initialize visuals
actor->updateVisual();
actor->GetGfxActor()->SetDebugView((DebugViewType)rq.asr_debugview);
// perform full visual update only if the vehicle won't be immediately driven by player.
if (actor->isPreloadedWithTerrain() || // .tobj file - Spawned sleeping somewhere on terrain
rq.asr_origin == ActorSpawnRequest::Origin::CONFIG_FILE || // RoR.cfg or commandline - not entered by default
actor->ar_num_cinecams == 0) // Not intended for player-controlling
{
actor->GetGfxActor()->UpdateSimDataBuffer(); // Initial fill of sim data buffers
actor->GetGfxActor()->UpdateFlexbodies(); // Push tasks to threadpool
actor->GetGfxActor()->UpdateWheelVisuals(); // Push tasks to threadpool
actor->GetGfxActor()->UpdateCabMesh();
actor->GetGfxActor()->UpdateWingMeshes();
actor->GetGfxActor()->UpdateProps(0.f, false);
actor->GetGfxActor()->UpdateRods(); // beam visuals
actor->GetGfxActor()->FinishWheelUpdates(); // Sync tasks from threadpool
actor->GetGfxActor()->FinishFlexbodyTasks(); // Sync tasks from threadpool
}
App::GetGfxScene()->RegisterGfxActor(actor->GetGfxActor());
if (actor->ar_engine)
{
if (!actor->m_preloaded_with_terrain && App::sim_spawn_running->getBool())
actor->ar_engine->StartEngine();
else
actor->ar_engine->OffStart();
}
// pressurize tires
if (actor->getTyrePressure().IsEnabled())
{
actor->getTyrePressure().ModifyTyrePressure(0.f); // Initialize springiness of pressure-beams.
}
actor->ar_state = ActorState::LOCAL_SLEEPING;
if (App::mp_state->getEnum<MpState>() == RoR::MpState::CONNECTED)
{
// network buffer layout (without RoRnet::VehicleState):
// -----------------------------------------------------
// - 3 floats (x,y,z) for the reference node 0
// - ar_num_nodes - 1 times 3 short ints (compressed position info)
actor->m_net_node_buf_size = sizeof(float) * 3 + (actor->m_net_first_wheel_node - 1) * sizeof(short int) * 3;
actor->m_net_total_buffer_size += actor->m_net_node_buf_size;
// - ar_num_wheels times a float for the wheel rotation
actor->m_net_wheel_buf_size = actor->ar_num_wheels * sizeof(float);
actor->m_net_total_buffer_size += actor->m_net_wheel_buf_size;
// - bit array (made of ints) for the prop animation key states
actor->m_net_propanimkey_buf_size =
(actor->m_prop_anim_key_states.size() / 8) + // whole chars
(size_t)(actor->m_prop_anim_key_states.size() % 8 != 0); // remainder: 0 or 1 chars
actor->m_net_total_buffer_size += actor->m_net_propanimkey_buf_size;
if (rq.asr_origin == ActorSpawnRequest::Origin::NETWORK)
{
actor->ar_state = ActorState::NETWORKED_OK;
if (actor->ar_engine)
{
actor->ar_engine->StartEngine();
}
}
actor->m_net_username = rq.asr_net_username;
actor->m_net_color_num = rq.asr_net_color;
}
else if (App::sim_replay_enabled->getBool())
{
actor->m_replay_handler = new Replay(actor, App::sim_replay_length->getInt());
}
// Launch scripts (FIXME: ignores sectionconfig)
for (RigDef::Script const& script_def : def->root_module->scripts)
{
App::GetScriptEngine()->loadScript(script_def.filename, ScriptCategory::ACTOR, actor);
}
LOG(" ===== DONE LOADING VEHICLE");
if (App::diag_actor_dump->getBool())
{
actor->WriteDiagnosticDump(actor->ar_filename + "_dump_recalc.txt"); // Saves file to 'logs'
}
m_actors.push_back(ActorPtr(actor));
return actor;
}
void ActorManager::RemoveStreamSource(int sourceid)
{
m_stream_mismatches.erase(sourceid);
for (ActorPtr& actor : m_actors)
{
if (actor->ar_state != ActorState::NETWORKED_OK)
continue;
if (actor->ar_net_source_id == sourceid)
{
App::GetGameContext()->PushMessage(Message(MSG_SIM_DELETE_ACTOR_REQUESTED, static_cast<void*>(new ActorPtr(actor))));
}
}
}
#ifdef USE_SOCKETW
void ActorManager::HandleActorStreamData(std::vector<RoR::NetRecvPacket> packet_buffer)
{
// Sort by stream source
std::stable_sort(packet_buffer.begin(), packet_buffer.end(),
[](const RoR::NetRecvPacket& a, const RoR::NetRecvPacket& b)
{ return a.header.source > b.header.source; });
// Compress data stream by eliminating all but the last update from every consecutive group of stream data updates
auto it = std::unique(packet_buffer.rbegin(), packet_buffer.rend(),
[](const RoR::NetRecvPacket& a, const RoR::NetRecvPacket& b)
{ return !memcmp(&a.header, &b.header, sizeof(RoRnet::Header)) &&
a.header.command == RoRnet::MSG2_STREAM_DATA; });
packet_buffer.erase(packet_buffer.begin(), it.base());
for (auto& packet : packet_buffer)
{
if (packet.header.command == RoRnet::MSG2_STREAM_REGISTER)
{
RoRnet::StreamRegister* reg = (RoRnet::StreamRegister *)packet.buffer;
if (reg->type == 0)
{
reg->name[127] = 0;
// NOTE: The filename is by default in "Bundle-qualified" format, i.e. "mybundle.zip:myactor.truck"
std::string filename_maybe_bundlequalified = SanitizeUtf8CString(reg->name);
std::string filename;
std::string bundlename;
SplitBundleQualifiedFilename(filename_maybe_bundlequalified, /*out:*/ bundlename, /*out:*/ filename);
RoRnet::UserInfo info;
if (!App::GetNetwork()->GetUserInfo(reg->origin_sourceid, info))
{
RoR::LogFormat("[RoR] Invalid STREAM_REGISTER, user id %d does not exist", reg->origin_sourceid);
reg->status = -1;
}
else if (filename.empty())
{
RoR::LogFormat("[RoR] Invalid STREAM_REGISTER (user '%s', ID %d), filename is empty string", info.username, reg->origin_sourceid);
reg->status = -1;
}
else
{
Str<200> text;
text << _L("spawned a new vehicle: ") << filename;
App::GetConsole()->putNetMessage(
reg->origin_sourceid, Console::CONSOLE_SYSTEM_NOTICE, text.ToCStr());
LOG("[RoR] Creating remote actor for " + TOSTRING(reg->origin_sourceid) + ":" + TOSTRING(reg->origin_streamid));
CacheEntryPtr actor_entry = App::GetCacheSystem()->FindEntryByFilename(LT_AllBeam, /*partial:*/false, filename_maybe_bundlequalified);
if (!actor_entry)
{
App::GetConsole()->putMessage(
Console::CONSOLE_MSGTYPE_INFO, Console::CONSOLE_SYSTEM_WARNING,
_L("Mod not installed: ") + filename);
RoR::LogFormat("[RoR] Cannot create remote actor (not installed), filename: '%s'", filename_maybe_bundlequalified.c_str());
AddStreamMismatch(reg->origin_sourceid, reg->origin_streamid);
reg->status = -1;
}
else
{
auto actor_reg = reinterpret_cast<RoRnet::ActorStreamRegister*>(reg);
if (m_stream_time_offsets.find(reg->origin_sourceid) == m_stream_time_offsets.end())
{
int offset = actor_reg->time - m_net_timer.getMilliseconds();
m_stream_time_offsets[reg->origin_sourceid] = offset - 100;
}
ActorSpawnRequest* rq = new ActorSpawnRequest;
rq->asr_origin = ActorSpawnRequest::Origin::NETWORK;
rq->asr_cache_entry = actor_entry;
if (strnlen(actor_reg->skin, 60) < 60 && actor_reg->skin[0] != '\0')
{
rq->asr_skin_entry = App::GetCacheSystem()->FetchSkinByName(actor_reg->skin); // FIXME: fetch skin by name+guid! ~ 03/2019
}
if (strnlen(actor_reg->sectionconfig, 60) < 60)
{
rq->asr_config = actor_reg->sectionconfig;
}
rq->asr_net_username = tryConvertUTF(info.username);
rq->asr_net_color = info.colournum;
rq->net_source_id = reg->origin_sourceid;
rq->net_stream_id = reg->origin_streamid;
App::GetGameContext()->PushMessage(Message(
MSG_SIM_SPAWN_ACTOR_REQUESTED, (void*)rq));
reg->status = 1;
}
}
App::GetNetwork()->AddPacket(reg->origin_streamid, RoRnet::MSG2_STREAM_REGISTER_RESULT, sizeof(RoRnet::StreamRegister), (char *)reg);
}
}
else if (packet.header.command == RoRnet::MSG2_STREAM_REGISTER_RESULT)
{
RoRnet::StreamRegister* reg = (RoRnet::StreamRegister *)packet.buffer;
for (ActorPtr& actor: m_actors)
{
if (actor->ar_net_source_id == reg->origin_sourceid && actor->ar_net_stream_id == reg->origin_streamid)
{
int sourceid = packet.header.source;
actor->ar_net_stream_results[sourceid] = reg->status;
String message = "";
switch (reg->status)
{
case 1: message = "successfully loaded stream"; break;
case -2: message = "detected mismatch stream"; break;
default: message = "could not load stream"; break;
}
LOG("Client " + TOSTRING(sourceid) + " " + message + " " + TOSTRING(reg->origin_streamid) +
" with name '" + reg->name + "', result code: " + TOSTRING(reg->status));
break;
}
}
}
else if (packet.header.command == RoRnet::MSG2_STREAM_UNREGISTER)
{
ActorPtr b = this->GetActorByNetworkLinks(packet.header.source, packet.header.streamid);
if (b)
{
if (b->ar_state == ActorState::NETWORKED_OK || b->ar_state == ActorState::NETWORKED_HIDDEN)
{
App::GetGameContext()->PushMessage(Message(MSG_SIM_DELETE_ACTOR_REQUESTED, static_cast<void*>(new ActorPtr(b))));
}
}
m_stream_mismatches[packet.header.source].erase(packet.header.streamid);
}
else if (packet.header.command == RoRnet::MSG2_USER_LEAVE)
{
this->RemoveStreamSource(packet.header.source);
}
else if (packet.header.command == RoRnet::MSG2_STREAM_DATA)
{
for (ActorPtr& actor: m_actors)
{
if (actor->ar_state != ActorState::NETWORKED_OK)
continue;
if (packet.header.source == actor->ar_net_source_id && packet.header.streamid == actor->ar_net_stream_id)
{
actor->pushNetwork(packet.buffer, packet.header.size);
break;
}
}
}
}
}
#endif // USE_SOCKETW
int ActorManager::GetNetTimeOffset(int sourceid)
{
auto search = m_stream_time_offsets.find(sourceid);
if (search != m_stream_time_offsets.end())
{
return search->second;
}
return 0;
}
void ActorManager::UpdateNetTimeOffset(int sourceid, int offset)
{
if (m_stream_time_offsets.find(sourceid) != m_stream_time_offsets.end())
{
m_stream_time_offsets[sourceid] += offset;
}
}
int ActorManager::CheckNetworkStreamsOk(int sourceid)
{
if (!m_stream_mismatches[sourceid].empty())
return 0;
for (ActorPtr& actor: m_actors)
{
if (actor->ar_state != ActorState::NETWORKED_OK)
continue;
if (actor->ar_net_source_id == sourceid)
{
return 1;
}
}
return 2;
}
int ActorManager::CheckNetRemoteStreamsOk(int sourceid)
{
int result = 2;
for (ActorPtr& actor: m_actors)
{
if (actor->ar_state == ActorState::NETWORKED_OK)
continue;
int stream_result = actor->ar_net_stream_results[sourceid];
if (stream_result == -1 || stream_result == -2)
return 0;
if (stream_result == 1)
result = 1;
}
return result;
}
const ActorPtr& ActorManager::GetActorByNetworkLinks(int source_id, int stream_id)
{
for (ActorPtr& actor: m_actors)
{
if (actor->ar_net_source_id == source_id && actor->ar_net_stream_id == stream_id)
{
return actor;
}
}
return ACTORPTR_NULL;
}
bool ActorManager::CheckActorCollAabbIntersect(int a, int b)
{
if (m_actors[a]->ar_collision_bounding_boxes.empty() && m_actors[b]->ar_collision_bounding_boxes.empty())
{
return m_actors[a]->ar_bounding_box.intersects(m_actors[b]->ar_bounding_box);
}
else if (m_actors[a]->ar_collision_bounding_boxes.empty())
{
for (const auto& bbox_b : m_actors[b]->ar_collision_bounding_boxes)
if (bbox_b.intersects(m_actors[a]->ar_bounding_box))
return true;
}
else if (m_actors[b]->ar_collision_bounding_boxes.empty())
{
for (const auto& bbox_a : m_actors[a]->ar_collision_bounding_boxes)
if (bbox_a.intersects(m_actors[b]->ar_bounding_box))
return true;
}
else
{
for (const auto& bbox_a : m_actors[a]->ar_collision_bounding_boxes)
for (const auto& bbox_b : m_actors[b]->ar_collision_bounding_boxes)
if (bbox_a.intersects(bbox_b))
return true;
}
return false;
}
bool ActorManager::PredictActorCollAabbIntersect(int a, int b)
{
if (m_actors[a]->ar_predicted_coll_bounding_boxes.empty() && m_actors[b]->ar_predicted_coll_bounding_boxes.empty())
{
return m_actors[a]->ar_predicted_bounding_box.intersects(m_actors[b]->ar_predicted_bounding_box);
}
else if (m_actors[a]->ar_predicted_coll_bounding_boxes.empty())
{
for (const auto& bbox_b : m_actors[b]->ar_predicted_coll_bounding_boxes)
if (bbox_b.intersects(m_actors[a]->ar_predicted_bounding_box))
return true;
}
else if (m_actors[b]->ar_predicted_coll_bounding_boxes.empty())
{
for (const auto& bbox_a : m_actors[a]->ar_predicted_coll_bounding_boxes)
if (bbox_a.intersects(m_actors[b]->ar_predicted_bounding_box))
return true;
}
else
{
for (const auto& bbox_a : m_actors[a]->ar_predicted_coll_bounding_boxes)
for (const auto& bbox_b : m_actors[b]->ar_predicted_coll_bounding_boxes)
if (bbox_a.intersects(bbox_b))
return true;
}
return false;
}
void ActorManager::RecursiveActivation(int j, std::vector<bool>& visited)
{
if (visited[j] || m_actors[j]->ar_state != ActorState::LOCAL_SIMULATED)
return;
visited[j] = true;
for (unsigned int t = 0; t < m_actors.size(); t++)
{
if (t == j || visited[t])
continue;
if (m_actors[t]->ar_state == ActorState::LOCAL_SIMULATED && CheckActorCollAabbIntersect(t, j))
{
m_actors[t]->ar_sleep_counter = 0.0f;
this->RecursiveActivation(t, visited);
}
if (m_actors[t]->ar_state == ActorState::LOCAL_SLEEPING && PredictActorCollAabbIntersect(t, j))
{
m_actors[t]->ar_sleep_counter = 0.0f;
m_actors[t]->ar_state = ActorState::LOCAL_SIMULATED;
this->RecursiveActivation(t, visited);
}
}
}
void ActorManager::ForwardCommands(ActorPtr source_actor)
{
if (source_actor->ar_forward_commands)
{
auto linked_actors = source_actor->ar_linked_actors;
for (ActorPtr& actor : this->GetActors())
{
if (actor != source_actor && actor->ar_import_commands &&
(actor->getPosition().distance(source_actor->getPosition()) <
actor->m_min_camera_radius + source_actor->m_min_camera_radius))
{
// activate the truck
if (actor->ar_state == ActorState::LOCAL_SLEEPING)
{
actor->ar_sleep_counter = 0.0f;
actor->ar_state = ActorState::LOCAL_SIMULATED;
}
if (App::sim_realistic_commands->getBool())
{
if (std::find(linked_actors.begin(), linked_actors.end(), actor) == linked_actors.end())
continue;
}
// forward commands
for (int j = 1; j <= MAX_COMMANDS; j++) // BEWARE: commandkeys are indexed 1-MAX_COMMANDS!
{
actor->ar_command_key[j].playerInputValue = std::max(source_actor->ar_command_key[j].playerInputValue,
source_actor->ar_command_key[j].commandValue);
}
if (source_actor->ar_toggle_ties)
{
//actor->tieToggle();
ActorLinkingRequest* rq = new ActorLinkingRequest();
rq->alr_type = ActorLinkingRequestType::TIE_TOGGLE;
rq->alr_actor_instance_id = actor->ar_instance_id;
rq->alr_tie_group = -1;
App::GetGameContext()->PushMessage(Message(MSG_SIM_ACTOR_LINKING_REQUESTED, rq));
}
if (source_actor->ar_toggle_ropes)
{
//actor->ropeToggle(-1);
ActorLinkingRequest* rq = new ActorLinkingRequest();
rq->alr_type = ActorLinkingRequestType::ROPE_TOGGLE;
rq->alr_actor_instance_id = actor->ar_instance_id;
rq->alr_rope_group = -1;
App::GetGameContext()->PushMessage(Message(MSG_SIM_ACTOR_LINKING_REQUESTED, rq));
}
}
}
// just send brake and lights to the connected trucks, and no one else :)
for (auto hook : source_actor->ar_hooks)
{
if (!hook.hk_locked_actor || hook.hk_locked_actor == source_actor)
continue;
// forward brakes
hook.hk_locked_actor->ar_brake = source_actor->ar_brake;
if (hook.hk_locked_actor->ar_parking_brake != source_actor->ar_trailer_parking_brake)
{
hook.hk_locked_actor->parkingbrakeToggle();
}
// forward lights
hook.hk_locked_actor->importLightStateMask(source_actor->getLightStateMask());
}
}
}
bool ActorManager::AreActorsDirectlyLinked(const ActorPtr& a1, const ActorPtr& a2)
{
for (auto& entry: inter_actor_links)
{
auto& actor_pair = entry.second;
if ((actor_pair.first == a1 && actor_pair.second == a2) ||
(actor_pair.first == a2 && actor_pair.second == a1))
{
return true;
}
}
return false;
}
void ActorManager::UpdateSleepingState(ActorPtr player_actor, float dt)
{
if (!m_forced_awake)
{
for (ActorPtr& actor: m_actors)
{
if (actor->ar_state != ActorState::LOCAL_SIMULATED)
continue;
if (actor->ar_driveable == AI)
continue;
if (actor->getVelocity().squaredLength() > 0.01f)
{
actor->ar_sleep_counter = 0.0f;
continue;
}
actor->ar_sleep_counter += dt;
if (actor->ar_sleep_counter >= 10.0f)
{
actor->ar_state = ActorState::LOCAL_SLEEPING;
}
}
}
if (player_actor && player_actor->ar_state == ActorState::LOCAL_SLEEPING)
{
player_actor->ar_state = ActorState::LOCAL_SIMULATED;
}
std::vector<bool> visited(m_actors.size());
// Recursivly activate all actors which can be reached from current actor
if (player_actor && player_actor->ar_state == ActorState::LOCAL_SIMULATED)
{
player_actor->ar_sleep_counter = 0.0f;
this->RecursiveActivation(player_actor->ar_vector_index, visited);
}
// Snowball effect (activate all actors which might soon get hit by a moving actor)
for (unsigned int t = 0; t < m_actors.size(); t++)
{
if (m_actors[t]->ar_state == ActorState::LOCAL_SIMULATED && m_actors[t]->ar_sleep_counter == 0.0f)
this->RecursiveActivation(t, visited);
}
}
void ActorManager::WakeUpAllActors()
{
for (ActorPtr& actor: m_actors)
{
if (actor->ar_state == ActorState::LOCAL_SLEEPING)
{
actor->ar_state = ActorState::LOCAL_SIMULATED;
actor->ar_sleep_counter = 0.0f;
}
}
}
void ActorManager::SendAllActorsSleeping()
{
m_forced_awake = false;
for (ActorPtr& actor: m_actors)
{
if (actor->ar_state == ActorState::LOCAL_SIMULATED)
{
actor->ar_state = ActorState::LOCAL_SLEEPING;
}
}
}
ActorPtr ActorManager::FindActorInsideBox(Collisions* collisions, const Ogre::String& inst, const Ogre::String& box)
{
// try to find the desired actor (the one in the box)
ActorPtr ret = nullptr;
for (ActorPtr& actor: m_actors)
{
if (collisions->isInside(actor->ar_nodes[0].AbsPosition, inst, box))
{
if (ret == nullptr)
// first actor found
ret = actor;
else
// second actor found -> unclear which one was meant
return nullptr;
}
}
return ret;
}
void ActorManager::RepairActor(Collisions* collisions, const Ogre::String& inst, const Ogre::String& box, bool keepPosition)
{
ActorPtr actor = this->FindActorInsideBox(collisions, inst, box);
if (actor != nullptr)
{
SOUND_PLAY_ONCE(actor, SS_TRIG_REPAIR);
ActorModifyRequest* rq = new ActorModifyRequest;
rq->amr_actor = actor->ar_instance_id;
rq->amr_type = ActorModifyRequest::Type::RESET_ON_SPOT;
App::GetGameContext()->PushMessage(Message(MSG_SIM_MODIFY_ACTOR_REQUESTED, (void*)rq));
}
}
void ActorManager::MuteAllActors()
{
for (ActorPtr& actor: m_actors)
{
actor->muteAllSounds();
}
}
void ActorManager::UnmuteAllActors()
{
for (ActorPtr& actor: m_actors)
{
actor->unmuteAllSounds();
}
}
std::pair<ActorPtr, float> ActorManager::GetNearestActor(Vector3 position)
{
ActorPtr nearest_actor = nullptr;
float min_squared_distance = std::numeric_limits<float>::max();
for (ActorPtr& actor : m_actors)
{
float squared_distance = position.squaredDistance(actor->ar_nodes[0].AbsPosition);
if (squared_distance < min_squared_distance)
{
min_squared_distance = squared_distance;
nearest_actor = actor;
}
}
return std::make_pair(nearest_actor, std::sqrt(min_squared_distance));
}
void ActorManager::CleanUpSimulation() // Called after simulation finishes
{
while (m_actors.size() > 0)
{
this->DeleteActorInternal(m_actors.back()); // OK to invoke here - CleanUpSimulation() - processing `MSG_SIM_UNLOAD_TERRAIN_REQUESTED`
}
m_total_sim_time = 0.f;
m_last_simulation_speed = 0.1f;
m_simulation_paused = false;
m_simulation_speed = 1.f;
}
void ActorManager::DeleteActorInternal(ActorPtr actor)
{
if (actor == nullptr || actor->ar_state == ActorState::DISPOSED)
return;
this->SyncWithSimThread();
#ifdef USE_SOCKETW
if (App::mp_state->getEnum<MpState>() == RoR::MpState::CONNECTED)
{
if (actor->ar_state != ActorState::NETWORKED_OK)
{
App::GetNetwork()->AddPacket(actor->ar_net_stream_id, RoRnet::MSG2_STREAM_UNREGISTER, 0, 0);
}
else if (std::count_if(m_actors.begin(), m_actors.end(), [actor](ActorPtr& b)
{ return b->ar_net_source_id == actor->ar_net_source_id; }) == 1)
{
// We're deleting the last actor from this stream source, reset the stream time offset
m_stream_time_offsets.erase(actor->ar_net_source_id);
}
}
#endif // USE_SOCKETW
// Unload actor's scripts
std::vector<ScriptUnitID_t> unload_list;
for (auto& pair : App::GetScriptEngine()->getScriptUnits())
{
if (pair.second.associatedActor == actor)
unload_list.push_back(pair.first);
}
for (ScriptUnitID_t id : unload_list)
{
App::GetScriptEngine()->unloadScript(id);
}
// Remove FreeForces referencing this actor
m_free_forces.erase(
std::remove_if(
m_free_forces.begin(),
m_free_forces.end(),
[actor](FreeForce& item) { return item.ffc_base_actor == actor || item.ffc_target_actor == actor; }),
m_free_forces.end());
// Only dispose(), do not `delete`; a script may still hold pointer to the object.
actor->dispose();
EraseIf(m_actors, [actor](ActorPtr& curActor) { return actor == curActor; });
// Upate actor indices
for (unsigned int i = 0; i < m_actors.size(); i++)
m_actors[i]->ar_vector_index = i;
}
// ACTORLIST for cycling with hotkeys
// ----------------------------------
int FindPivotActorId(ActorPtr player, ActorPtr prev_player)
{
if (player != nullptr)
return player->ar_vector_index;
else if (prev_player != nullptr)
return prev_player->ar_vector_index + 1;
return -1;
}
bool ShouldIncludeActorInList(const ActorPtr& actor)
{
bool retval = !actor->isPreloadedWithTerrain();
// Exclude remote actors, if desired
if (!App::mp_cyclethru_net_actors->getBool())
{
if (actor->ar_state == ActorState::NETWORKED_OK || actor->ar_state == ActorState::NETWORKED_HIDDEN)
{
retval = false;
}
}
return retval;
}
const ActorPtr& ActorManager::FetchNextVehicleOnList(ActorPtr player, ActorPtr prev_player)
{
int pivot_index = FindPivotActorId(player, prev_player);
for (int i = pivot_index + 1; i < m_actors.size(); i++)
{
if (ShouldIncludeActorInList(m_actors[i]))
return m_actors[i];
}
for (int i = 0; i < pivot_index; i++)
{
if (ShouldIncludeActorInList(m_actors[i]))
return m_actors[i];
}
if (pivot_index >= 0)
{
if (ShouldIncludeActorInList(m_actors[pivot_index]))
return m_actors[pivot_index];
}
return ACTORPTR_NULL;
}
const ActorPtr& ActorManager::FetchPreviousVehicleOnList(ActorPtr player, ActorPtr prev_player)
{
int pivot_index = FindPivotActorId(player, prev_player);
for (int i = pivot_index - 1; i >= 0; i--)
{
if (ShouldIncludeActorInList(m_actors[i]))
return m_actors[i];
}
for (int i = static_cast<int>(m_actors.size()) - 1; i > pivot_index; i--)
{
if (ShouldIncludeActorInList(m_actors[i]))
return m_actors[i];