-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRailDriver.txt
1167 lines (976 loc) · 43.2 KB
/
RailDriver.txt
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
#[
RailDriver. Smart Locomotive Control script for Garry's Mod Train Build Servers.
Copyright © 2022, Cassandra "ZZ Cat" Robinson. All rights reserved.
This E2 script is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This E2 script 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this E2 script. If not, see <https://www.gnu.org/licenses/>.
]#
@name RailDriver
@model models/beer/wiremod/gate_e2_nano.mdl
@persist Trucks:array Speedo:table NDOF:table
# @persist Brake
@persist [Direction Throttle EmergencyBrake]:number
@persist [OTALocal OTAOnline CLI PlayerControls ThrottleMap BrakeMap]:table TrainDriver:entity
@persist PIDF:table
@persist HillClimbDescentData:array
@persist EmBrakeState EmBrakeThisSpeed EmBrakeLastSpeed EmBrakeObserverTickInterval EmBrakePCFaultTimeoutSet
@persist Speed SpeedAbs SpeedMPH
@persist DupeTickInterval DupeIsLoading DupeIsFinished RailDriverState
@outputs Debugger:table DbgAcceleration:vector [DbgAngularVelocity DbgOrientation]:angle DbgGradient DbgHillClimbDescentFF
@strict
# Monitor Advanced Duplicator 2 for Dupe loading.
# This resolves a bug (#30) where RailDriver would not initialize properly after a Dupe is loaded.
if (duped())
{
DupeIsLoading = 1
DupeIsFinished = 0
DupeTickInterval = tickInterval() * 1000
RailDriverState = 0
timer("Dupe Timer", DupeTickInterval)
}
elseif (dupefinished())
{
DupeIsLoading = 0
DupeIsFinished = 1
RailDriverState = 0
}
elseif (clk("Dupe Timer"))
{
try
{
stoptimer("Dupe Timer")
if (DupeIsLoading & !DupeIsFinished)
{
timer("Dupe Timer", DupeTickInterval)
}
elseif (!DupeIsLoading & DupeIsFinished)
{
reset()
}
else
{
error("RailDriver failed to load.")
}
}
catch (Exception)
{
RailDriverState = 0
printColor(vec(255, 0, 0), "[RailDriver | ERROR]", vec(255, 255, 255), ": " + Exception)
}
}
elseif (first())
{
printColor(vec(220, 255, 0), "[RailDriver]", vec(255, 255, 255), ": Initializing...")
RailDriverState = 1
}
# New RailDriver initialization sequence uses a state machine.
# This ensures that RailDriver initializes properly, even after a Dupe is loaded.
if (RailDriverState == 1)
{
local PIDCoefficientKp = 1020
local PIDCoefficientKi = 850
local PIDCoefficientKd = 250
local PIDCoefficientFFprimary = 100
local PIDCoefficientFFhillclimb = 5500
local PIDItermDecayRate = 0.3
local PIDItermDecayThreshold = 7.0 * 17.6
local PIDItermDecayHysteresis = 1
local PIDFeedforwardLimit = 20000
local PIDItermLimit = 15000
local PIDOutputLimit = 75000
local SpeedometerFilterCutoffFrequency = 1
local SpeedometerDeadband = 2.0
try
{
#include "e2shared/RailDriver/lib/ota/local"
#include "e2shared/RailDriver/lib/ota/remote"
#include "e2shared/RailDriver/lib/smartEntityManagement"
#include "e2shared/RailDriver/lib/sensors/ndof"
#include "e2shared/RailDriver/lib/sensors/speedometer"
#include "e2shared/RailDriver/lib/controls/playerControls"
#include "e2shared/RailDriver/lib/cli"
#include "e2shared/RailDriver/lib/pidf"
# Set the driver to the player who spawned the E2.
TrainDriver = owner()
# Initialize the command line interface with a prefix of ".raildriver".
CLI = cliInit(".raildriver")
if (CLI:count() == 0)
{
# An empty command line interface is not useful.
error("Failed to initialize the command line interface.")
}
# Enable the command line interface.
runOnChat(1)
# Initialize Smart Entity Management.
if (semInit())
{
if (!semParentToLocomotive())
{
error("Failed to parent E2 to locomotive.")
}
Trucks = semFindTrucks()
if (!semValidateTrucks(Trucks))
{
error("Locomotive trucks are not valid physics objects.")
}
}
else
{
error("RailDriver: Failed to initialize Smart Entity Management.")
}
# Initialize Speedometer.
SpeedAbs = 0
Speedo = speedometerInit(Trucks[1, entity], Trucks[2, entity])
if (Speedo:count() == 8)
{
speedometerSetFilterCutoffFrequency(Speedo, SpeedometerFilterCutoffFrequency)
speedometerSetDeadband(Speedo, SpeedometerDeadband * 17.6)
speedometerStart(Speedo)
}
else
{
error("RailDriver: Failed to initialize Speedometer.")
}
# Initialize NDOF Sensor.
NDOF = ndofInit(Trucks)
if (NDOF:count() > 0)
{
ndofStartSensorLoop(NDOF)
}
else
{
error("RailDriver: Failed to initialize NDOF Sensor.")
}
# Setup throttle and brake maps.
ThrottleMap = table()
ThrottleMap["Throttle Input Type", string] = "Velocity"
ThrottleMap["Velocity Setpoint", array] = array(0, 5, 15, 20, 30, 40, 60)
ThrottleMap["Acceleration Setpoint", array] = array(0, 0.5, 1, 1.5, 2, 2.5, 3)
ThrottleMap["Torque Setpoint", array] = array(0, 1000, 2000, 3000, 4000, 5000, 6000)
BrakeMap = table()
BrakeMap["Brake Input Type", string] = "Velocity"
BrakeMap["Velocity Setpoint", array] = array(0, 0, 0, 0, 0, 0, 0)
BrakeMap["Deceleration Setpoint", array] = array(0, -0.5, -1, -1.5, -2, -2.5, -3)
BrakeMap["Torque Setpoint", array] = array(0, -1000, -2000, -3000, -4000, -5000, -6000)
# Setup default key bindings.
local KeyboardControls = table()
KeyboardControls["Increase Reverser", string] = "W"
KeyboardControls["Decrease Reverser", string] = "S"
KeyboardControls["Increase Throttle", string] = "D"
KeyboardControls["Decrease Throttle", string] = "A"
KeyboardControls["Increase Brake", string] = "left ctrl + D"
KeyboardControls["Decrease Brake", string] = "left ctrl + A"
KeyboardControls["Emergency Brake", string] = "space"
KeyboardControls["Horn", string] = "H"
KeyboardControls["Bell", string] = "left alt"
KeyboardControls["Headlights", string] = "F"
KeyboardControls["Ditch Lights", string] = "left shift + F"
# Initialize Player Controls.
PlayerControls = playerControlsInit(KeyboardControls, ThrottleMap, BrakeMap, TrainDriver)
if (PlayerControls:count() == 0)
{
error("Failed to initialize Player Controls.")
}
Direction = 0
Throttle = 1
# Brake = 1
EmergencyBrake = 0
EmBrakePCFaultTimeoutSet = 0
# Initialize the PIDF Controller.
PIDF = pidCreateInstance()
if (PIDF:count() == 57)
{
HillClimbDescentData = array(0, 0, 0)
# Set the PIDF Controller's proportional, integral, & derivative coefficients.
assert(pidSetCoefficient(PIDF, "proportional", PIDCoefficientKp) == PIDCoefficientKp, "Failed to set the PIDF Controller's proportional coefficient.")
assert(pidSetCoefficient(PIDF, "integral", PIDCoefficientKi) == PIDCoefficientKi, "Failed to set the PIDF Controller's integral coefficient.")
assert(pidSetCoefficient(PIDF, "derivative", PIDCoefficientKd) == PIDCoefficientKd, "Failed to set the PIDF Controller's derivative coefficient.")
# Set the PIDF Controller's feedforward coefficients.
assert(pidSetCoefficient(PIDF, "primary feedforward", PIDCoefficientFFprimary) == PIDCoefficientFFprimary, "Failed to set the PIDF Controller's primary feedforward coefficient.")
assert(pidSetCoefficient(PIDF, "hill climb/descent feedforward", PIDCoefficientFFhillclimb) == PIDCoefficientFFhillclimb, "Failed to set the PIDF Controller's hill climb/descent feedforward coefficient.")
# Set the PIDF Controller's mode.
pidSetDirection(PIDF, Direction)
assert(pidSetMode(PIDF, "Automatic") == 1, "Failed to set the PIDF Controller's mode.")
# Set the PIDF Controller's limits.
assert(pidSetFeedforwardLimits(PIDF, -PIDFeedforwardLimit, PIDFeedforwardLimit) == 1, "Failed to set the PIDF Controller's feedforward limits.")
assert(pidSetItermDecay(PIDF, PIDItermDecayRate, PIDItermDecayThreshold, PIDItermDecayHysteresis) == 1, "Failed to set the PIDF Controller's integral decay.")
assert(pidSetItermLimits(PIDF, -PIDItermLimit, PIDItermLimit) == 1, "Failed to set the PIDF Controller's integral limits.")
assert(pidSetOutputLimits(PIDF, -PIDOutputLimit, PIDOutputLimit) == 1, "Failed to set the PIDF Controller's output limits.")
# Enable the PIDF Controller.
runOnTick(1)
}
else
{
error("Failed to initialize PIDF controller.")
}
# Initialize Local OTA Updates.
OTALocal = otaLocalInit()
if (OTALocal:count() == 0)
{
error("Failed to initialize local Over The Air (OTA) Updates.")
}
otaLocalLoadVersionFile(OTALocal)
# Initialize Online OTA Updates.
OTAOnline = otaOnlineInit()
assert(OTAOnline:count() != 0, "Failed to initialize online Over The Air (OTA) Updates.")
# Show the RailDriver welcome message.
if (cliPrintToChat(CLI, "info", "Welcome to RailDriver!\nType '.raildriver help' for a list of commands."))
{
timer("Chat Print", 2200)
}
Debugger = table()
timer("Debug", 100)
#[
Lock the E2, so that it can't be deleted or edited by anyone
except you.
This is not a security measure, as the E2 can still be
deleted or edited by you. It is only a convenience measure,
to prevent other users from accidentally or maliciously
deleting or editing the E2, which would cause RailDriver to
stop working.
You can still update the E2 by using the "Update" button in
the Remote Upload menu of the Expression 2 Tool Gun.
]#
semLockE2()
assert(semE2IsLocked(), "Failed to lock E2.")
RailDriverState = 2
}
catch (Exception)
{
RailDriverState = 0
stopAllTimers()
runOnKeys(TrainDriver, 0)
runOnTick(0)
printColor(vec(255, 0, 0), "[RailDriver | Init | Error]", vec(255, 255, 255), ": " + Exception)
}
}
# New RailDriver running state.
# This state is entered after RailDriver has been initialized successfully.
# If the initialization fails, RailDriver will not enter this state.
elseif (RailDriverState == 2)
{
if (clk(otaOnlineGetClockID(OTAOnline)))
{
try
{
otaOnlineSendRequestHandler(OTAOnline)
}
catch (Exception)
{
printColor(vec(255, 0, 0), "[RailDriver | Http | Error]", vec(255, 255, 255), ": " + Exception)
}
}
if (httpClk())
{
try
{
otaOnlineReceiveResponseHandler(OTAOnline)
}
catch (Exception)
{
printColor(vec(255, 0, 0), "[RailDriver | Http | Error]", vec(255, 255, 255), ": " + Exception)
}
}
if (clk(otaLocalGetClockID(OTALocal)))
{
try
{
otaLocalLoadFileHandler(OTALocal)
}
catch (Exception)
{
printColor(vec(255, 0, 0), "[RailDriver | File | Error]", vec(255, 255, 255), ": " + Exception)
}
}
if (fileClk())
{
try
{
otaLocalFileLoadedHandler(OTALocal)
}
catch (Exception)
{
printColor(vec(255, 0, 0), "[RailDriver | File | Error]", vec(255, 255, 255), ": " + Exception)
}
}
if (chatClk(TrainDriver))
{
# The in-game chat is used to send commands to the E2.
# This is, for all intents and purposes, a CLI.
if (cliProcessMessage(CLI, TrainDriver:lastSaid()))
{
# Commands are processed by the CLI.
# If the CLI returns true, then the command was processed successfully.
# All that needs to be done here is to check if each command was updated.
# All commands are case-insensitive.
if (cliHelpIsUpdated(CLI))
{
# The help command was updated.
# Print the help message to the chat.
local Message = ""
Message += "Commands:\n"
Message += "All commands are prefixed with '.raildriver',\n"
Message += "and are case-insensitive.\n"
Message += cliCommandExists(CLI, "help") ? "help - " + cliGetHelp(CLI, "help") + "\n" : ""
Message += cliCommandExists(CLI, "about") ? "about - " + cliGetHelp(CLI, "about") + "\n" : ""
Message += cliCommandExists(CLI, "controls") ? "controls - " + cliGetHelp(CLI, "controls") + "\n" : ""
Message += cliCommandExists(CLI, "restart") ? "restart - " + cliGetHelp(CLI, "restart") + "\n" : ""
Message += cliCommandExists(CLI, "update") ? "update - " + cliGetHelp(CLI, "update") + "\n" : ""
if (cliPrintToChat(CLI, "help", Message))
{
timer("Chat Print", 100)
}
}
elseif(cliAboutIsUpdated(CLI))
{
# The about command was updated.
# Print the about message to the chat.
if (cliPrintToChat(CLI, "about", otaLocalGetAboutMessage(OTALocal)))
{
timer("Chat Print", 100)
}
}
elseif (cliControlsIsUpdated(CLI))
{
# The controls command was updated.
# Print the controls message to the chat.
local Message = ""
Message += "Controls:\n"
Message += "Increase Reverser: " + playerControlsGetKeyBinding(PlayerControls, "Increase Reverser") + "\n"
Message += "Decrease Reverser: " + playerControlsGetKeyBinding(PlayerControls, "Decrease Reverser") + "\n"
Message += "Increase Throttle: " + playerControlsGetKeyBinding(PlayerControls, "Increase Throttle") + "\n"
Message += "Decrease Throttle: " + playerControlsGetKeyBinding(PlayerControls, "Decrease Throttle") + "\n"
Message += "Increase Brake: " + playerControlsGetKeyBinding(PlayerControls, "Increase Brake") + "\n"
Message += "Decrease Brake: " + playerControlsGetKeyBinding(PlayerControls, "Decrease Brake") + "\n"
Message += "Emergency Brake: " + playerControlsGetKeyBinding(PlayerControls, "Emergency Brake") + "\n"
#Message += "Horn: " + playerControlsGetKeyBinding(PlayerControls, "Horn") + "\n"
#Message += "Bell: " + playerControlsGetKeyBinding(PlayerControls, "Bell") + "\n"
#Message += "Ditch Lights: " + playerControlsGetKeyBinding(PlayerControls, "Ditch Lights") + "\n"
#Message += "Headlights: " + playerControlsGetKeyBinding(PlayerControls, "Headlights") + "\n"
if (cliPrintToChat(CLI, "controls", Message))
{
timer("Chat Print", 100)
}
}
elseif (cliRestartIsUpdated(CLI))
{
# The restart command was updated.
# Check if the locomotive is moving.
if (SpeedAbs > 0)
{
if (cliPrintToChat(CLI, "error", "Unable to restart RailDriver while the locomotive is moving."))
{
timer("Chat Print", 100)
}
}
# Locomotive has stopped. It is now safe to restart RailDriver.
else
{
# Restart the E2.
if (cliPrintToChat(CLI, "restart", "Restarting..."))
{
runOnChat(0)
runOnKeys(TrainDriver, 0)
stopAllTimers()
timer("Chat Print", 100)
timer("Restart", 1000)
}
}
}
elseif (cliUpdateIsUpdated(CLI))
{
# The update command was updated.
# Check if the locomotive is moving.
if (SpeedAbs > 0)
{
if (cliPrintToChat(CLI, "error", "Unable to update RailDriver while the locomotive is moving."))
{
timer("Chat Print", 100)
}
}
# The locomotive has stopped. It is now safe to update RailDriver.
else
{
# Get the arguments for the update command.
local Arguments = cliGetArguments(CLI, "update")
# Check if the argument is 'local'.
if (Arguments[1, string] == "local")
{
local Message = ""
Message += "Updating...\n"
stopAllTimers()
# Update the E2 using the local version.
# Formerly 'otaLocalUploadRailDriver(OTALocal)'
if (otaLocalUpdateRailDriver(OTALocal) == 1)
{
#runOnChat(0)
runOnTick(0)
runOnKeys(TrainDriver, 0)
timer("OTA Updates Watchdog", 10000)
}
else
{
Message += "Unable to update RailDriver.\n"
}
if (cliPrintToChat(CLI, "update", Message))
{
timer("Chat Print", 100)
}
}
# Check if the argument is 'online'.
elseif (Arguments[1, string] == "online")
{
local Message = ""
Message += "Online updates are a work in progress.\n"
Message += "Please wait for version 1.0.0-RC1.\n"
Message += "RailDriver is now waiting for the watchdog to expire...\n"
stopAllTimers()
# Update the E2 using the online version.
if (otaOnlineUpdateRailDriver(OTAOnline, OTALocal) == 1)
{
runOnChat(0)
runOnTick(0)
runOnKeys(TrainDriver, 0)
timer("OTA Updates Watchdog", 10000)
}
else
{
Message = "Unable to update RailDriver.\n"
}
if (cliPrintToChat(CLI, "error", Message))
{
timer("Chat Print", 100)
}
}
}
}
}
}
if (clk("OTA Updates Watchdog"))
{
# Update failed.
if (cliPrintToChat(CLI, "error", "Unable to update RailDriver.\nOTA Updates Watchdog triggered.\nPlease wait while RailDriver restarts..."))
{
timer("Chat Print", 100)
timer("Restart", 5000)
}
}
if (clk("Restart"))
{
# Restart the E2.
stopAllTimers()
reset()
}
if (clk("Chat Print"))
{
stoptimer("Chat Print")
if (playerCanPrint())
{
if (cliChatPrintHandler(CLI) == 1)
{
timer("Chat Print", 100)
}
}
else
{
timer("Chat Print", 500)
}
}
if (clk(ndofGetClockId(NDOF)))
{
try
{
ndofSensorLoop(NDOF)
local SensorValues = ndofGetSensorValues(NDOF)
assert(SensorValues:count() == 3, "Invalid sensor values.")
local Acceleration = SensorValues[1, vector]
local AngularVelocity = SensorValues[2, angle]
local Orientation = SensorValues[3, angle]
# Debug.
DbgAcceleration = Acceleration
DbgAngularVelocity = AngularVelocity
DbgOrientation = Orientation
# Calculate the track's grade in percent from the pitch of the locomotive's orientation.
local Gradient = 0
Gradient = tan(Orientation:pitch()) * 100
# Debug.
DbgGradient = round(Gradient, 4)
# Set the Gradient input to the Hill Climb/Descent Feedforward data.
HillClimbDescentData[2, number] = Gradient
}
catch(Exception)
{
ndofStopSensorLoop(NDOF)
printColor(vec(255, 0, 0), "[RailDriver | NDOF | Error]", vec(255, 255, 255), ": " + Exception)
}
}
if (clk(speedometerGetClockId(Speedo)))
{
try
{
speedometerClearAndRestartTimer(Speedo)
# Calculate the speed of the locomotive.
local SpeedRaw = 0
SpeedRaw = speedometerGetSpeed(Speedo)
# Apply a deadband & low-pass filter to the speed.
Speed = speedometerDeadband(Speedo, speedometerFilter(Speedo, SpeedRaw))
SpeedAbs = abs(Speed)
# Update the PIDF controller's process variable.
# This is the measured speed of the locomotive.
pidSetProcessVariable(PIDF, SpeedAbs)
# Set the Speed input to the Hill Climb/Descent Feedforward data.
HillClimbDescentData[1, number] = SpeedAbs
# Convert speed from Garry's Mod units to miles per hour.
SpeedMPH = round(toUnit("mph", SpeedAbs) * 4 / 3)
}
catch (Exception)
{
printColor(vec(255, 0, 0), "[RailDriver | Speedo | Error]", vec(255, 255, 255), ": " + Exception)
}
}
if (tickClk())
{
try
{
# Set the Hill Climb/Descent Feedforward input to the PIDF controller.
pidSetHillClimbDescentFeedforward(PIDF, HillClimbDescentData)
# Debug.
DbgHillClimbDescentFF = pidGetFFhillClimbDescent(PIDF)
# Calculate the PIDF controller's output.
pidCalculate(PIDF) # <--- This is where the magick happens. =^/,..,^=
# Get the PIDF controller's output.
# This is the throttle and brake values that will be applied to the locomotive.
local PIDFOutput = pidGetOutput(PIDF)
#[ Bypass all of this for now. ]#
#[
# Set the throttle and brake values based on the PIDF controller's output and the current reverser position.
if (Reverser == 1)
{
Throttle = PIDFOutput
Brake = 0
}
elseif (Reverser == -1)
{
Throttle = 0
Brake = PIDFOutput
}
else
{
Throttle = 0
Brake = 0
}
# Apply the throttle, brake, and reverser values to the locomotive's traction motors.
semControlTrucks(Trucks, Throttle, Brake, Reverser)
]#
# Set the brakes, if the train is not moving & the setpoint is 0.
# This is to prevent the train from rolling away. Fixes #65.
if (SpeedAbs == 0 & pidGetSetPoint(PIDF) == 0)
{
# Set the train brakes to 100%.
semDirectControlBrakes(Trucks, 1)
}
else
{
# Release the brakes, if the Emergency Brake is not active.
if (EmBrakeState == 0)
{
# Set the train brakes to 0%.
semDirectControlBrakes(Trucks, 0)
}
}
# Apply the PIDF Controller's output directly to the locomotive's traction motors.
if (!semDirectControlTrucks(Trucks, PIDFOutput))
{
#[
Notes from ZZ Cat:
When 'semDirectControlTrucks()' returns false, the control loop is disabled.
The E2 is also unlocked, so you can edit or remove it.
This is to prevent the E2 from being locked forever.
Through testing, I found a few things:
- If the trucks are removed from the locomotive, 'semDirectControlTrucks()' will return false.
& the speedometer will show an "Invalid entity!" error.
- If the entire locomotive is removed from the world, 'semDirectControlTrucks()' will return false.
& the error below will be printed.
]#
# If the E2 is locked, unlock it.
# This is to prevent the E2 from being locked forever.
runOnTick(0)
if (semE2IsLocked())
{
semUnlockE2()
}
# Print an error message.
error("Failed to apply PIDF controller's output to locomotive's traction motors.")
}
}
catch (Exception)
{
printColor(vec(255, 0, 0), "[RailDriver | PID | Error]", vec(255, 255, 255), ": " + Exception)
}
}
if (keyClk())
{
try
{
if (playerControlsUpdate(PlayerControls))
{
if (!playerControlsValid(PlayerControls, Speed))
{
error(playerControlsGetFaultMessage(PlayerControls))
}
if (playerControlsDirectionIsUpdated(PlayerControls))
{
Direction = playerControlsGetDirection(PlayerControls)
# Set the PIDF controller's direction.
pidSetDirection(PIDF, Direction)
# Set the Direction input to the Hill Climb/Descent Feedforward data.
HillClimbDescentData[3, number] = Direction
# Clear the Direction is Updated flag.
playerControlsClearDirectionIsUpdated(PlayerControls)
}
if (playerControlsThrottleIsUpdated(PlayerControls))
{
# Get the current throttle value.
Throttle = playerControlsGetThrottle(PlayerControls)
# Get the current velocity setpoint & convert it from miles per hour to Garry's Mod units.
local VelocitySetpoint = playerControlsGetThrottleMap(PlayerControls, "Velocity Setpoint", Throttle)
local VelocitySetpointGM = VelocitySetpoint * 17.6
# Set the PIDF controller's setpoint.
pidSetFeedforward(PIDF, "Throttle", VelocitySetpointGM)
pidSetSetPoint(PIDF, VelocitySetpointGM)
# Set the Velocity Setpoint input to the Hill Climb/Descent Feedforward data.
HillClimbDescentData[4, number] = VelocitySetpointGM
# Clear the Throttle is Updated flag.
playerControlsClearThrottleIsUpdated(PlayerControls)
}
if (playerControlsBrakeIsUpdated(PlayerControls))
{
# Brake = playerControlsGetBrake(PlayerControls)
# Brake currently is not used.
# So, I'm gonna let it silently do nothing. =^/.~=
# Clear the Brake is Updated flag.
playerControlsClearBrakeIsUpdated(PlayerControls)
}
if (playerControlsEmergencyBrakeIsUpdated(PlayerControls))
{
EmergencyBrake = playerControlsGetEmergencyBrake(PlayerControls)
# If the Emergency Brake is pressed, set the controller's setpoint to 0.
if (EmergencyBrake)
{
# Initialize the Emergency Brake Observer.
# The Emergency Brake's Observer Interval is 2 Hz.
EmBrakeState = 1
EmBrakeObserverTickInterval = 1000 / 2
timer("Emergency Brake", tickInterval())
}
# Clear the Emergency Brake is Updated flag.
playerControlsClearEmergencyBrakeIsUpdated(PlayerControls)
}
}
}
catch (Exception)
{
local ErrorColor = vec(255, 0, 0)
local ErrorText = "[RailDriver | PlyCtrls | Error]"
if (Exception:find("Fault Cleared."))
{
ErrorColor = vec(0, 255, 0)
ErrorText = "[RailDriver | PlyCtrls | Fault Cleared]"
if (EmBrakePCFaultTimeoutSet)
{
# Clear the Emergency Brake Observer.
stoptimer("Emergency Brake")
EmBrakeState = 0
# Clear the Emergency Brake is Active flag.
playerControlsClearEmergencyBrakeIsActive(PlayerControls)
}
}
else
{
if (!playerControlsEmergencyBrakeIsActive(PlayerControls))
{
if (!EmBrakePCFaultTimeoutSet)
{
# Initialize the Emergency Brake Observer.
# The Emergency Brake's Observer Interval is 2 Hz.
# The initial timeout is 5 seconds, to give the player time to reset the fault.
# After the timeout, the Emergency Brake will be automatically applied.
EmBrakeState = 1
EmBrakeObserverTickInterval = 1000 / 2
timer("Emergency Brake", 5000)
EmBrakePCFaultTimeoutSet = 1
# Set the Emergency Brake to active.
playerControlsSetEmergencyBrakeActive(PlayerControls)
}
}
}
printColor(ErrorColor, ErrorText, vec(255, 255, 255), ": " + Exception)
}
}
if (clk("Emergency Brake"))
{
stoptimer("Emergency Brake")
try
{
# Emergency Brake State Machine.
# This state machine is an observer that will monitor the locomotive's speed
# while the Emergency Brake is active.
# If the locomotive's speed is not decreasing, tougher measures will be taken.
# When the locomotive is stopped, the Emergency Brake will be released.
# There are 5 states:
# 1. The Emergency Brake is activated.
# 2. The locomotive's speed is decreasing... or is it?
# 3. The locomotive's speed is not decreasing. Apply the brakes to force the locomotive to stop.
# 4. The locomotive should be stopped by now. Release the Emergency Brake.
# 5. The locomotive still isn't stopped? Okay, freeze the entire train & shut RailDriver down.
# This is the last resort. Somehow, the locomotive is still moving.
# This is a safety measure to prevent the locomotive from derailing &/or causing a collision.
if (EmBrakeState == 1)
{
#[ STOP THE TRAIN!!! ]#
EmBrakePCFaultTimeoutSet = 0
# Get the current speed of the locomotive.
EmBrakeThisSpeed = SpeedAbs
EmBrakeLastSpeed = SpeedAbs
# Reset the Throttle & Brake values.
playerControlsResetThrottle(PlayerControls)
# Set the PIDF controller's setpoint & feedforward to 0.
pidSetFeedforward(PIDF, "Throttle", 0)
pidSetSetPoint(PIDF, 0)
# Set the Velocity Setpoint input to the Hill Climb/Descent Feedforward data.
HillClimbDescentData[4, number] = 0
# Set the Emergency Brake state to 2.
EmBrakeState = 2
# Restart the Emergency Brake timer.
timer("Emergency Brake", EmBrakeObserverTickInterval)
}
# Emergency Brake state 2.
# This state is used to monitor the locomotive's speed to ensure that the locomotive is stopping.
# If the locomotive's speed is not decreasing, the Emergency Brake state is set to 3.
# If the locomotive is stopped, the Emergency Brake state is set to 4.
elseif (EmBrakeState == 2)
{
#[ I HOPE IT STOPS! ]#
# Get the current speed of the locomotive.
EmBrakeThisSpeed = SpeedAbs
# If the locomotive's speed is not decreasing, set the Emergency Brake state to 3.
if (EmBrakeThisSpeed >= EmBrakeLastSpeed)
{
EmBrakeState = 3
}
# If the locomotive is stopped, set the Emergency Brake state to 4.
elseif (EmBrakeThisSpeed == 0)
{
EmBrakeState = 4
}
# Set the last speed to the current speed.
EmBrakeLastSpeed = EmBrakeThisSpeed
# Restart the Emergency Brake timer.
timer("Emergency Brake", EmBrakeObserverTickInterval)
}
# Emergency Brake state 3.
# This state disables the PIDF controller, sets the locomotive's traction motors to 0, &
# uses the locomotive's brakes to stop the locomotive.
# If the locomotive is stopped, the Emergency Brake state is set to 4.
# If the locomotive's speed still is not decreasing, tougher measures are taken.
elseif (EmBrakeState == 3)
{
#[ I WASN'T ASKING!!! ]#
# Get the current speed of the locomotive.
EmBrakeThisSpeed = SpeedAbs
# If the locomotive is stopped, set the Emergency Brake state to 4.
if (EmBrakeThisSpeed == 0)
{
EmBrakeState = 4
}
# If the locomotive's speed still is not decreasing, set the Emergency Brake state to 5.
elseif (EmBrakeThisSpeed >= EmBrakeLastSpeed)
{
EmBrakeState = 5
}
# Set the last speed to the current speed.
EmBrakeLastSpeed = EmBrakeThisSpeed
# Disable the PIDF controller.
pidSetMode(PIDF, "Manual")
pidSetOutput(PIDF, 0)
runOnTick(0)
# Set the locomotive's traction motors to 0.
semDirectControlTrucks(Trucks, 0)
# Set the locomotive's brakes to 100%.
semDirectControlBrakes(Trucks, 2)
# Restart the Emergency Brake timer.
timer("Emergency Brake", EmBrakeObserverTickInterval)
}
# Emergency Brake state 4.
# This state releases the locomotive's brakes & re-enables the PIDF controller.
# But first, it needs to ensure that the locomotive is stopped.
# Then, it verifies that the locomotive is stopped.
# If the locomotive is stopped, the Emergency Brake state is set to 0.
# In this state, do the following:
# - The Emergency Brake is released.
# - The locomotive's traction motors are set to 0.
# - The locomotive's brakes are set to 0.
# - The PIDF controller is re-enabled.
# Otherwise, if the locomotive is not stopped, the Emergency Brake state is set to 5.
# Here, I am using the EmBrakeState to determine what the next action should be.
elseif (EmBrakeState == 4)
{
#[ YOU SHOULD HAVE LISTENED TO ME!!! ]#
# Get the current speed of the locomotive.
EmBrakeThisSpeed = SpeedAbs
# If the locomotive is stopped, set the Emergency Brake state to 0.
if (EmBrakeThisSpeed == 0)
{
EmBrakeState = 0
}
# If the locomotive is not stopped, set the Emergency Brake state to 5.
elseif (EmBrakeThisSpeed >= EmBrakeLastSpeed)
{
EmBrakeState = 5
}
# Set the last speed to the current speed.
EmBrakeLastSpeed = EmBrakeThisSpeed
# If the locomotive is stopped, release the Emergency Brake.
if (EmBrakeState == 0)