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 528
/
AIDriver.lua
1886 lines (1651 loc) · 71.2 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
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 = {},
DONE = {}
}
--- 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(11,vehicle,'AIDriver:init()')
self.debugChannel = 14
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.maxDrivingVectorLength = self.vehicle.cp.turnDiameter
---@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.collisionDetector = nil
-- list of active messages to display
self.activeMsgReferences = {}
-- make sure all vehicle settings are valid for this mode
if self.vehicle.cp.settings then
self:debug('Validating current settings...')
self.vehicle.cp.settings:validateCurrentValues()
end
self:setHudContent()
self.triggerHandler = TriggerHandler(self,self.vehicle,self:getSiloSelectedFillTypeSetting())
self.triggerHandler:enableFuelLoading()
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)
self.triggerHandler:writeUpdateStream(streamId)
streamWriteString(streamId,self.state.name)
streamWriteBool(streamId,self.active)
-- streamWriteBool(streamId,self.vehicle.cp.isDriving)
end
function AIDriver:readUpdateStream(streamId)
self.triggerHandler:readUpdateStream(streamId)
local nameState = streamReadString(streamId)
self.state = self.states[nameState]
self.active = streamReadBool(streamId)
-- self.vehicle.cp.isDriving = streamReadBool(streamId)
end
function AIDriver:postSync()
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, _ in pairs(states) do
self.states[key] = {name = tostring(key)}
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:initWages()
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(3,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()
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 its
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
self:resetTrafficControl()
self.vehicle:setBeaconLightsVisibility(false)
self:clearAllInfoTexts()
self:stop()
self.active = false
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
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:setDone(msgReference)
self:deleteCollisionDetector()
self:setInfoText(msgReference)
self.state = self.states.DONE
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
CpManager:setGlobalInfoText(self.vehicle, msg)
end
end
--- Update AI driver, everything that needs to run in every loop
function AIDriver:update(dt)
self:updateProximitySensors()
self:updatePathfinding()
self:drive(dt)
self:checkIfBlocked()
self:payWages(dt)
self:detectSlipping()
self:resetSpeed()
self:updateLoadingText()
self.triggerHandler:onUpdate(dt)
end
--- UpdateTick AI driver
function AIDriver:updateTick(dt)
self.triggerHandler:onUpdateTick(dt)
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()
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()
-- check if reversing
local lx, lz, moveForwards, isReverseActive = self:getReverseDrivingDirection()
-- stop for fuel if needed
if not self:checkFuel() then
self:hold()
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
local isInTrigger, isAugerWagonTrigger = self.triggerHandler:isInTrigger()
if self:getIsInFilltrigger() or isInTrigger then
self:setSpeed(self.vehicle.cp.speeds.approach)
if isAugerWagonTrigger then
self:setSpeed(self.APPROACH_AUGER_TRIGGER_SPEED)
end
end
self:slowDownForWaitPoints()
self:stopEngineIfNotNeeded()
if isReverseActive then
-- we go wherever goReverse() told us to go
self:driveVehicleInDirection(dt, self.allowedToDrive, moveForwards, lx, lz, self:getSpeed())
elseif self.useDirection then
lx, lz = self.ppc:getGoalPointDirection()
self:debug('%.1f %.1f', lx, lz)
self:driveVehicleInDirection(dt, self.allowedToDrive, moveForwards, lx / 2, 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)
if l > self.maxDrivingVectorLength then
-- point too far, bring it closer so the AI driver will start steer towards it
ax = gx * self.maxDrivingVectorLength / l
az = gz * self.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 = self:checkProximitySensor(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
-- 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 = self:checkProximitySensor(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
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:resetTrafficControl()
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
--- Course ended
function AIDriver:onEndCourse()
if self.vehicle.cp.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:stop(self.vehicle)
-- 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.vehicle.cp.settings.stopAtEnd:is(true) then
if self.state ~= self.states.STOPPED then
self:stop('END_POINT')
end
else
-- continue at the first waypoint
self.ppc:initialize(1)
end
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.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.vehicle.cp.waitTime)
self:stop('WAIT_POINT')
-- show continue button
self:refreshHUD()
end
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
--- 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()
if self:isAutoContinueAtWaitPointEnabled() then
if (self.vehicle.timer - self.lastMoveCommandTime) > self.vehicle.cp.waitTime * 1000 then
self:debug('Waiting time of %d s is over, continuing', self.vehicle.cp.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.vehicle.cp.waitTime > 0
end
function AIDriver:isWaiting()
return self.state == self.states.STOPPED
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.vehicle.cp.speeds.field, 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
--- 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.vehicle.cp.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 < 15 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
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.vehicle.cp.turnDiameter and self.vehicle.cp.alignment.enabled
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
self:debug("Can't find an alignment course, may be too close to target wp?" )
return nil
end
if #alignmentWaypoints < 3 then
self:debug("Alignment course would be only %d waypoints, it isn't needed then.", #alignmentWaypoints )
return nil
end
self:debug('Alignment course with %d waypoints started.', #alignmentWaypoints)
return Course(self.vehicle, courseGenerator.pointsToXzInPlace(alignmentWaypoints), true)
end
function AIDriver:debug(...)
courseplay.debugVehicle(self.debugChannel, self.vehicle, ...)
end
function AIDriver:info(...)
courseplay.infoVehicle(self.vehicle, ...)
end
function AIDriver:error(...)
courseplay.infoVehicle(self.vehicle, ...)
end
--- output debug message only at every debugTicks loop
function AIDriver:debugSparse(...)
if g_updateLoopIndex % self.debugTicks == 0 then
courseplay.debugVehicle(self.debugChannel, self.vehicle, ...)
end
end
function AIDriver:isStopped()
-- giants supplied last speed is in mm/s
return math.abs(self.vehicle.lastSpeedReal) < 0.0001
end
function AIDriver:drawTemporaryCourse()
if not self.course:isTemporary() then return end
if self.vehicle.cp.settings.enableVisualWaypointsTemporary:is(false) and
not courseplay.debugChannels[self.debugChannel] then
return
end
for i = 1, self.course:getNumberOfWaypoints() do
local x, y, z = self.course:getWaypointPosition(i)
cpDebug:drawPoint(x, y + 3, z, 10, 0, 0)
Utils.renderTextAtWorldPosition(x, y + 3.2, z, tostring(i), getCorrectTextSize(0.012), 0)
if i < self.course:getNumberOfWaypoints() then
local nx, ny, nz = self.course:getWaypointPosition(i + 1)
cpDebug:drawLine(x, y + 3, z, 0, 0, 100, nx, ny + 3, nz)
end
end
end
function AIDriver:enableCollisionDetection()
courseplay.debugVehicle(3,self.vehicle,'Collision detection enabled')
self.collisionDetectionEnabled = true
end
function AIDriver:disableCollisionDetection()
courseplay.debugVehicle(3,self.vehicle,'Collision detection disabled')
self.collisionDetectionEnabled = false
end
function AIDriver:detectCollision(dt)
-- if no detector yet, no problem, create it now.
if not self.collisionDetector then
self.collisionDetector = CollisionDetector(self.vehicle)
end
local isInTraffic, trafficSpeed = self.collisionDetector:getStatus(dt)
if self.collisionDetectionEnabled then
if trafficSpeed ~= 0 then
--get the speed from the target vehicle
self:setSpeed(trafficSpeed)
end
-- setting the speed to 0 won't slow us down fast enough so use the more effective allowedToDrive = false
if isInTraffic then
self:hold()
end
end
if isInTraffic then
self:setInfoText('TRAFFIC')
else
self:clearInfoText('TRAFFIC')
end
return self.allowedToDrive
end
function AIDriver:areBeaconLightsEnabled()
return self.vehicle.cp.settings.warningLightsMode:get() > WarningLightsModeSetting.WARNING_LIGHTS_NEVER
end
function AIDriver:updateLights()
if not self.vehicle.spec_lights then return end
if self:areBeaconLightsEnabled() then
self.vehicle:setBeaconLightsVisibility(true)
else
self.vehicle:setBeaconLightsVisibility(false)
end
end
function AIDriver:updateAILights(superFunc)
if self.cp and self.cp.driver and self:getIsCourseplayDriving() and self.spec_lights then
if self.cp.driver:shouldLightsBeUsedForEnvironment() then --fall back to base class AIDriver for this
self.cp.driver:setLightsMask(self)
elseif superFunc ~= nil then
superFunc(self)
end
elseif superFunc ~= nil then
superFunc(self)
end
end
Lights.updateAILights = Utils.overwrittenFunction(Lights.updateAILights , AIDriver.updateAILights)
function AIDriver:shouldLightsBeUsedForEnvironment()
-- How Giants decides lights in Lights:updateAILights
local dayMinutes = g_currentMission.environment.dayTime / (1000 * 60)
local nightTime = (dayMinutes > g_currentMission.environment.nightStartMinutes or dayMinutes < g_currentMission.environment.nightEndMinutes)
local rainScale = g_currentMission.environment.weather:getRainFallScale()
local timeSinceRain = g_currentMission.environment.weather:getTimeSinceLastRain()
local raining = rainScale > 0
local shouldLightsBeUsed = (nightTime or raining)
return shouldLightsBeUsed
end
function AIDriver:setLightsMask(vehicle)
local x,y,z = getWorldTranslation(vehicle.rootNode);
if not courseplay:isField(x, z) then