Repository navigation
Expand file tree
/
Copy pathRandomWorldEvents.lua
More file actions
2005 lines (1805 loc) · 91.7 KB
/
Copy pathRandomWorldEvents.lua
File metadata and controls
2005 lines (1805 loc) · 91.7 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
-- 2026-08-22 (Wizard): with MasterHUD installed this mod's own HUD hide/move keys must not
-- merely be inert, they must not REGISTER at all - that is what removes their rows from the
-- F1 legend and the Controls list. Probed on TaxMod first: skipping registration does remove
-- the row, so the pattern is used suite-wide. Only HUD hide/move actions are gated; every
-- other action this mod registers is untouched.
local function __rfMhOwnsHudKeys()
return ((g_currentMission ~= nil and g_currentMission.masterHUD) or g_masterHUD) ~= nil
end
-- =========================================================
-- Random World Events (version 2.1.3.0) - FS25 Conversion
-- =========================================================
-- Random events that can occur. Settings can be changed!
-- =========================================================
-- Author: TisonK
-- =========================================================
-- COPYRIGHT NOTICE:
-- All rights reserved. Unauthorized redistribution, copying,
-- or claiming this code as your own is strictly prohibited.
-- Original author: TisonK
-- =========================================================
-- Hot-reload latch (FuelCosts reference): g_currentModDirectory and
-- g_currentModName are nil on a live re-source, so they are latched into
-- module globals on first load, with a g_modsDirectory loose-folder fallback.
RandomWorldEventsModDirectory = RandomWorldEventsModDirectory
or g_currentModDirectory
or (g_modsDirectory ~= nil and (g_modsDirectory .. "FS25_RandomWorldEvents/") or nil)
RandomWorldEventsModName = RandomWorldEventsModName or g_currentModName or "FS25_RandomWorldEvents"
local modDirectory = RandomWorldEventsModDirectory
local modName = RandomWorldEventsModName
-- Resolve mod version once at load time so it's available everywhere.
local modVersion = "?"
do
local ok, info = pcall(function()
return g_modManager and g_modManager:getModByName(modName)
end)
if ok and info and info.version then modVersion = info.version end
end
---@class RandomWorldEvents
RandomWorldEvents = {
MOD_NAME = modName,
VERSION = modVersion,
events = {
enabled = true,
frequency = 5,
intensity = 2,
showNotifications = true,
showWarnings = true,
showHUD = true,
cooldown = 30,
-- Arcade-physics opt-in (default OFF). When ON, the retained physics
-- events (speed boost, engine trouble, equipment durability) may fire,
-- out of the economy: speed and engine on the host player's own vehicle,
-- durability on the usage wear of every vehicle in use.
arcadePhysics = false,
weatherEvents = false,
economicEvents = true,
vehicleEvents = true,
fieldEvents = true,
wildlifeEvents = true,
specialEvents = true,
debugLevel = 1
},
-- HUD scale stored at top-level (not under events/physics) for clarity
hudScale = 1.0,
debug = {
enabled = false,
debugLevel = 1,
showDebugInfo = false
},
physics = {
enabled = true,
wheelGripMultiplier = 1.0,
articulationDamping = 0.5,
comStrength = 1.0,
suspensionStiffness = 1.0,
showPhysicsInfo = false,
debugMode = false
},
modDirectory = modDirectory,
isInitialized = false,
needsSave = false,
saveTime = nil,
-- HUD instance (created in loadGUI)
eventHUD = nil,
-- Per-tick handler table populated by event modules.
-- Each entry: [name] = function(rweInstance) ... end
-- Called from applyActiveEventEffects() while an event is active.
tickHandlers = {}
}
RandomWorldEvents.EVENT_STATE = {
activeEvent = nil,
activeIntensity = nil, -- intensity (1-5) the active event was triggered at (companion read API)
activeCategory = nil, -- category of the active event (companion read API)
eventStartTime = 0,
eventDuration = 0,
eventData = {},
history = {},
cooldownUntil = 0,
-- Immersion: midpoint callback tracking
midpointFired = false,
-- Immersion: ambient message cycling
-- nextAmbientTime = absolute game-time (ms) when next ambient msg fires
nextAmbientTime = 0,
ambientMsgIndex = 1,
}
RandomWorldEvents.EVENTS = {}
RandomWorldEvents.eventCounter = 0
-- Subsystem API registry — populated by each RWE[Category]API on load.
-- Access via g_RandomWorldEvents:getSubsystem("economic") etc.
RandomWorldEvents.subsystems = {}
-- RSF-F201 item 12: the input-hook record home. The settings literal above is a
-- bare table on purpose (its constructor re-establishes the defaults on every
-- load), so it cannot hold a session-lived record. This latched table survives a
-- script reload the way the mod's other `X = X or {}` modules do, and holds only
-- the input-hook record: captured predecessors, install latch, owner binding.
-- No other participant reads or writes it.
RWE_InputHookRecord = RWE_InputHookRecord or {}
local RandomWorldEvents_mt = Class(RandomWorldEvents)
-- =====================
-- CORE FUNCTIONS
-- =====================
function RandomWorldEvents:new(mission)
local self = setmetatable({}, RandomWorldEvents_mt)
self.mission = mission
-- Per-instance subsystem registry (isolates across mission reloads).
-- Class-level RandomWorldEvents.subsystems is the default; this shadows it.
self.subsystems = {}
self.settingsManager = self:createSettingsManager()
self:loadSettings()
self:registerConsoleCommands()
Logging.info("[RandomWorldEvents] Core initialized successfully")
return self
end
function RandomWorldEvents:createSettingsManager()
local manager = {
MOD_NAME = self.MOD_NAME,
XMLTAG = "RandomWorldEvents",
defaultConfig = {
events = {
enabled = true,
frequency = 5,
intensity = 2,
showNotifications = true,
showWarnings = true,
showHUD = true,
cooldown = 30,
arcadePhysics = false,
weatherEvents = false,
economicEvents = true,
vehicleEvents = true,
fieldEvents = true,
wildlifeEvents = true,
specialEvents = true,
debugLevel = 1
},
hudScale = 1.0,
debug = {
enabled = false,
debugLevel = 1,
showDebugInfo = false
},
physics = {
enabled = true,
wheelGripMultiplier = 1.0,
articulationDamping = 0.5,
comStrength = 1.0,
suspensionStiffness = 1.0,
showPhysicsInfo = false,
debugMode = false
},
-- Release-gate opt-in (default false), orthogonal to difficulty. See ReleaseGate.lua.
experimentalSystems = false
}
}
-- Define methods after creating the table
manager.getSavegameXmlFilePath = function()
if g_currentMission and g_currentMission.missionInfo and g_currentMission.missionInfo.savegameDirectory then
return ("%s/%s.xml"):format(g_currentMission.missionInfo.savegameDirectory, manager.MOD_NAME)
end
return nil
end
manager.loadSettings = function(settingsObject)
local xmlPath = manager.getSavegameXmlFilePath()
if xmlPath and fileExists(xmlPath) then
local xml = XMLFile.load("rwe_Config", xmlPath)
if xml then
settingsObject.events.enabled = xml:getBool(manager.XMLTAG..".events.enabled", manager.defaultConfig.events.enabled)
settingsObject.events.frequency = xml:getInt(manager.XMLTAG..".events.frequency", manager.defaultConfig.events.frequency)
settingsObject.events.intensity = xml:getInt(manager.XMLTAG..".events.intensity", manager.defaultConfig.events.intensity)
settingsObject.events.showNotifications = xml:getBool(manager.XMLTAG..".events.showNotifications", manager.defaultConfig.events.showNotifications)
settingsObject.events.showWarnings = xml:getBool(manager.XMLTAG..".events.showWarnings", manager.defaultConfig.events.showWarnings)
settingsObject.events.showHUD = xml:getBool(manager.XMLTAG..".events.showHUD", manager.defaultConfig.events.showHUD)
settingsObject.events.cooldown = xml:getInt(manager.XMLTAG..".events.cooldown", manager.defaultConfig.events.cooldown)
settingsObject.events.arcadePhysics = xml:getBool(manager.XMLTAG..".events.arcadePhysics", manager.defaultConfig.events.arcadePhysics)
settingsObject.hudScale = xml:getFloat(manager.XMLTAG..".hudScale", manager.defaultConfig.hudScale)
settingsObject.events.weatherEvents = xml:getBool(manager.XMLTAG..".events.weatherEvents", manager.defaultConfig.events.weatherEvents)
settingsObject.events.economicEvents = xml:getBool(manager.XMLTAG..".events.economicEvents", manager.defaultConfig.events.economicEvents)
settingsObject.events.vehicleEvents = xml:getBool(manager.XMLTAG..".events.vehicleEvents", manager.defaultConfig.events.vehicleEvents)
settingsObject.events.fieldEvents = xml:getBool(manager.XMLTAG..".events.fieldEvents", manager.defaultConfig.events.fieldEvents)
settingsObject.events.wildlifeEvents = xml:getBool(manager.XMLTAG..".events.wildlifeEvents", manager.defaultConfig.events.wildlifeEvents)
settingsObject.events.specialEvents = xml:getBool(manager.XMLTAG..".events.specialEvents", manager.defaultConfig.events.specialEvents)
settingsObject.events.debugLevel = xml:getInt(manager.XMLTAG..".events.debugLevel", manager.defaultConfig.events.debugLevel)
settingsObject.debug.enabled = xml:getBool(manager.XMLTAG..".debug.enabled", manager.defaultConfig.debug.enabled)
settingsObject.debug.debugLevel = xml:getInt(manager.XMLTAG..".debug.debugLevel", manager.defaultConfig.debug.debugLevel)
settingsObject.debug.showDebugInfo = xml:getBool(manager.XMLTAG..".debug.showDebugInfo", manager.defaultConfig.debug.showDebugInfo)
settingsObject.physics.enabled = xml:getBool(manager.XMLTAG..".physics.enabled", manager.defaultConfig.physics.enabled)
settingsObject.physics.wheelGripMultiplier = xml:getFloat(manager.XMLTAG..".physics.wheelGripMultiplier", manager.defaultConfig.physics.wheelGripMultiplier)
settingsObject.physics.articulationDamping = xml:getFloat(manager.XMLTAG..".physics.articulationDamping", manager.defaultConfig.physics.articulationDamping)
settingsObject.physics.comStrength = xml:getFloat(manager.XMLTAG..".physics.comStrength", manager.defaultConfig.physics.comStrength)
settingsObject.physics.suspensionStiffness = xml:getFloat(manager.XMLTAG..".physics.suspensionStiffness", manager.defaultConfig.physics.suspensionStiffness)
settingsObject.physics.showPhysicsInfo = xml:getBool(manager.XMLTAG..".physics.showPhysicsInfo", manager.defaultConfig.physics.showPhysicsInfo)
settingsObject.physics.debugMode = xml:getBool(manager.XMLTAG..".physics.debugMode", manager.defaultConfig.physics.debugMode)
settingsObject.experimentalSystems = xml:getBool(manager.XMLTAG..".experimentalSystems", manager.defaultConfig.experimentalSystems)
-- Load saved event state (temp fields; applied in loadFinished when g_currentMission.time is valid)
local savedEvent = xml:getString(manager.XMLTAG..".eventState.activeEvent", "")
settingsObject._savedActiveEvent = savedEvent ~= "" and savedEvent or nil
settingsObject._savedActiveIntensity = xml:getInt(manager.XMLTAG..".eventState.intensity", 0)
settingsObject._savedRemainingMs = xml:getFloat(manager.XMLTAG..".eventState.remainingMs", 0)
settingsObject._savedCooldownRemainingMs = xml:getFloat(manager.XMLTAG..".eventState.cooldownRemainingMs", 0)
settingsObject._savedMidpointFired = xml:getBool(manager.XMLTAG..".eventState.midpointFired", false)
-- EC-6: the event summary, the crisis parts and the pending settlement lines.
local summaryKey = xml:getString(manager.XMLTAG..".eventState#summaryKey", "")
settingsObject._savedSummaryKey = summaryKey ~= "" and summaryKey or nil
local summaryArgs = {}
local i = 0
while true do
local arg = xml:getString(string.format("%s.eventState.summaryArg(%d)#value", manager.XMLTAG, i))
if arg == nil then break end
summaryArgs[#summaryArgs + 1] = arg
i = i + 1
end
settingsObject._savedSummaryArgs = summaryArgs
settingsObject._savedCrisisHasPrice = xml:getBool(manager.XMLTAG..".eventState#crisisHasPrice", false)
settingsObject._savedCrisisHasLoan = xml:getBool(manager.XMLTAG..".eventState#crisisHasLoan", false)
settingsObject._savedSettlement = RWESettlement ~= nil and RWESettlement.loadFromXML(xml, manager.XMLTAG..".eventState") or {}
-- The savegame-coupled state as it stands on disk: re-written unchanged
-- by every save that is not a real game save (see saveSettings).
settingsObject._savedStateSnapshot = {
activeEvent = settingsObject._savedActiveEvent,
intensity = settingsObject._savedActiveIntensity,
remainingMs = settingsObject._savedRemainingMs,
cooldownRemainingMs = settingsObject._savedCooldownRemainingMs,
midpointFired = settingsObject._savedMidpointFired,
summaryKey = settingsObject._savedSummaryKey,
summaryArgs = summaryArgs,
crisisHasPrice = settingsObject._savedCrisisHasPrice,
crisisHasLoan = settingsObject._savedCrisisHasLoan,
settlement = RWESettlement ~= nil and RWESettlement.validateSaved(settingsObject._savedSettlement) or {},
}
xml:delete()
return
end
end
-- Use deep copy to avoid reference issues
settingsObject.events = {}
settingsObject.debug = {}
settingsObject.physics = {}
settingsObject.hudScale = manager.defaultConfig.hudScale
settingsObject.experimentalSystems = manager.defaultConfig.experimentalSystems
for k, v in pairs(manager.defaultConfig.events) do
settingsObject.events[k] = v
end
for k, v in pairs(manager.defaultConfig.debug) do
settingsObject.debug[k] = v
end
for k, v in pairs(manager.defaultConfig.physics) do
settingsObject.physics[k] = v
end
end
manager.saveSettings = function(settingsObject, opts)
local xmlPath = manager.getSavegameXmlFilePath()
if not xmlPath then
Logging.warning("[RWE] No savegame path found")
return
end
local xml = XMLFile.create("rwe_Config", xmlPath, manager.XMLTAG)
if xml then
-- Save events settings
xml:setBool(manager.XMLTAG..".events.enabled", settingsObject.events.enabled)
xml:setInt(manager.XMLTAG..".events.frequency", settingsObject.events.frequency)
xml:setInt(manager.XMLTAG..".events.intensity", settingsObject.events.intensity)
xml:setBool(manager.XMLTAG..".events.showNotifications", settingsObject.events.showNotifications)
xml:setBool(manager.XMLTAG..".events.showWarnings", settingsObject.events.showWarnings)
xml:setBool(manager.XMLTAG..".events.showHUD", settingsObject.events.showHUD)
xml:setInt(manager.XMLTAG..".events.cooldown", settingsObject.events.cooldown)
xml:setBool(manager.XMLTAG..".events.arcadePhysics", settingsObject.events.arcadePhysics == true)
xml:setFloat(manager.XMLTAG..".hudScale", settingsObject.hudScale or 1.0)
xml:setBool(manager.XMLTAG..".events.weatherEvents", settingsObject.events.weatherEvents)
xml:setBool(manager.XMLTAG..".events.economicEvents", settingsObject.events.economicEvents)
xml:setBool(manager.XMLTAG..".events.vehicleEvents", settingsObject.events.vehicleEvents)
xml:setBool(manager.XMLTAG..".events.fieldEvents", settingsObject.events.fieldEvents)
xml:setBool(manager.XMLTAG..".events.wildlifeEvents", settingsObject.events.wildlifeEvents)
xml:setBool(manager.XMLTAG..".events.specialEvents", settingsObject.events.specialEvents)
xml:setInt(manager.XMLTAG..".events.debugLevel", settingsObject.events.debugLevel)
-- Save debug settings
xml:setBool(manager.XMLTAG..".debug.enabled", settingsObject.debug.enabled)
xml:setInt(manager.XMLTAG..".debug.debugLevel", settingsObject.debug.debugLevel)
xml:setBool(manager.XMLTAG..".debug.showDebugInfo", settingsObject.debug.showDebugInfo)
-- Save physics settings
xml:setBool(manager.XMLTAG..".physics.enabled", settingsObject.physics.enabled)
xml:setFloat(manager.XMLTAG..".physics.wheelGripMultiplier", settingsObject.physics.wheelGripMultiplier)
xml:setFloat(manager.XMLTAG..".physics.articulationDamping", settingsObject.physics.articulationDamping)
xml:setFloat(manager.XMLTAG..".physics.comStrength", settingsObject.physics.comStrength)
xml:setFloat(manager.XMLTAG..".physics.suspensionStiffness", settingsObject.physics.suspensionStiffness)
xml:setBool(manager.XMLTAG..".physics.showPhysicsInfo", settingsObject.physics.showPhysicsInfo)
xml:setBool(manager.XMLTAG..".physics.debugMode", settingsObject.physics.debugMode)
xml:setBool(manager.XMLTAG..".experimentalSystems", settingsObject.experimentalSystems == true)
-- EC-6: the event snapshot and the pending settlement lines are savegame-coupled
-- state. Only a real game save (opts.savegame) writes the current state; every
-- other write (a settings change, quitting) re-writes the snapshot of the last
-- real save, or of load. Otherwise quitting without saving would persist lines
-- the savegame never had (paid again on the next load) or drop lines it still
-- owes.
local snap
if opts ~= nil and opts.savegame then
snap = settingsObject:currentStateSnapshot()
settingsObject._savedStateSnapshot = snap
else
snap = settingsObject._savedStateSnapshot or {}
end
-- Save active event state as remaining time so timers survive reload
if snap.activeEvent ~= nil then
xml:setString(manager.XMLTAG..".eventState.activeEvent", snap.activeEvent)
xml:setFloat(manager.XMLTAG..".eventState.remainingMs", snap.remainingMs or 0)
xml:setBool(manager.XMLTAG..".eventState.midpointFired", snap.midpointFired == true)
xml:setInt(manager.XMLTAG..".eventState.intensity", snap.intensity or 0)
xml:setString(manager.XMLTAG..".eventState#summaryKey", snap.summaryKey or "")
for i, arg in ipairs(snap.summaryArgs or {}) do
xml:setString(string.format("%s.eventState.summaryArg(%d)#value", manager.XMLTAG, i - 1), tostring(arg))
end
xml:setBool(manager.XMLTAG..".eventState#crisisHasPrice", snap.crisisHasPrice == true)
xml:setBool(manager.XMLTAG..".eventState#crisisHasLoan", snap.crisisHasLoan == true)
else
xml:setString(manager.XMLTAG..".eventState.activeEvent", "")
end
xml:setFloat(manager.XMLTAG..".eventState.cooldownRemainingMs", snap.cooldownRemainingMs or 0)
if RWESettlement ~= nil then
RWESettlement.saveListToXML(xml, manager.XMLTAG..".eventState", snap.settlement or {})
end
xml:save()
xml:delete()
self:dbg("Settings saved successfully")
else
Logging.error("[RWE] Failed to create XML file for settings")
end
end
return manager
end
function RandomWorldEvents:loadSettings()
if self.settingsManager and self.settingsManager.loadSettings then
self.settingsManager.loadSettings(self)
self:dbg("Settings loaded")
else
Logging.error("[RandomWorldEvents] Settings manager not properly initialized")
end
end
--- @param opts table|nil { savegame = true } only from the game's save cycle
function RandomWorldEvents:saveSettings(opts)
if self.settingsManager and self.settingsManager.saveSettings then
self.settingsManager.saveSettings(self, opts)
self:dbg("Settings saved")
else
Logging.error("[RandomWorldEvents] Settings manager not properly initialized")
end
end
function RandomWorldEvents:registerConsoleCommands()
addConsoleCommand("rwe", "Random World Events commands", "consoleCommandHelp", self)
addConsoleCommand("rweStatus", "Show RWE status", "consoleCommandStatus", self)
addConsoleCommand("rweTest", "Test random event", "consoleCommandTest", self)
addConsoleCommand("rweEnd", "End current event", "consoleCommandEnd", self)
addConsoleCommand("rweDebug", "Toggle debug mode", "consoleCommandDebug", self)
addConsoleCommand("rweList", "List available events", "consoleCommandList", self)
addConsoleCommand("rweSettings", "Open settings screen", "consoleCommandSettings", self)
addConsoleCommand("rweRelease", "Release gate: show STABLE vs experimental-LOCKED systems", "consoleCommandRelease", self)
self:dbg("Console commands registered")
end
--- Release-gate opt-in. True when the player has explicitly enabled experimental
--- (LOCKED) systems. Orthogonal to difficulty: the two locks stack, see ReleaseGate.lua.
---@return boolean
function RandomWorldEvents:allowsExperimentalSystems()
return self.experimentalSystems == true
end
--- Arcade-physics opt-in (redesign): the retained vehicle-physics events
--- (speed boost, engine trouble, equipment durability) only fire when this is
--- ON. Default OFF. Speed boost and engine trouble act on the host player's own
--- vehicle; the equipment durability pair scales usage wear on every vehicle in
--- use, decided on the server (Design d3c0626). Never the economy. Admin key
--- RandomWorldEvents.arcadePhysics.
---@return boolean
function RandomWorldEvents:allowsArcadePhysics()
return self.events.arcadePhysics == true
end
-- =====================
-- DIFFICULTY (Option-Scaling Spine)
-- Difficulty rides the spine: the World-events dial scales event frequency
-- and base intensity; the Economy dial scales economic magnitude. When the
-- spine (or its profile) is absent every read is neutral, meaning RWE falls
-- back to its own configured frequency/intensity untouched.
-- =====================
--- Read the Option-Scaling Spine profile (if present) and resolve the two dials
--- RWE rides on. Neutral (nil) when the spine is absent or its profile is not
--- registered. Each factor is a multiplier around 1.0 (0.4 relaxed .. 1.7
--- punishing on the canonical World-events curve).
---@return table|nil { worldEvents = number, economy = number }
function RandomWorldEvents:getDifficulty()
if OptionScalingResolver == nil or OptionScalingResolver.readProfile == nil then
return nil
end
local hub = (g_currentMission ~= nil and g_currentMission.settingsHub) or g_settingsHub
local profile = OptionScalingResolver.readProfile(hub)
if profile == nil then return nil end
return {
worldEvents = OptionScalingResolver.resolve({ dial = "worldEvents", base = 1.0, neutral = 1.0 }, profile),
economy = OptionScalingResolver.resolve({ dial = "economy", base = 1.0, neutral = 1.0 }, profile),
}
end
--- Difficulty factor for one dial (1.0 = neutral, spine absent or dial off).
---@param dial string "worldEvents" or "economy"
---@return number
function RandomWorldEvents:getDifficultyFactor(dial)
local d = self:getDifficulty()
if d == nil or d[dial] == nil then return 1.0 end
return d[dial]
end
--- Spine-scaled event frequency (1-10). Neutral when the spine is absent.
---@return number
function RandomWorldEvents:getEffectiveFrequency()
local f = tonumber(self.events.frequency) or 5
local scaled = f * self:getDifficultyFactor("worldEvents")
return math.max(1, math.min(10, math.floor(scaled)))
end
--- Spine-scaled base intensity (1-5) used to trigger and scale events.
--- Neutral when the spine is absent.
---@return number
function RandomWorldEvents:getBaseIntensity()
local i = tonumber(self.events.intensity) or 2
local scaled = i * self:getDifficultyFactor("worldEvents")
return math.max(1, math.min(5, math.floor(scaled)))
end
function RandomWorldEvents:consoleCommandRelease()
if not ReleaseGate then return "Release gate not loaded" end
return ReleaseGate.status(self.experimentalSystems == true)
end
-- =====================
-- EVENT SYSTEM
-- =====================
function RandomWorldEvents:getFarmId()
return g_currentMission and g_currentMission.player and g_currentMission.player.farmId or 0
end
function RandomWorldEvents:getVehicle()
return g_currentMission and g_currentMission.controlledVehicle or nil
end
-- =====================
-- COMPANION READ API
-- Read-only surface for companion mods (e.g. DairyCore) reached via
-- g_currentMission.randomWorldEvents. RWE runs at most one event at a time and
-- is server-authoritative; these read the server-side event state.
-- =====================
--- The currently active world event, or nil when none is active.
--- @return table|nil A fresh copy: { name, intensity (1-5), category, remainingMs }.
function RandomWorldEvents:getActiveEvent()
local es = self.EVENT_STATE
if es == nil or es.activeEvent == nil then return nil end
local now = g_currentMission and g_currentMission.time or 0
return {
name = es.activeEvent,
intensity = es.activeIntensity or self.events.intensity or 1,
category = es.activeCategory,
remainingMs = math.max(0, (es.eventStartTime + (es.eventDuration or 0)) - now),
}
end
--- Intensity (1-5) of the currently active event, or 0 when none is active.
--- Falls back to the configured global intensity if an event is active but its
--- stored intensity is missing (e.g. a pre-upgrade save).
function RandomWorldEvents:getEventIntensity()
local es = self.EVENT_STATE
if es == nil or es.activeEvent == nil then return 0 end
return es.activeIntensity or self.events.intensity or 1
end
--- True while a world event is active.
---@return boolean
function RandomWorldEvents:isEventActive()
local es = self.EVENT_STATE
return es ~= nil and es.activeEvent ~= nil
end
--- Progress through the active event (0.0 -> 1.0), or 0 when none is active.
---@return number
function RandomWorldEvents:getProgress()
if not self:isEventActive() then return 0 end
local s = self.EVENT_STATE
if s.eventDuration == nil or s.eventDuration <= 0 then return 1 end
local elapsed = (g_currentMission and g_currentMission.time or 0) - (s.eventStartTime or 0)
return math.max(0, math.min(1, elapsed / s.eventDuration))
end
--- Seconds remaining in the active event, or 0 when none is active.
---@return number
function RandomWorldEvents:getRemainingTime()
if not self:isEventActive() then return 0 end
local s = self.EVENT_STATE
if s.eventDuration == nil then return 0 end
local now = g_currentMission and g_currentMission.time or 0
local remainingMs = math.max(0, (s.eventStartTime or 0) + s.eventDuration - now)
return math.floor(remainingMs / 1000)
end
--- Intensity (1-5) of the currently active event, or nil when none is active.
--- Neutral is nil (nothing active), matching the redesign read contract; use
--- getEventIntensity() if a numeric 0-when-inactive is preferred.
---@return number|nil
function RandomWorldEvents:getIntensity()
local es = self.EVENT_STATE
if es == nil or es.activeEvent == nil then return nil end
return es.activeIntensity or self.events.intensity or 1
end
function RandomWorldEvents:registerEvent(eventData)
self.eventCounter = self.eventCounter + 1
self.EVENTS[eventData.name] = eventData
self:dbg("Registered event: " .. eventData.name)
return eventData.name
end
-- Register a per-tick handler called while any event is active.
-- name : string key (used for deduplication/replacement)
-- handler: function(rweInstance) called each frame during an active event
function RandomWorldEvents:registerTickHandler(name, handler)
self.tickHandlers[name] = handler
self:dbg("Registered tick handler: " .. name)
end
-- Register a subsystem API table under a category name.
-- Called automatically by each api/[Category]API.lua on load.
-- name : category string key (e.g. "economic", "field")
-- apiTable : the RWE[Category]API global table
function RandomWorldEvents:registerSubsystem(name, apiTable)
self.subsystems[name] = apiTable
self:dbg("Subsystem registered: " .. tostring(name))
end
-- Return the registered subsystem API for the given category, or nil.
-- Usage: local econ = g_RandomWorldEvents:getSubsystem("economic")
---@param name string
---@return table|nil
function RandomWorldEvents:getSubsystem(name)
return self.subsystems[name]
end
-- Debug log helper — only prints when debug.enabled is true.
-- level 1 = verbose (default), level 2 = detailed, level 3 = trace
function RandomWorldEvents:dbg(msg, level)
if self.debug and self.debug.enabled then
if (self.debug.debugLevel or 1) >= (level or 1) then
Logging.info("[RWE-DBG] " .. tostring(msg))
end
end
end
-- =====================
-- EC-6: ELIGIBILITY, NOTICES, SHARED STATE, END PATH
-- =====================
--- True for the four arcade-physics events (stored gate). Their broadcast and
--- save-resume stay host-local, and so do the NOTICES of the two host-local ones,
--- speed boost and engine trouble. The durability pair is the exception on two
--- counts: its wear effect is server-decided, and since Design 2c032b5 its notice
--- DOES reach joined players. The announce sites gate on isArcadeEvent AND NOT
--- isServerScopedArcadeEvent via noticeIsHostLocal, branching on arcadeScope
--- rather than on this function, which cannot tell the pair apart.
function RandomWorldEvents:isArcadeEvent(event)
return type(event) == "table" and event.gate == "arcadePhysics"
end
--- The host player's current vehicle, or nil.
function RandomWorldEvents:getLocalVehicle()
local player = g_localPlayer
local cur = (player ~= nil and type(player.getCurrentVehicle) == "function") and player:getCurrentVehicle() or nil
return cur or (g_currentMission ~= nil and g_currentMission.controlledVehicle) or nil
end
--- Speed boost and engine trouble are host-local: the toggle is on, this machine is
--- a listen server with a local player, and that player is in a vehicle. A
--- dedicated server (no local player) and a pure client never start one.
function RandomWorldEvents:arcadeEligible()
return self:allowsArcadePhysics() and g_server ~= nil and g_localPlayer ~= nil and self:getLocalVehicle() ~= nil
end
--- The equipment durability pair (arcadeScope "server") scales usage wear on every
--- vehicle in use, which the server decides (Design d3c0626), so it needs only the
--- toggle and a server: a dedicated server with no local player starts one too.
function RandomWorldEvents:durabilityEligible()
return self:allowsArcadePhysics() and g_server ~= nil
end
--- True for an arcade event whose effect the server decides for every vehicle.
function RandomWorldEvents:isServerScopedArcadeEvent(event)
return self:isArcadeEvent(event) and event.arcadeScope == "server"
end
--- True when this event's notice must NOT leave the host.
---
--- This is the composition of the two predicates above, given a name so the four
--- announce sites share ONE tested expression instead of four transcriptions of it.
--- It introduces no new notion: arcadeScope is still the field, isServerScoped-
--- ArcadeEvent is still the test, and eventEligibility forks on the same split.
---
--- THE DISCRIMINATOR IS arcadeScope, NOT isArcadeEvent. All four arcade events
--- answer true to isArcadeEvent, including the durability pair whose notice MUST
--- reach clients (Design 2c032b5, "wear included"). Writing this as isArcadeEvent
--- alone would silence wear, which is the one way this gate can be wrong.
---
--- Only the host-local pair is held back. Speed boost and engine trouble need a
--- local player in a vehicle (arcadeEligible), so they fire only on a listen host
--- and affect only that machine. Design's ruling targets the unexplained-penalty
--- class, an effect a player feels with no notice explaining it; a joined player
--- feels nothing from these two, so a notice would describe an event that is not
--- happening to them rather than explain one that is.
function RandomWorldEvents:noticeIsHostLocal(event)
return self:isArcadeEvent(event) and not self:isServerScopedArcadeEvent(event)
end
--- The same eligibility for the scheduler and for every forced trigger: the stored
--- gate and the event's own canTrigger (price status, the old-market exclusion,
--- eligible farms, map conditions). Returns ok, reason.
function RandomWorldEvents:eventEligibility(event)
if type(event) ~= "table" then return false, "unknown event" end
if self:isServerScopedArcadeEvent(event) then
if not self:durabilityEligible() then
return false, "equipment durability events need Arcade Physics on, on the server"
end
elseif self:isArcadeEvent(event) and not self:arcadeEligible() then
return false, "arcade physics events need Arcade Physics on and the host player in a vehicle on a listen server"
end
local ok, can = pcall(event.canTrigger)
if ok and can then return true end
if RWEMarketBridge ~= nil then
local status = RWEMarketBridge.priceStatus()
if RWEMarketBridge.isOldMarketExcluded(event.name) then
return false, "update MarketDynamics to enable this event (status " .. tostring(status) .. ")"
end
if RWEMarketBridge.isPriceEvent(event.name) and status ~= RWEMarketBridge.STATUS_AVAILABLE then
return false, "market price events are unavailable (status " .. tostring(status) .. ")"
end
end
return false, ok and "no eligible farm or map condition for this event" or ("canTrigger error: " .. tostring(can))
end
--- Resolve a notice to display text. A notice is { key = "...", args = { ... } } with
--- string arguments (each resolved as a translation key when one exists), or a
--- plain string (a translation key when one exists, else literal text from a
--- third-party event). A missing key falls back to the key itself and logs once.
function RandomWorldEvents:noticeText(notice)
if notice == nil then return nil end
local function t(key)
if type(key) == "string" and g_i18n ~= nil and type(g_i18n.hasText) == "function" and g_i18n:hasText(key) then
return g_i18n:getText(key)
end
return nil
end
if type(notice) == "string" then return t(notice) or notice end
if type(notice) ~= "table" or type(notice.key) ~= "string" or notice.key == "" then return nil end
local template = t(notice.key)
if template == nil then
self._missingKeys = self._missingKeys or {}
if not self._missingKeys[notice.key] then
self._missingKeys[notice.key] = true
Logging.warning("[RWE] missing translation key '%s'", notice.key)
end
return notice.key
end
local args = {}
for i, a in ipairs(notice.args or {}) do args[i] = t(a) or tostring(a) end
if #args == 0 then return template end
local ok, text = pcall(string.format, template, unpack(args))
if ok then return text end
return template
end
--- The translated title of an event: rwe_event_<name>_title, or the raw id (logged once).
function RandomWorldEvents:eventTitle(name)
if name == nil then return "" end
local key = "rwe_event_" .. tostring(name) .. "_title"
if g_i18n ~= nil and type(g_i18n.hasText) == "function" and g_i18n:hasText(key) then
return g_i18n:getText(key)
end
self._missingKeys = self._missingKeys or {}
if not self._missingKeys[key] then
self._missingKeys[key] = true
Logging.warning("[RWE] missing translation key '%s'", key)
end
return tostring(name)
end
local function stringArgs(args)
local out = {}
for _, a in ipairs(type(args) == "table" and args or {}) do
if type(a) == "string" then out[#out + 1] = a end
end
return out
end
--- Choose the active shared event's figure-free summary into eventData. Arcade
--- events get none. The crisis chooses its row from the recorded parts.
function RandomWorldEvents:chooseSummary(event)
local d = self.EVENT_STATE.eventData
if type(d) ~= "table" then d = {}; self.EVENT_STATE.eventData = d end
d.summaryKey, d.summaryArgs = nil, {}
if type(event) ~= "table" or self:isArcadeEvent(event) then return end
if type(event.chooseSummary) == "function" then
local ok, key, args = pcall(event.chooseSummary, d)
if ok and type(key) == "string" then d.summaryKey, d.summaryArgs = key, stringArgs(args) end
elseif type(event.summaryKey) == "string" then
d.summaryKey = event.summaryKey
end
end
--- The shared state every client sees. The only numbers are intensity and
--- remainingMs. While an arcade event holds the slot, the event is empty.
function RandomWorldEvents:sharedState()
local es = self.EVENT_STATE
local p = {
activeEvent = "", activeIntensity = 0, activeCategory = "", remainingMs = 0, midpointFired = false,
priceStatus = RWEMarketBridge ~= nil and RWEMarketBridge.priceStatus() or "",
summaryKey = "", summaryArgs = {}, crisisHasPrice = false, crisisHasLoan = false,
noticeKind = "", noticeKey = "", noticeArgs = {},
}
local event = es.activeEvent ~= nil and self.EVENTS[es.activeEvent] or nil
if es.activeEvent ~= nil and not self:isArcadeEvent(event) then
local now = g_currentMission ~= nil and g_currentMission.time or 0
local d = type(es.eventData) == "table" and es.eventData or {}
p.activeEvent = es.activeEvent
p.activeIntensity = es.activeIntensity or 0
p.activeCategory = es.activeCategory or ""
p.remainingMs = math.max(0, (es.eventStartTime or 0) + (es.eventDuration or 0) - now)
p.midpointFired = es.midpointFired == true
p.summaryKey = d.summaryKey or ""
p.summaryArgs = stringArgs(d.summaryArgs)
if es.activeEvent == "economic_crisis" then
p.crisisHasPrice = d.crisisHasPrice == true
p.crisisHasLoan = d.crisisHasLoan == true
end
end
return p
end
--- Attach a notice to a shared state payload (only a keyed notice travels).
local function withNotice(p, kind, notice)
if type(notice) == "table" and type(notice.key) == "string" and notice.key ~= "" then
p.noticeKind, p.noticeKey, p.noticeArgs = kind, notice.key, stringArgs(notice.args)
elseif type(notice) == "string" and g_i18n ~= nil and type(g_i18n.hasText) == "function" and g_i18n:hasText(notice) then
p.noticeKind, p.noticeKey, p.noticeArgs = kind, notice, {}
end
return p
end
RandomWorldEvents._withNotice = withNotice
--- Broadcast the shared state to every client. Server only.
function RandomWorldEvents:broadcastState(p)
if g_server == nil or RWEEventStateEvent == nil then return false end
local ok = pcall(RWEEventStateEvent.broadcast, p or self:sharedState())
return ok
end
--- Client: apply the synced display copy. Never runs onEnd, onMid, tick handlers,
--- settlement or the price modifier.
function RandomWorldEvents:applySyncedState(p)
if g_server ~= nil or type(p) ~= "table" then return end
local es = self.EVENT_STATE
if RWEMarketBridge ~= nil then
RWEMarketBridge.clientPriceStatus = (p.priceStatus ~= nil and p.priceStatus ~= "") and p.priceStatus or nil
end
if p.activeEvent == nil or p.activeEvent == "" then
es.activeEvent, es.activeIntensity, es.activeCategory = nil, nil, nil
es.eventData = {}
es.midpointFired = false
else
es.activeEvent = p.activeEvent
es.activeIntensity = (tonumber(p.activeIntensity) or 0) > 0 and p.activeIntensity or nil
es.activeCategory = (p.activeCategory ~= nil and p.activeCategory ~= "") and p.activeCategory or nil
es.eventStartTime = g_currentMission ~= nil and g_currentMission.time or 0
es.eventDuration = tonumber(p.remainingMs) or 0
es.midpointFired = p.midpointFired == true
es.eventData = {
summaryKey = (p.summaryKey ~= nil and p.summaryKey ~= "") and p.summaryKey or nil,
summaryArgs = stringArgs(p.summaryArgs),
crisisHasPrice = p.crisisHasPrice == true,
crisisHasLoan = p.crisisHasLoan == true,
}
end
if p.noticeKey ~= nil and p.noticeKey ~= "" then
local positive = nil
if p.noticeKind == "start" then positive = true elseif p.noticeKind == "mid" then positive = "warn" end
local category = (p.activeCategory ~= nil and p.activeCategory ~= "") and p.activeCategory or nil
self:notifyEvent(self:noticeText({ key = p.noticeKey, args = p.noticeArgs }), category, positive)
end
end
--- The one server end path for every reason (timer, console, arcade toggle off,
--- price status). Clients never run it.
function RandomWorldEvents:_endActiveEvent(reason)
if g_server == nil then return false end
local es = self.EVENT_STATE
local name = es.activeEvent
if name == nil then return false end
local event = self.EVENTS[name]
local arcade = self:isArcadeEvent(event)
local notice = nil
if event ~= nil and type(event.onEnd) == "function" then
local ok, result = pcall(event.onEnd)
if ok then
notice = result
else
Logging.warning("[RWE] onEnd failed for %s: %s", tostring(name), tostring(result))
end
end
local category = es.activeCategory
Logging.info("[RWE] Event ended: %s (%s)", tostring(name), tostring(reason))
es.activeEvent = nil
es.activeIntensity = nil
es.activeCategory = nil
es.eventData = {}
es.customPriceModifiers = nil
if notice ~= nil then
self:notifyEvent(self:noticeText(notice), category, nil, self:noticeIsHostLocal(event))
end
if not arcade then
local p = withNotice(self:sharedState(), "end", notice)
p.activeCategory = category or ""
self:broadcastState(p)
end
return true
end
--- The live price-status rule (EC-6 3.7.7), called once per change by the watch:
--- (1) end or narrow the active event the same way roll and restore judge it,
--- (2) send the state, (3) ask a current MarketDynamics to recompose its quotes.
function RandomWorldEvents:onPriceStatusChanged(status)
if g_server == nil or RWEMarketBridge == nil then return end
local es = self.EVENT_STATE
local name = es.activeEvent
local available = status == RWEMarketBridge.STATUS_AVAILABLE
local updateNeeded = status == RWEMarketBridge.STATUS_UPDATE_NEEDED
local ended = false
if name == "economic_crisis" then
local d = type(es.eventData) == "table" and es.eventData or {}
es.eventData = d
if not available then d.crisisHasPrice = false end -- never revived during the event
if updateNeeded or d.crisisHasLoan ~= true then
ended = self:_endActiveEvent("price_status")
elseif not available then
self:chooseSummary(self.EVENTS[name])
es.ambientMsgIndex = 1
end
elseif name ~= nil then
if (RWEMarketBridge.isPriceEvent(name) and not available)
or (updateNeeded and RWEMarketBridge.OLD_READER_EXTRA[name] == true) then
ended = self:_endActiveEvent("price_status")
end
end
if not ended then
self:broadcastState(self:sharedState())
end
if RWEMarketBridge.market == "current" then
RWEMarketBridge.refresh()
end
end
--- The savegame-coupled state as it stands now (written only by a real save).
function RandomWorldEvents:currentStateSnapshot()
local es = self.EVENT_STATE
local now = g_currentMission ~= nil and g_currentMission.time or 0
local snap = {
cooldownRemainingMs = math.max(0, (es.cooldownUntil or 0) - now),
settlement = RWESettlement ~= nil and RWESettlement.serialize() or {},
}
if es.activeEvent ~= nil then
local d = type(es.eventData) == "table" and es.eventData or {}
snap.activeEvent = es.activeEvent
snap.intensity = es.activeIntensity or 0
snap.remainingMs = math.max(0, (es.eventStartTime or 0) + (es.eventDuration or 0) - now)
snap.midpointFired = es.midpointFired == true
snap.summaryKey = d.summaryKey
snap.summaryArgs = stringArgs(d.summaryArgs)
snap.crisisHasPrice = d.crisisHasPrice == true
snap.crisisHasLoan = d.crisisHasLoan == true
end
return snap
end
function RandomWorldEvents:triggerRandomEvent()
if g_server == nil then
return false
end
if not self.events.enabled then
self:dbg("triggerRandomEvent: events disabled")
return false
end
if self.EVENT_STATE.activeEvent ~= nil then
self:dbg("triggerRandomEvent: event already active: " .. tostring(self.EVENT_STATE.activeEvent))
return false
end
local baseIntensity = self:getBaseIntensity()
local available = {}
local ids = {}
for eventId in pairs(self.EVENTS) do ids[#ids + 1] = eventId end
table.sort(ids)
for _, eventId in ipairs(ids) do
local event = self.EVENTS[eventId]
local categoryKey = event.category .. "Events"
local categoryEnabled = self.events[categoryKey]
local intensityOk = baseIntensity >= (event.minIntensity or 1)
-- EC-6: the stored gate and the event's own canTrigger, the same check a
-- forced trigger applies.
local eligible = self:eventEligibility(event)
if categoryEnabled and intensityOk and eligible then
table.insert(available, eventId)
end
end
if #available == 0 then
self:dbg("triggerRandomEvent: no events passed canTrigger/category/intensity checks")
return false
end
self:dbg(string.format("triggerRandomEvent: %d events eligible", #available))
-- Weighted random selection: sum weights, pick by accumulated roll