misc_helpers.lua 17 KB

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