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