33
44local GLOBAL_KEY = ' emigration' -- used for state change hooks and persistence
55
6- enabled = enabled or false
6+ local function get_default_state ()
7+ return {enabled = false , last_cycle_tick = 0 }
8+ end
9+
10+ state = state or get_default_state ()
711
812function isEnabled ()
9- return enabled
13+ return state . enabled
1014end
1115
1216local function persist_state ()
13- dfhack .persistent .saveSiteData (GLOBAL_KEY , { enabled = enabled } )
17+ dfhack .persistent .saveSiteData (GLOBAL_KEY , state )
1418end
1519
20+ local TICKS_PER_MONTH = 33600
21+ local TICKS_PER_YEAR = 12 * TICKS_PER_MONTH
22+
1623function desireToStay (unit ,method ,civ_id )
1724 -- on a percentage scale
1825 local value = 100 - unit .status .current_soul .personality .stress / 5000
@@ -191,27 +198,36 @@ function checkmigrationnow()
191198 else
192199 for _ , civ_id in pairs (merchant_civ_ids ) do checkForDeserters (' merchant' , civ_id ) end
193200 end
201+
202+ state .last_cycle_tick = dfhack .world .ReadCurrentTick () + TICKS_PER_YEAR * dfhack .world .ReadCurrentYear ()
194203end
195204
196205local function event_loop ()
197- if enabled then
198- checkmigrationnow ()
199- dfhack .timeout (1 , ' months' , event_loop )
206+ if state .enabled then
207+ local current_tick = dfhack .world .ReadCurrentTick () + TICKS_PER_YEAR * dfhack .world .ReadCurrentYear ()
208+ if current_tick - state .last_cycle_tick < TICKS_PER_MONTH then
209+ local timeout_ticks = state .last_cycle_tick - current_tick + TICKS_PER_MONTH
210+ dfhack .timeout (timeout_ticks , ' ticks' , event_loop )
211+ else
212+ checkmigrationnow ()
213+ dfhack .timeout (1 , ' months' , event_loop )
214+ end
200215 end
201216end
202217
203218dfhack .onStateChange [GLOBAL_KEY ] = function (sc )
204219 if sc == SC_MAP_UNLOADED then
205- enabled = false
220+ state . enabled = false
206221 return
207222 end
208223
209224 if sc ~= SC_MAP_LOADED or df .global .gamemode ~= df .game_mode .DWARF then
210225 return
211226 end
212227
213- local persisted_data = dfhack .persistent .getSiteData (GLOBAL_KEY , {enabled = false })
214- enabled = persisted_data .enabled
228+ state = get_default_state ()
229+ utils .assign (state , dfhack .persistent .getSiteData (GLOBAL_KEY , state ))
230+
215231 event_loop ()
216232end
217233
@@ -230,11 +246,11 @@ if dfhack_flags and dfhack_flags.enable then
230246end
231247
232248if args [1 ] == " enable" then
233- enabled = true
249+ state . enabled = true
234250elseif args [1 ] == " disable" then
235- enabled = false
251+ state . enabled = false
236252else
237- print (' emigration is ' .. (enabled and ' enabled' or ' not enabled' ))
253+ print (' emigration is ' .. (state . enabled and ' enabled' or ' not enabled' ))
238254 return
239255end
240256
0 commit comments