-- Imports ----------------------------------------------------------------------------------------- local core = _G["core"] local math = _G["math"] local string = _G["string"] local table = _G["table"] local mcl_util -- Constants --------------------------------------------------------------------------------------- local MAIN = "main" local HOTBAR_SIZE = 9 local CONTAINER = { SMALL = 2, SHULKER = 3, LEFT = 5, RIGHT = 6, } -- Private Functions ------------------------------------------------------------------------------- local private = {} --[[ Combine like item stacks to make as compact a list as possible. This function avoids allocating new ItemStack objects by altering the counts of the existing stacks to fill up stacks earlier in the array with items from stacks found later in the array. If any given stack is emptied, it is omitted from the returned array. Args: - stacks:array[ItemStack] - an array-like table of ItemStack objects Returns: - array[ItemStack] - an new array-like table containing the consolidated item stacks remaining ]] function private.consolidate_stacks(stacks) local result = {} for _, stack in ipairs(stacks) do local item_def = core.registered_items[stack:get_name()] if item_def == nil then goto continue end if item_def.stack_max == nil then goto continue end for _, existing in ipairs(result) do if stack:get_name() == existing:get_name() then local capacity = item_def.stack_max - existing:get_count() if capacity > 0 then local allocate = math.min(stack:get_count(), capacity) existing:set_count(existing:get_count() + allocate) stack:set_count(stack:get_count() - allocate) if stack:get_count() == 0 then break end end end end if stack:get_count() > 0 then table.insert(result, stack) end ::continue:: end return result end --[[ Extract an array of item stacks from a given inventory. Args: - inventory:InvRef - the inventory from which to extract item stacks - target:array[ItemStack]|nil - the array to place the stacks into (a new list as default) - skip_count:int|nil - the number of slots to skip at the start of the list (e.g., the hotbar items from the player's "main" inventory) (0 by default) - list_name:str|nil - the list from which to extract items ("main" by default) Returns: - array[ItemStack] - the list which contains the extracted items ]] function private.extract_stacks(inventory, target, skip_count, list_name) target = target or {} skip_count = skip_count or 0 list_name = list_name or MAIN local first_slot = 1 + skip_count local last_slot = inventory:get_size(list_name) for index = first_slot, last_slot do local stack = inventory:get_stack(list_name, index) if stack == nil then goto continue end if stack:is_empty() then goto continue end table.insert(target, stack) ::continue:: end return target end --[[ Extract item stacks from any valid chest, small or large. This function can handle both small and large chests as well as other chest-like objects. Whatever the underlying node, a single list will be returned containing all the item stacks in the (potentially combined) inventory of all the blocks which make up the chest. Args: - pos:vector - the location of the chest (or half-chest) - target:array[ItemStack]|nil - the array to place the stacks into (a new list as default) Returns: - array[ItemStack] - the list which contains the extracted items ]] function private.extract_stacks_from_chest(pos, target) target = target or {} local node = core.get_node(pos) if node == nil then return target end private.extract_stacks_from_node(pos, target) if mcl_util ~= nil then local container_type = core.get_item_group(node.name, "container") if container_type == CONTAINER.LEFT then pos = mcl_util.get_double_container_neighbor_pos(pos, node.param2, "left") private.extract_stacks_from_node(pos, target) elseif container_type == CONTAINER.RIGHT then pos = mcl_util.get_double_container_neighbor_pos(pos, node.param2, "right") private.extract_stacks_from_node(pos, target) end end return target end --[[ Extract the item stacks contained in a node's inventory. Args: - pos:vector - the location of the node whose inventory is to be extracted - target:array[ItemStack]|nil - the array to place the stacks into (a new list as default) - list_name:string - the name of the inventory list to extract ("main" as default) Returns: - array[ItemStack] - the list which contains the extracted items ]] function private.extract_stacks_from_node(pos, target, list_name) local inventory = core.get_inventory({type="node", pos=pos}) if inventory == nil then return target end return private.extract_stacks(inventory, target, 0, list_name) end --[[ Retrieve the human-readable name for a given item stack. Args: - stack:ItemStack - the item stack whose name is desired Returns: - str - the unlocalized human-readble name for the given item ]] function private.get_human_name(stack) local desc = stack:get_short_description() local split, _ = string.find(desc, ")", 1, true) if split == nil then return desc end return string.sub(desc, split+1) end --[[ Replace the contents of an inventory list with an array of item stacks. This function overwrites the inventory list's contents with the provided array of item stacks, including emptying any "extra" positions. Args: - inventory:InvRef - the inventory to alter - stacks:array[ItemStack] - the item stacks to use as a replacement - list_name:str|nil - the list to overwrite ("main" by default) - skip_count:int - the number of slots at the start of the list to leave untouched (e.g., the hotbar of the player's "main" inventory list) (0 by default) Returns: - array[ItemStack] - any item stacks which didn't fit into the provided inventory ]] function private.inject_stacks(inventory, stacks, skip_count, list_name) list_name = list_name or MAIN skip_count = skip_count or 0 local first_index = 1 + skip_count local last_index = inventory:get_size(list_name) local stack_index = 1 for inv_index = first_index, last_index do inventory:set_stack(list_name, inv_index, stacks[stack_index]) stack_index = stack_index + 1 end local remaining = {} while stack_index <= #stacks do table.insert(remaining, stacks[stack_index]) stack_index = stack_index + 1 end return remaining end --[[ Inject item stacks into a chest, replacing the items which were already there. This function is aware of both single-node and multi-node chests. In the latter case, it will attempt to fill the left-hand side of the chest before proceeding on to the right-hand side. In either case, if not all of the items could be placed in the chest, the returned list will contain those left over. Args: - pos:vector - the location of the chest (or half-chest) - stacks:array[ItemStack] - the item stacks to be placed into the chest Returns: - array[ItemStack] - any items which couldn't be fit into the chest ]] function private.inject_stacks_into_chest(pos, stacks) local node = core.get_node(pos) if node == nil then return end local left_pos, right_pos = pos, nil if mcl_util ~= nil then local container_type = core.get_item_group(node.name, "container") if container_type == CONTAINER.LEFT then left_pos = pos right_pos = mcl_util.get_double_container_neighbor_pos(pos, node.param2, "left") elseif container_type == CONTAINER.RIGHT then left_pos = mcl_util.get_double_container_neighbor_pos(pos, node.param2, "right") right_pos = pos end end local remaining = stacks if left_pos ~= nil then remaining = private.inject_stacks_into_node(left_pos, remaining) end if right_pos ~= nil then remaining = private.inject_stacks_into_node(right_pos, remaining) end return remaining end --[[ Replace a given node's inventory with a give set of item stacks. Args: - pos:vector - the location of the node to modify - stacks:array[ItemStack] - the item stacks to insert - list_name:string|nil - the inventory list to affect ("main" as default) Returns: - array[ItemStack] - any items which couldn't be fit into the node's inventory ]] function private.inject_stacks_into_node(pos, stacks, list_name) local inventory = core.get_inventory({type="node", pos=pos}) if inventory == nil then return stacks end return private.inject_stacks(inventory, stacks, 0, list_name) end --[[ Determine whether a certain type of node contains an inventory. Args: - node:table - the node definition to consider Returns: - true if that node type has an inventory ]] function private.is_inventory_node(node_def) if node_def.allow_metadata_inventory_move then return true end if node_def.allow_metadata_inventory_put then return true end if node_def.allow_metadata_inventory_take then return true end return false end --[[ Sort the inventory attached to a chest. This function will look for a chest at the given coordinates, and both consolidate stacks and sort the contents by their (unlocalized) human-readable name. This function only affects the "main" inventory of the node, so its safe to use on things like furnaces, etc. It is also aware of double-chests added by Minclonia, and will correctly sort all the contents of such chests. Args: - pos:vector - the location of the node whose inventory should be sorted Returns: - nil ]] function private.sort_chest(pos) local stacks = private.extract_stacks_from_chest(pos) stacks = private.consolidate_stacks(stacks) stacks = private.sort_stacks(stacks) private.inject_stacks_into_chest(pos, stacks) end --[[ Sort the player's main inventory list (excluding the hotbar). Args: - player:ObjectRef - the player whose inventory is to be sorted Returns: - nil ]] function private.sort_player_inventory(player) local inventory = player:get_inventory() if inventory == nil then return end local stacks = private.extract_stacks(inventory, {}, HOTBAR_SIZE) stacks = private.consolidate_stacks(stacks) stacks = private.sort_stacks(stacks) private.inject_stacks(inventory, stacks, HOTBAR_SIZE) end --[[ Sort a list of item stacks according to human-readable name. The sorting is performed in place using the unlocalized human-readable name for each item taken from the item's "short" description. If multiple stacks have the same name, then the size of the stack (largest to smallest) is used to break the tie. Args: - stacks:array[ItemStack] - the array/table to be sorted Returns: - nil ]] function private.sort_stacks(stacks) table.sort(stacks, function(a, b) if a == nil then return false end if b == nil then return true end local a_name = private.get_human_name(a) local b_name = private.get_human_name(b) if a_name ~= b_name then return a_name < b_name end if a:get_count() ~= b:get_count() then return a:get_count() > b:get_count() end return false end) return stacks end --[[ Watch a given type of node for changes to its inventory. This function uses the standard callback functions for a node definition (i.e., the various on_metadata_inventory_* functions), and ensures the existing function is called first, so it's safe to use with other mods. Args: - table - the node type to watch Returns: - nil ]] function private.watch_node_inventory(node_def) local old_omi_move = node_def.on_metadata_inventory_move local old_omi_put = node_def.on_metadata_inventory_put local old_omi_take = node_def.on_metadata_inventory_take core.override_item(node_def.name, { on_metadata_inventory_move = (function( pos, from_list, from_index, to_list, to_index, count, player) old_omi_move(pos, from_list, from_index, to_list, to_index, count, player) private.sort_chest(pos) end), on_metadata_inventory_put = (function(pos, listname, index, stack, player) old_omi_put(pos, listname, index, stack, player) private.sort_chest(pos) end), on_metadata_inventory_take = (function(pos, listname, index, stack, player) old_omi_take(pos, listname, index, stack, player) private.sort_chest(pos) end) }) end -- Registrations ----------------------------------------------------------------------------------- core.register_on_joinplayer(function(player, last_login) private.sort_player_inventory(player) end) core.register_on_player_inventory_action(function(player, action, inventory, inventory_info) private.sort_player_inventory(player) end) core.register_on_item_eat(function(hp_change, replace_with_item, itemstack, player, pointed_thing) private.sort_player_inventory(player) end) core.register_on_mods_loaded(function() mcl_util = _G["mcl_util"] for name, node_def in pairs(core.registered_nodes) do if private.is_inventory_node(node_def) then private.watch_node_inventory(node_def) end end end)