]> git.lizzy.rs Git - minetest.git/blob - src/itemdef.cpp
(se)SerializeString: Include max length in the name
[minetest.git] / src / itemdef.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2013 Kahrl <kahrl@gmx.net>
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "itemdef.h"
22
23 #include "nodedef.h"
24 #include "tool.h"
25 #include "inventory.h"
26 #ifndef SERVER
27 #include "client/mapblock_mesh.h"
28 #include "client/mesh.h"
29 #include "client/wieldmesh.h"
30 #include "client/tile.h"
31 #include "client/client.h"
32 #endif
33 #include "log.h"
34 #include "settings.h"
35 #include "util/serialize.h"
36 #include "util/container.h"
37 #include "util/thread.h"
38 #include <map>
39 #include <set>
40
41 /*
42         ItemDefinition
43 */
44 ItemDefinition::ItemDefinition()
45 {
46         resetInitial();
47 }
48
49 ItemDefinition::ItemDefinition(const ItemDefinition &def)
50 {
51         resetInitial();
52         *this = def;
53 }
54
55 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
56 {
57         if(this == &def)
58                 return *this;
59
60         reset();
61
62         type = def.type;
63         name = def.name;
64         description = def.description;
65         inventory_image = def.inventory_image;
66         inventory_overlay = def.inventory_overlay;
67         wield_image = def.wield_image;
68         wield_overlay = def.wield_overlay;
69         wield_scale = def.wield_scale;
70         stack_max = def.stack_max;
71         usable = def.usable;
72         liquids_pointable = def.liquids_pointable;
73         if(def.tool_capabilities)
74         {
75                 tool_capabilities = new ToolCapabilities(
76                                 *def.tool_capabilities);
77         }
78         groups = def.groups;
79         node_placement_prediction = def.node_placement_prediction;
80         sound_place = def.sound_place;
81         sound_place_failed = def.sound_place_failed;
82         range = def.range;
83         palette_image = def.palette_image;
84         color = def.color;
85         return *this;
86 }
87
88 ItemDefinition::~ItemDefinition()
89 {
90         reset();
91 }
92
93 void ItemDefinition::resetInitial()
94 {
95         // Initialize pointers to NULL so reset() does not delete undefined pointers
96         tool_capabilities = NULL;
97         reset();
98 }
99
100 void ItemDefinition::reset()
101 {
102         type = ITEM_NONE;
103         name = "";
104         description = "";
105         inventory_image = "";
106         inventory_overlay = "";
107         wield_image = "";
108         wield_overlay = "";
109         palette_image = "";
110         color = video::SColor(0xFFFFFFFF);
111         wield_scale = v3f(1.0, 1.0, 1.0);
112         stack_max = 99;
113         usable = false;
114         liquids_pointable = false;
115         delete tool_capabilities;
116         tool_capabilities = NULL;
117         groups.clear();
118         sound_place = SimpleSoundSpec();
119         sound_place_failed = SimpleSoundSpec();
120         range = -1;
121
122         node_placement_prediction = "";
123 }
124
125 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
126 {
127         // protocol_version >= 37
128         u8 version = 6;
129         writeU8(os, version);
130         writeU8(os, type);
131         os << serializeString16(name);
132         os << serializeString16(description);
133         os << serializeString16(inventory_image);
134         os << serializeString16(wield_image);
135         writeV3F32(os, wield_scale);
136         writeS16(os, stack_max);
137         writeU8(os, usable);
138         writeU8(os, liquids_pointable);
139
140         std::string tool_capabilities_s;
141         if (tool_capabilities) {
142                 std::ostringstream tmp_os(std::ios::binary);
143                 tool_capabilities->serialize(tmp_os, protocol_version);
144                 tool_capabilities_s = tmp_os.str();
145         }
146         os << serializeString16(tool_capabilities_s);
147
148         writeU16(os, groups.size());
149         for (const auto &group : groups) {
150                 os << serializeString16(group.first);
151                 writeS16(os, group.second);
152         }
153
154         os << serializeString16(node_placement_prediction);
155
156         // Version from ContentFeatures::serialize to keep in sync
157         sound_place.serialize(os, CONTENTFEATURES_VERSION);
158         sound_place_failed.serialize(os, CONTENTFEATURES_VERSION);
159
160         writeF32(os, range);
161         os << serializeString16(palette_image);
162         writeARGB8(os, color);
163         os << serializeString16(inventory_overlay);
164         os << serializeString16(wield_overlay);
165 }
166
167 void ItemDefinition::deSerialize(std::istream &is)
168 {
169         // Reset everything
170         reset();
171
172         // Deserialize
173         int version = readU8(is);
174         if (version < 6)
175                 throw SerializationError("unsupported ItemDefinition version");
176
177         type = (enum ItemType)readU8(is);
178         name = deSerializeString16(is);
179         description = deSerializeString16(is);
180         inventory_image = deSerializeString16(is);
181         wield_image = deSerializeString16(is);
182         wield_scale = readV3F32(is);
183         stack_max = readS16(is);
184         usable = readU8(is);
185         liquids_pointable = readU8(is);
186
187         std::string tool_capabilities_s = deSerializeString16(is);
188         if (!tool_capabilities_s.empty()) {
189                 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
190                 tool_capabilities = new ToolCapabilities;
191                 tool_capabilities->deSerialize(tmp_is);
192         }
193
194         groups.clear();
195         u32 groups_size = readU16(is);
196         for(u32 i=0; i<groups_size; i++){
197                 std::string name = deSerializeString16(is);
198                 int value = readS16(is);
199                 groups[name] = value;
200         }
201
202         node_placement_prediction = deSerializeString16(is);
203
204         // Version from ContentFeatures::serialize to keep in sync
205         sound_place.deSerialize(is, CONTENTFEATURES_VERSION);
206         sound_place_failed.deSerialize(is, CONTENTFEATURES_VERSION);
207
208         range = readF32(is);
209         palette_image = deSerializeString16(is);
210         color = readARGB8(is);
211         inventory_overlay = deSerializeString16(is);
212         wield_overlay = deSerializeString16(is);
213
214         // If you add anything here, insert it primarily inside the try-catch
215         // block to not need to increase the version.
216         //try {
217         //} catch(SerializationError &e) {};
218 }
219
220
221 /*
222         CItemDefManager
223 */
224
225 // SUGG: Support chains of aliases?
226
227 class CItemDefManager: public IWritableItemDefManager
228 {
229 #ifndef SERVER
230         struct ClientCached
231         {
232                 video::ITexture *inventory_texture;
233                 ItemMesh wield_mesh;
234                 Palette *palette;
235
236                 ClientCached():
237                         inventory_texture(NULL),
238                         palette(NULL)
239                 {}
240         };
241 #endif
242
243 public:
244         CItemDefManager()
245         {
246
247 #ifndef SERVER
248                 m_main_thread = std::this_thread::get_id();
249 #endif
250                 clear();
251         }
252         virtual ~CItemDefManager()
253         {
254 #ifndef SERVER
255                 const std::vector<ClientCached*> &values = m_clientcached.getValues();
256                 for (ClientCached *cc : values) {
257                         if (cc->wield_mesh.mesh)
258                                 cc->wield_mesh.mesh->drop();
259                         delete cc;
260                 }
261
262 #endif
263                 for (auto &item_definition : m_item_definitions) {
264                         delete item_definition.second;
265                 }
266                 m_item_definitions.clear();
267         }
268         virtual const ItemDefinition& get(const std::string &name_) const
269         {
270                 // Convert name according to possible alias
271                 std::string name = getAlias(name_);
272                 // Get the definition
273                 auto i = m_item_definitions.find(name);
274                 if (i == m_item_definitions.cend())
275                         i = m_item_definitions.find("unknown");
276                 assert(i != m_item_definitions.cend());
277                 return *(i->second);
278         }
279         virtual const std::string &getAlias(const std::string &name) const
280         {
281                 auto it = m_aliases.find(name);
282                 if (it != m_aliases.cend())
283                         return it->second;
284                 return name;
285         }
286         virtual void getAll(std::set<std::string> &result) const
287         {
288                 result.clear();
289                 for (const auto &item_definition : m_item_definitions) {
290                         result.insert(item_definition.first);
291                 }
292
293                 for (const auto &alias : m_aliases) {
294                         result.insert(alias.first);
295                 }
296         }
297         virtual bool isKnown(const std::string &name_) const
298         {
299                 // Convert name according to possible alias
300                 std::string name = getAlias(name_);
301                 // Get the definition
302                 return m_item_definitions.find(name) != m_item_definitions.cend();
303         }
304 #ifndef SERVER
305 public:
306         ClientCached* createClientCachedDirect(const std::string &name,
307                         Client *client) const
308         {
309                 infostream<<"Lazily creating item texture and mesh for \""
310                                 <<name<<"\""<<std::endl;
311
312                 // This is not thread-safe
313                 sanity_check(std::this_thread::get_id() == m_main_thread);
314
315                 // Skip if already in cache
316                 ClientCached *cc = NULL;
317                 m_clientcached.get(name, &cc);
318                 if(cc)
319                         return cc;
320
321                 ITextureSource *tsrc = client->getTextureSource();
322                 const ItemDefinition &def = get(name);
323
324                 // Create new ClientCached
325                 cc = new ClientCached();
326
327                 // Create an inventory texture
328                 cc->inventory_texture = NULL;
329                 if (!def.inventory_image.empty())
330                         cc->inventory_texture = tsrc->getTexture(def.inventory_image);
331
332                 ItemStack item = ItemStack();
333                 item.name = def.name;
334
335                 getItemMesh(client, item, &(cc->wield_mesh));
336
337                 cc->palette = tsrc->getPalette(def.palette_image);
338
339                 // Put in cache
340                 m_clientcached.set(name, cc);
341
342                 return cc;
343         }
344         ClientCached* getClientCached(const std::string &name,
345                         Client *client) const
346         {
347                 ClientCached *cc = NULL;
348                 m_clientcached.get(name, &cc);
349                 if (cc)
350                         return cc;
351
352                 if (std::this_thread::get_id() == m_main_thread) {
353                         return createClientCachedDirect(name, client);
354                 }
355
356                 // We're gonna ask the result to be put into here
357                 static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
358
359                 // Throw a request in
360                 m_get_clientcached_queue.add(name, 0, 0, &result_queue);
361                 try {
362                         while(true) {
363                                 // Wait result for a second
364                                 GetResult<std::string, ClientCached*, u8, u8>
365                                         result = result_queue.pop_front(1000);
366
367                                 if (result.key == name) {
368                                         return result.item;
369                                 }
370                         }
371                 } catch(ItemNotFoundException &e) {
372                         errorstream << "Waiting for clientcached " << name
373                                 << " timed out." << std::endl;
374                         return &m_dummy_clientcached;
375                 }
376         }
377         // Get item inventory texture
378         virtual video::ITexture* getInventoryTexture(const std::string &name,
379                         Client *client) const
380         {
381                 ClientCached *cc = getClientCached(name, client);
382                 if(!cc)
383                         return NULL;
384                 return cc->inventory_texture;
385         }
386         // Get item wield mesh
387         virtual ItemMesh* getWieldMesh(const std::string &name,
388                         Client *client) const
389         {
390                 ClientCached *cc = getClientCached(name, client);
391                 if(!cc)
392                         return NULL;
393                 return &(cc->wield_mesh);
394         }
395
396         // Get item palette
397         virtual Palette* getPalette(const std::string &name,
398                         Client *client) const
399         {
400                 ClientCached *cc = getClientCached(name, client);
401                 if(!cc)
402                         return NULL;
403                 return cc->palette;
404         }
405
406         virtual video::SColor getItemstackColor(const ItemStack &stack,
407                 Client *client) const
408         {
409                 // Look for direct color definition
410                 const std::string &colorstring = stack.metadata.getString("color", 0);
411                 video::SColor directcolor;
412                 if (!colorstring.empty() && parseColorString(colorstring, directcolor, true))
413                         return directcolor;
414                 // See if there is a palette
415                 Palette *palette = getPalette(stack.name, client);
416                 const std::string &index = stack.metadata.getString("palette_index", 0);
417                 if (palette && !index.empty())
418                         return (*palette)[mystoi(index, 0, 255)];
419                 // Fallback color
420                 return get(stack.name).color;
421         }
422 #endif
423         void applyTextureOverrides(const std::vector<TextureOverride> &overrides)
424         {
425                 infostream << "ItemDefManager::applyTextureOverrides(): Applying "
426                         "overrides to textures" << std::endl;
427
428                 for (const TextureOverride& texture_override : overrides) {
429                         if (m_item_definitions.find(texture_override.id) == m_item_definitions.end()) {
430                                 continue; // Ignore unknown item
431                         }
432
433                         ItemDefinition* itemdef = m_item_definitions[texture_override.id];
434
435                         if (texture_override.hasTarget(OverrideTarget::INVENTORY))
436                                 itemdef->inventory_image = texture_override.texture;
437
438                         if (texture_override.hasTarget(OverrideTarget::WIELD))
439                                 itemdef->wield_image = texture_override.texture;
440                 }
441         }
442         void clear()
443         {
444                 for (auto &i : m_item_definitions)
445                 {
446                         delete i.second;
447                 }
448                 m_item_definitions.clear();
449                 m_aliases.clear();
450
451                 // Add the four builtin items:
452                 //   "" is the hand
453                 //   "unknown" is returned whenever an undefined item
454                 //     is accessed (is also the unknown node)
455                 //   "air" is the air node
456                 //   "ignore" is the ignore node
457
458                 ItemDefinition* hand_def = new ItemDefinition;
459                 hand_def->name = "";
460                 hand_def->wield_image = "wieldhand.png";
461                 hand_def->tool_capabilities = new ToolCapabilities;
462                 m_item_definitions.insert(std::make_pair("", hand_def));
463
464                 ItemDefinition* unknown_def = new ItemDefinition;
465                 unknown_def->type = ITEM_NODE;
466                 unknown_def->name = "unknown";
467                 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
468
469                 ItemDefinition* air_def = new ItemDefinition;
470                 air_def->type = ITEM_NODE;
471                 air_def->name = "air";
472                 m_item_definitions.insert(std::make_pair("air", air_def));
473
474                 ItemDefinition* ignore_def = new ItemDefinition;
475                 ignore_def->type = ITEM_NODE;
476                 ignore_def->name = "ignore";
477                 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
478         }
479         virtual void registerItem(const ItemDefinition &def)
480         {
481                 TRACESTREAM(<< "ItemDefManager: registering " << def.name << std::endl);
482                 // Ensure that the "" item (the hand) always has ToolCapabilities
483                 if (def.name.empty())
484                         FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities");
485
486                 if(m_item_definitions.count(def.name) == 0)
487                         m_item_definitions[def.name] = new ItemDefinition(def);
488                 else
489                         *(m_item_definitions[def.name]) = def;
490
491                 // Remove conflicting alias if it exists
492                 bool alias_removed = (m_aliases.erase(def.name) != 0);
493                 if(alias_removed)
494                         infostream<<"ItemDefManager: erased alias "<<def.name
495                                         <<" because item was defined"<<std::endl;
496         }
497         virtual void unregisterItem(const std::string &name)
498         {
499                 verbosestream<<"ItemDefManager: unregistering \""<<name<<"\""<<std::endl;
500
501                 delete m_item_definitions[name];
502                 m_item_definitions.erase(name);
503         }
504         virtual void registerAlias(const std::string &name,
505                         const std::string &convert_to)
506         {
507                 if (m_item_definitions.find(name) == m_item_definitions.end()) {
508                         TRACESTREAM(<< "ItemDefManager: setting alias " << name
509                                 << " -> " << convert_to << std::endl);
510                         m_aliases[name] = convert_to;
511                 }
512         }
513         void serialize(std::ostream &os, u16 protocol_version)
514         {
515                 writeU8(os, 0); // version
516                 u16 count = m_item_definitions.size();
517                 writeU16(os, count);
518
519                 for (const auto &it : m_item_definitions) {
520                         ItemDefinition *def = it.second;
521                         // Serialize ItemDefinition and write wrapped in a string
522                         std::ostringstream tmp_os(std::ios::binary);
523                         def->serialize(tmp_os, protocol_version);
524                         os << serializeString16(tmp_os.str());
525                 }
526
527                 writeU16(os, m_aliases.size());
528
529                 for (const auto &it : m_aliases) {
530                         os << serializeString16(it.first);
531                         os << serializeString16(it.second);
532                 }
533         }
534         void deSerialize(std::istream &is)
535         {
536                 // Clear everything
537                 clear();
538                 // Deserialize
539                 int version = readU8(is);
540                 if(version != 0)
541                         throw SerializationError("unsupported ItemDefManager version");
542                 u16 count = readU16(is);
543                 for(u16 i=0; i<count; i++)
544                 {
545                         // Deserialize a string and grab an ItemDefinition from it
546                         std::istringstream tmp_is(deSerializeString16(is), std::ios::binary);
547                         ItemDefinition def;
548                         def.deSerialize(tmp_is);
549                         // Register
550                         registerItem(def);
551                 }
552                 u16 num_aliases = readU16(is);
553                 for(u16 i=0; i<num_aliases; i++)
554                 {
555                         std::string name = deSerializeString16(is);
556                         std::string convert_to = deSerializeString16(is);
557                         registerAlias(name, convert_to);
558                 }
559         }
560         void processQueue(IGameDef *gamedef)
561         {
562 #ifndef SERVER
563                 //NOTE this is only thread safe for ONE consumer thread!
564                 while(!m_get_clientcached_queue.empty())
565                 {
566                         GetRequest<std::string, ClientCached*, u8, u8>
567                                         request = m_get_clientcached_queue.pop();
568
569                         m_get_clientcached_queue.pushResult(request,
570                                         createClientCachedDirect(request.key, (Client *)gamedef));
571                 }
572 #endif
573         }
574 private:
575         // Key is name
576         std::map<std::string, ItemDefinition*> m_item_definitions;
577         // Aliases
578         StringMap m_aliases;
579 #ifndef SERVER
580         // The id of the thread that is allowed to use irrlicht directly
581         std::thread::id m_main_thread;
582         // A reference to this can be returned when nothing is found, to avoid NULLs
583         mutable ClientCached m_dummy_clientcached;
584         // Cached textures and meshes
585         mutable MutexedMap<std::string, ClientCached*> m_clientcached;
586         // Queued clientcached fetches (to be processed by the main thread)
587         mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
588 #endif
589 };
590
591 IWritableItemDefManager* createItemDefManager()
592 {
593         return new CItemDefManager();
594 }