]> git.lizzy.rs Git - signs_lib.git/blob - api.lua
80e545b6d243af42901c942d311f2d2685913bc5
[signs_lib.git] / api.lua
1 -- signs_lib api, backported from street_signs
2
3 local S = signs_lib.gettext
4
5 signs_lib.lbm_restore_nodes = {}
6 signs_lib.old_fenceposts = {}
7 signs_lib.old_fenceposts_replacement_signs = {}
8 signs_lib.old_fenceposts_with_signs = {}
9 signs_lib.allowed_poles = {}
10
11 -- Settings used for a standard wood or steel wall sign
12 signs_lib.standard_lines = 6
13 signs_lib.standard_hscale = 1.7
14 signs_lib.standard_vscale = 1.75
15 signs_lib.standard_lspace = 1
16 signs_lib.standard_fsize = 15
17 signs_lib.standard_xoffs = 5
18 signs_lib.standard_yoffs = 38
19 signs_lib.standard_cpl = 25
20
21 signs_lib.standard_wood_groups =  {choppy = 2, flammable = 2, oddly_breakable_by_hand = 3}
22 signs_lib.standard_steel_groups = {cracky = 2, oddly_breakable_by_hand = 3} 
23
24 signs_lib.standard_yaw = {
25         0,
26         math.pi / -2,
27         math.pi,
28         math.pi / 2,
29 }
30
31 signs_lib.wallmounted_yaw = {
32         nil,
33         nil,
34         math.pi / -2,
35         math.pi / 2,
36         0,
37         math.pi,
38 }
39
40 local wall_dir_change = {
41         [0] = 2,
42         2,
43         5,
44         4,
45         2,
46         3,
47 }
48
49 signs_lib.fdir_to_back = {
50         {  0, -1 },
51         { -1,  0 },
52         {  0,  1 },
53         {  1,  0 },
54 }
55
56 signs_lib.wall_fdir_to_back = {
57         nil,
58         nil,
59         {  0,  1 },
60         {  0, -1 },
61         { -1,  0 },
62         {  1,  0 },
63 }
64
65 -- Initialize character texture cache
66 local ctexcache = {}
67
68 signs_lib.wallmounted_rotate = function(pos, node, user, mode)
69         if mode ~= screwdriver.ROTATE_FACE then return false end
70         minetest.swap_node(pos, { name = node.name, param2 = wall_dir_change[node.param2 % 6] })
71         for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
72                 local e = v:get_luaentity()
73                 if e and e.name == "signs_lib:text" then
74                         v:remove()
75                 end
76         end
77         signs_lib.update_sign(pos)
78         return true
79 end
80
81 signs_lib.facedir_rotate = function(pos, node, user, mode)
82         if mode ~= screwdriver.ROTATE_FACE or not signs_lib.can_modify(pos, user) then return end
83         newparam2 = ((node.param2 % 6 ) == 0) and 1 or 0
84         minetest.swap_node(pos, { name = node.name, param2 = newparam2 })
85         for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
86                 local e = v:get_luaentity()
87                 if e and e.name == "signs_lib:text" then
88                         v:remove()
89                 end
90         end
91         signs_lib.update_sign(pos)
92         return true
93 end
94
95 local DEFAULT_TEXT_SCALE = {x=10, y=10}
96
97 -- infinite stacks
98
99 if not minetest.settings:get_bool("creative_mode") then
100         signs_lib.expect_infinite_stacks = false
101 else
102         signs_lib.expect_infinite_stacks = true
103 end
104
105 -- CONSTANTS
106
107 -- Path to the textures.
108 local TP = signs_lib.path .. "/textures"
109 -- Font file formatter
110 local CHAR_FILE = "%s_%02x.png"
111 -- Fonts path
112 local CHAR_PATH = TP .. "/" .. CHAR_FILE
113
114 -- Lots of overkill here. KISS advocates, go away, shoo! ;) -- kaeza
115
116 local PNG_HDR = string.char(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
117
118 -- check if a file does exist
119 -- to avoid reopening file after checking again
120 -- pass TRUE as second argument
121 local function file_exists(name, return_handle, mode)
122         mode = mode or "r";
123         local f = io.open(name, mode)
124         if f ~= nil then
125                 if (return_handle) then
126                         return f
127                 end
128                 io.close(f) 
129                 return true 
130         else 
131                 return false 
132         end
133 end
134
135 -- Read the image size from a PNG file.
136 -- Returns image_w, image_h.
137 -- Only the LSB is read from each field!
138 function signs_lib.read_image_size(filename)
139         local f = file_exists(filename, true, "rb")
140         -- file might not exist (don't crash the game)
141         if (not f) then
142                 return 0, 0
143         end
144         f:seek("set", 0x0)
145         local hdr = f:read(string.len(PNG_HDR))
146         if hdr ~= PNG_HDR then
147                 f:close()
148                 return
149         end
150         f:seek("set", 0x13)
151         local ws = f:read(1)
152         f:seek("set", 0x17)
153         local hs = f:read(1)
154         f:close()
155         return ws:byte(), hs:byte()
156 end
157
158 -- 4 rows, max 80 chars per, plus a bit of fudge to
159 -- avoid excess trimming (e.g. due to color codes)
160
161 local MAX_INPUT_CHARS = 400
162
163 -- helper functions to trim sign text input/output
164
165 local function trim_input(text)
166         return text:sub(1, math.min(MAX_INPUT_CHARS, text:len()))
167 end
168
169 local function build_char_db(font_size)
170
171         local cw = {}
172
173         -- To calculate average char width.
174         local total_width = 0
175         local char_count = 0
176
177         for c = 32, 255 do
178                 local w, h = signs_lib.read_image_size(CHAR_PATH:format("signs_lib_font_"..font_size.."px", c))
179                 if w and h then
180                         local ch = string.char(c)
181                         cw[ch] = w
182                         total_width = total_width + w
183                         char_count = char_count + 1
184                 end
185         end
186
187         local cbw, cbh = signs_lib.read_image_size(TP.."/signs_lib_color_"..font_size.."px_n.png")
188         assert(cbw and cbh, "error reading bg dimensions")
189         return cw, cbw, cbh, (total_width / char_count)
190 end
191
192 signs_lib.charwidth15,
193 signs_lib.colorbgw15,
194 signs_lib.lineheight15,
195 signs_lib.avgwidth15 = build_char_db(15)
196
197 signs_lib.charwidth31,
198 signs_lib.colorbgw31,
199 signs_lib.lineheight31,
200 signs_lib.avgwidth31 = build_char_db(31)
201
202 local sign_groups = {choppy=2, dig_immediate=2}
203 local fences_with_sign = { }
204
205 -- some local helper functions
206
207 local function split_lines_and_words(text)
208         if not text then return end
209         local lines = { }
210         for _, line in ipairs(text:split("\n")) do
211                 table.insert(lines, line:split(" "))
212         end
213         return lines
214 end
215
216 local math_max = math.max
217
218 local function fill_line(x, y, w, c, font_size, colorbgw)
219         c = c or "0"
220         local tex = { }
221         for xx = 0, math.max(0, w), colorbgw do
222                 table.insert(tex, (":%d,%d=signs_lib_color_"..font_size.."px_%s.png"):format(x + xx, y, c))
223         end
224         return table.concat(tex)
225 end
226
227 -- make char texture file name
228 -- if texture file does not exist use fallback texture instead
229 local function char_tex(font_name, ch)
230         if ctexcache[font_name..ch] then
231                 return ctexcache[font_name..ch], true
232         else
233                 local c = ch:byte()
234                 local exists, tex = file_exists(CHAR_PATH:format(font_name, c))
235                 if exists and c ~= 14 then
236                         tex = CHAR_FILE:format(font_name, c)
237                 else
238                         tex = CHAR_FILE:format(font_name, 0x0)
239                 end
240                 ctexcache[font_name..ch] = tex
241                 return tex, exists
242         end
243 end
244
245 local function make_line_texture(line, lineno, pos, line_width, line_height, cwidth_tab, font_size, colorbgw)
246         local width = 0
247         local maxw = 0
248         local font_name = "signs_lib_font_"..font_size.."px"
249
250         local words = { }
251         local node = minetest.get_node(pos)
252         local def = minetest.registered_items[node.name]
253         local default_color = def.default_color or 0
254
255         local cur_color = tonumber(default_color, 16)
256
257         -- We check which chars are available here.
258         for word_i, word in ipairs(line) do
259                 local chars = { }
260                 local ch_offs = 0
261                 word = string.gsub(word, "%^[12345678abcdefgh]", {
262                         ["^1"] = string.char(0x81),
263                         ["^2"] = string.char(0x82),
264                         ["^3"] = string.char(0x83),
265                         ["^4"] = string.char(0x84),
266                         ["^5"] = string.char(0x85),
267                         ["^6"] = string.char(0x86),
268                         ["^7"] = string.char(0x87),
269                         ["^8"] = string.char(0x88),
270                         ["^a"] = string.char(0x8a),
271                         ["^b"] = string.char(0x8b),
272                         ["^c"] = string.char(0x8c),
273                         ["^d"] = string.char(0x8d),
274                         ["^e"] = string.char(0x8e),
275                         ["^f"] = string.char(0x8f),
276                         ["^g"] = string.char(0x90),
277                         ["^h"] = string.char(0x91)
278                 })
279                 local word_l = #word
280                 local i = 1
281                 while i <= word_l  do
282                         local c = word:sub(i, i)
283                         if c == "#" then
284                                 local cc = tonumber(word:sub(i+1, i+1), 16)
285                                 if cc then
286                                         i = i + 1
287                                         cur_color = cc
288                                 end
289                         else
290                                 local w = cwidth_tab[c]
291                                 if w then
292                                         width = width + w + 1
293                                         if width >= (line_width - cwidth_tab[" "]) then
294                                                 width = 0
295                                         else
296                                                 maxw = math_max(width, maxw)
297                                         end
298                                         if #chars < MAX_INPUT_CHARS then
299                                                 table.insert(chars, {
300                                                         off = ch_offs,
301                                                         tex = char_tex(font_name, c),
302                                                         col = ("%X"):format(cur_color),
303                                                 })
304                                         end
305                                         ch_offs = ch_offs + w
306                                 end
307                         end
308                         i = i + 1
309                 end
310                 width = width + cwidth_tab[" "] + 1
311                 maxw = math_max(width, maxw)
312                 table.insert(words, { chars=chars, w=ch_offs })
313         end
314
315         -- Okay, we actually build the "line texture" here.
316
317         local texture = { }
318
319         local start_xpos = math.floor((line_width - maxw) / 2) + def.x_offset
320
321         local xpos = start_xpos
322         local ypos = (line_height + def.line_spacing)* lineno + def.y_offset
323
324         cur_color = nil
325
326         for word_i, word in ipairs(words) do
327                 local xoffs = (xpos - start_xpos)
328                 if (xoffs > 0) and ((xoffs + word.w) > maxw) then
329                         table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
330                         xpos = start_xpos
331                         ypos = ypos + line_height + def.line_spacing
332                         lineno = lineno + 1
333                         if lineno >= def.number_of_lines then break end
334                         table.insert(texture, fill_line(xpos, ypos, maxw, cur_color, font_size, colorbgw))
335                 end
336                 for ch_i, ch in ipairs(word.chars) do
337                         if ch.col ~= cur_color then
338                                 cur_color = ch.col
339                                 table.insert(texture, fill_line(xpos + ch.off, ypos, maxw, cur_color, font_size, colorbgw))
340                         end
341                         table.insert(texture, (":%d,%d=%s"):format(xpos + ch.off, ypos, ch.tex))
342                 end
343                 table.insert(
344                         texture, 
345                         (":%d,%d="):format(xpos + word.w, ypos) .. char_tex(font_name, " ")
346                 )
347                 xpos = xpos + word.w + cwidth_tab[" "]
348                 if xpos >= (line_width + cwidth_tab[" "]) then break end
349         end
350
351         table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
352         table.insert(texture, fill_line(start_xpos, ypos + line_height, maxw, "n", font_size, colorbgw))
353
354         return table.concat(texture), lineno
355 end
356
357 local function make_sign_texture(lines, pos)
358         local node = minetest.get_node(pos)
359         local def = minetest.registered_items[node.name]
360
361         local font_size
362         local line_width
363         local line_height
364         local char_width
365         local colorbgw
366
367         if def.font_size and def.font_size == 31 then
368                 font_size = 31
369                 line_width = math.floor(signs_lib.avgwidth31 * def.chars_per_line) * def.horiz_scaling
370                 line_height = signs_lib.lineheight31
371                 char_width = signs_lib.charwidth31
372                 colorbgw = signs_lib.colorbgw31
373         else
374                 font_size = 15
375                 line_width = math.floor(signs_lib.avgwidth15 * def.chars_per_line) * def.horiz_scaling
376                 line_height = signs_lib.lineheight15
377                 char_width = signs_lib.charwidth15
378                 colorbgw = signs_lib.colorbgw15
379         end
380
381         local texture = { ("[combine:%dx%d"):format(line_width, (line_height + def.line_spacing) * def.number_of_lines * def.vert_scaling) }
382
383         local lineno = 0
384         for i = 1, #lines do
385                 if lineno >= def.number_of_lines then break end
386                 local linetex, ln = make_line_texture(lines[i], lineno, pos, line_width, line_height, char_width, font_size, colorbgw)
387                 table.insert(texture, linetex)
388                 lineno = ln + 1
389         end
390         table.insert(texture, "^[makealpha:0,0,0")
391         return table.concat(texture, "")
392 end
393
394 local function set_obj_text(obj, text, x, pos)
395         local split = split_lines_and_words
396         local text_ansi = Utf8ToAnsi(text)
397         local n = minetest.registered_nodes[minetest.get_node(pos).name]
398         local text_scale = (n and n.text_scale) or DEFAULT_TEXT_SCALE
399         local texture = make_sign_texture(split(text_ansi), pos)
400         obj:set_properties({
401                 textures={texture},
402                 visual_size = text_scale,
403         })
404 end
405
406 signs_lib.construct_sign = function(pos)
407         local meta = minetest.get_meta(pos)
408         meta:set_string(
409                 "formspec",
410                 "size[6,4]"..
411                 "textarea[0,-0.3;6.5,3;text;;${text}]"..
412                 "button_exit[2,3.4;2,1;ok;"..S("Write").."]"..
413                 "background[-0.5,-0.5;7,5;signs_lib_sign_bg.jpg]")
414         meta:set_string("infotext", "")
415 end
416
417 function signs_lib.destruct_sign(pos)
418         local objects = minetest.get_objects_inside_radius(pos, 0.5)
419         for _, v in ipairs(objects) do
420                 local e = v:get_luaentity()
421                 if e and e.name == "signs_lib:text" then
422                         v:remove()
423                 end
424         end
425 end
426
427 local function make_infotext(text)
428         text = trim_input(text)
429         local lines = split_lines_and_words(text) or {}
430         local lines2 = { }
431         for _, line in ipairs(lines) do
432                 table.insert(lines2, (table.concat(line, " "):gsub("#[0-9a-fA-F]", ""):gsub("##", "#")))
433         end
434         return table.concat(lines2, "\n")
435 end
436
437 function signs_lib.update_sign(pos, fields)
438         local meta = minetest.get_meta(pos)
439
440         local text = fields and fields.text or meta:get_string("text")
441         text = trim_input(text)
442
443         local owner = meta:get_string("owner")
444         ownstr = ""
445         if owner ~= "" then ownstr = S("Locked sign, owned by @1\n", owner) end
446
447         meta:set_string("text", text)
448         meta:set_string("infotext", ownstr..make_infotext(text).." ")
449
450         local objects = minetest.get_objects_inside_radius(pos, 0.5)
451         local found
452         for _, v in ipairs(objects) do
453                 local e = v:get_luaentity()
454                 if e and e.name == "signs_lib:text" then
455                         if found then
456                                 v:remove()
457                         else
458                                 set_obj_text(v, text, nil, pos)
459                                 found = true
460                         end
461                 end
462         end
463         if found then
464                 return
465         end
466
467         -- if there is no entity
468         local signnode = minetest.get_node(pos)
469         local signname = signnode.name
470         local def = minetest.registered_items[signname]
471         if not def.entity_info or not def.entity_info.yaw[signnode.param2 + 1] then return end
472         local obj = minetest.add_entity(pos, "signs_lib:text")
473
474         obj:setyaw(def.entity_info.yaw[signnode.param2 + 1])
475         obj:set_properties({
476                 mesh = def.entity_info.mesh,
477         })
478 end
479
480 function signs_lib.receive_fields(pos, formname, fields, sender)
481         if fields and fields.text and fields.ok and signs_lib.can_modify(pos, sender) then
482                 minetest.log("action", S("@1 wrote \"@2\" to sign at @3",
483                         (sender:get_player_name() or ""),
484                         fields.text:gsub('\\', '\\\\'):gsub("\n", "\\n"),
485                         minetest.pos_to_string(pos)
486                 ))
487                 signs_lib.update_sign(pos, fields)
488         end
489 end
490
491 function signs_lib.can_modify(pos, player)
492         local meta = minetest.get_meta(pos)
493         local owner = meta:get_string("owner")
494         local playername = player:get_player_name()
495
496         if minetest.is_protected(pos, playername) then 
497                 minetest.record_protection_violation(pos, playername)
498                 return false
499         end
500
501         if owner == ""
502           or playername == owner
503           or (minetest.check_player_privs(playername, {sign_editor=true}))
504           or (playername == minetest.settings:get("name")) then
505                 return true
506         end
507         minetest.record_protection_violation(pos, playername)
508         return false
509 end
510
511 local signs_text_on_activate = function(self)
512         local pos = self.object:getpos()
513         local meta = minetest.get_meta(pos)
514         local signnode = minetest.get_node(pos)
515         local signname = signnode.name
516         local def = minetest.registered_items[signname]
517         local text = meta:get_string("text")
518         if text and def and def.entity_info then
519                 text = trim_input(text)
520                 set_obj_text(self.object, text, nil, pos)
521                 self.object:set_properties({
522                         mesh = def.entity_info.mesh,
523                 })
524         end
525 end
526
527 minetest.register_entity("signs_lib:text", {
528         collisionbox = { 0, 0, 0, 0, 0, 0 },
529         visual = "mesh",
530         mesh = "signs_lib_basic_entity.obj",
531         textures = {},
532         on_activate = signs_text_on_activate,
533 })
534
535 -- make selection boxes
536 -- sizex/sizey specified in inches because that's what MUTCD uses.
537
538 function signs_lib.make_selection_boxes(sizex, sizey, onpole, xoffs, yoffs, zoffs, fdir)
539
540         local tx = (sizex * 0.0254 ) / 2
541         local ty = (sizey * 0.0254 ) / 2
542         local xo = xoffs and xoffs * 0.0254 or 0
543         local yo = yoffs and yoffs * 0.0254 or 0
544         local zo = zoffs and zoffs * 0.0254 or 0
545
546         if onpole == "_onpole" then
547                 if not fdir then
548                         return {
549                                 type = "wallmounted",
550                                 wall_side =   { -0.5 - 0.3125 + zo, -ty + yo, -tx + xo, -0.4375 - 0.3125 + zo, ty + yo , tx + xo },
551                                 wall_top =    {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5 },
552                                 wall_bottom = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5 },
553                         }
554                 else
555                         return {
556                                 type = "fixed",
557                                 fixed = { -tx + xo, -ty + yo, 0.5 + 0.3125 + zo, tx + xo, ty + yo, 0.4375 + 0.3125 + zo }
558                         }
559                 end
560         else
561                 if not fdir then
562                         return {
563                                 type = "wallmounted",
564                                 wall_side =   { -0.5, -ty, -tx, -0.4375, ty, tx },
565                                 wall_top =    { -tx - xo, 0.5 + zo, -ty + yo, tx - xo, 0.4375 + zo, ty + yo},
566                                 wall_bottom = { -tx - xo, -0.5 + zo, -ty + yo, tx - xo, -0.4375 + zo, ty + yo }
567                         }
568                 else
569                         return {
570                                 type = "fixed",
571                                 fixed = { -tx + xo, -ty + yo, 0.5 + zo, tx + xo, ty + yo, 0.4375 + zo}
572                         }
573                 end
574         end
575 end
576
577 function signs_lib.check_for_pole(pos, pointed_thing)
578         local ppos = minetest.get_pointed_thing_position(pointed_thing)
579         local pnode = minetest.get_node(ppos)
580         local pdef = minetest.registered_items[pnode.name]
581
582         if signs_lib.allowed_poles[pnode.name]
583                   or (pdef and pdef.drawtype == "fencelike")
584                   or string.find(pnode.name, "default:fence_")
585                   or string.find(pnode.name, "_post")
586                   or string.find(pnode.name, "fencepost")
587                   or (pnode.name == "streets:bigpole" and pnode.param2 < 4)
588                   or (pnode.name == "streets:bigpole" and pnode.param2 > 19 and pnode.param2 < 24) then
589                 return true
590         end
591 end
592
593 function signs_lib.after_place_node(pos, placer, itemstack, pointed_thing, locked)
594         local ppos = minetest.get_pointed_thing_position(pointed_thing)
595         local pnode = minetest.get_node(ppos)
596         local pdef = minetest.registered_items[pnode.name]
597         local playername = placer:get_player_name()
598
599         if signs_lib.check_for_pole(pos, pointed_thing) then
600                 local node = minetest.get_node(pos)
601                 minetest.swap_node(pos, {name = itemstack:get_name().."_onpole", param2 = node.param2})
602         end
603         if locked then
604                 local meta = minetest.get_meta(pos)
605                 meta:set_string("owner", playername)
606                 meta:set_string("infotext", S("Locked sign, owned by @1\n", playername))
607         end
608 end
609
610 function signs_lib.register_fence_with_sign()
611         minetest.log("warning", "[signs_lib] ".."Attempt to call no longer used function signs_lib.register_fence_with_sign()")
612 end
613
614 -- restore signs' text after /clearobjects and the like, the next time
615 -- a block is reloaded by the server.
616
617 minetest.register_lbm({
618         nodenames = signs_lib.lbm_restore_nodes,
619         name = "signs_lib:restore_sign_text",
620         label = "Restore sign text",
621         run_at_every_load = true,
622         action = function(pos, node)
623                 signs_lib.update_sign(pos,nil,nil,node)
624         end
625 })
626
627 -- Convert old signs on fenceposts into signs on.. um.. fence posts :P
628
629 minetest.register_lbm({
630         nodenames = signs_lib.old_fenceposts_with_signs,
631         name = "signs_lib:fix_fencepost_signs",
632         label = "Change single-node signs on fences into normal",
633         run_at_every_load = true,
634         action = function(pos, node)
635
636                 local fdir = node.param2 % 8
637                 local signpos = {
638                         x = pos.x + signs_lib.fdir_to_back[fdir+1][1],
639                         y = pos.y,
640                         z = pos.z + signs_lib.fdir_to_back[fdir+1][2]
641                 }
642
643                 if minetest.get_node(signpos).name == "air" then
644                         local new_wmdir = minetest.dir_to_wallmounted(minetest.facedir_to_dir(fdir))
645                         local oldfence =  signs_lib.old_fenceposts[node.name]
646                         local newsign =   signs_lib.old_fenceposts_replacement_signs[node.name]
647
648                         for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
649                                 local e = v:get_luaentity()
650                                 if e and e.name == "signs_lib:text" then
651                                         v:remove()
652                                 end
653                         end
654
655                         local oldmeta = minetest.get_meta(pos):to_table()
656                         minetest.set_node(pos, {name = oldfence})
657                         minetest.set_node(signpos, { name = newsign, param2 = new_wmdir })
658                         local newmeta = minetest.get_meta(signpos)
659                         newmeta:from_table(oldmeta)
660                         signs_lib.update_sign(signpos)
661                 end
662         end
663 })