Skip to content

Commit

Permalink
fix(server/crafting): weight discrepancy during crafting (#1849)
Browse files Browse the repository at this point in the history
Resolves #1848.
  • Loading branch information
subhampro authored Dec 10, 2024
1 parent 44d09a5 commit 0b09b6b
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions modules/crafting/server.lua
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,32 @@ lib.callback.register('ox_inventory:craftItem', function(source, id, index, reci

local craftedItem = Items(recipe.name)
local craftCount = (type(recipe.count) == 'number' and recipe.count) or (table.type(recipe.count) == 'array' and math.random(recipe.count[1], recipe.count[2])) or 1
local newWeight = left.weight + (craftedItem.weight + (recipe.metadata?.weight or 0)) * craftCount

-- Modified weight calculation
local newWeight = left.weight
local items = Inventory.Search(left, 'slots', tbl) or {}
---@todo new iterator or something to accept a map
-- First subtract weight of ingredients that will be removed
for name, needs in pairs(recipe.ingredients) do
if needs > 0 then
local item = Items(name)
if item then
newWeight -= (item.weight * needs)
end
end
end

-- Add weight of crafted item
newWeight += (craftedItem.weight + (recipe.metadata?.weight or 0)) * craftCount

if newWeight > left.maxWeight then return false, 'cannot_carry' end

local items = Inventory.Search(left, 'slots', tbl) or {}
table.wipe(tbl)

for name, needs in pairs(recipe.ingredients) do
if needs == 0 then break end

local slots = items[name] or items

if #slots == 0 then return end
Expand Down Expand Up @@ -149,13 +169,10 @@ lib.callback.register('ox_inventory:craftItem', function(source, id, index, reci
end
end
elseif needs <= slot.count then
local itemWeight = slot.weight / slot.count
newWeight = (newWeight - slot.weight) + (slot.count - needs) * itemWeight
tbl[slot.slot] = needs
break
else
tbl[slot.slot] = slot.count
newWeight -= slot.weight
needs -= slot.count
end

Expand All @@ -165,10 +182,6 @@ lib.callback.register('ox_inventory:craftItem', function(source, id, index, reci
end
end

if newWeight > left.maxWeight then
return false, 'cannot_carry'
end

if not TriggerEventHooks('craftItem', {
source = source,
benchId = id,
Expand Down

0 comments on commit 0b09b6b

Please sign in to comment.