forked from Courseplay/courseplay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CombineAIDriver.lua
1502 lines (1367 loc) · 63.3 KB
/
CombineAIDriver.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/>.
]]
---@class CombineAIDriver : UnloadableFieldworkAIDriver
CombineAIDriver = CpObject(UnloadableFieldworkAIDriver)
-- chopper: 0= pipe folded (really? isn't this 1?), 2,= autoaiming; combine: 1 = closed 2= open
CombineAIDriver.PIPE_STATE_MOVING = 0
CombineAIDriver.PIPE_STATE_CLOSED = 1
CombineAIDriver.PIPE_STATE_OPEN = 2
-- fill level when we start making a pocket to unload if we are on the outermost headland
CombineAIDriver.pocketFillLevelFullPercentage = 95
CombineAIDriver.myStates = {
PULLING_BACK_FOR_UNLOAD = {},
WAITING_FOR_UNLOAD_AFTER_PULLED_BACK = {},
RETURNING_FROM_PULL_BACK = {},
REVERSING_TO_MAKE_A_POCKET = {},
MAKING_POCKET = {},
WAITING_FOR_UNLOAD_IN_POCKET = {},
WAITING_FOR_UNLOAD_AFTER_FIELDWORK_ENDED = {},
WAITING_FOR_UNLOADER_TO_LEAVE = {},
RETURNING_FROM_POCKET = {},
DRIVING_TO_SELF_UNLOAD = {},
SELF_UNLOADING = {},
DRIVING_TO_SELF_UNLOAD_AFTER_FIELDWORK_ENDED = {},
SELF_UNLOADING_AFTER_FIELDWORK_ENDED = {},
RETURNING_FROM_SELF_UNLOAD = {}
}
CombineAIDriver.turnTypes = {
HEADLAND_NORMAL = {},
HEADLAND_EASY = {},
HEADLAND_POCKET = {},
UP_DOWN_NORMAL = {}
}
function CombineAIDriver:init(vehicle)
courseplay.debugVehicle(11, vehicle, 'CombineAIDriver:init()')
UnloadableFieldworkAIDriver.init(self, vehicle)
self:initStates(CombineAIDriver.myStates)
self.fruitLeft, self.fruitRight = 0, 0
self.litersPerMeter = 0
self.litersPerSecond = 0
self.fillLevelAtLastWaypoint = 0
self.beaconLightsActive = false
self.lastEmptyTimestamp = 0
self.pipeOffsetX = 0
self.unloaders = {}
self:initUnloadStates()
if self.vehicle.spec_combine then
self.combine = self.vehicle.spec_combine
else
local combineImplement = FieldworkAIDriver.getImplementWithSpecialization(self.vehicle, Combine)
if combineImplement then
self.combine = combineImplement.spec_combine
else
self:error('Vehicle is not a combine and could not find implement with spec_combine')
end
end
if self.vehicle.spec_pipe then
self.pipe = self.vehicle.spec_pipe
self.objectWithPipe = self.vehicle
else
local implementWithPipe = FieldworkAIDriver.getImplementWithSpecialization(self.vehicle, Pipe)
if implementWithPipe then
self.pipe = implementWithPipe.spec_pipe
self.objectWithPipe = implementWithPipe
else
self:info('Could not find implement with pipe')
end
end
if self.pipe then
-- check the pipe length:
-- unfold everything, open the pipe, check the side offset, then close pipe, fold everything back (if it was folded)
local wasFolded, wasClosed
if self.vehicle.spec_foldable then
wasFolded = not self.vehicle.spec_foldable:getIsUnfolded()
if wasFolded then
Foldable.setAnimTime(self.vehicle.spec_foldable, 0, true)
end
end
if self.pipe.currentState == CombineAIDriver.PIPE_STATE_CLOSED then
wasClosed = true
if self.pipe.animation.name then
self.pipe:setAnimationTime(self.pipe.animation.name, 1, true)
else
-- as seen in the Giants pipe code
self.objectWithPipe:setPipeState(CombineAIDriver.PIPE_STATE_OPEN)
self.objectWithPipe:updatePipeNodes(999999, nil)
end
end
local dischargeNode = self.combine:getCurrentDischargeNode()
self:fixDischargeDistance(dischargeNode)
local dx, _, _ = localToLocal(dischargeNode.node, self.combine.rootNode, 0, 0, 0)
self.pipeOnLeftSide = dx > 0
self:debug('Pipe on left side %s', tostring(self.pipeOnLeftSide))
-- use self.combine so attached harvesters have the offset relative to the harvester's root node
-- (and thus, does not depend on the angle between the tractor and the harvester)
self.pipeOffsetX, _, self.pipeOffsetZ = localToLocal(dischargeNode.node, self.combine.rootNode, 0, 0, 0)
self:debug('Pipe offset: x = %.1f, z = %.1f', self.pipeOffsetX, self.pipeOffsetZ)
if wasClosed then
if self.pipe.animation.name then
self.pipe:setAnimationTime(self.pipe.animation.name, 0, true)
else
self.objectWithPipe:setPipeState(CombineAIDriver.PIPE_STATE_CLOSED)
self.objectWithPipe:updatePipeNodes(999999, nil)
end
end
if self.vehicle.spec_foldable then
if wasFolded then
Foldable.setAnimTime(self.vehicle.spec_foldable, 1, true)
end
end
else
-- make sure pipe offset has a value until CombineUnloadManager as cleaned up as it calls getPipeOffset()
-- periodically even when CP isn't driving, and even for cotton harvesters...
self.pipeOffsetX, self.pipeOffsetZ = 0, 0
self.pipeOnLeftSide = true
end
-- distance to keep to the right when pulling back to make room for the tractor
self.pullBackSideOffset = self.pipeOffsetX - self.vehicle.cp.workWidth / 2 + 5
self.pullBackSideOffset = self.pipeOnLeftSide and self.pullBackSideOffset or -self.pullBackSideOffset
-- should be at pullBackSideOffset to the right at pullBackDistanceStart
self.pullBackDistanceStart = self.vehicle.cp.turnDiameter --* 0.7
-- and back up another bit
self.pullBackDistanceEnd = self.pullBackDistanceStart + 5
-- when making a pocket, how far to back up before changing to forward
self.pocketReverseDistance = 25
-- register ourselves at our boss
g_combineUnloadManager:addCombineToList(self.vehicle, self)
self:measureBackDistance()
end
function CombineAIDriver:writeUpdateStream(streamId)
AIDriver.writeUpdateStream(self,streamId)
end
function CombineAIDriver:readUpdateStream(streamId)
AIDriver.readUpdateStream(self,streamId)
end
--- Get the combine object, this can be different from the vehicle in case of tools towed or mounted on a tractor
function CombineAIDriver:getCombine()
return self.combine
end
function CombineAIDriver:start(startingPoint)
self:clearAllUnloaderInformation()
self:addBackwardProximitySensor()
UnloadableFieldworkAIDriver.start(self, startingPoint)
local total, pipeInFruit = self.fieldworkCourse:setPipeInFruitMap(self.pipeOffsetX, self.vehicle.cp.workWidth)
self:debug('Pipe in fruit map created, there are %d non-headland waypoints, of which at %d the pipe will be in the fruit',
total, pipeInFruit)
end
function CombineAIDriver:setHudContent()
UnloadableFieldworkAIDriver.setHudContent(self)
courseplay.hud:setCombineAIDriverContent(self.vehicle)
end
function CombineAIDriver:drive(dt)
-- handle the pipe in any state
self:handlePipe()
if self.isChopperWaitingForTrailer then
-- Give up all reservations while not moving (and do not reserve anything)
self:resetTrafficControl()
elseif not self:trafficControlOK() then
self:debugSparse('holding due to traffic')
self:hold()
end
-- the rest is the same as the parent class
UnloadableFieldworkAIDriver.drive(self, dt)
end
function CombineAIDriver:onEndCourse()
local fillLevel = self.vehicle:getFillUnitFillLevel(self.combine.fillUnitIndex)
if self.state == self.states.ON_FIELDWORK_COURSE and
self.fieldworkState == self.states.UNLOAD_OR_REFILL_ON_FIELD then
if self.fieldworkUnloadOrRefillState == self.states.DRIVING_TO_SELF_UNLOAD then
self:debug('Self unloading point reached, fill level %.1f.', fillLevel)
self.fieldworkUnloadOrRefillState = self.states.SELF_UNLOADING
elseif self.fieldworkUnloadOrRefillState == self.states.DRIVING_TO_SELF_UNLOAD_AFTER_FIELDWORK_ENDED then
self:debug('Self unloading point reached after fieldwork ended, fill level %.1f.', fillLevel)
self.fieldworkUnloadOrRefillState = self.states.SELF_UNLOADING_AFTER_FIELDWORK_ENDED
end
elseif self.state == self.states.ON_FIELDWORK_COURSE and fillLevel > 0 then
if self.vehicle.cp.settings.selfUnload:is(true) and self:startSelfUnload() then
self:raiseImplements()
self.fieldworkState = self.states.UNLOAD_OR_REFILL_ON_FIELD
self.fieldworkUnloadOrRefillState = self.states.DRIVING_TO_SELF_UNLOAD_AFTER_FIELDWORK_ENDED
self.ppc:setShortLookaheadDistance()
self:disableCollisionDetection()
else
self:setInfoText(self:getFillLevelInfoText())
-- let AutoDrive know we are done and can unload
self:debug('Fieldwork done, fill level is %.1f, now waiting to be unloaded.', fillLevel)
self.fieldworkState = self.states.UNLOAD_OR_REFILL_ON_FIELD
self.fieldworkUnloadOrRefillState = self.states.WAITING_FOR_UNLOAD_AFTER_FIELDWORK_ENDED
end
else
UnloadableFieldworkAIDriver.onEndCourse(self)
end
end
function CombineAIDriver:onWaypointPassed(ix)
if self.state == self.states.ON_FIELDWORK_COURSE and
(self.fieldworkUnloadOrRefillState == self.states.DRIVING_TO_SELF_UNLOAD or
self.fieldworkUnloadOrRefillState == self.states.DRIVING_TO_SELF_UNLOAD_AFTER_FIELDWORK_ENDED or
self.fieldworkUnloadOrRefillState == self.states.RETURNING_FROM_SELF_UNLOAD) then
-- nothing to do while driving to unload and back
return UnloadableFieldworkAIDriver.onWaypointPassed(self, ix)
end
self:checkFruit()
-- make sure we start making a pocket while we still have some fill capacity left as we'll be
-- harvesting fruit while making the pocket unless we have self unload turned on
if self:shouldMakePocket() and self.vehicle.cp.settings.selfUnload:is(false) then
self.fillLevelFullPercentage = self.pocketFillLevelFullPercentage
end
self:shouldStrawSwathBeOn(ix)
if self.state == self.states.ON_FIELDWORK_COURSE and self.fieldworkState == self.states.WORKING then
self:checkDistanceUntilFull(ix)
end
if self.state == self.states.ON_FIELDWORK_COURSE and
self.fieldworkState == self.states.UNLOAD_OR_REFILL_ON_FIELD and
self.fieldworkUnloadOrRefillState == self.states.MAKING_POCKET and
self.unloadInPocketIx and ix == self.unloadInPocketIx then
-- we are making a pocket and reached the waypoint where we are going to stop and wait for unload
self:debug('Waiting for unload in the pocket')
self:setInfoText(self:getFillLevelInfoText())
self.fieldworkUnloadOrRefillState = self.states.WAITING_FOR_UNLOAD_IN_POCKET
-- reset offset to return to the original up/down row after we unloaded in the pocket
self.aiDriverOffsetX = 0
end
if self.returnedFromPocketIx and self.returnedFromPocketIx == ix then
-- back to normal look ahead distance for PPC, no tight turns are needed anymore
self:debug('Reset PPC to normal lookahead distance')
self.ppc:setNormalLookaheadDistance()
end
UnloadableFieldworkAIDriver.onWaypointPassed(self, ix)
end
function CombineAIDriver:isWaitingInPocket()
return self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_UNLOAD_IN_POCKET
end
function CombineAIDriver:changeToFieldworkUnloadOrRefill()
if self.vehicle.cp.realisticDriving then
self:checkFruit()
-- TODO: check around turn maneuvers we may not want to pull back before a turn
if self.vehicle.cp.settings.selfUnload:is(true) and self:startSelfUnload() then
self:raiseImplements()
self.fieldworkState = self.states.UNLOAD_OR_REFILL_ON_FIELD
self.fieldworkUnloadOrRefillState = self.states.DRIVING_TO_SELF_UNLOAD
self.ppc:setShortLookaheadDistance()
self:disableCollisionDetection()
self:rememberWaypointToContinueFieldwork()
elseif self:shouldMakePocket() then
-- I'm on the edge of the field or fruit is on both sides, make a pocket on the right side and wait there for the unload
local pocketCourse, nextIx = self:createPocketCourse()
if pocketCourse then
self:debug('No room to the left, making a pocket for unload')
self.fieldworkState = self.states.UNLOAD_OR_REFILL_ON_FIELD
self.fieldworkUnloadOrRefillState = self.states.REVERSING_TO_MAKE_A_POCKET
-- raise header for reversing
self:raiseImplements()
self:startCourse(pocketCourse, 1, self.course, nextIx)
-- tighter turns
self.ppc:setShortLookaheadDistance()
else
-- revert to normal behavior
UnloadableFieldworkAIDriver.changeToFieldworkUnloadOrRefill(self)
end
elseif self:shouldPullBack() then
-- is our pipe in the fruit? (assuming pipe is on the left side)
local pullBackCourse = self:createPullBackCourse()
if pullBackCourse then
pullBackCourse:print()
self:debug('Pipe in fruit, pulling back to make room for unloading')
self.fieldworkState = self.states.UNLOAD_OR_REFILL_ON_FIELD
self.fieldworkUnloadOrRefillState = self.states.WAITING_FOR_STOP
self.courseAfterPullBack = self.course
self.ixAfterPullBack = self.ppc:getLastPassedWaypointIx() or self.ppc:getCurrentWaypointIx()
-- tighter turns
self.ppc:setShortLookaheadDistance()
self:startCourse(pullBackCourse, 1)
else
-- revert to normal behavior
UnloadableFieldworkAIDriver.changeToFieldworkUnloadOrRefill(self)
end
else
-- pipe not in fruit, combine not on outermost headland, just do the normal thing
UnloadableFieldworkAIDriver.changeToFieldworkUnloadOrRefill(self)
end
else
UnloadableFieldworkAIDriver.changeToFieldworkUnloadOrRefill(self)
end
end
function CombineAIDriver:driveFieldwork(dt)
if self.fieldworkState == self.states.WORKING then
if self.agreedUnloaderRendezvousWaypointIx then
local d = self.fieldworkCourse:getDistanceBetweenWaypoints(self.fieldworkCourse:getCurrentWaypointIx(),
self.agreedUnloaderRendezvousWaypointIx)
if d < 10 then
self:debugSparse('Slow down around the unloader rendezvous waypoint %d to let the unloader catch up',
self.agreedUnloaderRendezvousWaypointIx)
self:setSpeed(self:getWorkSpeed() / 2)
end
end
end
self:checkBlockingUnloader()
return UnloadableFieldworkAIDriver.driveFieldwork(self, dt)
end
--- Stop for unload/refill while driving the fieldwork course
function CombineAIDriver:driveFieldworkUnloadOrRefill()
if self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_STOP then
self:setSpeed(0)
-- wait until we stopped before raising the implements
if self:isStopped() then
self:debug('Raise implements and start pulling back')
self:raiseImplements()
self.fieldworkUnloadOrRefillState = self.states.PULLING_BACK_FOR_UNLOAD
end
elseif self.fieldworkUnloadOrRefillState == self.states.PULLING_BACK_FOR_UNLOAD then
self:setSpeed(self.vehicle.cp.speeds.reverse)
elseif self.fieldworkUnloadOrRefillState == self.states.REVERSING_TO_MAKE_A_POCKET then
self:setSpeed(self.vehicle.cp.speeds.reverse)
elseif self.fieldworkUnloadOrRefillState == self.states.MAKING_POCKET then
self:setSpeed(self:getWorkSpeed())
elseif self.fieldworkUnloadOrRefillState == self.states.RETURNING_FROM_PULL_BACK then
self:setSpeed(self.vehicle.cp.speeds.turn)
elseif self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_UNLOAD_IN_POCKET or
self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_UNLOAD_AFTER_PULLED_BACK then
if self:unloadFinished() then
self:clearInfoText(self:getFillLevelInfoText())
-- wait a bit after the unload finished to give a chance to the unloader to move away
self.stateBeforeWaitingForUnloaderToLeave = self.fieldworkUnloadOrRefillState
self.fieldworkUnloadOrRefillState = self.states.WAITING_FOR_UNLOADER_TO_LEAVE
self.waitingForUnloaderSince = self.vehicle.timer
self:debug('Unloading finished, wait for the unloader to leave...')
else
self:setSpeed(0)
end
elseif self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_UNLOAD_AFTER_FIELDWORK_ENDED then
local fillLevel = self.vehicle:getFillUnitFillLevel(self.combine.fillUnitIndex)
if fillLevel < 0.01 then
self:clearInfoText(self:getFillLevelInfoText())
self:debug('Unloading finished after fieldwork ended, end course')
UnloadableFieldworkAIDriver.onEndCourse(self)
else
self:setSpeed(0)
end
elseif self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_UNLOADER_TO_LEAVE then
self:setSpeed(0)
-- TODO: instead of just wait a few seconds we could check if the unloader has actually left
if self.waitingForUnloaderSince + 5000 < self.vehicle.timer then
if self.stateBeforeWaitingForUnloaderToLeave == self.states.WAITING_FOR_UNLOAD_AFTER_PULLED_BACK then
local pullBackReturnCourse = self:createPullBackReturnCourse()
if pullBackReturnCourse then
self.fieldworkUnloadOrRefillState = self.states.RETURNING_FROM_PULL_BACK
self:debug('Unloading finished, returning to fieldwork on return course')
self:startCourse(pullBackReturnCourse, 1, self.courseAfterPullBack, self.ixAfterPullBack)
else
self:debug('Unloading finished, returning to fieldwork directly')
self:startCourse(self.courseAfterPullBack, self.ixAfterPullBack)
self.ppc:setNormalLookaheadDistance()
self:changeToFieldwork()
end
elseif self.stateBeforeWaitingForUnloaderToLeave == self.states.WAITING_FOR_UNLOAD_IN_POCKET then
self:debug('Unloading in pocket finished, returning to fieldwork')
self.fillLevelFullPercentage = self.normalFillLevelFullPercentage
self:changeToFieldwork()
end
end
elseif self.fieldworkUnloadOrRefillState == self.states.DRIVING_TO_SELF_UNLOAD then
self:setSpeed(self.vehicle.cp.speeds.field)
elseif self.fieldworkUnloadOrRefillState == self.states.DRIVING_TO_SELF_UNLOAD_AFTER_FIELDWORK_ENDED then
self:setSpeed(self.vehicle.cp.speeds.field)
elseif self.fieldworkUnloadOrRefillState == self.states.SELF_UNLOADING then
self:setSpeed(0)
if self:unloadFinished() then
self:debug('Self unloading finished, returning to fieldwork')
if self:returnToFieldworkAfterSelfUnloading() then
self.fieldworkUnloadOrRefillState = self.states.RETURNING_FROM_SELF_UNLOAD
else
self:startFieldworkWithPathfinding(self.aiDriverData.continueFieldworkAtWaypoint)
end
self.ppc:setNormalLookaheadDistance()
end
elseif self.fieldworkUnloadOrRefillState == self.states.SELF_UNLOADING_AFTER_FIELDWORK_ENDED then
self:setSpeed(0)
if self:unloadFinished() then
self:debug('Self unloading finished, returning to fieldwork')
UnloadableFieldworkAIDriver.onEndCourse(self)
end
elseif self.fieldworkUnloadOrRefillState == self.states.RETURNING_FROM_SELF_UNLOAD then
self:setSpeed(self.vehicle.cp.speeds.field)
else
UnloadableFieldworkAIDriver.driveFieldworkUnloadOrRefill(self)
end
end
function CombineAIDriver:onLastWaypoint()
if self.fieldworkState == self.states.UNLOAD_OR_REFILL_ON_FIELD and
self.fieldworkUnloadOrRefillState == self.states.PULLING_BACK_FOR_UNLOAD then
-- pulled back, now wait for unload
self.fieldworkUnloadOrRefillState = self.states.WAITING_FOR_UNLOAD_AFTER_PULLED_BACK
self:debug('Pulled back, now wait for unload')
self:setInfoText(self:getFillLevelInfoText())
else
UnloadableFieldworkAIDriver.onLastWaypoint(self)
end
end
function CombineAIDriver:onNextCourse(ix)
if self.fieldworkState == self.states.UNLOAD_OR_REFILL_ON_FIELD then
if self.fieldworkUnloadOrRefillState == self.states.RETURNING_FROM_PULL_BACK then
self:debug('Pull back finished, returning to fieldwork')
self:changeToFieldwork()
elseif self.fieldworkUnloadOrRefillState == self.states.RETURNING_FROM_SELF_UNLOAD then
self:debug('Back from self unload, returning to fieldwork')
self:changeToFieldwork()
elseif self.fieldworkUnloadOrRefillState == self.states.REVERSING_TO_MAKE_A_POCKET then
self:debug('Reversed, now start making a pocket to waypoint %d', self.unloadInPocketIx)
self:lowerImplements()
self.fieldworkUnloadOrRefillState = self.states.MAKING_POCKET
self.aiDriverOffsetX = self.pullBackSideOffset
end
elseif self.fieldworkState == self.states.TURNING then
self.ppc:setNormalLookaheadDistance()
-- make sure the next waypoint is in front of us. It can be behind us after a turn with multitools where the
-- x offset is high (wide tools)
self.ppc:initialize(self.course:getNextFwdWaypointIxFromVehiclePosition(ix, self:getDirectionNode(), 0))
UnloadableFieldworkAIDriver.onNextCourse(self)
else
UnloadableFieldworkAIDriver.onNextCourse(self)
end
end
function CombineAIDriver:unloadFinished()
local discharging = true
local dischargingNow = false
if self.pipe then
dischargingNow = self.pipe:getDischargeState() ~= Dischargeable.DISCHARGE_STATE_OFF
end
--wait for 10 frames before taking discharging as false
if not dischargingNow then
self.notDischargingSinceLoopIndex =
self.notDischargingSinceLoopIndex and self.notDischargingSinceLoopIndex or g_updateLoopIndex
if g_updateLoopIndex - self.notDischargingSinceLoopIndex > 10 then
discharging = false
end
else
self.notDischargingSinceLoopIndex = nil
end
local fillLevel = self.vehicle:getFillUnitFillLevel(self.combine.fillUnitIndex)
-- unload is done when fill levels are ok (not full) and not discharging anymore (either because we
-- are empty or the trailer is full)
return (self:allFillLevelsOk() and not discharging) or fillLevel < 0.1
end
function CombineAIDriver:shouldMakePocket()
if self.fruitLeft > 0.75 and self.fruitRight > 0.75 then
-- fruit both sides
return true
elseif self.pipeOnLeftSide then
-- on the outermost headland clockwise (field edge)
return not self.fieldOnLeft
else
-- on the outermost headland counterclockwise (field edge)
return not self.fieldOnRight
end
end
function CombineAIDriver:shouldPullBack()
return self:isPipeInFruit()
end
function CombineAIDriver:isPipeOnLeft()
return self.pipeOnLeftSide
end
function CombineAIDriver:isPipeInFruit()
-- is our pipe in the fruit?
if self.pipeOnLeftSide then
return self.fruitLeft > self.fruitRight
else
return self.fruitLeft < self.fruitRight
end
end
function CombineAIDriver:checkFruit()
-- getValidityOfTurnDirections() wants to have the vehicle.aiDriveDirection, so get that here.
local dx,_,dz = localDirectionToWorld(self.vehicle:getAIVehicleDirectionNode(), 0, 0, 1)
local length = MathUtil.vector2Length(dx,dz)
dx = dx / length
dz = dz / length
self.vehicle.aiDriveDirection = {dx, dz}
self.fruitLeft, self.fruitRight = AIVehicleUtil.getValidityOfTurnDirections(self.vehicle)
local x, _, z = localToWorld(self:getDirectionNode(), self.vehicle.cp.workWidth, 0, 0)
self.fieldOnLeft = courseplay:isField(x, z, 1, 1)
x, _, z = localToWorld(self:getDirectionNode(), -self.vehicle.cp.workWidth, 0, 0)
self.fieldOnRight = courseplay:isField(x, z, 1, 1)
self:debug('Fruit left: %.2f right %.2f, field on left %s, right %s',
self.fruitLeft, self.fruitRight, tostring(self.fieldOnLeft), tostring(self.fieldOnRight))
end
function CombineAIDriver:checkDistanceUntilFull(ix)
-- calculate fill rate so the combine driver knows if it can make the next row without unloading
local fillLevel = self.vehicle:getFillUnitFillLevel(self.combine.fillUnitIndex)
if ix > 1 then
if self.fillLevelAtLastWaypoint and self.fillLevelAtLastWaypoint > 0 and self.fillLevelAtLastWaypoint <= fillLevel then
local litersPerMeter = (fillLevel - self.fillLevelAtLastWaypoint) / self.course:getDistanceToNextWaypoint(ix - 1)
-- make sure it won't end up being inf
local litersPerSecond = math.min(1000, (fillLevel - self.fillLevelAtLastWaypoint) /
((self.vehicle.timer - (self.fillLevelLastCheckedTime or self.vehicle.timer)) / 1000))
-- smooth everything a bit, also ignore 0
self.litersPerMeter = litersPerMeter > 0 and (self.litersPerMeter + litersPerMeter) / 2 or self.litersPerMeter
self.litersPerSecond = litersPerSecond > 0 and (self.litersPerSecond + litersPerSecond) / 2 or self.litersPerSecond
self.fillLevelAtLastWaypoint = (self.fillLevelAtLastWaypoint + fillLevel) / 2
else
-- no history yet, so make sure we don't end up with some unrealistic numbers
self.waypointIxWhenFull = nil
self.litersPerMeter = 0
self.litersPerSecond = 0
self.fillLevelAtLastWaypoint = fillLevel
end
self.fillLevelLastCheckedTime = self.vehicle.timer
self:debug('Fill rate is %.1f l/m, %.1f l/s', self.litersPerMeter, self.litersPerSecond)
end
local litersUntilFull = self.combine:getFillUnitCapacity(self.combine.fillUnitIndex) - fillLevel
local dUntilFull = litersUntilFull / self.litersPerMeter
self.secondsUntilFull = self.litersPerSecond > 0 and (litersUntilFull / self.litersPerSecond) or nil
self.waypointIxWhenFull = self.course:getNextWaypointIxWithinDistance(ix, dUntilFull) or self.course:getNumberOfWaypoints()
self.waypointIxWhenFull = self:getSafeUnloaderDestinationWaypoint(self.waypointIxWhenFull)
self.distanceToWaypointWhenFull =
self.course:getDistanceBetweenWaypoints(self.waypointIxWhenFull, self.course:getCurrentWaypointIx())
self:debug('Will be full at waypoint %d in %d m',
self.waypointIxWhenFull or -1, self.distanceToWaypointWhenFull)
end
---@param unloaderEstimatedSecondsEnroute number minimum time the unloader needs to get to the combine
---@return Waypoint, number, number waypoint to meet the unloader, index of waypoint, time we need to reach that waypoint
function CombineAIDriver:getUnloaderRendezvousWaypoint(unloaderEstimatedSecondsEnroute)
local dToUnloaderRendezvous = unloaderEstimatedSecondsEnroute * self:getWorkSpeed() / 3.6
local unloaderRendezvousWaypointIx = self.fieldworkCourse:getNextWaypointIxWithinDistance(self.fieldworkCourse:getCurrentWaypointIx(),
dToUnloaderRendezvous) or self.fieldworkCourse:getNumberOfWaypoints()
self:debug('Seconds until full: %d, unloader ETE: %d', self.secondsUntilFull or -1, unloaderEstimatedSecondsEnroute)
if not self.secondsUntilFull or (self.secondsUntilFull and self.secondsUntilFull > unloaderEstimatedSecondsEnroute) then
-- unloader will reach us before we are full, or we don't know where we'll be full, guess at which waypoint we will be by then
unloaderRendezvousWaypointIx = self:getSafeUnloaderDestinationWaypoint(unloaderRendezvousWaypointIx)
if self:canUnloadWhileMovingAtWaypoint(unloaderRendezvousWaypointIx) then
self.agreedUnloaderRendezvousWaypointIx = unloaderRendezvousWaypointIx
self:debug('Rendezvous with unloader at waypoint %d in %d m', unloaderRendezvousWaypointIx, dToUnloaderRendezvous)
return self.fieldworkCourse:getWaypoint(unloaderRendezvousWaypointIx), unloaderRendezvousWaypointIx, unloaderEstimatedSecondsEnroute
else
return nil, 0, 0
end
elseif self.waypointIxWhenFull then
self:debug('We don\'t know when exactly we\'ll be full, but it will be at waypoint %d in %d m, reject rendezvous',
self.waypointIxWhenFull, self.distanceToWaypointWhenFull)
if self:canUnloadWhileMovingAtWaypoint(unloaderRendezvousWaypointIx) then
self.agreedUnloaderRendezvousWaypointIx = self.waypointIxWhenFull
-- TODO: figure out what to do in this case, it does not seem to make sense to send the unloader to
-- a distant waypoint
return nil, 0, 0
-- return self.fieldworkCourse:getWaypoint(self.waypointIxWhenFull), self.waypointIxWhenFull, self.distanceToWaypointWhenFull / (self:getWorkSpeed() / 3.6)
else
return nil, 0, 0
end
else
self:debug('We don\t know when exactly we\'ll be full, reject rendezvous')
return nil, 0, 0
end
end
function CombineAIDriver:canUnloadWhileMovingAtWaypoint(ix)
if self.fieldworkCourse:isPipeInFruitAt(ix) then
self:debug('pipe would be in fruit at the planned rendezvous waypoint %d', ix)
return false
end
if self.fieldworkCourse:isOnHeadland(ix, 1) then
self:debug('planned rendezvous waypoint %d is on first headland, no unloading of moving combine there', ix)
return false
end
return true
end
--- Check if ix is a safe destination for an unloader, return an adjusted ix if not
---@param ix number waypoint index to check
---@return number waypoint index adjusted if needed
function CombineAIDriver:getSafeUnloaderDestinationWaypoint(ix)
local newWpIx = ix
if self.fieldworkCourse:isTurnStartAtIx(ix) then
if self.fieldworkCourse:isOnHeadland(ix) then
-- on the headland, use the wp after the turn, the one before may be very far, especially on a
-- transition from headland to up/down rows.
newWpIx = ix + 1
else
-- turn start waypoints usually aren't safe as they point to the turn end direction in 180 turns
-- so use the one before
newWpIx = ix - 1
end
else
end
-- if we ended up on a turn start WP and the row is long enough, move it a bit forward so the unloader does
-- not drive much off the field to align with it
if self.fieldworkCourse:isTurnStartAtIx(newWpIx) and self.fieldworkCourse:getDistanceToNextTurn(newWpIx) > 20 then
-- TODO: get the guess factor out of this (2 wp distance < 20 m)
newWpIx = newWpIx + 2
end
return newWpIx
end
-- TODO: put this in onBlocked()?
function CombineAIDriver:checkBlockingUnloader()
if not self.backwardLookingProximitySensorPack then return end
local d, blockingVehicle = self.backwardLookingProximitySensorPack:getClosestObjectDistanceAndRootVehicle()
if d < 1000 and blockingVehicle and self:isStopped() and self:isReversing() and not self:isWaitingForUnload() then
if g_updateLoopIndex % 250 == 0 then
self:debug('Can\'t reverse, %s at %.1f m is blocking', blockingVehicle:getName(), d)
if blockingVehicle.cp.driver and blockingVehicle.cp.driver.onBlockingOtherVehicle then
blockingVehicle.cp.driver:onBlockingOtherVehicle(self.vehicle)
end
end
end
end
function CombineAIDriver:checkFruitAtNode(node, offsetX, offsetZ)
local x, _, z = localToWorld(node, offsetX, 0, offsetZ or 0)
local hasFruit, fruitValue = PathfinderUtil.hasFruit(x, z, 5, 3)
return hasFruit, fruitValue
end
--- Is pipe in fruit according to the current field harvest state at waypoint?
function CombineAIDriver:isPipeInFruitAtWaypointNow(course, ix)
if not self.aiDriverData.fruitCheckHelperWpNode then
self.aiDriverData.fruitCheckHelperWpNode = WaypointNode(nameNum(self.vehicle) .. 'fruitCheckHelperWpNode')
end
self.aiDriverData.fruitCheckHelperWpNode:setToWaypoint(course, ix)
local hasFruit, fruitValue = self:checkFruitAtNode(self.aiDriverData.fruitCheckHelperWpNode.node, self.pipeOffsetX)
self:debug('at waypoint %d pipe in fruit %s (fruitValue %.1f)', ix, tostring(hasFruit), fruitValue or 0)
return hasFruit, fruitValue
end
--- Find the best waypoint to unload.
---@param waypointIxWhenFull number estimated waypoint index when full based on current fruit flow and distance
---@return number best waypoint to unload. What is a good point to unload:
function CombineAIDriver:findBestWaypointToUnload(waypointIxWhenFull)
if self.course:isOnHeadland(waypointIxWhenFull) then
return self:findBestWaypointToUnloadOnHeadland(waypointIxWhenFull)
else
return self:findBestWaypointToUnloadOnUpDownRows(waypointIxWhenFull)
end
end
function CombineAIDriver:findBestWaypointToUnloadOnHeadland(waypointIxWhenFull)
return waypointIxWhenFull
end
function CombineAIDriver:findBestWaypointToUnloadOnUpDownRows(waypointIxWhenFull)
local dToNextTurn = self.course:getDistanceToNextTurn(waypointIxWhenFull) or 0
local lRow, ixAtTurnEnd = self.course:getRowLength(waypointIxWhenFull)
local pipeInFruit, _ = self:isPipeInFruitAtWaypoint(self.course, waypointIxWhenFull)
self:debug('Estimated waypoint when full: %d on up/down row, pipe in fruit %s, dToNextTurn: %d m, lRow = %d m',
waypointIxWhenFull, tostring(pipeInFruit), dToNextTurn, lRow or 0)
if pipeInFruit then
self:debug('Pipe would be in fruit where we will be full. Check previous row')
if ixAtTurnEnd and ixAtTurnEnd > self.course:getCurrentWaypointIx() then
pipeInFruit, _ = self:isPipeInFruitAtWaypoint(self.course, ixAtTurnEnd - 1)
if not pipeInFruit then
local lPreviousRow = self.course:getRowLength(ixAtTurnEnd - 1)
self:debug('pipe not in fruit in the previous row (%d m, ending at wp %d), so unload there if long enough',
lPreviousRow, ixAtTurnEnd - 1)
return ixAtTurnEnd - 3
end
end
else
self:debug('pipe is not in fruit where we are full. If it is towards the end of the row, bring it up a bit')
-- so we'll have some distance for unloading
if ixAtTurnEnd and dToNextTurn < lRow / 2 then
return ixAtTurnEnd + 1
end
end
-- no better idea, just use the original estimated
return waypointIxWhenFull
end
function CombineAIDriver:updateLightsOnField()
-- handle beacon lights to call unload driver
-- copy/paste from AIDriveStrategyCombine
local fillLevel = self.vehicle:getFillUnitFillLevel(self.combine.fillUnitIndex)
local capacity = self.vehicle:getFillUnitCapacity(self.combine.fillUnitIndex)
if fillLevel > (0.8 * capacity) then
if not self.beaconLightsActive then
self.vehicle:setAIMapHotspotBlinking(true)
self.vehicle:setBeaconLightsVisibility(true)
self.beaconLightsActive = true
end
else
if self.beaconLightsActive then
self.vehicle:setAIMapHotspotBlinking(false)
self.vehicle:setBeaconLightsVisibility(false)
self.beaconLightsActive = false
end
end
end
--- Create a temporary course to pull back to the right when the pipe is in the fruit so the tractor does not have
-- to drive in the fruit to get under the pipe
function CombineAIDriver:createPullBackCourse()
-- all we need is a waypoint on our right side towards the back
self.returnPoint = {}
self.returnPoint.x, _, self.returnPoint.z = getWorldTranslation(self.vehicle.rootNode)
local dx,_,dz = localDirectionToWorld(self:getDirectionNode(), 0, 0, 1)
self.returnPoint.rotation = MathUtil.getYRotationFromDirection(dx, dz)
dx,_,dz = localDirectionToWorld(self:getDirectionNode(), 0, 0, -1)
local x1, _, z1 = localToWorld(self:getDirectionNode(), -self.pullBackSideOffset, 0, -self.pullBackDistanceStart)
local x2, _, z2 = localToWorld(self:getDirectionNode(), -self.pullBackSideOffset, 0, -self.pullBackDistanceEnd)
-- both points must be on the field
if courseplay:isField(x1, z1) and courseplay:isField(x2, z2) then
local referenceNode, debugText = AIDriverUtil.getReverserNode(self.vehicle)
if referenceNode then
self:debug('Using %s to start pull back course', debugText)
else
referenceNode = AIDriverUtil.getDirectionNode(self.vehicle)
self:debug('Using the direction node to start pull back course')
end
-- don't make this too complicated, just create a straight line on the left/right side (depending on
-- where the pipe is and rely on the PPC, no need for generating fancy curves
return Course.createFromNode(self.vehicle, referenceNode,
-self.pullBackSideOffset, 0, -self.pullBackDistanceEnd, -2, true)
else
self:debug("Pull back course would be outside of the field")
return nil
end
end
function CombineAIDriver:createPullBackReturnCourse()
-- nothing fancy here either, just move forward a few meters before returning to the fieldwork course
local referenceNode = AIDriverUtil.getDirectionNode(self.vehicle)
return Course.createFromNode(self.vehicle, referenceNode, 0, 0, 6, 2, false)
end
--- Create a temporary course to make a pocket in the fruit on the right (or left), so we can move into that pocket and
--- wait for the unload there. This way the unload tractor does not have to leave the field.
--- We create a temporary course to reverse back far enough. After that, we return to the main course but
--- set an offset to the right (or left)
function CombineAIDriver:createPocketCourse()
local startIx = self.ppc:getLastPassedWaypointIx() or self.ppc:getCurrentWaypointIx()
-- find the waypoint we want to back up to
local backIx = self.course:getPreviousWaypointIxWithinDistance(startIx, self.pocketReverseDistance)
if not backIx then return nil end
-- this is where we'll stop in the pocket for unload
self.unloadInPocketIx = startIx - 2
-- this where we are back on track after returning from the pocket
self.returnedFromPocketIx = self.ppc:getCurrentWaypointIx()
self:debug('Backing up %.1f meters from waypoint %d to %d to make a pocket', self.pocketReverseDistance, startIx, backIx)
if startIx - backIx > 2 then
local pocketReverseWaypoints = {}
for i = startIx, backIx, -1 do
if self.course:isTurnStartAtIx(i) then
self:debug('There is a turn behind me at waypoint %d, no pocket', i)
return nil
end
local x, _, z = self.course:getWaypointPosition(i)
table.insert(pocketReverseWaypoints, {x = x, z = z, rev = true})
end
return Course(self.vehicle, pocketReverseWaypoints, true), backIx + 1
else
self:debug('Not enough waypoints behind me, no pocket')
return nil
end
end
--- Disable auto stop for choppers as when we stop the engine they'll also raise implements and the way we restart them
--- won't lower the header. So for now, just don't let them to stop the engine
function CombineAIDriver:isEngineAutoStopEnabled()
return not self:isChopper() and AIDriver.isEngineAutoStopEnabled(self)
end
--- Compatibility function for turn.lua to check if the vehicle should stop during a turn (for example while it
--- is held for unloading or waiting for the straw swath to stop
--- Turn.lua calls this in every cycle during the turn and will stop the vehicle if this returns true.
---@param isApproaching boolean if true we are still in the turn approach phase (still working on the field,
---not yet reached the turn start
---@param isHeadlandCorner boolean is this a headland turn?
function CombineAIDriver:holdInTurnManeuver(isApproaching, isHeadlandCorner)
local discharging = self:isDischarging() and not self:isChopper()
local waitForStraw = self.combine.strawPSenabled and not isApproaching and not isHeadlandCorner
self:debugSparse('discharging %s, held for unload %s, straw active %s, approaching = %s',
tostring(discharging), tostring(self.heldForUnloadRefill), tostring(self.combine.strawPSenabled), tostring(isApproaching))
return discharging or self.heldForUnloadRefill or waitForStraw
end
--- Should we return to the first point of the course after we are done?
function CombineAIDriver:shouldReturnToFirstPoint()
-- Combines stay where they are after finishing work
-- TODO: call unload driver
return false
end
--- Interface for Mode 2 and AutoDrive
---@return boolean true when the combine is waiting to be unloaded
function CombineAIDriver:isWaitingForUnload()
return self.state == self.states.ON_FIELDWORK_COURSE and
self.fieldworkState == self.states.UNLOAD_OR_REFILL_ON_FIELD and
(self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_UNLOAD_OR_REFILL or
self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_UNLOAD_IN_POCKET or
self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_UNLOAD_AFTER_PULLED_BACK or
self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_UNLOAD_AFTER_FIELDWORK_ENDED)
end
--- Interface for AutoDrive
---@return boolean true when the combine is waiting to be unloaded after it ended the course
function CombineAIDriver:isWaitingForUnloadAfterCourseEnded()
return self.state == self.states.ON_FIELDWORK_COURSE and
self.fieldworkState == self.states.UNLOAD_OR_REFILL_ON_FIELD and
self.fieldworkUnloadOrRefillState == self.states.WAITING_FOR_UNLOAD_AFTER_FIELDWORK_ENDED
end
function CombineAIDriver:createTurnCourse()
return CombineCourseTurn(self.vehicle, self, self.turnContext, self.fieldworkCourse)
end
--- Will we be driving forward only (not reversing) during a turn
function CombineAIDriver:isTurnForwardOnly()
return self:isTurning() and self.aiTurn and self.aiTurn:isForwardOnly()
end
function CombineAIDriver:getTurnCourse()
return self.aiTurn and self.aiTurn:getCourse()
end
function CombineAIDriver:startTurn(ix)
self:debug('Starting a combine turn.')
self:setMarkers()
self.turnContext = TurnContext(self.course, ix, self.aiDriverData, self.vehicle.cp.workWidth, self.frontMarkerDistance,
self:getTurnEndSideOffset())
-- Combines drive special headland corner maneuvers, except potato and sugarbeet harvesters
if self.turnContext:isHeadlandCorner() then
if self:isPotatoOrSugarBeetHarvester() then
self:debug('Headland turn but this harvester uses normal turn maneuvers.')
self.turnType = self.turnTypes.HEADLAND_NORMAL
UnloadableFieldworkAIDriver.startTurn(self, ix)
elseif self.course:isOnOutermostHeadland(ix) and self.vehicle.cp.turnOnField then
self:debug('Creating a pocket in the corner so the combine stays on the field during the turn')
self.aiTurn = CombinePocketHeadlandTurn(self.vehicle, self, self.turnContext, self.fieldworkCourse)
self.turnType = self.turnTypes.HEADLAND_POCKET
self.fieldworkState = self.states.TURNING
self.ppc:setShortLookaheadDistance()
else
self:debug('Use combine headland turn.')
self.aiTurn = CombineHeadlandTurn(self.vehicle, self, self.turnContext)
self.turnType = self.turnTypes.HEADLAND_EASY
self.fieldworkState = self.states.TURNING
end
else
self:debug('Non headland turn.')
self.turnType = self.turnTypes.UP_DOWN_NORMAL
UnloadableFieldworkAIDriver.startTurn(self, ix)
end
self:sendTurnStartEventToUnloaders(ix, self.turnType)
end
function CombineAIDriver:isTurning()
return self.state == self.states.ON_FIELDWORK_COURSE and self.fieldworkState == self.states.TURNING
end
-- Turning except in the ending turn phase which isn't really a turn, it is rather 'starting row'
function CombineAIDriver:isTurningButNotEndingTurn()
return self:isTurning() and self.aiTurn and not self.aiTurn:isEndingTurn()
end
function CombineAIDriver:isFinishingRow()
return self:isTurning() and self.aiTurn and self.aiTurn:isFinishingRow()
end
function CombineAIDriver:getTurnStartWpIx()
return self.turnContext and self.turnContext.turnStartWpIx or nil
end
function CombineAIDriver:isTurningOnHeadland()
return self.fieldworkState == self.states.TURNING and self.turnContext and self.turnContext:isHeadlandCorner()
end
---@param turnType table one of CombineAIDriver.turnTypes
function CombineAIDriver:isHeadlandTurn(turnType)
return turnType ~= CombineAIDriver.turnTypes.UP_DOWN_NORMAL
end
function CombineAIDriver:isTurningLeft()
return self.fieldworkState == self.states.TURNING and self.turnContext and self.turnContext:isLeftTurn()
end
function CombineAIDriver:getFieldworkCourse()
return self.fieldworkCourse
end
function CombineAIDriver:getWorkWidth()
return self.vehicle.cp.workWidth
end
--- Create a pocket in the next row at the corner to stay on the field during the turn maneuver.
---@param turnContext TurnContext
function CombineAIDriver:createOuterHeadlandCornerCourse(turnContext)
local cornerWaypoints = {}
local turnRadius = self.vehicle.cp.turnDiameter / 2
-- this is how far we have to cut into the next headland (the position where the header will be after the turn)
local offset = math.min(turnRadius + self.frontMarkerDistance, self.vehicle.cp.workWidth)
local corner = turnContext:createCorner(self.vehicle, turnRadius)
local d = -self.vehicle.cp.workWidth / 2 + self.frontMarkerDistance
local wp = corner:getPointAtDistanceFromCornerStart(d + 2)
wp.speed = self.vehicle.cp.speeds.turn * 0.75
table.insert(cornerWaypoints, wp)
-- drive forward up to the field edge
wp = corner:getPointAtDistanceFromCornerStart(d)
wp.speed = self.vehicle.cp.speeds.turn * 0.75
table.insert(cornerWaypoints, wp)
-- drive back to prepare for making a pocket
-- reverse back to set up for the headland after the corner
local reverseDistance = 2 * offset
wp = corner:getPointAtDistanceFromCornerStart(reverseDistance / 2)
wp.rev = true
table.insert(cornerWaypoints, wp)
wp = corner:getPointAtDistanceFromCornerStart(reverseDistance)
wp.rev = true
table.insert(cornerWaypoints, wp)
-- now make a pocket in the inner headland to make room to turn
wp = corner:getPointAtDistanceFromCornerStart(reverseDistance * 0.75, -offset * 0.75)
table.insert(cornerWaypoints, wp)
wp = corner:getPointAtDistanceFromCornerStart(reverseDistance * 0.5, -offset * 0.9)
if not courseplay:isField(wp.x, wp.z) then
self:debug('No field where the pocket would be, this seems to be a 270 corner')
corner:delete()
return nil
end
table.insert(cornerWaypoints, wp)
-- drive forward to the field edge on the inner headland
wp = corner:getPointAtDistanceFromCornerStart(d, -offset)
wp.speed = self.vehicle.cp.speeds.turn * 0.75
table.insert(cornerWaypoints, wp)
wp = corner:getPointAtDistanceFromCornerStart(reverseDistance / 2)
wp.rev = true
table.insert(cornerWaypoints, wp)
wp = corner:getPointAtDistanceFromCornerEnd(turnRadius / 3, turnRadius / 4)
wp.speed = self.vehicle.cp.speeds.turn * 0.5
table.insert(cornerWaypoints, wp)
wp = corner:getPointAtDistanceFromCornerEnd(turnRadius, turnRadius / 4)
wp.speed = self.vehicle.cp.speeds.turn * 0.5
table.insert(cornerWaypoints, wp)
corner:delete()
return Course(self.vehicle, cornerWaypoints, true), turnContext.turnEndWpIx
end
function CombineAIDriver:isChopper()
return self.combine:getFillUnitCapacity(self.combine.fillUnitIndex) > 10000000
end
function CombineAIDriver:handlePipe()
if self.pipe then
if self:isChopper() then