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