Allow overriding tool capabilities through itemstack metadata

This makes it possible to modify the tool capabilities of individual
itemstacks by calling a method on itemstack metadata references.
This commit is contained in:
raymoo 2017-04-18 16:30:27 -07:00 committed by paramat
parent 610ea6f216
commit a637107a4e
10 changed files with 206 additions and 14 deletions

@ -3366,6 +3366,9 @@ Can be obtained via `item:get_meta()`.
#### Methods #### Methods
* All methods in MetaDataRef * All methods in MetaDataRef
* `set_tool_capabilities([tool_capabilities])`
* overrides the item's tool capabilities
* a nil value will clear the override data and restore the original behavior
### `StorageRef` ### `StorageRef`
Mod metadata: per mod metadata, saved automatically. Mod metadata: per mod metadata, saved automatically.

@ -3701,8 +3701,13 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
} else if (pointed.type == POINTEDTHING_NODE) { } else if (pointed.type == POINTEDTHING_NODE) {
ToolCapabilities playeritem_toolcap = ToolCapabilities playeritem_toolcap =
playeritem.getToolCapabilities(itemdef_manager); playeritem.getToolCapabilities(itemdef_manager);
if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) { if (playeritem.name.empty()) {
playeritem_toolcap = *hand_def.tool_capabilities; const ToolCapabilities *handToolcap = hlist
? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
: itemdef_manager->get("").tool_capabilities;
if (handToolcap != nullptr)
playeritem_toolcap = *handToolcap;
} }
handlePointingAtNode(pointed, playeritem_def, playeritem, handlePointingAtNode(pointed, playeritem_def, playeritem,
playeritem_toolcap, dtime); playeritem_toolcap, dtime);
@ -4004,9 +4009,9 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
// If can't dig, try hand // If can't dig, try hand
if (!params.diggable) { if (!params.diggable) {
InventoryList *hlist = local_inventory->getList("hand"); InventoryList *hlist = local_inventory->getList("hand");
const ItemDefinition &hand = const ToolCapabilities *tp = hlist
hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get(""); ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
const ToolCapabilities *tp = hand.tool_capabilities; : itemdef_manager->get("").tool_capabilities;
if (tp) if (tp)
params = getDigParams(nodedef_manager->get(n).groups, tp); params = getDigParams(nodedef_manager->get(n).groups, tp);

@ -111,12 +111,15 @@ struct ItemStack
const ToolCapabilities& getToolCapabilities( const ToolCapabilities& getToolCapabilities(
IItemDefManager *itemdef) const IItemDefManager *itemdef) const
{ {
ToolCapabilities *cap; const ToolCapabilities *item_cap =
cap = itemdef->get(name).tool_capabilities; itemdef->get(name).tool_capabilities;
if(cap == NULL)
cap = itemdef->get("").tool_capabilities; if (item_cap == NULL)
assert(cap != NULL); // Fall back to the hand's tool capabilities
return *cap; item_cap = itemdef->get("").tool_capabilities;
assert(item_cap != NULL);
return metadata.getToolCapabilities(*item_cap); // Check for override
} }
// Wear out (only tools) // Wear out (only tools)

@ -9,6 +9,22 @@
#define DESERIALIZE_KV_DELIM_STR "\x02" #define DESERIALIZE_KV_DELIM_STR "\x02"
#define DESERIALIZE_PAIR_DELIM_STR "\x03" #define DESERIALIZE_PAIR_DELIM_STR "\x03"
#define TOOLCAP_KEY "tool_capabilities"
void ItemStackMetadata::clear()
{
Metadata::clear();
updateToolCapabilities();
}
bool ItemStackMetadata::setString(const std::string &name, const std::string &var)
{
bool result = Metadata::setString(name, var);
if (name == TOOLCAP_KEY)
updateToolCapabilities();
return result;
}
void ItemStackMetadata::serialize(std::ostream &os) const void ItemStackMetadata::serialize(std::ostream &os) const
{ {
std::ostringstream os2; std::ostringstream os2;
@ -41,4 +57,29 @@ void ItemStackMetadata::deSerialize(std::istream &is)
m_stringvars[""] = in; m_stringvars[""] = in;
} }
} }
updateToolCapabilities();
}
void ItemStackMetadata::updateToolCapabilities()
{
if (contains(TOOLCAP_KEY)) {
toolcaps_overridden = true;
toolcaps_override = ToolCapabilities();
std::istringstream is(getString(TOOLCAP_KEY));
toolcaps_override.deserializeJson(is);
} else {
toolcaps_overridden = false;
}
}
void ItemStackMetadata::setToolCapabilities(const ToolCapabilities &caps)
{
std::ostringstream os;
caps.serializeJson(os);
setString(TOOLCAP_KEY, os.str());
}
void ItemStackMetadata::clearToolCapabilities()
{
setString(TOOLCAP_KEY, "");
} }

@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#pragma once #pragma once
#include "metadata.h" #include "metadata.h"
#include "tool.h"
class Inventory; class Inventory;
class IItemDefManager; class IItemDefManager;
@ -27,6 +28,27 @@ class IItemDefManager;
class ItemStackMetadata : public Metadata class ItemStackMetadata : public Metadata
{ {
public: public:
ItemStackMetadata() : toolcaps_overridden(false) {}
// Overrides
void clear() override;
bool setString(const std::string &name, const std::string &var) override;
void serialize(std::ostream &os) const; void serialize(std::ostream &os) const;
void deSerialize(std::istream &is); void deSerialize(std::istream &is);
const ToolCapabilities &getToolCapabilities(
const ToolCapabilities &default_caps) const
{
return toolcaps_overridden ? toolcaps_override : default_caps;
}
void setToolCapabilities(const ToolCapabilities &caps);
void clearToolCapabilities();
private:
void updateToolCapabilities();
bool toolcaps_overridden;
ToolCapabilities toolcaps_override;
}; };

@ -1210,9 +1210,10 @@ void Server::handleCommand_Interact(NetworkPacket* pkt)
// If can't dig, try hand // If can't dig, try hand
if (!params.diggable) { if (!params.diggable) {
InventoryList *hlist = playersao->getInventory()->getList("hand"); InventoryList *hlist = playersao->getInventory()->getList("hand");
const ItemDefinition &hand = const ToolCapabilities *tp = hlist
hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get(""); ? &hlist->getItem(0).getToolCapabilities(m_itemdef)
const ToolCapabilities *tp = hand.tool_capabilities; : m_itemdef->get("").tool_capabilities;
if (tp) if (tp)
params = getDigParams(m_nodedef->get(n).groups, tp); params = getDigParams(m_nodedef->get(n).groups, tp);
} }

@ -50,6 +50,20 @@ void ItemStackMetaRef::reportMetadataChange()
} }
// Exported functions // Exported functions
int ItemStackMetaRef::l_set_tool_capabilities(lua_State *L)
{
ItemStackMetaRef *metaref = checkobject(L, 1);
if (lua_isnoneornil(L, 2)) {
metaref->clearToolCapabilities();
} else if (lua_istable(L, 2)) {
ToolCapabilities caps = read_tool_capabilities(L, 2);
metaref->setToolCapabilities(caps);
} else {
luaL_typerror(L, 2, "table or nil");
}
return 0;
}
// garbage collector // garbage collector
int ItemStackMetaRef::gc_object(lua_State *L) { int ItemStackMetaRef::gc_object(lua_State *L) {
@ -116,5 +130,6 @@ const luaL_Reg ItemStackMetaRef::methods[] = {
luamethod(MetaDataRef, to_table), luamethod(MetaDataRef, to_table),
luamethod(MetaDataRef, from_table), luamethod(MetaDataRef, from_table),
luamethod(MetaDataRef, equals), luamethod(MetaDataRef, equals),
luamethod(ItemStackMetaRef, set_tool_capabilities),
{0,0} {0,0}
}; };

@ -40,7 +40,18 @@ private:
virtual void reportMetadataChange(); virtual void reportMetadataChange();
void setToolCapabilities(const ToolCapabilities &caps)
{
istack->metadata.setToolCapabilities(caps);
}
void clearToolCapabilities()
{
istack->metadata.clearToolCapabilities();
}
// Exported functions // Exported functions
static int l_set_tool_capabilities(lua_State *L);
// garbage collector // garbage collector
static int gc_object(lua_State *L); static int gc_object(lua_State *L);

@ -25,6 +25,34 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "util/serialize.h" #include "util/serialize.h"
#include "util/numeric.h" #include "util/numeric.h"
void ToolGroupCap::toJson(Json::Value &object) const
{
object["maxlevel"] = maxlevel;
object["uses"] = uses;
Json::Value times_object;
for (auto time : times)
times_object[time.first] = time.second;
object["times"] = times_object;
}
void ToolGroupCap::fromJson(const Json::Value &json)
{
if (json.isObject()) {
if (json["maxlevel"].isInt())
maxlevel = json["maxlevel"].asInt();
if (json["uses"].isInt())
uses = json["uses"].asInt();
const Json::Value &times_object = json["times"];
if (times_object.isArray()) {
Json::ArrayIndex size = times_object.size();
for (Json::ArrayIndex i = 0; i < size; ++i)
if (times_object[i].isDouble())
times[i] = times_object[i].asFloat();
}
}
}
void ToolCapabilities::serialize(std::ostream &os, u16 protocol_version) const void ToolCapabilities::serialize(std::ostream &os, u16 protocol_version) const
{ {
writeU8(os, 3); // protocol_version >= 36 writeU8(os, 3); // protocol_version >= 36
@ -84,6 +112,63 @@ void ToolCapabilities::deSerialize(std::istream &is)
} }
} }
void ToolCapabilities::serializeJson(std::ostream &os) const
{
Json::Value root;
root["full_punch_interval"] = full_punch_interval;
root["max_drop_level"] = max_drop_level;
Json::Value groupcaps_object;
for (auto groupcap : groupcaps) {
groupcap.second.toJson(groupcaps_object[groupcap.first]);
}
root["groupcaps"] = groupcaps_object;
Json::Value damage_groups_object;
DamageGroup::const_iterator dgiter;
for (dgiter = damageGroups.begin(); dgiter != damageGroups.end(); ++dgiter) {
damage_groups_object[dgiter->first] = dgiter->second;
}
root["damage_groups"] = damage_groups_object;
os << root;
}
void ToolCapabilities::deserializeJson(std::istream &is)
{
Json::Value root;
is >> root;
if (root.isObject()) {
if (root["full_punch_interval"].isDouble())
full_punch_interval = root["full_punch_interval"].asFloat();
if (root["max_drop_level"].isInt())
max_drop_level = root["max_drop_level"].asInt();
Json::Value &groupcaps_object = root["groupcaps"];
if (groupcaps_object.isObject()) {
Json::ValueIterator gciter;
for (gciter = groupcaps_object.begin();
gciter != groupcaps_object.end(); ++gciter) {
ToolGroupCap groupcap;
groupcap.fromJson(*gciter);
groupcaps[gciter.key().asString()] = groupcap;
}
}
Json::Value &damage_groups_object = root["damage_groups"];
if (damage_groups_object.isObject()) {
Json::ValueIterator dgiter;
for (dgiter = damage_groups_object.begin();
dgiter != damage_groups_object.end(); ++dgiter) {
Json::Value &value = *dgiter;
if (value.isInt())
damageGroups[dgiter.key().asString()] =
value.asInt();
}
}
}
}
DigParams getDigParams(const ItemGroupList &groups, DigParams getDigParams(const ItemGroupList &groups,
const ToolCapabilities *tp, float time_from_last_punch) const ToolCapabilities *tp, float time_from_last_punch)
{ {

@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include <string> #include <string>
#include <iostream> #include <iostream>
#include "itemgroup.h" #include "itemgroup.h"
#include <json/json.h>
struct ToolGroupCap struct ToolGroupCap
{ {
@ -42,6 +43,9 @@ struct ToolGroupCap
*time = i->second; *time = i->second;
return true; return true;
} }
void toJson(Json::Value &object) const;
void fromJson(const Json::Value &json);
}; };
@ -69,6 +73,8 @@ struct ToolCapabilities
void serialize(std::ostream &os, u16 version) const; void serialize(std::ostream &os, u16 version) const;
void deSerialize(std::istream &is); void deSerialize(std::istream &is);
void serializeJson(std::ostream &os) const;
void deserializeJson(std::istream &is);
}; };
struct DigParams struct DigParams