From 723ee6d1f67e2c8a0fa98e9df1b56778a9f21bde Mon Sep 17 00:00:00 2001 From: Pasi Kallinen Date: Fri, 26 Aug 2022 13:07:52 +0300 Subject: [PATCH] Expose selection bounds to lua --- doc/lua.adoc | 10 ++++++++++ src/nhlsel.c | 19 +++++++++++++++++++ test/test_sel.lua | 15 +++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/doc/lua.adoc b/doc/lua.adoc index cb0996719..e3f571a7a 100644 --- a/doc/lua.adoc +++ b/doc/lua.adoc @@ -891,6 +891,16 @@ Example: Alias for <<_fillrect>>. +=== bounds + +Get the bounding box for the selection. Returns a table with lx, ly, hx, hy integer fields. + +Example: + + local rect = sel:bounds(); + local s = string.format("(%i,%i)-(%i,%i)", rect.lx, rect.ly, rect.hx, rect.hy)); + + === circle Example: diff --git a/src/nhlsel.c b/src/nhlsel.c index 25ebed2d4..3f766abc9 100644 --- a/src/nhlsel.c +++ b/src/nhlsel.c @@ -17,6 +17,7 @@ static int l_selection_getpoint(lua_State *); static int l_selection_setpoint(lua_State *); static int l_selection_filter_percent(lua_State *); static int l_selection_rndcoord(lua_State *); +static int l_selection_getbounds(lua_State *); static boolean params_sel_2coords(lua_State *, struct selectionvar **, coordxy *, coordxy *, coordxy *, coordxy *); static int l_selection_line(lua_State *); @@ -382,6 +383,23 @@ l_selection_rndcoord(lua_State *L) return 1; } +/* local rect = sel:bounds(); */ +static int +l_selection_getbounds(lua_State *L) +{ + struct selectionvar *sel = l_selection_check(L, 1); + NhRect rect; + + selection_getbounds(sel, &rect); + lua_settop(L, 0); + lua_newtable(L); + nhl_add_table_entry_int(L, "lx", rect.lx); + nhl_add_table_entry_int(L, "ly", rect.ly); + nhl_add_table_entry_int(L, "hx", rect.hx); + nhl_add_table_entry_int(L, "hy", rect.hy); + return 1; +} + /* internal function to get a selection and 4 integer values from lua stack. removes the integers from the stack. returns TRUE if params are good. @@ -875,6 +893,7 @@ static const struct luaL_Reg l_selection_methods[] = { { "ellipse", l_selection_ellipse }, { "gradient", l_selection_gradient }, { "iterate", l_selection_iterate }, + { "bounds", l_selection_getbounds }, { NULL, NULL } }; diff --git a/test/test_sel.lua b/test/test_sel.lua index 70ff9e0ad..72c40896c 100644 --- a/test/test_sel.lua +++ b/test/test_sel.lua @@ -467,6 +467,20 @@ function test_sel_iterate() is_map_at(5,5, "L"); is_map_at(7,5, "L"); is_map_at(9,5, "L"); + +end + +function test_sel_bounds() + local __func__ = "test_sel_bounds"; + local sel = selection.new(); + sel:set(5, 5); + sel:set(7, 5); + sel:set(5, 6); + + local rect = sel:bounds(); + if (rect.lx ~= (5 + 1) or rect.ly ~= 5 or rect.hx ~= (7 + 1) or rect.hy ~= 6) then + error(string.format("selection bounds error:(%i,%i-%i,%i)", rect.lx, rect.ly, rect.hx, rect.hy)); + end end nh.debug_flags({mongen = false, hunger = false, overwrite_stairs = true }); @@ -487,3 +501,4 @@ test_sel_filter_mapchar(); test_sel_flood(); test_sel_match(); test_sel_iterate(); +test_sel_bounds();