-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathclient.lua
More file actions
1965 lines (1816 loc) · 81.3 KB
/
client.lua
File metadata and controls
1965 lines (1816 loc) · 81.3 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
---------------- Main data ----------------
--[[
These variables store the main state for the mileage and wear tracking system.
They are used throughout the script to keep track of the player's vehicle status,
UI visibility, wear levels, and cached data for server sync.
Customers can reference these variables to understand what is being tracked.
]]--
-- Importing the required lib
require("@wizard-lib/client/functions")
-- UI and vehicle state flags
local loaded = false -- Is vehicle data loaded?
local mileageVisible = false -- Is the mileage UI currently visible?
local isInVehicle = false -- Is the player currently in a vehicle?
local waitingForData = false -- Waiting for server data to load?
local clutchWearDirty = false -- Is clutch wear data dirty (needs sync)?
local brakeWearDirty = false -- Is brake wear data dirty (needs sync)?
local allowSmartGearDetect = true -- Allow smart gear detection for clutch wear?
local mileageUIVisible = true -- Should the mileage UI be shown?
local lastPos = nil -- Last known vehicle position (vector3)
local currentPlate = nil -- Current vehicle plate being tracked
local CWFT = false -- Is checkWear menu openned for targetting script?
local clipboardEntity = nil -- The clipboard entity for checking vehicle wear
local vehOwned = false -- Is the vehicle owned by anyone?
local playerPed = PlayerPedId() -- Get the player's ped id (will update during the script events)
-- Wear distances (in meters, set by config/unit)
local unitMultiplier = (Cfg.Unit == "imperial") and 1609.34 or 1000
local sparkPlugchangedist = Config.SparkPlugChangeDistance * unitMultiplier
local oilchangedist = Config.OilChangeDistance * unitMultiplier
local oilfilterchangedist = Config.OilFilterDistance * unitMultiplier
local airfilterchangedist = Config.AirFilterDistance * unitMultiplier
local tirechangedist = Config.TireWearDistance * unitMultiplier
-- Wear and mileage tracking values
local accDistance = 0.0 -- Accumulated distance driven (meters)
local lastOilChange = 0.0 -- Last oil change mileage
local lastOilFilterChange = 0.0 -- Last oil filter change mileage
local lastAirFilterChange = 0.0 -- Last air filter change mileage
local lastTireChange = 0.0 -- Last tire change mileage
local lastbrakeChange = 0.0 -- Last brake change mileage
local lastbrakeWear = 0.0 -- Current brake wear value
local lastClutchChange = 0.0 -- Last clutch change mileage
local lastClutchWear = 0.0 -- Current clutch wear value
local lastSuspensionChange = 0.0 -- Last suspension change mileage
local suspensionWear = 0.0 -- Current suspension wear value
local lastSparkPlugChange = 0.0 -- Last spark plug change mileage
local sparkPlugWear = 0.0 -- Current spark plug wear value
local lastSavedMil = 0.0 -- Lastest saved mileage
-- Cached values for syncing with the server
local cachedClutchWear = 0.0
local cachedBrakeWear = 0.0
-- UI customization values
local mileageUIPosX = 0.0
local mileageUIPosY = 0.0
local checkwearUIPosX = 0.0
local checkwearUIPosY = 0.0
local mileageUISize = 1.0
local checkwearUISize = 1.0
-- Engine warning notification timer
local lastEngineCriticalNotify = 0
-- Callback tables for vehicle list requests
local vehicleListCallbacks = {}
-- Default wait time invertals for threads
local wTM = 3000
local wTU = 5000
local wTB = 2000
local wTC = 2000
---------------- Bought vehicles detection ----------------
--[[
This section checks if a vehicle is owned by the player.
If Config.BoughtVehiclesOnly is true, it will ask the server for ownership status.
Otherwise, it will always return true (all vehicles are considered owned).
]]--
if Config.BoughtVehiclesOnly then
local ownershipCache = {} -- Cache to store ownership results for plates
-- Checks if the given plate is owned by the player
-- Returns true/false (cached if possible, otherwise asks the server)
function IsVehicleOwned(plate)
-- Use cached result if available for this plate
if ownershipCache[plate] ~= nil then
return ownershipCache[plate]
end
local p = promise.new() -- Create a promise for async server response
-- Handler for ownership result from server
local function ownershipHandler(owned)
ownershipCache[plate] = owned -- Cache the result
p:resolve(owned) -- Resolve the promise with the result
end
-- Register a one-time event handler for the ownership result
RegisterNetEvent('wizard_vehiclemileage:client:ownershipResult')
local eventHandler = AddEventHandler('wizard_vehiclemileage:client:ownershipResult', ownershipHandler)
-- Ask server if the vehicle is owned
TriggerServerEvent('wizard_vehiclemileage:server:checkOwnership', plate)
-- Wait for the result from the server
local result = Citizen.Await(p)
RemoveEventHandler(eventHandler) -- Clean up the event handler
return result
end
else
-- If not checking ownership, always return true (all vehicles are considered owned)
function IsVehicleOwned()
return true
end
end
---------------- Functions ----------------
--[[
Triggers a vehicle list callback to retrieve all vehicles from the server.
This is used for admin/database features that need to display or manage all vehicles.
The callback is stored in a table with a unique ID, so when the server responds,
the correct callback can be executed.
@param cb (function): The function to call with the vehicle list (table).
]]--
local function TriggerVehicleListCallback(cb)
local cbId = math.random(100000, 999999) -- Generate a unique callback ID
vehicleListCallbacks[cbId] = cb -- Store the callback for later use
TriggerServerEvent('wizard_vehiclemileage:server:getAllVehicles', cbId) -- Ask the server for the vehicle list
end
--[[
Updates the spark plug wear for the given vehicle.
- Calculates how much the spark plugs have worn based on distance driven since last change.
- Sends the updated wear value to the server for saving.
- If the spark plugs are fully worn, there is a chance for a misfire (engine RPM drops).
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateSparkPlugWear(vehicle)
if not Config.WearTracking.SparkPlugs then return end -- Skip if spark plug wear tracking is disabled
-- Calculate how far the vehicle has driven since last spark plug change
local distanceSinceSparkPlugChange = accDistance - lastSparkPlugChange
-- Calculate wear ratio (0 = new, 1 = fully worn)
local wearRatio = distanceSinceSparkPlugChange / (Config.SparkPlugChangeDistance * 1000)
if wearRatio > 1 then wearRatio = 1 end
sparkPlugWear = wearRatio
-- If spark plugs are fully worn, chance for a misfire
if sparkPlugWear >= 1.0 then
if DoesEntityExist(veh) then
if math.random() < Config.MissfireChance then
Notify('Wizard Mileage', locale('warning.spark_plug_misfire'), 'warning')
SetVehicleCurrentRpm(veh, 0.0)
Wait(100)
SetVehicleCurrentRpm(veh, 0.0)
end
end
end
end
--[[
Updates the engine damage based on oil and oil filter wear.
- If oil or filter is overdue, applies engine damage and drains oil faster.
- Notifies the player if engine health is critical.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateEngineDamage(vehicle)
if not Config.WearTracking.Oil then return end
-- Calculate wear ratios for oil and oil filter
local oilDistanceDriven = accDistance - lastOilChange
local oilWearRatio = oilDistanceDriven / oilchangedist
local filterDistanceDriven = accDistance - lastOilFilterChange
local filterWearRatio = filterDistanceDriven / oilfilterchangedist
-- If either oil or filter is overdue, apply damage
if oilWearRatio > 1.0 or filterWearRatio > 1.0 then
local engineHealth = GetVehicleEngineHealth(vehicle)
local damage = (math.max(oilWearRatio, filterWearRatio) - 1.0) * Config.EngineDamageRate
-- Simulate oil draining faster as damage increases
local oilDrainRate = damage * 0.1
lastOilChange = lastOilChange - (oilDrainRate * oilchangedist)
-- If engine is very damaged, reset oil change
if engineHealth < 400.0 then
lastOilChange = 0.0
end
-- Apply engine damage
SetVehicleEngineHealth(vehicle, math.max(0.0, engineHealth - damage))
-- Notify player if engine is critical
local invertal = Config.WarningsInterval * 1000
if engineHealth < 200.0 then
local currentTime = GetGameTimer()
if (currentTime - lastEngineCriticalNotify) >= invertal then
Notify('Wizard Mileage', locale('warning.engine_critical'), 'error')
lastEngineCriticalNotify = currentTime
end
end
end
end
--[[
Updates the air filter performance for the given vehicle.
- Reduces acceleration as the air filter wears out.
- Saves and restores original drive force as needed.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateAirFilterPerformance(vehicle)
if not Config.WearTracking.AirFilter then return end
-- Calculate air filter wear ratio (0 = new, 1 = fully worn)
local airFilterDistanceDriven = accDistance - lastAirFilterChange
local airFilterWearRatio = math.min(1.0, airFilterDistanceDriven / airfilterchangedist)
-- Get and save original drive force if not already saved
local plate = GetVehiclePlate(vehicle)
TriggerServerEvent('wizard_vehiclemileage:server:getOriginalDriveForce', plate)
local currentAcceleration = GetVehicleHandlingFloat(vehicle, "CHandlingData", "fInitialDriveForce")
originalDriveForce = originalDriveForce or currentAcceleration
TriggerServerEvent('wizard_vehiclemileage:server:saveOriginalDriveForce', plate, originalDriveForce)
-- Reduce acceleration based on wear
local reducedAcceleration = originalDriveForce * (1.0 - (Config.AccelerationReduction * airFilterWearRatio))
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fInitialDriveForce", reducedAcceleration)
end
--[[
Updates the tire wear for the given vehicle.
- Reduces tire grip as tires wear out.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateTireWear(vehicle)
if not Config.WearTracking.Tires then return end
-- Calculate tire wear ratio (0 = new, 1 = fully worn)
local distanceSinceTireChange = accDistance - lastTireChange
local wearRatio = distanceSinceTireChange / tirechangedist
if wearRatio > 1 then
wearRatio = 1
end
-- Calculate new grip value based on wear
local newGrip = Config.BaseTireGrip - ((Config.BaseTireGrip - Config.MinTireGrip) * wearRatio)
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fTractionCurveMax", newGrip)
end
--[[
Updates the brake wear for the given vehicle.
- Adjusts the brake force based on the current brake wear value.
- The more worn the brakes, the less effective they become.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateBrakeWear(vehicle)
if not Config.WearTracking.Brakes then return end -- Skip if brake wear tracking is disabled
-- Get the current brake force (for reference, not used in calculation)
local currentBrakeForce = GetVehicleHandlingFloat(vehicle, "CHandlingData", "fBrakeForce")
-- Calculate brake efficiency based on wear (1.0 = new, decreases as wear increases)
local efficiency = 1.0 - (math.min(lastbrakeWear, Config.MaxBrakeWear) / Config.MaxBrakeWear * Config.BrakeEfficiencyLoss)
local baseBrakeForce = Config.BaseBrakeForce
-- Set the new brake force on the vehicle, reduced by wear
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fBrakeForce", baseBrakeForce * efficiency)
end
--[[
Updates the suspension wear for the given vehicle.
- Calculates how much the suspension has worn based on distance driven since last change.
- Saves and restores original suspension force and raise values as needed.
- Applies new suspension values to the vehicle based on wear.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateSuspensionWear(vehicle)
if not Config.WearTracking.Suspension then return end -- Skip if suspension wear tracking is disabled
-- Calculate how far the vehicle has driven since last suspension change
local distanceSinceSuspensionChange = accDistance - lastSuspensionChange
-- Calculate wear ratio (0 = new, 1 = fully worn)
local wearRatio = distanceSinceSuspensionChange / (Config.SuspensionChangeDistance * 1000)
if wearRatio > 1 then wearRatio = 1 end
local plate = GetVehiclePlate(vehicle)
-- Request original suspension values from the server (if not already cached)
TriggerServerEvent('wizard_vehiclemileage:server:getOriginalSuspensionValue', plate)
suspensionWear = wearRatio
-- Get or save original suspension force and raise values
local originalForce = originalSuspensionForce or GetVehicleHandlingFloat(vehicle, "CHandlingData", "fSuspensionForce")
local originalRaise = originalSuspensionRaise or GetVehicleHandlingFloat(vehicle, "CHandlingData", "fSuspensionRaise")
if not originalSuspensionForce or originalSuspensionForce == 0 then
originalSuspensionForce = originalForce
TriggerServerEvent('wizard_vehiclemileage:server:saveOriginalSuspensionForce', plate, originalForce)
end
if not originalSuspensionRaise then
originalSuspensionRaise = originalRaise
TriggerServerEvent('wizard_vehiclemileage:server:saveOriginalSuspensionRaise', plate, originalRaise)
end
-- Calculate new suspension values based on wear
local newForce = originalForce * (1.0 - suspensionWear)
local newRaise = originalRaise * (1.0 - suspensionWear)
-- Apply new suspension values to the vehicle
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fSuspensionForce", newForce)
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fSuspensionRaise", newRaise)
end
--[[
Updates the clutch wear for the given vehicle.
- Calculates clutch efficiency based on wear.
- If the clutch is very worn (efficiency <= 20%), simulates clutch failure and possible engine stall.
- Notifies the player if the vehicle stalls due to clutch wear.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateClutchWear(vehicle)
-- Calculate clutch efficiency (1.0 = new, decreases as wear increases)
local efficiency = 1.0 - (math.min(lastClutchWear, Config.MaxClutchWear) / Config.MaxClutchWear * Config.ClutchEfficiencyLoss)
-- If clutch is very worn, simulate clutch failure and possible stall
if efficiency <= 0.2 then
-- Simulate clutch slipping/failure
InvokeNative(GetHashKey('SET_VEHICLE_CLUTCH') & 0xFFFFFFFF, vehicle, -1.0)
-- Random chance to stall the engine
if math.random() < Config.StallChance then
SetVehicleEngineOn(vehicle, false, true, true)
Notify('Wizard Mileage', locale('warning.stalled'), 'warning')
end
else
-- You can add logic here for normal clutch operation if needed
local baseClutchForce = Config.BaseClutchForce
end
end
--[[
Calculates the remaining life percentage for each tracked vehicle component.
Updates global variables for spark plugs, oil, filter, air filter, tires, brakes, suspension, and clutch based on current mileage and wear.
Also updates the displayed mileage value for the UI.
]]--
local function GetData()
if Config.WearTracking.SparkPlugs then
sparkPlugDistanceDriven = accDistance - lastSparkPlugChange
sparkPlugLifeRemaining = math.max(0, sparkPlugchangedist - sparkPlugDistanceDriven)
sparkPlugPercentage = math.floor((sparkPlugLifeRemaining / sparkPlugchangedist) * 100)
end
if Config.WearTracking.Oil then
oilDistanceDriven = accDistance - lastOilChange
oilLifeRemaining = math.max(0, oilchangedist - oilDistanceDriven)
oilPercentage = math.floor((oilLifeRemaining / oilchangedist) * 100)
filterDistanceDriven = accDistance - lastOilFilterChange
filterLifeRemaining = math.max(0, oilfilterchangedist - filterDistanceDriven)
filterPercentage = math.floor((filterLifeRemaining / oilfilterchangedist) * 100)
end
if Config.WearTracking.AirFilter then
airFilterDistanceDriven = accDistance - lastAirFilterChange
airFilterLifeRemaining = math.max(0, airfilterchangedist - airFilterDistanceDriven)
airFilterPercentage = math.floor((airFilterLifeRemaining / airfilterchangedist) * 100)
end
if Config.WearTracking.Tires then
tireDistanceDriven = accDistance - lastTireChange
tireLifeRemaining = math.max(0, tirechangedist - tireDistanceDriven)
tirePercentage = math.floor((tireLifeRemaining / tirechangedist) * 100)
end
if Config.WearTracking.Brakes then
brakePercentage = math.floor((1 - (lastbrakeWear / Config.MaxBrakeWear)) * 100)
end
if Config.WearTracking.Suspension then
suspensionDistanceDriven = accDistance - lastSuspensionChange
suspensionLifeRemaining = math.max(0, Config.SuspensionChangeDistance * 1000 - suspensionDistanceDriven)
suspensionPercentage = math.floor((suspensionLifeRemaining / (Config.SuspensionChangeDistance * 1000)) * 100)
end
if Config.WearTracking.Clutch then
clutchPercentage = math.floor((1 - (lastClutchWear / Config.MaxClutchWear)) * 100)
end
displayedMileage = convertDistance(accDistance)
end
--[[
Cleans up the clipboard entity and animation for the player.
Deletes the clipboard object if it exists and clears the player's current tasks/animations.
@param ped (entity): The player ped to clear tasks for.
]]--
local function CleanupClipboardEntity(ped)
if clipboardEntity then
DeleteObject(clipboardEntity)
clipboardEntity = nil
end
if ped then
ClearPedTasks(ped)
end
end
--[[
Opens the service menu for the player, using the configured menu system.
- If Config.Menu is "ox", shows the ox_lib context menu.
- If Config.Menu is "qb", opens the qb-menu with all available service options.
Each menu option triggers a client event to perform the selected maintenance action.
]]--
local function openServiceMenu()
if Config.Menu == "ox" then
-- Show ox_lib context menu
lib.showContext("vehicle_service_menu")
elseif Config.Menu == "qb" then
-- Open qb-menu with all service options
exports["qb-menu"]:openMenu({
{
header = "Wizard Mileage Service Menu",
isMenuHeader = true,
},
{
header = locale("target.changeoilfilter"),
txt = "Change oil filter",
params = { event = "wizard_vehiclemileage:client:changeoilfilter" }
},
{
header = locale("target.changeairfilter"),
txt = "Change air filter",
params = { event = "wizard_vehiclemileage:client:changeairfilter" }
},
{
header = locale("target.changetires"),
txt = "Change vehicle tires",
params = { event = "wizard_vehiclemileage:client:changetires" }
},
{
header = locale("target.changebrakes"),
txt = "Service vehicle brakes",
params = { event = "wizard_vehiclemileage:client:changebrakes" }
},
{
header = locale("target.changeclutch"),
txt = "Replace vehicle clutch",
params = { event = "wizard_vehiclemileage:client:changeclutch" }
},
{
header = locale("target.changesuspension"),
txt = "Replace vehicle suspension",
params = { event = "wizard_vehiclemileage:client:changesuspension" }
},
{
header = locale("target.changesparkplug"),
txt = "Replace spark plugs",
params = { event = "wizard_vehiclemileage:client:changesparkplug" }
},
})
end
end
--[[
Opens the vehicle wear check menu for a given vehicle.
Plays clipboard animation, checks for valid vehicle and ownership, and retrieves wear data from the server.
Displays error notifications if any checks fail, and cleans up the clipboard entity/animation as needed.
On success, sends wear data to the NUI for display.
@param vehicle (entity): The vehicle entity to check wear for.
]]--
local function openCheckWearMenu(vehicle)
Notify('Wizard Mileage', locale('warning.checking_veh'), 'warning')
local coords = GetEntityCoords(playerPed)
if clipboardEntity then
CleanupClipboardEntity(playerPed)
return
end
local clipboardHash = RequestProp(Config.CheckVehicle.Object)
clipboardEntity = CreateObject(clipboardHash, coords.x, coords.y, coords.z, true, true, true)
AttachEntityToEntity(clipboardEntity, playerPed, GetPedBoneIndex(playerPed, Config.CheckVehicle.Bone), -0.1, 0.0, 0.0, 90.0, 0.0, 0.0, true, true, false, true, 1, true)
TaskPlayAnim(playerPed, Config.CheckVehicle.AnimDict, Config.CheckVehicle.Animation, 8.0, -8.0, -1, 49, 0, false, false, false)
if not DoesEntityExist(vehicle) then
Notify('Wizard Mileage', locale('error.not_found'), 'error')
-- Clear the animation and remove the clipboard
CleanupClipboardEntity(playerPed)
return
end
if isInVehicle then
Notify('Wizard Mileage', locale('error.in_vehicle'), 'error')
-- Clear the animation and remove the clipboard
CleanupClipboardEntity(playerPed)
return
end
local plate = GetVehiclePlate(vehicle)
if not plate or plate == 'UNKNOWN' then
Notify('Wizard Mileage', locale('error.plate_not_found'), 'error')
-- Clear the animation and remove the clipboard
CleanupClipboardEntity(playerPed)
return
end
if not IsVehicleOwned(plate) then
Notify('Wizard Mileage', locale('error.not_owned'), 'error')
-- Clear the animation and remove the clipboard
CleanupClipboardEntity(playerPed)
return
end
loaded = false
TriggerServerEvent('wizard_vehiclemileage:server:retrieveMileage', plate)
while not loaded do
Wait(500)
end
CWFT = true
GetData()
SendNUIMessage({
type = "closeCustomization"
})
SetNuiFocus(true, false)
local wearDataCache = {
type = "updateWear",
showUI = true,
mileage = displayedMileage,
unit = (Cfg.Unit == "imperial" and "miles" or "km"),
sparkPlugPercentage = sparkPlugPercentage,
oilPercentage = oilPercentage,
filterPercentage = filterPercentage,
airFilterPercentage = airFilterPercentage,
tirePercentage = tirePercentage,
brakePercentage = brakePercentage,
suspensionPercentage = suspensionPercentage,
clutchPercentage = clutchPercentage
}
SendNUIMessage(wearDataCache)
end
--[[
Performs a maintenance action on the nearest vehicle.
Checks job and inventory requirements, plays animation, shows a progress bar, and removes the required item.
Handles advanced actions (like opening the hood) if specified.
Returns true and the vehicle entity on success, or false and nil on failure.
@param item (string): The required inventory item for maintenance.
@param errorMSG (string): The error message key for missing item.
@param configData (table): Animation and progress bar configuration.
@param progressMSG (string): The progress bar message key.
@param isAdv (boolean): Whether to perform advanced actions (e.g., open hood).
]]--
local function DoMaintenance(item, errorMSG, configData, progressMSG, isAdv)
if Config.JobRequired then
local Job, Grade = CheckJob()
for jobName, minGrade in pairs(Config.MechanicJobs) do
if Job == jobName then
if Grade >= minGrade then
break
else
Notify('Wizard Mileage', locale("error.low_grade"), "error")
return
end
else
Notify('Wizard Mileage', locale("error.not_mechanic"), "error")
return
end
end
end
if Config.InventoryItems and not checkInventoryItem(item) then
Notify('Wizard Mileage', locale("error." .. errorMSG), "error")
return
end
local closestVehicle = GetClosestVehicle(5.0)
if closestVehicle == 0 then
Notify('Wizard Mileage', locale("error.no_vehicle_nearby"), "error")
return
end
local vehicleClass = GetVehicleClass(closestVehicle)
if Config.DisabledVehicleClasses[vehicleClass] then
return
end
if isAdv then
if not IsVehicleDoorFullyOpen(closestVehicle, 4) then
SetVehicleDoorOpen(closestVehicle, 4, false, true)
Wait(500)
end
local offset = GetOffsetFromEntityInWorldCoords(closestVehicle, 0.0, 2.0, 0.0)
TaskGoStraightToCoord(playerPed, offset.x, offset.y, offset.z, 1.0, -1, -1, 0.0)
Wait(1000)
end
PlayAnimation(playerPed, configData.AnimationDict, configData.Animation, -1 , 1)
if DisplayProgressBar(configData.Duration, locale("progress." .. progressMSG), configData) then
TriggerServerEvent('wizard-lib:server:removeItem', item, 1)
if isAdv then SetVehicleDoorShut(closestVehicle, 4, false) end
ClearPedTasks(playerPed)
return true, closestVehicle
else
if isAdv then SetVehicleDoorShut(closestVehicle, 4, false) end
return false, nil
end
end
--[[
Loads vehicle and mileage data when the player enters a vehicle.
Sets state flags, caches the starting position, resets accumulated distance,
shows the mileage UI if enabled, and requests the latest mileage data from the server.
@side-effect: Updates global state variables and UI.
]]--
local function LoadData()
isInVehicle = true
lastPos = GetEntityCoords(veh)
waitingForData = true
accDistance = 0.0
if mileageUIVisible then
SendNUIMessage({ type = "toggleMileage", visible = true })
mileageVisible = true
end
TriggerServerEvent('wizard_vehiclemileage:server:retrieveMileage', currentPlate)
end
--[[
Clears and saves all vehicle and wear data when the player exits a vehicle or disconnects.
Hides the mileage UI, sends any unsaved wear and mileage data to the server,
resets all tracking variables, and clears cached state.
@side-effect: Triggers server events to persist data and resets local state.
]]--
local function ClearData(ClearType)
if mileageVisible then
SendNUIMessage({ type = "toggleMileage", visible = false })
mileageVisible = false
end
if ClearType == "normal" then
isInVehicle = false
inAnyVeh = false
lastPos = nil
accDistance = 0.0
currentPlate = nil
waitingForData = false
lastOilChange = 0.0
lastOilFilterChange = 0.0
lastAirFilterChange = 0.0
lastTireChange = 0.0
lastbrakeChange = 0.0
lastbrakeWear = 0.0
lastClutchChange = 0.0
lastClutchWear = 0.0
lastSuspensionChange = 0.0
suspensionWear = 0.0
lastSparkPlugChange = 0.0
sparkPlugWear = 0.0
cachedClutchWear = 0.0
cachedBrakeWear = 0.0
clutchWearDirty = false
brakeWearDirty = false
loaded = false
vehOwned = false
end
if currentPlate then
local savedPlate = currentPlate
local savedMil = accDistance
local savedPlugWear = sparkPlugWear
local savedSusWear = suspensionWear
if clutchWearDirty then
TriggerServerEvent('wizard_vehiclemileage:server:updateClutchWear', currentPlate, cachedClutchWear)
clutchWearDirty = false
end
if brakeWearDirty then
TriggerServerEvent('wizard_vehiclemileage:server:updateBrakeWear', currentPlate, cachedBrakeWear)
brakeWearDirty = false
end
TriggerServerEvent('wizard_vehiclemileage:server:updateMileage', currentPlate, savedMil)
TriggerServerEvent('wizard_vehiclemileage:server:updateSparkPlugWear', currentPlate, savedPlugWear)
TriggerServerEvent('wizard_vehiclemileage:server:updateSuspensionWear', currentPlate, savedSusWear)
end
end
---------------- Threads ----------------
--[[
Main thread for mileage and wear tracking and Targeting script handler.
This thread constantly checks if the player is in a vehicle, updates mileage, wear, and UI,
and handles entering/exiting vehicles and syncing data with the server.
also this thread sets up vehicle interaction targets for supported targeting systems (ox_target, qb-target).
- Adds a "Service Vehicle" option to all vehicles for mechanics (or anyone, if job not required).
- Checks if the player is not in a vehicle and owns the vehicle before allowing interaction.
- Handles job and grade checks if required.
- Opens the service menu when the target is selected.
- Also registers the ox_lib context menu if using ox as the menu system.
]]--
lib.onCache('vehicle', function(value, oldValue)
if not value then
ClearData("normal")
else
veh = value
inAnyVeh = true
local vehicleClass = GetVehicleClass(veh)
if Config.DisabledVehicleClasses[vehicleClass] then
return
end
currentPlate = GetVehiclePlate(veh)
if IsVehicleOwned(currentPlate) then
vehOwned = true
if GetPedInVehicleSeat(veh, -1) ~= playerPed then
return
end
LoadData()
else
vehOwned = false
end
end
end)
lib.onCache('seat', function(value, oldValue)
if oldValue == -1 then
ClearData("limited")
end
if value == -1 and vehOwned then
LoadData()
end
end)
lib.onCache('ped', function(value, oldValue)
playerPed = value
end)
CreateThread(function()
local lastMileage = -1
if Config.Targeting then
local targetConfig = {
ox = function()
exports.ox_target:addGlobalVehicle({
{
name = "vehicle_service",
icon = "fas fa-wrench",
label = "Service Vehicle",
canInteract = function(entity)
if inAnyVeh then
return false
end
local plate = GetVehicleNumberPlateText(entity)
if IsVehicleOwned(plate) then
local vehicleClass = GetVehicleClass(entity)
if Config.DisabledVehicleClasses[vehicleClass] then
return false
else
return true
end
end
end,
onSelect = function(data)
if Config.JobRequired then
local Job, Grade = CheckJob()
local allowed = false
for jobName, minGrade in pairs(Config.MechanicJobs) do
if Job == jobName then
if Grade >= minGrade then
break
else
Notify('Wizard Mileage', locale("error.low_grade"), "error")
return
end
else
Notify('Wizard Mileage', locale("error.not_mechanic"), "error")
return
end
end
end
openServiceMenu()
end
},
{
name = "vehicle_check",
icon = "fas fa-info",
label = "Check Vehicle",
canInteract = function(entity)
if inAnyVeh then
return false
end
local plate = GetVehicleNumberPlateText(entity)
if IsVehicleOwned(plate) then
local vehicleClass = GetVehicleClass(entity)
if Config.DisabledVehicleClasses[vehicleClass] then
return false
else
return true
end
end
end,
onSelect = function(data)
local targetVeh = data.entity
openCheckWearMenu(targetVeh)
end
}
})
end,
qb = function()
exports["qb-target"]:AddGlobalVehicle({
options = {
{
type = "client",
icon = "fas fa-wrench",
label = "Service Vehicle",
canInteract = function(entity)
if inAnyVeh then
return false
end
local plate = GetVehicleNumberPlateText(entity)
if IsVehicleOwned(plate) then
local vehicleClass = GetVehicleClass(entity)
if Config.DisabledVehicleClasses[vehicleClass] then
return false
else
return true
end
end
end,
action = function()
if Config.JobRequired then
local Job, Grade = CheckJob()
local allowed = false
for jobName, minGrade in pairs(Config.MechanicJobs) do
if Job == jobName then
if Grade >= minGrade then
break
else
Notify('Wizard Mileage', locale("error.low_grade"), "error")
return
end
else
Notify('Wizard Mileage', locale("error.not_mechanic"), "error")
return
end
end
end
openServiceMenu()
end
},
{
type = "client",
icon = "fas fa-info",
label = "Check Vehicle",
canInteract = function(entity)
if inAnyVeh then
return false
end
local plate = GetVehicleNumberPlateText(entity)
if IsVehicleOwned(plate) then
local vehicleClass = GetVehicleClass(entity)
if Config.DisabledVehicleClasses[vehicleClass] then
return false
else
return true
end
end
end,
action = function(data)
local targetVeh = data.entity
openCheckWearMenu(targetVeh)
end
}
},
distance = 2.5
})
end
}
local targetFunc = targetConfig[Config.Targeting]
if targetFunc then
targetFunc()
end
end
if Config.Menu == "ox" then
lib.registerContext({
id = "vehicle_service_menu",
title = "Wizard Mileage Service Menu",
options = {
{
title = locale("target.changesparkplug"),
description = "Replace spark plugs",
icon = "fas fa-bolt",
onSelect = function()
TriggerEvent('wizard_vehiclemileage:client:changesparkplug')
end
},
{
title = locale("target.changeoil"),
description = "Change vehicle oil",
icon = "oil-can",
onSelect = function()
TriggerEvent('wizard_vehiclemileage:client:changeoil')
end
},
{
title = locale("target.changeoilfilter"),
description = "Change oil filter",
icon = "filter",
onSelect = function()
TriggerEvent('wizard_vehiclemileage:client:changeoilfilter')
end
},
{
title = locale("target.changeairfilter"),
description = "Change air filter",
icon = "wind",
onSelect = function()
TriggerEvent('wizard_vehiclemileage:client:changeairfilter')
end
},
{
title = locale("target.changetires"),
description = "Change vehicle tires",
icon = "fa-regular fa-circle",
onSelect = function()
TriggerEvent('wizard_vehiclemileage:client:changetires')
end
},
{
title = locale("target.changebrakes"),
description = "Service vehicle brakes",
icon = "fas fa-record-vinyl",
onSelect = function()
TriggerEvent('wizard_vehiclemileage:client:changebrakes')
end
},
{
title = locale("target.changesuspension"),
description = "Replace vehicle suspension",
icon = "fas fa-car-burst",
onSelect = function()
TriggerEvent('wizard_vehiclemileage:client:changesuspension')
end
},
{
title = locale("target.changeclutch"),
description = "Replace vehicle clutch",
icon = "fas fa-cog",
onSelect = function()
TriggerEvent('wizard_vehiclemileage:client:changeclutch')
end
}
}
})
end
while true do
if isInVehicle then
wTM = 1000
if not waitingForData then
local currentPos = GetEntityCoords(veh)
local delta = getDistance(lastPos, currentPos)
accDistance = accDistance + delta
lastPos = currentPos
local displayedMileage = convertDistance(accDistance)
if displayedMileage ~= lastMileage then
SendNUIMessage({ type = "updateMileage", mileage = displayedMileage, unit = (Cfg.Unit == "imperial" and "miles" or "km") })
lastMileage = displayedMileage
end
end
else
wTM = 3000
end
Wait(wTM)
end
end)
CreateThread(function()
while true do
if isInVehicle then
wTU = 3000
if not waitingForData then
updateSparkPlugWear(veh)
updateEngineDamage(veh)
updateAirFilterPerformance(veh)
updateSuspensionWear(veh)
updateTireWear(veh)
end
else
wTU = 5000
end
Wait(wTU)
end
end)
--[[
Clutch wear tracking thread.
This thread monitors gear changes while the player is in a vehicle and updates clutch wear accordingly.
- Only runs if clutch wear tracking is enabled in the config.
- Increases clutch wear each time the player shifts gears (with a cooldown to prevent rapid wear).
- Larger gear jumps (e.g., 1st to 3rd) cause more wear.
- If wear exceeds the maximum, it is capped.
- Marks clutch wear as "dirty" so it will be synced to the server.
- Calls updateClutchWear to apply any clutch effects (like stalling).
]]--