]> git.lizzy.rs Git - signs_lib.git/blob - api.lua
in fact, just bail out if the sign needs no entity
[signs_lib.git] / api.lua
1 -- signs_lib api, backported from street_signs
2
3 local S = signs_lib.gettext
4
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 = {}
10
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 = 0
19 signs_lib.standard_cpl = 35
20
21 signs_lib.standard_wood_groups = table.copy(minetest.registered_items["default:sign_wall_wood"].groups)
22 signs_lib.standard_wood_groups.sign = 1
23 signs_lib.standard_wood_groups.attached_node = nil
24
25 signs_lib.standard_steel_groups = table.copy(minetest.registered_items["default:sign_wall_steel"].groups)
26 signs_lib.standard_steel_groups.sign = 1
27 signs_lib.standard_steel_groups.attached_node = nil
28
29 signs_lib.standard_wood_sign_sounds  = table.copy(minetest.registered_items["default:sign_wall_wood"].sounds)
30 signs_lib.standard_steel_sign_sounds = table.copy(minetest.registered_items["default:sign_wall_steel"].sounds)
31
32 signs_lib.default_text_scale = {x=10, y=10}
33
34 signs_lib.standard_yaw = {
35         0,
36         math.pi / -2,
37         math.pi,
38         math.pi / 2,
39 }
40
41 signs_lib.wallmounted_yaw = {
42         nil,
43         nil,
44         math.pi / -2,
45         math.pi / 2,
46         0,
47         math.pi,
48 }
49
50 signs_lib.fdir_to_back = {
51         {  0, -1 },
52         { -1,  0 },
53         {  0,  1 },
54         {  1,  0 },
55 }
56
57 signs_lib.wall_fdir_to_back = {
58         nil,
59         nil,
60         {  0,  1 },
61         {  0, -1 },
62         { -1,  0 },
63         {  1,  0 },
64 }
65
66 signs_lib.rotate_facedir = {
67         [0] = 1,
68         [1] = 6,
69         [2] = 3,
70         [3] = 0,
71         [4] = 2,
72         [5] = 6,
73         [6] = 4
74 }
75
76 signs_lib.rotate_walldir = {
77         [0] = 1,
78         [1] = 5,
79         [2] = 0,
80         [3] = 4,
81         [4] = 2,
82         [5] = 3
83 }
84
85 -- Initialize character texture cache
86 local ctexcache = {}
87
88 -- entity handling
89
90 minetest.register_entity("signs_lib:text", {
91         collisionbox = { 0, 0, 0, 0, 0, 0 },
92         visual = "mesh",
93         mesh = "signs_lib_standard_wall_sign_entity.obj",
94         textures = {},
95         static_save = false
96 })
97
98 function signs_lib.delete_objects(pos)
99         local objects = minetest.get_objects_inside_radius(pos, 0.5)
100         for _, v in ipairs(objects) do
101                 v:remove()
102         end
103 end
104
105 function signs_lib.spawn_entity(pos, texture)
106         local node = minetest.get_node(pos)
107         local def = minetest.registered_items[node.name]
108         if not def or not def.entity_info or not def.entity_info.yaw[node.param2 + 1] then return end
109
110         local text_scale = (node and node.text_scale) or signs_lib.default_text_scale
111         local objects = minetest.get_objects_inside_radius(pos, 0.5)
112         local obj
113
114         if #objects > 0 then
115                 obj = objects[1]
116         else
117                 obj = minetest.add_entity(pos, "signs_lib:text")
118         end
119
120         obj:setyaw(def.entity_info.yaw[node.param2 + 1])
121
122         if not texture then
123                 obj:set_properties({
124                         mesh = def.entity_info.mesh,
125                         visual_size = text_scale,
126                 })
127         else
128                 obj:set_properties({
129                         mesh = def.entity_info.mesh,
130                         visual_size = text_scale,
131                         textures={texture},
132                 })
133         end
134 end
135
136 -- rotation
137
138 function signs_lib.wallmounted_rotate(pos, node, user, mode)
139         if not signs_lib.can_modify(pos, user) then return false end
140
141         if mode ~= screwdriver.ROTATE_FACE or string.match(node.name, "_onpole") then
142                 return false
143         end
144
145         local newparam2 = signs_lib.rotate_walldir[node.param2] or 0
146
147         minetest.swap_node(pos, { name = node.name, param2 = newparam2 })
148         signs_lib.delete_objects(pos)
149         signs_lib.update_sign(pos)
150         return true
151 end
152
153 function signs_lib.facedir_rotate(pos, node, user, mode)
154         if not signs_lib.can_modify(pos, user) then return false end
155
156         if mode ~= screwdriver.ROTATE_FACE or string.match(node.name, "_onpole") then
157                 return false
158         end
159
160         local newparam2 = signs_lib.rotate_facedir[node.param2] or 0
161
162         minetest.swap_node(pos, { name = node.name, param2 = newparam2 })
163         signs_lib.delete_objects(pos)
164         signs_lib.update_sign(pos)
165         return true
166 end
167
168 -- infinite stacks
169
170 if not minetest.settings:get_bool("creative_mode") then
171         signs_lib.expect_infinite_stacks = false
172 else
173         signs_lib.expect_infinite_stacks = true
174 end
175
176 -- CONSTANTS
177
178 -- Path to the textures.
179 local TP = signs_lib.path .. "/textures"
180 -- Font file formatter
181 local CHAR_FILE = "%s_%02x.png"
182 -- Fonts path
183 local CHAR_PATH = TP .. "/" .. CHAR_FILE
184
185 -- Lots of overkill here. KISS advocates, go away, shoo! ;) -- kaeza
186
187 local PNG_HDR = string.char(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
188
189 -- check if a file does exist
190 -- to avoid reopening file after checking again
191 -- pass TRUE as second argument
192 local function file_exists(name, return_handle, mode)
193         mode = mode or "r";
194         local f = io.open(name, mode)
195         if f ~= nil then
196                 if (return_handle) then
197                         return f
198                 end
199                 io.close(f) 
200                 return true 
201         else 
202                 return false 
203         end
204 end
205
206 -- Read the image size from a PNG file.
207 -- Returns image_w, image_h.
208 -- Only the LSB is read from each field!
209 function signs_lib.read_image_size(filename)
210         local f = file_exists(filename, true, "rb")
211         -- file might not exist (don't crash the game)
212         if (not f) then
213                 return 0, 0
214         end
215         f:seek("set", 0x0)
216         local hdr = f:read(string.len(PNG_HDR))
217         if hdr ~= PNG_HDR then
218                 f:close()
219                 return
220         end
221         f:seek("set", 0x13)
222         local ws = f:read(1)
223         f:seek("set", 0x17)
224         local hs = f:read(1)
225         f:close()
226         return ws:byte(), hs:byte()
227 end
228
229 -- 4 rows, max 80 chars per, plus a bit of fudge to
230 -- avoid excess trimming (e.g. due to color codes)
231
232 local MAX_INPUT_CHARS = 400
233
234 -- helper functions to trim sign text input/output
235
236 local function trim_input(text)
237         return text:sub(1, math.min(MAX_INPUT_CHARS, text:len()))
238 end
239
240 local function build_char_db(font_size)
241
242         local cw = {}
243
244         -- To calculate average char width.
245         local total_width = 0
246         local char_count = 0
247
248         for c = 32, 255 do
249                 local w, h = signs_lib.read_image_size(CHAR_PATH:format("signs_lib_font_"..font_size.."px", c))
250                 if w and h then
251                         local ch = string.char(c)
252                         cw[ch] = w
253                         total_width = total_width + w
254                         char_count = char_count + 1
255                 end
256         end
257
258         local cbw, cbh = signs_lib.read_image_size(TP.."/signs_lib_color_"..font_size.."px_n.png")
259         assert(cbw and cbh, "error reading bg dimensions")
260         return cw, cbw, cbh, (total_width / char_count)
261 end
262
263 signs_lib.charwidth15,
264 signs_lib.colorbgw15,
265 signs_lib.lineheight15,
266 signs_lib.avgwidth15 = build_char_db(15)
267
268 signs_lib.charwidth31,
269 signs_lib.colorbgw31,
270 signs_lib.lineheight31,
271 signs_lib.avgwidth31 = build_char_db(31)
272
273 local sign_groups = {choppy=2, dig_immediate=2}
274 local fences_with_sign = { }
275
276 -- some local helper functions
277
278 local math_max = math.max
279
280 local function fill_line(x, y, w, c, font_size, colorbgw)
281         c = c or "0"
282         local tex = { }
283         for xx = 0, math.max(0, w), colorbgw do
284                 table.insert(tex, (":%d,%d=signs_lib_color_"..font_size.."px_%s.png"):format(x + xx, y, c))
285         end
286         return table.concat(tex)
287 end
288
289 -- make char texture file name
290 -- if texture file does not exist use fallback texture instead
291 local function char_tex(font_name, ch)
292         if ctexcache[font_name..ch] then
293                 return ctexcache[font_name..ch], true
294         else
295                 local c = ch:byte()
296                 local exists, tex = file_exists(CHAR_PATH:format(font_name, c))
297                 if exists and c ~= 14 then
298                         tex = CHAR_FILE:format(font_name, c)
299                 else
300                         tex = CHAR_FILE:format(font_name, 0x0)
301                 end
302                 ctexcache[font_name..ch] = tex
303                 return tex, exists
304         end
305 end
306
307 local function make_line_texture(line, lineno, pos, line_width, line_height, cwidth_tab, font_size, colorbgw)
308         local width = 0
309         local maxw = 0
310         local font_name = "signs_lib_font_"..font_size.."px"
311
312         local words = { }
313         local node = minetest.get_node(pos)
314         local def = minetest.registered_items[node.name]
315         local default_color = def.default_color or 0
316
317         local cur_color = tonumber(default_color, 16)
318
319         -- We check which chars are available here.
320         for word_i, word in ipairs(line) do
321                 local chars = { }
322                 local ch_offs = 0
323                 word = string.gsub(word, "%^[12345678abcdefgh]", {
324                         ["^1"] = string.char(0x81),
325                         ["^2"] = string.char(0x82),
326                         ["^3"] = string.char(0x83),
327                         ["^4"] = string.char(0x84),
328                         ["^5"] = string.char(0x85),
329                         ["^6"] = string.char(0x86),
330                         ["^7"] = string.char(0x87),
331                         ["^8"] = string.char(0x88),
332                         ["^a"] = string.char(0x8a),
333                         ["^b"] = string.char(0x8b),
334                         ["^c"] = string.char(0x8c),
335                         ["^d"] = string.char(0x8d),
336                         ["^e"] = string.char(0x8e),
337                         ["^f"] = string.char(0x8f),
338                         ["^g"] = string.char(0x90),
339                         ["^h"] = string.char(0x91)
340                 })
341                 local word_l = #word
342                 local i = 1
343                 while i <= word_l  do
344                         local c = word:sub(i, i)
345                         if c == "#" then
346                                 local cc = tonumber(word:sub(i+1, i+1), 16)
347                                 if cc then
348                                         i = i + 1
349                                         cur_color = cc
350                                 end
351                         else
352                                 local w = cwidth_tab[c]
353                                 if w then
354                                         width = width + w + 1
355                                         if width >= (line_width - cwidth_tab[" "]) then
356                                                 width = 0
357                                         else
358                                                 maxw = math_max(width, maxw)
359                                         end
360                                         if #chars < MAX_INPUT_CHARS then
361                                                 table.insert(chars, {
362                                                         off = ch_offs,
363                                                         tex = char_tex(font_name, c),
364                                                         col = ("%X"):format(cur_color),
365                                                 })
366                                         end
367                                         ch_offs = ch_offs + w
368                                 end
369                         end
370                         i = i + 1
371                 end
372                 width = width + cwidth_tab[" "] + 1
373                 maxw = math_max(width, maxw)
374                 table.insert(words, { chars=chars, w=ch_offs })
375         end
376
377         -- Okay, we actually build the "line texture" here.
378
379         local texture = { }
380
381         local start_xpos = math.floor((line_width - maxw) / 2) + def.x_offset
382
383         local xpos = start_xpos
384         local ypos = (line_height + def.line_spacing)* lineno + def.y_offset
385
386         cur_color = nil
387
388         for word_i, word in ipairs(words) do
389                 local xoffs = (xpos - start_xpos)
390                 if (xoffs > 0) and ((xoffs + word.w) > maxw) then
391                         table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
392                         xpos = start_xpos
393                         ypos = ypos + line_height + def.line_spacing
394                         lineno = lineno + 1
395                         if lineno >= def.number_of_lines then break end
396                         table.insert(texture, fill_line(xpos, ypos, maxw, cur_color, font_size, colorbgw))
397                 end
398                 for ch_i, ch in ipairs(word.chars) do
399                         if ch.col ~= cur_color then
400                                 cur_color = ch.col
401                                 table.insert(texture, fill_line(xpos + ch.off, ypos, maxw, cur_color, font_size, colorbgw))
402                         end
403                         table.insert(texture, (":%d,%d=%s"):format(xpos + ch.off, ypos, ch.tex))
404                 end
405                 table.insert(
406                         texture, 
407                         (":%d,%d="):format(xpos + word.w, ypos) .. char_tex(font_name, " ")
408                 )
409                 xpos = xpos + word.w + cwidth_tab[" "]
410                 if xpos >= (line_width + cwidth_tab[" "]) then break end
411         end
412
413         table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
414         table.insert(texture, fill_line(start_xpos, ypos + line_height, maxw, "n", font_size, colorbgw))
415
416         return table.concat(texture), lineno
417 end
418
419 local function make_sign_texture(lines, pos)
420         local node = minetest.get_node(pos)
421         local def = minetest.registered_items[node.name]
422         if not def or not def.entity_info then return end
423
424         local font_size
425         local line_width
426         local line_height
427         local char_width
428         local colorbgw
429
430         if def.font_size and def.font_size == 31 then
431                 font_size = 31
432                 line_width = math.floor(signs_lib.avgwidth31 * def.chars_per_line) * def.horiz_scaling
433                 line_height = signs_lib.lineheight31
434                 char_width = signs_lib.charwidth31
435                 colorbgw = signs_lib.colorbgw31
436         else
437                 font_size = 15
438                 line_width = math.floor(signs_lib.avgwidth15 * def.chars_per_line) * def.horiz_scaling
439                 line_height = signs_lib.lineheight15
440                 char_width = signs_lib.charwidth15
441                 colorbgw = signs_lib.colorbgw15
442         end
443
444         local texture = { ("[combine:%dx%d"):format(line_width, (line_height + def.line_spacing) * def.number_of_lines * def.vert_scaling) }
445
446         local lineno = 0
447         for i = 1, #lines do
448                 if lineno >= def.number_of_lines then break end
449                 local linetex, ln = make_line_texture(lines[i], lineno, pos, line_width, line_height, char_width, font_size, colorbgw)
450                 table.insert(texture, linetex)
451                 lineno = ln + 1
452         end
453         table.insert(texture, "^[makealpha:0,0,0")
454         return table.concat(texture, "")
455 end
456
457 function signs_lib.split_lines_and_words(text)
458         if not text then return end
459         local lines = { }
460         for _, line in ipairs(text:split("\n")) do
461                 table.insert(lines, line:split(" "))
462         end
463         return lines
464 end
465
466 function signs_lib.set_obj_text(pos, text)
467         local split = signs_lib.split_lines_and_words
468         local text_ansi = Utf8ToAnsi(text)
469         local n = minetest.registered_nodes[minetest.get_node(pos).name]
470         signs_lib.delete_objects(pos)
471         signs_lib.spawn_entity(pos, make_sign_texture(split(text_ansi), pos))
472 end
473
474 local function make_widefont_nodename(name)
475         if string.find(name, "_widefont") then return name end
476         if string.find(name, "_onpole")  then
477                 return string.gsub(name, "_onpole", "_widefont_onpole")
478         elseif string.find(name, "_hanging") then
479                 return string.gsub(name, "_hanging", "_widefont_hanging")
480         else
481                 return name.."_widefont"
482         end
483 end
484
485 function signs_lib.construct_sign(pos)
486         local form = "size[6,4]"..
487                 "textarea[0,-0.3;6.5,3;text;;${text}]"..
488                 "background[-0.5,-0.5;7,5;signs_lib_sign_bg.jpg]"
489         local node = minetest.get_node(pos)
490         local wname = make_widefont_nodename(node.name)
491
492         if minetest.registered_items[wname] then
493                 local state = "off"
494                 if string.find(node.name, "widefont") then state = "on" end
495                 form = form.."label[1,3.4;Use wide font]"..
496                         "image_button[1.1,3.7;1,0.6;signs_lib_switch_"..
497                         state..".png;"..
498                         state..";;;false;signs_lib_switch_interm.png]"..
499                         "button_exit[3,3.4;2,1;ok;"..S("Write").."]"
500         else
501                 form = form.."button_exit[2,3.4;2,1;ok;"..S("Write").."]"
502         end
503
504         local meta = minetest.get_meta(pos)
505         meta:set_string("formspec", form)
506         local i = meta:get_string("infotext")
507         if i == "" then -- it wasn't even set, so set it.
508                 meta:set_string("infotext", "")
509         end
510 end
511
512 function signs_lib.destruct_sign(pos)
513         signs_lib.delete_objects(pos)
514 end
515
516 local function make_infotext(text)
517         text = trim_input(text)
518         local lines = signs_lib.split_lines_and_words(text) or {}
519         local lines2 = { }
520         for _, line in ipairs(lines) do
521                 table.insert(lines2, (table.concat(line, " "):gsub("#[0-9a-fA-F]", ""):gsub("##", "#")))
522         end
523         return table.concat(lines2, "\n")
524 end
525
526 function signs_lib.update_sign(pos, fields)
527         local meta = minetest.get_meta(pos)
528
529         local text = fields and fields.text or meta:get_string("text")
530         text = trim_input(text)
531
532         local owner = meta:get_string("owner")
533         local ownstr = ""
534         if owner ~= "" then ownstr = S("Locked sign, owned by @1\n", owner) end
535
536         meta:set_string("text", text)
537         meta:set_string("infotext", ownstr..make_infotext(text).." ")
538         signs_lib.set_obj_text(pos, text)
539 end
540
541 function signs_lib.receive_fields(pos, formname, fields, sender)
542
543         if not fields or not signs_lib.can_modify(pos, sender) then return end
544
545         if fields.text and fields.ok then
546                 minetest.log("action", S("@1 wrote \"@2\" to sign at @3",
547                         (sender:get_player_name() or ""),
548                         fields.text:gsub('\\', '\\\\'):gsub("\n", "\\n"),
549                         minetest.pos_to_string(pos)
550                 ))
551                 signs_lib.update_sign(pos, fields)
552         elseif fields.on or fields.off then
553                 local node = minetest.get_node(pos)
554                 local newname
555
556                 if fields.on and string.find(node.name, "widefont") then
557                         newname = string.gsub(node.name, "_widefont", "")
558                 elseif fields.off and not string.find(node.name, "widefont") then
559                         newname = make_widefont_nodename(node.name)
560                 end
561                 if newname then
562                         minetest.log("action", S("@1 flipped the wide-font switch to \"@2\" at @3",
563                                 (sender:get_player_name() or ""),
564                                 (fields.on and "off" or "on"),
565                                 minetest.pos_to_string(pos)
566                         ))
567
568                         minetest.swap_node(pos, {name = newname, param2 = node.param2})
569                         signs_lib.construct_sign(pos)
570                         signs_lib.update_sign(pos, fields)
571                 end
572         end
573 end
574
575 function signs_lib.can_modify(pos, player)
576         local meta = minetest.get_meta(pos)
577         local owner = meta:get_string("owner")
578         local playername = player:get_player_name()
579
580         if minetest.is_protected(pos, playername) then 
581                 minetest.record_protection_violation(pos, playername)
582                 return false
583         end
584
585         if owner == ""
586           or playername == owner
587           or (minetest.check_player_privs(playername, {sign_editor=true}))
588           or (playername == minetest.settings:get("name")) then
589                 return true
590         end
591         minetest.record_protection_violation(pos, playername)
592         return false
593 end
594
595 -- make selection boxes
596 -- sizex/sizey specified in inches because that's what MUTCD uses.
597
598 function signs_lib.make_selection_boxes(sizex, sizey, foo, xoffs, yoffs, zoffs, is_facedir)
599
600         local tx = (sizex * 0.0254 ) / 2
601         local ty = (sizey * 0.0254 ) / 2
602         local xo = xoffs and xoffs * 0.0254 or 0
603         local yo = yoffs and yoffs * 0.0254 or 0
604         local zo = zoffs and zoffs * 0.0254 or 0
605
606         if not is_facedir then
607                 return {
608                         type = "wallmounted",
609                         wall_side =   { -0.5 + zo, -ty + yo, -tx + xo, -0.4375 + zo, ty + yo, tx + xo },
610                         wall_top =    { -tx - xo, 0.5 + zo, -ty + yo, tx - xo, 0.4375 + zo, ty + yo},
611                         wall_bottom = { -tx - xo, -0.5 + zo, -ty + yo, tx - xo, -0.4375 + zo, ty + yo }
612                 }
613         else
614                 return {
615                         type = "fixed",
616                         fixed = { -tx + xo, -ty + yo, 0.5 + zo, tx + xo, ty + yo, 0.4375 + zo}
617                 }
618         end
619 end
620
621 function signs_lib.check_for_pole(pos, pointed_thing)
622         local ppos = minetest.get_pointed_thing_position(pointed_thing)
623         local pnode = minetest.get_node(ppos)
624         local pdef = minetest.registered_items[pnode.name]
625
626         if (signs_lib.allowed_poles[pnode.name]
627                   or (pdef and pdef.drawtype == "fencelike")
628                   or string.find(pnode.name, "default:fence_")
629                   or string.find(pnode.name, "_post")
630                   or string.find(pnode.name, "fencepost")
631                   or string.find(pnode.name, "streets:streetlamp_basic_top")
632                   or (pnode.name == "streets:bigpole" and pnode.param2 < 4)
633                   or (pnode.name == "streets:bigpole" and pnode.param2 > 19 and pnode.param2 < 24)
634                 )
635           and
636                 (pos.x ~= ppos.x or pos.z ~= ppos.z) then
637                 return true
638         end
639 end
640
641 function signs_lib.check_for_ceiling(pointed_thing)
642         if pointed_thing.above.x == pointed_thing.under.x
643           and pointed_thing.above.z == pointed_thing.under.z
644           and pointed_thing.above.y < pointed_thing.under.y then
645                 return true
646         end
647 end
648
649 function signs_lib.after_place_node(pos, placer, itemstack, pointed_thing, locked)
650         local playername = placer:get_player_name()
651         local def = minetest.registered_items[itemstack:get_name()]
652
653         local ppos = minetest.get_pointed_thing_position(pointed_thing)
654         local pnode = minetest.get_node(ppos)
655         local pdef = minetest.registered_items[pnode.name]
656
657         if (def.allow_onpole ~= false) and signs_lib.check_for_pole(pos, pointed_thing) then
658                 local node = minetest.get_node(pos)
659                 minetest.swap_node(pos, {name = itemstack:get_name().."_onpole", param2 = node.param2})
660         elseif def.allow_hanging and signs_lib.check_for_ceiling(pointed_thing) then
661                 local newparam2 = minetest.dir_to_facedir(placer:get_look_dir())
662                 local node = minetest.get_node(pos)
663                 minetest.swap_node(pos, {name = itemstack:get_name().."_hanging", param2 = newparam2})
664         end
665         if locked then
666                 local meta = minetest.get_meta(pos)
667                 meta:set_string("owner", playername)
668                 meta:set_string("infotext", S("Locked sign, owned by @1\n", playername))
669         end
670 end
671
672 function signs_lib.register_fence_with_sign()
673         minetest.log("warning", "[signs_lib] ".."Attempt to call no longer used function signs_lib.register_fence_with_sign()")
674 end
675
676 local function register_sign(name, rdef)
677         local def = table.copy(rdef)
678
679         if rdef.entity_info == "standard" then
680                 def.entity_info = {
681                         mesh = "signs_lib_standard_wall_sign_entity.obj",
682                         yaw = signs_lib.wallmounted_yaw
683                 }
684         elseif rdef.entity_info then
685                 def.entity_info = rdef.entity_info
686         end
687
688         def.after_place_node = rdef.after_place_node or signs_lib.after_place_node
689
690         if rdef.entity_info then
691                 def.on_rightclick       = rdef.on_rightclick       or signs_lib.construct_sign
692                 def.on_construct        = rdef.on_construct        or signs_lib.construct_sign
693                 def.on_destruct         = rdef.on_destruct         or signs_lib.destruct_sign
694                 def.on_receive_fields   = rdef.on_receive_fields   or signs_lib.receive_fields
695                 def.on_punch            = rdef.on_punch            or signs_lib.update_sign
696                 def.number_of_lines     = rdef.number_of_lines     or signs_lib.standard_lines
697                 def.horiz_scaling       = rdef.horiz_scaling       or signs_lib.standard_hscale
698                 def.vert_scaling        = rdef.vert_scaling        or signs_lib.standard_vscale
699                 def.line_spacing        = rdef.line_spacing        or signs_lib.standard_lspace
700                 def.font_size           = rdef.font_size           or signs_lib.standard_fsize
701                 def.x_offset            = rdef.x_offset            or signs_lib.standard_xoffs
702                 def.y_offset            = rdef.y_offset            or signs_lib.standard_yoffs
703                 def.chars_per_line      = rdef.chars_per_line      or signs_lib.standard_cpl
704                 def.default_color       = rdef.default_color       or "0"
705                 if rdef.locked and not rdef.after_place_node then
706                         def.after_place_node = function(pos, placer, itemstack, pointed_thing)
707                                 signs_lib.after_place_node(pos, placer, itemstack, pointed_thing, true)
708                         end
709                 end
710         end
711
712         def.paramtype           = rdef.paramtype           or "light"
713         def.drawtype            = rdef.drawtype            or "mesh"
714         def.mesh                = rdef.mesh                or "signs_lib_standard_wall_sign.obj"
715         def.wield_image         = rdef.wield_image         or def.inventory_image
716         def.drop                = rdef.drop                or name
717         def.sounds              = rdef.sounds              or signs_lib.standard_wood_sign_sounds
718         def.on_rotate           = rdef.on_rotate           or signs_lib.wallmounted_rotate
719         def.paramtype2          = rdef.paramtype2          or "wallmounted"
720
721         if rdef.on_rotate then
722                 def.on_rotate = rdef.on_rotate
723         elseif rdef.drawtype == "wallmounted" then
724                 def.on_rotate = signs_lib.wallmounted_rotate
725         else
726                 def.on_rotate = signs_lib.facedir_rotate
727         end
728
729         if rdef.groups then
730                 def.groups = rdef.groups
731         else
732                 def.groups = signs_lib.standard_wood_groups
733         end
734
735         local cbox = signs_lib.make_selection_boxes(35, 25, allow_onpole)
736
737         def.selection_box = rdef.selection_box or cbox
738         def.node_box      = table.copy(rdef.node_box or rdef.selection_box or cbox)
739
740         if def.sunlight_propagates ~= false then
741                 def.sunlight_propagates = true
742         end
743
744         minetest.register_node(":"..name, def)
745         table.insert(signs_lib.lbm_restore_nodes, name)
746
747         if rdef.allow_onpole ~= false then
748
749                 local opdef = table.copy(def)
750
751                 local offset = 0.3125
752                 if opdef.uses_slim_pole_mount then
753                         offset = 0.35
754                 end
755
756                 opdef.selection_box = rdef.onpole_selection_box or opdef.selection_box
757                 opdef.node_box = rdef.onpole_node_box or opdef.selection_box
758
759                 if opdef.paramtype2 == "wallmounted" then
760                         opdef.node_box.wall_side[1] = def.node_box.wall_side[1] - offset
761                         opdef.node_box.wall_side[4] = def.node_box.wall_side[4] - offset
762
763                         opdef.selection_box.wall_side[1] = def.selection_box.wall_side[1] - offset
764                         opdef.selection_box.wall_side[4] = def.selection_box.wall_side[4] - offset
765                 else
766                         opdef.node_box.fixed[3] = def.node_box.fixed[3] + offset
767                         opdef.node_box.fixed[6] = def.node_box.fixed[6] + offset
768
769                         opdef.selection_box.fixed[3] = def.selection_box.fixed[3] + offset
770                         opdef.selection_box.fixed[6] = def.selection_box.fixed[6] + offset
771                 end
772
773                 opdef.groups.not_in_creative_inventory = 1
774                 opdef.tiles[3] = "signs_lib_pole_mount.png"
775                 opdef.mesh = string.gsub(opdef.mesh, ".obj$", "_onpole.obj")
776                 opdef.on_rotate = nil
777
778
779                 if opdef.entity_info then
780                         opdef.entity_info.mesh = string.gsub(opdef.entity_info.mesh, ".obj$", "_onpole.obj")
781                 end
782                 minetest.register_node(":"..name.."_onpole", opdef)
783                 table.insert(signs_lib.lbm_restore_nodes, name.."_onpole")
784         end
785
786         if rdef.allow_hanging then
787
788                 local hdef = table.copy(def)
789                 hdef.paramtype2 = "facedir"
790
791                 local hcbox = signs_lib.make_selection_boxes(35, 32, false, 0, 3, -18.5, true)
792
793                 hdef.selection_box = rdef.hanging_selection_box or hcbox
794                 hdef.node_box = rdef.hanging_node_box or rdef.hanging_selection_box or hcbox
795
796                 hdef.groups.not_in_creative_inventory = 1
797                 hdef.tiles[3] = "signs_lib_hangers.png"
798                 hdef.mesh = string.gsub(string.gsub(hdef.mesh, "_facedir.obj", ".obj"), ".obj$", "_hanging.obj")
799                 hdef.on_rotate = nil
800
801                 if hdef.entity_info then
802                         hdef.entity_info.mesh = string.gsub(string.gsub(hdef.entity_info.mesh, "_facedir.obj", ".obj"), ".obj$", "_hanging.obj")
803                         hdef.entity_info.yaw = signs_lib.standard_yaw
804                 end
805
806                 minetest.register_node(":"..name.."_hanging", hdef)
807                 table.insert(signs_lib.lbm_restore_nodes, name.."_hanging")
808         end
809 end
810
811 --[[
812 The main sign registration function
813 ===================================
814
815 Example minimal recommended def for writable signs:
816
817 signs_lib.register_sign("foo:my_cool_sign", {
818         description = "Wooden cool sign",
819         inventory_image = "signs_lib_sign_cool_inv.png",
820         tiles = {
821                 "signs_lib_sign_cool.png",
822                 "signs_lib_sign_cool_edges.png"
823         },
824         number_of_lines = 2,
825         horiz_scaling = 0.8,
826         vert_scaling = 1,
827         line_spacing = 9,
828         font_size = 31,
829         x_offset = 7,
830         y_offset = 4,
831         chars_per_line = 40,
832         entity_info = "standard"
833 })
834
835 * default def assumes a wallmounted sign with on-pole being allowed.
836
837 *For signs that can't support onpole, include in the def:
838         allow_onpole = false,
839
840 * "standard" entity info implies the standard wood/steel sign model, in
841   wallmounted mode.  For facedir signs using the standard model, use:
842
843         entity_info = {
844                 mesh = "signs_lib_standard_wall_sign_entity.obj",
845                 yaw = signs_lib.standard_yaw
846         },
847
848 ]]--
849
850 function signs_lib.register_sign(name, rdef)
851         register_sign(name, rdef)
852
853         if rdef.allow_widefont then
854
855                 wdef = table.copy(minetest.registered_items[name])
856                 wdef.groups.not_in_creative_inventory = 1
857                 wdef.horiz_scaling = wdef.horiz_scaling / 2
858
859                 register_sign(name.."_widefont", wdef)
860         end
861 end
862
863 -- restore signs' text after /clearobjects and the like, the next time
864 -- a block is reloaded by the server.
865
866 minetest.register_lbm({
867         nodenames = signs_lib.lbm_restore_nodes,
868         name = "signs_lib:restore_sign_text",
869         label = "Restore sign text",
870         run_at_every_load = true,
871         action = function(pos, node)
872                 signs_lib.update_sign(pos,nil,nil,node)
873         end
874 })
875
876 -- Convert old signs on fenceposts into signs on.. um.. fence posts :P
877
878 minetest.register_lbm({
879         nodenames = signs_lib.old_fenceposts_with_signs,
880         name = "signs_lib:fix_fencepost_signs",
881         label = "Change single-node signs on fences into normal",
882         run_at_every_load = true,
883         action = function(pos, node)
884
885                 local fdir = node.param2 % 8
886                 local signpos = {
887                         x = pos.x + signs_lib.fdir_to_back[fdir+1][1],
888                         y = pos.y,
889                         z = pos.z + signs_lib.fdir_to_back[fdir+1][2]
890                 }
891
892                 if minetest.get_node(signpos).name == "air" then
893                         local new_wmdir = minetest.dir_to_wallmounted(minetest.facedir_to_dir(fdir))
894                         local oldfence =  signs_lib.old_fenceposts[node.name]
895                         local newsign =   signs_lib.old_fenceposts_replacement_signs[node.name]
896
897                         signs_lib.delete_objects(pos)
898
899                         local oldmeta = minetest.get_meta(pos):to_table()
900                         minetest.set_node(pos, {name = oldfence})
901                         minetest.set_node(signpos, { name = newsign, param2 = new_wmdir })
902                         local newmeta = minetest.get_meta(signpos)
903                         newmeta:from_table(oldmeta)
904                         signs_lib.update_sign(signpos)
905                 end
906         end
907 })
908
909 signs_lib.block_list = {}
910 signs_lib.totalblocks = 0
911
912 -- Maintain a list of currently-loaded blocks
913 minetest.register_lbm({
914         nodenames = {"group:sign"},
915         name = "signs_lib:update_block_list",
916         label = "Update list of loaded blocks, log only those with signs",
917         run_at_every_load = true,
918         action = function(pos, node)
919                 -- yeah, yeah... I know I'm hashing a block pos, but it's still just a set of coords
920                 local hash = minetest.hash_node_position(vector.floor(vector.divide(pos, core.MAP_BLOCKSIZE)))
921                 if not signs_lib.block_list[hash] then
922                         signs_lib.block_list[hash] = true
923                         signs_lib.totalblocks = signs_lib.totalblocks + 1
924                 end
925         end
926 })
927
928 minetest.register_chatcommand("regen_signs", {
929         params = "",
930         privs = {server = true},
931         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.",
932         func = function(player_name, params)
933                 local allsigns = {}
934                 local totalsigns = 0
935                 for b in pairs(signs_lib.block_list) do
936                         local blockpos = minetest.get_position_from_hash(b)
937                         local pos1 = vector.multiply(blockpos, core.MAP_BLOCKSIZE)
938                         local pos2 = vector.add(pos1, core.MAP_BLOCKSIZE - 1)
939                         if minetest.get_node_or_nil(vector.add(pos1, core.MAP_BLOCKSIZE/2)) then
940                                 local signs_in_block = minetest.find_nodes_in_area(pos1, pos2, {"group:sign"})
941                                 allsigns[#allsigns + 1] = signs_in_block
942                                 totalsigns = totalsigns + #signs_in_block
943                         else
944                                 signs_lib.block_list[b] = nil -- if the block is no longer loaded, remove it from the table
945                                 signs_lib.totalblocks = signs_lib.totalblocks - 1
946                         end
947                 end
948                 if signs_lib.totalblocks < 0 then signs_lib.totalblocks = 0 end
949                 if totalsigns == 0 then
950                         minetest.chat_send_player(player_name, "There are no signs in the currently-loaded terrain.")
951                         signs_lib.block_list = {}
952                         return
953                 end
954
955                 minetest.chat_send_player(player_name, "Found a total of "..totalsigns.." sign nodes across "..signs_lib.totalblocks.." blocks.")
956                 minetest.chat_send_player(player_name, "Regenerating sign entities...")
957
958                 for _, b in pairs(allsigns) do
959                         for _, pos in ipairs(b) do
960                                 signs_lib.delete_objects(pos)
961                                 local node = minetest.get_node(pos)
962                                 local def = minetest.registered_items[node.name]
963                                 if def and def.entity_info then
964                                         signs_lib.update_sign(pos)
965                                 end
966                         end
967                 end
968                 minetest.chat_send_player(player_name, "Finished.")
969         end
970 })