-- Mobs Api+random(1)

mobs = {}
mobs.mod = "redo"
mobs.version = "20180505"


-- Intllib
local MP = minetest.get_modpath(minetest.get_current_modname())
local S, NS = dofile(MP .. "/intllib.lua")
mobs.intllib = S


local isInvisible=function(player)
	if not minetest.is_player(player) then return false end
	--return not minetest.check_player_privs(player, "interact") or mfplayers[player:get_player_name()].invisible
	--local name=player:get_player_name()
	--if mfplayers[name] and mfplayers[name].invisible then return true end
	return not minetest.check_player_privs(player, "interact")
end

-- creative check
local creative_mode_cache = minetest.settings:get_bool("creative_mode")
function mobs.is_creative(name)
	return creative_mode_cache or minetest.check_player_privs(name, {creative = true})
end


-- localize math functions
local Vero= vector.zero() -- {x=0, y=0, z=0}
local pi = math.pi
local square = math.sqrt
local sin = math.sin
local cos = math.cos
local abs = math.abs
local min = math.min
local max = math.max
local atann = math.atan
local random = math.random
local floor = math.floor
local atan = function(x)
	if not x or x ~= x then
		--error("atan bassed NaN")
		return 0
	else
		return atann(x)
	end
end


-- Load settings
local damage_enabled = minetest.settings:get_bool("enable_damage")
local creative = minetest.settings:get_bool("creative_mode")
local show_health = minetest.settings:get_bool("mob_show_health") == true
local mob_chance_multiplier = tonumber(minetest.settings:get("mob_chance_multiplier") or 1)

-- calculate aoc range for mob count
local aosrb = tonumber(minetest.settings:get("active_object_send_range_blocks"))
local abr = tonumber(minetest.settings:get("active_block_range"))
local aoc_range = max(aosrb, abr) * 16

-- default nodes
mobs.fallback_node = minetest.registered_aliases["mapgen_dirt"] or "default:dirt"

mobs.tp_fx= function(pos)
	minetest.add_particlespawner
	{
		amount=25,
		time=1,
		minpos={x=pos.x-0.1, y=pos.y, z=pos.z-0.1},
		maxpos={x=pos.x+0.1, y=pos.y, z=pos.z+0.1},
		minvel={x=0,y=1,z=0},
		maxvel={x=0,y=3,z=0},
		minsize=3,
		maxsize=4,
		glow=7,
		texture={name="default_mineral_mese.png", alpha_tween={1,0}}
	}
end

local function dmg_fx(pos, damage)
	local radius=5
	minetest.add_particlespawner({
		amount = damage,
		time = 0.1,
		minpos = pos,
		maxpos = pos,
		minvel = {x = -radius, y = 1, z = -radius},
		maxvel = {x = radius, y = 1, z = radius},
		minacc = {x = 0, y = -7, z = 0},
		maxacc = {x = 0, y = -7, z = 0},
		drag={x=5, y=0, z=5},
		minexptime = 5,
		maxexptime = 20,
		minsize = 0.25,
		maxsize = 0.25,
		texture ={name="dot.png^[colorize:orange", alpha_tween={1,0}} ,
		glow=1,
		collisiondetection=true,
		bounce=0,
	})

end

local half_height=function(self)
	return (self.initial_properties.collisionbox[2] + self.initial_properties.collisionbox[5]) / 2
end
	

local must_flee=function(self)
	if self.suicidal then return false end
	return (self.health/self.initial_properties.hp_max) < math.sqrt(random())
end

-- play sound
local mob_sound = function(self, sound)

	if sound then
		minetest.sound_play(sound, {
			object = self.object,
			max_hear_distance = self.sounds.distance
		}, true)
	end
end


-- attack player/mob
local do_attack = function(self, player)

	--[[
	if self.state == "attack" then
		return
	end
	]]

	self.attack = player
	self.state = "attack"
	self.lifespan=300

	if random(0, 100) < 90 then
		mob_sound(self, self.sounds.war_cry)
	end
	mf.threatWarn(player)
end

-- set and return valid yaw
local set_yaw = function(self, yaw)

	self.object:set_yaw(yaw)
	return yaw
end

local get_yaw = function(self)

	return (self.object:get_yaw() or 0)
end

-- global function to set mob yaw
--[[
function mobs:yaw(self, yaw)
	set_yaw(self, yaw)
end
]]

local function angle_to(self, p)
	local s = self.object:get_pos()
	if p.x==s.x then return 0 end
	local yaw = (atan((p.z-s.z)/(p.x-s.x)) + pi / 2) - self.rotate
	if p.x > s.x then yaw = yaw + pi end
	return yaw
end

-- move mob in facing direction
local set_velocity = function(self, v)

	local yaw = get_yaw(self)

	local vel= self.object:get_velocity()
	if not vel then return end
	-- get_velocity can return numbers that set_velocity won't accept...
	if abs(vel.y)>10000 then vel.y=0 end
	self.object:set_velocity({
		x = sin(yaw+self.rotate) * -v,
		y = (self.fly and 0) or vel.y,
		z = cos(yaw+self.rotate) * v
	})

end

-- apparently automatic_face_dir is not protected against floating point gitches when it
-- tries to compute the direction angle of a null vector So we can't use Vero here.
local stop_moving= function(self) self.object:set_velocity(self.object:get_velocity()*0.01) end

-- above function exported for mount.lua
function mobs:set_animation(self, anim)
	set_animation(self, anim)
end

-- set defined animation
local set_animation = function(self, anim)
	if not self.animation or not anim or not self.animation[anim .. "_start"] or not self.animation[anim .. "_end"] then
		return
	end
	self.current_anim = anim
	if anim=="freeze" then
		-- virtual
		set_velocity(self, 0.25)
		self.object:set_animation_frame_speed(1);
	else
		self.object:set_animation({ x = self.animation[anim .. "_start"], y = self.animation[anim .. "_end"]},
		self.animation[anim .. "_speed"] or self.animation.speed_normal or 15,
		0, self.animation[anim .. "_loop"] ~= false)
	end
end



local do_stand=function(self)
	stop_moving(self)
	set_animation(self, "stand")
	self.state = "stand"
end

local do_walk=function(self)
	self.state = "walk"
	set_animation(self, "walk")
	set_velocity(self, self.walk_velocity)
end


-- used for NPCs
function mobs.turn_away_from(self, pos)
	-- self.object:set_yaw(angle_to(self, pos)+pi)
	set_yaw(self, angle_to(self, pos)+pi)
	do_walk(self)
end

-- used by whales
function mobs.force_walk(self)
	do_walk(self)
end

local get_distance = vector.distance

-- check line of sight (BrunoMine)

--[[
local line_of_sight=function(self, pos1, pos2)
	local ray=minetest.raycast(pos1, pos2, true, false)
	local thing=ray:next()
	while thing do
		if thing.type=="object" and thing.ref~=self.object and not thing.ref:is_player() then return false end
		if thing.type=="node" then
			local node=minetest.registered_items[minetest.get_node(thing.under).name]
			if node and node.walkable then return false end
		end
		thing=ray:next()
	end
	return true
end
]]

local can_see=function(self, entity)
	if isInvisible(entity) then return false end
	local p1=self.object:get_pos()
	p1.y=p1.y + self.initial_properties.collisionbox[5]
	local p2=entity:get_pos()
	if not p2 then return false end
	p2.y=p2.y + entity:get_properties().collisionbox[5]

	local ray=minetest.raycast(p1, p2, true, false)
	local thing=ray:next()
	while thing do
		if thing.type=="node" then
			local node=minetest.registered_items[minetest.get_node(thing.under).name]
			if node and node.walkable then return false end
		elseif thing.type=="object" and thing.ref~=self.object and thing.ref~=entity then
			return false
		end
		thing=ray:next()
	end
	return true
end

