]> git.lizzy.rs Git - signs_lib.git/blob - init.lua
Cache character textures
[signs_lib.git] / init.lua
1 -- This mod provides the visible text on signs library used by Home Decor
2 -- and perhaps other mods at some point in the future.  Forked from thexyz's/
3 -- PilzAdam's original text-on-signs mod and rewritten by Vanessa Ezekowitz
4 -- and Diego Martinez
5
6 -- textpos = {
7 --              { delta = {entity position for 0° yaw}, exact yaw expression }
8 --              { delta = {entity position for 180° yaw}, exact yaw expression }
9 --              { delta = {entity position for 270° yaw}, exact yaw expression }
10 --              { delta = {entity position for 90° yaw}, exact yaw expression }
11 -- }
12 -- Made colored metal signs optionals
13 local enable_colored_metal_signs = true
14
15 -- CWz's keyword interact mod uses this setting.
16 local current_keyword = minetest.settings:get("interact_keyword") or "iaccept"
17
18 signs_lib = {}
19 signs_lib.path = minetest.get_modpath(minetest.get_current_modname())
20 screwdriver = screwdriver or {}
21
22 -- Load support for intllib.
23 local S, NS = dofile(signs_lib.path .. "/intllib.lua")
24 signs_lib.gettext = S
25
26 -- text encoding
27 dofile(signs_lib.path .. "/encoding.lua");
28
29 -- Initialize character texture cache
30 local ctexcache = {}
31
32
33 local wall_dir_change = {
34         [0] = 4,
35         0,
36         5,
37         1,
38         2,
39         3,
40         0
41 }
42
43 signs_lib.wallmounted_rotate = function(pos, node, user, mode)
44         if mode ~= screwdriver.ROTATE_FACE then return false end 
45         minetest.swap_node(pos, { name = node.name, param2 = wall_dir_change[node.param2 % 6] })
46         signs_lib.update_sign(pos,nil,nil,node)
47         return true
48 end
49
50 signs_lib.facedir_rotate = function(pos, node, user, mode)
51         if mode ~= screwdriver.ROTATE_FACE then return false end
52         local newparam2 = (node.param2 %8) + 1
53         if newparam2 == 5 then
54                 newparam2 = 6
55         elseif newparam2 > 6 then
56                 newparam2 = 0
57         end
58         minetest.swap_node(pos, { name = node.name, param2 = newparam2 })
59         signs_lib.update_sign(pos,nil,nil,node)
60         return true
61 end
62
63 signs_lib.facedir_rotate_simple = function(pos, node, user, mode)
64         if mode ~= screwdriver.ROTATE_FACE then return false end
65         local newparam2 = (node.param2 %8) + 1
66         if newparam2 > 3 then newparam2 = 0 end
67         minetest.swap_node(pos, { name = node.name, param2 = newparam2 })
68         signs_lib.update_sign(pos,nil,nil,node)
69         return true
70 end
71
72
73 signs_lib.modpath = minetest.get_modpath("signs_lib")
74
75 local DEFAULT_TEXT_SCALE = {x=0.8, y=0.5}
76
77 signs_lib.regular_wall_sign_model = {
78         nodebox = {
79                 type = "wallmounted",
80                 wall_side =   { -0.5,    -0.25,   -0.4375, -0.4375,  0.375,  0.4375 },
81                 wall_bottom = { -0.4375, -0.5,    -0.25,    0.4375, -0.4375, 0.375 },
82                 wall_top =    { -0.4375,  0.4375, -0.375,   0.4375,  0.5,    0.25 }
83         },
84         textpos = {
85                 nil,
86                 nil,
87                 {delta = { x =  0.41, y = 0.07, z =  0    }, yaw = math.pi / -2},
88                 {delta = { x = -0.41, y = 0.07, z =  0    }, yaw = math.pi / 2},
89                 {delta = { x =  0,    y = 0.07, z =  0.41 }, yaw = 0},
90                 {delta = { x =  0,    y = 0.07, z = -0.41 }, yaw = math.pi},
91         }
92 }
93
94 signs_lib.metal_wall_sign_model = {
95         nodebox = {
96                 type = "fixed",
97                 fixed = {-0.4375, -0.25, 0.4375, 0.4375, 0.375, 0.5}
98         },
99         textpos = {
100                 {delta = { x =  0,     y = 0.07, z =  0.41 }, yaw = 0},
101                 {delta = { x =  0.41,  y = 0.07, z =  0    }, yaw = math.pi / -2},
102                 {delta = { x =  0,     y = 0.07, z = -0.41 }, yaw = math.pi},
103                 {delta = { x = -0.41,  y = 0.07, z =  0    }, yaw = math.pi / 2},
104         }
105 }
106
107 signs_lib.yard_sign_model = {
108         nodebox = {
109                 type = "fixed",
110                 fixed = {
111                                 {-0.4375, -0.25, -0.0625, 0.4375, 0.375, 0},
112                                 {-0.0625, -0.5, -0.0625, 0.0625, -0.1875, 0},
113                 }
114         },
115         textpos = {
116                 {delta = { x =  0,    y = 0.07, z = -0.08 }, yaw = 0},
117                 {delta = { x = -0.08, y = 0.07, z =  0    }, yaw = math.pi / -2},
118                 {delta = { x =  0,    y = 0.07, z =  0.08 }, yaw = math.pi},
119                 {delta = { x =  0.08, y = 0.07, z =  0    }, yaw = math.pi / 2},
120         }
121 }
122
123 signs_lib.hanging_sign_model = {
124         nodebox = {
125                 type = "fixed",
126                 fixed = {
127                                 {-0.4375, -0.3125, -0.0625, 0.4375, 0.3125, 0},
128                                 {-0.4375, 0.25, -0.03125, 0.4375, 0.5, -0.03125},
129                 }
130         },
131         textpos = {
132                 {delta = { x =  0,    y = -0.02, z = -0.08 }, yaw = 0},
133                 {delta = { x = -0.08, y = -0.02, z =  0    }, yaw = math.pi / -2},
134                 {delta = { x =  0,    y = -0.02, z =  0.08 }, yaw = math.pi},
135                 {delta = { x =  0.08, y = -0.02, z =  0    }, yaw = math.pi / 2},
136         }
137 }
138
139 signs_lib.sign_post_model = {
140         nodebox = {
141                 type = "fixed",
142                 fixed = {
143                                 {-0.4375, -0.25, -0.1875, 0.4375, 0.375, -0.125},
144                                 {-0.125, -0.5, -0.125, 0.125, 0.5, 0.125},
145                 }
146         },
147         textpos = {
148                 {delta = { x = 0,    y = 0.07, z = -0.2 }, yaw = 0},
149                 {delta = { x = -0.2, y = 0.07, z = 0    }, yaw = math.pi / -2},
150                 {delta = { x = 0,    y = 0.07, z = 0.2  }, yaw = math.pi},
151                 {delta = { x = 0.2,  y = 0.07, z = 0    }, yaw = math.pi / 2},
152         }
153 }
154
155 -- the list of standard sign nodes
156
157 signs_lib.sign_node_list = {
158         "default:sign_wall_wood",
159         "default:sign_wall_steel",
160         "signs:sign_yard",
161         "signs:sign_hanging",
162         "signs:sign_wall_green",
163         "signs:sign_wall_yellow",
164         "signs:sign_wall_red",
165         "signs:sign_wall_white_red",
166         "signs:sign_wall_white_black",
167         "signs:sign_wall_orange",
168         "signs:sign_wall_blue",
169         "signs:sign_wall_brown",
170         "locked_sign:sign_wall_locked"
171 }
172
173 local default_sign, default_sign_image
174
175 -- Default sign was renamed in 0.4.14. Support both & old versions.
176 if minetest.registered_nodes["default:sign_wall_wood"] then
177         default_sign = "default:sign_wall_wood"
178         default_sign_image = "default_sign_wood.png"
179 else
180         default_sign = "default:sign_wall"
181         default_sign_image = "default_sign_wall.png"
182 end
183
184 default_sign_metal = "default:sign_wall_steel"
185 default_sign_metal_image = "default_sign_steel.png"
186
187 --table copy
188
189 function signs_lib.table_copy(t)
190         local nt = { }
191         for k, v in pairs(t) do
192                 if type(v) == "table" then
193                         nt[k] = signs_lib.table_copy(v)
194                 else
195                         nt[k] = v
196                 end
197         end
198         return nt
199 end
200
201 -- infinite stacks
202
203 if not minetest.settings:get_bool("creative_mode") then
204         signs_lib.expect_infinite_stacks = false
205 else
206         signs_lib.expect_infinite_stacks = true
207 end
208
209 -- CONSTANTS
210
211 -- Path to the textures.
212 local TP = signs_lib.path .. "/textures"
213 -- Font file formatter
214 local CHAR_FILE = "%s_%02x.png"
215 -- Fonts path
216 local CHAR_PATH = TP .. "/" .. CHAR_FILE
217
218 -- Font name.
219 local font_name = "hdf"
220
221 -- Lots of overkill here. KISS advocates, go away, shoo! ;) -- kaeza
222
223 local PNG_HDR = string.char(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
224
225 -- check if a file does exist
226 -- to avoid reopening file after checking again
227 -- pass TRUE as second argument
228 function file_exists(name, return_handle, mode)
229         mode = mode or "r";
230         local f = io.open(name, mode)
231         if f ~= nil then
232                 if (return_handle) then
233                         return f
234                 end
235                 io.close(f) 
236                 return true 
237         else 
238                 return false 
239         end
240 end
241
242 -- Read the image size from a PNG file.
243 -- Returns image_w, image_h.
244 -- Only the LSB is read from each field!
245 local function read_image_size(filename)
246         local f = file_exists(filename, true, "rb")
247         -- file might not exist (don't crash the game)
248         if (not f) then
249                 return 0, 0
250         end
251         f:seek("set", 0x0)
252         local hdr = f:read(string.len(PNG_HDR))
253         if hdr ~= PNG_HDR then
254                 f:close()
255                 return
256         end
257         f:seek("set", 0x13)
258         local ws = f:read(1)
259         f:seek("set", 0x17)
260         local hs = f:read(1)
261         f:close()
262         return ws:byte(), hs:byte()
263 end
264
265 -- Set by build_char_db()
266 local LINE_HEIGHT
267 local SIGN_WIDTH
268 local COLORBGW, COLORBGH
269
270 -- Size of the canvas, in characters.
271 -- Please note that CHARS_PER_LINE is multiplied by the average character
272 -- width to get the total width of the canvas, so for proportional fonts,
273 -- either more or fewer characters may fit on a line.
274 local CHARS_PER_LINE = 30
275 local NUMBER_OF_LINES = 6
276
277 -- 6 rows, max 80 chars per, plus a bit of fudge to
278 -- avoid excess trimming (e.g. due to color codes)
279
280 local MAX_INPUT_CHARS = 600
281
282 -- This holds the individual character widths.
283 -- Indexed by the actual character (e.g. charwidth["A"])
284 local charwidth
285
286 -- helper functions to trim sign text input/output
287
288 local function trim_input(text)
289         return text:sub(1, math.min(MAX_INPUT_CHARS, text:len()))
290 end
291
292 local function build_char_db()
293
294         charwidth = { }
295
296         -- To calculate average char width.
297         local total_width = 0
298         local char_count = 0
299
300         for c = 32, 255 do
301                 local w, h = read_image_size(CHAR_PATH:format(font_name, c))
302                 if w and h then
303                         local ch = string.char(c)
304                         charwidth[ch] = w
305                         total_width = total_width + w
306                         char_count = char_count + 1
307                 end
308         end
309
310         COLORBGW, COLORBGH = read_image_size(TP.."/slc_n.png")
311         assert(COLORBGW and COLORBGH, "error reading bg dimensions")
312         LINE_HEIGHT = COLORBGH
313
314         -- XXX: Is there a better way to calc this?
315         SIGN_WIDTH = math.floor((total_width / char_count) * CHARS_PER_LINE)
316
317 end
318
319 local sign_groups = {choppy=2, dig_immediate=2}
320
321 local fences_with_sign = { }
322
323 -- some local helper functions
324
325 local function split_lines_and_words_old(text)
326         local lines = { }
327         local line = { }
328         if not text then return end
329         for word in text:gmatch("%S+") do
330                 if word == "|" then
331                         table.insert(lines, line)
332                         if #lines >= NUMBER_OF_LINES then break end
333                         line = { }
334                 elseif word == "\\|" then
335                         table.insert(line, "|")
336                 else
337                         table.insert(line, word)
338                 end
339         end
340         table.insert(lines, line)
341         return lines
342 end
343
344 local function split_lines_and_words(text)
345         if not text then return end
346         text = string.gsub(text, "@KEYWORD", current_keyword)
347         local lines = { }
348         for _, line in ipairs(text:split("\n")) do
349                 table.insert(lines, line:split(" "))
350         end
351         return lines
352 end
353
354 local math_max = math.max
355
356 local function fill_line(x, y, w, c)
357         c = c or "0"
358         local tex = { }
359         for xx = 0, math.max(0, w), COLORBGW do
360                 table.insert(tex, (":%d,%d=slc_%s.png"):format(x + xx, y, c))
361         end
362         return table.concat(tex)
363 end
364
365 -- make char texture file name
366 -- if texture file does not exist use fallback texture instead
367 local function char_tex(font_name, ch)
368         if ctexcache[font_name..ch] then
369                 return ctexcache[font_name..ch], true
370         else
371                 local c = ch:byte()
372                 local exists, tex = file_exists(CHAR_PATH:format(font_name, c))
373                 if exists and c ~= 14 then
374                         tex = CHAR_FILE:format(font_name, c)
375                 else
376                         tex = CHAR_FILE:format(font_name, 0x0)
377                 end
378                 ctexcache[font_name..ch] = tex
379                 return tex, exists
380         end
381 end
382
383 local function make_line_texture(line, lineno, pos)
384
385         local width = 0
386         local maxw = 0
387
388         local words = { }
389         local n = minetest.registered_nodes[minetest.get_node(pos).name]
390         local default_color = n.default_color or 0
391
392         local cur_color = tonumber(default_color, 16)
393
394         -- We check which chars are available here.
395         for word_i, word in ipairs(line) do
396                 local chars = { }
397                 local ch_offs = 0
398                 word = string.gsub(word, "%^[12345678abcdefgh]", {
399                         ["^1"] = string.char(0x81),
400                         ["^2"] = string.char(0x82),
401                         ["^3"] = string.char(0x83),
402                         ["^4"] = string.char(0x84),
403                         ["^5"] = string.char(0x85),
404                         ["^6"] = string.char(0x86),
405                         ["^7"] = string.char(0x87),
406                         ["^8"] = string.char(0x88),
407                         ["^a"] = string.char(0x8a),
408                         ["^b"] = string.char(0x8b),
409                         ["^c"] = string.char(0x8c),
410                         ["^d"] = string.char(0x8d),
411                         ["^e"] = string.char(0x8e),
412                         ["^f"] = string.char(0x8f),
413                         ["^g"] = string.char(0x90),
414                         ["^h"] = string.char(0x91)
415                 })
416                 local word_l = #word
417                 local i = 1
418                 while i <= word_l  do
419                         local c = word:sub(i, i)
420                         if c == "#" then
421                                 local cc = tonumber(word:sub(i+1, i+1), 16)
422                                 if cc then
423                                         i = i + 1
424                                         cur_color = cc
425                                 end
426                         else
427                                 local w = charwidth[c]
428                                 if w then
429                                         width = width + w + 1
430                                         if width >= (SIGN_WIDTH - charwidth[" "]) then
431                                                 width = 0
432                                         else
433                                                 maxw = math_max(width, maxw)
434                                         end
435                                         if #chars < MAX_INPUT_CHARS then
436                                                 table.insert(chars, {
437                                                         off = ch_offs,
438                                                         tex = char_tex(font_name, c),
439                                                         col = ("%X"):format(cur_color),
440                                                 })
441                                         end
442                                         ch_offs = ch_offs + w
443                                 end
444                         end
445                         i = i + 1
446                 end
447                 width = width + charwidth[" "] + 1
448                 maxw = math_max(width, maxw)
449                 table.insert(words, { chars=chars, w=ch_offs })
450         end
451
452         -- Okay, we actually build the "line texture" here.
453
454         local texture = { }
455
456         local start_xpos = math.floor((SIGN_WIDTH - maxw) / 2)
457
458         local xpos = start_xpos
459         local ypos = (LINE_HEIGHT * lineno)
460
461         cur_color = nil
462
463         for word_i, word in ipairs(words) do
464                 local xoffs = (xpos - start_xpos)
465                 if (xoffs > 0) and ((xoffs + word.w) > maxw) then
466                         table.insert(texture, fill_line(xpos, ypos, maxw, "n"))
467                         xpos = start_xpos
468                         ypos = ypos + LINE_HEIGHT
469                         lineno = lineno + 1
470                         if lineno >= NUMBER_OF_LINES then break end
471                         table.insert(texture, fill_line(xpos, ypos, maxw, cur_color))
472                 end
473                 for ch_i, ch in ipairs(word.chars) do
474                         if ch.col ~= cur_color then
475                                 cur_color = ch.col
476                                 table.insert(texture, fill_line(xpos + ch.off, ypos, maxw, cur_color))
477                         end
478                         table.insert(texture, (":%d,%d=%s"):format(xpos + ch.off, ypos, ch.tex))
479                 end
480                 table.insert(
481                         texture, 
482                         (":%d,%d="):format(xpos + word.w, ypos) .. char_tex(font_name, " ")
483                 )
484                 xpos = xpos + word.w + charwidth[" "]
485                 if xpos >= (SIGN_WIDTH + charwidth[" "]) then break end
486         end
487
488         table.insert(texture, fill_line(xpos, ypos, maxw, "n"))
489         table.insert(texture, fill_line(start_xpos, ypos + LINE_HEIGHT, maxw, "n"))
490
491         return table.concat(texture), lineno
492 end
493
494 local function make_sign_texture(lines, pos)
495         local texture = { ("[combine:%dx%d"):format(SIGN_WIDTH, LINE_HEIGHT * NUMBER_OF_LINES) }
496         local lineno = 0
497         for i = 1, #lines do
498                 if lineno >= NUMBER_OF_LINES then break end
499                 local linetex, ln = make_line_texture(lines[i], lineno, pos)
500                 table.insert(texture, linetex)
501                 lineno = ln + 1
502         end
503         table.insert(texture, "^[makealpha:0,0,0")
504         return table.concat(texture, "")
505 end
506
507 local function set_obj_text(obj, text, new, pos)
508         local split = new and split_lines_and_words or split_lines_and_words_old
509         local text_ansi = Utf8ToAnsi(text)
510         local n = minetest.registered_nodes[minetest.get_node(pos).name]
511         local text_scale = (n and n.text_scale) or DEFAULT_TEXT_SCALE
512         obj:set_properties({
513                 textures={make_sign_texture(split(text_ansi), pos)},
514                 visual_size = text_scale,
515         })
516 end
517
518 signs_lib.construct_sign = function(pos, locked)
519         local meta = minetest.get_meta(pos)
520         meta:set_string(
521                 "formspec",
522                 "size[6,4]"..
523                 "textarea[0,-0.3;6.5,3;text;;${text}]"..
524                 "button_exit[2,3.4;2,1;ok;"..S("Write").."]"..
525                 "background[-0.5,-0.5;7,5;bg_signs_lib.jpg]")
526         meta:set_string("infotext", "")
527 end
528
529 signs_lib.destruct_sign = function(pos)
530         local objects = minetest.get_objects_inside_radius(pos, 0.5)
531         for _, v in ipairs(objects) do
532                 local e = v:get_luaentity()
533                 if e and e.name == "signs:text" then
534                         v:remove()
535                 end
536         end
537 end
538
539 local function make_infotext(text)
540         text = trim_input(text)
541         local lines = split_lines_and_words(text) or {}
542         local lines2 = { }
543         for _, line in ipairs(lines) do
544                 table.insert(lines2, (table.concat(line, " "):gsub("#[0-9a-fA-F]", ""):gsub("##", "#")))
545         end
546         return table.concat(lines2, "\n")
547 end
548
549 signs_lib.update_sign = function(pos, fields, owner, node)
550
551         -- First, check if the interact keyword from CWz's mod is being set,
552         -- or has been changed since the last restart...
553
554         local meta = minetest.get_meta(pos)
555         local stored_text = meta:get_string("text") or ""
556         current_keyword = rawget(_G, "mki_interact_keyword") or current_keyword
557
558         if fields then -- ...we're editing the sign.
559                 if fields.text and string.find(dump(fields.text), "@KEYWORD") then
560                         meta:set_string("keyword", current_keyword)
561                 else
562                         meta:set_string("keyword", nil)
563                 end
564         elseif string.find(dump(stored_text), "@KEYWORD") then -- we need to check if the password is being set/changed
565
566                 local stored_keyword = meta:get_string("keyword")
567                 if stored_keyword and stored_keyword ~= "" and stored_keyword ~= current_keyword then
568                         signs_lib.destruct_sign(pos)
569                         meta:set_string("keyword", current_keyword)
570                         local ownstr = ""
571                         if owner then ownstr = S("Locked sign, owned by @1\n", owner) end
572                         meta:set_string("infotext", ownstr..string.gsub(make_infotext(stored_text), "@KEYWORD", current_keyword).." ")
573                 end
574         end
575
576         local new
577
578         if fields then
579
580                 fields.text = trim_input(fields.text)
581
582                 local ownstr = ""
583                 if owner then ownstr = S("Locked sign, owned by @1\n", owner) end
584
585                 meta:set_string("infotext", ownstr..string.gsub(make_infotext(fields.text), "@KEYWORD", current_keyword).." ")
586                 meta:set_string("text", fields.text)
587                 
588                 meta:set_int("__signslib_new_format", 1)
589                 new = true
590         else
591                 new = (meta:get_int("__signslib_new_format") ~= 0)
592         end
593         signs_lib.destruct_sign(pos)
594         local text = meta:get_string("text")
595         if text == nil or text == "" then return end
596         local sign_info
597         local signnode = node or minetest.get_node(pos)
598         local signname = signnode.name
599         local textpos = minetest.registered_nodes[signname].textpos
600         if textpos then
601                 sign_info = textpos[minetest.get_node(pos).param2 + 1]
602         elseif signnode.name == "signs:sign_yard" then
603                 sign_info = signs_lib.yard_sign_model.textpos[minetest.get_node(pos).param2 + 1]
604         elseif signnode.name == "signs:sign_hanging" then
605                 sign_info = signs_lib.hanging_sign_model.textpos[minetest.get_node(pos).param2 + 1]
606         elseif string.find(signnode.name, "sign_wall") then
607                 if signnode.name == default_sign
608                   or signnode.name == default_sign_metal
609                   or signnode.name == "locked_sign:sign_wall_locked" then
610                         sign_info = signs_lib.regular_wall_sign_model.textpos[minetest.get_node(pos).param2 + 1]
611                 else
612                         sign_info = signs_lib.metal_wall_sign_model.textpos[minetest.get_node(pos).param2 + 1]
613                 end
614         else -- ...it must be a sign on a fence post.
615                 sign_info = signs_lib.sign_post_model.textpos[minetest.get_node(pos).param2 + 1]
616         end
617         if sign_info == nil then
618                 return
619         end
620         local text = minetest.add_entity({x = pos.x + sign_info.delta.x,
621                                                                                 y = pos.y + sign_info.delta.y,
622                                                                                 z = pos.z + sign_info.delta.z}, "signs:text")
623         text:setyaw(sign_info.yaw)
624 end
625
626 -- What kind of sign do we need to place, anyway?
627
628 function signs_lib.determine_sign_type(itemstack, placer, pointed_thing, locked)
629         local name
630         name = minetest.get_node(pointed_thing.under).name
631         if fences_with_sign[name] then
632                 if minetest.is_protected(pointed_thing.under, placer:get_player_name()) then
633                         minetest.record_protection_violation(pointed_thing.under,
634                                 placer:get_player_name())
635                         return itemstack
636                 end
637         else
638                 name = minetest.get_node(pointed_thing.above).name
639                 local def = minetest.registered_nodes[name]
640                 if not def.buildable_to then
641                         return itemstack
642                 end
643                 if minetest.is_protected(pointed_thing.above, placer:get_player_name()) then
644                         minetest.record_protection_violation(pointed_thing.above,
645                                 placer:get_player_name())
646                         return itemstack
647                 end
648         end
649
650         local node=minetest.get_node(pointed_thing.under)
651
652         if minetest.registered_nodes[node.name] and
653            minetest.registered_nodes[node.name].on_rightclick and
654            not placer:get_player_control().sneak then
655                 return minetest.registered_nodes[node.name].on_rightclick(pointed_thing.under, node, placer, itemstack, pointed_thing)
656         else
657                 local above = pointed_thing.above
658                 local under = pointed_thing.under
659                 local dir = {x = under.x - above.x,
660                                          y = under.y - above.y,
661                                          z = under.z - above.z}
662
663                 local wdir = minetest.dir_to_wallmounted(dir)
664
665                 local placer_pos = placer:getpos()
666                 if placer_pos then
667                         dir = {
668                                 x = above.x - placer_pos.x,
669                                 y = above.y - placer_pos.y,
670                                 z = above.z - placer_pos.z
671                         }
672                 end
673
674                 local fdir = minetest.dir_to_facedir(dir)
675                 local pt_name = minetest.get_node(under).name
676                 local signname = itemstack:get_name()
677
678                 if fences_with_sign[pt_name] and signname == default_sign then
679                         minetest.add_node(under, {name = fences_with_sign[pt_name], param2 = fdir})
680                 elseif wdir == 0 and signname == default_sign then
681                         minetest.add_node(above, {name = "signs:sign_hanging", param2 = fdir})
682                 elseif wdir == 1 and signname == default_sign then
683                         minetest.add_node(above, {name = "signs:sign_yard", param2 = fdir})
684                 elseif signname == default_sign_metal then
685                         minetest.add_node(above, {name = signname, param2 = wdir })
686                 elseif signname ~= default_sign
687                   and signname ~= default_sign_metal
688                   and signname ~= "locked_sign:sign_wall_locked" then -- it's a signs_lib colored metal wall sign.
689                         minetest.add_node(above, {name = signname, param2 = fdir})
690                 else -- it must be a default or locked wooden wall sign
691                         minetest.add_node(above, {name = signname, param2 = wdir }) -- note it's wallmounted here!
692                         if locked then
693                                 local meta = minetest.get_meta(above)
694                                 local owner = placer:get_player_name()
695                                 meta:set_string("owner", owner)
696                         end
697                 end
698
699                 if not signs_lib.expect_infinite_stacks then
700                         itemstack:take_item()
701                 end
702                 return itemstack
703         end
704 end
705
706 function signs_lib.receive_fields(pos, formname, fields, sender, lock)
707         if minetest.is_protected(pos, sender:get_player_name()) then
708                 minetest.record_protection_violation(pos,
709                         sender:get_player_name())
710                 return
711         end
712         local lockstr = lock and S("locked ") or ""
713         if fields and fields.text and fields.ok then
714                 minetest.log("action", S("@1 wrote \"@2\" to @3sign at @4",
715                         (sender:get_player_name() or ""),
716                         fields.text:gsub('\\', '\\\\'):gsub("\n", "\\n"),
717                         lockstr,
718                         minetest.pos_to_string(pos)
719                 ))
720                 if lock then
721                         signs_lib.update_sign(pos, fields, sender:get_player_name())
722                 else
723                         signs_lib.update_sign(pos, fields)
724                 end
725         end
726 end
727
728 minetest.register_node(":"..default_sign, {
729         description = S("Sign"),
730         inventory_image = default_sign_image,
731         wield_image = default_sign_image,
732         node_placement_prediction = "",
733         sunlight_propagates = true,
734         paramtype = "light",
735         paramtype2 = "wallmounted",
736         drawtype = "nodebox",
737         node_box = signs_lib.regular_wall_sign_model.nodebox,
738         tiles = {"signs_wall_sign.png"},
739         groups = sign_groups,
740
741         on_place = function(itemstack, placer, pointed_thing)
742                 return signs_lib.determine_sign_type(itemstack, placer, pointed_thing)
743         end,
744         on_construct = function(pos)
745                 signs_lib.construct_sign(pos)
746         end,
747         on_destruct = function(pos)
748                 signs_lib.destruct_sign(pos)
749         end,
750         on_receive_fields = function(pos, formname, fields, sender)
751                 signs_lib.receive_fields(pos, formname, fields, sender)
752         end,
753         on_punch = function(pos, node, puncher)
754                 signs_lib.update_sign(pos,nil,nil,node)
755         end,
756         on_rotate = signs_lib.wallmounted_rotate
757 })
758
759 minetest.register_node(":signs:sign_yard", {
760         paramtype = "light",
761         sunlight_propagates = true,
762         paramtype2 = "facedir",
763         drawtype = "nodebox",
764         node_box = signs_lib.yard_sign_model.nodebox,
765         selection_box = {
766                 type = "fixed",
767                 fixed = {-0.4375, -0.5, -0.0625, 0.4375, 0.375, 0}
768         },
769         tiles = {"signs_top.png", "signs_bottom.png", "signs_side.png", "signs_side.png", "signs_back.png", "signs_front.png"},
770         groups = {choppy=2, dig_immediate=2},
771         drop = default_sign,
772
773         on_construct = function(pos)
774                 signs_lib.construct_sign(pos)
775         end,
776         on_destruct = function(pos)
777                 signs_lib.destruct_sign(pos)
778         end,
779         on_receive_fields = function(pos, formname, fields, sender)
780                 signs_lib.receive_fields(pos, formname, fields, sender)
781         end,
782         on_punch = function(pos, node, puncher)
783                 signs_lib.update_sign(pos,nil,nil,node)
784         end,
785         on_rotate = signs_lib.facedir_rotate_simple
786
787 })
788
789 minetest.register_node(":signs:sign_hanging", {
790         paramtype = "light",
791         sunlight_propagates = true,
792         paramtype2 = "facedir",
793         drawtype = "nodebox",
794         node_box = signs_lib.hanging_sign_model.nodebox,
795         selection_box = {
796                 type = "fixed",
797                 fixed = {-0.45, -0.275, -0.049, 0.45, 0.5, 0.049}
798         },
799         tiles = {
800                 "signs_hanging_top.png",
801                 "signs_hanging_bottom.png",
802                 "signs_hanging_side.png",
803                 "signs_hanging_side.png",
804                 "signs_hanging_back.png",
805                 "signs_hanging_front.png"
806         },
807         groups = {choppy=2, dig_immediate=2},
808         drop = default_sign,
809
810         on_construct = function(pos)
811                 signs_lib.construct_sign(pos)
812         end,
813         on_destruct = function(pos)
814                 signs_lib.destruct_sign(pos)
815         end,
816         on_receive_fields = function(pos, formname, fields, sender)
817                 signs_lib.receive_fields(pos, formname, fields, sender)
818         end,
819         on_punch = function(pos, node, puncher)
820                 signs_lib.update_sign(pos,nil,nil,node)
821         end,
822         on_rotate = signs_lib.facedir_rotate_simple
823 })
824
825 minetest.register_node(":signs:sign_post", {
826         paramtype = "light",
827         sunlight_propagates = true,
828         paramtype2 = "facedir",
829         drawtype = "nodebox",
830         node_box = signs_lib.sign_post_model.nodebox,
831         tiles = {
832                 "signs_post_top.png",
833                 "signs_post_bottom.png",
834                 "signs_post_side.png",
835                 "signs_post_side.png",
836                 "signs_post_back.png",
837                 "signs_post_front.png",
838         },
839         groups = {choppy=2, dig_immediate=2},
840         drop = {
841                 max_items = 2,
842                 items = {
843                         { items = { default_sign }},
844                         { items = { "default:fence_wood" }},
845                 },
846         },
847         on_rotate = signs_lib.facedir_rotate_simple
848 })
849
850 -- Locked wall sign
851
852 minetest.register_privilege("sign_editor", S("Can edit all locked signs"))
853
854 minetest.register_node(":locked_sign:sign_wall_locked", {
855         description = S("Locked Sign"),
856         inventory_image = "signs_locked_inv.png",
857         wield_image = "signs_locked_inv.png",
858         node_placement_prediction = "",
859         sunlight_propagates = true,
860         paramtype = "light",
861         paramtype2 = "wallmounted",
862         drawtype = "nodebox",
863         node_box = signs_lib.regular_wall_sign_model.nodebox,
864         tiles = { "signs_wall_sign_locked.png" },
865         groups = sign_groups,
866         on_place = function(itemstack, placer, pointed_thing)
867                 return signs_lib.determine_sign_type(itemstack, placer, pointed_thing, true)
868         end,
869         on_construct = function(pos)
870                 signs_lib.construct_sign(pos, true)
871         end,
872         on_destruct = function(pos)
873                 signs_lib.destruct_sign(pos)
874         end,
875         on_receive_fields = function(pos, formname, fields, sender)
876                 local meta = minetest.get_meta(pos)
877                 local owner = meta:get_string("owner")
878                 local pname = sender:get_player_name() or ""
879                 if pname ~= owner and pname ~= minetest.settings:get("name")
880                   and not minetest.check_player_privs(pname, {sign_editor=true}) then
881                         return
882                 end
883                 signs_lib.receive_fields(pos, formname, fields, sender, true)
884         end,
885         on_punch = function(pos, node, puncher)
886                 signs_lib.update_sign(pos,nil,nil,node)
887         end,
888         can_dig = function(pos, player)
889                 local meta = minetest.get_meta(pos)
890                 local owner = meta:get_string("owner")
891                 local pname = player:get_player_name()
892                 return pname == owner or pname == minetest.settings:get("name")
893                         or minetest.check_player_privs(pname, {sign_editor=true})
894         end,
895         on_rotate = signs_lib.wallmounted_rotate
896 })
897
898 -- default metal sign, if defined
899
900 if minetest.registered_nodes["default:sign_wall_steel"] then
901         minetest.register_node(":"..default_sign_metal, {
902                 description = S("Sign"),
903                 inventory_image = default_sign_metal_image,
904                 wield_image = default_sign_metal_image,
905                 node_placement_prediction = "",
906                 sunlight_propagates = true,
907                 paramtype = "light",
908                 paramtype2 = "wallmounted",
909                 drawtype = "nodebox",
910                 node_box = signs_lib.regular_wall_sign_model.nodebox,
911                 tiles = {"signs_wall_sign_metal.png"},
912                 groups = sign_groups,
913
914                 on_place = function(itemstack, placer, pointed_thing)
915                         return signs_lib.determine_sign_type(itemstack, placer, pointed_thing)
916                 end,
917                 on_construct = function(pos)
918                         signs_lib.construct_sign(pos)
919                 end,
920                 on_destruct = function(pos)
921                         signs_lib.destruct_sign(pos)
922                 end,
923                 on_receive_fields = function(pos, formname, fields, sender)
924                         signs_lib.receive_fields(pos, formname, fields, sender)
925                 end,
926                 on_punch = function(pos, node, puncher)
927                         signs_lib.update_sign(pos,nil,nil,node)
928                 end,
929                 on_rotate = signs_lib.wallmounted_rotate
930         })
931 end
932
933 -- metal, colored signs
934 if enable_colored_metal_signs then
935         -- array : color, translated color, default text color
936         local sign_colors = {
937                 {"green",        S("green"),       "f"},
938                 {"yellow",       S("yellow"),      "0"},
939                 {"red",          S("red"),         "f"},
940                 {"white_red",    S("white_red"),   "4"},
941                 {"white_black",  S("white_black"), "0"},
942                 {"orange",       S("orange"),      "0"},
943                 {"blue",         S("blue"),        "f"},
944                 {"brown",        S("brown"),       "f"},
945         }
946
947         for i, color in ipairs(sign_colors) do
948                 minetest.register_node(":signs:sign_wall_"..color[1], {
949                         description = S("Sign (@1, metal)", color[2]),
950                         inventory_image = "signs_"..color[1].."_inv.png",
951                         wield_image = "signs_"..color[1].."_inv.png",
952                         node_placement_prediction = "",
953                         paramtype = "light",
954                         sunlight_propagates = true,
955                         paramtype2 = "facedir",
956                         drawtype = "nodebox",
957                         node_box = signs_lib.metal_wall_sign_model.nodebox,
958                         tiles = {
959                                 "signs_metal_tb.png",
960                                 "signs_metal_tb.png",
961                                 "signs_metal_sides.png",
962                                 "signs_metal_sides.png",
963                                 "signs_metal_back.png",
964                                 "signs_"..color[1].."_front.png"
965                         },
966                         default_color = color[3],
967                         groups = sign_groups,
968                         on_place = function(itemstack, placer, pointed_thing)
969                                 return signs_lib.determine_sign_type(itemstack, placer, pointed_thing)
970                         end,
971                         on_construct = function(pos)
972                                 signs_lib.construct_sign(pos)
973                         end,
974                         on_destruct = function(pos)
975                                 signs_lib.destruct_sign(pos)
976                         end,
977                         on_receive_fields = function(pos, formname, fields, sender)
978                                 signs_lib.receive_fields(pos, formname, fields, sender)
979                         end,
980                         on_punch = function(pos, node, puncher)
981                                 signs_lib.update_sign(pos,nil,nil,node)
982                         end,
983                         on_rotate = signs_lib.facedir_rotate
984                 })
985         end
986 end
987
988 local signs_text_on_activate
989
990 signs_text_on_activate = function(self)
991         local pos = self.object:getpos()
992         local meta = minetest.get_meta(pos)
993         local text = meta:get_string("text")
994         local new = (meta:get_int("__signslib_new_format") ~= 0)
995         if text and minetest.registered_nodes[minetest.get_node(pos).name] then
996                 text = trim_input(text)
997                 set_obj_text(self.object, text, new, pos)
998         end
999 end
1000
1001 minetest.register_entity(":signs:text", {
1002         collisionbox = { 0, 0, 0, 0, 0, 0 },
1003         visual = "upright_sprite",
1004         textures = {},
1005
1006         on_activate = signs_text_on_activate,
1007 })
1008
1009 -- And the good stuff here! :-)
1010
1011 function signs_lib.register_fence_with_sign(fencename, fencewithsignname)
1012         local def = minetest.registered_nodes[fencename]
1013         local def_sign = minetest.registered_nodes[fencewithsignname]
1014         if not (def and def_sign) then
1015                 minetest.log("warning", "[signs_lib] "..S("Attempt to register unknown node as fence"))
1016                 return
1017         end
1018         def = signs_lib.table_copy(def)
1019         def_sign = signs_lib.table_copy(def_sign)
1020         fences_with_sign[fencename] = fencewithsignname
1021
1022         def_sign.on_place = function(itemstack, placer, pointed_thing, ...)
1023                 local node_above = minetest.get_node_or_nil(pointed_thing.above)
1024                 local node_under = minetest.get_node_or_nil(pointed_thing.under)
1025                 local def_above = node_above and minetest.registered_nodes[node_above.name]
1026                 local def_under = node_under and minetest.registered_nodes[node_under.name]
1027                 local fdir = minetest.dir_to_facedir(placer:get_look_dir())
1028                 local playername = placer:get_player_name()
1029
1030                 if minetest.is_protected(pointed_thing.under, playername) then
1031                         minetest.record_protection_violation(pointed_thing.under, playername)
1032                         return itemstack
1033                 end
1034
1035                 if minetest.is_protected(pointed_thing.above, playername) then
1036                         minetest.record_protection_violation(pointed_thing.above, playername)
1037                         return itemstack
1038                 end
1039
1040                 if def_under and def_under.on_rightclick then
1041                         return def_under.on_rightclick(pointed_thing.under, node_under, placer, itemstack, pointed_thing) or itemstack
1042                 elseif def_under and def_under.buildable_to then
1043                         minetest.add_node(pointed_thing.under, {name = fencename, param2 = fdir})
1044                         if not signs_lib.expect_infinite_stacks then
1045                                 itemstack:take_item()
1046                         end
1047                         placer:set_wielded_item(itemstack)
1048                 elseif def_above and def_above.buildable_to then
1049                         minetest.add_node(pointed_thing.above, {name = fencename, param2 = fdir})
1050                         if not signs_lib.expect_infinite_stacks then
1051                                 itemstack:take_item()
1052                         end
1053                         placer:set_wielded_item(itemstack)
1054                 end
1055                 return itemstack
1056         end
1057         def_sign.on_construct = function(pos, ...)
1058                 signs_lib.construct_sign(pos)
1059         end
1060         def_sign.on_destruct = function(pos, ...)
1061                 signs_lib.destruct_sign(pos)
1062         end
1063         def_sign.on_receive_fields = function(pos, formname, fields, sender)
1064                 signs_lib.receive_fields(pos, formname, fields, sender)
1065         end
1066         def_sign.on_punch = function(pos, node, puncher, ...)
1067                 signs_lib.update_sign(pos,nil,nil,node)
1068         end
1069         local fencename = fencename
1070         def_sign.after_dig_node = function(pos, node, ...)
1071                 node.name = fencename
1072                 minetest.add_node(pos, node)
1073         end
1074         def_sign.on_rotate = signs_lib.facedir_rotate_simple
1075
1076         def_sign.drop = default_sign
1077         minetest.register_node(":"..fencename, def)
1078         minetest.register_node(":"..fencewithsignname, def_sign)
1079         table.insert(signs_lib.sign_node_list, fencewithsignname)
1080         minetest.log("verbose", S("Registered @1 and @2", fencename, fencewithsignname))
1081 end
1082
1083 build_char_db()
1084
1085 minetest.register_alias("homedecor:fence_wood_with_sign", "signs:sign_post")
1086 minetest.register_alias("sign_wall_locked", "locked_sign:sign_wall_locked")
1087
1088 signs_lib.register_fence_with_sign("default:fence_wood", "signs:sign_post")
1089
1090 -- restore signs' text after /clearobjects and the like, the next time
1091 -- a block is reloaded by the server.
1092
1093 minetest.register_lbm({
1094         nodenames = signs_lib.sign_node_list,
1095         name = "signs_lib:restore_sign_text",
1096         label = "Restore sign text",
1097         run_at_every_load = true,
1098         action = function(pos, node)
1099                 signs_lib.update_sign(pos,nil,nil,node)
1100         end
1101 })
1102
1103 -- locked sign
1104
1105 minetest.register_craft({
1106                 output = "locked_sign:sign_wall_locked",
1107                 recipe = {
1108                         {default_sign},
1109                         {"basic_materials:padlock"},
1110         },
1111 })
1112
1113 -- craft recipes for the metal signs
1114 if enable_colored_metal_signs then
1115
1116         minetest.register_craft( {
1117                 output = "signs:sign_wall_green",
1118                 recipe = {
1119                                 { "dye:dark_green", "dye:white", "dye:dark_green" },
1120                                 { "", default_sign_metal, "" }
1121                 },
1122         })
1123
1124         minetest.register_craft( {
1125                 output = "signs:sign_wall_green 2",
1126                 recipe = {
1127                                 { "dye:dark_green", "dye:white", "dye:dark_green" },
1128                                 { "steel:sheet_metal", "steel:sheet_metal", "steel:sheet_metal" }
1129                 },
1130         })
1131
1132         minetest.register_craft( {
1133                 output = "signs:sign_wall_yellow",
1134                 recipe = {
1135                                 { "dye:yellow", "dye:black", "dye:yellow" },
1136                                 { "", default_sign_metal, "" }
1137                 },
1138         })
1139
1140         minetest.register_craft( {
1141                 output = "signs:sign_wall_yellow 2",
1142                 recipe = {
1143                                 { "dye:yellow", "dye:black", "dye:yellow" },
1144                                 { "steel:sheet_metal", "steel:sheet_metal", "steel:sheet_metal" }
1145                 },
1146         })
1147
1148         minetest.register_craft( {
1149                 output = "signs:sign_wall_red",
1150                 recipe = {
1151                                 { "dye:red", "dye:white", "dye:red" },
1152                                 { "", default_sign_metal, "" }
1153                 },
1154         })
1155
1156         minetest.register_craft( {
1157                 output = "signs:sign_wall_red 2",
1158                 recipe = {
1159                                 { "dye:red", "dye:white", "dye:red" },
1160                                 { "steel:sheet_metal", "steel:sheet_metal", "steel:sheet_metal" }
1161                 },
1162         })
1163
1164         minetest.register_craft( {
1165                 output = "signs:sign_wall_white_red",
1166                 recipe = {
1167                                 { "dye:white", "dye:red", "dye:white" },
1168                                 { "", default_sign_metal, "" }
1169                 },
1170         })
1171
1172         minetest.register_craft( {
1173                 output = "signs:sign_wall_white_red 2",
1174                 recipe = {
1175                                 { "dye:white", "dye:red", "dye:white" },
1176                                 { "steel:sheet_metal", "steel:sheet_metal", "steel:sheet_metal" }
1177                 },
1178         })
1179
1180         minetest.register_craft( {
1181                 output = "signs:sign_wall_white_black",
1182                 recipe = {
1183                                 { "dye:white", "dye:black", "dye:white" },
1184                                 { "", default_sign_metal, "" }
1185                 },
1186         })
1187
1188         minetest.register_craft( {
1189                 output = "signs:sign_wall_white_black 2",
1190                 recipe = {
1191                                 { "dye:white", "dye:black", "dye:white" },
1192                                 { "steel:sheet_metal", "steel:sheet_metal", "steel:sheet_metal" }
1193                 },
1194         })
1195
1196         minetest.register_craft( {
1197                 output = "signs:sign_wall_orange",
1198                 recipe = {
1199                                 { "dye:orange", "dye:black", "dye:orange" },
1200                                 { "", default_sign_metal, "" }
1201                 },
1202         })
1203
1204         minetest.register_craft( {
1205                 output = "signs:sign_wall_orange 2",
1206                 recipe = {
1207                                 { "dye:orange", "dye:black", "dye:orange" },
1208                                 { "steel:sheet_metal", "steel:sheet_metal", "steel:sheet_metal" }
1209                 },
1210         })
1211
1212         minetest.register_craft( {
1213                 output = "signs:sign_wall_blue",
1214                 recipe = {
1215                                 { "dye:blue", "dye:white", "dye:blue" },
1216                                 { "", default_sign_metal, "" }
1217                 },
1218         })
1219
1220         minetest.register_craft( {
1221                 output = "signs:sign_wall_blue 2",
1222                 recipe = {
1223                                 { "dye:blue", "dye:white", "dye:blue" },
1224                                 { "steel:sheet_metal", "steel:sheet_metal", "steel:sheet_metal" }
1225                 },
1226         })
1227
1228         minetest.register_craft( {
1229                 output = "signs:sign_wall_brown",
1230                 recipe = {
1231                                 { "dye:brown", "dye:white", "dye:brown" },
1232                                 { "", default_sign_metal, "" }
1233                 },
1234         })
1235
1236         minetest.register_craft( {
1237                 output = "signs:sign_wall_brown 2",
1238                 recipe = {
1239                                 { "dye:brown", "dye:white", "dye:brown" },
1240                                 { "steel:sheet_metal", "steel:sheet_metal", "steel:sheet_metal" }
1241                 },
1242         })
1243 end
1244
1245 if minetest.settings:get("log_mods") then
1246         minetest.log("action", S("[MOD] signs loaded"))
1247 end