forked from bodzio528/FS22_CropRotation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCropRotation.lua
1126 lines (914 loc) · 39.9 KB
/
CropRotation.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
--
-- FS22 Crop Rotation mod
--
-- CropRotation.lua
--
-- @Author: Bodzio528
-- @Version: 2.0.0.0
-- Changelog:
-- v2.0.0.0 (05.09.2022):
-- - code rewrite
-- v1.0.0.0 (03.08.2022):
-- - Initial release
CropRotation = {
MOD_NAME = g_currentModName or "FS22_CropRotation",
MOD_DIRECTORY = g_currentModDirectory,
MAP_VERSION = 2,
MAP_NUM_CHANNELS = 12 -- [R2:5][R1:5][F:1][H:1]
}
local CropRotation_mt = Class(CropRotation)
CropRotation.PrecisionFarming = "FS22_precisionFarming"
CropRotation.COLORS = {
[0] = {
color = {0.0000, 0.4341, 0.0802, 1},
colorBlind = {1.0000, 1.0000, 0.1000, 1},
text = "cropRotation_hud_fieldInfo_perfect"
},
[1] = {
color = {0.0331, 0.4564, 0.0513, 1},
colorBlind = {0.9250, 0.9250, 0.1000, 1},
text = "cropRotation_hud_fieldInfo_good"
},
[2] = {
color = {0.1329, 0.4735, 0.0296, 1},
colorBlind = {0.8500, 0.8500, 0.1000, 1},
text = "cropRotation_hud_fieldInfo_good"
},
[3] = {
color = {0.3231, 0.4969, 0.0137, 1},
colorBlind = {0.7500, 0.7500, 0.1000, 1},
text = "cropRotation_hud_fieldInfo_ok"
},
[4] = {
color = {0.6105, 0.5149, 0.0048, 1},
colorBlind = {0.6500, 0.6500, 0.1000, 1},
text = "cropRotation_hud_fieldInfo_ok"
},
[5] = {
color = {0.9910, 0.3231, 0.0000, 1},
colorBlind = {0.4500, 0.4500, 0.1000, 1},
text = "cropRotation_hud_fieldInfo_bad"
},
[6] = {
color = {0.9911, 0.0742, 0.0000, 1},
colorBlind = {0.2500, 0.2500, 0.1000, 1},
text = "cropRotation_hud_fieldInfo_bad"
},
[7] = {
color = {0.9910, 0.0000, 0.0000, 1},
colorBlind = {0.1000, 0.1000, 0.1000, 1},
text = "cropRotation_hud_fieldInfo_bad"
}
}
CropRotation.debug = false -- true --
function overwrittenStaticFunction(object, funcName, newFunc)
local oldFunc = object[funcName]
object[funcName] = function(...)
return newFunc(oldFunc, ...)
end
end
function applyYieldMultiplier(multiplier, ...)
if select('#', ...) > 0 then
local arg = {...}
arg[1] = multiplier * arg[1]
return unpack(arg)
end
return nil
end
function CropRotation:new(mission, modDirectory, messageCenter, fruitTypeManager, i18n, data, densityMapUpdater)
local self = setmetatable({}, CropRotation_mt)
self.isServer = mission:getIsServer()
self.mission = mission
self.modDirectory = modDirectory
self.messageCenter = messageCenter
self.fruitTypeManager = fruitTypeManager
self.i18n = i18n
self.data = data
self.mapName = "cropRotation"
self.mapFilePath = self.mission.missionInfo.savegameDirectory .. "/cropRotation.grle"
self.xmlName = "CropRotationXML"
self.xmlFilePath = self.mission.missionInfo.savegameDirectory .. "/cropRotation.xml"
self.xmlRootElement = "cropRotation"
self.densityMapUpdater = densityMapUpdater
self.numFruits = math.min(31, #self.fruitTypeManager:getFruitTypes())
self.isVisualizeEnabled = false
self.isNewSavegame = false
overwrittenStaticFunction(FSDensityMapUtil, "updateSowingArea", CropRotation.inj_densityMapUtil_updateSowingArea)
overwrittenStaticFunction(FSDensityMapUtil, "updateDirectSowingArea", CropRotation.inj_densityMapUtil_updateSowingArea)
overwrittenStaticFunction(FSDensityMapUtil, "cutFruitArea", CropRotation.inj_densityMapUtil_cutFruitArea)
addConsoleCommand("crInfo", "Get crop rotation info", "commandGetInfo", self)
addConsoleCommand("crPlanner", "Perform planner function with specified crops", "commandPlanner", self)
if CropRotation.debug then
addConsoleCommand("crVisualizeToggle", "Toggle Crop Rotation visualization", "commandToggleVisualize", self)
end
if CropRotation.debug or g_addCheatCommands then -- cheats enabled
addConsoleCommand("crFallowRun", "Run yearly fallow", "commandRunFallow", self)
addConsoleCommand("crFallowSet", "Set fallow state", "commandSetFallow", self)
addConsoleCommand("crFallowClear", "Clear fallow state", "commandClearFallow", self)
addConsoleCommand("crHarvestSet", "Set harvest state", "commandSetHarvest", self)
addConsoleCommand("crHarvestClear", "Clear harvest state", "commandClearHarvest", self)
end
self:initCache()
return self
end
-- fill function cache to speedup execution
function CropRotation:initCache()
self.cache = {}
self.cache.fieldInfoDisplay = {}
self.cache.fieldInfoDisplay.title = self.i18n:getText("cropRotation_hud_fieldInfo_title")
self.cache.fieldInfoDisplay.previousTitle = self.i18n:getText("cropRotation_hud_fieldInfo_previous")
self.cache.fieldInfoDisplay.previousFallow = self.i18n:getText("cropRotation_fallow")
self.cache.fieldInfoDisplay.currentTypeIndex = FruitType.UNKNOWN
self.cache.fieldInfoDisplay.currentFruitState = 0
-- crop rotation fieldInfoDisplay level text
self.cache.fieldInfoDisplay.texts = {}
for level = 0, 7 do
self.cache.fieldInfoDisplay.texts[level] = self.i18n:getText(CropRotation.COLORS[level].text)
end
--[[ TODO: get rid of global CropRotation.COLORS, make it read from configuration XML
self.cache.fieldInfoDisplay.colors = {}
for level = 0, 7 do
self.cache.fieldInfoDisplay.colors[level] = {
color = CropRotation.COLORS[level].color,
colorBlind = CropRotation.COLORS[level].colorBlind
}
end
--]]
-- readFromMap smart cache
self.cache.readFromMap = {}
self.cache.readFromMap.previousCrop = FruitType.UNKNOWN -- R2
self.cache.readFromMap.lastCrop = FruitType.UNKNOWN -- R1
end
function CropRotation:delete()
self.densityMapUpdater:unregister("UpdateFallow")
self.densityMapUpdater:unregister("UpdateRegrow")
if self.densityMapUpdater ~= nil then
self.densityMapUpdater = nil
end
self.cache = nil
removeConsoleCommand("crInfo")
removeConsoleCommand("crPlanner")
if CropRotation.debug then
removeConsoleCommand("crVisualizeToggle", self)
end
if CropRotation.debug or g_addCheatCommands then
removeConsoleCommand("crFallowRun")
removeConsoleCommand("crFallowSet")
removeConsoleCommand("crFallowClear")
removeConsoleCommand("crHarvestSet")
removeConsoleCommand("crHarvestClear")
end
self.messageCenter:unsubscribeAll(self)
end
-- this function will add synchronization between all clients in MP game...
-- ...hopefully
function CropRotation:addDensityMapSyncer(densityMapSyncer)
if self.map ~= nil then
densityMapSyncer:addDensityMap(self.map)
end
end
------------------------------------------------
--- Events from mod event handling
------------------------------------------------
function CropRotation:loadMap()
self:loadSavegame()
FSBaseMission.saveSavegame = Utils.appendedFunction(FSBaseMission.saveSavegame, CropRotation.saveSavegame)
if g_modIsLoaded[CropRotation.PrecisionFarming] then -- extend PlayerHUDUpdater with crop rotation info
local pfModule = FS22_precisionFarming.g_precisionFarming
if pfModule ~= nil then
pfModule.fieldInfoDisplayExtension:addFieldInfo(
self.cache.fieldInfoDisplay.title,
self,
self.updateFieldInfoDisplay,
4, -- prio
self.yieldChangeFunc)
pfModule.fieldInfoDisplayExtension:addFieldInfo(
self.i18n:getText("cropRotation_hud_fieldInfo_previous"),
self,
self.updateFieldInfoDisplayPreviousCrops,
5, -- prio
nil) -- no yield change
end
PlayerHUDUpdater.fieldAddFruit =
Utils.appendedFunction(
PlayerHUDUpdater.fieldAddFruit,
function(updater, data, box)
local cropRotation = g_cropRotation
assert(cropRotation ~= nil)
cropRotation.cache.fieldInfoDisplay.currentTypeIndex = data.fruitTypeMax or FruitType.UNKNOWN
cropRotation.cache.fieldInfoDisplay.currentFruitState = data.fruitStateMax or 0
end
)
else -- OR simply add Crop Rotation Info to standard HUD
PlayerHUDUpdater.fieldAddFruit =
Utils.appendedFunction(PlayerHUDUpdater.fieldAddFruit, CropRotation.fieldAddFruit)
PlayerHUDUpdater.updateFieldInfo =
Utils.prependedFunction(PlayerHUDUpdater.updateFieldInfo, CropRotation.updateFieldInfo)
end
end
---Called every frame update
function CropRotation:update(dt)
if self.densityMapUpdater ~= nil then
self.densityMapUpdater:update(dt)
end
if CropRotation.debug and self.isVisualizeEnabled then
self:visualize()
end
end
------------------------------------------------
--- Player HUD Updater
------------------------------------------------
function CropRotation.getLevelByCrFactor(factor)
-- factor -- min = 0.7x -- max = 1.15x
if factor >= 1.10 then return 0 end
if factor >= 1.05 then return 1 end
if factor >= 1.00 then return 2 end
if factor >= 0.95 then return 3 end
if factor >= 0.90 then return 4 end
if factor >= 0.85 then return 5 end
if factor >= 0.80 then return 6 end
return 7
end
function CropRotation:getFruitTitle(index)
if not index or index == FruitType.UNKNOWN then
return self.cache.fieldInfoDisplay.previousFallow
end
return self.fruitTypeManager:getFruitTypeByIndex(index).fillType.title
end
function CropRotation:updateFieldInfo(posX, posZ, rotY)
if self.requestedFieldData then
return
end
local cropRotation = g_cropRotation
assert(cropRotation ~= nil)
if g_farmlandManager:getOwnerIdAtWorldPosition(posX, posZ) ~= g_currentMission.player.farmId then
cropRotation.cache.fieldInfoDisplay.rotation = nil
return
end
local prev, last = cropRotation:getInfoAtWorldParallelogram(CropRotation.getParallellogramFromXZrotY(posX, posZ, rotY))
if prev == -1 or last == -1 then
cropRotation.cache.fieldInfoDisplay.rotation = nil
else
cropRotation.cache.fieldInfoDisplay.rotation = {
prev = prev,
last = last
}
end
end
function CropRotation:fieldAddFruit(data, box)
local cropRotation = g_cropRotation
assert(cropRotation ~= nil)
if cropRotation.cache.fieldInfoDisplay.rotation ~= nil then
if data.fruitTypeMax and data.fruitTypeMax ~= FruitType.UNKNOWN then
local fruitType = g_fruitTypeManager:getFruitTypeByIndex(data.fruitTypeMax)
if fruitType.cutState ~= data.fruitStateMax then
local crYieldMultiplier =
cropRotation:getRotationYieldMultiplier(
cropRotation.cache.fieldInfoDisplay.rotation.prev,
cropRotation.cache.fieldInfoDisplay.rotation.last,
data.fruitTypeMax
)
local level = CropRotation.getLevelByCrFactor(crYieldMultiplier)
local text = cropRotation.cache.fieldInfoDisplay.texts[level]
local isColorBlindMode = g_gameSettings:getValue(GameSettings.SETTING.USE_COLORBLIND_MODE) or false
box:addLine(
string.format("%s (%s)", cropRotation.cache.fieldInfoDisplay.title, text),
string.format("%d %%", math.ceil(100.0 * crYieldMultiplier)),
true, -- use color
isColorBlindMode and CropRotation.COLORS[level].colorBlind or CropRotation.COLORS[level].color
)
end
end
box:addLine(
cropRotation.cache.fieldInfoDisplay.previousTitle,
string.format(
"%s | %s",
cropRotation:getFruitTitle(cropRotation.cache.fieldInfoDisplay.rotation.last),
cropRotation:getFruitTitle(cropRotation.cache.fieldInfoDisplay.rotation.prev)
)
)
end
end
------------------------------------------------
--- PrecisionFarming DLC Player HUD Updater
------------------------------------------------
function CropRotation:yieldChangeFunc(fieldInfo)
local crFactor = fieldInfo.crFactor or 1.00
return 2.0 * (crFactor - 1.0), 1.0, fieldInfo.yieldPotential, fieldInfo.yieldPotentialToHa
end
function CropRotation:updateFieldInfoDisplay(fieldInfo, startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ, isColorBlindMode)
if g_farmlandManager:getOwnerIdAtWorldPosition(startWorldX, startWorldZ) ~= g_currentMission.player.farmId then
return nil
end
local cropRotation = g_cropRotation
assert(cropRotation ~= nil)
local prevIndex, lastIndex = cropRotation:getInfoAtWorldParallelogram(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ)
if prevIndex == -1 or lastIndex == -1 then
return nil
end
local currentIndex = cropRotation.cache.fieldInfoDisplay.currentTypeIndex
if FruitType.UNKNOWN == currentIndex then
return nil
end
local fruitType = g_fruitTypeManager:getFruitTypeByIndex(currentIndex)
if fruitType.cutState == cropRotation.cache.fieldInfoDisplay.currentFruitState then
return nil
end
-- update for PF's yieldChangeFunc (above)
fieldInfo.crFactor = cropRotation:getRotationYieldMultiplier(prevIndex, lastIndex, currentIndex)
local value = string.format("%d %%", math.ceil(100.0 * fieldInfo.crFactor))
local level = CropRotation.getLevelByCrFactor(fieldInfo.crFactor)
local color = isColorBlindMode and CropRotation.COLORS[level].color or CropRotation.COLORS[level].colorBlind
return value, color, cropRotation.cache.fieldInfoDisplay.texts[level]
end
function CropRotation:updateFieldInfoDisplayPreviousCrops(fieldInfo, startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ, isColorBlindMode)
if g_farmlandManager:getOwnerIdAtWorldPosition(startWorldX, startWorldZ) ~= g_currentMission.player.farmId then
return nil
end
local cropRotation = g_cropRotation
assert(cropRotation ~= nil)
-- Read CR data
local prev, last = cropRotation:getInfoAtWorldParallelogram(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ)
if prev == -1 or last == -1 then
return nil
end
return string.format("%s | %s", cropRotation:getFruitTitle(last), cropRotation:getFruitTitle(prev))
end
------------------------------------------------
--- Load/Save handlers
------------------------------------------------
function CropRotation:saveSavegame()
local cropRotation = g_cropRotation
assert(cropRotation ~= nil)
if self.missionInfo.isValid then
local xmlFile = createXMLFile(cropRotation.xmlName, cropRotation.xmlFilePath, cropRotation.xmlRootElement)
if xmlFile ~= nil then
cropRotation:saveToSavegame(xmlFile)
saveXMLFile(xmlFile)
delete(xmlFile)
end
end
end
function CropRotation:saveToSavegame(xmlFile)
setXMLInt(xmlFile, "cropRotation.mapVersion", CropRotation.MAP_VERSION)
if self.map ~= 0 then
saveBitVectorMapToFile(self.map, self.mapFilePath)
end
-- TODO: self.planner:saveToSavegame(xmlFile)
end
function CropRotation:loadSavegame()
if self.mission:getIsServer() and self.mission.missionInfo.savegameDirectory ~= nil then
if fileExists(self.xmlFilePath) then
local xmlFile = loadXMLFile(self.xmlName, self.xmlFilePath)
if xmlFile ~= nil then
self:loadFromSavegame(xmlFile)
-- TODO: self.planner:loadFromSavegame(xmlFile)
delete(xmlFile)
end
end
end
end
function CropRotation:loadFromSavegame(xmlFile)
local mapVersionKey = "cropRotation.mapVersion"
if not hasXMLProperty(xmlFile, mapVersionKey) then
self.isNewSavegame = true
log("CropRotation:loadMap(): WARNING old version of mod was in use! Discarding crop rotation history.")
return
end
local mapVersionLoaded = getXMLInt(xmlFile, mapVersionKey)
if mapVersionLoaded and mapVersionLoaded < CropRotation.MAP_VERSION then
self.isNewSavegame = true
self.convertMapFromVersion = mapVersionLoaded
log("CropRotation:loadMap(): INFO found old version of crop rotation map! Converting...")
end
end
------------------------------------------------
--- Game initializing
------------------------------------------------
function CropRotation:load()
self.data:load()
self:loadCropRotationMap() --
self:loadModifiers()
local finalizer = function(target)
log("DensityMapUpdater: INFO job finished!")
end
self.densityMapUpdater:register("UpdateFallow", self.task_updateFallow, self, finalizer)
self.densityMapUpdater:register("UpdateRegrow", self.task_updateRegrow, self, finalizer)
self.messageCenter:subscribe(MessageType.YEAR_CHANGED, self.onYearChanged, self)
self.messageCenter:subscribe(MessageType.PERIOD_CHANGED, self.onPeriodChanged, self)
end
function CropRotation:onTerrainLoaded(mission, terrainId, mapFilename)
self.terrainSize = self.mission.terrainSize
end
function CropRotation:loadCropRotationMap()
self.map = createBitVectorMap(self.mapName)
local success = false
if self.mission.missionInfo.isValid then
if fileExists(self.mapFilePath) and not self.isNewSavegame then
success = loadBitVectorMapFromFile(self.map, self.mapFilePath, CropRotation.MAP_NUM_CHANNELS)
end
end
if not success then
local size = getDensityMapSize(self.mission.terrainDetailId)
loadBitVectorMapNew(self.map, size, size, CropRotation.MAP_NUM_CHANNELS, false)
end
self.mapSize = getBitVectorMapSize(self.map)
end
function CropRotation:loadModifiers()
-- M:12 = [R2:5][R1:5][F:1][H:1]
local modifiers = {}
modifiers.map = {}
modifiers.map.modifier = DensityMapModifier.new(self.map, 0, CropRotation.MAP_NUM_CHANNELS)
modifiers.map.modifier:setPolygonRoundingMode(DensityRoundingMode.INCLUSIVE)
modifiers.map.filter = DensityMapFilter.new(modifiers.map.modifier)
modifiers.map.modifierR2 = DensityMapModifier.new(self.map, 7, 5)
modifiers.map.filterR2 = DensityMapFilter.new(modifiers.map.modifierR2)
modifiers.map.modifierR1 = DensityMapModifier.new(self.map, 2, 5)
modifiers.map.filterR1 = DensityMapFilter.new(modifiers.map.modifierR1)
modifiers.map.modifierF = DensityMapModifier.new(self.map, 1, 1)
modifiers.map.filterF = DensityMapFilter.new(modifiers.map.modifierF)
modifiers.map.filterF:setValueCompareParams(DensityValueCompareType.EQUAL, 0)
modifiers.map.modifierH = DensityMapModifier.new(self.map, 0, 1)
modifiers.map.filterH = DensityMapFilter.new(modifiers.map.modifierH)
modifiers.map.filterH:setValueCompareParams(DensityValueCompareType.EQUAL, 0)
self.modifiers = modifiers
end
------------------------------------------------
--- Message Center Event handlers
------------------------------------------------
function CropRotation:onYearChanged(newYear)
self.densityMapUpdater:schedule("UpdateFallow")
end
function CropRotation:onPeriodChanged(newPeriod)
self.densityMapUpdater:schedule("UpdateRegrow")
end
------------------------------------------------
--- Density Map Updater periodic tasks
------------------------------------------------
-- yearly fallow bit update on parallelogram(start, width, height)
function CropRotation:task_updateFallow(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ)
local terrainSize = self.terrainSize
local mapModifiers = self.modifiers.map
mapModifiers.modifierR1:setParallelogramUVCoords(
startWorldX / terrainSize + 0.5,
startWorldZ / terrainSize + 0.5,
widthWorldX / terrainSize + 0.5,
widthWorldZ / terrainSize + 0.5,
heightWorldX / terrainSize + 0.5,
heightWorldZ / terrainSize + 0.5,
DensityCoordType.POINT_POINT_POINT
)
mapModifiers.modifierR2:setParallelogramUVCoords(
startWorldX / terrainSize + 0.5,
startWorldZ / terrainSize + 0.5,
widthWorldX / terrainSize + 0.5,
widthWorldZ / terrainSize + 0.5,
heightWorldX / terrainSize + 0.5,
heightWorldZ / terrainSize + 0.5,
DensityCoordType.POINT_POINT_POINT
)
for i = 0, self.numFruits do
mapModifiers.filterR1:setValueCompareParams(DensityValueCompareType.EQUAL, i)
mapModifiers.modifierR2:executeSet(i, mapModifiers.filterF, mapModifiers.filterR1)
mapModifiers.modifierR1:executeSet(FruitType.UNKNOWN, mapModifiers.filterF, mapModifiers.filterR1)
end
mapModifiers.modifierF:setParallelogramUVCoords(
startWorldX / terrainSize + 0.5,
startWorldZ / terrainSize + 0.5,
widthWorldX / terrainSize + 0.5,
widthWorldZ / terrainSize + 0.5,
heightWorldX / terrainSize + 0.5,
heightWorldZ / terrainSize + 0.5,
DensityCoordType.POINT_POINT_POINT
)
mapModifiers.modifierF:executeSet(0)
end
function CropRotation:task_updateRegrow(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ)
local terrainSize = self.terrainSize
local mapModifiers = self.modifiers.map
for i, desc in pairs(self.fruitTypeManager:getFruitTypes()) do
if desc.regrows then
mapModifiers.filterR1:setValueCompareParams(DensityValueCompareType.EQUAL, i)
mapModifiers.modifierH:setParallelogramUVCoords(
startWorldX / terrainSize + 0.5,
startWorldZ / terrainSize + 0.5,
widthWorldX / terrainSize + 0.5,
widthWorldZ / terrainSize + 0.5,
heightWorldX / terrainSize + 0.5,
heightWorldZ / terrainSize + 0.5,
DensityCoordType.POINT_POINT_POINT
)
mapModifiers.modifierH:executeSet(0, mapModifiers.filterR1)
end
end
end
------------------------------------------------
-- Injections to core game functions
------------------------------------------------
function CropRotation.inj_densityMapUtil_updateSowingArea(superFunc, fruitIndex, startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ, fieldGroundType, angle, growthState, blockedSprayTypeIndex)
local fruitDesc = g_fruitTypeManager:getFruitTypeByIndex(fruitIndex)
if fruitDesc and fruitDesc.rotation.enabled then
local cropRotation = g_cropRotation
local modifiers = cropRotation.modifiers
local terrainSize = cropRotation.terrainSize
modifiers.map.modifierH:setParallelogramUVCoords(
startWorldX / terrainSize + 0.5,
startWorldZ / terrainSize + 0.5,
widthWorldX / terrainSize + 0.5,
widthWorldZ / terrainSize + 0.5,
heightWorldX / terrainSize + 0.5,
heightWorldZ / terrainSize + 0.5,
DensityCoordType.POINT_POINT_POINT
)
modifiers.map.modifierH:executeSet(0)
end
return superFunc(fruitIndex, startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ, fieldGroundType, angle, growthState, blockedSprayTypeIndex)
end
function CropRotation.inj_densityMapUtil_cutFruitArea(superFunc, fruitIndex, startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ, destroySpray, useMinForageState, excludedSprayType, setsWeeds, limitToField)
if g_farmlandManager:getOwnerIdAtWorldPosition(0.5*(widthWorldX+heightWorldX), 0.5*(widthWorldZ+heightWorldZ)) ~= g_currentMission.player.farmId then
-- no cropRotation bonus in NPC missions
return superFunc(fruitIndex, startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ, destroySpray, useMinForageState, excludedSprayType, setsWeeds, limitToField)
end
local cropRotation = g_cropRotation
assert(cropRotation ~= nil)
local desc = g_fruitTypeManager:getFruitTypeByIndex(fruitIndex)
if desc.terrainDataPlaneId == nil then
return 0
end
local fruitFilter = nil
local functionData = FSDensityMapUtil.functionCache.cutFruitArea
if functionData ~= nil and functionData.fruitFilters ~= nil then
fruitFilter = functionData.fruitFilters[fruitIndex]
end
if fruitFilter == nil then
-- we have missed the cache - create new filter and store inside cache for future use
if CropRotation.debug then
log(string.format("CropRotation:cutFruitArea(): WARNING: function cache missed for fruit index %d", fruitIndex))
end
fruitFilter =
DensityMapFilter.new(
desc.terrainDataPlaneId,
desc.startStateChannel,
desc.numStateChannels,
g_currentMission.terrainRootNode
)
if functionData ~= nil and functionData.fruitFilters ~= nil then
functionData.fruitFilters[fruitIndex] = fruitFilter
end
end
local minState = desc.minHarvestingGrowthState
if useMinForageState then
minState = desc.minForageGrowthState
end
fruitFilter:setValueCompareParams(DensityValueCompareType.BETWEEN, minState, desc.maxHarvestingGrowthState)
local prev, last, mapModifier = cropRotation:readFromMap(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX,heightWorldZ, fruitFilter, true)
local yieldMultiplier = 1.0
if prev ~= -1 or last ~= -1 then
yieldMultiplier = cropRotation:getRotationYieldMultiplier(prev, last, fruitIndex)
mapModifier:executeSet(
cropRotation:encode(last, fruitIndex, 1, 1),
fruitFilter,
cropRotation.modifiers.map.filterH
)
end
return applyYieldMultiplier(
yieldMultiplier,
superFunc(
fruitIndex,
startWorldX,
startWorldZ,
widthWorldX,
widthWorldZ,
heightWorldX,
heightWorldZ,
destroySpray,
useMinForageState,
excludedSprayType,
setsWeeds,
limitToField
)
)
end
------------------------------------------------
-- Reading and writing
------------------------------------------------
-- [R2:5][R1:5][F:1][H:1]
function CropRotation:decode(bits)
local previous = bitShiftRight(bitAND(bits, 3968), 7)
local last = bitShiftRight(bitAND(bits, 124), 2)
local fallow = bitShiftRight(bitAND(bits, 2), 1)
local harvest = bitAND(bits, 1)
return previous, last, fallow, harvest
end
function CropRotation:encode(previous, last, fallow, harvest)
return bitShiftLeft(previous, 7) + bitShiftLeft(last, 2) + bitShiftLeft(fallow, 1) + harvest
end
---Read the forecrops and aftercrops from the map.
function CropRotation:readFromMap(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ, filter, skipWhenHarvested)
local terrainSize = self.terrainSize
local r2, r1 = -1, -1
local mapModifiers = self.modifiers.map
-- Read value from CR map
local mapModifier = mapModifiers.modifier
mapModifier:setParallelogramUVCoords(
startWorldX / terrainSize + 0.5,
startWorldZ / terrainSize + 0.5,
widthWorldX / terrainSize + 0.5,
widthWorldZ / terrainSize + 0.5,
heightWorldX / terrainSize + 0.5,
heightWorldZ / terrainSize + 0.5,
DensityCoordType.POINT_POINT_POINT
)
mapModifiers.modifierR2:setParallelogramUVCoords(
startWorldX / terrainSize + 0.5,
startWorldZ / terrainSize + 0.5,
widthWorldX / terrainSize + 0.5,
widthWorldZ / terrainSize + 0.5,
heightWorldX / terrainSize + 0.5,
heightWorldZ / terrainSize + 0.5,
DensityCoordType.POINT_POINT_POINT
)
mapModifiers.filterR2:setValueCompareParams(DensityValueCompareType.EQUAL, self.cache.readFromMap.previousCrop)
local area, totalArea
if skipWhenHarvested then
_, area, totalArea = mapModifiers.modifierR2:executeGet(filter, mapModifiers.filterH, mapModifiers.filterR2)
else
_, area, totalArea = mapModifiers.modifierR2:executeGet(filter, mapModifiers.filterR2)
end
if area >= totalArea * 0.5 then
r2 = self.cache.readFromMap.previousCrop
else
local maxArea = 0
for i = 0, self.numFruits do
mapModifiers.filterR2:setValueCompareParams(DensityValueCompareType.EQUAL, i)
local area, totalArea
if skipWhenHarvested then
acc, area, totalArea = mapModifiers.modifierR2:executeGet(filter, mapModifiers.filterH, mapModifiers.filterR2)
else
acc, area, totalArea = mapModifiers.modifierR2:executeGet(filter, mapModifiers.filterR2)
end
if area > maxArea then
maxArea = area
r2 = i
end
if area >= totalArea * 0.5 then
self.cache.readFromMap.previousCrop = i -- update function cache
break
end
end
end
mapModifiers.modifierR1:setParallelogramUVCoords(
startWorldX / terrainSize + 0.5,
startWorldZ / terrainSize + 0.5,
widthWorldX / terrainSize + 0.5,
widthWorldZ / terrainSize + 0.5,
heightWorldX / terrainSize + 0.5,
heightWorldZ / terrainSize + 0.5,
DensityCoordType.POINT_POINT_POINT
)
mapModifiers.filterR1:setValueCompareParams(DensityValueCompareType.EQUAL, self.cache.readFromMap.lastCrop)
local area, totalArea
if skipWhenHarvested then
_, area, totalArea = mapModifiers.modifierR1:executeGet(filter, mapModifiers.filterH, mapModifiers.filterR1)
else
_, area, totalArea = mapModifiers.modifierR1:executeGet(filter, mapModifiers.filterR1)
end
if area >= totalArea * 0.5 then
r1 = self.cache.readFromMap.lastCrop
else
local maxArea = 0
for i = 0, self.numFruits do
mapModifiers.filterR1:setValueCompareParams(DensityValueCompareType.EQUAL, i)
local area, totalArea
if skipWhenHarvested then
acc, area, totalArea = mapModifiers.modifierR1:executeGet(filter, mapModifiers.filterH, mapModifiers.filterR1)
else
acc, area, totalArea = mapModifiers.modifierR1:executeGet(filter, mapModifiers.filterR1)
end
if area > maxArea then
maxArea = area
r1 = i
end
if area >= totalArea * 0.5 then
self.cache.readFromMap.lastCrop = i -- update function cache
break
end
end
end
return r2, r1, mapModifier
end
-----------------------------------
-- Algorithms
-----------------------------------
function CropRotation:getRotationYieldMultiplier(prevIndex, lastIndex, currentIndex)
local currentDesc = self.fruitTypeManager:getFruitTypeByIndex(currentIndex)
local returnPeriod = self:getRotationReturnPeriodMultiplier(prevIndex, lastIndex, currentDesc)
local forecrops = self:getRotationForecropMultiplier(prevIndex, lastIndex, currentIndex)
return returnPeriod * forecrops
end
function CropRotation:getRotationReturnPeriodMultiplier(prev, last, current)
local returnPeriod = current.rotation.returnPeriod
if returnPeriod == 3 then
return 1 - (current.index == last and 0.1 or 0) - (current.index == prev and 0.05 or 0)
end
if returnPeriod == 2 then
return 1 - ((current.index == last) and 0.05 or 0) - (current.index == prev and 0.05 or 0)
end
return 1.0
end
function CropRotation:getRotationForecropMultiplier(prevIndex, lastIndex, currentIndex)
local prevValue = self.data:getRotationForecropValue(prevIndex, currentIndex)
local lastValue = self.data:getRotationForecropValue(lastIndex, currentIndex)
local prevFactor = -0.025 * prevValue ^ 2 + 0.125 * prevValue -- <0.0 ; 0.15>
local lastFactor = -0.05 * lastValue ^ 2 + 0.25 * lastValue -- <0.0 ; 0.30>
return 0.7 + (prevFactor + lastFactor) -- <0.7 ; 1.15>
end
-- input: list of crop indices: {11, 2, 3}
-- output: list of multipliers: {1.15, 1.1, 1.0}
function CropRotation:getRotationPlannerYieldMultipliers(input)
if #input < 1 then
return {}
end
result = {}
for pos, current in pairs(input) do
if current and current ~= FruitType.UNKNOWN then
lastPos = 1 + math.fmod((pos + #input - 1) - 1, #input)
prevPos = 1 + math.fmod((pos + #input - 1) - 2, #input)
table.insert(result, self:getRotationYieldMultiplier(input[prevPos], input[lastPos], current))
else
table.insert(result, 0.0)
end
end
return result
end
------------------------------------------------
-- Getting info
------------------------------------------------
function CropRotation.getParallellogramFromXZrotY(posX, posZ, rotY)
local sizeX = 5
local sizeZ = 5
local distance = 2
local dirX, dirZ = MathUtil.getDirectionFromYRotation(rotY)
local sideX, _, sideZ = MathUtil.crossProduct(dirX, 0, dirZ, 0, 1, 0)
local startWorldX = posX - sideX * sizeX * 0.5 - dirX * distance
local startWorldZ = posZ - sideZ * sizeX * 0.5 - dirZ * distance
local widthWorldX = posX + sideX * sizeX * 0.5 - dirX * distance
local widthWorldZ = posZ + sideZ * sizeX * 0.5 - dirZ * distance
local heightWorldX = posX - sideX * sizeX * 0.5 - dirX * (distance + sizeZ)
local heightWorldZ = posZ - sideZ * sizeX * 0.5 - dirZ * (distance + sizeZ)
return startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ
end
function CropRotation:getInfoAtWorldParallelogram(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ)
local groundTypeMapId, groundTypeFirstChannel, groundTypeNumChannels =
g_currentMission.fieldGroundSystem:getDensityMapData(FieldDensityMap.GROUND_TYPE)
local groundFilter = DensityMapFilter.new(groundTypeMapId, groundTypeFirstChannel, groundTypeNumChannels)
groundFilter:setValueCompareParams(DensityValueCompareType.GREATER, 0)
local prev, last =
self:readFromMap(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ, groundFilter, false)
return prev, last
end
function CropRotation:getInfoAtWorldCoords(x, z)
local worldToDensityMap = self.mapSize / self.mission.terrainSize
local xi = math.floor((x + self.mission.terrainSize * 0.5) * worldToDensityMap)
local zi = math.floor((z + self.mission.terrainSize * 0.5) * worldToDensityMap)
local v = getBitVectorMapPoint(self.map, xi, zi, 0, CropRotation.MAP_NUM_CHANNELS)
return self:decode(v) -- prev, last, fallow, harvest
end
function CropRotation:commandGetInfo()
local x, _, z = getWorldTranslation(getCamera(0))
local prev, last, fallow, harvest = self:getInfoAtWorldCoords(x, z)
local getName = function(fruitIndex)
if fruitIndex ~= FruitType.UNKNOWN then
return g_fruitTypeManager:getFruitTypeByIndex(last).fillType.title
end
return g_i18n:getText("cropRotation_fallow")
end
log(string.format("crops: [last: %s(%d)] [previous: %s(%d)] bits: [Fallow: %d] [Harvest: %d]",
getName(last), last,
getName(prev), prev,
fallow,
harvest)
)
end
function CropRotation:commandPlanner(...)
-- prepare request
cropIndices = {}
for i, name in pairs({...}) do
crop = self.fruitTypeManager:getFruitTypeByName(name:upper()) or FruitType.UNKNOWN
table.insert(cropIndices, crop.index)
end
result = self:getRotationPlannerYieldMultipliers(cropIndices)
-- format the response
for i, cropIndex in pairs(cropIndices) do
if cropIndex == FruitType.UNKNOWN then
log("FALLOW", "-")
else
crop = self.fruitTypeManager:getFruitTypeByIndex(cropIndex)
log(string.format("%-20s %1.2f", crop.name, math.ceil(100 * result[i]) / 100))
end
end
end
------------------------------------------------
-- Debugging
------------------------------------------------
function CropRotation:commandRunFallow()