-- are we flying in what we are suppose to? (taikedz)
local flight_check = function(self, pos_w)

	local nod = (pos_w and minetest.get_node(pos_w).name) or self.standing_in
	local def = minetest.registered_nodes[nod]

	if not def then return false end -- nil check

	if type(self.fly_in) == "string"
		and nod == self.fly_in then

		return true

	elseif type(self.fly_in) == "table" then

		for _,fly_in in pairs(self.fly_in) do

			if nod == fly_in then

				return true
			end
		end
	end

	-- stops mobs getting stuck inside stairs and plantlike nodes
	if def.drawtype ~= "airlike"
		and def.drawtype ~= "liquid"
		and def.drawtype ~= "flowingliquid" then
		return true
	end

	return false
end


-- custom particle effects
--[[
local effect = function(pos, amount, texture, min_size, max_size, radius, gravity, glow)

	radius = radius or 3
	min_size = min_size or 0.5
	max_size = max_size or 1
	gravity = gravity or -10
	glow = glow or 0

	minetest.add_particlespawner({
		amount = amount,
		time = 0.1,
		minpos = pos,
		maxpos = pos,
		minvel = {x = -radius, y = -radius, z = -radius},
		maxvel = {x = radius, y = radius, z = radius},
		minacc = {x = 0, y = gravity, z = 0},
		maxacc = {x = 0, y = gravity, z = 0},
		minexptime = 0.1,
		maxexptime = 0.5,
		minsize = min_size,
		maxsize = max_size,
		texture = texture,
		glow = glow,
	})
end
]]

-- update nametag colour
local update_tag = function(self)

	local col = "#00FF00"
	local qua = self.initial_properties.hp_max / 4

	if self.health <= floor(qua * 3) then
		col = "#FFFF00"
	end

	if self.health <= floor(qua * 2) then
		col = "#FF6600"
	end

	if self.health <= floor(qua) then
		col = "#FF0000"
	end

	self.object:set_properties({
		nametag = self.nametag,
		nametag_color = col
	})

end


-- drop items
local item_drop = function(self)

	local obj, item, num
	local pos = self.object:get_pos()

	self.drops = self.drops or {} -- nil check

	for n = 1, #self.drops do
		if random(1, self.drops[n].chance)== 1 then

			num = random(self.drops[n].min or 1, self.drops[n].max or 1)
			item = self.drops[n].name

			-- add item if it exists
			obj = minetest.add_item(pos, ItemStack(item .. " " .. num))

			if obj and obj:get_luaentity() then

				obj:set_velocity({ x = random(-10, 10) / 9, y = 6, z = random(-10, 10) / 9, })
			elseif obj then
				obj:remove() -- item does not exist
			end
		end
	end

	self.drops = {} 
end


-- check if mob is dead or only hurt
local check_for_death = function(self, cause, cmi_cause)

	-- has health actually changed?
	if self.health == self.old_health and self.health > 0 then
		return
	end

	self.old_health = self.health

	-- still got some health? play hurt sound
	if self.health > 0 then

		mob_sound(self, self.sounds.damage)

		-- make sure health isn't higher than max
		self.health=min(self.health, self.initial_properties.hp_max)

		-- backup nametag so we can show health stats
		if not self.nametag2 then
			self.nametag2 = self.nametag or ""
		end

		if show_health
			and (cmi_cause and cmi_cause.type == "punch") then

			self.htimer = 2
			self.nametag = "♥ " .. self.health .. " / " .. self.initial_properties.hp_max

			update_tag(self)
		end

		return false
	end

	local pos = self.object:get_pos()

	item_drop(self)

	-- default death function and die animation (if defined)
	if self.animation
		and self.animation.die_start
		and self.animation.die_end then

		self.attack = nil
		self.timer = 0
		self.passive = true
		self.state = "die"
		stop_moving(self)
		set_animation(self, "die")
	else
		--self.reqRemoval=true -- self.object:remove()
		set_animation(self, "stand")
		--self.object:set_rotation { x=0, y=0, z=math.pi }
	end

	-- mob_sound(self, self.sounds.death)
	minetest.sound_play("default_tool_break", { object = self.object, pitch=0.5, gain=0.5, max_hear_distance = 5 }, true)
	
	dmg_fx({x=pos.x, y=pos.y+half_height(self), z=pos.z}, self.initial_properties.hp_max)
	-- FWIW original mod would shunt most actions if on_die is set. As most of them are
	-- easily avoidable, I think it is more convenient to have on_die do additional stuff.
	if self.on_die then self.on_die(self, pos) end
	return true
end


-- check if within physical map limits (-30911 to 30927)
local within_limits = function(pos, radius)

	-- fast check
	if vector.length(pos) < 30000 then return true end

	if  (pos.x - radius) > -30913
		and (pos.x + radius) <  30928
		and (pos.y - radius) > -30913
		and (pos.y + radius) <  30928
		and (pos.z - radius) > -30913
		and (pos.z + radius) <  30928 then
		return true -- within limits
	end

	return false -- beyond limits
end

-- get node but use fallback for nil or unknown
local node_ok = function(pos)
	return minetest.get_node_or_nil(pos) or minetest.registered_nodes["air"]
end



