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