Skip to content

Movegoods fix - #1655

Open
ab9rf wants to merge 4 commits into
DFHack:masterfrom
ab9rf:movegoods-fix
Open

ab9rf wants to merge 4 commits into
DFHack:masterfrom
ab9rf:movegoods-fix

Conversation

@ab9rf

@ab9rf ab9rf commented Nov 29, 2026

Copy link
Copy Markdown
Member

rewrite the UI and backend processing for movegoods to avoid repeatedly retraversing the item list while (un)marking items for trade

also use a coroutine to ensure the frame pump continues to run when (un)marking a large number of items

additional optimizations added to try to reduce the startup time especially in large forts

fixes DFHack/dfhack#6050

rewrite the UI and backend processing for `movegoods` to avoid repeatedly retraversing the item list while (un)marking items for trade

also use a coroutine to ensure the frame pump continues to run when (un)marking a large number of items

fixes DFHack/dfhack#6050
item scan in the test fort i am using was taking ~6s. these changes trim it to about ~2s which is a significant improvement

will look into why dfhack.item.* methods are so slow to invoke (~95-100 microseconds per call) - there might be a core issue here that can be mitigated but that'll be done separately
mark preservation was not working correctly in conjunction with item grouping, caused a CI test failure
test got desynced from implementation

@SilasD SilasD left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

generally, the scan_queued looks over-engineered and a bit confusing.

  • as far as I can tell, scan_queued is a hash table that can be empty, or can contain a single key, either true or false, with a value of true. that key is the value to use for inside_containers for the queued scan.
  • then there is a separate scan hash table, that contains (at least) a key inside_containers with the value being used on the currently in-progress scan.
  • the current inside_containers setting is sometimes taken directly from scan, and sometimes passed into functions as a parameter.

it all feels a bit inconsistent. and clunky. I'm sure it works though.

if you do choose to re-engineer it, perhaps settle on the scan hash table and all the keys it can use (I think this is currently only inside_containers), and make scan_queued into a table (or preferrably a list) of pending scan settings.
then starting the next scan is just a case of getting the next scan parameters from the table or list.
Something like

local next_scan_settings = { inside_containers = inside_containers }
table.insert(scan_queued, next_scan_settings)

and

self.scan = table.remove(scan_queued, 1)

would be ideal, as it would make the thing into a real queue.
(note that you can table.remove() from an empty table; it returns nil instead of throwing.)
this would still be over-engineered, but it would be clearer and would be trivially extendable to support scan parameters other than inside_containers. the current implementation would require rewriting to support other scan parameters.

neat coroutine idea. I can't quite tell if the game is forced paused during the asynchronous processing, so I'll just mention that it needs to be.
(later) especially as the code keeps references to items across yields.

I'm burned out, but I hope to get back to this.

-- on forts with a large number of items. the coroutine yields after each time
-- slice and is resumed once per rendered frame by pump_scan().
local SCAN_TIME_BUDGET_MS = 10
local SCAN_TIME_CHECK = 32

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

required by a suggestion on line 620. this also boosts the number of items between "should I yield?" to 1024.

Suggested change
local SCAN_TIME_CHECK = 32
local SCAN_TIME_CHECK = math.tointeger(2^10 -1) -- *must* be one less than a power of 2.

-- so capability is determined once per item type
local name_capable_by_type = {}
for i = 0, #items - 1 do
if i % SCAN_TIME_CHECK == 0 and dfhack.getTickCount() >= deadline then

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like that % modulus operation. I do like the idea of only checking getTickCount every n iterations,
but I think it's losing a lot from that modulus. I forecast that & bitmath should be much faster.

Suggested change
if i % SCAN_TIME_CHECK == 0 and dfhack.getTickCount() >= deadline then
if i & SCAN_TIME_CHECK == 0 and dfhack.getTickCount() >= deadline then

where SCAN_TIME_CHECK is required to be one less than a power of 2.

Edit: or if you implement the outer, inner loops from the above comment, this doesn't matter.


