improve UUID functionality

This commit is contained in:
kno10
2025-01-16 22:17:48 +01:00
committed by the-real-herowl
parent 2d61cc1178
commit 9472017fdb
3 changed files with 14 additions and 9 deletions
mods
CORE/mcl_util
ENTITIES
mcl_entity_invs
mobs_mc

@ -689,13 +689,19 @@ function mcl_util.trace_nodes(pos, dir, allowed_nodes, limit)
return nil, limit, nil
end
function mcl_util.gen_uuid()
-- Generate a random 128-bit ID that can be assumed to be unique
-- To have a 1% chance of a collision, there would have to be 1.6x10^76 IDs generated
-- https://en.wikipedia.org/wiki/Birthday_problem#Probability_table
-- Make a local random to guard against someone misusing math.randomseed
local uuid_rng = PcgRandom(bit.bxor(math.random(0xFFFFFFFF), os.time()))
--- Generate a random 128-bit ID that can be assumed to be unique
--- To have a 1% chance of a collision, there would have to be 1.6x10^76 IDs generated
--- https://en.wikipedia.org/wiki/Birthday_problem#Probability_table
--- @param len32 integer: length in 32-bit units, optional, default 4 (128 bit)
--- @return string: UUID string, 8xlen32 characters, default 32
function mcl_util.gen_uuid(len32)
len32 = (len32 and len32 > 0) and len32 or 4 -- len32 might be nil
local u = {}
for i = 1,16 do
u[#u + 1] = string.format("%02X",math.random(1,255))
for i = 1,len32 do
u[#u + 1] = bit.tohex(uuid_rng:next()) -- 32 bit at a time
end
return table.concat(u)
end

@ -163,8 +163,7 @@ function mcl_entity_invs.register_inv(entity_name,show_name,size,no_on_righclick
self._items = d._items
self._inv_size = d._inv_size
else
self._inv_id="entity_inv_"..minetest.sha1(minetest.get_gametime()..minetest.pos_to_string(self.object:get_pos())..tostring(math.random()))
--gametime and position for collision safety and math.random salt to protect against position brute-force
self._inv_id="entity_inv_"..mcl_util.gen_uuid()
end
return r
end

@ -2284,7 +2284,7 @@ mcl_mobs.register_mob("mobs_mc:villager", {
set_textures(self)
return
end
self._id=minetest.sha1(minetest.get_gametime()..minetest.pos_to_string(self.object:get_pos())..tostring(math.random()))
self._id=mcl_util.gen_uuid()
set_textures(self)
end,
on_die = function(self, pos, cmi_cause)