forked from Dukefarming/FS25-lua-scripting
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVehicleSystem.lua
More file actions
1401 lines (1079 loc) · 47.5 KB
/
VehicleSystem.lua
File metadata and controls
1401 lines (1079 loc) · 47.5 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
---Stores all vehicles of the savegame and handles the loading of them
local VehicleSystem_mt = Class(VehicleSystem)
---
function VehicleSystem.new(mission, customMt)
local self = setmetatable({}, customMt or VehicleSystem_mt)
self.mission = mission
self.vehicles = {} -- vehicles that are registered
self.pendingVehicleLoadingData = {} -- vehicle loading data that is currently pending
self.vehicleByUniqueId = {}
self.wetVehicles = {}
self.enterables = {}
self.lastEnteredVehicleIndex = 1
self.inputAttacherJoints = {}
self.interactiveVehicles = {}
self.vehiclesToDelete = {}
self.isReloadRunning = false
if g_addCheatCommands then
addConsoleCommand("gsVehicleShowDistance", "Shows the distance between vehicle and cam", "consoleCommandShowVehicleDistance", self)
end
if self.mission:getIsServer() then
addConsoleCommand("gsVehicleReload", "Reloads currently entered vehicle or vehicles within a range when second radius parameter is given", "consoleCommandReloadVehicle", self, "[resetVehicle]; [radiusAroundPlayer]")
if g_addCheatCommands then
addConsoleCommand("gsPalletAdd", "Adds a pallet", "consoleCommandAddPallet", self, "fillTypeName; [fillAmount]; [worldX]; [worldZ]")
addConsoleCommand("gsVehicleFuelSet", "Sets the vehicle fuel level", "consoleCommandSetFuel", self)
addConsoleCommand("gsVehicleTemperatureSet", "Sets the vehicle motor temperature", "consoleCommandSetMotorTemperature", self)
addConsoleCommand("gsFillUnitAdd", "Changes a fillUnit with given filllevel and filltype", "consoleCommandFillUnitAdd", self, "fillUnitIndex; fillTypeName; [amount]")
addConsoleCommand("gsVehicleOperatingTimeSet", "Sets the vehicle operating time", "consoleCommandSetOperatingTime", self)
addConsoleCommand("gsVehicleAddDirt", "Adds a given amount to current dirt amount", "consoleCommandAddDirtAmount", self)
addConsoleCommand("gsVehicleAddWear", "Adds a given amount to current wear amount", "consoleCommandAddWearAmount", self)
addConsoleCommand("gsVehicleAddWetness", "Adds a given amount to current wetness amount", "consoleCommandAddWetnessAmount", self)
addConsoleCommand("gsVehicleAddDamage", "Adds a given amount to current damage amount", "consoleCommandAddDamageAmount", self)
addConsoleCommand("gsVehicleLoadAll", "Load all vehicles", "consoleCommandLoadAllVehicles", self, "[loadConfigs]; [modsOnly]; [palletsOnly]; [verbose]", true)
end
if g_addTestCommands then
addConsoleCommand("gsVehicleToggleRandomFail", "Toggles random vehicle load failing", "consoleCommandVehicleToggleRandomFail", self)
addConsoleCommand("gsVehicleRemoveAll", "Removes all vehicles from current mission", "consoleCommandVehicleRemoveAll", self, nil, true)
addConsoleCommand("gsExportVehicleSets", "Exports vehicle sets", "consoleCommandExportVehicleSets", self)
end
end
g_messageCenter:subscribe(BuyVehicleEvent, self.onVehicleBuyEvent, self)
return self
end
---
function VehicleSystem:delete()
for i=#self.pendingVehicleLoadingData, 1, -1 do
self.pendingVehicleLoadingData[i]:cancelLoading()
end
for k, vehicle in pairs(self.vehiclesToDelete) do
vehicle:delete(true)
self.vehiclesToDelete[k] = nil
end
for i=#self.vehicles, 1, -1 do
local vehicle = self.vehicles[i]
vehicle:delete(true)
end
if self.savegameXMLFile ~= nil then
self.savegameXMLFile:delete()
self.savegameXMLFile = nil
end
self.mission = nil
self.vehicles = {}
self.vehicleByUniqueId = {}
self.wetVehicles = {}
self.enterables = {}
self.interactiveVehicles = {}
g_messageCenter:unsubscribeAll(self)
removeConsoleCommand("gsVehicleShowDistance")
removeConsoleCommand("gsVehicleReload")
removeConsoleCommand("gsPalletAdd")
removeConsoleCommand("gsVehicleFuelSet")
removeConsoleCommand("gsVehicleTemperatureSet")
removeConsoleCommand("gsFillUnitAdd")
removeConsoleCommand("gsVehicleOperatingTimeSet")
removeConsoleCommand("gsVehicleAddDirt")
removeConsoleCommand("gsVehicleAddWear")
removeConsoleCommand("gsVehicleAddWetness")
removeConsoleCommand("gsVehicleAddDamage")
removeConsoleCommand("gsVehicleLoadAll")
removeConsoleCommand("gsVehicleRemoveAll")
removeConsoleCommand("gsExportVehicleSets")
end
---
function VehicleSystem:deleteAll()
local numDeleted = #self.vehicles
for i=#self.vehicles, 1, -1 do
local vehicle = self.vehicles[i]
vehicle:delete()
end
return numDeleted
end
---
function VehicleSystem:update(dt)
if self.debugVehiclesToBeLoaded ~= nil then
self:consoleCommandLoadAllVehiclesNext()
end
if g_server ~= nil then
local weather = g_currentMission.environment.weather
local indoorMask = g_currentMission.indoorMask
local rainScale = weather:getRainFallScale()
if rainScale > 0.1 then
local timeSinceLastRain = weather:getTimeSinceLastRain()
local temperature = weather:getCurrentTemperature()
if timeSinceLastRain < 30 and temperature > 0 then
for _, vehicle in pairs(self.vehicles) do
if vehicle.updateWetness ~= nil then
local x, _, z = getWorldTranslation(vehicle.rootNode)
local isInside = indoorMask:getIsIndoorAtWorldPosition(x, z)
if not isInside then
vehicle:updateWetness(true, dt)
if vehicle:getIsWet() then
self.wetVehicles[vehicle] = vehicle
end
else
vehicle:updateWetness(false, dt)
if not vehicle:getIsWet() then
self.wetVehicles[vehicle] = nil
end
end
end
end
end
elseif next(self.wetVehicles) ~= nil then
for vehicle, _ in pairs(self.wetVehicles) do
vehicle:updateWetness(false, dt)
if not vehicle:getIsWet() then
self.wetVehicles[vehicle] = nil
end
end
end
end
end
---
function VehicleSystem:draw()
for _, vehicle in pairs(self.enterables) do
vehicle:drawUIInfo()
end
end
---
function VehicleSystem:addVehicle(vehicle)
if vehicle == nil or vehicle:isa(Vehicle) == nil then
Logging.error("Given object is not a vehicle")
return false
end
-- Ensure the vehicle has not already been added.
if vehicle:getUniqueId() ~= nil and self.vehicleByUniqueId[vehicle:getUniqueId()] ~= nil then
Logging.warning("Tried to add existing vehicle with unique id of %s! Existing: %s, new: %s", vehicle:getUniqueId(), tostring(self.vehicleByUniqueId[vehicle:getUniqueId()]), tostring(vehicle))
return false
end
-- If the vehicle has no unique id, give it one.
if vehicle:getUniqueId() == nil then
vehicle:setUniqueId(Utils.getUniqueId(vehicle, self.vehicleByUniqueId, VehicleSystem.UNIQUE_ID_PREFIX))
end
table.addElement(self.vehicles, vehicle)
self.vehicleByUniqueId[vehicle:getUniqueId()] = vehicle
if vehicle.getIsWet ~= nil then
if vehicle:getIsWet() then
self.wetVehicles[vehicle] = vehicle
end
end
g_messageCenter:publish(MessageType.VEHICLE_ADDED)
return true
end
---
function VehicleSystem:removeVehicle(vehicle)
table.removeElement(self.vehicles, vehicle)
local uniqueId = vehicle:getUniqueId()
if uniqueId ~= nil then
if self.vehicleByUniqueId[uniqueId] == vehicle then
self.vehicleByUniqueId[uniqueId] = nil
end
end
self.wetVehicles[vehicle] = nil
g_messageCenter:publish(MessageType.VEHICLE_REMOVED)
end
---
function VehicleSystem:getVehicleByUniqueId(uniqueId)
return self.vehicleByUniqueId[uniqueId]
end
---
function VehicleSystem:addPendingVehicleLoad(vehicleLoadingData)
table.addElement(self.pendingVehicleLoadingData, vehicleLoadingData)
end
---
function VehicleSystem:removePendingVehicleLoad(vehicleLoadingData)
table.removeElement(self.pendingVehicleLoadingData, vehicleLoadingData)
end
---
function VehicleSystem:canStartMission()
for i=1, #self.vehicles do
if not self.vehicles[i]:getIsSynchronized() then
return false
end
end
if #self.pendingVehicleLoadingData > 0 then
return false
end
return true
end
---
function VehicleSystem:addEnterableVehicle(vehicle)
table.addElement(self.enterables, vehicle)
end
---
function VehicleSystem:removeEnterableVehicle(vehicle)
table.removeElement(self.enterables, vehicle)
end
---
function VehicleSystem:setEnteredVehicle(vehicle)
for i=1, #self.enterables do
if self.enterables[i] == vehicle then
self.lastEnteredVehicleIndex = i
break
end
end
end
---
function VehicleSystem:getNextEnterableVehicle(currentVehicle, delta)
local numVehicles = #self.enterables
if numVehicles == 0 then
return nil
end
local index = 1
if g_localPlayer:getIsInVehicle() and currentVehicle ~= nil then
for i, enterable in ipairs(self.enterables) do
if currentVehicle == self.enterables[i] then
index = i + delta
break
end
end
else
if delta > 0 then
-- with tab we go directly in the last entered vehicle
index = self.lastEnteredVehicleIndex
else
-- with shift + tab we enter the last vehicle in the list -> to quickly get in the last bought one
index = numVehicles
end
end
local found = false
for _=1, numVehicles do
local enterable = self.enterables[index]
if enterable ~= nil and enterable:getIsTabbable() and enterable:getIsEnterable() then
found = true
break
else
index = index + delta
if index > numVehicles then
index = 1
elseif index < 1 then
index = numVehicles
end
end
end
if found then
return self.enterables[index]
end
return nil
end
---
function VehicleSystem:registerInputAttacherJoint(vehicle, inputAttacherJointIndex, inputAttacherJoint)
local inputAttacherJointInfo = {}
inputAttacherJointInfo.vehicle = vehicle
inputAttacherJointInfo.jointIndex = inputAttacherJointIndex
inputAttacherJointInfo.inputAttacherJoint = inputAttacherJoint
inputAttacherJointInfo.node = inputAttacherJoint.node
inputAttacherJointInfo.jointType = inputAttacherJoint.jointType
inputAttacherJointInfo.translation = {getWorldTranslation(inputAttacherJoint.node)}
table.addElement(self.inputAttacherJoints, inputAttacherJointInfo)
return inputAttacherJointInfo
end
---
function VehicleSystem:updateInputAttacherJoint(inputAttacherJointInfo)
local x, y, z = getWorldTranslation(inputAttacherJointInfo.node)
inputAttacherJointInfo.translation[1], inputAttacherJointInfo.translation[2], inputAttacherJointInfo.translation[3] = x, y, z
end
---
function VehicleSystem:removeInputAttacherJoint(inputAttacherJointInfo)
table.removeElement(self.inputAttacherJoints, inputAttacherJointInfo)
end
---
function VehicleSystem:addInteractiveVehicle(vehicle)
self.interactiveVehicles[vehicle] = vehicle
end
---
function VehicleSystem:removeInteractiveVehicle(vehicle)
self.interactiveVehicles[vehicle] = nil
end
---
function VehicleSystem:save(xmlFilename, usedModNames)
local xmlFile = XMLFile.create("vehiclesXML", xmlFilename, "vehicles", Vehicle.xmlSchemaSavegame)
if xmlFile ~= nil then
self:saveToXML(self.vehicles, xmlFile, usedModNames)
xmlFile:delete()
end
end
---
function VehicleSystem:saveToXML(vehicles, xmlFile, usedModNames)
if xmlFile ~= nil then
local xmlIndex = 0
for i, vehicle in ipairs(vehicles) do
if vehicle:getNeedsSaving() then
self:saveVehicleToXML(vehicle, xmlFile, xmlIndex, i, usedModNames)
xmlIndex = xmlIndex + 1
end
end
xmlFile:save(false, true)
end
end
---
function VehicleSystem:saveVehicleToXML(vehicle, xmlFile, index, i, usedModNames)
local vehicleKey = string.format("vehicles.vehicle(%d)", index)
local modName = vehicle.customEnvironment
if modName ~= nil then
if usedModNames ~= nil then
usedModNames[modName] = modName
end
xmlFile:setValue(vehicleKey.."#modName", modName)
end
xmlFile:setValue(vehicleKey.."#filename", HTMLUtil.encodeToHTML(NetworkUtil.convertToNetworkFilename(vehicle.configFileName)))
vehicle:saveToXMLFile(xmlFile, vehicleKey, usedModNames)
end
---
function VehicleSystem:load(xmlFilename, asyncCallbackFunction, asyncCallbackObject, asyncCallbackArguments, resetVehicles)
self.savegameXMLFile = XMLFile.load("vehiclesXML", xmlFilename, Vehicle.xmlSchemaSavegame)
self:loadFromXMLFile(self.savegameXMLFile, asyncCallbackFunction, asyncCallbackObject, asyncCallbackArguments)
end
---
function VehicleSystem:loadFromXMLFile(xmlFile, asyncCallbackFunction, asyncCallbackObject, asyncCallbackArguments, resetVehicles, keepPosition)
local defaultItemsToSPFarm = xmlFile:getValue("vehicles#loadAnyFarmInSingleplayer", false)
self.loadedVehicles = {}
self.vehiclesToLoad = 0
self.vehicleLoadingState = nil
self.asyncCallbackFunction = asyncCallbackFunction
self.asyncCallbackObject = asyncCallbackObject
self.asyncCallbackArguments = asyncCallbackArguments
xmlFile:iterate("vehicles.vehicle", function(index, key)
g_asyncTaskManager:addSubtask(function()
self:loadVehicleFromXML(xmlFile, key, defaultItemsToSPFarm, resetVehicles, keepPosition)
end)
end)
if self.asyncCallbackFunction ~= nil then
g_asyncTaskManager:addSubtask(function()
if self.vehiclesToLoad <= 0 then
self.asyncCallbackFunction(self.asyncCallbackObject, self.loadedVehicles, VehicleLoadingState.OK, self.asyncCallbackArguments)
self.asyncCallbackFunction = nil
self.asyncCallbackObject = nil
self.asyncCallbackArguments = nil
end
end)
end
end
---
function VehicleSystem:loadVehicleFromXML(xmlFile, key, defaultItemsToSPFarm, resetVehicles, keepPosition)
local missionInfo = g_currentMission.missionInfo
local missionDynamicInfo = g_currentMission.missionDynamicInfo
local filename = xmlFile:getValue(key.."#filename")
local defaultProperty = xmlFile:getValue(key .. "#defaultFarmProperty", false)
local farmId = xmlFile:getValue(key .. "#farmId")
local loadForCompetitive = defaultProperty and missionInfo.isCompetitiveMultiplayer and g_farmManager:getFarmById(farmId) ~= nil
local loadDefaultProperty = defaultProperty and (missionInfo.loadDefaultFarm and not missionDynamicInfo.isMultiplayer) and (farmId == FarmManager.SINGLEPLAYER_FARM_ID or defaultItemsToSPFarm)
local allowedToLoad = missionInfo.isValid or not defaultProperty or loadDefaultProperty or loadForCompetitive
if allowedToLoad then
filename = NetworkUtil.convertFromNetworkFilename(filename)
local savegame = {xmlFile=xmlFile, key=key, ignoreFarmId=false, resetVehicles=resetVehicles, keepPosition=keepPosition}
if loadDefaultProperty and defaultItemsToSPFarm and farmId ~= FarmManager.SINGLEPLAYER_FARM_ID then
farmId = FarmManager.SINGLEPLAYER_FARM_ID
savegame.ignoreFarmId = true
end
local storeItem = g_storeManager:getItemByXMLFilename(filename)
if storeItem ~= nil then
if g_currentMission.slotSystem:hasEnoughSlots(storeItem) then
self.vehiclesToLoad = self.vehiclesToLoad + 1
local data = VehicleLoadingData.new()
data:setStoreItem(storeItem)
data:setSavegameData(savegame)
data:setAddToPhysics(false)
data:load(self.loadVehicleFinished, self)
return true
else
g_currentMission:addMoney(storeItem.price, farmId, MoneyType.SHOP_VEHICLE_SELL, true)
Logging.warning("Too many slots in use. Selling vehicle '%s' for '%d'", filename, storeItem.price)
end
end
else
Logging.xmlInfo(xmlFile, "Vehicle '%s' is not allowed to be loaded", filename)
end
return false
end
---
function VehicleSystem:loadVehicleFinished(vehicles, loadingState)
if loadingState == VehicleLoadingState.OK then
for _, vehicle in ipairs(vehicles) do
table.insert(self.loadedVehicles, vehicle)
end
else
self.vehicleLoadingState = self.vehicleLoadingState or loadingState
end
self.vehiclesToLoad = self.vehiclesToLoad - 1
if self.vehiclesToLoad <= 0 then
for _, loadedVehicle in ipairs(self.loadedVehicles) do
loadedVehicle:addToPhysics()
end
if self.asyncCallbackFunction ~= nil then
self.asyncCallbackFunction(self.asyncCallbackObject, self.loadedVehicles, self.vehicleLoadingState or VehicleLoadingState.OK, self.asyncCallbackArguments)
self.asyncCallbackFunction = nil
self.asyncCallbackObject = nil
self.asyncCallbackArguments = nil
self.loadedVehicles = nil
self.vehicleLoadingState = nil
end
end
end
---
function VehicleSystem:onVehicleBuyEvent(errorCode, leaseVehicle, price)
local serverFarmId = g_currentMission:getFarmId()
local numDrivables = 0
local numVehicles = 0
for _, item in ipairs(self.vehicles) do
if item:getOwnerFarmId() == serverFarmId then
if item.spec_drivable ~= nil then
numDrivables = numDrivables + 1
numVehicles = numVehicles + 1
elseif item.spec_attachable ~= nil and item.spec_bigBag == nil then
numVehicles = numVehicles + 1
end
end
end
g_achievementManager:tryUnlock("NumDrivables", numDrivables)
g_achievementManager:tryUnlock("NumVehiclesSmall", numVehicles)
g_achievementManager:tryUnlock("NumVehiclesLarge", numVehicles)
end
---Returns the corresponding vehicle to a given physics node id (supports correct detection of hard attached implements, which share the same compound as the parent vehicle)
function VehicleSystem:getVehicleByNodeId(nodeId, subShapeId)
local vehicle
if nodeId ~= subShapeId then
-- object is a compoundChild. Try to find the compound
local parentId = subShapeId
while parentId ~= 0 do
if g_currentMission.nodeToObject[parentId] ~= nil then
-- found valid compound
vehicle = g_currentMission.nodeToObject[parentId]
break
end
parentId = getParent(parentId)
end
else
vehicle = g_currentMission.nodeToObject[nodeId]
end
if vehicle ~= nil and vehicle.isa ~= nil and vehicle:isa(Vehicle) then
return vehicle
end
return nil
end
---
function VehicleSystem:consoleCommandShowVehicleDistance(active)
g_showVehicleDistance = Utils.getNoNil(active, not g_showVehicleDistance)
end
---
function VehicleSystem:consoleCommandReloadVehicle(resetVehicle, radius)
local usage = "Usage: gsVehicleReload [resetVehicle] [radius]"
if g_gui.currentGuiName == "ShopMenu" or g_gui.currentGuiName == "ShopConfigScreen" then
return "Error: Reload not supported while in shop!"
end
if self.isReloadRunning then
return "Error: Reloading of vehicles already in progress!"
end
if not self.mission:getIsServer() or self.mission.missionDynamicInfo.isMultiplayer then
return "Error: Reloading only available in SP"
end
resetVehicle = Utils.stringToBoolean(resetVehicle)
radius = tonumber(radius) or 0
local posX, posY, posZ = g_localPlayer:getPosition()
-- reload sound and material templates so the new vehicle sounds and materials are based on the newest templates
g_soundManager:reloadSoundTemplates()
g_vehicleMaterialManager:loadMaterialTemplates(VehicleMaterialManager.DEFAULT_TEMPLATES_FILENAME)
g_vehicleMaterialManager:loadMaterialTemplates(VehicleMaterialManager.DEFAULT_BRAND_TEMPLATES_FILENAME)
local affectedVehicles = {} -- list with vehicle plus all attachments affected by the reload
local usedVehicles = {}
local usedModNames = {}
local function addVehicleToReload(v, list)
if v.isVehicleSaved then
v.isReconfigurating = true
table.insert(list, v)
usedVehicles[v] = true
if v ~= nil and v.getAttachedImplements ~= nil then
local attachedImplements = v:getAttachedImplements()
for _, implement in pairs(attachedImplements) do
addVehicleToReload(implement.object, list)
end
end
else
v:delete()
end
end
if g_localPlayer:getCurrentVehicle() ~= nil then
addVehicleToReload(g_localPlayer:getCurrentVehicle(), affectedVehicles)
end
-- within this radius all vehicles are reloaded
if radius ~= 0 then
for _, v in pairs(self.vehicles) do
if v ~= g_localPlayer:getCurrentVehicle() then
local vx, vy, vz = getWorldTranslation(v.rootNode)
if MathUtil.vector3Length(vx-posX, vy-posY, vz-posZ) < radius then
if usedVehicles[v.rootVehicle] == nil then
addVehicleToReload(v.rootVehicle, affectedVehicles)
end
end
end
end
end
if #affectedVehicles == 0 then
return "Warning: No vehicle reloaded. Enter a vehicle first or use the command with the radius parameter given, e.g. 'gsVehicleReload false 25'\n" .. usage
end
local xmlFile = XMLFile.create("reloadVehiclesXMLFile", "", "vehicles", Vehicle.xmlSchemaSavegame)
if xmlFile == nil then
return "Error: Unable to create XML for saving vehicles"
end
simulatePhysics(false)
self.isReloadRunning = true
-- remove the vehicles from the unique id mapping, so we allow registration of the new vehicles
-- if the registration fails, we readd the vehicles to the mapping
for _, vehicle in ipairs(affectedVehicles) do
self.vehicleByUniqueId[vehicle:getUniqueId()] = nil
end
self:saveToXML(affectedVehicles, xmlFile, usedModNames)
for _, vehicle in ipairs(affectedVehicles) do
vehicle:removeFromPhysics()
end
local steerableId
if g_localPlayer:getCurrentVehicle() ~= nil then
steerableId = g_localPlayer:getCurrentVehicle():getUniqueId()
end
g_i3DManager:clearEntireSharedI3DFileCache(false)
local function asyncCallbackFunction(_, vehicles, vehicleLoadState, arguments)
local success = true
if vehicleLoadState == VehicleLoadingState.OK then
if #vehicles == #affectedVehicles then
for _, affected_vehicle in pairs(affectedVehicles) do
affected_vehicle:delete()
end
if steerableId ~= nil then
for _, vehicle in pairs(vehicles) do
if vehicle:getUniqueId() == steerableId then
g_localPlayer:requestToEnterVehicle(vehicle)
end
end
end
else
Logging.error("Not all vehicles could be reloaded")
success = false
end
else
Logging.error("Failed to load vehicles")
success = false
end
if not success then
for _, loadedVehicle in pairs(vehicles) do
loadedVehicle:delete()
end
for _, vehicle in ipairs(affectedVehicles) do
vehicle:addToPhysics()
self.vehicleByUniqueId[vehicle:getUniqueId()] = vehicle
end
end
xmlFile:delete()
self.isReloadRunning = false
simulatePhysics(true)
if success then
Logging.info("%d vehicle(s) reloaded", #affectedVehicles)
end
end
g_asyncTaskManager:addTask(function()
local keepPosition = true
self:loadFromXMLFile(xmlFile, asyncCallbackFunction, nil, nil, resetVehicle, keepPosition)
end)
return
end
---
function VehicleSystem:consoleCommandAddPallet(palletFillTypeName, amount, worldX, worldZ)
local pallets = {}
for _, fillType in pairs(g_fillTypeManager:getFillTypes()) do
if fillType.palletFilename ~= nil then
pallets[fillType.name] = fillType.palletFilename
end
end
if palletFillTypeName == nil then
return "Error: no fillType given"
end
local localPlayer = g_localPlayer
if palletFillTypeName:lower() == "all" then
local x, _, z = localPlayer:getPosition()
local dirX, dirZ = localPlayer:getCurrentFacingDirection()
for _, fillType in pairs(g_fillTypeManager:getFillTypes()) do
if fillType.palletFilename ~= nil then
x, z = x + dirX * 3, z + dirZ * 3
self:consoleCommandAddPallet(fillType.name, amount, x, z)
end
end
return
end
palletFillTypeName = string.upper(palletFillTypeName)
local palletFillType = g_fillTypeManager:getFillTypeIndexByName(palletFillTypeName)
if palletFillType == nil then
return string.format("Error: Invalid pallet fillType '%s'. Valid types are %s", palletFillTypeName, table.concatKeys(pallets, ", "))
end
local xmlFilename = pallets[palletFillTypeName]
if xmlFilename == nil then
return string.format("Error: no pallet for given fillType '%s'", palletFillTypeName)
end
local x, y, z = localPlayer:getPosition()
local dirX, dirZ = localPlayer:getCurrentFacingDirection()
x,z = x+dirX*4, z+dirZ*4
if worldX ~= nil then
x = tonumber(worldX)
end
if worldZ ~= nil then
z = tonumber(worldZ)
end
local yOffset = 0
if Platform.gameplay.hasDynamicPallets then
yOffset = 0.2
end
local collisionMask = CollisionFlag.STATIC_OBJECT + CollisionFlag.TERRAIN + CollisionFlag.TERRAIN_DELTA + CollisionFlag.DYNAMIC_OBJECT + CollisionFlag.VEHICLE
local objectId, _, hitY, _, _ = RaycastUtil.raycastClosest(x, y + 25, z, 0, -1, 0, 40, collisionMask)
if objectId ~= nil then
y = hitY
else
y = getTerrainHeightAtWorldPos(g_terrainNode, x, y, z)
end
local function asyncCallbackFunction(_, vehicles, vehicleLoadState, arguments)
if vehicleLoadState == VehicleLoadingState.OK then
local vehicle = vehicles[1]
local fillUnits = vehicle:getFillUnits()
local amountToAdd = tonumber(amount) or math.huge
local addedAmount = 0
for _, fillUnit in ipairs(fillUnits) do
if vehicle:getFillUnitSupportsFillType(fillUnit.fillUnitIndex, palletFillType) then
addedAmount = addedAmount + vehicle:addFillUnitFillLevel(1, fillUnit.fillUnitIndex, amountToAdd, palletFillType, ToolType.UNDEFINED, nil)
amountToAdd = amountToAdd - addedAmount
if amountToAdd <= 0 then
break
end
end
end
print(string.format("Loaded pallet with %dl of %s", addedAmount, palletFillTypeName))
return
end
printError("Error: Failed to load pallet")
end
local farmId = self.mission:getFarmId()
farmId = ((farmId ~= FarmManager.SPECTATOR_FARM_ID) and farmId) or 1
local data = VehicleLoadingData.new()
data:setFilename(xmlFilename)
data:setPosition(x, y + yOffset, z)
data:setPropertyState(VehiclePropertyState.OWNED)
data:setOwnerFarmId(farmId)
data:load(asyncCallbackFunction)
return
end
---
function VehicleSystem:consoleCommandSetFuel(fuelLevel)
if self.mission:getIsServer() then
if fuelLevel == nil then
return "No fuellevel given! Usage: gsVehicleFuelSet <fuelLevel>"
end
fuelLevel = Utils.getNoNil(tonumber(fuelLevel), 10000000000)
local vehicle = g_localPlayer:getCurrentVehicle()
if vehicle ~= nil then
if vehicle.getConsumerFillUnitIndex ~= nil then
local fillUnitIndex = vehicle:getConsumerFillUnitIndex(FillType.DIESEL) or vehicle:getConsumerFillUnitIndex(FillType.ELECTRICCHARGE) or vehicle:getConsumerFillUnitIndex(FillType.METHANE)
if fillUnitIndex ~= nil then
local fillLevel = vehicle:getFillUnitFillLevel(fillUnitIndex)
local delta = fuelLevel - fillLevel
vehicle:addFillUnitFillLevel(self.mission:getFarmId(), fillUnitIndex, delta, vehicle:getFillUnitFirstSupportedFillType(fillUnitIndex), ToolType.UNDEFINED, nil)
return "Added fuel"
else
return "No Fuel filltype supported!"
end
end
return "Vehicle has no consumer"
else
return "Enter a vehicle first!"
end
end
return "Not available on clients"
end
---
function VehicleSystem:consoleCommandSetMotorTemperature(temperature)
if self.mission:getIsServer() then
if temperature == nil then
return "No temperature given! Usage: gsVehicleTemperatureSet <temperature>"
end
temperature = Utils.getNoNil(tonumber(temperature), 0)
local vehicle = g_localPlayer:getCurrentVehicle()
if vehicle ~= nil then
local spec = vehicle.spec_motorized
if spec ~= nil then
spec.motorTemperature.value = math.clamp(temperature, spec.motorTemperature.valueMin, spec.motorTemperature.valueMax)
return "Set motor temperature to "..spec.motorTemperature.value
end
return "Vehicle has no motor"
else
return "Enter a vehicle first!"
end
end
return "Not available on clients"
end
---
function VehicleSystem:consoleCommandFillUnitAdd(fillUnitIndex, fillTypeName, amount)
local usage = "Usage: 'gsFillUnitAdd <fillUnitIndex> <fillTypeName> [amount]'"
local mission = self.mission
local player = g_localPlayer
local controlledVehicle = player:getCurrentVehicle()
local fillableVehicle
if controlledVehicle ~= nil and controlledVehicle.getSelectedObject ~= nil then
local selectedObject = controlledVehicle:getSelectedObject()
if selectedObject ~= nil and selectedObject.vehicle.addFillUnitFillLevel ~= nil then
fillableVehicle = selectedObject.vehicle
end
end
if fillableVehicle == nil then
if controlledVehicle ~= nil and controlledVehicle.addFillUnitFillLevel ~= nil then
fillableVehicle = controlledVehicle
end
end
if fillableVehicle == nil then
-- TODO: Update this to new player.
if player.isControlled and player.lastFoundAnyObject ~= nil then
local object = g_currentMission.nodeToObject[mission.player.lastFoundAnyObject]
if object ~= nil and object:isa(Vehicle) and object.addFillUnitFillLevel ~= nil then
fillableVehicle = object
end
end
end
local farmId = mission:getFarmId()
if fillableVehicle == nil or fillableVehicle.getFillUnitSupportedToolTypes == nil then
return "Error: could not find a fillable vehicle!"
end
local function getSupportedFilltypesString()
local fillUnits = {}
for fillUnitIdx, fillTypesIndices in pairs(fillableVehicle:debugGetSupportedFillTypesPerFillUnit()) do
table.insert(fillUnits, string.format("FillUnit %d - FillTypes: %s", fillUnitIdx, table.concat(g_fillTypeManager:getFillTypeNamesByIndices(fillTypesIndices), " ")))
end
return "Available FillUnits and supported FillTypes:\n" .. table.concat(fillUnits, "\n")
end
if fillUnitIndex == nil or fillTypeName == nil then
return "Error: Missing parameters.\n" .. usage
end
if not mission:getIsServer() then
return "Error: 'gsFillUnitAdd' can only be called on server side!"
end
fillUnitIndex = tonumber(fillUnitIndex)
local fillTypeIndex = g_fillTypeManager:getFillTypeIndexByName(fillTypeName)
amount = tonumber(amount)