aboutsummaryrefslogtreecommitdiff
path: root/builtin/game/register.lua
blob: ec6f28097c8543698e8d9bceb20def960c1f0ea2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
-- Minetest: builtin/serialize.lua

-- https://github.com/fab13n/metalua/blob/no-dll/src/lib/serialize.lua
-- Copyright (c) 2006-2997 Fabien Fleutot <metalua@gmail.com>
-- License: MIT
--------------------------------------------------------------------------------
-- Serialize an object into a source code string. This string, when passed as
-- an argument to deserialize(), returns an object structurally identical
-- to the original one. The following are currently supported:
-- * strings, numbers, booleans, nil
-- * tables thereof. Tables can have shared part, but can't be recursive yet.
-- Caveat: metatables and environments aren't saved.
--------------------------------------------------------------------------------

local no_identity = { number=1, boolean=1, string=1, ['nil']=1 }

function minetest.serialize(x)

	local gensym_max   =  0  -- index of the gensym() symbol generator
	local seen_once    = { } -- element->true set of elements seen exactly once in the table
	local multiple     = { } -- element->varname set of elements seen more than once
	local nested       = { } -- transient, set of elements currently being traversed
	local nest_points  = { }
	local nest_patches = { }
	
	local function gensym()
		gensym_max = gensym_max + 1 ;  return gensym_max
	end

	-----------------------------------------------------------------------------
	-- nest_points are places where a table appears within itself, directly or not.
	-- for instance, all of these chunks create nest points in table x:
	-- "x = { }; x[x] = 1", "x = { }; x[1] = x", "x = { }; x[1] = { y = { x } }".
	-- To handle those, two tables are created by mark_nest_point:
	-- * nest_points [parent] associates all keys and values in table parent which
	--   create a nest_point with boolean `true'
	-- * nest_patches contain a list of { parent, key, value } tuples creating
	--   a nest point. They're all dumped after all the other table operations
	--   have been performed.
	--
	-- mark_nest_point (p, k, v) fills tables nest_points and nest_patches with
	-- informations required to remember that key/value (k,v) create a nest point
	-- in table parent. It also marks `parent' as occuring multiple times, since
	-- several references to it will be required in order to patch the nest
	-- points.
	-----------------------------------------------------------------------------
	local function mark_nest_point (parent, k, v)
		local nk, nv = nested[k], nested[v]
		assert (not nk or seen_once[k] or multiple[k])
		assert (not nv or seen_once[v] or multiple[v])
		local mode = (nk and nv and "kv") or (nk and "k") or ("v")
		local parent_np = nest_points [parent]
		local pair = { k, v }
		if not parent_np then parent_np = { }; nest_points [parent] = parent_np end
		parent_np [k], parent_np [v] = nk, nv
		table.insert (nest_patches, { parent, k, v })
		seen_once [parent], multiple [parent]  = nil, true
	end

	-----------------------------------------------------------------------------
	-- First pass, list the tables and functions which appear more than once in x
	-----------------------------------------------------------------------------
	local function mark_multiple_occurences (x)
		if no_identity [type(x)] then return end
		if     seen_once [x]     then seen_once [x], multiple [x] = nil, true
		elseif multiple  [x]     then -- pass
		else   seen_once [x] = true end
		
		if type (x) == 'table' then
			nested [x] = true
			for k, v in pairs (x) do
				if nested[k] or nested[v] then mark_nest_point (x, k, v) else
					mark_multiple_occurences (k)
					mark_multiple_occurences (v)
				end
			end
			nested [x] = nil
		end
	end

	local dumped    = { } -- multiply occuring values already dumped in localdefs
	local localdefs = { } -- already dumped local definitions as source code lines

	-- mutually recursive functions:
	local dump_val, dump_or_ref_val

	--------------------------------------------------------------------
	-- if x occurs multiple times, dump the local var rather than the
	-- value. If it's the first time it's dumped, also dump the content
	-- in localdefs.
	--------------------------------------------------------------------
	function dump_or_ref_val (x)
		if nested[x] then return 'false' end -- placeholder for recursive reference
		if not multiple[x] then return dump_val (x) end
		local var = dumped [x]
		if var then return "_[" .. var .. "]"-- Minetest: builtin/misc_register.lua

