3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2013 Kahrl <kahrl@gmx.net>
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.
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.
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.
26 #include "inventory.h"
28 #include "mapblock_mesh.h"
33 #include "main.h" // g_settings
35 #include "util/serialize.h"
36 #include "util/container.h"
37 #include "util/thread.h"
48 ItemDefinition::ItemDefinition()
53 ItemDefinition::ItemDefinition(const ItemDefinition &def)
59 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
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;
74 liquids_pointable = def.liquids_pointable;
75 if(def.tool_capabilities)
77 tool_capabilities = new ToolCapabilities(
78 *def.tool_capabilities);
81 node_placement_prediction = def.node_placement_prediction;
82 sound_place = def.sound_place;
87 ItemDefinition::~ItemDefinition()
92 void ItemDefinition::resetInitial()
94 // Initialize pointers to NULL so reset() does not delete undefined pointers
95 tool_capabilities = NULL;
99 void ItemDefinition::reset()
104 inventory_image = "";
106 wield_scale = v3f(1.0, 1.0, 1.0);
109 liquids_pointable = false;
110 if(tool_capabilities)
112 delete tool_capabilities;
113 tool_capabilities = NULL;
116 sound_place = SimpleSoundSpec();
119 node_placement_prediction = "";
122 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
124 if(protocol_version <= 17)
125 writeU8(os, 1); // version
126 else if(protocol_version <= 20)
127 writeU8(os, 2); // version
129 writeU8(os, 3); // version
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);
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();
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);
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);
158 if(protocol_version > 20){
159 writeF1000(os, range);
163 void ItemDefinition::deSerialize(std::istream &is)
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);
180 liquids_pointable = readU8(is);
181 std::string tool_capabilities_s = deSerializeString(is);
182 if(!tool_capabilities_s.empty())
184 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
185 tool_capabilities = new ToolCapabilities;
186 tool_capabilities->deSerialize(tmp_is);
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;
196 // We cant be sure that node_placement_prediction is send in version 1
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);
210 range = readF1000(is);
212 // If you add anything here, insert it primarily inside the try-catch
213 // block to not need to increase the version.
215 }catch(SerializationError &e) {};
222 // SUGG: Support chains of aliases?
224 class CItemDefManager: public IWritableItemDefManager
229 video::ITexture *inventory_texture;
230 scene::IMesh *wield_mesh;
233 inventory_texture(NULL),
244 m_main_thread = get_current_thread_id();
248 virtual ~CItemDefManager()
251 const std::list<ClientCached*> &values = m_clientcached.getValues();
252 for(std::list<ClientCached*>::const_iterator
253 i = values.begin(); i != values.end(); ++i)
255 ClientCached *cc = *i;
257 cc->wield_mesh->drop();
262 for (std::map<std::string, ItemDefinition*>::iterator iter =
263 m_item_definitions.begin(); iter != m_item_definitions.end();
267 m_item_definitions.clear();
269 virtual const ItemDefinition& get(const std::string &name_) const
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());
281 virtual std::string getAlias(const std::string &name) const
283 std::map<std::string, std::string>::const_iterator i;
284 i = m_aliases.find(name);
285 if(i != m_aliases.end())
289 virtual std::set<std::string> getAll() const
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++)
296 result.insert(i->first);
298 for(std::map<std::string, std::string>::const_iterator
299 i = m_aliases.begin();
300 i != m_aliases.end(); i++)
302 result.insert(i->first);
306 virtual bool isKnown(const std::string &name_) const
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();
316 ClientCached* createClientCachedDirect(const std::string &name,
317 IGameDef *gamedef) const
319 infostream<<"Lazily creating item texture and mesh for \""
320 <<name<<"\""<<std::endl;
322 // This is not thread-safe
323 assert(get_current_thread_id() == m_main_thread);
325 // Skip if already in cache
326 ClientCached *cc = NULL;
327 m_clientcached.get(name, &cc);
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);
337 // Create new ClientCached
338 cc = new ClientCached();
340 bool need_node_mesh = false;
342 // Create an inventory texture
343 cc->inventory_texture = NULL;
344 if(def->inventory_image != "")
346 cc->inventory_texture = tsrc->getTexture(def->inventory_image);
348 else if(def->type == ITEM_NODE)
350 need_node_mesh = true;
353 // Create a wield mesh
354 assert(cc->wield_mesh == NULL);
355 if(def->type == ITEM_NODE && def->wield_image == "")
357 need_node_mesh = true;
359 else if(def->wield_image != "" || def->inventory_image != "")
361 // Extrude the wield image into a mesh
363 std::string imagename;
364 if(def->wield_image != "")
365 imagename = def->wield_image;
367 imagename = def->inventory_image;
369 cc->wield_mesh = createExtrudedMesh(
370 tsrc->getTexture(imagename),
372 def->wield_scale * v3f(40.0, 40.0, 4.0));
373 if(cc->wield_mesh == NULL)
375 infostream<<"ItemDefManager: WARNING: "
376 <<"updateTexturesAndMeshes(): "
377 <<"Unable to create extruded mesh for item "
378 <<def->name<<std::endl;
387 content_t id = nodedef->getId(def->name);
388 const ContentFeatures &f = nodedef->get(id);
391 if(f.param_type == CPT_LIGHT)
395 Make a mesh from the node
397 bool reenable_shaders = false;
398 if(g_settings->getBool("enable_shaders")){
399 reenable_shaders = true;
400 g_settings->setBool("enable_shaders",false);
402 MeshMakeData mesh_make_data(gamedef);
404 if (f.param_type_2 == CPT2_WALLMOUNTED)
406 MapNode mesh_make_node(id, param1, param2);
407 mesh_make_data.fillSingleNode(&mesh_make_node);
408 MapBlockMesh mapblock_mesh(&mesh_make_data, v3s16(0, 0, 0));
409 scene::IMesh *node_mesh = mapblock_mesh.getMesh();
411 video::SColor c(255, 255, 255, 255);
412 setMeshColor(node_mesh, c);
415 Scale and translate the mesh so it's a unit cube
416 centered on the origin
418 scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
419 translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));
422 Draw node mesh into a render target texture
424 if(cc->inventory_texture == NULL)
426 TextureFromMeshParams params;
427 params.mesh = node_mesh;
428 params.dim.set(64, 64);
429 params.rtt_texture_name = "INVENTORY_"
430 + def->name + "_RTT";
431 params.delete_texture_on_shutdown = true;
432 params.camera_position.set(0, 1.0, -1.5);
433 params.camera_position.rotateXZBy(45);
434 params.camera_lookat.set(0, 0, 0);
435 // Set orthogonal projection
436 params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
438 params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
439 params.light_position.set(10, 100, -50);
440 params.light_color.set(1.0, 0.5, 0.5, 0.5);
441 params.light_radius = 1000;
444 params.camera_position.set(0, -1.0, -1.5);
445 params.camera_position.rotateXZBy(45);
446 params.light_position.set(10, -100, -50);
448 cc->inventory_texture =
449 tsrc->generateTextureFromMesh(params);
451 // render-to-target didn't work
452 if(cc->inventory_texture == NULL)
454 cc->inventory_texture =
455 tsrc->getTexture(f.tiledef[0].name);
460 Use the node mesh as the wield mesh
463 // Scale to proper wield mesh proportions
464 scaleMesh(node_mesh, v3f(30.0, 30.0, 30.0)
467 cc->wield_mesh = node_mesh;
468 cc->wield_mesh->grab();
470 //no way reference count can be smaller than 2 in this place!
471 assert(cc->wield_mesh->getReferenceCount() >= 2);
473 if (reenable_shaders)
474 g_settings->setBool("enable_shaders",true);
478 m_clientcached.set(name, cc);
482 ClientCached* getClientCached(const std::string &name,
483 IGameDef *gamedef) const
485 ClientCached *cc = NULL;
486 m_clientcached.get(name, &cc);
490 if(get_current_thread_id() == m_main_thread)
492 return createClientCachedDirect(name, gamedef);
496 // We're gonna ask the result to be put into here
497 static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
499 // Throw a request in
500 m_get_clientcached_queue.add(name, 0, 0, &result_queue);
503 // Wait result for a second
504 GetResult<std::string, ClientCached*, u8, u8>
505 result = result_queue.pop_front(1000);
507 if (result.key == name) {
512 catch(ItemNotFoundException &e)
514 errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl;
515 return &m_dummy_clientcached;
519 // Get item inventory texture
520 virtual video::ITexture* getInventoryTexture(const std::string &name,
521 IGameDef *gamedef) const
523 ClientCached *cc = getClientCached(name, gamedef);
526 return cc->inventory_texture;
528 // Get item wield mesh
529 virtual scene::IMesh* getWieldMesh(const std::string &name,
530 IGameDef *gamedef) const
532 ClientCached *cc = getClientCached(name, gamedef);
535 return cc->wield_mesh;
540 for(std::map<std::string, ItemDefinition*>::const_iterator
541 i = m_item_definitions.begin();
542 i != m_item_definitions.end(); i++)
546 m_item_definitions.clear();
549 // Add the four builtin items:
551 // "unknown" is returned whenever an undefined item
552 // is accessed (is also the unknown node)
553 // "air" is the air node
554 // "ignore" is the ignore node
556 ItemDefinition* hand_def = new ItemDefinition;
558 hand_def->wield_image = "wieldhand.png";
559 hand_def->tool_capabilities = new ToolCapabilities;
560 m_item_definitions.insert(std::make_pair("", hand_def));
562 ItemDefinition* unknown_def = new ItemDefinition;
563 unknown_def->type = ITEM_NODE;
564 unknown_def->name = "unknown";
565 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
567 ItemDefinition* air_def = new ItemDefinition;
568 air_def->type = ITEM_NODE;
569 air_def->name = "air";
570 m_item_definitions.insert(std::make_pair("air", air_def));
572 ItemDefinition* ignore_def = new ItemDefinition;
573 ignore_def->type = ITEM_NODE;
574 ignore_def->name = "ignore";
575 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
577 virtual void registerItem(const ItemDefinition &def)
579 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
580 // Ensure that the "" item (the hand) always has ToolCapabilities
582 assert(def.tool_capabilities != NULL);
584 if(m_item_definitions.count(def.name) == 0)
585 m_item_definitions[def.name] = new ItemDefinition(def);
587 *(m_item_definitions[def.name]) = def;
589 // Remove conflicting alias if it exists
590 bool alias_removed = (m_aliases.erase(def.name) != 0);
592 infostream<<"ItemDefManager: erased alias "<<def.name
593 <<" because item was defined"<<std::endl;
595 virtual void registerAlias(const std::string &name,
596 const std::string &convert_to)
598 if(m_item_definitions.find(name) == m_item_definitions.end())
600 verbosestream<<"ItemDefManager: setting alias "<<name
601 <<" -> "<<convert_to<<std::endl;
602 m_aliases[name] = convert_to;
605 void serialize(std::ostream &os, u16 protocol_version)
607 writeU8(os, 0); // version
608 u16 count = m_item_definitions.size();
610 for(std::map<std::string, ItemDefinition*>::const_iterator
611 i = m_item_definitions.begin();
612 i != m_item_definitions.end(); i++)
614 ItemDefinition *def = i->second;
615 // Serialize ItemDefinition and write wrapped in a string
616 std::ostringstream tmp_os(std::ios::binary);
617 def->serialize(tmp_os, protocol_version);
618 os<<serializeString(tmp_os.str());
620 writeU16(os, m_aliases.size());
621 for(std::map<std::string, std::string>::const_iterator
622 i = m_aliases.begin(); i != m_aliases.end(); i++)
624 os<<serializeString(i->first);
625 os<<serializeString(i->second);
628 void deSerialize(std::istream &is)
633 int version = readU8(is);
635 throw SerializationError("unsupported ItemDefManager version");
636 u16 count = readU16(is);
637 for(u16 i=0; i<count; i++)
639 // Deserialize a string and grab an ItemDefinition from it
640 std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
642 def.deSerialize(tmp_is);
646 u16 num_aliases = readU16(is);
647 for(u16 i=0; i<num_aliases; i++)
649 std::string name = deSerializeString(is);
650 std::string convert_to = deSerializeString(is);
651 registerAlias(name, convert_to);
654 void processQueue(IGameDef *gamedef)
657 //NOTE this is only thread safe for ONE consumer thread!
658 while(!m_get_clientcached_queue.empty())
660 GetRequest<std::string, ClientCached*, u8, u8>
661 request = m_get_clientcached_queue.pop();
663 m_get_clientcached_queue.pushResult(request,
664 createClientCachedDirect(request.key, gamedef));
670 std::map<std::string, ItemDefinition*> m_item_definitions;
672 std::map<std::string, std::string> m_aliases;
674 // The id of the thread that is allowed to use irrlicht directly
675 threadid_t m_main_thread;
676 // A reference to this can be returned when nothing is found, to avoid NULLs
677 mutable ClientCached m_dummy_clientcached;
678 // Cached textures and meshes
679 mutable MutexedMap<std::string, ClientCached*> m_clientcached;
680 // Queued clientcached fetches (to be processed by the main thread)
681 mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
685 IWritableItemDefManager* createItemDefManager()
687 return new CItemDefManager();