-- LUALOCALS < ---------------------------------------------------------
local klots, minetest, vector
    = klots, minetest, vector
-- LUALOCALS > ---------------------------------------------------------

if klots.editmode then return end

local modname = minetest.get_current_modname()

local actuate_opacity = 64

local function playercast(player)
	local pos = player:get_pos()
	pos.y = pos.y + player:get_properties().eye_height
	local look = player:get_look_dir()
	local target = vector.add(pos, vector.multiply(look, 4))
	for pt in minetest.raycast(pos, target, false, false) do
		if pt.type == "node" then
			return pt
		end
	end
end

local function settip(player, data, pos)
	if not pos then
		if data.hud then
			player:hud_remove(data.hud)
			data.hud = nil
		end
		return
	end
	local ppos = player:get_pos()
	ppos.y = ppos.y + player:get_properties().eye_height
	local diff = vector.subtract(ppos, pos)
	local scale = 1.25 / vector.length(diff)
	if not data.hud then
		data.hud = player:hud_add({
				hud_elem_type = "image_waypoint",
				world_pos = pos,
				text = modname .. "_actuate.png^[opacity:"
				.. actuate_opacity,
				scale = {x = scale, y = scale},
				precision = 0,
				number = 0xffffff,
				z_index = -250,
				alignment = {x = 0, y = 0}
			})
		data.pos = pos
		data.scale = scale
	else
		if not vector.equals(data.pos, pos) then
			player:hud_change(data.hud, "world_pos", pos)
			data.pos = pos
		end
		local sdiff = data.scale / scale
		if sdiff < 0.99 or sdiff > 1.01 then
			player:hud_change(data.hud, "scale", {x = scale, y = scale})
			data.scale = scale
		end
	end
end

local function nodeface(pt)
	return vector.multiply(vector.add(
			pt.under, pt.above), 0.5)
end

klots.register_playerstep(function(player, data)
		local pt = playercast(player)
		if not pt then return settip(player, data) end
		local node = minetest.get_node(pt.under)
		local def = minetest.registered_nodes[node.name]
		if def and def.on_actuate then
			return settip(player, data, nodeface(pt))
		end
		return settip(player, data)
	end)

minetest.register_on_joinplayer(function(player)
		if klots.editmode then
			player:set_properties({zoom_fov = 60})
		else
			player:set_fov(90)
		end
	end)