-- is mob facing a cliff
local is_at_cliff = function(self)

	if self.fly then
		return false
	end

	local pos = self.object:get_pos()
	if not pos then return false end

	--[[
	local yaw = get_yaw(self)
	-- we assume here that the colbox is X and Z centered (never seen a model which wasn't)
	local ypos = pos.y - (self.initial_properties.collisionbox[5] - self.initial_properties.collisionbox[2])-0.1

	local nothing, pos=minetest.line_of_sight(
	{x = pos.x,  y = ypos, z = pos.z },
	{x = pos.x, y = ypos - self.fear_height, z = pos.z}
	) 
	if nothing then
		return true
	end
	return false
	]]
	local y = pos.y + self.initial_properties.collisionbox[2]-0.1
	pos=pos+vector.normalize(self.object:get_velocity()) -- basically +look_dir()
	pos.y=y

	local nn=minetest.get_node(pos).name
	local node=minetest.registered_nodes[nn]
	if node and node.walkable then return false end
	pos.y=pos.y-1
	nn=minetest.get_node(pos).name
	node=minetest.registered_nodes[nn]
	if node and node.walkable then return false end
	return true
end



local can_pass_through=function(name)
	local node=minetest.registered_nodes[name]
	if not node then return false end
	if minetest.get_item_group(name, "stair")+minetest.get_item_group(name, "slab")~=0 then 
		return true
	end
	return not node.walkable 
end

local do_jump = function(self, force, touching_ground)
	-- avoid silly jumps.
	if self.state=="stand" then return false end


	local pos = self.object:get_pos()
	if not pos then return false end
	local yaw = get_yaw(self)
	local props=self.initial_properties

	-- probing only ahead doesn't work well because cubic collboxes.
	local rnd_yaw=yaw+random(-1.5, 1.5) -- approx. +- pi/2
	local dist=props.collisionbox[4]*2
	local dir_x = -sin(rnd_yaw-self.rotate)*dist
	local dir_z = cos(rnd_yaw-self.rotate)*dist

	-- what is in front of mob?
	local node_pos=vector.new(pos.x+dir_x, pos.y+self.initial_properties.collisionbox[2], pos.z+dir_z)

	local node=node_ok(node_pos)

	if not force and can_pass_through(node.name) then
		return false
	end
	-- Something's in the way.
	node_pos.y=node_pos.y+self.initial_properties.stepheight+0.1	
	node=node_ok(node_pos)
	if not force and can_pass_through(node.name) then
		-- mob will stepheight over it.
		return false
	end
	-- That something is at least two nodes high, mob needs to jump or go around
	if self.fly or not self.jump or self.jump_height<1 then
		-- can't jump. automatic movement dir should already have altered the orientation of the mob.
		local angle=(vector.angle(node_pos, pos)<=0 and pi/4) or -pi/4
		local dir=vector.rotate_around_axis(vector.new(1,0,0), vector.new(0,1,0), yaw+angle)
		local vel= (self.state~="walk" and self.run_velocity) or self.walk_velocity
		self.object:set_velocity(vector.normalize(dir)*vel)
		-- animation should already be correct ?
		return false
	elseif touching_ground then
		-- touching_ground can happen during a jump, so we cannot use add_velocity().
		local v=self.object:get_velocity()
		v.y=self.jump_height
		self.object:set_velocity(v)

		set_animation(self, "jump")
		return true
	end
	return false
end

-- environmental damage (water, lava, fire, light etc.)
local do_env_damage = function(self)

	-- feed/tame text timer (so mob 'full' messages dont spam chat)
	if self.htimer > 0 then
		self.htimer = self.htimer - 1
	end

	-- reset nametag after showing health stats
	if self.htimer < 1 and self.nametag2 then

		self.nametag = self.nametag2
		self.nametag2 = nil

		update_tag(self)
	end

	local pos = self.object:get_pos()

	-- remove mob if beyond map limits
	--[[
	if not within_limits(pos, 0) then
		self.reqRemoval=true -- self.object:remove()
		return
	end
	--]]


	-- don't fall when on ignore, just stand still
	if self.standing_in == "ignore" then
		stop_moving(self)
		return
	end

	local nodef = minetest.registered_nodes[self.standing_in]

	-- pos.y = pos.y + 1 -- for particle effect position

	local dmg=0
	if self.env_dmg[self.standing_in] then
		dmg=self.env_dmg[self.standing_in]
	elseif self.water_damage and nodef.groups.water then
		dmg=self.water_damage
	elseif nodef.damage_per_second >=1 then
		dmg=nodef.damage_per_second
	elseif self.type=="monster" and minetest.is_protected(pos, "") then
		dmg=1
	elseif self.pause_timer<=0 then
		dmg=-self.regen
	end

	if dmg >= 1 then
		-- dmg >=1 because of the Shadow.
		self.object:punch(self.object, 1.0, {
			full_punch_interval = 1.0,
			damage_groups = {fleshy = dmg, knockback=0.25},
		}, nil)
		self.wasHit=false -- don't want melding because of protection damage.
		local yaw=get_yaw(self)
		if yaw then
			-- set_yaw(self,angle_to(self, vector.round(pos))+pi)
			-- set_velocity(self, self.run_velocity)
			self.object:set_velocity(vector.direction(pos, vector.round(pos))*self.run_velocity)
			set_animation(self, "run")
			-- self.state = "runaway"
			-- self.runaway_timer = 1
			-- self.timer=0
		end
	else
		self.health=max(0,min(self.health-dmg,self.initial_properties.hp_max))
		check_for_death(self, "hit", {type = "punch"})
	end
end




-- should mob follow what I'm holding ?
local follow_holding = function(self, clicker)

	--if mobs.invis[clicker:get_player_name()] then
	if isInvisible(clicker) then
		return false
	end

	local item = clicker:get_wielded_item()
	local t = type(self.follow)

	-- single item
	if t == "string"
		and item:get_name() == self.follow then
		return true

		-- multiple items
	elseif t == "table" then

		for no = 1, #self.follow do

			if self.follow[no] == item:get_name() then
				return true
			end
		end
	end

	return false
end


-- find and replace what mob is looking for (grass, wheat etc.)
local replace = function(self)
	if not self.env_alt then return end
	local pos=self.object:get_pos()
	if not pos then return end
	local alt=self.env_alt[self.standing_in]
	if alt and random(1, alt[2])==1 and not minetest.is_protected(pos) then
		minetest.set_node(pos, {name = alt[1]})
	end
end


-- specific attacks
local specific_attack = function(list, what)

	-- no list so attack default (player, animals etc.)
	if list == nil then
		return true
	end

	-- found entity on list to attack?
	for no = 1, #list do

		if list[no] == what then
			return true
		end
	end

	return false
end

-- monster find someone to attack
local monster_attack = function(self)

	local s = self.object:get_pos()
	if not s then return end
	local p, sp, dist
	local player, obj, min_player
	local type, name = "", ""
	local min_dist = self.view_range
	local objs = minetest.get_objects_inside_radius(s, self.view_range)

	for n = 1, #objs do

		if objs[n]:is_player() then

			--if mobs.invis[ objs[n]:get_player_name() ] then
			if isInvisible(objs[n]) then

				type = ""
			else
				player = objs[n]
				type = "player"
				name = "player"
			end
		else
			obj = objs[n]:get_luaentity()

			if obj then
				player = obj.object
				type = obj.type
				name = obj.name or ""
			end
		end

		-- find specific mob to attack, failing that attack player/npc/animal
		if specific_attack(self.specific_attack, name) and
			(type == "player" or type == "npc" or (type == "animal" and self.attack_animals == true)) then

			p = player:get_pos()
			-- local colbox=self.collisionbox
			-- local sp = {x=s.x, y=s.y+(colbox[5]-colbox[2])*0.75, z=s.z} 

			dist = get_distance(p, s)

			-- aim higher to make looking up hills more realistic
			-- p.y = p.y + 1
			-- sp.y = sp.y + 1


			-- choose closest player to attack
			if dist < min_dist and can_see(self, player) then
				min_dist = dist
				min_player = player
			end
		end
	end


	-- attack player
	if min_player then
		do_attack(self, min_player)
	end
end


-- npc, find closest monster to attack
local npc_attack = function(self)

	local s = self.object:get_pos()
	if not s then return end
	local obj, min_player
	local min_dist = self.view_range + 1
	local objs = minetest.get_objects_inside_radius(s, self.view_range)

	for n = 1, #objs do

		obj = objs[n]:get_luaentity()

		if obj and obj.type == "monster" and obj~=self then
			local dist = get_distance(obj.object:get_pos(), s)
			if dist < min_dist and can_see(self, obj.object) then
				min_dist = dist
				min_player = obj.object
			end
		end
	end

	if min_player then
		do_attack(self, min_player)
	end
end

local look_for_target=function(self)
	if self.state=="attack" or not damage_enabled then return end

	if self.type=="monster" then
		monster_attack(self) 
	elseif self.type=="npc" then
		npc_attack(self)
	elseif self.attack_animals then
		moster_attack(self)
	end
end

-- specific runaway
--[[
local specific_runaway = function(list, what)

	-- no list so do not run
	if list == nil then return false end

	-- found entity on list to attack?
	for no = 1, #list do
		if list[no] == what then
			return true
		end
	end

	return false
end
]]


-- find someone to runaway from
local runaway_from = function(self)

	local s = self.object:get_pos()
	if not s then return end

	local low_health= must_flee(self)
	if not self.runaway_from and not low_health then return look_for_target(self) end

	local p, sp, dist
	local min_dist = self.view_range + 1
	local player, min_player
	local name = ""
	
	--[[
	local objs = minetest.get_objects_inside_radius(s, self.view_range)

	for n = 1, #objs do

		local obj=objs[n]
		if obj:is_player() then

			--if mobs.invis[ objs[n]:get_player_name() ]
			if isInvisible(objs[n])
				or self.owner == obj:get_player_name() then

				name=""
			else
				player = obj
				name = "player"
			end
		end

		-- find specific mob to runaway from
		if name ~= "" and name ~= self.name
			and (low_health or specific_runaway(self.runaway_from, name)) then

			p = player:get_pos()
			dist = get_distance(p, s)

			-- choose closest player/mpb to runaway from
			-- if dist < min_dist and line_of_sight(self, sp, p, .1) == true then
			-- if dist < min_dist and can_see(self, player) then
			if dist < min_dist then
				min_dist = dist
				min_player = player
			end
		end
	end
	]]
	-- Simplifed version; "runaway_from" run away from everything except same species ans owner
	for _, obj in ipairs(minetest.get_objects_inside_radius(s, self.view_range)) do
		player=nil
		if obj:is_player() then 
			if self.owner ~= obj:get_player_name() then player=obj end
		elseif  (self.runaway_from or low_health) and
			self.name ~= obj:get_luaentity().name and
			can_see(self, obj) then 
			player=obj
		end

		if player then
			dist = get_distance(player:get_pos(), s)
			if dist < min_dist then
				min_dist = dist
				min_player = player
			end
		end
	end


	if not min_player then return end

	local lp = min_player:get_pos()
	-- randomize the position of the threat so that the fleeing mob appears to dodge.
	local v=vector.direction(lp+vector.new(random(-3,3), 0, random(-3,3)), s)*self.run_velocity
	v.y=(self.fly and 0) or self.object:get_velocity().y
	self.object:set_velocity(v)
	set_animation(self, "run")
	if self.state~="runaway" then self.runaway_timer = 5 end
	self.lifespan=300
	self.state = "runaway"
end


local closest_player=function(self)
	local pos=self.object:get_pos()
	local players=minetest.get_connected_players()
	local nearest=0
	local player=nil

	for n=1, #players do
		if player then
			local d=get_distance(players[n]:get_pos(), pos)
			if d<nearest then
				player=players[n]
				nearest=d
			end
		else
			player=players[n]
			nearest=get_distance(player:get_pos(), pos)
		end
	end
	return player
end

		
-- execute current state (stand, walk, run, attacks)
local do_states = function(self, mr)

	--local s = self.object:get_pos()

	local yaw = get_yaw(self)
	if not yaw then return end


	if self.state == "stand" then
		if self.timer<0.75 then return end
		self.timer=0
		if random(100) < 25 then
			mob_sound(self, self.sounds.random)
		end

		if random(1, 100) <= self.walk_chance then
			yaw=set_yaw(self, yaw+(self.alturn and pi/3 or -pi/3))
			do_walk(self)

			-- fly up/down randomly for flying mobs
			if self.fly then
				local up=self.object:get_pos(); up.y=up.y+1
				local ud = random(-3, 3) / 9
				if ud<=0 or flight_check(self, up) then
					local v = self.object:get_velocity()
					if v then self.object:set_velocity({x = v.x, y = ud, z = v.z}) end
				end
			end
		end
		runaway_from(self)
	elseif self.state == "walk" then
		if self.timer<0.75 then return end
		self.timer=0
		if mr.touching_ground or self.fly then replace(self) end
		if self.name=="mob_whale:whale" and self.driver then return end
		if (random(1, 100) > self.walk_chance) or
			vector.length(self.object:get_velocity())<0.5 or
			(is_at_cliff(self) and mr.touching_ground)
			then
			do_stand(self)
		end
		runaway_from(self)
	elseif self.state == "runaway" then
		if self.runaway_timer <= 0 then
			do_walk(self)
			look_for_target(self)
			return
		end
		if self.timer<0.75 then return end
		self.timer=0
		runaway_from(self)
	elseif self.state == "attack" then
		local s = self.object:get_pos()
		local p = self.attack and self.attack:get_pos()
		if not p then
			do_stand(self)
			return
		end
		local cb=self.initial_properties.collisionbox
		s.y=s.y+cb[5] -- (cb[5]+cb[2])*0.75
		cb=self.attack:get_properties().collisionbox
		p.y=p.y+cb[5] -- (cb[5]+cb[2])*0.75

		local dist = get_distance(p, s)

		-- stop attacking if player invisible or out of range
		if dist > self.view_range or not self.attack or self.attack:get_hp() <= 0
			or isInvisible(self.attack) or not can_see(self, self.attack) then
			self.attack = nil
			do_stand(self)
			return
		end
		mf.threatWarn(self.attack)

		if dist <= self.reach then
			self.object:set_velocity(vector.direction(s,p)*0.01)
			if self.timer > 1.5 then
				self.timer = 0
				set_animation(self, "punch")
				mob_sound(self, self.sounds.attack)
				-- local attached = self.attack:get_attach()
				-- if attached then self.attack=attached end
				self.attack:punch(self.object, 1.0, { full_punch_interval = 1, damage_groups = {fleshy = self.damage, knockback=0.25} }, nil)
			end
		elseif self.attack_type=="dogfight" or not self.fly then
			-- move towards enemy if beyond mob reach
			if mr.touching_ground and (is_at_cliff(self)  or (p.y - s.y >=2)) then
				do_jump(self, true, true)
			elseif vector.length(self.object:get_velocity())<1 then
				-- mob may be e.g. stuck behind a tree. Auto-turn should have change
				-- its angle, just push it in that direction.
				self.object:set_velocity(self.object:get_velocity()*self.run_velocity)
			else
				local v=vector.direction(s, p)*self.run_velocity
				v.y=(self.fly and 0) or self.object:get_velocity().y
				self.object:set_velocity(v)
				set_animation(self, "run")
			end
			if self.fly then
				-- dogfighting fliers have to adjust their altitude too.
				local me_y = floor(s.y)
				local p_y = floor(p.y)
				local v = self.object:get_velocity()
				if flight_check(self, s) then
					if me_y < p_y then
						self.object:set_velocity({ x = v.x, y = 1 * self.run_velocity, z = v.z })
					elseif me_y > p_y then
						self.object:set_velocity({ x = v.x, y = -1 * self.run_velocity, z = v.z })
					end
				else
					self.object:set_velocity({ x = v.x, y = -1.01, z = v.z })
				end
			end
		else
			-- Flying shooters stay still when aiming.
			-- stop_moving(self) set_yaw(self, yaw)
			self.object:set_velocity(vector.direction(s,p)*0.01)
		end


		if self.attack_type=="shoot" and dist>self.reach and self.timer >= self.shoot_interval then
			self.timer = 0
			set_animation(self, "shoot")
			mob_sound(self, self.sounds.shoot_attack)

			local p = self.object:get_pos()
			p.y = p.y + half_height(self) 
			if minetest.registered_entities[self.arrow] then
				set_animation(self, "punch")
				local obj = minetest.add_entity(p, self.arrow)
				local ent = obj:get_luaentity()
				ent.owner_id = self.object -- add unique owner id to arrow

				obj:set_velocity(self.attack:get_velocity()+vector.direction(p, self.attack:get_pos())*(ent.velocity or 1))
			end
		elseif self.attack_type=="magic" and dist>self.reach and self.timer>=self.shoot_interval then
			-- this is a custom attack for the orange wasp, currently
			self.timer=0
			set_animation(self, "shoot")
			mob_sound(self, self.sounds.shoot_attack)
			local radius=2
			local time=1

			local p=self.attack:get_pos()
			if not p then return end
			p=vector.add(p, self.attack:get_velocity()) -- extrapolate position one second later.
			minetest.add_particlespawner({
				amount = 1000,
				time = time,
				-- minpos={x=p.x-radius, y=p.y, z=p.z-radius},
				-- maxpos={x=p.x+radius, y=p.y, z=p.z+radius},
				pos=p,
				radius=radius,
				texture =
				{
					name="magic_wand_lightning.png^[multiply:orange",
					alpha_tween={0,1},
					scale=0.1,
					scale_tween={ 0.1, 2},

				} ,
				glow=14,
				collisiondetection=false,
			})
			minetest.sound_play("wasp", {pitch=1.25, gain=0.25, start_time=1.95, pos=p, max_hear_distance=10}, true)
			minetest.after(time, function()
				local objs=minetest.get_objects_inside_radius(p, radius)
				for n=1, #objs do
					local obj=objs[n]
					obj:punch(self.object, 1.0, {
						full_punch_interval=0.1,
						damage_groups={fleshy=2},
					}, nil)
				end
			end)
		end


	else
		-- Just spawned or reactivated. Reset to standing state
		do_stand(self)
		look_for_target(self)
		self.timer=1
	end
end


local newton=vector.new(0, -8, 0)
local archie=vector.new(0, 1, 0)
-- falling, flying and floating
local falling = function(self)

	if self.fly and self.pause_timer<=0.1 and flight_check(self) then
		self.object:set_acceleration(Vero)
		return
	end

	local p = self.object:get_pos()
	if not p then return end

	if minetest.registered_nodes[node_ok(p).name].groups.liquid and self.floats == 1 then
			self.object:set_acceleration(archie)
			return
	end

	self.object:set_acceleration(newton)

end

-- deal damage and effects when mob punched
local function glow(self, On)
	if On then
		self.object:set_texture_mod("^[brighten");
	else
		self.object:set_texture_mod("");
	end
end

local mob_punch = function(self, hitter, tflp, tool_capabilities, dir)

	hitter=(hitter and hitter:get_luaentity() and hitter:get_luaentity().owner_id) or hitter

	-- custom punch function overtakes if it returns false
	if self.do_punch and not self.do_punch(self, hitter, tflp, tool_capabilities, dir) then
		return
	end

	-- error checking when mod profiling is enabled
	if not tool_capabilities then
		minetest.log("warning", "[mobs] Mod profiling enabled, damage not enabled")
		return
	end

	-- weapon wear
	local weapon = hitter and hitter:get_wielded_item()

	-- calculate mob damage
	local damage = 0
	local armor = self.object:get_armor_groups() or {}
	local tmp

	-- quick error check incase it ends up 0 (serialize.h check test)
	tflp=tflp or 0.2

	for group,_ in pairs( (tool_capabilities.damage_groups or {}) ) do

		tmp = tflp / (tool_capabilities.full_punch_interval or 1.4)

		if tmp < 0 then
			tmp = 0.0
		elseif tmp > 1 then
			tmp = 1.0
		end

		damage = damage + (tool_capabilities.damage_groups[group] or 0)
		* tmp * ((armor[group] or 0) / 100.0)
	end

	-- healing
	if damage <= -1 then
		self.health = self.health - floor(damage)
		return
	end

	local punch_interval = tool_capabilities.full_punch_interval or 1.4
	if tflp<punch_interval then
		minetest.sound_play("mobs_swing", {object=hitter, max_hear_distance=4}, true)
		return
	end

	local uses=tool_capabilities.punch_attack_uses or 128	

	if weapon and weapon:get_definition()
		and weapon:get_definition().tool_capabilities then
		weapon:add_wear(65536/uses)
		hitter:set_wielded_item(weapon)
	end

	if damage >= 1 then
		minetest.sound_play("default_ice_dug", { object = self.object, pitch=2, gain=0.25, max_hear_distance = 5 }, true)

		local p=self.object:get_pos()
		p.y=p.y+half_height(self)
		dmg_fx(p, damage)

		-- do damage
		self.health = self.health - floor(damage)

		-- exit here if dead
		if check_for_death(self, "hit", {type = "punch", puncher = hitter}) then return end

		self.wasHit=true

		local kb=max(tool_capabilities.damage_groups.knockback or damage/10, 0.2)
		if kb>0 then
			if self.state=="runaway" then kb=kb/2 end
			if self.pause_timer>0 then kb=kb*1.25
			else
				set_animation(self, "freeze")
				set_velocity(self, 0.01)
				glow(self, true)
			end
			self.pause_timer =self.pause_timer+kb
			return
		end
	end

	-- if skittish then run away
	if (hitter~=self.object) and (must_flee(self) or not can_see(self, hitter)) then
		self.state = "runaway"
		self.runaway_timer = 2*(1+random())
		return
	end

	-- attack puncher and call other mobs for help
	if self.passive == false and not isInvisible(hitter) and hitter~=self.object then
		-- attack whoever punched mob
		if self.pause_timer<=0 then do_stand(self) end
		do_attack(self, hitter)
	end
end


-- get entity staticdata
local mob_staticdata = function(self)

	-- self.attack = nil
	-- self.state = "stand"

	local tmp = {}

	for _,stat in pairs(self) do

		local t = type(stat)

		if  t ~= "function"
			and t ~= "nil"
			and t ~= "userdata"
			and _ ~= "_cmi_components" then
			tmp[_] = stat 
		end
	end
	tmp.attack=nil

	--print('===== '..self.name..'\n'.. dump(tmp)..'\n=====\n')
	return minetest.serialize(tmp)
end


-- activate mob and reload settings
local mob_activate = function(self, staticdata, def, dtime)

	-- load entity variables
	local tmp = minetest.deserialize(staticdata)

	if tmp then
		for _,stat in pairs(tmp) do
			self[_] = stat
		end
	end

	-- select random texture, set model and size
	if not self.base_texture then

		-- compatiblity with old simple mobs textures
		if type(def.textures[1]) == "string" then
			def.textures = {def.textures}
		end

		self.base_texture = def.textures[random(1, #def.textures)]
		self.base_mesh = def.mesh
		self.base_size = self.visual_size
	end


	-- set texture, model and size
	local textures = self.base_texture
	local mesh = self.base_mesh
	local vis_size = self.base_size

	if self.health == 0 then
		self.health = floor(self.initial_properties.hp_max*(1+random(0.25)))
	end

	-- mob defaults
	self.object:set_armor_groups({immortal = 1, fleshy = 100})
	self.old_health = self.health
	self.sounds.distance = self.sounds.distance or 10
	self.textures = textures
	self.mesh = mesh
	self.visual_size = vis_size
	self.standing_in = ""
	self.current_anim=nil

	self.suicidal=self.suicidal or (random(4)==1)
	self.alturn=(random(2)==1)
	-- check existing nametag
	if not self.nametag then
		self.nametag = def.nametag
	end
	
	-- set anything changed above
	self.object:set_properties(self)
	set_yaw(self, random(2*pi))
	update_tag(self)

	-- run on_spawn function if found
	if self.on_spawn and not self.on_spawn_run then
		if self.on_spawn(self, self.object:get_pos()) then
			self.on_spawn_run = true --  if true, set flag to run once only
		end
	end

	-- run after_activate
	if def.after_activate then
		def.after_activate(self, staticdata, def, dtime)
	end
	do_stand(self)
	self.timer=1
end


-- main mob function
local mob_step = function(self, dtime, mr)

	local pos = self.object:get_pos()

	if self.health<=0 or not within_limits(pos, 0) then 
		self.object:remove()
		return
	end
	self.lifespan=(self.lifespan or 300)-dtime
	if self.lifespan<0 and self.type ~= "npc" and not self.driver then
		-- driver check is for whales.
		if self.type=="monster" and self.wasHit and minetest.get_node(pos).name=="air" and not minetest.is_protected(pos) and not self.fly then
				minetest.swap_node(pos, {name="melding:node"})

		end
		self.object:remove()
		mobs.tp_fx(pos)
		return
	end

	--[[
	local t=minetest.get_gametime()
	if t >= (self.lastseen or t)+300 and self.type~="npc" and random(1,2)==1 then
		self.object:remove()
		return
	end
	self.lastseen=t
	]]

	-- standing_in update
	--local pos = self.object:get_pos()
	--pos.y=pos.y + self.initial_properties.collisionbox[5]/2
	--pos.y=pos.y + self.initial_properties.collisionbox[2]+0.1
	self.standing_in = node_ok(pos).name

	-- environmental damage timer (every 1 second)
	self.env_damage_timer = self.env_damage_timer + dtime
	if self.env_damage_timer>=1 then
		do_env_damage(self)
		self.env_damage_timer=0
	end

	-- knockback/snare timer
	if self.pause_timer > 0 then
		self.pause_timer = self.pause_timer - dtime
		if self.pause_timer<=0 then
			glow(self, false)
			if self.fly then
				set_animation(self, "stand");
				stop_moving(self)
			end
		end
		if not mr.touching_ground then falling(self) end
		return
	end
	
	-- general purpose timer
	self.timer = self.timer + dtime

	if self.runaway_timer>0  then self.runaway_timer=self.runaway_timer-dtime end

	-- run custom function (defined in mob lua file)
	if self.do_custom and self.do_custom(self, dtime) == false then
		return
	end

	-- mob freezing ice hack
	--[[
	if self.standing_in == "default:ice" then
		set_velocity(self, 0)
		return
	end
	]]


	do_states(self, mr)
	do_jump(self, false, mr.touching_ground)
	if not mr.touching_ground then 
		falling(self)
	end
end


-- default function when mobs are blown up with TNT
local do_tnt = function(obj, damage)

	--print ("----- Damage", damage)

	obj.object:punch(obj.object, 1.0, {
		full_punch_interval = 1.0,
		damage_groups = {fleshy = damage, knockback=3},
	}, nil)

	return false, true, {}
end


mobs.spawning_mobs = {}

-- register mob entity
function mobs:register_mob(name, def)

	mobs.spawning_mobs[name] = true

	def.env_dmg=def.env_dmg or {}
	if not def.env_dmg["melding:node"] then def.env_dmg["melding:node"]=1 end

	minetest.register_entity(name, {
		-- damage_texture_modifier="^[brighten",
		name = name,
		type = def.type,
		attack_type = def.attack_type,
		fly = def.fly,
		fly_in = def.fly_in or "air",
		owner = def.owner or "",
		on_die = def.on_die,
		do_custom = def.do_custom,
		jump_height = def.jump_height or 5, -- was 6
		rotate = math.rad(def.rotate or 0), --  0=front, 90=side, 180=back, 270=side2
		initial_properties=
		{
			hp_max = max(1, (def.hp_max or 10)),
			physical = true,
			collisionbox = def.collisionbox,
			visual = def.visual,
			mesh = def.mesh,
			visual_size = def.visual_size or {x = 1, y = 1},
			makes_footstep_sound = def.makes_footstep_sound or false,
			stepheight = def.stepheight or 0.2, -- was 0.6
			glow=def.glow or 1,
			infotext=def.infotext,
			show_on_minimap=def.show_on_minimap,
			automatic_face_movement_dir=-90-(def.rotate or 0),
			--automatic_face_movement_max_rotation_per_sec=1440,
		},
		view_range = def.view_range or 5,
		walk_velocity = def.walk_velocity or 1,
		run_velocity = def.run_velocity or 2,
		damage = max(0, (def.damage or 0)),
		regen= def.regen or 0.4, -- approx. health regen per sec.
		water_damage = def.water_damage,
		fall_speed = def.fall_speed or -10, -- must be lower than -2 (default: -10)
		drops = def.drops or {},
		on_rightclick = def.on_rightclick,
		arrow = def.arrow,
		shoot_interval = def.shoot_interval,
		sounds = def.sounds or {},
		animation = def.animation,
		-- follow = def.follow,
		jump = def.jump ~= false,
		walk_chance = def.walk_chance or 70,
		attacks_monsters = def.attacks_monsters or false,
		group_attack = def.group_attack or true,
		passive = def.passive or false,
		-- blood_amount = 10, -- def.blood_amount or 10,
		--blood_texture = --[[def.blood_texture or ]] "default_mineral_mese.png",
		shoot_offset = def.shoot_offset or 0,
		floats = def.floats or 1, -- floats in water by default
		env_alt=def.env_alt,
		env_dmg=def.env_dmg or {},
		env_damage_timer = 0, -- only used when state = "attack"
		timer = 0,
		tamed = false,
		pause_timer = 0,
		health = 0,
		reach = def.reach or 3,
		htimer = 0,
		--texture_list = def.textures,
		fear_height = def.fear_height or 0,
		suicidal = def.suicidal,
		runaway_timer = 0,
		--immune_to = def.immune_to or {},
		attack_animals = def.attack_animals or false,
		specific_attack = def.specific_attack,
		runaway_from = def.runaway_from,
		owner_loyal = def.owner_loyal,
		--reqRemoval= false,

		on_spawn = def.on_spawn,
		on_blast = def.on_blast or do_tnt,
		on_step = mob_step,
		do_punch = def.do_punch,
		on_punch = mob_punch,
		-- on_grown = def.on_grown,

		on_activate = function(self, staticdata, dtime)
			return mob_activate(self, staticdata, def, dtime)
		end,

		get_staticdata = function(self)
			return mob_staticdata(self)
		end,
	})

end -- END mobs:register_mob function


-- count how many mobs of one type are inside an area
-- Used by wands.
function mobs:count_mobs(pos, type)

	local num_type = 0
	local num_total = 0
	local objs = minetest.get_objects_inside_radius(pos, aoc_range)

	for n = 1, #objs do

		if not objs[n]:is_player() then

			local obj = objs[n]:get_luaentity()
			-- count mob type and add to total also
			if obj and obj.name and obj.name == type then
				num_type = num_type + 1
			end
		end
	end

	return num_type
end

function mobs:check_near(pos, radius, name)
	for _, ent in ipairs(minetest.get_objects_inside_radius(pos, radius)) do
		if ent:is_player() or ent:get_luaentity().name==name then
			return true
		end
	end
	return false
end


-- global functions

function mobs:spawn_specific(name, nodes, neighbors, min_light, max_light,
	interval, chance, aoc, min_height, max_height, day_toggle, on_spawn)

	-- aoc is not used anymore, because it failed to meet its goal.
	-- we now use a simpler "no other inside a radius" polivy, plus
	-- automatic despawn if a mob "older" than 5 minutes is reactivated.

	minetest.register_abm({

		label = name .. " spawning",
		nodenames = nodes,
		neighbors = neighbors,
		interval = interval,
		chance = max(1, (chance * mob_chance_multiplier)),
		catch_up = true,
		min_y=min_height,
		max_y=max_height,

		action = function(pos, node, active_object_count, active_object_count_wider)

			-- is mob actually registered?
			local ent = minetest.registered_entities[name]
			if not mobs.spawning_mobs[name]
				or not ent then
				--print ("--- mob doesn't exist", name)
				return
			end

			-- are we spawning within height limits?
			--[[
			if pos.y > max_height
				or pos.y < min_height then
				--print ("--- height limits not met", name, pos.y)
				return
			end
			]]


			-- if toggle set to nil then ignore day/night check
			if day_toggle ~= nil then

				local tod = (minetest.get_timeofday() or 0) * 24000

				if tod > 4500 and tod < 19500 then
					-- daylight, but mob wants night
					if day_toggle == false then
						--print ("--- mob needs night", name)
						return
					end
				else
					-- night time but mob wants day
					if day_toggle == true then
						--print ("--- mob needs day", name)
						return
					end
				end
			end
			-- decrease the chance for slabs and stairs
			if minetest.get_item_group(node, "slab")~=0 and random(1,2)~=1 then return end
			if minetest.get_item_group(node, "stair")~=0 and random(1,4)~=1 then return end


			-- Two free blocks required. Stairs/slabs allowed just above
			pos.y = pos.y + 1 
			local nn=node_ok(pos).name
			if minetest.registered_nodes[nn].walkable == true or (ent.env_dmg[nn] or 0) > 0 then return end
			pos.y=pos.y+1
			nn=node_ok(pos).name
			if minetest.registered_nodes[nn].walkable == true or (ent.env_dmg[nn] or 0) > 0 then return end
			pos.y=pos.y-1

			-- are light levels ok?
			local light = minetest.get_node_light(pos)
			if not light
				or light > max_light
				or light < min_light then
				--print ("--- light limits not met", name, light)
				return
			end

			if ent.type=="monster" and minetest.is_protected(pos) then return end
			if mobs:check_near(pos, 10, name) then return end 


			-- back to node above spawner, account for mods that don't have their origin on bottom
			pos.y=pos.y-ent.initial_properties.collisionbox[2]
			if ent.type=="monster" then
				minetest.add_particlespawner({
					amount = 100,
					time = 3,
					pos=pos,
					radius=1.5,
					attract={kind="point", origin=pos, strength=0.75},
					minsize = 1,
					maxsize = 1,
					texture ={name="dot.png^[colorize:magenta", alpha_tween={0,1}} ,
					glow=14,
					collisiondetection=false,
				})
			end
			minetest.after(3, function()
				local mob = minetest.add_entity(pos, name)
				-- minetest.log("Spawning ".. name) 

				if on_spawn then
					local e = mob:get_luaentity() -- e is probably the same as ent above.
					on_spawn(e, pos)
				end
			end)

		end
	})
end


-- compatibility with older mob registration
function mobs:register_spawn(name, nodes, max_light, min_light, chance, active_object_count, max_height, day_toggle)

	mobs:spawn_specific(name, nodes, {"air"}, min_light, max_light, 29,
	chance, active_object_count, -31000, max_height, day_toggle)
end


-- MarkBu's spawn function
function mobs:spawn(def)

	local name = def.name
	local nodes = def.nodes or {"group:soil", "group:stone"}
	local neighbors = def.neighbors or {"air"}
	local min_light = def.min_light or 0
	local max_light = def.max_light or 15
	local interval = def.interval or 17
	local chance = def.chance or 5000
	local active_object_count = def.active_object_count or 1
	local min_height = def.min_height or -31000
	local max_height = def.max_height or 31000
	local day_toggle = def.day_toggle
	local on_spawn = def.on_spawn

	mobs:spawn_specific(name, nodes, neighbors, min_light, max_light, interval,
	chance, active_object_count, min_height, max_height, day_toggle, on_spawn)
end


--[[
local inside=function(pos, box, pbox)
	-- box is a collision box
	-- pbox is the position of the entity
	return pos.y<=pbox.y+box[5] and pos.y>=pbox.y+box[2] and pos.x<=pbox.x+box[4] and pos.x>=pbox.x+box[1] and pos.z<=pbox.z+box[6] and pos.z>=pbox.z+box[3]
end
--]]

-- register arrow for shoot attack
local radius=0.25
local Minvel=vector.new(-radius, -radius, -radius)
local Maxvel=vector.new(radius, radius, radius)

function mobs:register_arrow(name, def)

	if not name or not def then return end -- errorcheck
	minetest.register_entity(name, {

		initial_properties=
		{
			hp_max=1,
			physical = true,
			collisionbox = {-0.1, -0.1, -0.1, 0.1, 0.1, 0.1},
			visual = def.visual,
			visual_size={x=0.1, y=0.1}, -- visual_size = def.visual_size,
			glow=def.glow,
			textures = def.textures,
		},
		velocity = def.velocity,
		hit_player = def.hit_player,
		hit_node = def.hit_node,
		hit_mob = def.hit_mob,
		drop = def.drop or false, -- drops arrow as registered item when true
		ttl = def.ttl or 5,
		owner_id = def.owner_id,
		rotate = def.rotate,

		on_activate=function(self)
			minetest.add_particlespawner {
				amount = 50,
				time=0,
				minvel = Minvel,
				maxvel = Maxvel,
				minacc = Vero,
				maxacc = Vero,
				minexptime = 0.25,
				maxexptime = 0.5,
				texture = { name=def.textures[1], --[[ alpha_tween={1,0}, ]] scale=def.visual_size},
				glow = def.glow,
				attached=self.object
			}
		end,	

		on_step = function(self, dtime, moveres)

			self.ttl = self.ttl - dtime

			local pos = self.object:get_pos()

			if self.ttl < 0 or not within_limits(pos, 0) then
				self.object:remove()
				return
			end

			local thing=moveres.collides and moveres.collisions[1]
			if thing then
				if thing.type=="node" then
					local p=thing.node_pos
					if self.hit_node and not core.is_protected(p) then
						self.hit_node(self, thing.node_pos, core.get_node(p).name)
					end
					self.object:remove()
					return
				end
				if thing.type=="object" then
					local object=thing.object
					if object:is_player() then
						if self.hit_player then self.hit_player(self, object) end
					elseif self.hit_mob then
						self.hit_mob(self, object)
					end
					self.object:remove()
					return
				end
			end

			
			self.lastpos = pos
			if def.on_step then def.on_step(self,dtime) end
		end
	})
end


--[[
-- blast damage to entities nearby (modified from TNT mod)
local entity_physics = function(pos, radius)

	radius = radius * 2

	local objs = minetest.get_objects_inside_radius(pos, radius)
	local obj_pos, dist

	for n = 1, #objs do

		obj_pos = objs[n]:get_pos()

		dist = get_distance(pos, obj_pos)
		if dist < 1 then dist = 1 end

		local damage = floor((4 / dist) * radius)
		local ent = objs[n]:get_luaentity()

		-- punches work on entities AND players
		objs[n]:punch(objs[n], 1.0, {
			full_punch_interval = 1.0,
			damage_groups = {fleshy = damage},
		}, pos)
	end
end

-- no damage to nodes explosion
function mobs:safe_boom(self, pos, radius)

	minetest.sound_play(self.sounds and self.sounds.explode or "tnt_explode", {
		pos = pos,
		gain = 1.0,
		max_hear_distance = self.sounds and self.sounds.distance or 32
	})

	entity_physics(pos, radius)
	effect(pos, 32, "tnt_smoke.png", radius * 3, radius * 5, radius, 1, 0)
end
]]

-- compatibility function
function mobs:explosion(pos, radius)
	local self = {sounds = {}}
	self.sounds.explode = "tnt_explode"
	mobs:boom(self, pos, radius)
end

-- make explosion with protection and tnt mod check
function mobs:boom(self, pos, radius)

	if not minetest.is_protected(pos, "") then
		mf_tnt.boom(pos, {
			radius = radius,
			damage_radius = radius,
			sound = self.sounds and self.sounds.explode,
			explode_center = true,
		})
	end
end


-- Register spawn eggs

-- Note: This also introduces the “spawn_egg” group:
-- * spawn_egg=1: Spawn egg (generic mob, no metadata)
-- * spawn_egg=2: Spawn egg (captured/tamed mob, metadata)
function mobs:register_egg(mob, desc, background, addegg, no_creative)

	local grp = {spawn_egg = 1}

	-- do NOT add this egg to creative inventory (e.g. dungeon master)
	if creative and no_creative == true then
		grp.not_in_creative_inventory = 1
	end

	local invimg = background

	if addegg == 1 then
		invimg = "mobs_chicken_egg.png^(" .. invimg ..
		"^[mask:mobs_chicken_egg_overlay.png)"
	end

	-- register new spawn egg containing mob information
	minetest.register_craftitem(mob .. "_set", {

		description = S("@1", desc),
		inventory_image = invimg,
		groups = {spawn_egg = 2, not_in_creative_inventory = 1},
		stack_max = 1,

		on_place = function(itemstack, placer, pointed_thing)

			local pos = pointed_thing.above

			-- am I clicking on something with existing on_rightclick function?
			local under = minetest.get_node(pointed_thing.under)
			local def = minetest.registered_nodes[under.name]
			if def and def.on_rightclick then
				return def.on_rightclick(pointed_thing.under, under, placer, itemstack)
			end

			if pos
				and within_limits(pos, 0)
				and not minetest.is_protected(pos, placer:get_player_name()) then

				if not minetest.registered_entities[mob] then
					return
				end

				pos.y = pos.y + 0.5

				local data = itemstack:get_metadata()
				local mob = minetest.add_entity(pos, mob, data)
				local ent = mob:get_luaentity()
				if not ent then return end

				--ent.type="npc"
				-- set owner if not a monster
				-- if ent.type ~= "monster" then
				ent.owner = placer:get_player_name()
				--ent.tamed = true
				-- end

				-- since mob is unique we remove egg once spawned
				itemstack:take_item()
			end

			return itemstack
		end,
	})


	-- register old stackable mob egg
	minetest.register_craftitem(mob, {

		description = desc,
		inventory_image = invimg,
		groups = grp,

		on_place = function(itemstack, placer, pointed_thing)

			local pos = pointed_thing.above

			-- am I clicking on something with existing on_rightclick function?
			local under = minetest.get_node(pointed_thing.under)
			local def = minetest.registered_nodes[under.name]
			if def and def.on_rightclick then
				return def.on_rightclick(pointed_thing.under, under, placer, itemstack)
			end

			if pos
				and within_limits(pos, 0)
				and not minetest.is_protected(pos, placer:get_player_name()) then

				if not minetest.registered_entities[mob] then
					return
				end

				pos.y = pos.y + 0.5

				local mob = minetest.add_entity(pos, mob)
				local ent = mob:get_luaentity()

				--ent.type="npc"
				-- don't set owner if monster or sneak pressed
				--if ent.type ~= "monster"
				--and not placer:get_player_control().sneak then
				ent.owner = placer:get_player_name()
				--ent.tamed = true
				--end

				-- if not in creative then take item
				if not mobs.is_creative(placer:get_player_name()) then
					itemstack:take_item()
				end
			end

			return itemstack
		end,
	})

end


-- capture critter (thanks to blert2112 for idea)
function mobs:capture_mob(self, clicker, chance_hand, chance_net, chance_lasso, force_take, replacewith)

	if not clicker:is_player() or not clicker:get_inventory() then
		return false
	end

	-- get name of clicked mob
	local mobname = self.name

	-- if not nil change what will be added to inventory
	if replacewith then
		mobname = replacewith
	end

	local name = clicker:get_player_name()
	local tool = clicker:get_wielded_item()

	if tool:get_name() ~= ""
		and tool:get_name() ~= "mobs:net"
		and tool:get_name() ~= "mobs:lasso" then
		return false
	end

	--[[ no ownership
	-- is mob tamed?
	if self.tamed == false and force_take == false then
		minetest.chat_send_player(name, S("Not tamed!"))
		return true -- false
	end

	-- cannot pick up if not owner
	if self.owner~="" and self.owner ~= name then
		minetest.chat_send_player(name, S("@1 is owner!", self.owner))
		return true -- false
	end
	]]

	if clicker:get_inventory():room_for_item("main", mobname) then

		-- was mob clicked with hand or net?
		local chance = 0

		if tool:get_name() == "" then
			chance = chance_hand
		elseif tool:get_name() == "mobs:net" then
			chance = chance_net
			-- tool:add_wear(65536/32) -- Wear is applied by the net's on_place/on_secondary_use
			clicker:set_wielded_item(tool)

		end

		-- Minefall: We make it more difficult to catch mobs through different means like
		-- a shorter reach for the net or mobs that can juke the player, so we don't need
		-- a random factor anymore. We have to keep, though, the distinction between net and hand

		if chance > 0 then

			-- default mob egg
			local new_stack = ItemStack(mobname)

			-- add special mob egg with all mob information
			-- unless 'replacewith' contains new item to use
			if not replacewith then

				new_stack = ItemStack(mobname .. "_set")

				local tmp = {}

				for _,stat in pairs(self) do
					local t = type(stat)
					if  t ~= "function"
						and t ~= "nil"
						and t ~= "userdata" then
						tmp[_] = self[_]
					end
				end

				local data_str = minetest.serialize(tmp)

				new_stack:set_metadata(data_str)
			end

			local inv = clicker:get_inventory()

			if inv:room_for_item("main", new_stack) then
				inv:add_item("main", new_stack)
			else
				minetest.add_item(clicker:get_pos(), new_stack)
			end


			mob_sound(self, "default_place_node_hard")
			self.object:remove()
		end
	end

	return true
end


-- protect tamed mob with rune item
function mobs:protect(self, clicker) end


local mob_obj = {}
local mob_sta = {}

-- feeding, taming and breeding (thanks blert2112)
function mobs:feed_tame(self, clicker, feed_count, breed, tame)
--[[
	if not self.follow then
		return false
	end

	-- can eat/tame with item in hand
	if follow_holding(self, clicker) then

		-- if not in creative then take item
		if not mobs.is_creative(clicker:get_player_name()) then

			local item = clicker:get_wielded_item()

			item:take_item()

			clicker:set_wielded_item(item)
		end

		-- increase health
		self.health = self.health + 4

		if self.health > self.hp_max then
			self.health = self.hp_max
			if self.htimer < 1 then
				minetest.chat_send_player(clicker:get_player_name(),
				S("@1 at full health (@2)",
				self.name:split(":")[2], tostring(self.health)))
				self.htimer = 5
			end
		end

		self.object:set_hp(self.health)

		update_tag(self)

		-- feed and tame
		self.food = (self.food or 0) + 1
		if self.food >= feed_count then
			self.food = 0
			if tame then

				if self.tamed == false then
					minetest.chat_send_player(clicker:get_player_name(),
					S("@1 has been tamed!",
					self.name:split(":")[2]))
				end

				self.tamed = true

				if not self.owner or self.owner == "" then
					self.owner = clicker:get_player_name()
				end
			end

			-- make sound when fed so many times
			mob_sound(self, self.sounds.random)
		end

		return true
	end

	local item = clicker:get_wielded_item()

	-- if mob has been tamed you can name it with a nametag
	if item:get_name() == "mobs:nametag"
		and clicker:get_player_name() == self.owner then

		local name = clicker:get_player_name()

		-- store mob and nametag stack in external variables
		mob_obj[name] = self
		mob_sta[name] = item

		local tag = self.nametag or ""

		minetest.show_formspec(name, "mobs_nametag", "size[8,4]"
		.. default.gui_bg
		.. default.gui_bg_img
		.. "field[0.5,1;7.5,0;name;" .. minetest.formspec_escape(S("Enter name:")) .. ";" .. tag .. "]"
		.. "button_exit[2.5,3.5;3,1;mob_rename;" .. minetest.formspec_escape(S("Rename")) .. "]")
	end

	return false
	]]
end


-- inspired by blockmen's nametag mod
minetest.register_on_player_receive_fields(function(player, formname, fields)

	-- right-clicked with nametag and name entered?
	if formname == "mobs_nametag"
		and fields.name
		and fields.name ~= "" then

		local name = player:get_player_name()

		if not mob_obj[name]
			or not mob_obj[name].object then
			return
		end

		-- make sure nametag is being used to name mob
		local item = player:get_wielded_item()

		if item:get_name() ~= "mobs:nametag" then
			return
		end

		-- limit name entered to 64 characters long
		if string.len(fields.name) > 64 then
			fields.name = string.sub(fields.name, 1, 64)
		end

		-- update nametag
		mob_obj[name].nametag = fields.name

		update_tag(mob_obj[name])

		-- if not in creative then take item
		if not mobs.is_creative(name) then

			mob_sta[name]:take_item()

			player:set_wielded_item(mob_sta[name])
		end

		-- reset external variables
		mob_obj[name] = nil
		mob_sta[name] = nil
	end
end)


-- compatibility function for old entities to new modpack entities
function mobs:alias_mob(old_name, new_name)

	-- spawn egg
	minetest.register_alias(old_name, new_name)

	-- entity
	minetest.register_entity(":" .. old_name, {

		physical = false,

		on_step = function(self)

			local pos = self.object:get_pos()

			if minetest.registered_entities[new_name] then
				minetest.add_entity(pos, new_name)
			end

			self.object:remove()
		end
	})
end

