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