aboutsummaryrefslogtreecommitdiff
path: root/advtrains/helpers.lua
diff options
context:
space:
mode:
Diffstat (limited to 'advtrains/helpers.lua')
-rw-r--r--advtrains/helpers.lua48
1 files changed, 40 insertions, 8 deletions
diff --git a/advtrains/helpers.lua b/advtrains/helpers.lua
index d7b977e..f2e969f 100644
--- a/advtrains/helpers.lua
+++ b/advtrains/helpers.lua
@@ -151,26 +151,58 @@ function advtrains.yawToDirection(yaw, conn1, conn2)
if not conn1 or not conn2 then
error("given nil to yawToDirection: conn1="..(conn1 or "nil").." conn2="..(conn1 or "nil"))
end
- local yaw1=math.pi*(conn1/4)
- local yaw2=math.pi*(conn2/4)
- if advtrains.minAngleDiffRad(yaw, yaw1)<advtrains.minAngleDiffRad(yaw, yaw2) then--change to > if weird behavior
+ local yaw1=math.pi*(conn1/8)
+ local yaw2=math.pi*(conn2/8)
+ local adiff1 = advtrains.minAngleDiffRad(yaw, yaw1)
+ local adiff2 = advtrains.minAngleDiffRad(yaw, yaw2)
+
+ if math.abs(adiff2)<math.abs(adiff1) then
return conn2
else
return conn1
end
end
+function advtrains.yawToAnyDir(yaw)
+ local min_conn, min_diff=0, 10
+ for conn, vec in pairs(advtrains.dir_trans_tbl) do
+ local uvec = vector.normalize(advtrains.dirToCoord(conn))
+ local yaw1 = math.atan2(uvec.z, uvec.x)
+ local diff = advtrains.minAngleDiffRad(yaw, yaw1)
+ if diff < min_diff then
+ min_conn = conn
+ min_diff = diff
+ end
+ end
+ return min_conn
+end
+
function advtrains.minAngleDiffRad(r1, r2)
+ local pi, pi2 = math.pi, 2*math.pi
+ while r1>pi2 do
+ r1=r1-pi2
+ end
+ while r1<0 do
+ r1=r1+pi2
+ end
+ while r2>pi2 do
+ r2=r2-pi2
+ end
+ while r1<0 do
+ r2=r2+pi2
+ end
local try1=r2-r1
- local try2=(r2+2*math.pi)-r1
- local try3=r2-(r1+2*math.pi)
- if math.min(math.abs(try1), math.abs(try2), math.abs(try3))==math.abs(try1) then
+ local try2=r2+pi2-r1
+ local try3=r2-pi2-r1
+
+ local minabs = math.min(math.abs(try1), math.abs(try2), math.abs(try3))
+ if minabs==math.abs(try1) then
return try1
end
- if math.min(math.abs(try1), math.abs(try2), math.abs(try3))==math.abs(try2) then
+ if minabs==math.abs(try2) then
return try2
end
- if math.min(math.abs(try1), math.abs(try2), math.abs(try3))==math.abs(try3) then
+ if minabs==math.abs(try3) then
return try3
end
end