

pmb_spawn_inhibitors.registered_inhibitor_entities = {}
pmb_spawn_inhibitors.max_distance = 1
local reg = pmb_spawn_inhibitors.registered_inhibitor_entities
function pmb_spawn_inhibitors.register_inhibitor_entity(entity_name, dist)
    reg[entity_name] = dist

    if pmb_spawn_inhibitors.max_distance < dist then
        pmb_spawn_inhibitors.max_distance = dist
    end
end

function pmb_spawn_inhibitors.squaredist(p1, p2)
    return (((p1.x - p2.x) ^ 2) + ((p1.y - p2.y) ^ 2) + ((p1.z - p2.z) ^ 2))
end
local squaredist = pmb_spawn_inhibitors.squaredist

function pmb_spawn_inhibitors.is_uninhibited(pos)
    local d = pmb_spawn_inhibitors.max_distance + 4 -- extra
    local objects = minetest.get_objects_in_area(
        vector.offset(pos, -d, -d, -d),
        vector.offset(pos,  d,  d,  d)
    )
    for i, object in ipairs(objects) do
        local ent = object:get_luaentity()
        if not (ent and reg[ent.name]) then goto continue end

        if (ent._is_position_uninhibited == nil) then
            if squaredist(object:get_pos(), pos) < reg[ent.name] ^ 2 then
                return false
            end
        elseif not ent._is_position_uninhibited(ent, pos) then
            return false
        end
        ::continue::
    end
    return true
end

if minetest.get_modpath("pmb_mob_spawn") then
    pmb_mob_spawn.register_spawnrule(pmb_spawn_inhibitors.is_uninhibited)
else
    minetest.log("error", "pmb_spawn_inhibitors will be ineffective: could not find `pmb_mob_spawn` mod. ")
end