--
-- Make raw registration functions inaccessible to anyone except this file
--

local register_item_raw = core.register_item_raw
core.register_item_raw = nil

local unregister_item_raw = core.unregister_item_raw
core.unregister_item_raw = nil

local register_alias_raw = core.register_alias_raw
core.register_alias_raw = nil

--
-- Item / entity / ABM / LBM registration functions
--

core.registered_abms = {}
core.registered_lbms = {}
core.registered_entities = {}
core.registered_items = {}
core
	-----------------------------------------------------------------------------
	function dump_val(x)
		local  t = type(x)
		if     x==nil        then return 'nil'
		elseif t=="number"   then return tostring(x)
		elseif t=="string"   then return string.format("%q", x)
		elseif t=="boolean"  then return x and "true" or "false"
		elseif t=="table" then
			local acc        = { }
			local idx_dumped = { }
			local np         = nest_points [x]
			for i, v in ipairs(x) do
				if np and np[v] then
					table.insert (acc, 'false') -- placeholder
				else
					table.insert (acc, dump_or_ref_val(v))
				end
				idx_dumped[i] = true
			end
			for k, v in pairs(x) do
				if np and (np[k] or np[v]) then
					--check_multiple(k); check_multiple(v) -- force dumps in localdefs
				elseif not idx_dumped[k] then
					table.insert (acc, "[" .. dump_or_ref_val(k) .. "] = " .. dump_or_ref_val(v))
				end
			end
			return "{ "..table.concat(acc,", ").." }"
		else
			error ("Can't serialize data of type "..t)
		end
	end
	
	local function dump_nest_patches()
		for _, entry in ipairs(nest_patches) do
			local p, k, v = unpack (entry)
			assert (multiple[p])
			local set = dump_or_ref_val (p) .. "[" .. dump_or_ref_val (k) .. "] = " .. 
				dump_or_ref_val (v) .. " -- rec "
			table.insert (localdefs, set)
		end
	end

	mark_multiple_occurences (x)
	local toplevel = dump_or_ref_val (x)
	dump_nest_patches()

	if next (localdefs) then
		return "local _={ }\n" ..
			table.concat (localdefs, "\n") .. 
			"\n.mod_origin = core.get_current_modname() or "??"
end

function core.register_entity(name, prototype)
	-- Check name
	if name == nil then
		error("Unable to register entity: Name is nil")
	end
	name = check_modname_prefix(tostring(name))

	prototype.name = name
	prototype.__index = prototype  -- so that it can be used as a metatable

	-- Add to core.registered_entities
	core.registered_entities[name] = prototype
	prototype.mod_origin = core.get_current_modname() or "??"
end

function core.register_item(name, itemdef)
	-- Check name
	if name == nil then
		error("Unable to register item: Name is nil")
	end
	name = check_modname_prefix(tostring(name))
	if forbidden_item_names[name] then
		error("Unable to register item: Name is forbidden: " .. name)
	end
	itemdef.name = name

	error(name .. ': failed')
		end
	end

	unittest_input = {cat={sound="nyan", speed=400}, dog={sound="woof"}}
	unittest_output = minetest.deserialize(minetest.serialize(unittest_input))

	unitTest("test 1a", unittest_input.cat.sound == unittest_output.cat.sound)
	unitTest("test 1b", unittest_input.cat.speed == unittest_output.cat.speed)
	unitTest("test 1c", unittest_input.dog.sound == unittest_output.dog.sound)

	unittest_input = {escapechars="\n\r\t\v\\\"\'", noneuropean="θשׁ٩∂"}
	unittest_output = minetest.deserialize(minetest.serialize(unittest_input))
	unitTest("test 3a", unittest_input.escapechars == unittest_output.escapechars)
	unitTest("test 3b", unittest_input.noneuropean == unittest_output.noneuropean)
end
unit_test() -- Run it
unit_test = nil -- Hide it

