-- LUALOCALS < ---------------------------------------------------------
local klots, math, minetest
    = klots, math, minetest
local math_acos, math_cos, math_pi, math_random, math_sin
    = math.acos, math.cos, math.pi, math.random, math.sin
-- LUALOCALS > ---------------------------------------------------------

local modname = minetest.get_current_modname()

local function play(data, pos)
	return minetest.sound_play(modname .. "_air",
		{
			to_player = data.pname,
			pos = pos,
			gain = 0.001,
			pitch = 0.9 + math_random() * 0.2
		})
end

klots.register_playerstep(function(player, data, dtime)
		data.cd = (data.cd or 0) - dtime
		if data.cd > 0 then return end
		data.cd = math_random()

		local pos = player:get_pos()
		pos.y = pos.y + player:get_properties().eye_height

		local l = math_acos(2 * math_random() - 1) - math_pi / 2
		local t = math_pi * 2 * math_random()
		local target = {
			x = pos.x + math_cos(l) * math_sin(t) * 8,
			y = pos.y + math_sin(l) * 8,
			z = pos.z + math_cos(l) * math_cos(t) * 8
		}

		data.pname = data.pname or player:get_player_name()
		for pt in minetest.raycast(pos, target, false, true) do
			if pt.type == "node" then
				return play(data, pt.intersection_point or pt.above)
			end
		end
		return play(data, target)
	end)

minetest.register_on_joinplayer(function(player)
		minetest.sound_play(modname .. "_noise", {
				to_player = player:get_player_name(),
				loop = true,
				gain = 0.0002
			})
	end)
