~gpcf/advtrains-devel

[Discussion] [API] advtrains.get_wagon_at_pos(pos) v1 SUPERSEDED

Y. Wang: 1
 Add API to get wagons at a specific position

 2 files changed, 31 insertions(+), 0 deletions(-)
Hi,

yes, generally this is the right way to do. However you need to be
careful because the index does not necessarily match the real position
(an index of 1 can be a distance greater than 1)

Since I have some time today, I added such a function in 283efc4. You
should be able to use it right away.

Regards,
orwell
Hi again,

Just noticed you added a patch here an hour ago... Which means we were
working in parallel.

My remark still holds though, and I believe my implementation is
correct.
Regards,
orwell
Export patchset (mbox)
How do I use this?

Copy & paste the following snippet into your terminal to import this patchset into git:

curl -s https://lists.sr.ht/~gpcf/advtrains-devel/patches/41443/mbox | git am -3
Learn more about email & git

[PATCH] Add API to get wagons at a specific position Export this patch

---
 advtrains/occupation.lua | 14 ++++++++++++++
 advtrains/trainlogic.lua | 17 +++++++++++++++++
 2 files changed, 31 insertions(+)

diff --git a/advtrains/occupation.lua b/advtrains/occupation.lua
index db39991..18e3f2b 100644
--- a/advtrains/occupation.lua
+++ b/advtrains/occupation.lua
@@ -186,6 +186,20 @@ function o.get_trains_at(ppos)
	return r
end

-- Gets a mapping of wagon id's to offsets of wagons that stand or drive over;
-- the offset is relative to the center of the wagon
-- returns (table with wagon_id->offset)
function o.get_wagons_at(pos)
	local r = {}
	for id, idx in pairs(o.get_trains_at(pos)) do
		local w, offset = advtrains.get_wagon_at_index(id, idx)
		if w then
			r[w.id] = offset
		end
	end
	return r
end

-- Gets a mapping of train id's to indexes of trains that have a path
-- generated over this node
-- returns (table with train_id->index)
diff --git a/advtrains/trainlogic.lua b/advtrains/trainlogic.lua
index 288e224..186a7ff 100644
--- a/advtrains/trainlogic.lua
+++ b/advtrains/trainlogic.lua
@@ -1238,6 +1238,23 @@ function advtrains.get_train_at_pos(pos)
	end
end

function advtrains.get_wagon_at_index(train, index)
	if train == nil then
		return
	elseif type(train) ~= "table" then
		return advtrains.get_wagon_at_index(advtrains.trains[train], index)
	end
	local offset = train.index - index
	local p0, p1 = 0, 0
	for _, wid in ipairs(train.trainparts) do
		local wagon = advtrains.wagons[wid]
		local wp = advtrains.wagon_prototypes[wagon.type] or advtrains.wagon_prototypes["advtrains:wagon_placeholder"]
		p0, p1 = p1, p1+2*wp.wagon_span
		if offset <= p1 then
			return wagon, wagon.pos_in_train - offset
		end
	end
end

-- ehm... I never adapted this function to the new path system ?!
function advtrains.invalidate_all_paths(pos)
-- 
2.40.1