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