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