Repository navigation
Expand file tree
/
Copy pathIAGameLoopHelper.lua
More file actions
4035 lines (3789 loc) · 164 KB
/
Copy pathIAGameLoopHelper.lua
File metadata and controls
4035 lines (3789 loc) · 164 KB
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
--
-- FS25 - InteractiveNeighbours - Game Loop Helper
--
-- @Interface: 1.0.0.0
-- @Author: AirFoxTwo
-- @Date: 23.01.2026
-- @Version: 1.0.0.0
-- Helper class for scenario generation logic
IAGameLoopHelper = {}
IAGameLoopHelper._mt = Class(IAGameLoopHelper)
-- Minimum distance (meters) from player to a place for a situation to be created there (avoids spawning when player is nearby)
IAGameLoopHelper.MIN_PLAYER_DISTANCE_FOR_PLACE_SITUATION = 20
-- Allowed crops for "next crop" selection (must match crops used in situations/fields_of_stories_situations.xml seed and fieldwork)
IAGameLoopHelper.NEXT_CROP_WHITELIST_NAMES = {
"CANOLA",
"WHEAT",
"BARLEY",
"OAT",
"SOYBEAN"
}
-- Daily fieldwork ordering (lower = earlier): harvest, seed, spray, fertilize subtypes, plow, harrow, cultivate — batch similar machines.
-- Keyed by IAFieldwork.JobType.* (canonical strings) so it tracks the enum without separate string drift.
IAGameLoopHelper.FIELDWORK_TYPE_PRIORITY = {
[IAFieldwork.JobType.HARVEST] = 1,
[IAFieldwork.JobType.HARVEST_DELIVER_CORN] = 1,
[IAFieldwork.JobType.GRASS_MOWING] = 2,
[IAFieldwork.JobType.SEED] = 3,
[IAFieldwork.JobType.SPRAY] = 4,
[IAFieldwork.JobType.MANURESPREADING] = 5,
[IAFieldwork.JobType.SLURRYSPREADING] = 5,
[IAFieldwork.JobType.FERTILIZEDSPREADING] = 5,
[IAFieldwork.JobType.LIME] = 5,
[IAFieldwork.JobType.STONE_PICKING] = 5,
[IAFieldwork.JobType.PLOW] = 6,
[IAFieldwork.JobType.HARROW] = 7,
[IAFieldwork.JobType.CULTIVATE] = 8,
[IAFieldwork.JobType.IA_FIELD_OUTCOME] = 9,
}
-- Phone-accepted fieldwork uses IAFieldOutcomeMission only (no vanilla FertilizeMission / tryGenerateMission).
-- Inbound contract rings per schedule day: first at callPlayerHour:Minute, then at least +1 in-game hour from the previous actual ring.
IAGameLoopHelper.CONTRACT_CALL_MAX_RING_OPENS_PER_DAY = 3
IAGameLoopHelper.CONTRACT_CALL_RETRY_MIN_INGAME_MINUTES = 60
-- Maximum number of fields/farmlands a neighbour can outsource as contracts per day
IAGameLoopHelper.CONTRACT_MAX_FIELDS_PER_NEIGHBOUR_PER_DAY = 3
-- Create a new IAGameLoopHelper instance
-- @param table ianeighboursInstance - Reference to IANeighbours instance
function IAGameLoopHelper.new(ianeighboursInstance)
local self = setmetatable({}, IAGameLoopHelper._mt)
self.ianeighbours = ianeighboursInstance
self.homebaseParking = IAHomebaseParking.new(ianeighboursInstance)
return self
end
-- True if situation placetypes match runtime place.type or semantic basePlaceType (e.g. shop on player farm is type player_farm).
local function placeMatchesPlacetypes(place, placetypes)
if place == nil or placetypes == nil or #placetypes == 0 then
return false
end
if type(IAHelper_valueEqualsAnyInArrayIgnoreCase) == "function" and IAHelper_valueEqualsAnyInArrayIgnoreCase(place.type, placetypes) then
return true
end
local sem = (place.getSemanticType ~= nil and place:getSemanticType()) or place.type
if sem ~= nil and sem ~= place.type and type(IAHelper_valueEqualsAnyInArrayIgnoreCase) == "function" and IAHelper_valueEqualsAnyInArrayIgnoreCase(sem, placetypes) then
return true
end
return false
end
-- Place sizeType values that situations must explicitly opt into via <placeSizes>; never selected by default.
-- Silo places are storage buildings, not parking bays, and must never be selected for vehicle/attachment parking.
local IA_EXCLUSIVE_PLACE_SIZE_TYPES = {
["large_area"] = true,
["silo"] = true,
}
--- True when the place's sizeType satisfies the situation config's <placeSizes> list.
-- - Empty/missing list: allow any size EXCEPT entries in IA_EXCLUSIVE_PLACE_SIZE_TYPES (opt-in only).
-- - Non-empty list: place.sizeType (case-insensitive) must equal one of the listed values.
local function placeMatchesRequestedSize(place, situationConfig)
if place == nil then
return false
end
local requested = situationConfig and situationConfig.placeSizes
local st = (place.sizeType ~= nil) and string.lower(tostring(place.sizeType)) or nil
if requested ~= nil and #requested > 0 then
if st == nil then
return false
end
if type(IAHelper_valueEqualsAnyInArrayIgnoreCase) == "function" then
return IAHelper_valueEqualsAnyInArrayIgnoreCase(st, requested) == true
end
for _, item in ipairs(requested) do
if string.lower(tostring(item)) == st then
return true
end
end
return false
end
if st ~= nil and IA_EXCLUSIVE_PLACE_SIZE_TYPES[st] == true then
return false
end
return true
end
--- Rebuild IAGameLoopHelper._placesByTypeBuckets when #places changed.
function IAGameLoopHelper:rebuildPlacesByTypeBucketsIfNeeded()
local places = self.ianeighbours and self.ianeighbours.places
if places == nil then
self._placesByTypeBuckets = nil
self._placesByTypeBucketsLen = nil
return
end
local n = #places
if self._placesByTypeBuckets ~= nil and self._placesByTypeBucketsLen == n then
return
end
local buckets = {}
for _, place in ipairs(places) do
if place ~= nil and place.type ~= nil then
local t1 = string.lower(tostring(place.type))
if buckets[t1] == nil then
buckets[t1] = {}
end
table.insert(buckets[t1], place)
local sem = (place.getSemanticType ~= nil and place:getSemanticType()) or nil
if sem ~= nil then
local t2 = string.lower(tostring(sem))
if t2 ~= t1 then
if buckets[t2] == nil then
buckets[t2] = {}
end
table.insert(buckets[t2], place)
end
end
end
end
self._placesByTypeBuckets = buckets
self._placesByTypeBucketsLen = n
end
function IAGameLoopHelper:invalidatePlacesTypeBucketCache()
self._placesByTypeBuckets = nil
self._placesByTypeBucketsLen = nil
end
--- Union of places that might match placetypes (type / semantic buckets), deduped; each entry verified with placeMatchesPlacetypes.
function IAGameLoopHelper:collectPlacesMatchingPlacetypes(placetypes)
self:rebuildPlacesByTypeBucketsIfNeeded()
local buckets = self._placesByTypeBuckets
if buckets == nil or placetypes == nil then
return {}
end
local seen = {}
local out = {}
for _, pt in ipairs(placetypes) do
local k = string.lower(tostring(pt))
for _, place in ipairs(buckets[k] or {}) do
if not seen[place] and placeMatchesPlacetypes(place, placetypes) then
seen[place] = true
table.insert(out, place)
end
end
end
return out
end
--- Priority rank for sorting fieldwork (unknown types last).
-- @param string|nil fieldworkLower - lowercase job string from config.fieldwork
-- @return number
function IAGameLoopHelper.getFieldworkPriorityRank(fieldworkLower)
if fieldworkLower == nil or fieldworkLower == "" then
return 999
end
local p = IAGameLoopHelper.FIELDWORK_TYPE_PRIORITY[fieldworkLower]
if p ~= nil then
return p
end
if IAFieldwork ~= nil and type(IAFieldwork.normalizeFieldworkJobType) == "function" then
local jt = IAFieldwork.normalizeFieldworkJobType(fieldworkLower)
if jt ~= nil then
local pj = IAGameLoopHelper.FIELDWORK_TYPE_PRIORITY[jt]
if pj ~= nil then
return pj
end
end
end
return 998
end
local function configIdSortKey(config)
if config == nil or config.id == nil then
return "\255"
end
local n = tonumber(config.id)
if n ~= nil then
return string.format("%012d", n)
end
return tostring(config.id)
end
local function compareFieldworkScheduleTasks(a, b)
if a == nil or b == nil then
return false
end
local ja = (a.config and a.config.fieldwork) and string.lower(tostring(a.config.fieldwork)) or ""
local jb = (b.config and b.config.fieldwork) and string.lower(tostring(b.config.fieldwork)) or ""
local ra = IAGameLoopHelper.getFieldworkPriorityRank(ja)
local rb = IAGameLoopHelper.getFieldworkPriorityRank(jb)
if ra ~= rb then
return ra < rb
end
-- Field order is a per-neighbour, per-day random permutation (fieldOrderKey) instead of
-- ascending farmlandId, so neighbours don't always start at their lowest field id.
-- Falls back to farmlandId when no random key was assigned (e.g. legacy loaded rows).
local fa = a.fieldOrderKey or a.farmlandId or 0
local fb = b.fieldOrderKey or b.farmlandId or 0
if fa ~= fb then
return fa < fb
end
return configIdSortKey(a.config) < configIdSortKey(b.config)
end
-- True if the planned next crop may be sown in the current period (FruitType growthDataSeasonal.plantingAllowed),
-- or when that data is missing, if current month appears on any matching SEED situation (legacy XML months).
function IAGameLoopHelper:isSowingMonthForPlannedSeed(neighbour, farmlandId, monthOverride)
if neighbour == nil or farmlandId == nil or self.ianeighbours.situationConfigs == nil then
return false
end
local nextCrop = (neighbour.assignedFarmlandNextCrop ~= nil and neighbour.assignedFarmlandNextCrop[farmlandId] ~= nil)
and neighbour.assignedFarmlandNextCrop[farmlandId]
or self:getNextCropForField(neighbour, farmlandId)
if nextCrop == nil then
return false
end
-- When an explicit month is given (day-end completion), convert to the matching
-- growth period so iaIsFruitTypePlantingAllowedInPeriod checks the right calendar
-- window instead of the post-rollover environment period.
local period = nil
if monthOverride ~= nil then
local om = tonumber(monthOverride)
if om ~= nil then
if om >= 3 then
period = om - 2
else
period = om + 10
end
end
end
local planting = iaIsFruitTypePlantingAllowedInPeriod(nextCrop, period)
if planting == true then
return true
end
if planting == false then
return false
end
local currentMonth = monthOverride
if currentMonth == nil then
currentMonth = getEnvironmentMonth1to12()
end
if currentMonth == nil then
return false
end
currentMonth = tonumber(currentMonth) or currentMonth
for _, config in ipairs(self.ianeighbours.situationConfigs) do
if config ~= nil and config.type ~= nil and string.lower(tostring(config.type)) == "fieldwork"
and config.fieldwork ~= nil and string.lower(tostring(config.fieldwork)) == "seed" then
if self:doesSituationConfigMatchNeighbour(config, neighbour) then
local seedIdx = IAFieldwork.resolveFruitTypeNameOrIndex(config.seedFruitTypeIndex)
if seedIdx ~= nil and seedIdx == nextCrop and config.months ~= nil and #config.months > 0 then
for _, monthNum in ipairs(config.months) do
if currentMonth == (tonumber(monthNum) or monthNum) then
return true
end
end
end
end
end
end
return false
end
function IAGameLoopHelper:findSituationConfigById(situationId)
if situationId == nil or self.ianeighbours.situationConfigs == nil then
return nil
end
for _, config in ipairs(self.ianeighbours.situationConfigs) do
if config ~= nil and tostring(config.id) == tostring(situationId) then
return config
end
end
return nil
end
--- True when an IAFieldOutcomeMission (player phone contract) is currently bound to the given farmland and not yet finished.
--- Falls back to scanning g_missionManager.missions when farmland.field.currentMission has not been set yet
--- (e.g. mission registered but startMission deferred). Active situations the AI started do not count here.
-- @param number farmlandId
-- @return boolean
function IAGameLoopHelper:hasActivePlayerFieldOutcomeForFarmland(farmlandId)
if farmlandId == nil then
return false
end
farmlandId = tonumber(farmlandId)
if farmlandId == nil then
return false
end
if g_farmlandManager ~= nil and type(g_farmlandManager.getFarmlands) == "function" then
local farmlands = g_farmlandManager:getFarmlands()
if farmlands ~= nil then
for _, f in pairs(farmlands) do
if f ~= nil and tonumber(f.id) == farmlandId and f.field ~= nil then
local mission = f.field.currentMission
if mission ~= nil and mission.farmId ~= nil then
return true
end
end
end
end
end
if g_missionManager ~= nil and g_missionManager.missions ~= nil then
for _, m in pairs(g_missionManager.missions) do
if m ~= nil and m.iaFieldsOfStoriesMission == true then
local mFarmland = m.iaFieldFarmlandId
if mFarmland == nil and m.field ~= nil and type(m.field.getFarmlandId) == "function" then
mFarmland = m.field:getFarmlandId()
end
if mFarmland ~= nil and tonumber(mFarmland) == farmlandId then
if MissionStatus == nil or m.status == nil
or m.status == MissionStatus.RUNNING
or m.status == MissionStatus.PREPARING
or m.status == MissionStatus.CREATED then
return true
end
end
end
end
end
return false
end
-- Build ordered daily queue from open candidates; mutates neighbour fieldwork schedule fields.
-- @param table|nil opts { defineContracts = bool (default true), isDayChange = bool (default false) }
-- defineContracts=true: pick outsource type, set random call window, mark contractEnabled rows (6:00 run).
-- defineContracts=false: preserve existing outsourceType/callHour/callMinute; match contractEnabled by
-- identical (situationId, farmlandId) from old schedule; new rows of the same type get contractEnabled
-- up to the cap. Clears contract bookkeeping only on day change.
function IAGameLoopHelper:rebuildDailyFieldworkSchedule(neighbour, opts)
opts = opts or {}
local defineContracts = opts.defineContracts ~= false -- default true
local isDayChange = opts.isDayChange == true
local additiveOnly = opts.additiveOnly == true
local year, month, dayIn = getEnvironmentYearMonthDayInPeriod()
-- Save old schedule for contract preservation (before we potentially clear it)
local oldContractKeys = {}
local oldOutsourcedJobType = nil
local existingRowKeys = {} -- set of "situationId|farmlandId" already in schedule
if (not defineContracts or additiveOnly) and neighbour.fieldworkScheduleTasks ~= nil then
for _, row in ipairs(neighbour.fieldworkScheduleTasks) do
if row ~= nil and row.situationId ~= nil and row.farmlandId ~= nil then
local rk = tostring(row.situationId) .. "|" .. tostring(row.farmlandId)
existingRowKeys[rk] = true
if row.contractEnabled == true then
oldContractKeys[rk] = true
end
end
end
oldOutsourcedJobType = neighbour._iaLastOutsourcedJobType
end
-- Determine if we need to define contracts: either explicit, or additive mode with zero existing contracts.
-- Also treats acceptedByPlayer rows as "contracts already handled" so we don't redefine after player acceptance.
-- Likewise checks contractFallbackToAiFiredForScheduleKey (decline) and contractCallRingAnsweredToday (answered) so a resolved call doesn't trigger fresh contracts.
local hasPlayerAcceptedContract = false
if additiveOnly and not defineContracts then
local hasAnyContract = false
if neighbour.fieldworkScheduleTasks ~= nil then
for _, row in ipairs(neighbour.fieldworkScheduleTasks) do
if row ~= nil and row.contractEnabled == true then
hasAnyContract = true
end
if row ~= nil and row.acceptedByPlayer == true then
hasPlayerAcceptedContract = true
end
if hasAnyContract and hasPlayerAcceptedContract then
break
end
end
end
local scheduleKey = self:getFieldworkScheduleDayKey(neighbour)
-- acceptedByPlayer / decline / already-answered-today all count as "contracts handled" —
-- don't auto-define fresh ones (prevents a same-day re-call after the player resolved a call).
if not hasAnyContract and not hasPlayerAcceptedContract
and neighbour.contractCallRingAnsweredToday ~= true
and neighbour.contractFallbackToAiFiredForScheduleKey ~= scheduleKey then
defineContracts = true
end
end
--- Normalized fieldwork key for daily planning (stubble_cultivation → harrow; sow → seed).
local function fieldworkKeyForOutsource(cfg)
local jt = (cfg ~= nil and cfg.fieldwork) and string.lower(tostring(cfg.fieldwork)) or ""
if jt == "" then return "" end
if IAFieldwork ~= nil and type(IAFieldwork.normalizeFieldworkJobType) == "function" then
local n = IAFieldwork.normalizeFieldworkJobType(jt)
if n ~= nil then return n end
end
return jt
end
local all = self:collectOpenFieldworkCandidates(neighbour)
-- In additive mode, filter out candidates already present in the schedule.
if additiveOnly then
local newCandidates = {}
for _, c in ipairs(all) do
local rk = tostring(c.config.id) .. "|" .. tostring(c.farmlandId)
if not existingRowKeys[rk] then
table.insert(newCandidates, c)
end
end
all = newCandidates
end
-- Always stamp the day so calendarDayMatchesStoredSchedule works correctly
-- even when there are no candidates.
neighbour.fieldworkScheduleYear = year
neighbour.fieldworkScheduleMonth = month
neighbour.fieldworkScheduleDayInPeriod = dayIn
if #all == 0 then
return
end
-- From here on we know we have candidates. Clear the schedule only in non-additive mode.
if not additiveOnly then
neighbour.fieldworkScheduleTasks = {}
-- Only clear contract bookkeeping on day-change rebuilds (not on mid-day refreshes)
if isDayChange or defineContracts then
neighbour.contractCallTriggerFiredForScheduleKey = nil
neighbour.contractCallRingOpensCount = 0
neighbour.contractCallRingAnsweredToday = false
neighbour.contractFallbackToAiFiredForScheduleKey = nil
neighbour.contractCallLastRingScheduleKey = nil
neighbour.contractCallLastRingTotalMinutes = nil
end
else
-- Additive mode: never clear existing rows. But if we auto-enabled
-- defineContracts (no contracts existed), reset call bookkeeping.
if neighbour.fieldworkScheduleTasks == nil then
neighbour.fieldworkScheduleTasks = {}
end
if defineContracts then
neighbour.contractCallTriggerFiredForScheduleKey = nil
neighbour.contractCallRingOpensCount = 0
neighbour.contractCallRingAnsweredToday = false
neighbour.contractFallbackToAiFiredForScheduleKey = nil
neighbour.contractCallLastRingScheduleKey = nil
neighbour.contractCallLastRingTotalMinutes = nil
end
end
if IATestRunner ~= nil and type(IATestRunner.onScheduleRebuildBegin) == "function" then
IATestRunner.onScheduleRebuildBegin(neighbour)
end
local byField = {}
for _, c in ipairs(all) do
local fid = c.farmlandId
if byField[fid] == nil then byField[fid] = {} end
table.insert(byField[fid], c)
end
local chosen = {}
for _, farmlandId in ipairs(neighbour.assignedFarmlands) do
local matches = byField[farmlandId]
if matches ~= nil and #matches > 0 then
local urgent = self:isSowingMonthForPlannedSeed(neighbour, farmlandId)
if urgent then
local bestByJob = {}
for _, c in ipairs(matches) do
local jt = fieldworkKeyForOutsource(c.config)
local prev = bestByJob[jt]
if prev == nil or configIdSortKey(c.config) < configIdSortKey(prev.config) then
bestByJob[jt] = c
end
end
for _, c in pairs(bestByJob) do
table.insert(chosen, c)
end
else
local best = nil
for _, c in ipairs(matches) do
local jt = (c.config and c.config.fieldwork) and string.lower(tostring(c.config.fieldwork)) or ""
local rank = IAGameLoopHelper.getFieldworkPriorityRank(jt)
if best == nil then
best = c
else
local bjt = string.lower(tostring(best.config.fieldwork))
local br = IAGameLoopHelper.getFieldworkPriorityRank(bjt)
if rank < br or (rank == br and configIdSortKey(c.config) < configIdSortKey(best.config)) then
best = c
end
end
end
if best ~= nil then
table.insert(chosen, best)
end
end
end
end
-- Random field order permutation
local fieldOrderKeyByFarmland = {}
do
local ids = {}
for _, fid in ipairs(neighbour.assignedFarmlands) do table.insert(ids, fid) end
for i = #ids, 2, -1 do
local j = math.random(1, i)
ids[i], ids[j] = ids[j], ids[i]
end
for rank, fid in ipairs(ids) do fieldOrderKeyByFarmland[fid] = rank end
end
for _, c in ipairs(chosen) do c.fieldOrderKey = fieldOrderKeyByFarmland[c.farmlandId] end
table.sort(chosen, compareFieldworkScheduleTasks)
-- Determine outsource type: pick fresh when defineContracts, else preserve from old schedule
local outsourcedJobType = nil
if defineContracts then
local activeJobTypeKey = nil
if neighbour.activeSituation ~= nil and neighbour.activeSituation.jobType ~= nil then
local rawActive = string.lower(tostring(neighbour.activeSituation.jobType))
if IAFieldwork ~= nil and type(IAFieldwork.normalizeFieldworkJobType) == "function" then
local norm = IAFieldwork.normalizeFieldworkJobType(rawActive)
if norm ~= nil and norm ~= "" then activeJobTypeKey = norm end
end
if activeJobTypeKey == nil and rawActive ~= "" then activeJobTypeKey = rawActive end
end
local distinctNonHarvestTypes = {}
local seenType = {}
local jobTypeLacksEquipment = {}
for _, c in ipairs(chosen) do
local key = fieldworkKeyForOutsource(c.config)
if key ~= "" and (activeJobTypeKey == nil or key ~= activeJobTypeKey) and not seenType[key] then
seenType[key] = true
table.insert(distinctNonHarvestTypes, key)
if IAFieldwork ~= nil and type(IAFieldwork.neighbourHasFleetEquipmentForJobType) == "function" then
if not IAFieldwork.neighbourHasFleetEquipmentForJobType(neighbour, key) then
jobTypeLacksEquipment[key] = true
end
end
end
end
if #distinctNonHarvestTypes > 0 then
local weightedPool = {}
for _, jt in ipairs(distinctNonHarvestTypes) do
table.insert(weightedPool, jt)
if jobTypeLacksEquipment[jt] then table.insert(weightedPool, jt) end
end
outsourcedJobType = weightedPool[math.random(1, #weightedPool)]
end
if IATestRunner ~= nil and type(IATestRunner.forceOutsourceType) == "string" and IATestRunner.forceOutsourceType ~= "" then
outsourcedJobType = IATestRunner.forceOutsourceType
end
neighbour._iaLastOutsourcedJobType = outsourcedJobType
neighbour.callPlayerHour = math.random(8, 14)
neighbour.callPlayerMinute = math.random(0, 59)
else
outsourcedJobType = oldOutsourcedJobType
end
-- Determine contract eligibility for each row
local function rowIsContractForOutsource(c)
local key = fieldworkKeyForOutsource(c.config)
return outsourcedJobType ~= nil and key == outsourcedJobType
end
local function rowKey(c)
return tostring(c.config.id) .. "|" .. tostring(c.farmlandId)
end
local aiFirst = {}
local contractTail = {}
for _, c in ipairs(chosen) do
if rowIsContractForOutsource(c) then
table.insert(contractTail, c)
else
table.insert(aiFirst, c)
end
end
local ordered = {}
for _, c in ipairs(aiFirst) do table.insert(ordered, c) end
for _, c in ipairs(contractTail) do table.insert(ordered, c) end
local maxContractFields = IAGameLoopHelper.CONTRACT_MAX_FIELDS_PER_NEIGHBOUR_PER_DAY
if IASettings ~= nil and type(IASettings.getContractMaxFieldsPerNeighbour) == "function" then
local settingCap = IASettings.getContractMaxFieldsPerNeighbour()
if settingCap ~= nil then maxContractFields = settingCap end
end
-- In additive mode, count existing contracts so we respect the cap across old + new rows.
local contractFieldCount = 0
if additiveOnly and neighbour.fieldworkScheduleTasks ~= nil then
for _, row in ipairs(neighbour.fieldworkScheduleTasks) do
if row ~= nil and row.contractEnabled == true then
contractFieldCount = contractFieldCount + 1
end
end
end
for _, c in ipairs(ordered) do
local row = { situationId = c.config.id, farmlandId = c.farmlandId }
if c.nextCropFruitTypeIndex ~= nil then row.seedFruitTypeIndex = c.nextCropFruitTypeIndex end
if rowIsContractForOutsource(c) then
local rk = rowKey(c)
if defineContracts then
-- Fresh contract marking based on chosen outsource type (6:00 or additive with zero contracts)
if maxContractFields < 0 or contractFieldCount < maxContractFields then
row.contractEnabled = true
contractFieldCount = contractFieldCount + 1
end
elseif oldContractKeys[rk] then
-- Preserve: same row was contract before, keep it
if maxContractFields < 0 or contractFieldCount < maxContractFields then
row.contractEnabled = true
contractFieldCount = contractFieldCount + 1
end
elseif not hasPlayerAcceptedContract
and neighbour.contractCallRingAnsweredToday ~= true
and (maxContractFields < 0 or contractFieldCount < maxContractFields) then
-- New row of the contract type — add to the bundle (up to cap),
-- but only when the player hasn't already accepted contracts today.
row.contractEnabled = true
contractFieldCount = contractFieldCount + 1
end
end
table.insert(neighbour.fieldworkScheduleTasks, row)
end
if IATestRunner ~= nil and type(IATestRunner.onScheduleRebuildEnd) == "function" then
IATestRunner.onScheduleRebuildEnd(neighbour, outsourcedJobType)
end
if self.ianeighbours.debug then
local contractCount = 0
for _, t in ipairs(neighbour.fieldworkScheduleTasks) do
if t.contractEnabled then contractCount = contractCount + 1 end
end
print("--- IAGameLoopHelper:rebuildDailyFieldworkSchedule() - "..tostring(neighbour.name).." y="..tostring(year).." m="..tostring(month).." d="..tostring(dayIn).." tasks="..tostring(#neighbour.fieldworkScheduleTasks).." outsourceType="..tostring(outsourcedJobType or "none").." contracts="..tostring(contractCount).." defineContracts="..tostring(defineContracts).." callAt="..string.format("%02d:%02d", neighbour.callPlayerHour or 0, neighbour.callPlayerMinute or 0))
end
end
--- Apply completed field state for every still-valid row on yesterday's schedule (day rollover, before rebuild).
--- Skips accepted contracts (active mission), already-worked fields, and stale rows via validateScheduleEntry.
function IAGameLoopHelper:autoCompleteScheduledFieldworkAtDayEnd(neighbour)
if neighbour == nil or neighbour.fieldworkScheduleTasks == nil or #neighbour.fieldworkScheduleTasks == 0 then
return
end
if IAFieldwork == nil or type(IAFieldwork.enqueueCompleteFieldworkFieldUpdate) ~= "function" then
return
end
if g_farmlandManager == nil or type(g_farmlandManager.getFarmlands) ~= "function" then
return
end
local completed = 0
local completedMonth = nil
if neighbour ~= nil and neighbour.fieldworkScheduleMonth ~= nil then
completedMonth = tonumber(neighbour.fieldworkScheduleMonth)
end
if completedMonth == nil then
completedMonth = getEnvironmentMonth1to12()
end
local tasks = neighbour.fieldworkScheduleTasks
for _, row in ipairs(tasks) do
local ok, err = pcall(function()
-- Resolve the job type up front: harvest needs relaxed validation at day end (see below),
-- so we must know the job before calling validateScheduleEntry.
local rowConfig = self:findSituationConfigById(row ~= nil and row.situationId or nil)
if rowConfig == nil or rowConfig.fieldwork == nil or rowConfig.fieldwork == "" then
return
end
local jobType = nil
if type(IAFieldwork.normalizeFieldworkJobType) == "function" then
jobType = IAFieldwork.normalizeFieldworkJobType(string.lower(tostring(rowConfig.fieldwork)))
end
if jobType == nil then
return
end
-- The calendar already rolled over before this runs, so the engine applied a day of growth
-- and withering. A harvest-ready crop left unworked yesterday is now withered and no longer
-- matches the situation's harvest growth trigger; relax the field-state trigger check for
-- harvest so the withered crop is still cleared (harvested) here.
local validateOpts = (jobType == IAFieldwork.JobType.HARVEST) and { skipFieldStateTriggerMatch = true } or nil
local valid = self:validateScheduleEntry(neighbour, row, validateOpts)
if valid == nil then
return
end
local field = nil
local farmlands = g_farmlandManager:getFarmlands()
if farmlands ~= nil then
for _, f in pairs(farmlands) do
if f ~= nil and f.id == valid.farmlandId and f.field ~= nil then
field = f.field
break
end
end
end
if field == nil then
return
end
local seedFruitTypeIndex = valid.nextCropFruitTypeIndex
local fertilizeSprayTypeIndex = nil
if type(IAFieldwork.getFertilizeSprayTypeIndexForJobType) == "function" then
fertilizeSprayTypeIndex = IAFieldwork.getFertilizeSprayTypeIndexForJobType(jobType)
end
-- Day-end variant compensates for the elapsed day: seeded crops advance one growth stage
-- (they would have grown overnight). Harvest leaves the field in its harvested (cut) state
-- even when the crop withered overnight.
local enqueued = false
if type(IAFieldwork.enqueueCompleteFieldworkFieldUpdateForDayEnd) == "function" then
enqueued = IAFieldwork.enqueueCompleteFieldworkFieldUpdateForDayEnd(field, jobType, seedFruitTypeIndex, fertilizeSprayTypeIndex)
else
IAFieldwork.enqueueCompleteFieldworkFieldUpdate(field, jobType, seedFruitTypeIndex, fertilizeSprayTypeIndex)
enqueued = true
end
if enqueued then
completed = completed + 1
end
end)
if not ok and self.ianeighbours ~= nil and self.ianeighbours.debug then
print("--- IAGameLoopHelper:autoCompleteScheduledFieldworkAtDayEnd() - row failed: " .. tostring(err))
end
end
-- Fast-forward urgent seeding: when a field is in a pre-seed pipeline state
-- (harvested, stubble, plowed, cultivated) and the planned next crop must be
-- sown in the current month, bypass multi-day cultivation and seed directly.
-- Uses the same day-end FieldUpdateTask so the crop gets the overnight growth
-- compensation built into enqueueCompleteFieldworkFieldUpdateForDayEnd.
if IAFieldwork ~= nil and IAFieldwork.JobType ~= nil and IAFieldwork.JobType.SEED ~= nil then
local grassFruitTypeIndex = IAFieldwork.resolveFruitTypeNameOrIndex("GRASS")
local PRE_SEED_GROUND_TYPES = {
[2] = true, -- STUBBLE_TILLAGE
[3] = true, -- CULTIVATED
[4] = true, -- SEEDBED
[5] = true, -- PLOWED
[6] = true, -- other cultivated
[13] = true, -- HARVEST_READY
[14] = true, -- HARVEST_READY_OTHER
}
local farmlands = g_farmlandManager:getFarmlands()
if farmlands ~= nil then
for _, farmlandId in ipairs(neighbour.assignedFarmlands) do
if neighbour.activeSituation ~= nil
and neighbour.activeSituation.farmlandId ~= nil
and tonumber(neighbour.activeSituation.farmlandId) == tonumber(farmlandId) then
-- actively worked, skip
elseif not self:isSowingMonthForPlannedSeed(neighbour, farmlandId, completedMonth) then
-- not urgent, skip
else
local field = nil
for _, f in pairs(farmlands) do
if f ~= nil and f.id == farmlandId and f.field ~= nil then
field = f.field
break
end
end
if field ~= nil and not self:hasActivePlayerFieldOutcomeForFarmland(farmlandId) then
local fs = IAHelper_getFieldStateFresh(field)
if fs ~= nil and (grassFruitTypeIndex == nil or tonumber(fs.fruitTypeIndex) ~= grassFruitTypeIndex)
and PRE_SEED_GROUND_TYPES[tonumber(fs.groundType)] then
local nextCrop = nil
if neighbour.assignedFarmlandNextCrop ~= nil then
nextCrop = neighbour.assignedFarmlandNextCrop[farmlandId]
end
if nextCrop == nil then
nextCrop = self:getNextCropForField(neighbour, farmlandId)
end
if nextCrop ~= nil then
if type(IAFieldwork.enqueueCompleteFieldworkFieldUpdateForDayEnd) == "function" then
if IAFieldwork.enqueueCompleteFieldworkFieldUpdateForDayEnd(
field, IAFieldwork.JobType.SEED, nextCrop, nil) then
completed = completed + 1
if self.ianeighbours ~= nil and self.ianeighbours.debug then
print("--- IAGameLoopHelper:autoCompleteScheduledFieldworkAtDayEnd() - fast-forward seed farmland " .. tostring(farmlandId) .. " nextCrop=" .. tostring(nextCrop))
end
end
end
end
end
end
end
end
end
end
if self.ianeighbours ~= nil and self.ianeighbours.debug then
print("--- IAGameLoopHelper:autoCompleteScheduledFieldworkAtDayEnd() - " .. tostring(neighbour.name)
.. " completed " .. tostring(completed) .. " of " .. tostring(#tasks) .. " scheduled tasks at day end")
end
end
function IAGameLoopHelper:calendarDayMatchesStoredSchedule(neighbour)
if neighbour == nil then
return false
end
local y, m, d = getEnvironmentYearMonthDayInPeriod()
if y == nil or m == nil or d == nil then
return false
end
if neighbour.fieldworkScheduleYear == nil or neighbour.fieldworkScheduleMonth == nil or neighbour.fieldworkScheduleDayInPeriod == nil then
return false
end
return neighbour.fieldworkScheduleYear == y
and neighbour.fieldworkScheduleMonth == m
and neighbour.fieldworkScheduleDayInPeriod == d
end
function IAGameLoopHelper:ensureDailyFieldworkSchedule(neighbour)
if neighbour == nil then
return
end
if neighbour.fieldworkScheduleTasks == nil then
neighbour.fieldworkScheduleTasks = {}
end
if not self:calendarDayMatchesStoredSchedule(neighbour) then
self:autoCompleteScheduledFieldworkAtDayEnd(neighbour)
-- Day-change rebuild: defer contract definition to the first evaluateScheduledFieldworkRefresh run.
-- Field state queue from autoComplete should flush by then.
self:rebuildDailyFieldworkSchedule(neighbour, { defineContracts = false, isDayChange = true })
end
if self:calendarDayMatchesStoredSchedule(neighbour)
and neighbour.fieldworkScheduleTasks ~= nil
and #neighbour.fieldworkScheduleTasks == 0 then
-- Same-day empty schedule fallback: rebuild without redefining contracts.
local dayKey = self:getFieldworkScheduleDayKey(neighbour)
if dayKey ~= nil and neighbour.contractCallTriggerFiredForScheduleKey == dayKey then
return
end
self:rebuildDailyFieldworkSchedule(neighbour, { defineContracts = false })
end
end
-- Called from the neighbour's 30-second interval timer. Runs the daily fieldwork
-- schedule rebuild on every tick:
-- First run of the day – full rebuild (defineContracts=true): pick outsource type,
-- set call window, mark contract-enabled rows.
-- Subsequent runs – additive rebuild: keep all existing rows, only add new field
-- candidates. If no contracts exist, falls back to defineContracts=true.
--
-- A full rebuild only fires once per day (tracked via neighbour._iaScheduleRebuiltForDayKey).
function IAGameLoopHelper:evaluateScheduledFieldworkRefresh(neighbour)
if neighbour == nil or not neighbour.initialized then
return
end
if neighbour.job ~= "Farmer" or neighbour.role ~= "Neighbour" then
return
end
if g_currentMission == nil or g_currentMission.environment == nil then
return
end
-- Ensure we have a schedule for today (handles day-change if needed)
self:ensureDailyFieldworkSchedule(neighbour)
if not self:calendarDayMatchesStoredSchedule(neighbour) then
return
end
local dayKey = self:getFieldworkScheduleDayKey(neighbour)
if dayKey == nil then
return
end
-- First run of the day: full rebuild with contract definition.
-- Subsequent runs: additive-only (keep existing rows, only add new candidates).
local isFirstRunToday = (neighbour._iaScheduleRebuiltForDayKey ~= dayKey)
neighbour._iaScheduleRebuiltForDayKey = dayKey
if isFirstRunToday then
if self.ianeighbours.debug then
print("--- IAGameLoopHelper:evaluateScheduledFieldworkRefresh() - " .. tostring(neighbour.name)
.. " FIRST-RUN defineContracts=true")
end
self:rebuildDailyFieldworkSchedule(neighbour, { defineContracts = true })
else
if self.ianeighbours.debug then
print("--- IAGameLoopHelper:evaluateScheduledFieldworkRefresh() - " .. tostring(neighbour.name)
.. " additiveOnly")
end
self:rebuildDailyFieldworkSchedule(neighbour, { defineContracts = false, additiveOnly = true })
end
end
-- How many contract inbound rings can still fit from callPlayerHour today (same minute each hour), capped at CONTRACT_CALL_MAX_RING_OPENS_PER_DAY.
function IAGameLoopHelper.getContractCallRingSlotsCountForCallHour(callPlayerHour)
local h = tonumber(callPlayerHour)
if h == nil or h < 0 or h > 23 then
return 0
end
return math.min(IAGameLoopHelper.CONTRACT_CALL_MAX_RING_OPENS_PER_DAY, math.max(0, 24 - h))
end
-- Up to three in-game hourly slots (call time, +1h, +2h same minute); answering locks the rest of the day. Plan lock key set on first successful ring (see ensureDailyFieldworkSchedule).
function IAGameLoopHelper:evaluateContractPlayerCallTrigger(neighbour)
if neighbour == nil or not neighbour.initialized then
return
end
if neighbour.job ~= "Farmer" or neighbour.role ~= "Neighbour" then
return
end
if IANeighbours ~= nil and type(IANeighbours.isPlayerInAnyConversation) == "function" and IANeighbours.isPlayerInAnyConversation() then
return
end
if g_currentMission == nil or g_currentMission.environment == nil then
return
end
self:ensureDailyFieldworkSchedule(neighbour)
if not self:calendarDayMatchesStoredSchedule(neighbour) then
return
end
if neighbour.callPlayerHour == nil or neighbour.callPlayerMinute == nil then
return
end
local tasks = neighbour.fieldworkScheduleTasks
if tasks == nil then
return
end
local hasContract = false
for _, row in ipairs(tasks) do
if row ~= nil and row.contractEnabled == true then
hasContract = true
break
end
end
if not hasContract then
return
end
local env = g_currentMission.environment
local curH = env.currentHour or 0
local curM = env.currentMinute or 0
local curTotal = curH * 60 + curM
if g_inGameMenu ~= nil and g_inGameMenu.isOpen == true then
return
end
local mi = g_currentMission.missionInfo
if mi == nil or mi.timeScale == nil or mi.timeScale >= 500 then
return
end
local scheduleKey = tostring(neighbour.fieldworkScheduleYear) .. "_" .. tostring(neighbour.fieldworkScheduleMonth) .. "_" .. tostring(neighbour.fieldworkScheduleDayInPeriod)
if neighbour.contractCallRingAnsweredToday == true then
return
end
local maxOpens = IAGameLoopHelper.getContractCallRingSlotsCountForCallHour(neighbour.callPlayerHour)
if maxOpens <= 0 then
return
end
local opens = tonumber(neighbour.contractCallRingOpensCount) or 0
if opens >= maxOpens then
return
end
if opens > 0 then
local lastRingTotal = tonumber(neighbour.contractCallLastRingTotalMinutes)
if neighbour.contractCallLastRingScheduleKey == scheduleKey and lastRingTotal ~= nil then
local retryMinMinutes = tonumber(IAGameLoopHelper.CONTRACT_CALL_RETRY_MIN_INGAME_MINUTES) or 60
if curTotal < lastRingTotal + retryMinMinutes then
return
end
end
end
local slotHour = neighbour.callPlayerHour + opens
if slotHour > 23 then
return
end
local slotTotal = slotHour * 60 + (neighbour.callPlayerMinute or 0)
if curTotal < slotTotal then
return
end
-- Classic mission offer mode: no phone call rings at all.
if IASettings ~= nil and type(IASettings.isMissionOfferModeClassic) == "function" then
if IASettings.isMissionOfferModeClassic() then
return
end
end