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