1 -- signs_lib api, backported from street_signs
3 local S = signs_lib.gettext
5 signs_lib.lbm_restore_nodes = {}
6 signs_lib.old_fenceposts = {}
7 signs_lib.old_fenceposts_replacement_signs = {}
8 signs_lib.old_fenceposts_with_signs = {}
9 signs_lib.allowed_poles = {}
11 -- Settings used for a standard wood or steel wall sign
12 signs_lib.standard_lines = 6
13 signs_lib.standard_hscale = 1
14 signs_lib.standard_vscale = 1
15 signs_lib.standard_lspace = 1
16 signs_lib.standard_fsize = 15
17 signs_lib.standard_xoffs = 4
18 signs_lib.standard_yoffs = 2
19 signs_lib.standard_cpl = 35
21 signs_lib.standard_wood_groups = {sign = 1, choppy = 2, flammable = 2, oddly_breakable_by_hand = 3}
22 signs_lib.standard_steel_groups = {sign = 1, cracky = 2, oddly_breakable_by_hand = 3}
24 signs_lib.standard_yaw = {
31 signs_lib.wallmounted_yaw = {
40 signs_lib.fdir_to_back = {
47 signs_lib.wall_fdir_to_back = {
56 signs_lib.rotate_facedir = {
66 signs_lib.rotate_walldir = {
75 -- Initialize character texture cache
78 signs_lib.wallmounted_rotate = function(pos, node, user, mode)
79 if not signs_lib.can_modify(pos, user) then return false end
81 if mode ~= screwdriver.ROTATE_FACE or string.match(node.name, "_onpole") then
85 local newparam2 = signs_lib.rotate_walldir[node.param2] or 0
87 minetest.swap_node(pos, { name = node.name, param2 = newparam2 })
88 for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
89 local e = v:get_luaentity()
90 if e and e.name == "signs_lib:text" then
94 signs_lib.update_sign(pos)
98 signs_lib.facedir_rotate = function(pos, node, user, mode)
99 if not signs_lib.can_modify(pos, user) then return false end
101 if mode ~= screwdriver.ROTATE_FACE or string.match(node.name, "_onpole") then
105 local newparam2 = signs_lib.rotate_facedir[node.param2] or 0
107 minetest.swap_node(pos, { name = node.name, param2 = newparam2 })
108 for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
109 local e = v:get_luaentity()
110 if e and e.name == "signs_lib:text" then
114 signs_lib.update_sign(pos)
118 local DEFAULT_TEXT_SCALE = {x=10, y=10}
122 if not minetest.settings:get_bool("creative_mode") then
123 signs_lib.expect_infinite_stacks = false
125 signs_lib.expect_infinite_stacks = true
130 -- Path to the textures.
131 local TP = signs_lib.path .. "/textures"
132 -- Font file formatter
133 local CHAR_FILE = "%s_%02x.png"
135 local CHAR_PATH = TP .. "/" .. CHAR_FILE
137 -- Lots of overkill here. KISS advocates, go away, shoo! ;) -- kaeza
139 local PNG_HDR = string.char(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
141 -- check if a file does exist
142 -- to avoid reopening file after checking again
143 -- pass TRUE as second argument
144 local function file_exists(name, return_handle, mode)
146 local f = io.open(name, mode)
148 if (return_handle) then
158 -- Read the image size from a PNG file.
159 -- Returns image_w, image_h.
160 -- Only the LSB is read from each field!
161 function signs_lib.read_image_size(filename)
162 local f = file_exists(filename, true, "rb")
163 -- file might not exist (don't crash the game)
168 local hdr = f:read(string.len(PNG_HDR))
169 if hdr ~= PNG_HDR then
178 return ws:byte(), hs:byte()
181 -- 4 rows, max 80 chars per, plus a bit of fudge to
182 -- avoid excess trimming (e.g. due to color codes)
184 local MAX_INPUT_CHARS = 400
186 -- helper functions to trim sign text input/output
188 local function trim_input(text)
189 return text:sub(1, math.min(MAX_INPUT_CHARS, text:len()))
192 local function build_char_db(font_size)
196 -- To calculate average char width.
197 local total_width = 0
201 local w, h = signs_lib.read_image_size(CHAR_PATH:format("signs_lib_font_"..font_size.."px", c))
203 local ch = string.char(c)
205 total_width = total_width + w
206 char_count = char_count + 1
210 local cbw, cbh = signs_lib.read_image_size(TP.."/signs_lib_color_"..font_size.."px_n.png")
211 assert(cbw and cbh, "error reading bg dimensions")
212 return cw, cbw, cbh, (total_width / char_count)
215 signs_lib.charwidth15,
216 signs_lib.colorbgw15,
217 signs_lib.lineheight15,
218 signs_lib.avgwidth15 = build_char_db(15)
220 signs_lib.charwidth31,
221 signs_lib.colorbgw31,
222 signs_lib.lineheight31,
223 signs_lib.avgwidth31 = build_char_db(31)
225 local sign_groups = {choppy=2, dig_immediate=2}
226 local fences_with_sign = { }
228 -- some local helper functions
230 local function split_lines_and_words(text)
231 if not text then return end
233 for _, line in ipairs(text:split("\n")) do
234 table.insert(lines, line:split(" "))
239 local math_max = math.max
241 local function fill_line(x, y, w, c, font_size, colorbgw)
244 for xx = 0, math.max(0, w), colorbgw do
245 table.insert(tex, (":%d,%d=signs_lib_color_"..font_size.."px_%s.png"):format(x + xx, y, c))
247 return table.concat(tex)
250 -- make char texture file name
251 -- if texture file does not exist use fallback texture instead
252 local function char_tex(font_name, ch)
253 if ctexcache[font_name..ch] then
254 return ctexcache[font_name..ch], true
257 local exists, tex = file_exists(CHAR_PATH:format(font_name, c))
258 if exists and c ~= 14 then
259 tex = CHAR_FILE:format(font_name, c)
261 tex = CHAR_FILE:format(font_name, 0x0)
263 ctexcache[font_name..ch] = tex
268 local function make_line_texture(line, lineno, pos, line_width, line_height, cwidth_tab, font_size, colorbgw)
271 local font_name = "signs_lib_font_"..font_size.."px"
274 local node = minetest.get_node(pos)
275 local def = minetest.registered_items[node.name]
276 local default_color = def.default_color or 0
278 local cur_color = tonumber(default_color, 16)
280 -- We check which chars are available here.
281 for word_i, word in ipairs(line) do
284 word = string.gsub(word, "%^[12345678abcdefgh]", {
285 ["^1"] = string.char(0x81),
286 ["^2"] = string.char(0x82),
287 ["^3"] = string.char(0x83),
288 ["^4"] = string.char(0x84),
289 ["^5"] = string.char(0x85),
290 ["^6"] = string.char(0x86),
291 ["^7"] = string.char(0x87),
292 ["^8"] = string.char(0x88),
293 ["^a"] = string.char(0x8a),
294 ["^b"] = string.char(0x8b),
295 ["^c"] = string.char(0x8c),
296 ["^d"] = string.char(0x8d),
297 ["^e"] = string.char(0x8e),
298 ["^f"] = string.char(0x8f),
299 ["^g"] = string.char(0x90),
300 ["^h"] = string.char(0x91)
305 local c = word:sub(i, i)
307 local cc = tonumber(word:sub(i+1, i+1), 16)
313 local w = cwidth_tab[c]
315 width = width + w + 1
316 if width >= (line_width - cwidth_tab[" "]) then
319 maxw = math_max(width, maxw)
321 if #chars < MAX_INPUT_CHARS then
322 table.insert(chars, {
324 tex = char_tex(font_name, c),
325 col = ("%X"):format(cur_color),
328 ch_offs = ch_offs + w
333 width = width + cwidth_tab[" "] + 1
334 maxw = math_max(width, maxw)
335 table.insert(words, { chars=chars, w=ch_offs })
338 -- Okay, we actually build the "line texture" here.
342 local start_xpos = math.floor((line_width - maxw) / 2) + def.x_offset
344 local xpos = start_xpos
345 local ypos = (line_height + def.line_spacing)* lineno + def.y_offset
349 for word_i, word in ipairs(words) do
350 local xoffs = (xpos - start_xpos)
351 if (xoffs > 0) and ((xoffs + word.w) > maxw) then
352 table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
354 ypos = ypos + line_height + def.line_spacing
356 if lineno >= def.number_of_lines then break end
357 table.insert(texture, fill_line(xpos, ypos, maxw, cur_color, font_size, colorbgw))
359 for ch_i, ch in ipairs(word.chars) do
360 if ch.col ~= cur_color then
362 table.insert(texture, fill_line(xpos + ch.off, ypos, maxw, cur_color, font_size, colorbgw))
364 table.insert(texture, (":%d,%d=%s"):format(xpos + ch.off, ypos, ch.tex))
368 (":%d,%d="):format(xpos + word.w, ypos) .. char_tex(font_name, " ")
370 xpos = xpos + word.w + cwidth_tab[" "]
371 if xpos >= (line_width + cwidth_tab[" "]) then break end
374 table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
375 table.insert(texture, fill_line(start_xpos, ypos + line_height, maxw, "n", font_size, colorbgw))
377 return table.concat(texture), lineno
380 local function make_sign_texture(lines, pos)
381 local node = minetest.get_node(pos)
382 local def = minetest.registered_items[node.name]
390 if def.font_size and def.font_size == 31 then
392 line_width = math.floor(signs_lib.avgwidth31 * def.chars_per_line) * def.horiz_scaling
393 line_height = signs_lib.lineheight31
394 char_width = signs_lib.charwidth31
395 colorbgw = signs_lib.colorbgw31
398 line_width = math.floor(signs_lib.avgwidth15 * def.chars_per_line) * def.horiz_scaling
399 line_height = signs_lib.lineheight15
400 char_width = signs_lib.charwidth15
401 colorbgw = signs_lib.colorbgw15
404 local texture = { ("[combine:%dx%d"):format(line_width, (line_height + def.line_spacing) * def.number_of_lines * def.vert_scaling) }
408 if lineno >= def.number_of_lines then break end
409 local linetex, ln = make_line_texture(lines[i], lineno, pos, line_width, line_height, char_width, font_size, colorbgw)
410 table.insert(texture, linetex)
413 table.insert(texture, "^[makealpha:0,0,0")
414 return table.concat(texture, "")
417 local function set_obj_text(obj, text, x, pos)
418 local split = split_lines_and_words
419 local text_ansi = Utf8ToAnsi(text)
420 local n = minetest.registered_nodes[minetest.get_node(pos).name]
421 local text_scale = (n and n.text_scale) or DEFAULT_TEXT_SCALE
422 local texture = make_sign_texture(split(text_ansi), pos)
425 visual_size = text_scale,
429 signs_lib.construct_sign = function(pos)
430 local meta = minetest.get_meta(pos)
434 "textarea[0,-0.3;6.5,3;text;;${text}]"..
435 "button_exit[2,3.4;2,1;ok;"..S("Write").."]"..
436 "background[-0.5,-0.5;7,5;signs_lib_sign_bg.jpg]")
437 local i = meta:get_string("infotext")
438 if i == "" then -- it wasn't even set, so set it.
439 meta:set_string("infotext", "")
443 function signs_lib.destruct_sign(pos)
444 local objects = minetest.get_objects_inside_radius(pos, 0.5)
445 for _, v in ipairs(objects) do
446 local e = v:get_luaentity()
447 if e and e.name == "signs_lib:text" then
453 local function make_infotext(text)
454 text = trim_input(text)
455 local lines = split_lines_and_words(text) or {}
457 for _, line in ipairs(lines) do
458 table.insert(lines2, (table.concat(line, " "):gsub("#[0-9a-fA-F]", ""):gsub("##", "#")))
460 return table.concat(lines2, "\n")
463 function signs_lib.update_sign(pos, fields)
464 local meta = minetest.get_meta(pos)
466 local text = fields and fields.text or meta:get_string("text")
467 text = trim_input(text)
469 local owner = meta:get_string("owner")
471 if owner ~= "" then ownstr = S("Locked sign, owned by @1\n", owner) end
473 meta:set_string("text", text)
474 meta:set_string("infotext", ownstr..make_infotext(text).." ")
476 local objects = minetest.get_objects_inside_radius(pos, 0.5)
478 for _, v in ipairs(objects) do
479 local e = v:get_luaentity()
480 if e and e.name == "signs_lib:text" then
484 set_obj_text(v, text, nil, pos)
493 -- if there is no entity
494 local signnode = minetest.get_node(pos)
495 local signname = signnode.name
496 local def = minetest.registered_items[signname]
497 if not def.entity_info or not def.entity_info.yaw[signnode.param2 + 1] then return end
498 local obj = minetest.add_entity(pos, "signs_lib:text")
500 obj:setyaw(def.entity_info.yaw[signnode.param2 + 1])
502 mesh = def.entity_info.mesh,
506 function signs_lib.receive_fields(pos, formname, fields, sender)
507 if fields and fields.text and fields.ok and signs_lib.can_modify(pos, sender) then
508 minetest.log("action", S("@1 wrote \"@2\" to sign at @3",
509 (sender:get_player_name() or ""),
510 fields.text:gsub('\\', '\\\\'):gsub("\n", "\\n"),
511 minetest.pos_to_string(pos)
513 signs_lib.update_sign(pos, fields)
517 function signs_lib.can_modify(pos, player)
518 local meta = minetest.get_meta(pos)
519 local owner = meta:get_string("owner")
520 local playername = player:get_player_name()
522 if minetest.is_protected(pos, playername) then
523 minetest.record_protection_violation(pos, playername)
528 or playername == owner
529 or (minetest.check_player_privs(playername, {sign_editor=true}))
530 or (playername == minetest.settings:get("name")) then
533 minetest.record_protection_violation(pos, playername)
537 local signs_text_on_activate = function(self)
538 local pos = self.object:getpos()
539 local meta = minetest.get_meta(pos)
540 local signnode = minetest.get_node(pos)
541 local signname = signnode.name
542 local def = minetest.registered_items[signname]
543 local text = meta:get_string("text")
544 if text and def and def.entity_info then
545 text = trim_input(text)
546 set_obj_text(self.object, text, nil, pos)
547 self.object:set_properties({
548 mesh = def.entity_info.mesh,
553 minetest.register_entity("signs_lib:text", {
554 collisionbox = { 0, 0, 0, 0, 0, 0 },
556 mesh = "signs_lib_standard_wall_sign_entity.obj",
558 on_activate = signs_text_on_activate,
561 -- make selection boxes
562 -- sizex/sizey specified in inches because that's what MUTCD uses.
564 function signs_lib.make_selection_boxes(sizex, sizey, onpole, xoffs, yoffs, zoffs, fdir)
566 local tx = (sizex * 0.0254 ) / 2
567 local ty = (sizey * 0.0254 ) / 2
568 local xo = xoffs and xoffs * 0.0254 or 0
569 local yo = yoffs and yoffs * 0.0254 or 0
570 local zo = zoffs and zoffs * 0.0254 or 0
572 if onpole == "_onpole" then
575 type = "wallmounted",
576 wall_side = { -0.5 - 0.3125 + zo, -ty + yo, -tx + xo, -0.4375 - 0.3125 + zo, ty + yo , tx + xo },
577 wall_top = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5 },
578 wall_bottom = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5 },
583 fixed = { -tx + xo, -ty + yo, 0.5 + 0.3125 + zo, tx + xo, ty + yo, 0.4375 + 0.3125 + zo }
589 type = "wallmounted",
590 wall_side = { -0.5 + zo, -ty + yo, -tx + xo, -0.4375 + zo, ty + yo, tx + xo },
591 wall_top = { -tx - xo, 0.5 + zo, -ty + yo, tx - xo, 0.4375 + zo, ty + yo},
592 wall_bottom = { -tx - xo, -0.5 + zo, -ty + yo, tx - xo, -0.4375 + zo, ty + yo }
597 fixed = { -tx + xo, -ty + yo, 0.5 + zo, tx + xo, ty + yo, 0.4375 + zo}
603 function signs_lib.check_for_pole(pos, pointed_thing)
604 local ppos = minetest.get_pointed_thing_position(pointed_thing)
605 local pnode = minetest.get_node(ppos)
606 local pdef = minetest.registered_items[pnode.name]
611 if (signs_lib.allowed_poles[pnode.name]
612 or (pdef and pdef.drawtype == "fencelike")
613 or string.find(pnode.name, "default:fence_")
614 or string.find(pnode.name, "_post")
615 or string.find(pnode.name, "fencepost")
616 or (pnode.name == "streets:bigpole" and pnode.param2 < 4)
617 or (pnode.name == "streets:bigpole" and pnode.param2 > 19 and pnode.param2 < 24)
620 (pos.x ~= ppos.x or pos.z ~= ppos.z) then
621 print("signs_lib.check_for_pole returned true")
626 function signs_lib.after_place_node(pos, placer, itemstack, pointed_thing, locked)
627 local ppos = minetest.get_pointed_thing_position(pointed_thing)
628 local pnode = minetest.get_node(ppos)
629 local pdef = minetest.registered_items[pnode.name]
630 local playername = placer:get_player_name()
632 if signs_lib.check_for_pole(pos, pointed_thing) then
633 local node = minetest.get_node(pos)
634 minetest.swap_node(pos, {name = itemstack:get_name().."_onpole", param2 = node.param2})
637 local meta = minetest.get_meta(pos)
638 meta:set_string("owner", playername)
639 meta:set_string("infotext", S("Locked sign, owned by @1\n", playername))
643 function signs_lib.register_fence_with_sign()
644 minetest.log("warning", "[signs_lib] ".."Attempt to call no longer used function signs_lib.register_fence_with_sign()")
647 -- restore signs' text after /clearobjects and the like, the next time
648 -- a block is reloaded by the server.
650 minetest.register_lbm({
651 nodenames = signs_lib.lbm_restore_nodes,
652 name = "signs_lib:restore_sign_text",
653 label = "Restore sign text",
654 run_at_every_load = true,
655 action = function(pos, node)
656 signs_lib.update_sign(pos,nil,nil,node)
660 -- Convert old signs on fenceposts into signs on.. um.. fence posts :P
662 minetest.register_lbm({
663 nodenames = signs_lib.old_fenceposts_with_signs,
664 name = "signs_lib:fix_fencepost_signs",
665 label = "Change single-node signs on fences into normal",
666 run_at_every_load = true,
667 action = function(pos, node)
669 local fdir = node.param2 % 8
671 x = pos.x + signs_lib.fdir_to_back[fdir+1][1],
673 z = pos.z + signs_lib.fdir_to_back[fdir+1][2]
676 if minetest.get_node(signpos).name == "air" then
677 local new_wmdir = minetest.dir_to_wallmounted(minetest.facedir_to_dir(fdir))
678 local oldfence = signs_lib.old_fenceposts[node.name]
679 local newsign = signs_lib.old_fenceposts_replacement_signs[node.name]
681 for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
682 local e = v:get_luaentity()
683 if e and e.name == "signs_lib:text" then
688 local oldmeta = minetest.get_meta(pos):to_table()
689 minetest.set_node(pos, {name = oldfence})
690 minetest.set_node(signpos, { name = newsign, param2 = new_wmdir })
691 local newmeta = minetest.get_meta(signpos)
692 newmeta:from_table(oldmeta)
693 signs_lib.update_sign(signpos)
698 signs_lib.block_list = {}
699 signs_lib.totalblocks = 0
701 -- Maintain a list of currently-loaded blocks
702 minetest.register_lbm({
703 nodenames = {"group:sign"},
704 name = "signs_lib:update_block_list",
705 label = "Update list of loaded blocks, log only those with signs",
706 run_at_every_load = true,
707 action = function(pos, node)
708 -- yeah, yeah... I know I'm hashing a block pos, but it's still just a set of coords
709 local hash = minetest.hash_node_position(vector.floor(vector.divide(pos, core.MAP_BLOCKSIZE)))
710 if not signs_lib.block_list[hash] then
711 signs_lib.block_list[hash] = true
712 signs_lib.totalblocks = signs_lib.totalblocks + 1
717 minetest.register_chatcommand("regen_signs", {
719 privs = {server = true},
720 description = "Skims through all currently-loaded sign-bearing mapblocks, clears away any entities within each sign's node space, and regenerates their text entities, if any.",
721 func = function(player_name, params)
724 for b in pairs(signs_lib.block_list) do
725 local blockpos = minetest.get_position_from_hash(b)
726 local pos1 = vector.multiply(blockpos, core.MAP_BLOCKSIZE)
727 local pos2 = vector.add(pos1, core.MAP_BLOCKSIZE - 1)
728 if minetest.get_node_or_nil(vector.add(pos1, core.MAP_BLOCKSIZE/2)) then
729 local signs_in_block = minetest.find_nodes_in_area(pos1, pos2, {"group:sign"})
730 allsigns[#allsigns + 1] = signs_in_block
731 totalsigns = totalsigns + #signs_in_block
733 signs_lib.block_list[b] = nil -- if the block is no longer loaded, remove it from the table
734 signs_lib.totalblocks = signs_lib.totalblocks - 1
737 if signs_lib.totalblocks < 0 then signs_lib.totalblocks = 0 end
738 if totalsigns == 0 then
739 minetest.chat_send_player(player_name, "There are no signs in the currently-loaded terrain.")
740 signs_lib.block_list = {}
744 minetest.chat_send_player(player_name, "Found a total of "..totalsigns.." sign nodes across "..signs_lib.totalblocks.." blocks.")
745 minetest.chat_send_player(player_name, "Regenerating sign entities...")
747 for _, b in pairs(allsigns) do
748 for _, pos in ipairs(b) do
749 local objects = minetest.get_objects_inside_radius(pos, 0.5)
751 for _, v in ipairs(objects) do
755 local node = minetest.get_node(pos)
756 local def = minetest.registered_items[node.name]
757 if def and def.entity_info then
758 signs_lib.update_sign(pos)
762 minetest.chat_send_player(player_name, "Finished.")