From 74bf177cc850164a0a6c13a634e7da6410f9f73a Mon Sep 17 00:00:00 2001 From: techniX Date: Fri, 10 Jul 2020 12:02:23 +0200 Subject: optimize path_get_index_by_offset Instead of calling path_get_adjacent twice (which calls path_get twice, i.e. 4 times overall), we call path_get directly only 2 times with min and max indices to generate all the path we need for calculations. --- advtrains/path.lua | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'advtrains') diff --git a/advtrains/path.lua b/advtrains/path.lua index 23f5e78..ee82c06 100644 --- a/advtrains/path.lua +++ b/advtrains/path.lua @@ -286,16 +286,26 @@ end -- This function determines the index resulting from moving along the path by 'offset' meters -- starting from 'index'. See also the comment on the top of the file. function advtrains.path_get_index_by_offset(train, index, offset) + local advtrains_path_get = advtrains.path_get + -- Step 1: determine my current absolute pos on the path - local start_index_f = math.floor(index) - local _, _, frac = advtrains.path_get_adjacent(train, index) + local start_index_f = atfloor(index) + local end_index_f = start_index_f + 1 + local c_idx = atfloor(index + offset) + local c_idx_f = c_idx + 1 + + local frac = index - start_index_f + + advtrains_path_get(train, math.min(start_index_f, end_index_f, c_idx, c_idx_f)) + advtrains_path_get(train, math.max(start_index_f, end_index_f, c_idx, c_idx_f)) + local dist1, dist2 = train.path_dist[start_index_f], train.path_dist[start_index_f+1] - local start_dist = n_interpolate(dist1, dist2, frac) + local start_dist = dist1 + (dist2-dist1)*frac -- Step 2: determine the total end distance and estimate the index we'd come out local end_dist = start_dist + offset - local c_idx = math.floor(index + offset) + local c_idx = atfloor(index + offset) -- Step 3: move forward/backward to find real index -- We assume here that the distance between 2 path items is never smaller than 1. @@ -306,9 +316,7 @@ function advtrains.path_get_index_by_offset(train, index, offset) -- Desired position: -------#------ -- Path items : --|--|--|--|-- -- c_idx : ^ - - advtrains.path_get_adjacent(train, c_idx) - + while train.path_dist[c_idx] < end_dist do c_idx = c_idx + 1 end -- cgit v1.2.3