]> git.lizzy.rs Git - dragonfireclient.git/blob - src/itemdef.cpp
Suppress MSVC warning in chat.cpp
[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 "gamedef.h"
24 #include "nodedef.h"
25 #include "tool.h"
26 #include "inventory.h"
27 #ifndef SERVER
28 #include "mapblock_mesh.h"
29 #include "mesh.h"
30 #include "wieldmesh.h"
31 #include "tile.h"
32 #endif
33 #include "log.h"
34 #include "main.h" // g_settings
35 #include "settings.h"
36 #include "util/serialize.h"
37 #include "util/container.h"
38 #include "util/thread.h"
39 #include <map>
40 #include <set>
41
42 #ifdef __ANDROID__
43 #include <GLES/gl.h>
44 #endif
45
46 /*
47         ItemDefinition
48 */
49 ItemDefinition::ItemDefinition()
50 {
51         resetInitial();
52 }
53
54 ItemDefinition::ItemDefinition(const ItemDefinition &def)
55 {
56         resetInitial();
57         *this = def;
58 }
59
60 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
61 {
62         if(this == &def)
63                 return *this;
64
65         reset();
66
67         type = def.type;
68         name = def.name;
69         description = def.description;
70         inventory_image = def.inventory_image;
71         wield_image = def.wield_image;
72         wield_scale = def.wield_scale;
73         stack_max = def.stack_max;
74         usable = def.usable;
75         liquids_pointable = def.liquids_pointable;
76         if(def.tool_capabilities)
77         {
78                 tool_capabilities = new ToolCapabilities(
79                                 *def.tool_capabilities);
80         }
81         groups = def.groups;
82         node_placement_prediction = def.node_placement_prediction;
83         sound_place = def.sound_place;
84         range = def.range;
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         wield_image = "";
107         wield_scale = v3f(1.0, 1.0, 1.0);
108         stack_max = 99;
109         usable = false;
110         liquids_pointable = false;
111         if(tool_capabilities)
112         {
113                 delete tool_capabilities;
114                 tool_capabilities = NULL;
115         }
116         groups.clear();
117         sound_place = SimpleSoundSpec();
118         range = -1;
119
120         node_placement_prediction = "";
121 }
122
123 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
124 {
125         if(protocol_version <= 17)
126                 writeU8(os, 1); // version
127         else if(protocol_version <= 20)
128                 writeU8(os, 2); // version
129         else
130                 writeU8(os, 3); // version
131         writeU8(os, type);
132         os<<serializeString(name);
133         os<<serializeString(description);
134         os<<serializeString(inventory_image);
135         os<<serializeString(wield_image);
136         writeV3F1000(os, wield_scale);
137         writeS16(os, stack_max);
138         writeU8(os, usable);
139         writeU8(os, liquids_pointable);
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<<serializeString(tool_capabilities_s);
147         writeU16(os, groups.size());
148         for(std::map<std::string, int>::const_iterator
149                         i = groups.begin(); i != groups.end(); i++){
150                 os<<serializeString(i->first);
151                 writeS16(os, i->second);
152         }
153         os<<serializeString(node_placement_prediction);
154         if(protocol_version > 17){
155                 //serializeSimpleSoundSpec(sound_place, os);
156                 os<<serializeString(sound_place.name);
157                 writeF1000(os, sound_place.gain);
158         }
159         if(protocol_version > 20){
160                 writeF1000(os, range);
161         }
162 }
163
164 void ItemDefinition::deSerialize(std::istream &is)
165 {
166         // Reset everything
167         reset();
168
169         // Deserialize
170         int version = readU8(is);
171         if(version < 1 || version > 3)
172                 throw SerializationError("unsupported ItemDefinition version");
173         type = (enum ItemType)readU8(is);
174         name = deSerializeString(is);
175         description = deSerializeString(is);
176         inventory_image = deSerializeString(is);
177         wield_image = deSerializeString(is);
178         wield_scale = readV3F1000(is);
179         stack_max = readS16(is);
180         usable = readU8(is);
181         liquids_pointable = readU8(is);
182         std::string tool_capabilities_s = deSerializeString(is);
183         if(!tool_capabilities_s.empty())
184         {
185                 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
186                 tool_capabilities = new ToolCapabilities;
187                 tool_capabilities->deSerialize(tmp_is);
188         }
189         groups.clear();
190         u32 groups_size = readU16(is);
191         for(u32 i=0; i<groups_size; i++){
192                 std::string name = deSerializeString(is);
193                 int value = readS16(is);
194                 groups[name] = value;
195         }
196         if(version == 1){
197                 // We cant be sure that node_placement_prediction is send in version 1
198                 try{
199                         node_placement_prediction = deSerializeString(is);
200                 }catch(SerializationError &e) {};
201                 // Set the old default sound
202                 sound_place.name = "default_place_node";
203                 sound_place.gain = 0.5;
204         } else if(version >= 2) {
205                 node_placement_prediction = deSerializeString(is);
206                 //deserializeSimpleSoundSpec(sound_place, is);
207                 sound_place.name = deSerializeString(is);
208                 sound_place.gain = readF1000(is);
209         }
210         if(version == 3) {
211                 range = readF1000(is);
212         }
213         // If you add anything here, insert it primarily inside the try-catch
214         // block to not need to increase the version.
215         try{
216         }catch(SerializationError &e) {};
217 }
218
219 /*
220         CItemDefManager
221 */
222
223 // SUGG: Support chains of aliases?
224
225 class CItemDefManager: public IWritableItemDefManager
226 {
227 #ifndef SERVER
228         struct ClientCached
229         {
230                 video::ITexture *inventory_texture;
231                 scene::IMesh *wield_mesh;
232
233                 ClientCached():
234                         inventory_texture(NULL),
235                         wield_mesh(NULL)
236                 {}
237         };
238 #endif
239
240 public:
241         CItemDefManager()
242         {
243
244 #ifndef SERVER
245                 m_main_thread = get_current_thread_id();
246 #endif
247                 clear();
248         }
249         virtual ~CItemDefManager()
250         {
251 #ifndef SERVER
252                 const std::list<ClientCached*> &values = m_clientcached.getValues();
253                 for(std::list<ClientCached*>::const_iterator
254                                 i = values.begin(); i != values.end(); ++i)
255                 {
256                         ClientCached *cc = *i;
257                         if (cc->wield_mesh)
258                                 cc->wield_mesh->drop();
259                         delete cc;
260                 }
261
262 #endif
263                 for (std::map<std::string, ItemDefinition*>::iterator iter =
264                                 m_item_definitions.begin(); iter != m_item_definitions.end();
265                                 iter ++) {
266                         delete iter->second;
267                 }
268                 m_item_definitions.clear();
269         }
270         virtual const ItemDefinition& get(const std::string &name_) const
271         {
272                 // Convert name according to possible alias
273                 std::string name = getAlias(name_);
274                 // Get the definition
275                 std::map<std::string, ItemDefinition*>::const_iterator i;
276                 i = m_item_definitions.find(name);
277                 if(i == m_item_definitions.end())
278                         i = m_item_definitions.find("unknown");
279                 assert(i != m_item_definitions.end());
280                 return *(i->second);
281         }
282         virtual std::string getAlias(const std::string &name) const
283         {
284                 std::map<std::string, std::string>::const_iterator i;
285                 i = m_aliases.find(name);
286                 if(i != m_aliases.end())
287                         return i->second;
288                 return name;
289         }
290         virtual std::set<std::string> getAll() const
291         {
292                 std::set<std::string> result;
293                 for(std::map<std::string, ItemDefinition*>::const_iterator
294                                 i = m_item_definitions.begin();
295                                 i != m_item_definitions.end(); i++)
296                 {
297                         result.insert(i->first);
298                 }
299                 for(std::map<std::string, std::string>::const_iterator
300                                 i = m_aliases.begin();
301                                 i != m_aliases.end(); i++)
302                 {
303                         result.insert(i->first);
304                 }
305                 return result;
306         }
307         virtual bool isKnown(const std::string &name_) const
308         {
309                 // Convert name according to possible alias
310                 std::string name = getAlias(name_);
311                 // Get the definition
312                 std::map<std::string, ItemDefinition*>::const_iterator i;
313                 return m_item_definitions.find(name) != m_item_definitions.end();
314         }
315 #ifndef SERVER
316 public:
317         ClientCached* createClientCachedDirect(const std::string &name,
318                         IGameDef *gamedef) const
319         {
320                 infostream<<"Lazily creating item texture and mesh for \""
321                                 <<name<<"\""<<std::endl;
322
323                 // This is not thread-safe
324                 assert(get_current_thread_id() == m_main_thread);
325
326                 // Skip if already in cache
327                 ClientCached *cc = NULL;
328                 m_clientcached.get(name, &cc);
329                 if(cc)
330                         return cc;
331
332                 ITextureSource *tsrc = gamedef->getTextureSource();
333                 INodeDefManager *nodedef = gamedef->getNodeDefManager();
334                 const ItemDefinition &def = get(name);
335
336                 // Create new ClientCached
337                 cc = new ClientCached();
338
339                 // Create an inventory texture
340                 cc->inventory_texture = NULL;
341                 if(def.inventory_image != "")
342                         cc->inventory_texture = tsrc->getTexture(def.inventory_image);
343
344                 // Additional processing for nodes:
345                 // - Create a wield mesh if WieldMeshSceneNode can't render
346                 //   the node on its own.
347                 // - If inventory_texture isn't set yet, create one using
348                 //   render-to-texture.
349                 if (def.type == ITEM_NODE) {
350                         // Get node properties
351                         content_t id = nodedef->getId(name);
352                         const ContentFeatures &f = nodedef->get(id);
353
354                         bool need_rtt_mesh = cc->inventory_texture == NULL;
355
356                         // Keep this in sync with WieldMeshSceneNode::setItem()
357                         bool need_wield_mesh =
358                                 !(f.mesh_ptr[0] ||
359                                   f.drawtype == NDT_NORMAL ||
360                                   f.drawtype == NDT_ALLFACES ||
361                                   f.drawtype == NDT_AIRLIKE);
362
363                         scene::IMesh *node_mesh = NULL;
364
365                         bool reenable_shaders = false;
366
367                         if (need_rtt_mesh || need_wield_mesh) {
368                                 u8 param1 = 0;
369                                 if (f.param_type == CPT_LIGHT)
370                                         param1 = 0xee;
371
372                                 /*
373                                         Make a mesh from the node
374                                 */
375                                 if (g_settings->getBool("enable_shaders")) {
376                                         reenable_shaders = true;
377                                         g_settings->setBool("enable_shaders", false);
378                                 }
379                                 MeshMakeData mesh_make_data(gamedef);
380                                 u8 param2 = 0;
381                                 if (f.param_type_2 == CPT2_WALLMOUNTED)
382                                         param2 = 1;
383                                 MapNode mesh_make_node(id, param1, param2);
384                                 mesh_make_data.fillSingleNode(&mesh_make_node);
385                                 MapBlockMesh mapblock_mesh(&mesh_make_data, v3s16(0, 0, 0));
386                                 node_mesh = mapblock_mesh.getMesh();
387                                 node_mesh->grab();
388                                 video::SColor c(255, 255, 255, 255);
389                                 setMeshColor(node_mesh, c);
390
391                                 // scale and translate the mesh so it's a
392                                 // unit cube centered on the origin
393                                 scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
394                                 translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));
395                         }
396
397                         /*
398                                 Draw node mesh into a render target texture
399                         */
400                         if (need_rtt_mesh) {
401                                 TextureFromMeshParams params;
402                                 params.mesh = node_mesh;
403                                 params.dim.set(64, 64);
404                                 params.rtt_texture_name = "INVENTORY_"
405                                         + def.name + "_RTT";
406                                 params.delete_texture_on_shutdown = true;
407                                 params.camera_position.set(0, 1.0, -1.5);
408                                 params.camera_position.rotateXZBy(45);
409                                 params.camera_lookat.set(0, 0, 0);
410                                 // Set orthogonal projection
411                                 params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
412                                                 1.65, 1.65, 0, 100);
413                                 params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
414                                 params.light_position.set(10, 100, -50);
415                                 params.light_color.set(1.0, 0.5, 0.5, 0.5);
416                                 params.light_radius = 1000;
417
418 #ifdef __ANDROID__
419                                 params.camera_position.set(0, -1.0, -1.5);
420                                 params.camera_position.rotateXZBy(45);
421                                 params.light_position.set(10, -100, -50);
422 #endif
423                                 cc->inventory_texture =
424                                         tsrc->generateTextureFromMesh(params);
425
426                                 // render-to-target didn't work
427                                 if (cc->inventory_texture == NULL) {
428                                         cc->inventory_texture =
429                                                 tsrc->getTexture(f.tiledef[0].name);
430                                 }
431                         }
432
433                         /*
434                                 Use the node mesh as the wield mesh
435                         */
436                         if (need_wield_mesh) {
437                                 cc->wield_mesh = node_mesh;
438                                 cc->wield_mesh->grab();
439
440                                 // no way reference count can be smaller than 2 in this place!
441                                 assert(cc->wield_mesh->getReferenceCount() >= 2);
442                         }
443
444                         if (node_mesh)
445                                 node_mesh->drop();
446
447                         if (reenable_shaders)
448                                 g_settings->setBool("enable_shaders",true);
449                 }
450
451                 // Put in cache
452                 m_clientcached.set(name, cc);
453
454                 return cc;
455         }
456         ClientCached* getClientCached(const std::string &name,
457                         IGameDef *gamedef) const
458         {
459                 ClientCached *cc = NULL;
460                 m_clientcached.get(name, &cc);
461                 if(cc)
462                         return cc;
463
464                 if(get_current_thread_id() == m_main_thread)
465                 {
466                         return createClientCachedDirect(name, gamedef);
467                 }
468                 else
469                 {
470                         // We're gonna ask the result to be put into here
471                         static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
472
473                         // Throw a request in
474                         m_get_clientcached_queue.add(name, 0, 0, &result_queue);
475                         try{
476                                 while(true) {
477                                         // Wait result for a second
478                                         GetResult<std::string, ClientCached*, u8, u8>
479                                                 result = result_queue.pop_front(1000);
480
481                                         if (result.key == name) {
482                                                 return result.item;
483                                         }
484                                 }
485                         }
486                         catch(ItemNotFoundException &e)
487                         {
488                                 errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl;
489                                 return &m_dummy_clientcached;
490                         }
491                 }
492         }
493         // Get item inventory texture
494         virtual video::ITexture* getInventoryTexture(const std::string &name,
495                         IGameDef *gamedef) const
496         {
497                 ClientCached *cc = getClientCached(name, gamedef);
498                 if(!cc)
499                         return NULL;
500                 return cc->inventory_texture;
501         }
502         // Get item wield mesh
503         virtual scene::IMesh* getWieldMesh(const std::string &name,
504                         IGameDef *gamedef) const
505         {
506                 ClientCached *cc = getClientCached(name, gamedef);
507                 if(!cc)
508                         return NULL;
509                 return cc->wield_mesh;
510         }
511 #endif
512         void clear()
513         {
514                 for(std::map<std::string, ItemDefinition*>::const_iterator
515                                 i = m_item_definitions.begin();
516                                 i != m_item_definitions.end(); i++)
517                 {
518                         delete i->second;
519                 }
520                 m_item_definitions.clear();
521                 m_aliases.clear();
522
523                 // Add the four builtin items:
524                 //   "" is the hand
525                 //   "unknown" is returned whenever an undefined item
526                 //     is accessed (is also the unknown node)
527                 //   "air" is the air node
528                 //   "ignore" is the ignore node
529
530                 ItemDefinition* hand_def = new ItemDefinition;
531                 hand_def->name = "";
532                 hand_def->wield_image = "wieldhand.png";
533                 hand_def->tool_capabilities = new ToolCapabilities;
534                 m_item_definitions.insert(std::make_pair("", hand_def));
535
536                 ItemDefinition* unknown_def = new ItemDefinition;
537                 unknown_def->type = ITEM_NODE;
538                 unknown_def->name = "unknown";
539                 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
540
541                 ItemDefinition* air_def = new ItemDefinition;
542                 air_def->type = ITEM_NODE;
543                 air_def->name = "air";
544                 m_item_definitions.insert(std::make_pair("air", air_def));
545
546                 ItemDefinition* ignore_def = new ItemDefinition;
547                 ignore_def->type = ITEM_NODE;
548                 ignore_def->name = "ignore";
549                 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
550         }
551         virtual void registerItem(const ItemDefinition &def)
552         {
553                 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
554                 // Ensure that the "" item (the hand) always has ToolCapabilities
555                 if(def.name == "")
556                         assert(def.tool_capabilities != NULL);
557
558                 if(m_item_definitions.count(def.name) == 0)
559                         m_item_definitions[def.name] = new ItemDefinition(def);
560                 else
561                         *(m_item_definitions[def.name]) = def;
562
563                 // Remove conflicting alias if it exists
564                 bool alias_removed = (m_aliases.erase(def.name) != 0);
565                 if(alias_removed)
566                         infostream<<"ItemDefManager: erased alias "<<def.name
567                                         <<" because item was defined"<<std::endl;
568         }
569         virtual void registerAlias(const std::string &name,
570                         const std::string &convert_to)
571         {
572                 if(m_item_definitions.find(name) == m_item_definitions.end())
573                 {
574                         verbosestream<<"ItemDefManager: setting alias "<<name
575                                 <<" -> "<<convert_to<<std::endl;
576                         m_aliases[name] = convert_to;
577                 }
578         }
579         void serialize(std::ostream &os, u16 protocol_version)
580         {
581                 writeU8(os, 0); // version
582                 u16 count = m_item_definitions.size();
583                 writeU16(os, count);
584                 for(std::map<std::string, ItemDefinition*>::const_iterator
585                                 i = m_item_definitions.begin();
586                                 i != m_item_definitions.end(); i++)
587                 {
588                         ItemDefinition *def = i->second;
589                         // Serialize ItemDefinition and write wrapped in a string
590                         std::ostringstream tmp_os(std::ios::binary);
591                         def->serialize(tmp_os, protocol_version);
592                         os<<serializeString(tmp_os.str());
593                 }
594                 writeU16(os, m_aliases.size());
595                 for(std::map<std::string, std::string>::const_iterator
596                         i = m_aliases.begin(); i != m_aliases.end(); i++)
597                 {
598                         os<<serializeString(i->first);
599                         os<<serializeString(i->second);
600                 }
601         }
602         void deSerialize(std::istream &is)
603         {
604                 // Clear everything
605                 clear();
606                 // Deserialize
607                 int version = readU8(is);
608                 if(version != 0)
609                         throw SerializationError("unsupported ItemDefManager version");
610                 u16 count = readU16(is);
611                 for(u16 i=0; i<count; i++)
612                 {
613                         // Deserialize a string and grab an ItemDefinition from it
614                         std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
615                         ItemDefinition def;
616                         def.deSerialize(tmp_is);
617                         // Register
618                         registerItem(def);
619                 }
620                 u16 num_aliases = readU16(is);
621                 for(u16 i=0; i<num_aliases; i++)
622                 {
623                         std::string name = deSerializeString(is);
624                         std::string convert_to = deSerializeString(is);
625                         registerAlias(name, convert_to);
626                 }
627         }
628         void processQueue(IGameDef *gamedef)
629         {
630 #ifndef SERVER
631                 //NOTE this is only thread safe for ONE consumer thread!
632                 while(!m_get_clientcached_queue.empty())
633                 {
634                         GetRequest<std::string, ClientCached*, u8, u8>
635                                         request = m_get_clientcached_queue.pop();
636
637                         m_get_clientcached_queue.pushResult(request,
638                                         createClientCachedDirect(request.key, gamedef));
639                 }
640 #endif
641         }
642 private:
643         // Key is name
644         std::map<std::string, ItemDefinition*> m_item_definitions;
645         // Aliases
646         std::map<std::string, std::string> m_aliases;
647 #ifndef SERVER
648         // The id of the thread that is allowed to use irrlicht directly
649         threadid_t m_main_thread;
650         // A reference to this can be returned when nothing is found, to avoid NULLs
651         mutable ClientCached m_dummy_clientcached;
652         // Cached textures and meshes
653         mutable MutexedMap<std::string, ClientCached*> m_clientcached;
654         // Queued clientcached fetches (to be processed by the main thread)
655         mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
656 #endif
657 };
658
659 IWritableItemDefManager* createItemDefManager()
660 {
661         return new CItemDefManager();
662 }