>.name] = itemdef elseif itemdef.type == "tool" then setmetatable(itemdef, {__index = core.tooldef_default}) core.registered_tools[itemdef.name] = itemdef elseif itemdef.type == "none" then setmetatable(itemdef, {__index = core.noneitemdef_default}) else error("Unable to register item: Type is invalid: " .. dump(itemdef)) end -- Flowing liquid uses param2 if itemdef.type == "node" and itemdef.liquidtype == "flowing" then itemdef.paramtype2 = "flowingliquid" end -- BEGIN Legacy stuff if itemdef.cookresult_itemstring ~= nil and itemdef.cookresult_itemstring ~= "" then core.register_craft({ type="cooking", output=itemdef.cookresult_itemstring, recipe=itemdef.name, cooktime=itemdef.furnace_cooktime }) end if itemdef.furnace_burntime ~= nil and itemdef.furnace_burntime >= 0 then core.register_craft({ type="fuel", recipe=itemdef.name, burntime=itemdef.furnace_burntime }) end -- END Legacy stuff itemdef.mod_origin = core.get_current_modname() or "??" -- Disable all further modifications getmetatable(itemdef).__newindex = {} --core.log("Registering item: " .. itemdef.name) core.registered_items[itemdef.name] = itemdef core.registered_aliases[itemdef.name] = nil register_item_raw(itemdef) end function core.unregister_item(name) if not core.registered_items[name] then core.log("warning", "Not unregistering item " ..name.. " because it doesn't exist.") return end -- Erase from registered_* table local type = core.registered_items[name].type if type == "node" then core.registered_nodes[name] = nil elseif type == "craft" then core.registered_craftitems[name] = nil elseif type == "tool" then core.registered_tools[name] = nil end core.registered_items[name] = nil unregister_item_raw(name) end function core.register_node(name, nodedef) nodedef.type = "node" core.register_item(name, nodedef) end function core.register_craftitem(name, craftitemdef) craftitemdef.type = "craft" -- BEGIN Legacy stuff if craftitemdef.inventory_image == nil and craftitemdef.image ~= nil then craftitemdef.inventory_image = craftitemdef.image end -- END Legacy stuff core.register_item(name, craftitemdef) end function core.register_tool(name, tooldef) tooldef.type = "tool" tooldef.stack_max = 1 -- BEGIN Legacy stuff if tooldef.inventory_image == nil and tooldef.image ~= nil then tooldef.inventory_image = tooldef.image end if tooldef.tool_capabilities == nil and (tooldef.full_punch_interval ~= nil or tooldef.basetime ~= nil or tooldef.dt_weight ~= nil or tooldef.dt_crackiness ~= nil or tooldef.dt_crumbliness ~= nil or tooldef.dt_cuttability ~= nil or tooldef.basedurability ~= nil or tooldef.dd_weight ~= nil or tooldef.dd_crackiness ~= nil or tooldef.dd_crumbliness ~= nil or tooldef.dd_cuttability ~= nil) then tooldef.tool_capabilities = { full_punch_interval = tooldef.full_punch_interval, basetime = tooldef.basetime, dt_weight = tooldef.dt_weight, dt_crackiness = tooldef.dt_crackiness, dt_crumbliness = tooldef.dt_crumbliness, dt_cuttability = tooldef.dt_cuttability, basedurability = tooldef.basedurability, dd_weight = tooldef.dd_weight, dd_crackiness = tooldef.dd_crackiness, dd_crumbliness = tooldef.dd_crumbliness, dd_cuttability = tooldef.dd_cuttability, } end -- END Legacy stuff core.register_item(name, tooldef) end function core.register_alias(name, convert_to) if forbidden_item_names[name] then error("Unable to register alias: Name is forbidden: " .. name) end if core.registered_items[name] ~= nil then core.log("warning", "Not registering alias, item with same name" .. " is already defined: " .. name .. " -> " .. convert_to) else --core.log("Registering alias: " .. name .. " -> " .. convert_to) core.registered_aliases[name] = convert_to register_alias_raw(name, convert_to) end end function core.register_alias_force(name, convert_to) if forbidden_item_names[name] then error("Unable to register alias: Name is forbidden: " .. name) end if core.registered_items[name] ~= nil then core.unregister_item(name) core.log("info", "Removed item " ..name.. " while attempting to force add an alias") end --core.log("Registering alias: " .. name .. " -> " .. convert_to) core.registered_aliases[name] = convert_to register_alias_raw(name, convert_to) end function core.on_craft(itemstack, player, old_craft_list, craft_inv) for _, func in ipairs(core.registered_on_crafts) do itemstack = func(itemstack, player, old_craft_list, craft_inv) or itemstack end return itemstack end function core.craft_predict(itemstack, player, old_craft_list, craft_inv) for _, func in ipairs(core.registered_craft_predicts) do itemstack = func(itemstack, player, old_craft_list, craft_inv) or itemstack end return itemstack end -- Alias the forbidden item names to "" so they can't be -- created via itemstrings (e.g. /give) local name for name in pairs(forbidden_item_names) do core.registered_aliases[name] = "" register_alias_raw(name, "") end -- Deprecated: -- Aliases for core.register_alias (how ironic...) --core.alias_node = core.register_alias --core.alias_tool = core.register_alias --core.alias_craftitem = core.register_alias -- -- Built-in node definitions. Also defined in C. -- core.register_item(":unknown", { type = "none", description = "Unknown Item", inventory_image = "unknown_item.png", on_place = core.item_place, on_secondary_use = core.item_secondary_use, on_drop = core.item_drop, groups = {not_in_creative_inventory=1}, diggable = true, }) core.register_node(":air", { description = "Air (you hacker you!)", inventory_image = "air.png", wield_image = "air.png", drawtype = "airlike", paramtype = "light", sunlight_propagates = true, walkable = false, pointable = false, diggable = false, buildable_to = true, floodable = true, air_equivalent = true, drop = "", groups = {not_in_creative_inventory=1}, }) core.register_node(":ignore", { description = "Ignore (you hacker you!)", inventory_image = "ignore.png", wield_image = "ignore.png", drawtype = "airlike", paramtype = "none", sunlight_propagates = false, walkable = false, pointable = false, diggable = false, buildable_to = true, -- A way to remove accidentally placed ignores air_equivalent = true, drop = "", groups = {not_in_creative_inventory=1}, }) -- The hand (bare definition) core.register_item(":", { type = "none", groups = {not_in_creative_inventory=1}, }) function core.override_item(name, redefinition) if redefinition.name ~= nil then error("Attempt to redefine name of "..name.." to "..dump(redefinition.name), 2) end if redefinition.type ~= nil then error("Attempt to redefine type of "..name.." to "..dump(redefinition.type), 2) end local item = core.registered_items[name] if not item then error("Attempt to override non-existent item "..name, 2) end for k, v in pairs(redefinition) do rawset(item, k, v) end register_item_raw(item) end core.callback_origins = {} function core.run_callbacks(callbacks, mode, ...) assert(type(callbacks) == "table") local cb_len = #callbacks if cb_len == 0 then if mode == 2 or mode == 3 then return true elseif mode == 4 or mode == 5 then return false end end local ret = nil for i = 1, cb_len do local origin = core.callback_origins[callbacks[i]] if origin then core.set_last_run_mod(origin.mod) --print("Running " .. tostring(callbacks[i]) .. -- " (a " .. origin.name .. " callback in " .. origin.mod .. ")") else --print("No data associated with callback") end local cb_ret = callbacks[i](...) if mode == 0 and i == 1 then ret = cb_ret elseif mode == 1 and i == cb_len then ret = cb_ret elseif mode == 2 then if not cb_ret or i == 1 then ret = cb_ret end elseif mode == 3 then if cb_ret then return cb_ret end ret = cb_ret elseif mode == 4 then if (cb_ret and not ret) or i == 1 then ret = cb_ret end elseif mode == 5 and cb_ret then return cb_ret end end return ret end -- -- Callback registration -- local function make_registration() local t = {} local registerfunc = function(func) t[#t + 1] = func core.callback_origins[func] = { mod = core.get_current_modname() or "??", name = debug.getinfo(1, "n").name or "??" } --local origin = core.callback_origins[func] --print(origin.name .. ": " .. origin.mod .. " registering cbk " .. tostring(func)) end return t, registerfunc end local function make_registration_reverse() local t = {} local registerfunc = function(func) table.insert(t, 1, func) core.callback_origins[func] = { mod = core.get_current_modname() or "??", name = debug.getinfo(1, "n").name or "??" } --local origin = core.callback_origins[func] --print(origin.name .. ": " .. origin.mod .. " registering cbk " .. tostring(func)) end return t, registerfunc end local function make_registration_wrap(reg_fn_name, clear_fn_name) local list = {} local orig_reg_fn = core[reg_fn_name] core[reg_fn_name] = function(def) local retval = orig_reg_fn(def) if retval ~= nil then if def.name ~= nil then list[def.name] = def else list[retval] = def end end return retval end local orig_clear_fn = core[clear_fn_name] core[clear_fn_name] = function() for k in pairs(list) do list[k] = nil end return orig_clear_fn() end return list end core.registered_on_player_hpchanges = { modifiers = { }, loggers = { } } function core.registered_on_player_hpchange(player, hp_change) local last = false for i = #core.registered_on_player_hpchanges.modifiers, 1, -1 do local func = core.registered_on_player_hpchanges.modifiers[i] hp_change, last = func(player, hp_change) if type(hp_change) ~= "number" then local debuginfo = debug.getinfo(func) error("The register_on_hp_changes function has to return a number at " .. debuginfo.short_src .. " line " .. debuginfo.linedefined) end if last then break end end for i, func in ipairs(core.registered_on_player_hpchanges.loggers) do func(player, hp_change) end return hp_change end function core.register_on_player_hpchange(func, modifier) if modifier then core.registered_on_player_hpchanges.modifiers[#core.registered_on_player_hpchanges.modifiers + 1] = func else core.registered_on_player_hpchanges.loggers[#core.registered_on_player_hpchanges.loggers + 1] = func end core.callback_origins[func] = { mod = core.get_current_modname() or "??", name = debug.getinfo(1, "n").name or "??" } end core.registered_biomes = make_registration_wrap("register_biome", "clear_registered_biomes") core.registered_ores = make_registration_wrap("register_ore", "clear_registered_ores") core.registered_decorations = make_registration_wrap("register_decoration", "clear_registered_decorations") core.registered_on_chat_messages, core.register_on_chat_message = make_registration() core.registered_globalsteps, core.register_globalstep = make_registration() core.registered_playerevents, core.register_playerevent = make_registration() core.registered_on_shutdown, core.register_on_shutdown = make_registration() core.registered_on_punchnodes, core.register_on_punchnode = make_registration() core.registered_on_placenodes, core.register_on_placenode = make_registration() core.registered_on_dignodes, core.register_on_dignode = make_registration() core.registered_on_generateds, core.register_on_generated = make_registration() core.registered_on_newplayers, core.register_on_newplayer = make_registration() core.registered_on_dieplayers, core.register_on_dieplayer = make_registration() core.registered_on_respawnplayers, core.register_on_respawnplayer = make_registration() core.registered_on_prejoinplayers, core.register_on_prejoinplayer = make_registration() core.registered_on_joinplayers, core.register_on_joinplayer = make_registration() core.registered_on_leaveplayers, core.register_on_leaveplayer = make_registration() core.registered_on_player_receive_fields, core.register_on_player_receive_fields = make_registration_reverse() core.registered_on_cheats, core.register_on_cheat = make_registration() core.registered_on_crafts, core.register_on_craft = make_registration() core.registered_craft_predicts, core.register_craft_predict = make_registration() core.registered_on_protection_violation, core.register_on_protection_violation = make_registration() core.registered_on_item_eats, core.register_on_item_eat = make_registration() core.registered_on_punchplayers, core.register_on_punchplayer = make_registration() -- -- Compatibility for on_mapgen_init() -- core.register_on_mapgen_init = function(func) func(core.get_mapgen_params()) end