init.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. ap = ap or {}
  2. ap.modpath = ap.modpath or minetest.get_modpath("ap")
  3. ap.players = ap.players or {}
  4. -- Number of seconds to keep track of player's reported positions.
  5. -- This must be at least 1 (though such a small value is NOT useful).
  6. ap.record_time = 60
  7. -- Localize vector.distance() for performance.
  8. local vector_distance = vector.distance
  9. function ap.get_record_time()
  10. return ap.record_time
  11. end
  12. function ap.update_players()
  13. local players = minetest.get_connected_players()
  14. for i=1, #players, 1 do
  15. local pref = players[i]
  16. local p = pref:get_pos() -- Note: position is NOT rounded.
  17. local t = ap.players[pref:get_player_name()].positions
  18. -- Don't add position to list of last recorded positions if the player
  19. -- hasn't moved since last time.
  20. local add = true
  21. if #t > 0 then
  22. local op = t[#t].pos
  23. if vector_distance(op, p) < 1 then
  24. add = false
  25. end
  26. end
  27. -- Insert position into player's record (for this session) and remove old
  28. -- entries from the beginning.
  29. if add then
  30. table.insert(t, {pos=p, time=os.time()})
  31. if #t > ap.record_time then
  32. table.remove(t, 1)
  33. end
  34. end
  35. end
  36. end
  37. -- Returns a list of positions for this player in the last few seconds,
  38. -- or an empty table if that player wasn't loaded.
  39. -- Each entry is a table in the format {pos, time}.
  40. function ap.get_position_list(pname)
  41. return ap.players[pname].positions or {}
  42. end
  43. function ap.on_joinplayer(pref)
  44. ap.players[pref:get_player_name()] = {
  45. positions = {},
  46. }
  47. end
  48. function ap.on_leaveplayer(pref)
  49. ap.players[pref:get_player_name()] = nil
  50. end
  51. local time = 0
  52. function ap.global_step(dtime)
  53. time = time + dtime
  54. if time < 1 then return end
  55. time = 0
  56. ap.update_players()
  57. end
  58. if not ap.registered then
  59. local c = "ap:core"
  60. local f = ap.modpath .. "/init.lua"
  61. reload.register_file(c, f, false)
  62. minetest.register_on_joinplayer(function(...)
  63. ap.on_joinplayer(...) end)
  64. minetest.register_on_leaveplayer(function(...)
  65. ap.on_leaveplayer(...) end)
  66. minetest.register_globalstep(function(...)
  67. ap.global_step(...) end)
  68. ap.registered = true
  69. end