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