Skip to content

Commit

Permalink
Backport tool charge helpers
Browse files Browse the repository at this point in the history
set_charge/get_charge from other Technic mod
  • Loading branch information
S-S-X committed Jan 7, 2025
1 parent 9b1a188 commit dbcc03c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
7 changes: 7 additions & 0 deletions technic/doc/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ Helper functions
* Some configuration function
* `technic.tube_inject_item(pos, start_pos, velocity, item)`
* Same as `pipeworks.tube_inject_item`
* `technic.get_RE_charge(itemstack)`
* Returns current charge level of tool.
* `technic.set_RE_charge(itemstack, charge)`
* Sets tool charge level.
* `technic.use_RE_charge(itemstack, charge)`
* Attempt to use charge and return `true`/`false` indicating success.
* Always succeeds without checking charge level if creative is enabled.

Registration functions
----------------------
Expand Down
37 changes: 37 additions & 0 deletions technic/helpers.lua
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,43 @@ function technic.refill_RE_charge(stack)
return stack
end

function technic.set_RE_charge(stack, charge)
local max_charge = technic.power_tools[stack:get_name()]
if max_charge then
technic.set_RE_wear(stack, charge, max_charge)
local meta = minetest.deserialize(stack:get_metadata()) or {}
meta.charge = math.min(math.max(0, charge), max_charge)
stack:set_metadata(minetest.serialize(meta))
end
end

technic.set_charge = technic.set_RE_charge

function technic.get_RE_charge(stack)
local max_charge = technic.power_tools[stack:get_name()]
if max_charge then
local meta = minetest.deserialize(stack:get_metadata()) or {}
return meta.charge or 0, max_charge
end
return 0, 0
end

technic.get_charge = technic.get_RE_charge

function technic.use_RE_charge(stack, amount)
if technic.creative_mode or amount <= 0 then
-- Do not check charge in creative mode or when trying to use zero amount
return true
end
local charge = technic.get_RE_charge(stack)
if charge < amount then
-- Not enough energy available
return false
end
technic.set_RE_charge(stack, charge - amount)
-- Charge used successfully
return true
end

-- If the node is loaded, returns it. If it isn't loaded, load it and return nil.
function technic.get_or_load_node(pos)
Expand Down

0 comments on commit dbcc03c

Please sign in to comment.