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