This repository has been archived by the owner on May 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 525
/
AIDriver.lua
2325 lines (2021 loc) · 88.1 KB
/
AIDriver.lua
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 file is part of Courseplay (https://github.com/Courseplay/courseplay)
Copyright (C) 2019 Peter Vaiko
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
]]
--[[
This is the base class of all AI drivers (modes) and implements MODE_TRANSPORT (5),
using the PurePursuitController (PPC). It replaces the code in drive.lua and has the
basic functionality:
• Drive a course
• Drive turn maneuvers
• Add an alignment when needed before starting the course (this is a lot easier now as
it just initializes the PPC with the alignment course and after that is finished, initializes
it with the regular course)
• Restarts or finishes the course at the last waypoint.
• Uses reverse.lua to reverse with a trailer but can reverse single vehicles.
• Has collision detection enabled by default
The AIDriver class implements all functionality common to all modes (like lights, covers, etc.).
Mode specific functions should all go into the derived classes. AIDriver MUST NOT HAVE any
IF statements with things like cp.mode == x!
Start/Stop
----------
Start the AIDriver with calling start(), stop it with dismiss().
If you implement your own start() and don't call AIDriver.start() then make sure you call
beforeStart() to perform some essential initialization.
Drive
-----
Call drive() in each update loop. Like with start() if you implement your own drive() function
it is a good idea to call AIDriver.drive() from that once you did your derived class specific
stuff. If you don't call AIDriver.drive() make sure you call at least self.ppc:update() at the
beginning of the function and resetSpeed() just before leaving drive() these are essential for
the AIDriver.
For some more control you can use any one of the drive*() function but driveVehicleToLocalPosition()
must always be called either through these or directly to do the actual driving.
Speed Control
-------------
The general idea is that the AIDriver follows the current course by steering the vehicle and switching to
forward or reverse. Then, based on various conditions we regulate the driving speed, for example to
stop for refill or wait for the implements to unfold, etc.
There are two functions provided to control the speed: hold() and setSpeed(). At the end of every loop
these are reset so if you don't do anything, the AIDriver will keep driving with the recorded speed.
If you want to momentarily stop the vehicle, you'll have to call hold() in every loop as long as you
don't want it to move (this will set allowedToDrive = false and stop abruptly). You can also stop the
vehicle by setting the speed to 0, this will just let it roll until it stops without applying the brake.
Likewise, if you want to drive with any speed different than the recorded one you have to call setSpeed()
at least once during the update loop, before driveVehicleToLocalPosition() is called. You can call
setSpeed() multiple times in a loop, the AIDriver will apply the lowest value set in the loop.
Triggering Position Based Events
--------------------------------
If you need to control your vehicle based on its position on the course please use the callback provided
by the PPC (like onWaypointPassed()) or the functions of the Course() class like hasUnloadPointAround())
and never the waypoints directly.
Displaying Messages
-------------------
Use setInfoText(<message>) to display a message where message is one of the globalInfoText.msgReference
entries. You can set it in each loop or set it once the condition (like NEEDS_UNLOADING) emerges. A message
turned on by calling setInfoText() will be shown until clearInfoText(<message>) is called again or the
helper is dismissed.
You can add multiple messages to display by calling setInfoText() multiple times with different messages.
Make sure to call updateInfoText() in each cycle to display the current message texts.
Note:
If the AIDriver does not seem to have the functionality you need please contact me, we'll figure something out.
Peter
]]
---@class AIDriver
AIDriver = CpObject()
-- steering angle (normalized, between 0 and 1) over which the speed is reduced
AIDriver.slowAngleLimit = 0.3
AIDriver.slowAcceleration = 0.5
AIDriver.slowDownFactor = 0.5
-- Proximity sensor
-- how far the sensor can see
AIDriver.proximitySensorRange = 10
-- the sensor will proportionally reduce speed when objects are in range down to this limit (won't set a speed lower than this)
AIDriver.proximityMinLimitedSpeed = 2
-- if anything closer than this, we stop
AIDriver.proximityLimitLow = 1.5
-- if anything closer than this, we reverse
AIDriver.proximityLimitReverse = 1
-- an obstacle is considered ahead of us if the reported angle is less then this
-- (and we won't stop or reverse if the angle is higher than this, thus obstacles to the left or right)
AIDriver.proximityAngleAheadDeg = 45
-- default slow down distance before last waypoint
AIDriver.defaultSlowDownDistanceBeforeLastWaypoint = 15
AIDriver.APPROACH_AUGER_TRIGGER_SPEED = 3
AIDriver.EMERGENCY_BRAKE_FORCE = 1000000
-- we use this as an enum
AIDriver.myStates = {
TEMPORARY = {}, -- Temporary course, dynamically generated, for example alignment or fruit avoidance
RUNNING = {},
STOPPED = {},
STOPPED_AT_WAIT_POINT = {}, -- Is the driver stopped at an waypoint.
FINISHED = {} -- Driver has finished it's course/job.
}
--- Create a new driver (usage: aiDriver = AIDriver(vehicle)
-- @param vehicle to drive. Will set up a course to drive from vehicle.Waypoints
function AIDriver:init(vehicle)
courseplay.debugVehicle(courseplay.DBG_AI_DRIVER,vehicle,'AIDriver:init()')
self.debugChannel = courseplay.DBG_MODE_5
self.mode = courseplay.MODE_TRANSPORT
self.states = {}
self:initStates(AIDriver.myStates)
self.vehicle = vehicle
-- set up a global container on the vehicle to persist AI Driver related data between AIDriver incarnations
if not vehicle.cp.aiDriverData then
vehicle.cp.aiDriverData = {}
end
self.aiDriverData = vehicle.cp.aiDriverData
self:debug('creating AIDriver')
self.settings = self.vehicle.cp.settings
self.courseGeneratorSettings = self.vehicle.cp.courseGeneratorSettings
-- make sure all vehicle settings are valid for this mode
if self.settings then
self:debug('Validating current settings...')
self.settings:validateCurrentValues()
end
---@type PurePursuitController
self.ppc = PurePursuitController(self.vehicle)
self.vehicle.cp.ppc = self.ppc
self.ppc:registerListeners(self, 'onWaypointPassed', 'onWaypointChange')
self.ppc:enable()
self.nextWpIx = 1
self.acceleration = 1
self.state = self.states.STOPPED
self.debugTicks = 100 -- show sparse debug information only at every debugTicks update
-- AIDriver and its derived classes set the self.speed in various locations in
-- the code and then getSpeed() will pass that on to AIDriver.driveCourse.
self.speed = 0
-- same for allowedToDrive, is reset at the end of each loop to true and needs to be set to false
-- if someone wants to stop by calling hold()
self.allowedToDrive = true
self.collisionDetectionEnabled = true
self.trafficConflictDetectionEnabled = true
self.collisionDetector = nil
-- list of active messages to display
self.activeMsgReferences = {}
self:setHudContent()
---@type TriggerHandler
self.triggerHandler = TriggerHandler(self,self.vehicle,self:getSiloSelectedFillTypeSetting())
self.triggerHandler:enableFuelLoading()
---@type TriggerSensor
self.triggerSensor = TriggerSensor(self,self.vehicle)
end
---This function is called once on the first update tick,
---for post setup possibilities.
function AIDriver:postInit()
end
function AIDriver:updateLoadingText()
local fillableObject = self.triggerHandler.fillableObject
if fillableObject then
local fillLevel = fillableObject.object:getFillUnitFillLevel(fillableObject.fillUnitIndex)
local fillCapacity = fillableObject.object:getFillUnitCapacity(fillableObject.fillUnitIndex)
if fillLevel and fillCapacity then
if fillableObject.isLoading then
courseplay:setInfoText(self.vehicle, string.format("COURSEPLAY_LOADING_AMOUNT;%d;%d",math.floor(fillLevel),fillCapacity))
else
courseplay:setInfoText(self.vehicle, string.format("COURSEPLAY_UNLOADING_AMOUNT;%d;%d",math.floor(fillLevel),fillCapacity))
end
end
end
end
function AIDriver:writeUpdateStream(streamId, connection, dirtyMask)
self.triggerHandler:writeUpdateStream(streamId)
if self.state ~= self.stateSend then
streamWriteBool(streamId,true)
streamWriteString(streamId,self.state.name)
self.stateSend = self.state
else
streamWriteBool(streamId,false)
end
if self.active ~= self.activeSend then
streamWriteBool(streamId,true)
streamWriteBool(streamId,self.active or false)
self.activeSend = self.active
else
streamWriteBool(streamId,false)
end
end
function AIDriver:readUpdateStream(streamId, timestamp, connection)
self.triggerHandler:readUpdateStream(streamId)
if streamReadBool(streamId) then
local nameState = streamReadString(streamId)
self.state = self.states[nameState]
end
if streamReadBool(streamId) then
self.active = streamReadBool(streamId)
end
end
function AIDriver:onWriteStream(streamId)
streamWriteString(streamId,self.state.name)
streamWriteBool(streamId,self.active or false)
end
function AIDriver:onReadStream(streamId)
local nameState = streamReadString(streamId)
self.state = self.states[nameState]
self.active = streamReadBool(streamId)
end
function AIDriver:setHudContent()
courseplay.hud:setAIDriverContent(self.vehicle)
end
-- destructor. The reason for having this is the collisionDetector which creates nodes and
-- we want those nodes removed when the AIDriver instance is deleted.
function AIDriver:delete()
self:debug('delete AIDriver')
self:deleteCollisionDetector()
end
function AIDriver:deleteCollisionDetector()
if self.collisionDetector then
self.collisionDetector:delete()
end
self.collisionDetector = nil
end
--- Aggregation of states from this and all descendant classes
function AIDriver:initStates(states)
for key, state in pairs(states) do
self.states[key] = {name = tostring(key), properties = state}
end
end
function AIDriver:getMode()
return self.mode
end
--- If you have your own start() implementation and you do not call AIDriver.start() then
-- make sure this is called from the derived start() to initialize all common stuff
function AIDriver:beforeStart()
self.active = true
self.nextCourse = nil
if self.collisionDetector == nil then
self.collisionDetector = CollisionDetector(self.vehicle)
end
self.normalBrakeForce = self.vehicle.spec_motorized.brakeForce
self:setBackMarkerNode(self.vehicle)
self:setFrontMarkerNode(self.vehicle)
self:startEngineIfNeeded()
self.firstReversingWheeledWorkTool = courseplay:getFirstReversingWheeledWorkTool(self.vehicle)
-- for now, pathfinding generated courses can't be driven by towed tools
self.allowReversePathfinding = self.firstReversingWheeledWorkTool == nil
if self.vehicle:getAINeedsTrafficCollisionBox() then
courseplay.debugVehicle(courseplay.DBG_TRAFFIC,self.vehicle,"Making sure cars won't stop around us")
-- something deep inside the Giants vehicle sets the translation of this box to whatever
-- is in aiTrafficCollisionTranslation, if you do a setTranslation() it won't remain there...
self.vehicle.spec_aiVehicle.aiTrafficCollisionTranslation[2] = -1000
end
self.triggerHandler:onStart()
self:createTrafficConflictDetector()
-- add a proximity sensor to the front by default
self:addForwardProximitySensor()
self:enableProximitySpeedControl()
self:enableProximitySwerve()
---Reset Moved distance on start.
self.movedDistance = 0
end
--- Start driving
--- @param startingPoint number, one of StartingPointSetting.START_AT_* constants
function AIDriver:start(startingPoint)
self:beforeStart()
self.state = self.states.RUNNING
-- derived classes must disable collision detection if they don't need it
self:enableCollisionDetection()
-- for now, initialize the course with the vehicle's current course
-- main course is the one generated/loaded/recorded
self.mainCourse = Course(self.vehicle, self.vehicle.Waypoints)
local ix = self.mainCourse:getStartingWaypointIx(AIDriverUtil.getDirectionNode(self.vehicle), startingPoint)
self:info('AI driver in mode %d starting at %d/%d waypoints (%s)',
self:getMode(), ix, self.mainCourse:getNumberOfWaypoints(), tostring(startingPoint))
self:startCourseWithAlignment(self.mainCourse, ix)
end
--- Dismiss the driver
function AIDriver:dismiss()
if self.collisionDetector then
self.collisionDetector:reset() -- restore the default direction of the colli boxes
end
---disable turn lights and beacon lights
self.vehicle:setBeaconLightsVisibility(false)
self.vehicle:setTurnLightState(Lights.TURNLIGHT_OFF)
self:clearAllInfoTexts()
self:stop()
self.active = false
if self.trafficConflictDetector then
self.trafficConflictDetector:delete()
self.trafficConflictDetector = nil
end
end
--- Is the driver started?
function AIDriver:isActive()
return self.active
end
--- Stop the driver
--- @param msgReference string as defined in globalInfoText.msgReference
function AIDriver:stop(msgReference)
self:deleteCollisionDetector()
self.triggerHandler:onStop()
-- not much to do here, see the derived classes
self:setInfoText(msgReference)
self.state = self.states.STOPPED
-- deactivate pathfinder
self.pathfinder = nil
end
function AIDriver:stopAtWaitPoint()
self:setInfoText("WAIT_POINT")
self.state = self.states.STOPPED_AT_WAIT_POINT
end
--- Stop the driver when the work is done. Could just dismiss at this point,
--- the only reason we are still active is that we are displaying the info text while waiting to be dismissed
function AIDriver:setWorkFinished(msgReference)
self:deleteCollisionDetector()
self.triggerHandler:onStop()
self:setInfoText(msgReference)
self.state = self.states.FINISHED
end
function AIDriver:continue()
self:debug('Continuing...')
self.state = self.states.RUNNING
self.triggerHandler:onContinue()
-- can be stopped for various reasons and those can have different msgReferences, so
-- just remove all, if there's a condition which requires a message it'll call setInfoText() again anyway.
self:clearAllInfoTexts()
end
--- Compatibility function for the legacy CP code so the course can be resumed
-- at the index as originally was in vehicle.Waypoints.
function AIDriver:resumeAtOriginalIx(cpIx)
local i = self.course:findOriginalIx(cpIx)
self:debug('resumeAtOriginalIx %d (legacy) %d (AIDriver', cpIx, i)
self.ppc:initialize(i)
end
function AIDriver:resumeAt(ix)
self.ppc:initialize(ix)
end
--- @param msgReference string as defined in globalInfoText.msgReference
function AIDriver:setInfoText(msgReference)
if msgReference then
self:debugSparse('set info text to %s', msgReference)
self.activeMsgReferences[msgReference] = true
end
end
--- @param msgReference string as defined in globalInfoText.msgReference
function AIDriver:clearInfoText(msgReference)
if msgReference then
self.activeMsgReferences[msgReference] = nil
end
end
function AIDriver:clearAllInfoTexts()
self.activeMsgReferences = {}
end
-- This has to be called in each update cycle to show messages
function AIDriver:updateInfoText()
for msg, _ in pairs(self.activeMsgReferences) do
g_globalInfoTextHandler:setInfoText(self.vehicle, msg)
end
end
--- Displays an one time ingame warning.
---@param msgReference string this can be a global info text or just a translation text.
function AIDriver:displayWarning(msgReference)
local infoTexts = g_globalInfoTextHandler:getInfoTexts()
local msg = infoTexts[msgReference] and infoTexts[msgReference].text or msgReference
local text = string.format("%s: %s",nameNum(self.vehicle),courseplay:loc(msg))
g_currentMission:addIngameNotification(FSBaseMission.INGAME_NOTIFICATION_CRITICAL, text)
end
--- Update AI driver, everything that needs to run in every loop
function AIDriver:update(dt)
self:updatePathfinding()
self:drive(dt)
self:checkIfBlocked()
self:detectSlipping()
self:resetSpeed()
self:updateLoadingText()
self.triggerHandler:onUpdate(dt)
self.triggerSensor:onUpdate(dt)
self:shouldDriverBeReleased()
self:updateDistanceMovedSinceStart()
end
---Update moved distance since start.
function AIDriver:updateDistanceMovedSinceStart()
self.movedDistance = self.movedDistance + self.vehicle.lastMovedDistance
end
---Gets the moved distance since start.
function AIDriver:getDistanceMovedSinceStart()
return self.movedDistance
end
--- UpdateTick AI driver
function AIDriver:updateTick(dt)
self.triggerHandler:onUpdateTick(dt)
end
--check if we should stop Driver completely
function AIDriver:shouldDriverBeReleased()
--override from FieldWorkAIDriver
end
--- Main driving function
-- should be called from update()
-- This base implementation just follows the waypoints, anything more than that
-- should be implemented by the derived classes as needed.
function AIDriver:drive(dt)
-- update current waypoint/goal point
self.ppc:update()
-- collision detection
self:detectCollision(dt)
self:updateInfoText()
if self.state == self.states.STOPPED or self.triggerHandler:isLoading() or self.triggerHandler:isUnloading() then
self:hold()
end
if self.state == self.states.FINISHED then
self:holdWithFuelSave()
end
if self:isWaitingAtWaitPoint() then
self:holdWithFuelSave()
self:continueIfWaitTimeIsOver()
end
self:driveCourse(dt)
self:drawTemporaryCourse()
end
--- Normal driving according to the course waypoints, using courseplay:goReverse() when needed
-- to reverse with trailer.
function AIDriver:driveCourse(dt)
self:updateLights()
-- stop for fuel if needed
if not self:isFuelLevelOk() then
self:holdWithFuelSave()
end
if not self:getIsEngineReady() then
if self:getSpeed() > 0 and self.allowedToDrive then
self:startEngineIfNeeded()
self:hold()
self:debugSparse('Wait for the engine to start')
end
end
-- use the recorded speed by default
if not self:hasTipTrigger() then
self:setSpeed(self:getRecordedSpeed())
end
if self.triggerHandler:isInTrigger() or self.triggerSensor:isNearTriggers() then
self:setSpeed(self.vehicle.cp.speeds.approach)
end
self:slowDownForWaitPoints()
self:stopEngineIfNotNeeded()
self:updateTrafficConflictDetector(self.course, self.ppc:getRelevantWaypointIx(), self:getSpeed())
-- check if reversing
local lx, lz, moveForwards, isReverseActive = self:getReverseDrivingDirection()
if isReverseActive then
-- we go wherever goReverse() told us to go
self:driveVehicleInDirection(dt, self.allowedToDrive, moveForwards, lx, lz, self:getSpeed())
else
-- use the PPC goal point when forward driving or reversing without trailer
local gx, _, gz = self.ppc:getGoalPointLocalPosition()
self:driveVehicleToLocalPosition(dt, self.allowedToDrive, moveForwards, gx, gz, self:getSpeed())
end
end
--- Drive to a local position. This is the simplest driving mode towards the goal point
function AIDriver:driveVehicleToLocalPosition(dt, allowedToDrive, moveForwards, gx, gz, maxSpeed)
-- gx and gz are vehicle local coordinates of the point we want the vehicle drive to.
-- AIVehicleUtil.driveToPoint() does not seem to be able to handle the cases where:
-- 1. this point is too far and/or
-- 2. this point is behind the vehicle.
-- In those case it drives the vehicle on a very large radius arc. Until we clarify why this happens,
-- we adjust these coordinates to make sure the vehicle turns towards the point as soon as possible.
local ax, az = gx, gz
local l = MathUtil.vector2Length(gx, gz)
local maxDrivingVectorLength = self.settings.turnDiameter:get()
if l > maxDrivingVectorLength then
-- point too far, bring it closer so the AI driver will start steer towards it
ax = gx * maxDrivingVectorLength / l
az = gz * maxDrivingVectorLength / l
end
if (moveForwards and gz < 0) or (not moveForwards and gz > 0) then
-- make sure point is not behind us (no matter if driving reverse or forward)
az = 0
end
if AIDriverUtil.isReverseDriving(self.vehicle) then
self:debugSparse('reverse driving, reversing steering')
ax = -ax
end
-- TODO: remove allowedToDrive parameter and only use self.allowedToDrive
if not self.allowedToDrive then allowedToDrive = false end
maxSpeed, allowedToDrive, moveForwards = self:checkSafetyConstraints(maxSpeed, allowedToDrive, moveForwards)
-- driveToPoint does not like speeds under 1.5 (will stop) so make sure we set at least 2
if maxSpeed > 0.01 and maxSpeed < 2 then
maxSpeed = 2
end
self:debugSparse('Speed = %.1f, gx=%.1f gz=%.1f l=%.1f ax=%.1f az=%.1f allowed=%s fwd=%s', maxSpeed, gx, gz, l, ax, az,
allowedToDrive, moveForwards)
if self.collisionDetector then
self.collisionDetector:update(self.course, self.ppc:getCurrentWaypointIx(), ax, az)
end
AIVehicleUtil.driveToPoint(self.vehicle, dt, self.acceleration, allowedToDrive, moveForwards, ax, az, maxSpeed, false)
end
--[[ emergency brake, maybe for mode 4/8 refill at trigger ??
local oldFunc = self.vehicle.getBrakeForce
self.vehicle.getBrakeForce = function () return 10000000 end
AIVehicleUtil.driveToPoint(self.vehicle, dt, self.acceleration, allowedToDrive, moveForwards, ax, az, maxSpeed, false)
self.vehicle.getBrakeForce = oldFunc
]]--
-- many courseplay modes control the vehicle through the lx/lz normalized local directions.
-- this is an interface for those modes to drive the vehicle.
function AIDriver:driveVehicleInDirection(dt, allowedToDrive, moveForwards, lx, lz, maxSpeed)
-- construct an artificial goal point to drive to
local gx, gz = lx * self.ppc:getLookaheadDistance(), lz * self.ppc:getLookaheadDistance()
self:driveVehicleToLocalPosition(dt, allowedToDrive, moveForwards, gx, gz, maxSpeed)
end
--- Drive vehicle by using a steering angle. This is similar to the Giants AIVehicleUtil.driveInDirection() but
--- instead of the direction (lx, lz) uses a steering angle.
--- @param dt number dt
--- @param moveForwards boolean if true, we want the vehicle to move forwards, false for backwards
--- @param steeringAngleNormalized number between 0 and 1, 1 being the maximum steering angle.
--- @param turnLeft boolean true when turning to the left
--- @param maxSpeed number speed we want the vehicle to drive
function AIDriver:driveVehicleBySteeringAngle(dt, moveForwards, steeringAngleNormalized, turnLeft, maxSpeed)
if not moveForwards then
turnLeft = not turnLeft;
end
-- flip it again if in reverse driving vehicle
if AIDriverUtil.isReverseDriving(self.vehicle) then
turnLeft = not turnLeft;
end
local targetRotTime = 0;
if turnLeft then
--rotate to the left
targetRotTime = self.vehicle.maxRotTime*math.min(steeringAngleNormalized, 1);
else
--rotate to the right
targetRotTime = self.vehicle.minRotTime*math.min(steeringAngleNormalized, 1);
end
if targetRotTime > self.vehicle.rotatedTime then
self.vehicle.rotatedTime = math.min(self.vehicle.rotatedTime + dt*self.vehicle:getAISteeringSpeed(), targetRotTime);
else
self.vehicle.rotatedTime = math.max(self.vehicle.rotatedTime - dt*self.vehicle:getAISteeringSpeed(), targetRotTime);
end
if self.vehicle.firstTimeRun then
local acc = self.acceleration;
maxSpeed, self.allowedToDrive, moveForwards = self:checkSafetyConstraints(maxSpeed, self.allowedToDrive, moveForwards)
if maxSpeed ~= nil and maxSpeed ~= 0 then
if steeringAngleNormalized >= self.slowAngleLimit then
maxSpeed = maxSpeed * self.slowDownFactor;
end
self.vehicle.spec_motorized.motor:setSpeedLimit(maxSpeed);
if self.vehicle.spec_drivable.cruiseControl.state ~= Drivable.CRUISECONTROL_STATE_ACTIVE then
self.vehicle:setCruiseControlState(Drivable.CRUISECONTROL_STATE_ACTIVE);
end
else
if steeringAngleNormalized >= self.slowAngleLimit then
acc = self.slowAcceleration;
end
end
if not self.allowedToDrive or math.abs(maxSpeed) < 0.0001 then
acc = 0;
end
if not moveForwards then
acc = -acc;
end
local node = moveForwards and self:getFrontMarkerNode(self.vehicle) or self:getBackMarkerNode(self.vehicle)
self:updateTrafficConflictDetector(nil, nil, maxSpeed, moveForwards, node)
WheelsUtil.updateWheelsPhysics(self.vehicle, dt, self.vehicle.lastSpeedReal*self.vehicle.movingDirection, acc, not self.allowedToDrive, true)
end
end
-- node pointing in the direction the driver is facing, even in case of reverse driving tractors
function AIDriver:getDirectionNode()
return AIDriverUtil.getDirectionNode(self.vehicle)
end
--- Start a course and continue with nextCourse at ix when done
---@param tempCourse Course
---@param nextCourse Course
---@param ix number
function AIDriver:startCourse(course, ix, nextCourse, nextWpIx)
if nextWpIx then
self:debug('Starting a course, at waypoint %d, will continue at waypoint %d afterwards.', ix, nextWpIx)
else
self:debug('Starting a course, at waypoint %d, no next course set.', ix)
end
self.nextWpIx = nextWpIx
self.nextCourse = nextCourse
self.course = course
self.ppc:setCourse(self.course)
self.ppc:initialize(ix)
end
function AIDriver:getCurrentCourse()
return self.course
end
--- Start course (with alignment if needed) and set course as the current one
---@param course Course
---@param ix number
---@return boolean true when an alignment course was added
function AIDriver:startCourseWithAlignment(course, ix)
local alignmentCourse
if self:isAlignmentCourseNeeded(course, ix) then
alignmentCourse = self:setUpAlignmentCourse(course, ix)
end
if alignmentCourse then
self:startCourse(alignmentCourse, 1, course, ix)
else
self:startCourse(course, ix)
end
return alignmentCourse
end
--- Do whatever is needed after switching to the next course
function AIDriver:onNextCourse()
-- nothing in general, derived classes will implement when needed
end
--- Should we stop at the end of the course (or restart it from the beginning)
--- In Mode 5 we do what the user wants.
function AIDriver:shouldStopAtEndOfCourse()
return self.settings.stopAtEnd:is(true)
end
--- Course ended
function AIDriver:onEndCourse()
if self.settings.autoDriveMode:useForParkVehicle() then
-- use AutoDrive to send the vehicle to its parking spot
if self.vehicle.spec_autodrive and self.vehicle.spec_autodrive.GetParkDestination then
self:debug('Let AutoDrive park this vehicle')
-- we are not needed here anymore
courseplay.onStopCpAIDriver(self.vehicle,AIVehicle.STOP_REASON_REGULAR)
-- TODO: encapsulate this in an AutoDriveInterface class
local parkDestination = self.vehicle.spec_autodrive:GetParkDestination(self.vehicle)
self.vehicle.spec_autodrive:StartDrivingWithPathFinder(self.vehicle, parkDestination, -3, nil, nil, nil)
end
elseif self:shouldStopAtEndOfCourse() then
self:onEndCourseFinished()
else
-- continue at the first waypoint
self.ppc:initialize(1)
end
end
function AIDriver:onEndCourseFinished()
self:setWorkFinished('END_POINT')
end
function AIDriver:getDirectionToGoalPoint()
-- goal point to drive to
local gx, gy, gz = self.ppc:getGoalPointPosition()
-- direction to the goal point
return AIVehicleUtil.getDriveDirection(self:getDirectionNode(), gx, gy, gz);
end
--- Get the goal point when courseplay:goReverse is driving.
-- if isReverseActive is false, use the returned gx, gz for driveToPoint, otherwise get them
-- from PPC
function AIDriver:getReverseDrivingDirection()
local moveForwards = true
local isReverseActive = false
-- get the direction to drive to
local lx, lz = self:getDirectionToGoalPoint()
-- take care of reversing
if self.ppc:isReversing() then
-- TODO: currently goReverse() calls ppc:initialize(), this is not really transparent,
-- should be refactored so it returns a status telling us to drive forward from waypoint x instead.
lx, lz, moveForwards, isReverseActive = courseplay:goReverse(self.vehicle, lx, lz)
-- as of now we need to invert the direction from goReverse to work correctly with
-- AI Driver, it seems to have a different reference
lx, lz = -lx, -lz
self:setSpeed(self.vehicle.cp.speeds.reverse or self.vehicle.cp.speeds.crawl)
end
return lx, lz, moveForwards, isReverseActive
end
function AIDriver:onWaypointChange(newIx)
-- for backwards compatibility, we keep the legacy CP waypoint index up to date
courseplay:setWaypointIndex(self.vehicle, self.ppc:getCurrentOriginalWaypointIx())
-- rest is implemented by the derived classes
end
function AIDriver:onWaypointPassed(ix)
self:debug('onWaypointPassed %d', ix)
--- Check if we are at the last waypoint and should we continue with first waypoint of the course
-- or stop.
if ix == self.course:getNumberOfWaypoints() then
self:onLastWaypoint()
elseif self:isStoppingAtWaitPointAllowed() and self.course:isWaitAt(ix) then
-- default behaviour for mode 5 (transport), if a waypoint with the wait attribute is
-- passed stop until the user presses the continue button or the timer elapses
self:debug('Waiting point reached, wait time %d s', self.settings.waitTime:get())
self:stopAtWaitPoint()
-- show continue button
self:refreshHUD()
end
end
function AIDriver:isStoppingAtWaitPointAllowed()
return true
end
function AIDriver:onLastWaypoint()
if self.nextCourse then
self:continueOnNextCourse(self.nextCourse, self.nextWpIx)
else
self:debug('Last waypoint reached, end of course.')
self:onEndCourse()
end
end
--- Does the driver has a next course after the current course ?
function AIDriver:hasNextCourse()
return self.nextCourse ~= nil
end
--- End a course and then continue on nextCourse at nextWpIx
function AIDriver:continueOnNextCourse(nextCourse, nextWpIx)
self:startCourse(nextCourse, nextWpIx)
self:debug('Starting next course at waypoint %d', nextWpIx)
self:onNextCourse(nextWpIx)
end
--- When stopped at a wait point, check if the waiting time is over
-- and continue when needed
function AIDriver:continueIfWaitTimeIsOver()
--- Wait time in secondes.
local waitTime = self.settings.waitTime:get()
if self:isAutoContinueAtWaitPointEnabled() then
if (self.vehicle.timer - self.lastMoveCommandTime) > waitTime * 1000 then
self:debug('Waiting time of %d s is over, continuing', waitTime)
self:continue()
end
end
end
--- Is automatically continuing after stopped at a waypoint enabled? This is the default behavior in
--- mode 5 when there's a wait time set. As long as the waitpoint is used for other purposes in other modes,
--- those modes have to override this.
-- TODO: consider deriving a TransportAIDriver class for mode 5 if there are mode 5 only behaviors.
function AIDriver:isAutoContinueAtWaitPointEnabled()
return self:isStoppingAtWaitPointAllowed() and self.settings.waitTime:get() > 0
end
function AIDriver:isWaitingAtWaitPoint()
return self.state == self.states.STOPPED_AT_WAIT_POINT
end
function AIDriver:hasTipTrigger()
return self.vehicle.cp.currentTipTrigger ~= nil
end
--- Set the speed. The idea is that self.speed is reset at the beginning of every loop and
-- every function calls setSpeed() and the speed will be set to the minimum
-- speed set in this loop.
function AIDriver:setSpeed(speed)
self.speed = math.min(self.speed, speed)
end
--- Speed on the field when not working
function AIDriver:getFieldSpeed()
return self.vehicle.cp.speeds.field
end
--- Speed on the field when working
function AIDriver:getWorkSpeed()
-- use the speed limit supplied by Giants for fieldwork
local speedLimit = self.vehicle:getSpeedLimit() or math.huge
return math.min(self:getFieldSpeed(), speedLimit)
end
function AIDriver:resetLastMoveCommandTime()
self.lastMoveCommandTime = self.vehicle.timer
end
--- Don't auto stop engine. Keep calling this when you do something where the vehicle has a planned stop for a while
--- and you don't want to engine auto stop to engage (for example waiting in the convoy)
function AIDriver:overrideAutoEngineStop()
self:resetLastMoveCommandTime()
end
--- Reset drive controls at the end of each loop
function AIDriver:resetSpeed()
if self.speed > 0 and self.allowedToDrive then
self:resetLastMoveCommandTime()
if self.vehicle:getLastSpeed() > 0.5 then
self.lastRealMovingTime = self.vehicle.timer
self.stoppedButShouldBeMoving = false
elseif not self.stoppedButShouldBeMoving then
self.stoppedMovingAt = self.vehicle.timer
self.stoppedButShouldBeMoving = true
end
else
self.stoppedButShouldBeMoving = false
self.lastStopCommandTime = self.vehicle.timer
end
-- reset speed limit for the next loop
self.speed = math.huge
self.allowedToDrive = true
end
--- Anyone wants to temporarily stop driving for whatever reason, call this
function AIDriver:hold()
self.allowedToDrive = false
-- prevent detecting this state as blocked. TODO: rethink this whole blocking logic, is now confusing as hell
self:resetLastMoveCommandTime()
end
--- Anyone wants to temporarily stop driving for whatever reason, call this
function AIDriver:holdWithFuelSave()
self.allowedToDrive = false
self:setSpeed(0)
end
--- Function used by the driver to get the speed it is supposed to drive at
--
function AIDriver:getSpeed()
return self.speed or 15
end
function AIDriver:getTotalLength()
return self.vehicle.cp.totalLength
end
--- Get waypoint closest to the current position of the vehicle
function AIDriver:getRelevantWaypointIx()
return self.ppc:getRelevantWaypointIx()
end
function AIDriver:getRecordedSpeed()
-- default is the street speed (reduced in corners)
local speed = self:getDefaultStreetSpeed(self.ppc:getCurrentWaypointIx()) or self.vehicle.cp.speeds.street
if self.settings.useRecordingSpeed:is(true) then
-- use default street speed if there's no recorded speed.
speed = math.min(self.course:getAverageSpeed(self.ppc:getCurrentWaypointIx(), 4) or speed, speed)
end
return speed
end
-- get a default street speed in case there's no recorded speed. Slow down in corners and at the end of the course
function AIDriver:getDefaultStreetSpeed(ix)
-- reduce speed before the end of the course
local dToEnd = self.course:getDistanceToLastWaypoint(ix)
if dToEnd < self:getSlowDownDistanceBeforeLastWaypoint() then
-- TODO make this smoother depending on the remaining distance?
return self.vehicle.cp.speeds.turn
end
local radius = self.course:getMinRadiusWithinDistance(ix, 15)
if radius then
return math.max(self.vehicle.cp.speeds.turn, math.min(radius / 20 * self.vehicle.cp.speeds.street, self.vehicle.cp.speeds.street))
end
return self.vehicle.cp.speeds.street
end
-- if closer than this to the last waypoint, start slowing down
function AIDriver:getSlowDownDistanceBeforeLastWaypoint()
return AIDriver.defaultSlowDownDistanceBeforeLastWaypoint
end
function AIDriver:slowDownForWaitPoints()
if self.course:hasWaitPointAround(self.ppc:getCurrentOriginalWaypointIx(), 1, 2) then
self:setSpeed(self.vehicle.cp.speeds.turn)
end
end
-- TODO: review this whole fillpoint/filltrigger thing.
function AIDriver:isNearFillPoint()
if self.course == nil then
return false
else
return self.course:havePhysicallyPassedWaypoint(self:getDirectionNode(),#self.course.waypoints) and self.ppc:getCurrentWaypointIx() <= 5;
end
end
function AIDriver:getIsInFilltrigger()
return self.vehicle.cp.fillTrigger ~= nil or self:isNearFillPoint()
end
--- Is an alignment course needed to reach waypoint ix in the current course?
-- override in derived classes as needed
---@param course Course
function AIDriver:isAlignmentCourseNeeded(course, ix)
local d = course:getDistanceBetweenVehicleAndWaypoint(self.vehicle, ix)
return d > self.settings.turnDiameter:get()
end
function AIDriver:startTurn(ix)
self:debug('Attempting to starting a turn which is not implemented in this mode')
end
---@param course Course
function AIDriver:setUpAlignmentCourse(course, ix)
local x, z, yRot = PathfinderUtil.getNodePositionAndDirection(AIDriverUtil.getDirectionNode(self.vehicle), 0, 0)
local start = State3D(x, -z, courseGenerator.fromCpAngle(yRot))
x, _, z = course:getWaypointPosition(ix)
local goal = State3D(x, -z, courseGenerator.fromCpAngle(math.rad(course:getWaypointAngleDeg(ix))))
local turnRadius = AIDriverUtil.getTurningRadius(self.vehicle)
local solution
if self.allowReversePathfinding then
solution = PathfinderUtil.reedSheppSolver:solve(start, goal, turnRadius)
else
solution = PathfinderUtil.dubinsSolver:solve(start, goal, turnRadius)
end
local alignmentWaypoints = solution:getWaypoints(start, turnRadius)
if not alignmentWaypoints then