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
/
TriggerHandler.lua
1281 lines (1177 loc) · 51.5 KB
/
TriggerHandler.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
--- TODO: needs refactoring !
--- especially the loading.
TriggerHandler = CpObject()
TriggerHandler.myLoadingStates = {
IS_LOADING = {},
IS_LOADING_FUEL = {},
NOTHING = {},
IS_UNLOADING = {},
DRIVE_NOW = {},
STOPPED = {},
WAITING_FOR_UNLOAD_READY = {}
}
TriggerHandler.APPROACH_AUGER_TRIGGER_SPEED = 3
function TriggerHandler:init(driver,vehicle,siloSelectedFillTypeSetting)
self.vehicle = vehicle
self.driver = driver
self.siloSelectedFillTypeSetting=siloSelectedFillTypeSetting
self.alwaysSearchFuel = vehicle.cp.settings.alwaysSearchFuel
self.validFillTypeLoading = false
self.validFillTypeUnloading = false
self.validFillTypeUnloadingAugerWagon = false
self.validFuelLoading = false
self.loadingState = StateModule(self,"debug", self.vehicle)
self.loadingState:initStates(TriggerHandler.myLoadingStates)
self.loadingState.state = self.loadingState.states.STOPPED
self.objectsInTrigger= {}
self.fillableObject = nil
self.lastLoadedFillTypes = {}
self.debugTicks = 10
self.debugChannel = courseplay.DBG_TRIGGERS
self.lastDistanceToTrigger = nil
self.lastDebugLoadingCallback = nil
end
function TriggerHandler:isDebugActive()
return courseplay.debugChannels[courseplay.DBG_LOAD_UNLOAD]
end
function TriggerHandler:debugSparse(vehicle,...)
if g_updateLoopIndex % self.debugTicks == 0 then
courseplay.debugVehicle(self.debugChannel, vehicle, ...)
end
end
function TriggerHandler:debug(vehicle,...)
courseplay.debugVehicle(self.debugChannel, vehicle, ...)
end
function TriggerHandler:onStart()
self:changeLoadingState("NOTHING")
self.lastDistanceToTrigger = nil
self.objectsInTrigger = {}
self.lastLoadedFillTypes = {}
end
function TriggerHandler:onStop()
self:changeLoadingState("STOPPED")
self:forceStopLoading()
end
function TriggerHandler:onUpdate(dt)
if not self:isDriveNowActivated() and not self:isStopped() then
self:updateLoadingTriggers()
end
if not self:isStopped() then
if self.validFillTypeUnloading then
self:updateUnloadingTriggers(dt)
end
if not self:isUnloading() then
if self.driver:hasSugarCaneTrailerToolPositions() then
self.driver:isWorkingToolPositionReached(dt,SugarCaneTrailerToolPositionsSetting.TRANSPORT_POSITION)
end
end
end
--temp hack to reset driveNow
local isNearWaitPoint, waitPointIx = (self.driver.ppc:getCurrentWaypointIx()-5)>1 and self.driver.course:hasWaitPointWithinDistance(self.driver.ppc:getCurrentWaypointIx()-5, 10)
if not self:isInTrigger() and not isNearWaitPoint then
if self:isDriveNowActivated() then
self:changeLoadingState("NOTHING")
end
end
end
--debug info
function TriggerHandler:onDraw()
if self:isDebugActive() then
local y = 0.5
y = self:renderText(y,"validFillTypeLoading: "..tostring(self.validFillTypeLoading))
y = self:renderText(y,"validFillTypeUnloading: "..tostring(self.validFillTypeUnloading))
y = self:renderText(y,"loadingState: "..tostring(self.loadingState:getName()))
y = self:renderText(y,"isInTrigger: "..tostring(self:isInTrigger()))
local yTable = {}
yTable.y = y
self:debugDischargeNodes(self.vehicle,yTable)
y=yTable.y
if self.lastDebugLoadingCallback then
self:debugLoadingCallback(self.lastDebugLoadingCallback)
end
if self.fillableObject then
self:debugFillableObject(self.fillableObject)
end
end
end
function TriggerHandler:debugDischargeNodes(object,yTable)
local spec = object.spec_dischargeable
if spec then
local node = object:getCurrentDischargeNode()
if node then
yTable.y = self:renderText(yTable.y,"object: "..nameNum(object))
yTable.y = self:renderText(yTable.y,"has dischargeObject: "..tostring(node.dischargeObject and true or false))
end
end
for _,impl in pairs(object:getAttachedImplements()) do
self:debugDischargeNodes(impl.object,yTable)
end
end
TriggerHandler.debugLoadingCallbackData = {}
TriggerHandler.debugLoadingCallbackData[0] = "Max"
TriggerHandler.debugLoadingCallbackData[1] = "Counter"
TriggerHandler.debugLoadingCallbackData[2] = "separate"
TriggerHandler.debugLoadingCallbackData[3] = "min"
TriggerHandler.debugLoadingCallbackData[4] = "ok"
TriggerHandler.debugLoadingCallbackData[5] = "skip"
TriggerHandler.debugLoadingCallbackData[6] = "done"
function TriggerHandler:debugLoadingCallback(loadingCallback)
if not loadingCallback or not loadingCallback[1] then
return
end
local y = 0.5
local lastCallbackData = nil
y = self:renderText(y,"debugLoadingCallback:",0.2)
y = self:renderText(y,string.format("fillUnitIndex: %s",tostring(loadingCallback[1].fillUnitIndex)),0.2)
for indexCallback,callbackData in ipairs(loadingCallback) do
local data = callbackData.data
local fillType = data.fillType
lastCallbackData = callbackData
local text = string.format("index: %s, fillType: %s, callback: %s",indexCallback,tostring(g_fillTypeManager:getFillTypeByIndex(fillType).title),self.debugLoadingCallbackData[callbackData.callback])
y = self:renderText(y,text,0.2)
end
if lastCallbackData then
local text = string.format("lastCallback: fillType: %s, callback: %s",tostring(g_fillTypeManager:getFillTypeByIndex(lastCallbackData.data.fillType).title),self.debugLoadingCallbackData[lastCallbackData.callback])
y = self:renderText(y,text,0.2)
end
end
function TriggerHandler:debugFillableObject(fillableObject)
local y = 0.5
local lastCallbackData = nil
y = self:renderText(y,"debugFillableObject:",0.4)
y = self:renderText(y,string.format("object: %s",nameNum(fillableObject.object)),0.4)
y = self:renderText(y,string.format("fillUnitIndex: %s",tostring(fillableObject.fillUnitIndex)),0.4)
y = self:renderText(y,string.format("fillType: %s",tostring(fillableObject.fillType)),0.4)
y = self:renderText(y,string.format("trigger: %s",tostring(fillableObject.trigger)),0.4)
y = self:renderText(y,string.format("isLoading: %s",tostring(fillableObject.isLoading)),0.4)
y = self:renderText(y,text,0.4)
end
function TriggerHandler:renderText(y,text,xOffset)
renderText(xOffset and 0.3+xOffset or 0.3,y,0.02,tostring(text))
return y-0.02
end
function TriggerHandler:onUpdateTick(dt)
end
function TriggerHandler:onContinue()
self:forceStopLoading()
if self:isStopped() then
self:changeLoadingState("NOTHING")
elseif self:isLoading() or self:isUnloading() then
self:changeLoadingState("NOTHING")
end
end
function TriggerHandler:writeUpdateStream(streamId)
self.loadingState:onWriteUpdateStream(streamId)
end
function TriggerHandler:readUpdateStream(streamId)
self.loadingState:onReadUpdateStream(streamId)
end
function TriggerHandler:onWriteStream(streamId)
self.loadingState:onWriteStream(streamId)
end
function TriggerHandler:onReadStream(streamId)
self.loadingState:onReadStream(streamId)
end
function TriggerHandler:onDriveNow()
self:setDriveNow()
end
function TriggerHandler:changeLoadingState(newState)
self.loadingState:changeState(newState)
end
function TriggerHandler:updateLoadingTriggers()
if self.validFillTypeLoading or self:isAllowedToLoadFuel() then
self:activateLoadingTriggerWhenAvailable()
end
if self:isLoading() or self:isLoadingFuel() then
self:disableFillingIfFull()
end
end
function TriggerHandler:updateUnloadingTriggers(dt)
if self:isUnloading() then
self:disableUnloadingIfEmpty()
if self.driver:hasSugarCaneTrailerToolPositions() then
self.driver:isWorkingToolPositionReached(dt,SugarCaneTrailerToolPositionsSetting.UNLOADING_POSITION)
end
end
end
function TriggerHandler:disableFillingIfFull()
if self:isFilledUntilPercentageX() then
self:forceStopLoading()
self:resetLoadingState()
end
end
--saftey check as driver sometimes dosen't restart automaticlly
function TriggerHandler:disableUnloadingIfEmpty()
if self.fillableObject then
local fillUnitIndex = self.fillableObject.fillUnitIndex
local object = self.fillableObject.object
if object:getFillUnitFillLevelPercentage(fillUnitIndex)*100 < 0.5 and (object.spec_waterTrailer or self.driver:hasSugarCaneTrailerToolPositions()) then
self:resetUnloadingState()
end
end
end
function TriggerHandler:isFilledUntilPercentageX()
if self.fillableObject then
local fillUnitIndex = self.fillableObject.fillUnitIndex
local object = self.fillableObject.object
local fillType = self.fillableObject.fillType
local maxFillLevelPercentage = not self:isLoadingFuel() and self.siloSelectedFillTypeSetting:getMaxFillLevelByFillType(self.fillableObject.fillType) or 99
return not self:maxFillLevelNotReached(object,fillUnitIndex,maxFillLevelPercentage,fillType)
end
end
function TriggerHandler:getSiloSelectedFillTypeData()
if self.siloSelectedFillTypeSetting then
local fillTypeData = self.siloSelectedFillTypeSetting:getData()
local size = self.siloSelectedFillTypeSetting:getSize()
return fillTypeData,size
end
end
function TriggerHandler:getTriggerDischargeNode(trigger)
return trigger.dischargeInfo and trigger.dischargeInfo.nodes and (trigger.dischargeInfo.nodes.node or trigger.dischargeInfo.nodes[1].node) -- or trigger.triggerNode
end
--used to move the trailer more to the middle, but not really reliable,
--as we can't do a proper full stop or calculate the need distance to stop
function TriggerHandler:isNearDischargeNode(object,fillUnitIndex,trigger)
if object and fillUnitIndex and trigger then
local node = object:getFillUnitExactFillRootNode(fillUnitIndex)
local triggerNode = self:getTriggerDischargeNode(trigger)
if node and triggerNode then
if self:isDebugActive() then
DebugUtil.drawDebugNode(node,"relevant node")
DebugUtil.drawDebugNode(triggerNode,"trigger node")
end
local distance = calcDistanceFrom(triggerNode, node)
if self.lastDistanceToTrigger and distance > self.lastDistanceToTrigger then
self:debugSparse(object,"dischargeNode and TriggerNode distance okay !")
return true
else
self.driver:setSpeed(math.min(0.5,distance))
self:debugSparse(object,"dischargeNode and TriggerNode distance not okay, continue..!")
self.lastDistanceToTrigger = distance
end
elseif node == nil then
self:debugSparse(object,"dischargeNodeX not found!")
return true
else
self:debugSparse(object,"TriggerNodeX not found!")
return true
end
else
self:debugSparse(object,"dischargeNode or TriggerNode not found!")
end
end
----
--Driver set to wait while loading
function TriggerHandler:setLoadingState(object,fillUnitIndex,fillType,trigger)
if self:isLoadingFuel() then
self:setFuelLoadingState(object,fillUnitIndex,fillType,trigger)
return
end
self:setFillableObject(object,fillUnitIndex,fillType,trigger,true)
--saftey check for drive now
if not self:isDriveNowActivated() and not self:isLoading() then
self:changeLoadingState("IS_LOADING")
end
end
--Driver set to wait while loading
function TriggerHandler:setFuelLoadingState(object,fillUnitIndex,fillType,trigger)
self:setFillableObject(object,fillUnitIndex,fillType,trigger,true)
--saftey check for drive now
if not self:isLoadingFuel() then
self:changeLoadingState("IS_LOADING_FUEL")
end
end
function TriggerHandler:setFillableObject(object,fillUnitIndex,fillType,trigger,isLoading)
if object then
self.fillableObject = {}
self.fillableObject.object = object
self.fillableObject.fillUnitIndex = fillUnitIndex
self.fillableObject.fillType = fillType
self.fillableObject.trigger = trigger
self.fillableObject.isLoading = isLoading
end
self.driver:refreshHUD()
end
function TriggerHandler:resetFillableObject()
self.fillableObject=nil
end
function TriggerHandler:isLoading()
return self.loadingState:is("IS_LOADING") or self:isLoadingFuel()
end
function TriggerHandler:isLoadingFuel()
return self.loadingState:is("IS_LOADING_FUEL")
end
function TriggerHandler:isUnloading()
return self.loadingState:is("IS_UNLOADING")
end
--Driver stops loading
function TriggerHandler:resetLoadingState()
if not self:isDriveNowActivated() then
self:changeLoadingState("NOTHING")
end
self:resetFillableObject()
end
--Driver set to wait while unloading
function TriggerHandler:setUnloadingState(object,fillUnitIndex,fillType)
self:setFillableObject(object,fillUnitIndex,fillType)
if not self:isDriveNowActivated() then
self:changeLoadingState("IS_UNLOADING")
end
self.driver:refreshHUD()
end
--Driver stops unloading
function TriggerHandler:resetUnloadingState()
if not self:isDriveNowActivated() then
self:changeLoadingState("NOTHING")
end
self:resetFillableObject()
end
function TriggerHandler:setDriveNow()
if self:isLoading() or self:isUnloading() then
self:forceStopLoading()
self:changeLoadingState("DRIVE_NOW")
end
if self:isUnloading() then
courseplay:resetTipTrigger(self.vehicle, true);
end
end
--AIDriver uses this function to check if we are in trigger or not!
function TriggerHandler:isInTrigger()
local oldCpTrigger = self.vehicle.cp.currentTipTrigger
if oldCpTrigger and oldCpTrigger.bunkerSilo ~= nil then
return false
end
return self.validFillTypeUnloading and self.driver:hasTipTrigger()
end
function TriggerHandler:isDriveNowActivated()
return self.loadingState:is("DRIVE_NOW")
end
function TriggerHandler:isStopped()
return self.loadingState:is("STOPPED")
end
--force stop loading/ unloading if "continue" or stop is pressed
function TriggerHandler:forceStopLoading()
if self.fillableObject then
if self.fillableObject.trigger then
if self.fillableObject.trigger:isa(Vehicle) then --disable filling at Augerwagons
--TODO!!
else --disable filling at LoadingTriggers
self.fillableObject.trigger:setIsLoading(false)
end
else
if self.fillableObject.isLoading then -- disable filling at fillTriggers
self:debug(self.fillableObject,"forceStop setFillUnitIsFilling")
self.fillableObject.object:setFillUnitIsFilling(false)
elseif self.fillableObject.object.setDischargeState then -- disable unloading
self.fillableObject.object:setDischargeState(Dischargeable.DISCHARGE_STATE_OFF)
end
end
end
end
function TriggerHandler:needsFuel()
local currentFuelPercentage = self.driver:getFuelLevelPercentage()
local searchForFuel = self.alwaysSearchFuel:is(true) and currentFuelPercentage <99 or currentFuelPercentage < 20
if searchForFuel then
return true
end
end
--scanning for LoadingTriggers and FillTriggers(checkFillTriggers)
function TriggerHandler:activateLoadingTriggerWhenAvailable()
for key, object in pairs(g_currentMission.activatableObjects) do
if object:getIsActivatable(self.vehicle) and self:isObjectALoadingTrigger(object) then
self:activateTriggerForVehicle(object, self.vehicle)
end
end
end
function TriggerHandler:isObjectALoadingTrigger(object)
return object.source and (object.source.getAllFillLevels or object.source.getAllProvidedFillLevels)
end
function TriggerHandler:enableFillTypeLoading()
self.validFillTypeLoading = true
end
function TriggerHandler:enableFillTypeUnloading()
self.validFillTypeUnloading = true
end
function TriggerHandler:enableFillTypeUnloadingBunkerSilo()
self.validFillTypeUnloadingBunkerSilo = true
end
function TriggerHandler:enableFillTypeUnloadingAugerWagon()
self.validFillTypeUnloadingAugerWagon = true
end
function TriggerHandler:enableFuelLoading()
self.validFuelLoading = true
end
function TriggerHandler:disableFillTypeLoading()
self.validFillTypeLoading = false
if self.siloSelectedFillTypeSetting and self.siloSelectedFillTypeSetting:isRunCounterActive() then
self.siloSelectedFillTypeSetting:decrementRunCounterByFillType(self.lastLoadedFillTypes)
self.driver:refreshHUD()
end
self.lastLoadedFillTypes = {}
end
function TriggerHandler:disableFillTypeUnloading()
self.validFillTypeUnloading = false
self.validFillTypeUnloadingAugerWagon = false
self.validFillTypeUnloadingBunkerSilo = false
end
function TriggerHandler:disableFuelLoading()
self.validFuelLoading = false
end
function TriggerHandler:isAllowedToLoadFillType()
if self.validFillTypeLoading and self.siloSelectedFillTypeSetting then
return true
end
end
function TriggerHandler:isAllowedToLoadFuel()
if self.validFuelLoading and self:needsFuel() then
return true
end
end
function TriggerHandler:isAllowedToUnloadAtBunkerSilo()
return self.validFillTypeUnloadingBunkerSilo
end
--Loading Trigger callback check
--1: maxFillLevel reached
--2: runCounter valid or can be ignored
--3: load seperarteFillType activated or ignored
--4: minFillLevel reached or allowed to drive if trigger empty
TriggerHandler.CALLBACK = {}
TriggerHandler.CALLBACK.MAX_REACHED = 0
TriggerHandler.CALLBACK.RUN_COUNTER_NOT_REACHED = 1
TriggerHandler.CALLBACK.SEPARATE_FILLTYPE_NOT_ALLOWED = 2
TriggerHandler.CALLBACK.MIN_NOT_REACHED = 3
TriggerHandler.CALLBACK.OK = 4
TriggerHandler.CALLBACK.SKIP_LOADING = 5
TriggerHandler.CALLBACK.DONE_LOADING = 6
function TriggerHandler:triggerCanStartLoading(trigger,object,fillUnitIndex,triggerFillLevel,data, dataLength)
--is fillLevel < maxFillLevel
local callback = nil
local fillType = data.fillType
if self:maxFillLevelNotReached(object,fillUnitIndex,data.maxFillLevel,fillType) then
--if runCounter activated and runCounter > 0
if self:isRunCounterValid(data.runCounter,data.fillType) then
-- is separateFillTypeLoading not activated or separateFillType not loaded yet
if self:isAllowedToLoadSeparateFillType(object,dataLength,fillType) then
-- is minFillLevelPercentage in trigger or infinity fillLevel trigger or autoStart at trigger
if triggerFillLevel and triggerFillLevel> 0 or trigger.hasInfiniteCapacity or triggerFillLevel == nil then -- or trigger.autoStart then
if data.minFillLevel == 0 or self:isMinFillLevelReachedToLoad(object,fillUnitIndex,triggerFillLevel,data.minFillLevel,fillType) then
callback = self.CALLBACK.OK
else --minFillLevel not reached!!
callback = self.CALLBACK.SKIP_LOADING
self:debugSparse(object,"skip loading trigger < min needed, %s",tostring(g_fillTypeManager:getFillTypeByIndex(fillType).title))
end
else --triggerFillLevel is empty!!
local fillLevelPercentage
if object.spec_mixerWagon then
local fillLevel = AIDriverUtil.getMixerWagonFillLevelForFillTypes(object,fillType)
fillLevelPercentage = fillLevel/object:getFillUnitCapacity(fillUnitIndex)*100
else
fillLevelPercentage = object:getFillUnitFillLevelPercentage(fillUnitIndex)*100
end
if fillLevelPercentage> 0 then
if fillLevelPercentage >= data.minFillLevel then
if fillType == object:getFillUnitFillType(fillUnitIndex) then
callback = self.CALLBACK.DONE_LOADING
self:debugSparse(object,"skip loading triggerEmpty min reached, %s",tostring(g_fillTypeManager:getFillTypeByIndex(fillType).title))
else
callback = self.CALLBACK.SKIP_LOADING
self:debugSparse(object,"skip loading triggerEmpty, skip to next fillType, %s",tostring(g_fillTypeManager:getFillTypeByIndex(fillType).title))
end
else
callback = self.CALLBACK.MIN_NOT_REACHED
self:debugSparse(object,"skip loading triggerEmpty waiting for more, %s",tostring(g_fillTypeManager:getFillTypeByIndex(fillType).title))
end
else
callback = self.CALLBACK.SKIP_LOADING
self:debugSparse(object,"skip loading triggerEmpty, skip to next fillType, %s",tostring(g_fillTypeManager:getFillTypeByIndex(fillType).title))
end
end
else
callback = self.CALLBACK.SEPARATE_FILLTYPE_NOT_ALLOWED
self:debugSparse(object,"Sepeate filltype not allowed, %s",tostring(g_fillTypeManager:getFillTypeByIndex(fillType).title))
end
else
callback = self.CALLBACK.RUN_COUNTER_NOT_REACHED
self:debugSparse(object,"skip loading, runcounter = 0, %s",tostring(g_fillTypeManager:getFillTypeByIndex(fillType).title))
end
else
callback = self.CALLBACK.MAX_REACHED
end
return callback
end
--- Checks if the max fill level is not reached.
---@param object table
---@param fillUnitIndex number
---@param maxFillLevelPercentage number
---@param fillType number
---@return boolean max fill level is reached.
function TriggerHandler:maxFillLevelNotReached(object,fillUnitIndex,maxFillLevelPercentage,fillType)
local fillLevelPercentage = 0
local fillLevel = AIDriverUtil.getMixerWagonFillLevelForFillTypes(object,fillType)
if fillLevel then
fillLevelPercentage = fillLevel/object:getFillUnitCapacity(fillUnitIndex)*100
else
fillLevelPercentage = object:getFillUnitFillLevelPercentage(fillUnitIndex)*100
end
self:debugSparse(object,"maxFillLevel:, fillPercentage: %s > maxFillLevel: %s, fillType: %s",tostring(fillLevelPercentage),tostring(maxFillLevelPercentage),tostring(g_fillTypeManager:getFillTypeByIndex(fillType).title))
return fillLevelPercentage < (maxFillLevelPercentage or 99)
end
--- Checks if the min fill level to start loading is there.
---@param object table
---@param fillUnitIndex number
---@param triggerFillLevel number
---@param minFillLevelPercentage number
---@param fillType number
---@return boolean min fill level to start loading is reached.
function TriggerHandler:isMinFillLevelReachedToLoad(object,fillUnitIndex,triggerFillLevel,minFillLevelPercentage,fillType)
local capacity = object:getFillUnitCapacity(fillUnitIndex)
local fillLevel = AIDriverUtil.getMixerWagonFillLevelForFillTypes(object,fillType)
if not fillLevel then
fillLevel = object:getFillUnitFillLevel(fillUnitIndex)
end
local minNeededFillLevel = minFillLevelPercentage and minFillLevelPercentage*0.01*capacity - fillLevel or 0.1
self:debugSparse(object,"min FillLevel:, triggerFillLevel: %s, objectFillCapacity: %s, minNeededFillLevel: %s, fillType: %s",tostring(triggerFillLevel),tostring(capacity),tostring(minNeededFillLevel),tostring(g_fillTypeManager:getFillTypeByIndex(fillType).title))
return triggerFillLevel and triggerFillLevel > minNeededFillLevel
end
--- Checks if run counter is enabled and still valid.
---@param runCounter number
---@param fillType number
---@return boolean run counter is valid.
function TriggerHandler:isRunCounterValid(runCounter,fillType)
return runCounter and runCounter>0 or runCounter == nil
end
--- Check if loading separate fill types is allowed and valid.
---@param object table
---@param dataLength number
---@param fillType number
---@return boolean is separate fill type loading allowed.
function TriggerHandler:isAllowedToLoadSeparateFillType(object,dataLength,fillType)
local separateFillTypeLoading = self.driver:getSeparateFillTypeLoadingSetting()
if object.spec_mixerWagon or not separateFillTypeLoading then
return true
end
--- If the fill type was already loaded or less then max diff fill types were loaded.
if separateFillTypeLoading:hasDiffFillTypes() and #self.lastLoadedFillTypes < separateFillTypeLoading:get() then
return not self.lastLoadedFillTypes[fillType]
end
return true
end
-- Custom version of trigger:onActivateObject to allow activating for a non-controlled vehicle
function TriggerHandler:activateTriggerForVehicle(trigger, vehicle)
--Cache giant values to restore later
local defaultGetFarmIdFunction = g_currentMission.getFarmId;
local oldControlledVehicle = g_currentMission.controlledVehicle;
--Override farm id to match the calling vehicle (fixes issue when obtaining fill levels)
local overriddenFarmIdFunc = function()
local ownerFarmId = vehicle:getOwnerFarmId()
courseplay.debugVehicle(courseplay.DBG_TRIGGERS, vehicle, 'Overriding farm id during trigger activation to %d', ownerFarmId);
return ownerFarmId;
end
g_currentMission.getFarmId = overriddenFarmIdFunc;
--Override controlled vehicle if I'm not in it
if g_currentMission.controlledVehicle ~= vehicle then
g_currentMission.controlledVehicle = vehicle;
end
--Call giant method with new params set
trigger:onActivateObject(vehicle)
--Restore previous values
g_currentMission.getFarmId = defaultGetFarmIdFunction;
g_currentMission.controlledVehicle = oldControlledVehicle;
end
-- LoadTrigger doesn't allow filling non controlled tools
function TriggerHandler:getIsActivatable(superFunc,objectToFill)
--when the trigger is filling, it uses this function without objectToFill
if objectToFill then
local oldVehicle = {}
local oldVehicle = g_currentMission.controlledVehicle
local vehicle = objectToFill:getRootVehicle()
g_currentMission.controlledVehicle = vehicle or objectToFill
local bool = superFunc(self,objectToFill)
g_currentMission.controlledVehicle = oldVehicle
return bool
else
return superFunc(self,objectToFill)
end
end
LoadTrigger.getIsActivatable = Utils.overwrittenFunction(LoadTrigger.getIsActivatable,TriggerHandler.getIsActivatable)
--LoadTrigger activate, if fillType is right and fillLevel ok
function TriggerHandler:onActivateObject(superFunc,vehicle)
--self = LoadTrigger!
if courseplay:isAIDriverActive(vehicle) then
local triggerHandler = vehicle.cp.driver.triggerHandler
if not triggerHandler:isAllowedToLoadFuel() and not triggerHandler:isAllowedToLoadFillType() then
return superFunc(self)
end
if not self.isLoading then
local fillLevels, capacity
--normal fillLevels of silo
if self.source.getAllFillLevels then
fillLevels, capacity = self.source:getAllFillLevels(g_currentMission:getFarmId())
--g_company fillLevels of silo
elseif self.source.getAllProvidedFillLevels then --g_company fillLevels
--self.managerId should be self.extraParameter!!!
fillLevels, capacity = self.source:getAllProvidedFillLevels(g_currentMission:getFarmId(), self.managerId)
else
return superFunc(self)
end
local fillableObject = self.validFillableObject
local fillUnitIndex = self.validFillableFillUnitIndex
--fixes giants bug for Lemken Solitaer with has fillunit that keeps on filling to infinity
if fillableObject:getFillUnitCapacity(fillUnitIndex) <=0 then
triggerHandler:resetLoadingState()
return
end
-- local node = fillableObject:getFillUnitExactFillRootNode(fillUnitIndex)
-- DebugUtil.drawDebugNode(node, "ExactFillRootNode", false)
--checks if we are in the fillPlane, bugged with mode 4 as driver dosen't stop fast enough..
if not triggerHandler:isNearDischargeNode(fillableObject,fillUnitIndex,self) then
triggerHandler:resetLoadingState()
return
elseif not triggerHandler:isDriveNowActivated() then
--- vehicle.cp.driver:hold()
end
if fillableObject.spec_cover and fillableObject.spec_cover.isDirty then
triggerHandler:setLoadingState()
triggerHandler:debugSparse(fillableObject, 'Cover is still opening!')
return
end
local fillTypeData,fillTypeDataSize = triggerHandler:getSiloSelectedFillTypeData()
local loadingCallback = {}
local indexCallback = 1
if triggerHandler:isAllowedToLoadFillType() then
for _,data in ipairs(fillTypeData) do
for fillTypeIndex, fillLevel in pairs(fillLevels) do
if fillableObject:getFillUnitAllowsFillType(fillUnitIndex, fillTypeIndex) and fillTypeIndex == data.fillType and data.fillType ~= nil then
local callback = triggerHandler:triggerCanStartLoading(self,fillableObject,fillUnitIndex,fillLevel,data,fillTypeDataSize)
loadingCallback[indexCallback] = {}
loadingCallback[indexCallback].callback = callback
loadingCallback[indexCallback].data = data
loadingCallback[indexCallback].fillLevelTrigger = fillLevel
loadingCallback[indexCallback].fillUnitIndex = fillUnitIndex
indexCallback = indexCallback +1
end
end
end
end
--seperarte for only loading Fuel in to motors!
if triggerHandler:isAllowedToLoadFuel() and fillableObject == vehicle then
for fillTypeIndex, fillLevel in pairs(fillLevels) do
if vehicle.cp.driver:isValidFuelType(fillableObject,fillTypeIndex) then
if fillableObject:getFillUnitAllowsFillType(fillUnitIndex, fillTypeIndex) then
if triggerHandler:maxFillLevelNotReached(fillableObject,fillUnitIndex,99,fillTypeIndex) then
if fillLevel>0 then
triggerHandler:setFuelLoadingState()
self:onFillTypeSelection(fillTypeIndex)
g_currentMission.activatableObjects[self] = nil
return
else
triggerHandler:setFuelLoadingState()
g_globalInfoTextHandler:setInfoText(vehicle, 'FARM_SILO_IS_EMPTY')
courseplay.debugFormat(courseplay.DBG_LOAD_UNLOAD, 'No Diesel at this trigger.')
end
else
courseplay.debugFormat(courseplay.DBG_LOAD_UNLOAD, 'max FillLevel Reached')
triggerHandler:resetLoadingState()
end
end
end
end
end
if loadingCallback and #loadingCallback > 0 then
triggerHandler:handleLoadingCallback(self,fillableObject,fillUnitIndex,loadingCallback)
end
end
else
return superFunc(self)
end
end
LoadTrigger.onActivateObject = Utils.overwrittenFunction(LoadTrigger.onActivateObject,TriggerHandler.onActivateObject)
--- Evaluates the trigger callback. Basically handles the loading start,stop and so on..
---@param trigger table
---@param object table
---@param fillUnitIndex number
---@param loadingCallback table
function TriggerHandler:handleLoadingCallback(trigger,object,fillUnitIndex,loadingCallback)
local lastCallbackData = nil
self.lastDebugLoadingCallback = loadingCallback
for indexCallback,callbackData in ipairs(loadingCallback) do
local data = callbackData.data
local fillType = data.fillType
lastCallbackData = callbackData
--all okay start loading
if callbackData.callback == TriggerHandler.CALLBACK.OK then
self.lastLoadedFillTypes[fillType] = true
if trigger and trigger.onFillTypeSelection then
trigger:onFillTypeSelection(fillType)
else
object:setFillUnitIsFilling(true,nil,callbackData.currentTrigger)
self:setLoadingState(object,callbackData.fillUnitIndex,fillType)
end
self:debugSparse(object, 'LoadingTrigger: start Loading, fillType: '..g_fillTypeManager:getFillTypeByIndex(fillType).title)
return
--max FillLevel reached
elseif callbackData.callback == TriggerHandler.CALLBACK.MAX_REACHED and not object.spec_mixerWagon then
self:resetLoadingState()
self:debugSparse(object, 'LoadingTrigger: max Reached, fillType: '..g_fillTypeManager:getFillTypeByIndex(fillType).title)
return
-- min FillLevel not reached to start filling
elseif callbackData.callback == TriggerHandler.CALLBACK.MIN_NOT_REACHED then
self:setLoadingState()
g_globalInfoTextHandler:setInfoText(self.vehicle, 'FARM_SILO_IS_EMPTY');
self:debugSparse(object, 'LoadingTrigger: minLevel not reached, fillType: '..g_fillTypeManager:getFillTypeByIndex(fillType).title)
return
--min is reached so continue..
elseif callbackData.callback == TriggerHandler.CALLBACK.DONE_LOADING and not object.spec_mixerWagon then
lastCallbackData = nil
self:resetLoadingState()
self:debugSparse(object, 'LoadingTrigger: continue!! : '..g_fillTypeManager:getFillTypeByIndex(fillType).title)
return
end
end
--runCounter = 0
if lastCallbackData and lastCallbackData.callback == TriggerHandler.CALLBACK.RUN_COUNTER_NOT_REACHED then
self:setLoadingState()
g_globalInfoTextHandler:setInfoText(self.vehicle, 'RUNCOUNTER_ERROR_FOR_TRIGGER');
self:debugSparse(object, 'last runCounter=0, fillType: '..g_fillTypeManager:getFillTypeByIndex(lastCallbackData.data.fillType).title)
return
end
if lastCallbackData and (lastCallbackData.callback == TriggerHandler.CALLBACK.SKIP_LOADING or lastCallbackData.callback == TriggerHandler.CALLBACK.SEPARATE_FILLTYPE_NOT_ALLOWED) then
--not enough fillTypes loaded!!
self:setLoadingState()
g_globalInfoTextHandler:setInfoText(self.vehicle, 'FARM_SILO_IS_EMPTY');
self:debugSparse(object, 'last FillType minLevel not reached, fillType: '..g_fillTypeManager:getFillTypeByIndex(lastCallbackData.data.fillType).title)
return
end
if lastCallbackData and loadingCallback.callback == TriggerHandler.CALLBACK.MAX_REACHED then
self:resetLoadingState()
self:debugSparse(object, 'LoadingTrigger: max Reached, fillType: '..g_fillTypeManager:getFillTypeByIndex(fillType).title)
return
end
end
--LoadTrigger => start/stop driver and close cover once free from trigger
function TriggerHandler:setIsLoading(superFunc,isLoading, targetObject, fillUnitIndex, fillType, noEventSend)
if self.validFillableObject then
local rootVehicle = self.validFillableObject:getRootVehicle()
if courseplay:isAIDriverActive(rootVehicle) then
local triggerHandler = rootVehicle.cp.driver.triggerHandler
if not triggerHandler.validFillTypeLoading and not triggerHandler.validFuelLoading then
return superFunc(self,isLoading, targetObject, fillUnitIndex, fillType, noEventSend)
end
if isLoading then
triggerHandler:setLoadingState(self.validFillableObject,fillUnitIndex, fillType,self)
triggerHandler:debug(self.validFillableObject, 'LoadTrigger setLoading, FillType: '..g_fillTypeManager:getFillTypeByIndex(fillType).title)
else
triggerHandler:resetLoadingState()
triggerHandler:debug(self.validFillableObject, 'LoadTrigger resetLoading and close Cover')
g_currentMission:addActivatableObject(self)
end
end
end
return superFunc(self,isLoading, targetObject, fillUnitIndex, fillType, noEventSend)
end
LoadTrigger.setIsLoading = Utils.overwrittenFunction(LoadTrigger.setIsLoading,TriggerHandler.setIsLoading)
--close cover after tipping for trailer if not closed already
function TriggerHandler:endTipping(superFunc,noEventSend)
local rootVehicle = self:getRootVehicle()
if courseplay:isAIDriverActive(rootVehicle) then
rootVehicle.cp.driver.triggerHandler:debug(self,"finished unloading, endTipping !! ")
if rootVehicle.cp.settings.automaticCoverHandling:is(true) and self.spec_cover then
self:setCoverState(0, true)
end
rootVehicle.cp.driver.triggerHandler:resetUnloadingState()
end
return superFunc(self,noEventSend)
end
Trailer.endTipping = Utils.overwrittenFunction(Trailer.endTipping,TriggerHandler.endTipping)
--pass trigger from updateFillUnitTriggers to spec
function TriggerHandler:setFillUnitIsFilling(superFunc,isFilling, noEventSend,trigger)
local spec = self.spec_fillUnit
local rootVehicle = self:getRootVehicle()
if courseplay:isAIDriverActive(rootVehicle) then
if isFilling ~= spec.fillTrigger.isFilling then
if noEventSend == nil or noEventSend == false then
if g_server ~= nil then
g_server:broadcastEvent(SetFillUnitIsFillingEvent:new(self, isFilling), nil, nil, self)
else
g_client:getServerConnection():sendEvent(SetFillUnitIsFillingEvent:new(self, isFilling))
end
end
spec.fillTrigger.isFilling = isFilling
if trigger then
spec.fillTrigger.currentTrigger = trigger
end
if self.isClient then
self:setFillSoundIsPlaying(isFilling)
if spec.fillTrigger.currentTrigger ~= nil then
spec.fillTrigger.currentTrigger:setFillSoundIsPlaying(isFilling)
end
end
if not trigger then
spec.fillTrigger.currentTrigger = nil
end
SpecializationUtil.raiseEvent(self, "onFillUnitIsFillingStateChanged", isFilling)
end
else
return superFunc(self,isFilling, noEventSend)
end
end
FillUnit.setFillUnitIsFilling = Utils.overwrittenFunction(FillUnit.setFillUnitIsFilling,TriggerHandler.setFillUnitIsFilling)
--LoadTrigger callback used to open correct cover for loading
function TriggerHandler:loadTriggerCallback(triggerId, otherId, onEnter, onLeave, onStay, otherShapeId)
local rootVehicle
local fillableObject = g_currentMission:getNodeObject(otherId)
if fillableObject and fillableObject:isa(Vehicle) then
rootVehicle = fillableObject:getRootVehicle()
end
if not self.courseplayersInTrigger then
self.courseplayersInTrigger = {}
end
if rootVehicle then
if onLeave then
if self.courseplayersInTrigger[rootVehicle] then
self.courseplayersInTrigger[rootVehicle][fillableObject] = nil
if next(self.courseplayersInTrigger[rootVehicle]) == nil then
self.courseplayersInTrigger[rootVehicle] = nil
end
end
else
if self.courseplayersInTrigger[rootVehicle] == nil then
self.courseplayersInTrigger[rootVehicle]= {}
end
self.courseplayersInTrigger[rootVehicle][fillableObject] = true
end
end
if courseplay:isAIDriverActive(rootVehicle) then
TriggerHandler.handleLoadTriggerCallback(self,triggerId, otherId, onEnter, onLeave, onStay, otherShapeId,rootVehicle,fillableObject)
end
end
LoadTrigger.loadTriggerCallback = Utils.appendedFunction(LoadTrigger.loadTriggerCallback,TriggerHandler.loadTriggerCallback)
function TriggerHandler.handleLoadTriggerCallback(self,triggerId, otherId, onEnter, onLeave, onStay, otherShapeId,rootVehicle,fillableObject)
if onEnter then
courseplay.debugVehicle(courseplay.DBG_LOAD_UNLOAD,fillableObject, 'LoadTrigger onEnter')
if fillableObject.getFillUnitIndexFromNode ~= nil then
local fillLevels, capacity
if self.source.getAllFillLevels then
fillLevels, capacity = self.source:getAllFillLevels(g_currentMission:getFarmId())
elseif self.source.getAllProvidedFillLevels then
fillLevels, capacity = self.source:getAllProvidedFillLevels(g_currentMission:getFarmId(), self.managerId)
end
if fillLevels then
local foundFillUnitIndex = fillableObject:getFillUnitIndexFromNode(otherId)
for fillTypeIndex, fillLevel in pairs(fillLevels) do
if fillableObject:getFillUnitSupportsFillType(foundFillUnitIndex, fillTypeIndex) then
if fillableObject:getFillUnitAllowsFillType(foundFillUnitIndex, fillTypeIndex) and fillableObject.spec_cover then
SpecializationUtil.raiseEvent(fillableObject, "onAddedFillUnitTrigger",fillTypeIndex,foundFillUnitIndex,1)
courseplay.debugVehicle(courseplay.DBG_LOAD_UNLOAD,fillableObject,"LoadTrigger: open Cover for loading")
end
end
end
end
end
end
if onLeave then
local stillInTrailer = false
for id,data in pairs(self.fillableObjects) do
if data.object.getRootVehicle then
stillInTrailer = data.object:getRootVehicle() == rootVehicle
end
end
if not stillInTrailer then
local spec = fillableObject.spec_fillUnit
SpecializationUtil.raiseEvent(fillableObject, "onRemovedFillUnitTrigger",#spec.fillTrigger.triggers)
end
courseplay.debugVehicle(courseplay.DBG_LOAD_UNLOAD,fillableObject, 'LoadTrigger: onLeave, disableTriggerSpeed')
else
courseplay.debugVehicle(courseplay.DBG_LOAD_UNLOAD,fillableObject, 'LoadTrigger: enableTriggerSpeed')
end
courseplay.debugVehicle(courseplay.DBG_LOAD_UNLOAD,fillableObject, "validFillableObject: "..nameNum(self.validFillableObject))
end
--FillTrigger callback used to set approach speed for Cp driver
function TriggerHandler:fillTriggerCallback(superFunc, triggerId, otherId, onEnter, onLeave, onStay, otherShapeId)
local fillableObject = g_currentMission:getNodeObject(otherId)
local rootVehicle
if fillableObject and fillableObject:isa(Vehicle) then
rootVehicle = fillableObject:getRootVehicle()
end
if not self.courseplayersInTrigger then
self.courseplayersInTrigger = {}
end
if onEnter and rootVehicle then
if self.courseplayersInTrigger[rootVehicle] == nil then
self.courseplayersInTrigger[rootVehicle]= {}
end
self.courseplayersInTrigger[rootVehicle][fillableObject] = true
elseif onLeave and rootVehicle then
if self.courseplayersInTrigger[rootVehicle] then
self.courseplayersInTrigger[rootVehicle][fillableObject] = nil
if next(self.courseplayersInTrigger[rootVehicle]) == nil then
self.courseplayersInTrigger[rootVehicle] = nil