forked from tmj-fstate/maszyna
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdrivermode.cpp
1196 lines (1041 loc) · 45.6 KB
/
drivermode.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 Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "drivermode.h"
#include "driveruilayer.h"
#include "Globals.h"
#include "application.h"
#include "simulation.h"
#include "simulationtime.h"
#include "simulationenvironment.h"
#include "lightarray.h"
#include "particles.h"
#include "Train.h"
#include "Driver.h"
#include "DynObj.h"
#include "Model3d.h"
#include "Event.h"
#include "messaging.h"
#include "Timer.h"
#include "renderer.h"
#include "utilities.h"
#include "Logs.h"
/*
namespace input {
user_command command; // currently issued control command, if any
}
*/
void
driver_mode::drivermode_input::poll() {
if (telemetry)
telemetry->update();
keyboard.poll();
if( true == Global.InputMouse ) {
mouse.poll();
}
if( true == Global.InputGamepad ) {
gamepad.poll();
}
#ifdef WITH_UART
if( uart != nullptr ) {
uart->poll();
}
#endif
/*
// TBD, TODO: wrap current command in object, include other input sources?
input::command = (
mouse.command() != user_command::none ?
mouse.command() :
keyboard.command() );
*/
}
bool
driver_mode::drivermode_input::init() {
// initialize input devices
auto result = (
keyboard.init()
&& mouse.init() );
if( true == Global.InputGamepad ) {
gamepad.init();
}
#ifdef WITH_UART
if( true == Global.uart_conf.enable ) {
uart = std::make_unique<uart_input>();
uart->init();
}
#endif
if (Global.motiontelemetry_conf.enable)
telemetry = std::make_unique<motiontelemetry>();
#ifdef _WIN32
Console::On(); // włączenie konsoli
#endif
return result;
}
driver_mode::driver_mode() {
m_userinterface = std::make_shared<driver_ui>();
}
// initializes internal data structures of the mode. returns: true on success, false otherwise
bool
driver_mode::init() {
return m_input.init();
}
// mode-specific update of simulation data. returns: false on error, true otherwise
bool
driver_mode::update() {
Timer::UpdateTimers(Global.iPause != 0);
Timer::subsystem.sim_total.start();
double const deltatime = Timer::GetDeltaTime(); // 0.0 gdy pauza
if( Global.iPause == 0 ) {
// jak pauza, to nie ma po co tego przeliczać
simulation::Time.update( deltatime );
}
simulation::State.update_clocks();
simulation::Environment.update();
// fixed step, simulation time based updates
// m_primaryupdateaccumulator += dt; // unused for the time being
m_secondaryupdateaccumulator += deltatime;
/*
// NOTE: until we have no physics state interpolation during render, we need to rely on the old code,
// as doing fixed step calculations but flexible step render results in ugly mini jitter
// core routines (physics)
int updatecount = 0;
while( ( m_primaryupdateaccumulator >= m_primaryupdaterate )
&&( updatecount < 20 ) ) {
// no more than 20 updates per single pass, to keep physics from hogging up all run time
Ground.Update( m_primaryupdaterate, 1 );
++updatecount;
m_primaryupdateaccumulator -= m_primaryupdaterate;
}
*/
int updatecount = 1;
if( deltatime > m_primaryupdaterate ) // normalnie 0.01s
{
/*
// NOTE: experimentally disabled physics update cap
auto const iterations = std::ceil(dt / m_primaryupdaterate);
updatecount = std::min( 20, static_cast<int>( iterations ) );
*/
updatecount = std::ceil( deltatime / m_primaryupdaterate );
/*
// NOTE: changing dt wrecks things further down the code. re-acquire proper value later or cleanup here
dt = dt / iterations; // Ra: fizykę lepiej by było przeliczać ze stałym krokiem
*/
}
auto const stepdeltatime { deltatime / updatecount };
// NOTE: updates are limited to 20, but dt is distributed over potentially many more iterations
// this means at count > 20 simulation and render are going to desync. is that right?
// NOTE: experimentally changing this to prevent the desync.
// TODO: test what happens if we hit more than 20 * 0.01 sec slices, i.e. less than 5 fps
Timer::subsystem.sim_dynamics.start();
if( true == Global.FullPhysics ) {
// mixed calculation mode, steps calculated in ~0.05s chunks
while( updatecount >= 5 ) {
simulation::State.update( stepdeltatime, 5 );
updatecount -= 5;
}
if( updatecount ) {
simulation::State.update( stepdeltatime, updatecount );
}
}
else {
// simplified calculation mode; faster but can lead to errors
simulation::State.update( stepdeltatime, updatecount );
}
Timer::subsystem.sim_dynamics.stop();
// secondary fixed step simulation time routines
while( m_secondaryupdateaccumulator >= m_secondaryupdaterate ) {
// awaria PoKeys mogła włączyć pauzę - przekazać informację
if( Global.iMultiplayer ) // dajemy znać do serwera o wykonaniu
if( iPause != Global.iPause ) { // przesłanie informacji o pauzie do programu nadzorującego
multiplayer::WyslijParam( 5, 3 ); // ramka 5 z czasem i stanem zapauzowania
iPause = Global.iPause;
}
// TODO: generic shake update pass for vehicles within view range
if( Camera.m_owner != nullptr ) {
Camera.m_owner->update_shake( m_secondaryupdaterate );
}
m_secondaryupdateaccumulator -= m_secondaryupdaterate; // these should be inexpensive enough we have no cap
}
// variable step simulation time routines
if( ( simulation::Train == nullptr ) && ( false == FreeFlyModeFlag ) ) {
// intercept cases when the driven train got removed after entering portal
InOutKey();
}
if( Global.changeDynObj ) {
// ABu zmiana pojazdu - przejście do innego
ChangeDynamic();
}
if( simulation::Train != nullptr ) {
TSubModel::iInstance = reinterpret_cast<std::uintptr_t>( simulation::Train->Dynamic() );
simulation::Train->Update( deltatime );
}
else {
TSubModel::iInstance = 0;
}
simulation::Events.update();
simulation::Region->update_events();
simulation::Lights.update();
// render time routines follow:
auto const deltarealtime = Timer::GetDeltaRenderTime(); // nie uwzględnia pauzowania ani mnożenia czasu
// fixed step render time routines
fTime50Hz += deltarealtime; // w pauzie też trzeba zliczać czas, bo przy dużym FPS będzie problem z odczytem ramek
while( fTime50Hz >= 1.0 / 50.0 ) {
#ifdef _WIN32
Console::Update(); // to i tak trzeba wywoływać
#endif
ui::Transcripts.Update(); // obiekt obsługujący stenogramy dźwięków na ekranie
m_userinterface->update();
// decelerate camera
Camera.Velocity *= 0.65;
if( std::abs( Camera.Velocity.x ) < 0.01 ) { Camera.Velocity.x = 0.0; }
if( std::abs( Camera.Velocity.y ) < 0.01 ) { Camera.Velocity.y = 0.0; }
if( std::abs( Camera.Velocity.z ) < 0.01 ) { Camera.Velocity.z = 0.0; }
// decelerate debug camera too
DebugCamera.Velocity *= 0.65;
if( std::abs( DebugCamera.Velocity.x ) < 0.01 ) { DebugCamera.Velocity.x = 0.0; }
if( std::abs( DebugCamera.Velocity.y ) < 0.01 ) { DebugCamera.Velocity.y = 0.0; }
if( std::abs( DebugCamera.Velocity.z ) < 0.01 ) { DebugCamera.Velocity.z = 0.0; }
fTime50Hz -= 1.0 / 50.0;
}
// variable step render time routines
update_camera( deltarealtime );
simulation::Environment.update_precipitation(); // has to be launched after camera step to work properly
Timer::subsystem.sim_total.stop();
simulation::Region->update_sounds();
audio::renderer.update( Global.iPause ? 0.0 : deltarealtime );
// NOTE: particle system runs on simulation time, but needs actual camera position to determine how to update each particle source
simulation::Particles.update();
GfxRenderer.Update( deltarealtime );
simulation::is_ready = true;
return true;
}
// maintenance method, called when the mode is activated
void
driver_mode::enter() {
TDynamicObject *nPlayerTrain { (
( Global.asHumanCtrlVehicle != "ghostview" ) ?
simulation::Vehicles.find( Global.asHumanCtrlVehicle ) :
nullptr ) };
Camera.Init(Global.FreeCameraInit[0], Global.FreeCameraInitAngle[0], nPlayerTrain );
Global.pCamera = Camera;
Global.pDebugCamera = DebugCamera;
if (nPlayerTrain)
{
WriteLog( "Initializing player train, \"" + Global.asHumanCtrlVehicle + "\"" );
if( simulation::Train == nullptr ) {
simulation::Train = new TTrain();
}
if( simulation::Train->Init( nPlayerTrain ) )
{
WriteLog("Player train initialization OK");
Application.set_title( Global.AppName + " (" + simulation::Train->Controlled()->Name + " @ " + Global.SceneryFile + ")" );
CabView();
}
else
{
Error("Bad init: player train initialization failed");
FreeFlyModeFlag = true; // Ra: automatycznie włączone latanie
SafeDelete( simulation::Train );
Camera.m_owner = nullptr;
}
}
else
{
if (Global.asHumanCtrlVehicle != "ghostview")
{
Error("Bad scenario: failed to locate player train, \"" + Global.asHumanCtrlVehicle + "\"" );
}
FreeFlyModeFlag = true; // Ra: automatycznie włączone latanie
Camera.m_owner = nullptr;
DebugCamera = Camera;
}
// if (!Global.bMultiplayer) //na razie włączone
{ // eventy aktywowane z klawiatury tylko dla jednego użytkownika
KeyEvents[ 0 ] = simulation::Events.FindEvent( "keyctrl00" );
KeyEvents[ 1 ] = simulation::Events.FindEvent( "keyctrl01" );
KeyEvents[ 2 ] = simulation::Events.FindEvent( "keyctrl02" );
KeyEvents[ 3 ] = simulation::Events.FindEvent( "keyctrl03" );
KeyEvents[ 4 ] = simulation::Events.FindEvent( "keyctrl04" );
KeyEvents[ 5 ] = simulation::Events.FindEvent( "keyctrl05" );
KeyEvents[ 6 ] = simulation::Events.FindEvent( "keyctrl06" );
KeyEvents[ 7 ] = simulation::Events.FindEvent( "keyctrl07" );
KeyEvents[ 8 ] = simulation::Events.FindEvent( "keyctrl08" );
KeyEvents[ 9 ] = simulation::Events.FindEvent( "keyctrl09" );
}
//ui_log->enabled = false;
Timer::ResetTimers();
set_picking( Global.ControlPicking );
}
// maintenance method, called when the mode is deactivated
void
driver_mode::exit() {
}
void
driver_mode::on_key( int const Key, int const Scancode, int const Action, int const Mods ) {
Global.shiftState = ( Mods & GLFW_MOD_SHIFT ) ? true : false;
Global.ctrlState = ( Mods & GLFW_MOD_CONTROL ) ? true : false;
Global.altState = ( Mods & GLFW_MOD_ALT ) ? true : false;
// give the ui first shot at the input processing...
if( true == m_userinterface->on_key( Key, Action ) ) { return; }
// ...if the input is left untouched, pass it on
if( true == m_input.keyboard.key( Key, Action ) ) { return; }
if( ( true == Global.InputMouse )
&& ( ( Key == GLFW_KEY_LEFT_ALT )
|| ( Key == GLFW_KEY_RIGHT_ALT ) ) ) {
// if the alt key was pressed toggle control picking mode and set matching cursor behaviour
if( Action == GLFW_PRESS ) {
// toggle picking mode
set_picking( !Global.ControlPicking );
}
}
if( Action != GLFW_RELEASE ) {
OnKeyDown( Key );
}
}
void
driver_mode::on_cursor_pos( double const Horizontal, double const Vertical ) {
// give the ui first shot at the input processing...
if( true == m_userinterface->on_cursor_pos( Horizontal, Vertical ) ) { return; }
if( false == Global.ControlPicking ) {
// in regular view mode keep cursor on screen
Application.set_cursor_pos( 0, 0 );
}
// give the potential event recipient a shot at it, in the virtual z order
m_input.mouse.move( Horizontal, Vertical );
}
void
driver_mode::on_mouse_button( int const Button, int const Action, int const Mods ) {
// give the ui first shot at the input processing...
if( true == m_userinterface->on_mouse_button( Button, Action ) ) { return; }
// give the potential event recipient a shot at it, in the virtual z order
m_input.mouse.button( Button, Action );
}
void
driver_mode::on_scroll( double const Xoffset, double const Yoffset ) {
m_input.mouse.scroll( Xoffset, Yoffset );
}
void
driver_mode::on_event_poll() {
m_input.poll();
}
void
driver_mode::update_camera( double const Deltatime ) {
auto *controlled = (
simulation::Train ?
simulation::Train->Dynamic() :
nullptr );
if( false == Global.ControlPicking ) {
if( m_input.mouse.button( GLFW_MOUSE_BUTTON_LEFT ) == GLFW_PRESS ) {
Camera.Reset(); // likwidacja obrotów - patrzy horyzontalnie na południe
if( Camera.m_owner == nullptr ) {
if( controlled && LengthSquared3( controlled->GetPosition() - Camera.Pos ) < ( 1500 * 1500 ) ) {
// gdy bliżej niż 1.5km
Camera.LookAt = controlled->GetPosition();
}
else {
TDynamicObject *d = std::get<TDynamicObject *>( simulation::Region->find_vehicle( Global.pCamera.Pos, 300, false, false ) );
if( !d )
d = std::get<TDynamicObject *>( simulation::Region->find_vehicle( Global.pCamera.Pos, 1000, false, false ) ); // dalej szukanie, jesli bliżej nie ma
if( d && pDynamicNearest ) {
// jeśli jakiś jest znaleziony wcześniej
if( 100.0 * LengthSquared3( d->GetPosition() - Camera.Pos ) > LengthSquared3( pDynamicNearest->GetPosition() - Camera.Pos ) ) {
d = pDynamicNearest; // jeśli najbliższy nie jest 10 razy bliżej niż
}
}
// poprzedni najbliższy, zostaje poprzedni
if( d )
pDynamicNearest = d; // zmiana na nowy, jeśli coś znaleziony niepusty
if( pDynamicNearest )
Camera.LookAt = pDynamicNearest->GetPosition();
}
Camera.RaLook(); // jednorazowe przestawienie kamery
}
else {
if( false == FreeFlyModeFlag ) {
// reset cached view angle in the cab
simulation::Train->pMechViewAngle = { Camera.Angle.x, Camera.Angle.y };
}
}
}
else if( m_input.mouse.button( GLFW_MOUSE_BUTTON_RIGHT ) == GLFW_PRESS ) {
CabView();
}
}
if( m_input.mouse.button( GLFW_MOUSE_BUTTON_MIDDLE ) == GLFW_PRESS ) {
// middle mouse button controls zoom.
Global.ZoomFactor = std::min( 4.5f, Global.ZoomFactor + 15.0f * static_cast<float>( Deltatime ) );
}
else if( m_input.mouse.button( GLFW_MOUSE_BUTTON_MIDDLE ) != GLFW_PRESS ) {
// reset zoom level if the button is no longer held down.
// NOTE: yes, this is terrible way to go about it. it'll do for now.
Global.ZoomFactor = std::max( 1.0f, Global.ZoomFactor - 15.0f * static_cast<float>( Deltatime ) );
}
// uwzględnienie ruchu wywołanego klawiszami
if( false == DebugCameraFlag ) {
// regular camera
if( ( false == FreeFlyModeFlag )
&& ( false == Global.CabWindowOpen ) ) {
// if in cab potentially alter camera placement based on changes in train object
Camera.m_owneroffset = simulation::Train->pMechOffset;
Camera.Angle.x = simulation::Train->pMechViewAngle.x;
Camera.Angle.y = simulation::Train->pMechViewAngle.y;
}
Camera.Update();
if( false == FreeFlyModeFlag ) {
// keep the camera within cab boundaries
Camera.m_owneroffset = simulation::Train->clamp_inside( Camera.m_owneroffset );
}
if( ( false == FreeFlyModeFlag )
&& ( false == Global.CabWindowOpen ) ) {
// cache cab camera in case of view type switch
simulation::Train->pMechViewAngle = { Camera.Angle.x, Camera.Angle.y };
simulation::Train->pMechOffset = Camera.m_owneroffset;
}
if( ( true == FreeFlyModeFlag )
&& ( Camera.m_owner != nullptr ) ) {
// cache external view config
auto &externalviewconfig { m_externalviewconfigs[ m_externalviewmode ] };
externalviewconfig.owner = Camera.m_owner;
externalviewconfig.offset = Camera.m_owneroffset;
externalviewconfig.angle = Camera.Angle;
}
}
else {
// debug camera
DebugCamera.Update();
}
// reset window state, it'll be set again if applicable in a check below
Global.CabWindowOpen = false;
if( ( simulation::Train != nullptr )
&& ( Camera.m_owner != nullptr )
&& ( false == DebugCameraFlag ) ) {
// jeśli jazda w kabinie, przeliczyć trzeba parametry kamery
/*
auto tempangle = controlled->VectorFront() * ( controlled->MoverParameters->ActiveCab == -1 ? -1 : 1 );
double modelrotate = atan2( -tempangle.x, tempangle.z );
*/
if( ( false == FreeFlyModeFlag )
&& ( true == Global.ctrlState )
&& ( ( m_input.keyboard.key( GLFW_KEY_LEFT ) != GLFW_RELEASE )
|| ( m_input.keyboard.key( GLFW_KEY_RIGHT ) != GLFW_RELEASE ) ) ) {
// jeśli lusterko lewe albo prawe (bez rzucania na razie)
Global.CabWindowOpen = true;
auto const lr { m_input.keyboard.key( GLFW_KEY_LEFT ) != GLFW_RELEASE };
// Camera.Yaw powinno być wyzerowane, aby po powrocie patrzeć do przodu
Camera.Pos = controlled->GetPosition() + simulation::Train->MirrorPosition( lr ); // pozycja lusterka
Camera.Angle.y = 0; // odchylenie na bok od Camera.LookAt
if( simulation::Train->Occupied()->ActiveCab == 0 ) {
// gdy w korytarzu
Camera.LookAt = Camera.Pos - simulation::Train->GetDirection();
}
else if( Global.shiftState ) {
// patrzenie w bok przez szybę
Camera.LookAt = Camera.Pos - ( lr ? -1 : 1 ) * controlled->VectorLeft() * simulation::Train->Occupied()->ActiveCab;
}
else { // patrzenie w kierunku osi pojazdu, z uwzględnieniem kabiny - jakby z lusterka,
// ale bez odbicia
Camera.LookAt = Camera.Pos - simulation::Train->GetDirection() * simulation::Train->Occupied()->ActiveCab; //-1 albo 1
}
auto const shakeangles { simulation::Train->Dynamic()->shake_angles() };
Camera.Angle.x = 0.5 * shakeangles.second; // hustanie kamery przod tyl
Camera.Angle.z = shakeangles.first; // hustanie kamery na boki
/*
Camera.Roll = std::atan( simulation::Train->pMechShake.x * simulation::Train->BaseShake.angle_scale.x ); // hustanie kamery na boki
Camera.Pitch = 0.5 * std::atan( simulation::Train->vMechVelocity.z * simulation::Train->BaseShake.angle_scale.z ); // hustanie kamery przod tyl
*/
Camera.vUp = controlled->VectorUp();
}
else {
// patrzenie standardowe
if( false == FreeFlyModeFlag ) {
// potentially restore view angle after returning from external view
// TODO: mirror view toggle as separate method
Camera.Angle.x = simulation::Train->pMechViewAngle.x;
Camera.Angle.y = simulation::Train->pMechViewAngle.y;
}
auto const shakescale { FreeFlyModeFlag ? 5.0 : 1.0 };
auto shakencamerapos {
Camera.m_owneroffset
+ shakescale * Math3D::vector3(
1.5 * Camera.m_owner->ShakeState.offset.x,
2.0 * Camera.m_owner->ShakeState.offset.y,
1.5 * Camera.m_owner->ShakeState.offset.z ) };
Camera.Pos = (
Camera.m_owner->GetWorldPosition (
FreeFlyModeFlag ?
shakencamerapos : // TODO: vehicle collision box for the external vehicle camera
simulation::Train->clamp_inside( shakencamerapos ) ) );
if( !Global.iPause ) {
// podczas pauzy nie przeliczać kątów przypadkowymi wartościami
auto const shakeangles { Camera.m_owner->shake_angles() };
Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl
Camera.Angle.z = shakeangles.first; // hustanie kamery na boki
/*
Camera.Roll = std::atan( simulation::Train->vMechVelocity.x * simulation::Train->BaseShake.angle_scale.x ); // hustanie kamery na boki
Camera.Pitch -= 0.5 * atan( simulation::Train->vMechVelocity.z * simulation::Train->BaseShake.angle_scale.z ); // hustanie kamery przod tyl
*/
}
/*
// ABu011104: rzucanie pudlem
vector3 temp;
if( abs( Train->pMechShake.y ) < 0.25 )
temp = vector3( 0, 0, 6 * Train->pMechShake.y );
else if( ( Train->pMechShake.y ) > 0 )
temp = vector3( 0, 0, 6 * 0.25 );
else
temp = vector3( 0, 0, -6 * 0.25 );
if( Controlled )
Controlled->ABuSetModelShake( temp );
// ABu: koniec rzucania
*/
if( simulation::Train->Occupied()->ActiveCab == 0 ) {
// gdy w korytarzu
Camera.LookAt =
Camera.m_owner->GetWorldPosition( Camera.m_owneroffset )
+ Camera.m_owner->VectorFront() * 5.0;
}
else {
// patrzenie w kierunku osi pojazdu, z uwzględnieniem kabiny
Camera.LookAt =
Camera.m_owner->GetWorldPosition( Camera.m_owneroffset )
+ Camera.m_owner->VectorFront() * 5.0
* simulation::Train->Occupied()->ActiveCab; //-1 albo 1
}
Camera.vUp = simulation::Train->GetUp();
}
}
// all done, update camera position to the new value
Global.pCamera = Camera;
}
void
driver_mode::OnKeyDown(int cKey) {
// dump keypress info in the log
// podczas pauzy klawisze nie działają
std::string keyinfo;
auto keyname = glfwGetKeyName( cKey, 0 );
if( keyname != nullptr ) {
keyinfo += std::string( keyname );
}
else {
switch( cKey ) {
case GLFW_KEY_SPACE: { keyinfo += "Space"; break; }
case GLFW_KEY_ENTER: { keyinfo += "Enter"; break; }
case GLFW_KEY_ESCAPE: { keyinfo += "Esc"; break; }
case GLFW_KEY_TAB: { keyinfo += "Tab"; break; }
case GLFW_KEY_INSERT: { keyinfo += "Insert"; break; }
case GLFW_KEY_DELETE: { keyinfo += "Delete"; break; }
case GLFW_KEY_HOME: { keyinfo += "Home"; break; }
case GLFW_KEY_END: { keyinfo += "End"; break; }
case GLFW_KEY_F1: { keyinfo += "F1"; break; }
case GLFW_KEY_F2: { keyinfo += "F2"; break; }
case GLFW_KEY_F3: { keyinfo += "F3"; break; }
case GLFW_KEY_F4: { keyinfo += "F4"; break; }
case GLFW_KEY_F5: { keyinfo += "F5"; break; }
case GLFW_KEY_F6: { keyinfo += "F6"; break; }
case GLFW_KEY_F7: { keyinfo += "F7"; break; }
case GLFW_KEY_F8: { keyinfo += "F8"; break; }
case GLFW_KEY_F9: { keyinfo += "F9"; break; }
case GLFW_KEY_F10: { keyinfo += "F10"; break; }
case GLFW_KEY_F11: { keyinfo += "F11"; break; }
case GLFW_KEY_F12: { keyinfo += "F12"; break; }
case GLFW_KEY_PAUSE: { keyinfo += "Pause"; break; }
}
}
if( keyinfo.empty() == false ) {
std::string keymodifiers;
if( Global.shiftState )
keymodifiers += "[Shift]+";
if( Global.ctrlState )
keymodifiers += "[Ctrl]+";
WriteLog( "Key pressed: " + keymodifiers + "[" + keyinfo + "]" );
}
// actual key processing
// TODO: redo the input system
if( ( cKey >= GLFW_KEY_0 ) && ( cKey <= GLFW_KEY_9 ) ) {
// klawisze cyfrowe
int i = cKey - GLFW_KEY_0; // numer klawisza
if (Global.shiftState) {
// z [Shift] uruchomienie eventu
if( ( false == Global.iPause ) // podczas pauzy klawisze nie działają
&& ( KeyEvents[ i ] != nullptr ) ) {
simulation::Events.AddToQuery( KeyEvents[ i ], NULL );
}
}
else if( Global.ctrlState ) {
// zapamiętywanie kamery może działać podczas pauzy
if( FreeFlyModeFlag ) {
// w trybie latania można przeskakiwać do ustawionych kamer
if( ( Global.FreeCameraInit[ i ].x == 0.0 )
&& ( Global.FreeCameraInit[ i ].y == 0.0 )
&& ( Global.FreeCameraInit[ i ].z == 0.0 ) ) {
// jeśli kamera jest w punkcie zerowym, zapamiętanie współrzędnych i kątów
Global.FreeCameraInit[ i ] = Camera.Pos;
Global.FreeCameraInitAngle[ i ] = Camera.Angle;
// logowanie, żeby można było do scenerii przepisać
WriteLog(
"camera " + std::to_string( Global.FreeCameraInit[ i ].x ) + " "
+ std::to_string( Global.FreeCameraInit[ i ].y ) + " "
+ std::to_string( Global.FreeCameraInit[ i ].z ) + " "
+ std::to_string( RadToDeg( Global.FreeCameraInitAngle[ i ].x ) ) + " "
+ std::to_string( RadToDeg( Global.FreeCameraInitAngle[ i ].y ) ) + " "
+ std::to_string( RadToDeg( Global.FreeCameraInitAngle[ i ].z ) ) + " "
+ std::to_string( i ) + " endcamera" );
}
else // również przeskakiwanie
{ // Ra: to z tą kamerą (Camera.Pos i Global.pCameraPosition) jest trochę bez sensu
Global.pCamera.Pos = Global.FreeCameraInit[ i ]; // nowa pozycja dla generowania obiektów
Camera.Init( Global.FreeCameraInit[ i ], Global.FreeCameraInitAngle[ i ], nullptr ); // przestawienie
}
}
}
return;
}
switch (cKey) {
case GLFW_KEY_F1: {
if( DebugModeFlag ) {
// additional simulation clock jump keys in debug mode
if( Global.ctrlState ) {
// ctrl-f1
simulation::Time.update( 20.0 * 60.0 );
}
else if( Global.shiftState ) {
// shift-f1
simulation::Time.update( 5.0 * 60.0 );
}
}
break;
}
case GLFW_KEY_F4: {
if( Global.shiftState ) { ExternalView(); } // with Shift, cycle through external views
else { InOutKey(); } // without, step out of the cab or return to it
break;
}
case GLFW_KEY_F5: {
// przesiadka do innego pojazdu
if( false == FreeFlyModeFlag ) {
// only available in free fly mode
break;
}
TDynamicObject *tmp = std::get<TDynamicObject *>( simulation::Region->find_vehicle( Global.pCamera.Pos, 50, true, false ) );
if( tmp != nullptr ) {
if( ( true == DebugModeFlag )
|| ( tmp->MoverParameters->Vel <= 5.0 ) ) {
// works always in debug mode, or for stopped/slow moving vehicles otherwise
if( simulation::Train ) { // jeśli mielismy pojazd
if( simulation::Train->Dynamic()->Mechanik ) { // na skutek jakiegoś błędu może czasem zniknąć
if( ( tmp->ctOwner == simulation::Train->Dynamic()->Mechanik )
&& ( true == Global.ctrlState ) ) {
// if the vehicle we left to the ai controlled the vehicle we're about to take over
// put the ai we left in charge of our old vehicle to sleep
// TODO: remove ctrl key mode once manual cab (de)activation is in place
simulation::Train->Dynamic()->Mechanik->primary( false );
simulation::Train->Dynamic()->Mechanik->action() = TAction::actSleep;
simulation::Train->Dynamic()->MoverParameters->CabDeactivisation();
}
simulation::Train->Dynamic()->Mechanik->TakeControl( true ); // oddajemy dotychczasowy AI
}
}
if( simulation::Train == nullptr ) {
simulation::Train = new TTrain(); // jeśli niczym jeszcze nie jeździlismy
}
if( simulation::Train->Init( tmp ) ) {
// przejmujemy sterowanie
if( true == Global.ctrlState ) {
// make sure we can take over the consist
// TODO: remove ctrl key mode once manual cab (de)activation is in place
simulation::Train->Dynamic()->Mechanik->primary( true );
simulation::Train->Dynamic()->MoverParameters->CabActivisation();
}
simulation::Train->Dynamic()->Mechanik->TakeControl( false, true );
}
else {
SafeDelete( simulation::Train ); // i nie ma czym sterować
}
if( simulation::Train ) {
InOutKey(); // do kabiny
}
}
}
break;
}
case GLFW_KEY_F6: {
// przyspieszenie symulacji do testowania scenerii... uwaga na FPS!
if( DebugModeFlag ) {
if( Global.ctrlState ) { Global.fTimeSpeed = ( Global.shiftState ? 60.0 : 20.0 ); }
else { Global.fTimeSpeed = ( Global.shiftState ? 5.0 : 1.0 ); }
}
break;
}
case GLFW_KEY_F7: {
// debug mode functions
if( DebugModeFlag ) {
if( Global.ctrlState
&& Global.shiftState ) {
// shift + ctrl + f7 toggles between debug and regular camera
DebugCameraFlag = !DebugCameraFlag;
}
else if( Global.ctrlState ) {
// ctrl + f7 toggles static daylight
simulation::Environment.toggle_daylight();
break;
}
else if( Global.shiftState ) {
// shift + f7 is currently unused
}
else {
// f7: wireframe toggle
// TODO: pass this to renderer instead of making direct calls
Global.bWireFrame = !Global.bWireFrame;
if( true == Global.bWireFrame ) {
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
}
else {
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
}
}
}
break;
}
case GLFW_KEY_F11: {
// editor mode
if( ( false == Global.ctrlState )
&& ( false == Global.shiftState ) ) {
Application.push_mode( eu07_application::mode::editor );
}
break;
}
case GLFW_KEY_F12: {
// quick debug mode toggle
if( Global.ctrlState
&& Global.shiftState ) {
DebugModeFlag = !DebugModeFlag;
}
break;
}
case GLFW_KEY_LEFT_BRACKET:
case GLFW_KEY_RIGHT_BRACKET:
case GLFW_KEY_TAB: {
// consist movement in debug mode
if( ( true == DebugModeFlag )
&& ( false == Global.shiftState )
&& ( true == Global.ctrlState )
&& ( simulation::Train != nullptr )
&& ( simulation::Train->Dynamic()->Controller == Humandriver ) ) {
if( DebugModeFlag ) {
// przesuwanie składu o 100m
auto *vehicle { simulation::Train->Dynamic() };
TDynamicObject *d = vehicle;
if( cKey == GLFW_KEY_LEFT_BRACKET ) {
while( d ) {
d->Move( 100.0 * d->DirectionGet() );
d = d->Next(); // pozostałe też
}
d = vehicle->Prev();
while( d ) {
d->Move( 100.0 * d->DirectionGet() );
d = d->Prev(); // w drugą stronę też
}
}
else if( cKey == GLFW_KEY_RIGHT_BRACKET ) {
while( d ) {
d->Move( -100.0 * d->DirectionGet() );
d = d->Next(); // pozostałe też
}
d = vehicle->Prev();
while( d ) {
d->Move( -100.0 * d->DirectionGet() );
d = d->Prev(); // w drugą stronę też
}
}
else if( cKey == GLFW_KEY_TAB ) {
while( d ) {
d->MoverParameters->V += d->DirectionGet()*2.78;
d = d->Next(); // pozostałe też
}
d = vehicle->Prev();
while( d ) {
d->MoverParameters->V += d->DirectionGet()*2.78;
d = d->Prev(); // w drugą stronę też
}
}
}
}
break;
}
default: {
break;
}
}
return; // nie są przekazywane do pojazdu wcale
}
// places camera outside the controlled vehicle, or nearest if nothing is under control
// depending on provided switch the view is placed right outside, or at medium distance
void
driver_mode::DistantView( bool const Near ) {
TDynamicObject const *vehicle = { (
( simulation::Train != nullptr ) ?
simulation::Train->Dynamic() :
pDynamicNearest ) };
if( vehicle == nullptr ) { return; }
auto const cab =
( vehicle->MoverParameters->ActiveCab == 0 ?
1 :
vehicle->MoverParameters->ActiveCab );
auto const left = vehicle->VectorLeft() * cab;
if( true == Near ) {
Camera.Pos =
Math3D::vector3( Camera.Pos.x, vehicle->GetPosition().y, Camera.Pos.z )
+ left * vehicle->GetWidth()
+ Math3D::vector3( 1.25 * left.x, 1.6, 1.25 * left.z );
}
else {
Camera.Pos =
vehicle->GetPosition()
+ vehicle->VectorFront() * vehicle->MoverParameters->ActiveCab * 50.0
+ Math3D::vector3( -10.0 * left.x, 1.6, -10.0 * left.z );
}
Camera.m_owner = nullptr;
Camera.LookAt = vehicle->GetPosition();
Camera.RaLook(); // jednorazowe przestawienie kamery
}
void
driver_mode::ExternalView() {
auto *train { simulation::Train };
if( train == nullptr ) { return; }
auto *vehicle { train->Dynamic() };
// disable detailed cab in external view modes
vehicle->bDisplayCab = false;
if( true == m_externalview ) {
// we're already in some external view mode, so select next one on the list
m_externalviewmode = clamp_circular( ++m_externalviewmode, static_cast<int>( view::count_ ) );
}
FreeFlyModeFlag = true;
m_externalview = true;
Camera.Reset();
// configure camera placement for the selected view mode
switch( m_externalviewmode ) {
case view::consistfront: {
// bind camera with the vehicle
auto *owner { vehicle->Mechanik->Vehicle( end::front ) };
Camera.m_owner = owner;
auto const &viewconfig { m_externalviewconfigs[ m_externalviewmode ] };
if( owner == viewconfig.owner ) {
// restore view config for previous owner
Camera.m_owneroffset = viewconfig.offset;
Camera.Angle = viewconfig.angle;
}
else {
// default view setup
auto const offsetflip{
( vehicle->MoverParameters->ActiveCab == 0 ? 1 : vehicle->MoverParameters->ActiveCab )
* ( vehicle->MoverParameters->ActiveDir == 0 ? 1 : vehicle->MoverParameters->ActiveDir ) };
Camera.m_owneroffset = {
1.5 * owner->MoverParameters->Dim.W * offsetflip,
std::max( 5.0, 1.25 * owner->MoverParameters->Dim.H ),
-0.4 * owner->MoverParameters->Dim.L * offsetflip };
Camera.Angle.y = glm::radians( ( vehicle->MoverParameters->ActiveDir < 0 ? 180.0 : 0.0 ) );
}
auto const shakeangles{ owner->shake_angles() };
Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl
Camera.Angle.z = shakeangles.first; // hustanie kamery na boki
break;
}
case view::consistrear: {
// bind camera with the vehicle
auto *owner { vehicle->Mechanik->Vehicle( end::rear ) };
Camera.m_owner = owner;
auto const &viewconfig{ m_externalviewconfigs[ m_externalviewmode ] };
if( owner == viewconfig.owner ) {
// restore view config for previous owner
Camera.m_owneroffset = viewconfig.offset;
Camera.Angle = viewconfig.angle;
}
else {
// default view setup
auto const offsetflip{
( vehicle->MoverParameters->ActiveCab == 0 ? 1 : vehicle->MoverParameters->ActiveCab )
* ( vehicle->MoverParameters->ActiveDir == 0 ? 1 : vehicle->MoverParameters->ActiveDir )
* -1 };
Camera.m_owneroffset = {
1.5 * owner->MoverParameters->Dim.W * offsetflip,
std::max( 5.0, 1.25 * owner->MoverParameters->Dim.H ),
0.2 * owner->MoverParameters->Dim.L * offsetflip };
Camera.Angle.y = glm::radians( ( vehicle->MoverParameters->ActiveDir < 0 ? 0.0 : 180.0 ) );
}
auto const shakeangles { owner->shake_angles() };
Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl