Allow overriding tool capabilities through itemstack metadata
authorraymoo <uguu@installgentoo.com>
Tue, 18 Apr 2017 23:30:27 +0000 (16:30 -0700)
committerparamat <mat.gregory@virginmedia.com>
Sun, 29 Oct 2017 11:57:38 +0000 (11:57 +0000)
This makes it possible to modify the tool capabilities of individual
itemstacks by calling a method on itemstack metadata references.

doc/lua_api.txt
src/game.cpp
src/inventory.h
src/itemstackmetadata.cpp
src/itemstackmetadata.h
src/network/serverpackethandler.cpp
src/script/lua_api/l_itemstackmeta.cpp
src/script/lua_api/l_itemstackmeta.h
src/tool.cpp
src/tool.h

index 6109f082bb011bc9bdc9c3478c9265e4b90d66c7..de4cc50291e2e00a6575e4ffce3f4db24f46d54c 100644 (file)
@@ -3366,6 +3366,9 @@ Can be obtained via `item:get_meta()`.
 
 #### Methods
 * 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`
 Mod metadata: per mod metadata, saved automatically.
index cd4650baf0712b7355f23cbf9ce1f28541cb414a..fd3914356225f59a3f3204aea55105f37c064a9b 100644 (file)
@@ -3701,8 +3701,13 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
        } else if (pointed.type == POINTEDTHING_NODE) {
                ToolCapabilities playeritem_toolcap =
                                playeritem.getToolCapabilities(itemdef_manager);
-               if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
-                       playeritem_toolcap = *hand_def.tool_capabilities;
+               if (playeritem.name.empty()) {
+                       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,
                        playeritem_toolcap, dtime);
@@ -4004,9 +4009,9 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
        // If can't dig, try hand
        if (!params.diggable) {
                InventoryList *hlist = local_inventory->getList("hand");
-               const ItemDefinition &hand =
-                       hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
-               const ToolCapabilities *tp = hand.tool_capabilities;
+               const ToolCapabilities *tp = hlist
+                       ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
+                       : itemdef_manager->get("").tool_capabilities;
 
                if (tp)
                        params = getDigParams(nodedef_manager->get(n).groups, tp);
index d04dc1e69f36f35d6b11285afee6235241e868bb..465aa66db346934fb95314765c5b1b2199fc4e68 100644 (file)
@@ -111,12 +111,15 @@ struct ItemStack
        const ToolCapabilities& getToolCapabilities(
                        IItemDefManager *itemdef) const
        {
-               ToolCapabilities *cap;
-               cap = itemdef->get(name).tool_capabilities;
-               if(cap == NULL)
-                       cap = itemdef->get("").tool_capabilities;
-               assert(cap != NULL);
-               return *cap;
+               const ToolCapabilities *item_cap =
+                       itemdef->get(name).tool_capabilities;
+
+               if (item_cap == NULL)
+                       // Fall back to the hand's tool capabilities
+                       item_cap = itemdef->get("").tool_capabilities;
+
+               assert(item_cap != NULL);
+               return metadata.getToolCapabilities(*item_cap); // Check for override
        }
 
        // Wear out (only tools)
index f63671425d390222397a35df81aa0a0dbbe68b10..53c8bad83e25680f4d0c5da866ca6963203d1fcc 100644 (file)
@@ -9,6 +9,22 @@
 #define DESERIALIZE_KV_DELIM_STR "\x02"
 #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
 {
        std::ostringstream os2;
@@ -41,4 +57,29 @@ void ItemStackMetadata::deSerialize(std::istream &is)
                        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, "");
 }
index 843ef48325c997065158036985d1439a4ced8086..0e1977c8c850590b1c312f9c1c3212cb85b9224f 100644 (file)
@@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #pragma once
 
 #include "metadata.h"
+#include "tool.h"
 
 class Inventory;
 class IItemDefManager;
@@ -27,6 +28,27 @@ class IItemDefManager;
 class ItemStackMetadata : public Metadata
 {
 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 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;
 };
index 31bff7b5c6f758cf9a59293e22d95e02bbb47f68..b248b867bc85ae8a5b3b1c368c1d988ae66f3a6f 100644 (file)
@@ -1210,9 +1210,10 @@ void Server::handleCommand_Interact(NetworkPacket* pkt)
                                // If can't dig, try hand
                                if (!params.diggable) {
                                        InventoryList *hlist = playersao->getInventory()->getList("hand");
-                                       const ItemDefinition &hand =
-                                               hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get("");
-                                       const ToolCapabilities *tp = hand.tool_capabilities;
+                                       const ToolCapabilities *tp = hlist
+                                               ? &hlist->getItem(0).getToolCapabilities(m_itemdef)
+                                               : m_itemdef->get("").tool_capabilities;
+
                                        if (tp)
                                                params = getDigParams(m_nodedef->get(n).groups, tp);
                                }
index c37a82116d83bac99a0e7a193021afd83c8bd6eb..3cbc3d0f74721559a2f3e636c98528a8d38bc565 100644 (file)
@@ -50,6 +50,20 @@ void ItemStackMetaRef::reportMetadataChange()
 }
 
 // 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
 int ItemStackMetaRef::gc_object(lua_State *L) {
@@ -116,5 +130,6 @@ const luaL_Reg ItemStackMetaRef::methods[] = {
        luamethod(MetaDataRef, to_table),
        luamethod(MetaDataRef, from_table),
        luamethod(MetaDataRef, equals),
+       luamethod(ItemStackMetaRef, set_tool_capabilities),
        {0,0}
 };
index 241f04c4ce0dff953f622f5e94c8659b93f0e3f3..46c40ab30b835af2b35f1a8b09f5d20f27162fd0 100644 (file)
@@ -40,7 +40,18 @@ private:
 
        virtual void reportMetadataChange();
 
+       void setToolCapabilities(const ToolCapabilities &caps)
+       {
+               istack->metadata.setToolCapabilities(caps);
+       }
+
+       void clearToolCapabilities()
+       {
+               istack->metadata.clearToolCapabilities();
+       }
+
        // Exported functions
+       static int l_set_tool_capabilities(lua_State *L);
 
        // garbage collector
        static int gc_object(lua_State *L);
index 839b1e387891162ccbd6384959c49ab629440b1d..2d2f9dee51f832afbcab322328d2434ed809ea57 100644 (file)
@@ -25,6 +25,34 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "util/serialize.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
 {
        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,
                const ToolCapabilities *tp, float time_from_last_punch)
 {
index c6bf0ad73fbee6b9e4b2f8cc4e9cd19e4b2298a4..f6b196a49daba6c7559f0525d81a4c194a2f08cf 100644 (file)
@@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include <string>
 #include <iostream>
 #include "itemgroup.h"
+#include <json/json.h>
 
 struct ToolGroupCap
 {
@@ -42,6 +43,9 @@ struct ToolGroupCap
                *time = i->second;
                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 deSerialize(std::istream &is);
+       void serializeJson(std::ostream &os) const;
+       void deserializeJson(std::istream &is);
 };
 
 struct DigParams