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