-- takes into account trade agreements
function get_perceived_value(item, caravan_state)
local EMPTY_CONTAINED = {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like having this constant. it made me wonder, is something being maintained in this between yields? is this something that needs to be cleared out when the calling script exits?

I think you should zap it and just use a {} empty-table constructor in the two places it's used.

Edit: wait, hold the phone, it's completely unneccesary. discussion below. zap it.

Suggested change
local EMPTY_CONTAINED = {}

local value = dfhack.items.getValue(item, caravan_state)
for _,contained_item in ipairs(dfhack.items.getContainedItems(item)) do
if not contained then
contained = item.flags.container and dfhack.items.getContainedItems(item) or EMPTY_CONTAINED

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it turns out that getContainedItems does the right thing if the item being probed isn't a container; it returns an empty list instead of throwing or otherwise misfunctioning. I think it's just as fast to call it as to test a flag bit and choose between two options.
The only reason I see to continue using the constant is to have a pre-constructed empty table to iterate over instead of constructing and abandoning one on each call. And I don't think that's worth it, especially with the new code to dodge the whole issue with the passed-in contents list.

Suggested change
contained = item.flags.container and dfhack.items.getContainedItems(item) or EMPTY_CONTAINED
contained = dfhack.items.getContainedItems(item)

if match_risky(item, risky_items) then return false, true end
for _,contained_item in ipairs(dfhack.items.getContainedItems(item)) do
if not contained then
contained = item.flags.container and dfhack.items.getContainedItems(item) or EMPTY_CONTAINED

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
contained = item.flags.container and dfhack.items.getContainedItems(item) or EMPTY_CONTAINED
contained = dfhack.items.getContainedItems(item)

coroutine.yield()
deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS
end
local item = items[i]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this makes me uncomfortable, not gonna lie. because it's keeping df.item objects over frames.
even if the game is forced-paused, other tools could be manipulating items. deleting items.
a deleted item is going to have a stale reference here, not detectable simply via checking nil.

okay, you're getting items directly from IN_PLAY, that's not as bad as it could be. withdrawing this objection.

-- only some item classes have a 'name' field; probing it errors on others,
-- so capability is determined once per item type
local name_capable_by_type = {}
for i = 0, #items - 1 do

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this will go bad if the size of df.global.world.items.other.IN_PLAY shrinks between yields. just saying.

maybe rework this as a while i < #items do stuff; i = i + 1; end.
if you do that, you could also make this a two-level loop, and completely get rid of the SCAN_TIME_CHECK test in the inner loop.
while not done do for i = j, j+sheafsize-1 do stuff end; j=j+sheafsize; yield(); end;
kind of concept. or the same thing with a repeat for do stuff end until test

goto continue
elseif not inside_containers and item.flags.in_inventory then
local items = df.global.world.items.other.IN_PLAY
local deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this needs rethought.

oh yeah, getTickCount() is not about game ticks, or even frames I guess. the name must be legacy.

Still, I'm wondering if you should consult a wall clock. Do we have one exported to Lua? I don't think we do.

Comment on lines +394 to +395
local pos = item.pos
return pos.x ~= -30000 and pos or nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reminder that this is returning a live reference to an item's internal fields.
if that item goes away over a yield(), it'll be a stale reference.

I'm not alert enough right now to check if that's a problem.

Comment on lines +443 to +447
-- items on the same tile share walkability; memoize per tile since the
-- check is expensive and stockpiles cluster many items onto few tiles
local tile_key = (pos.x*1024 + pos.y)*1024 + pos.z + 64
local walkable = walkable_cache[tile_key]
if walkable == nil then

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maps::canWalkBetween() looks pretty cheap to me. remember that DF is already caching walkable groups.

Maps::canWalkBetween() is two Maps::GetTileBlock() calls and two index_tile macros, and some NULL tests and == tests. I am not convinced that caching the results in Lua is a win.

I do not have any resources explaining the Lua 5.3 VM instruction set, but in Lua 5.1, this looks
like it would be something similar to:

local tile_key = (pos.x*1024 + pos.y)*1024 + pos.z + 64

  • GETUPVAL 'pos'
  • LOADK 'string x'
  • GETTABLE (if pos is a df::coord, this will call into DFHack Lua glue code),
  • LOADK 'integer 1024'
  • MUL
  • GETUPVAL 'pos' (the code generator might reuse the previous load of pos.)
  • LOADK 'string y'
  • GETTABLE
  • ADD
  • LOADK 'integer 1024' (or, quite likely, the code generator reuses the previous 1024)
  • MUL
  • GETUPVAL 'pos' (again, this might be reused from above.)
  • LOADK 'string z'
  • GETTABLE
  • ADD
  • LOADK 'integer 64'
  • ADD

So I really question whether 15-ish VM instructions can beat the function call.

local walkable = walkable_cache[tile_key]
if walkable == nil then

  • GETGLOBAL 'walkable_cache'
  • GETTABLE
  • EQ (may be special cased for nil)

that part should be fast.

when I tried to cache, oh, something about tiletype attributes, the details escape me, I found that my best, most aggressive caching strategies didn't beat just calling the C++ function I was trying to bypass. I think this will be the same situation.

I went into too much detail here, but oh well, not going to delete it.

Edit: if you do remove the caching, you can precompute the Depot's walkability group and then just compare that with the result of dfhack.maps.getWalkableGroup(pos).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

dfhack trade interface is extremely slow when doing bulk trade marking or unmarking

2 participants