]> git.lizzy.rs Git - minetest.git/blob - builtin/common/misc_helpers.lua
Use vector.dot and vector.cross in vector.angle
[minetest.git] / builtin / common / misc_helpers.lua
1 -- Minetest: builtin/misc_helpers.lua
2
3 --------------------------------------------------------------------------------
4 -- Localize functions to avoid table lookups (better performance).
5 local string_sub, string_find = string.sub, string.find
6
7 --------------------------------------------------------------------------------
8 function basic_dump(o)
9         local tp = type(o)
10         if tp == "number" then
11                 return tostring(o)
12         elseif tp == "string" then
13                 return string.format("%q", o)
14         elseif tp == "boolean" then
15                 return tostring(o)
16         elseif tp == "nil" then
17                 return "nil"
18         -- Uncomment for full function dumping support.
19         -- Not currently enabled because bytecode isn't very human-readable and
20         -- dump's output is intended for humans.
21         --elseif tp == "function" then
22         --      return string.format("loadstring(%q)", string.dump(o))
23         else
24                 return string.format("<%s>", tp)
25         end
26 end
27
28 local keywords = {
29         ["and"] = true,
30         ["break"] = true,
31         ["do"] = true,
32         ["else"] = true,
33         ["elseif"] = true,
34         ["end"] = true,
35         ["false"] = true,
36         ["for"] = true,
37         ["function"] = true,
38         ["goto"] = true,  -- Lua 5.2
39         ["if"] = true,
40         ["in"] = true,
41         ["local"] = true,
42         ["nil"] = true,
43         ["not"] = true,
44         ["or"] = true,
45         ["repeat"] = true,
46         ["return"] = true,
47         ["then"] = true,
48         ["true"] = true,
49         ["until"] = true,
50         ["while"] = true,
51 }
52 local function is_valid_identifier(str)
53         if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
54                 return false
55         end
56         return true
57 end
58
59 --------------------------------------------------------------------------------
60 -- Dumps values in a line-per-value format.
61 -- For example, {test = {"Testing..."}} becomes:
62 --   _["test"] = {}
63 --   _["test"][1] = "Testing..."
64 -- This handles tables as keys and circular references properly.
65 -- It also handles multiple references well, writing the table only once.
66 -- The dumped argument is internal-only.
67
68 function dump2(o, name, dumped)
69         name = name or "_"
70         -- "dumped" is used to keep track of serialized tables to handle
71         -- multiple references and circular tables properly.
72         -- It only contains tables as keys.  The value is the name that
73         -- the table has in the dump, eg:
74         -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
75         dumped = dumped or {}
76         if type(o) ~= "table" then
77                 return string.format("%s = %s\n", name, basic_dump(o))
78         end
79         if dumped[o] then
80                 return string.format("%s = %s\n", name, dumped[o])
81         end
82         dumped[o] = name
83         -- This contains a list of strings to be concatenated later (because
84         -- Lua is slow at individual concatenation).
85         local t = {}
86         for k, v in pairs(o) do
87                 local keyStr
88                 if type(k) == "table" then
89                         if dumped[k] then
90                                 keyStr = dumped[k]
91                         else
92                                 -- Key tables don't have a name, so use one of
93                                 -- the form _G["table: 0xFFFFFFF"]
94                                 keyStr = string.format("_G[%q]", tostring(k))
95                                 -- Dump key table
96                                 t[#t + 1] = dump2(k, keyStr, dumped)
97                         end
98                 else
99                         keyStr = basic_dump(k)
100                 end
101                 local vname = string.format("%s[%s]", name, keyStr)
102                 t[#t + 1] = dump2(v, vname, dumped)
103         end
104         return string.format("%s = {}\n%s", name, table.concat(t))
105 end
106
107 --------------------------------------------------------------------------------
108 -- This dumps values in a one-statement format.
109 -- For example, {test = {"Testing..."}} becomes:
110 -- [[{
111 --      test = {
112 --              "Testing..."
113 --      }
114 -- }]]
115 -- This supports tables as keys, but not circular references.
116 -- It performs poorly with multiple references as it writes out the full
117 -- table each time.
118 -- The indent field specifies a indentation string, it defaults to a tab.
119 -- Use the empty string to disable indentation.
120 -- The dumped and level arguments are internal-only.
121
122 function dump(o, indent, nested, level)
123         local t = type(o)
124         if not level and t == "userdata" then
125                 -- when userdata (e.g. player) is passed directly, print its metatable:
126                 return "userdata metatable: " .. dump(getmetatable(o))
127         end
128         if t ~= "table" then
129                 return basic_dump(o)
130         end
131         -- Contains table -> true/nil of currently nested tables
132         nested = nested or {}
133         if nested[o] then
134                 return "<circular reference>"
135         end
136         nested[o] = true
137         indent = indent or "\t"
138         level = level or 1
139         local t = {}
140         local dumped_indexes = {}
141         for i, v in ipairs(o) do
142                 t[#t + 1] = dump(v, indent, nested, level + 1)
143                 dumped_indexes[i] = true
144         end
145         for k, v in pairs(o) do
146                 if not dumped_indexes[k] then
147                         if type(k) ~= "string" or not is_valid_identifier(k) then
148                                 k = "["..dump(k, indent, nested, level + 1).."]"
149                         end
150                         v = dump(v, indent, nested, level + 1)
151                         t[#t + 1] = k.." = "..v
152                 end
153         end
154         nested[o] = nil
155         if indent ~= "" then
156                 local indent_str = "\n"..string.rep(indent, level)
157                 local end_indent_str = "\n"..string.rep(indent, level - 1)
158                 return string.format("{%s%s%s}",
159                                 indent_str,
160                                 table.concat(t, ","..indent_str),
161                                 end_indent_str)
162         end
163         return "{"..table.concat(t, ", ").."}"
164 end
165
166 --------------------------------------------------------------------------------
167 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
168         delim = delim or ","
169         max_splits = max_splits or -2
170         local items = {}
171         local pos, len = 1, #str
172         local plain = not sep_is_pattern
173         max_splits = max_splits + 1
174         repeat
175                 local np, npe = string_find(str, delim, pos, plain)
176                 np, npe = (np or (len+1)), (npe or (len+1))
177                 if (not np) or (max_splits == 1) then
178                         np = len + 1
179                         npe = np
180                 end
181                 local s = string_sub(str, pos, np - 1)
182                 if include_empty or (s ~= "") then
183                         max_splits = max_splits - 1
184                         items[#items + 1] = s
185                 end
186                 pos = npe + 1
187         until (max_splits == 0) or (pos > (len + 1))
188         return items
189 end
190
191 --------------------------------------------------------------------------------
192 function table.indexof(list, val)
193         for i, v in ipairs(list) do
194                 if v == val then
195                         return i
196                 end
197         end
198         return -1
199 end
200
201 assert(table.indexof({"foo", "bar"}, "foo") == 1)
202 assert(table.indexof({"foo", "bar"}, "baz") == -1)
203
204 --------------------------------------------------------------------------------
205 if INIT ~= "client" then
206         function file_exists(filename)
207                 local f = io.open(filename, "r")
208                 if f == nil then
209                         return false
210                 else
211                         f:close()
212                         return true
213                 end
214         end
215 end
216 --------------------------------------------------------------------------------
217 function string:trim()
218         return (self:gsub("^%s*(.-)%s*$", "%1"))
219 end
220
221 assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
222
223 --------------------------------------------------------------------------------
224 function math.hypot(x, y)
225         local t
226         x = math.abs(x)
227         y = math.abs(y)
228         t = math.min(x, y)
229         x = math.max(x, y)
230         if x == 0 then return 0 end
231         t = t / x
232         return x * math.sqrt(1 + t * t)
233 end
234
235 --------------------------------------------------------------------------------
236 function math.sign(x, tolerance)
237         tolerance = tolerance or 0
238         if x > tolerance then
239                 return 1
240         elseif x < -tolerance then
241                 return -1
242         end
243         return 0
244 end
245
246 --------------------------------------------------------------------------------
247 function math.factorial(x)
248         assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
249         if x >= 171 then
250                 -- 171! is greater than the biggest double, no need to calculate
251                 return math.huge
252         end
253         local v = 1
254         for k = 2, x do
255                 v = v * k
256         end
257         return v
258 end
259
260 --------------------------------------------------------------------------------
261 function get_last_folder(text,count)
262         local parts = text:split(DIR_DELIM)
263
264         if count == nil then
265                 return parts[#parts]
266         end
267
268         local retval = ""
269         for i=1,count,1 do
270                 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
271         end
272
273         return retval
274 end
275
276 --------------------------------------------------------------------------------
277 function cleanup_path(temppath)
278
279         local parts = temppath:split("-")
280         temppath = ""
281         for i=1,#parts,1 do
282                 if temppath ~= "" then
283                         temppath = temppath .. "_"
284                 end
285                 temppath = temppath .. parts[i]
286         end
287
288         parts = temppath:split(".")
289         temppath = ""
290         for i=1,#parts,1 do
291                 if temppath ~= "" then
292                         temppath = temppath .. "_"
293                 end
294                 temppath = temppath .. parts[i]
295         end
296
297         parts = temppath:split("'")
298         temppath = ""
299         for i=1,#parts,1 do
300                 if temppath ~= "" then
301                         temppath = temppath .. ""
302                 end
303                 temppath = temppath .. parts[i]
304         end
305
306         parts = temppath:split(" ")
307         temppath = ""
308         for i=1,#parts,1 do
309                 if temppath ~= "" then
310                         temppath = temppath
311                 end
312                 temppath = temppath .. parts[i]
313         end
314
315         return temppath
316 end
317
318 function core.formspec_escape(text)
319         if text ~= nil then
320                 text = string.gsub(text,"\\","\\\\")
321                 text = string.gsub(text,"%]","\\]")
322                 text = string.gsub(text,"%[","\\[")
323                 text = string.gsub(text,";","\\;")
324                 text = string.gsub(text,",","\\,")
325         end
326         return text
327 end
328
329
330 function core.wrap_text(text, max_length, as_table)
331         local result = {}
332         local line = {}
333         if #text <= max_length then
334                 return as_table and {text} or text
335         end
336
337         for word in text:gmatch('%S+') do
338                 local cur_length = #table.concat(line, ' ')
339                 if cur_length > 0 and cur_length + #word + 1 >= max_length then
340                         -- word wouldn't fit on current line, move to next line
341                         table.insert(result, table.concat(line, ' '))
342                         line = {}
343                 end
344                 table.insert(line, word)
345         end
346
347         table.insert(result, table.concat(line, ' '))
348         return as_table and result or table.concat(result, '\n')
349 end
350
351 --------------------------------------------------------------------------------
352
353 if INIT == "game" then
354         local dirs1 = {9, 18, 7, 12}
355         local dirs2 = {20, 23, 22, 21}
356
357         function core.rotate_and_place(itemstack, placer, pointed_thing,
358                         infinitestacks, orient_flags, prevent_after_place)
359                 orient_flags = orient_flags or {}
360
361                 local unode = core.get_node_or_nil(pointed_thing.under)
362                 if not unode then
363                         return
364                 end
365                 local undef = core.registered_nodes[unode.name]
366                 if undef and undef.on_rightclick then
367                         return undef.on_rightclick(pointed_thing.under, unode, placer,
368                                         itemstack, pointed_thing)
369                 end
370                 local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
371
372                 local above = pointed_thing.above
373                 local under = pointed_thing.under
374                 local iswall = (above.y == under.y)
375                 local isceiling = not iswall and (above.y < under.y)
376
377                 if undef and undef.buildable_to then
378                         iswall = false
379                 end
380
381                 if orient_flags.force_floor then
382                         iswall = false
383                         isceiling = false
384                 elseif orient_flags.force_ceiling then
385                         iswall = false
386                         isceiling = true
387                 elseif orient_flags.force_wall then
388                         iswall = true
389                         isceiling = false
390                 elseif orient_flags.invert_wall then
391                         iswall = not iswall
392                 end
393
394                 local param2 = fdir
395                 if iswall then
396                         param2 = dirs1[fdir + 1]
397                 elseif isceiling then
398                         if orient_flags.force_facedir then
399                                 param2 = 20
400                         else
401                                 param2 = dirs2[fdir + 1]
402                         end
403                 else -- place right side up
404                         if orient_flags.force_facedir then
405                                 param2 = 0
406                         end
407                 end
408
409                 local old_itemstack = ItemStack(itemstack)
410                 local new_itemstack, removed = core.item_place_node(
411                         itemstack, placer, pointed_thing, param2, prevent_after_place
412                 )
413                 return infinitestacks and old_itemstack or new_itemstack
414         end
415
416
417 --------------------------------------------------------------------------------
418 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
419 --implies infinite stacks when performing a 6d rotation.
420 --------------------------------------------------------------------------------
421         local creative_mode_cache = core.settings:get_bool("creative_mode")
422         local function is_creative(name)
423                 return creative_mode_cache or
424                                 core.check_player_privs(name, {creative = true})
425         end
426
427         core.rotate_node = function(itemstack, placer, pointed_thing)
428                 local name = placer and placer:get_player_name() or ""
429                 local invert_wall = placer and placer:get_player_control().sneak or false
430                 core.rotate_and_place(itemstack, placer, pointed_thing,
431                                 is_creative(name),
432                                 {invert_wall = invert_wall}, true)
433                 return itemstack
434         end
435 end
436
437 --------------------------------------------------------------------------------
438 function core.explode_table_event(evt)
439         if evt ~= nil then
440                 local parts = evt:split(":")
441                 if #parts == 3 then
442                         local t = parts[1]:trim()
443                         local r = tonumber(parts[2]:trim())
444                         local c = tonumber(parts[3]:trim())
445                         if type(r) == "number" and type(c) == "number"
446                                         and t ~= "INV" then
447                                 return {type=t, row=r, column=c}
448                         end
449                 end
450         end
451         return {type="INV", row=0, column=0}
452 end
453
454 --------------------------------------------------------------------------------
455 function core.explode_textlist_event(evt)
456         if evt ~= nil then
457                 local parts = evt:split(":")
458                 if #parts == 2 then
459                         local t = parts[1]:trim()
460                         local r = tonumber(parts[2]:trim())
461                         if type(r) == "number" and t ~= "INV" then
462                                 return {type=t, index=r}
463                         end
464                 end
465         end
466         return {type="INV", index=0}
467 end
468
469 --------------------------------------------------------------------------------
470 function core.explode_scrollbar_event(evt)
471         local retval = core.explode_textlist_event(evt)
472
473         retval.value = retval.index
474         retval.index = nil
475
476         return retval
477 end
478
479 --------------------------------------------------------------------------------
480 function core.rgba(r, g, b, a)
481         return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
482                         string.format("#%02X%02X%02X", r, g, b)
483 end
484
485 --------------------------------------------------------------------------------
486 function core.pos_to_string(pos, decimal_places)
487         local x = pos.x
488         local y = pos.y
489         local z = pos.z
490         if decimal_places ~= nil then
491                 x = string.format("%." .. decimal_places .. "f", x)
492                 y = string.format("%." .. decimal_places .. "f", y)
493                 z = string.format("%." .. decimal_places .. "f", z)
494         end
495         return "(" .. x .. "," .. y .. "," .. z .. ")"
496 end
497
498 --------------------------------------------------------------------------------
499 function core.string_to_pos(value)
500         if value == nil then
501                 return nil
502         end
503
504         local p = {}
505         p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
506         if p.x and p.y and p.z then
507                 p.x = tonumber(p.x)
508                 p.y = tonumber(p.y)
509                 p.z = tonumber(p.z)
510                 return p
511         end
512         p = {}
513         p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
514         if p.x and p.y and p.z then
515                 p.x = tonumber(p.x)
516                 p.y = tonumber(p.y)
517                 p.z = tonumber(p.z)
518                 return p
519         end
520         return nil
521 end
522
523 assert(core.string_to_pos("10.0, 5, -2").x == 10)
524 assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
525 assert(core.string_to_pos("asd, 5, -2)") == nil)
526
527 --------------------------------------------------------------------------------
528 function core.string_to_area(value)
529         local p1, p2 = unpack(value:split(") ("))
530         if p1 == nil or p2 == nil then
531                 return nil
532         end
533
534         p1 = core.string_to_pos(p1 .. ")")
535         p2 = core.string_to_pos("(" .. p2)
536         if p1 == nil or p2 == nil then
537                 return nil
538         end
539
540         return p1, p2
541 end
542
543 local function test_string_to_area()
544         local p1, p2 = core.string_to_area("(10.0, 5, -2) (  30.2,   4, -12.53)")
545         assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
546         assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)
547
548         p1, p2 = core.string_to_area("(10.0, 5, -2  30.2,   4, -12.53")
549         assert(p1 == nil and p2 == nil)
550
551         p1, p2 = core.string_to_area("(10.0, 5,) -2  fgdf2,   4, -12.53")
552         assert(p1 == nil and p2 == nil)
553 end
554
555 test_string_to_area()
556
557 --------------------------------------------------------------------------------
558 function table.copy(t, seen)
559         local n = {}
560         seen = seen or {}
561         seen[t] = n
562         for k, v in pairs(t) do
563                 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
564                         (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
565         end
566         return n
567 end
568
569
570 function table.insert_all(t, other)
571         for i=1, #other do
572                 t[#t + 1] = other[i]
573         end
574         return t
575 end
576
577
578 --------------------------------------------------------------------------------
579 -- mainmenu only functions
580 --------------------------------------------------------------------------------
581 if INIT == "mainmenu" then
582         function core.get_game(index)
583                 local games = core.get_games()
584
585                 if index > 0 and index <= #games then
586                         return games[index]
587                 end
588
589                 return nil
590         end
591 end
592
593 if INIT == "client" or INIT == "mainmenu" then
594         function fgettext_ne(text, ...)
595                 text = core.gettext(text)
596                 local arg = {n=select('#', ...), ...}
597                 if arg.n >= 1 then
598                         -- Insert positional parameters ($1, $2, ...)
599                         local result = ''
600                         local pos = 1
601                         while pos <= text:len() do
602                                 local newpos = text:find('[$]', pos)
603                                 if newpos == nil then
604                                         result = result .. text:sub(pos)
605                                         pos = text:len() + 1
606                                 else
607                                         local paramindex =
608                                                 tonumber(text:sub(newpos+1, newpos+1))
609                                         result = result .. text:sub(pos, newpos-1)
610                                                 .. tostring(arg[paramindex])
611                                         pos = newpos + 2
612                                 end
613                         end
614                         text = result
615                 end
616                 return text
617         end
618
619         function fgettext(text, ...)
620                 return core.formspec_escape(fgettext_ne(text, ...))
621         end
622 end
623
624 local ESCAPE_CHAR = string.char(0x1b)
625
626 function core.get_color_escape_sequence(color)
627         return ESCAPE_CHAR .. "(c@" .. color .. ")"
628 end
629
630 function core.get_background_escape_sequence(color)
631         return ESCAPE_CHAR .. "(b@" .. color .. ")"
632 end
633
634 function core.colorize(color, message)
635         local lines = tostring(message):split("\n", true)
636         local color_code = core.get_color_escape_sequence(color)
637
638         for i, line in ipairs(lines) do
639                 lines[i] = color_code .. line
640         end
641
642         return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
643 end
644
645
646 function core.strip_foreground_colors(str)
647         return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
648 end
649
650 function core.strip_background_colors(str)
651         return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
652 end
653
654 function core.strip_colors(str)
655         return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
656 end
657
658 function core.translate(textdomain, str, ...)
659         local start_seq
660         if textdomain == "" then
661                 start_seq = ESCAPE_CHAR .. "T"
662         else
663                 start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
664         end
665         local arg = {n=select('#', ...), ...}
666         local end_seq = ESCAPE_CHAR .. "E"
667         local arg_index = 1
668         local translated = str:gsub("@(.)", function(matched)
669                 local c = string.byte(matched)
670                 if string.byte("1") <= c and c <= string.byte("9") then
671                         local a = c - string.byte("0")
672                         if a ~= arg_index then
673                                 error("Escape sequences in string given to core.translate " ..
674                                         "are not in the correct order: got @" .. matched ..
675                                         "but expected @" .. tostring(arg_index))
676                         end
677                         if a > arg.n then
678                                 error("Not enough arguments provided to core.translate")
679                         end
680                         arg_index = arg_index + 1
681                         return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
682                 elseif matched == "n" then
683                         return "\n"
684                 else
685                         return matched
686                 end
687         end)
688         if arg_index < arg.n + 1 then
689                 error("Too many arguments provided to core.translate")
690         end
691         return start_seq .. translated .. end_seq
692 end
693
694 function core.get_translator(textdomain)
695         return function(str, ...) return core.translate(textdomain or "", str, ...) end
696 end
697
698 --------------------------------------------------------------------------------
699 -- Returns the exact coordinate of a pointed surface
700 --------------------------------------------------------------------------------
701 function core.pointed_thing_to_face_pos(placer, pointed_thing)
702         -- Avoid crash in some situations when player is inside a node, causing
703         -- 'above' to equal 'under'.
704         if vector.equals(pointed_thing.above, pointed_thing.under) then
705                 return pointed_thing.under
706         end
707
708         local eye_height = placer:get_properties().eye_height
709         local eye_offset_first = placer:get_eye_offset()
710         local node_pos = pointed_thing.under
711         local camera_pos = placer:get_pos()
712         local pos_off = vector.multiply(
713                         vector.subtract(pointed_thing.above, node_pos), 0.5)
714         local look_dir = placer:get_look_dir()
715         local offset, nc
716         local oc = {}
717
718         for c, v in pairs(pos_off) do
719                 if nc or v == 0 then
720                         oc[#oc + 1] = c
721                 else
722                         offset = v
723                         nc = c
724                 end
725         end
726
727         local fine_pos = {[nc] = node_pos[nc] + offset}
728         camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
729         local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
730
731         for i = 1, #oc do
732                 fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
733         end
734         return fine_pos
735 end
736
737 function core.string_to_privs(str, delim)
738         assert(type(str) == "string")
739         delim = delim or ','
740         local privs = {}
741         for _, priv in pairs(string.split(str, delim)) do
742                 privs[priv:trim()] = true
743         end
744         return privs
745 end
746
747 function core.privs_to_string(privs, delim)
748         assert(type(privs) == "table")
749         delim = delim or ','
750         local list = {}
751         for priv, bool in pairs(privs) do
752                 if bool then
753                         list[#list + 1] = priv
754                 end
755         end
756         return table.concat(list, delim)
757 end
758
759 assert(core.string_to_privs("a,b").b == true)
760 assert(core.privs_to_string({a=true,b=true}) == "a,b")