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"
44 ItemDefinition::ItemDefinition()
49 ItemDefinition::ItemDefinition(const ItemDefinition &def)
55 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
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;
70 liquids_pointable = def.liquids_pointable;
71 if(def.tool_capabilities)
73 tool_capabilities = new ToolCapabilities(
74 *def.tool_capabilities);
77 node_placement_prediction = def.node_placement_prediction;
78 sound_place = def.sound_place;
82 ItemDefinition::~ItemDefinition()
87 void ItemDefinition::resetInitial()
89 // Initialize pointers to NULL so reset() does not delete undefined pointers
90 tool_capabilities = NULL;
94 void ItemDefinition::reset()
101 wield_scale = v3f(1.0, 1.0, 1.0);
104 liquids_pointable = false;
105 if(tool_capabilities)
107 delete tool_capabilities;
108 tool_capabilities = NULL;
111 sound_place = SimpleSoundSpec();
113 node_placement_prediction = "";
116 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
118 if(protocol_version <= 17)
119 writeU8(os, 1); // version
121 writeU8(os, 2); // version
123 os<<serializeString(name);
124 os<<serializeString(description);
125 os<<serializeString(inventory_image);
126 os<<serializeString(wield_image);
127 writeV3F1000(os, wield_scale);
128 writeS16(os, stack_max);
130 writeU8(os, liquids_pointable);
131 std::string tool_capabilities_s = "";
132 if(tool_capabilities){
133 std::ostringstream tmp_os(std::ios::binary);
134 tool_capabilities->serialize(tmp_os, protocol_version);
135 tool_capabilities_s = tmp_os.str();
137 os<<serializeString(tool_capabilities_s);
138 writeU16(os, groups.size());
139 for(std::map<std::string, int>::const_iterator
140 i = groups.begin(); i != groups.end(); i++){
141 os<<serializeString(i->first);
142 writeS16(os, i->second);
144 os<<serializeString(node_placement_prediction);
145 if(protocol_version > 17){
146 //serializeSimpleSoundSpec(sound_place, os);
147 os<<serializeString(sound_place.name);
148 writeF1000(os, sound_place.gain);
152 void ItemDefinition::deSerialize(std::istream &is)
158 int version = readU8(is);
159 if(version != 1 && version != 2)
160 throw SerializationError("unsupported ItemDefinition version");
161 type = (enum ItemType)readU8(is);
162 name = deSerializeString(is);
163 description = deSerializeString(is);
164 inventory_image = deSerializeString(is);
165 wield_image = deSerializeString(is);
166 wield_scale = readV3F1000(is);
167 stack_max = readS16(is);
169 liquids_pointable = readU8(is);
170 std::string tool_capabilities_s = deSerializeString(is);
171 if(!tool_capabilities_s.empty())
173 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
174 tool_capabilities = new ToolCapabilities;
175 tool_capabilities->deSerialize(tmp_is);
178 u32 groups_size = readU16(is);
179 for(u32 i=0; i<groups_size; i++){
180 std::string name = deSerializeString(is);
181 int value = readS16(is);
182 groups[name] = value;
185 // We cant be sure that node_placement_prediction is send in version 1
187 node_placement_prediction = deSerializeString(is);
188 }catch(SerializationError &e) {};
189 // Set the old default sound
190 sound_place.name = "default_place_node";
191 sound_place.gain = 0.5;
192 } else if(version == 2) {
193 node_placement_prediction = deSerializeString(is);
194 //deserializeSimpleSoundSpec(sound_place, is);
195 sound_place.name = deSerializeString(is);
196 sound_place.gain = readF1000(is);
198 // If you add anything here, insert it primarily inside the try-catch
199 // block to not need to increase the version.
202 }catch(SerializationError &e) {};
209 // SUGG: Support chains of aliases?
211 class CItemDefManager: public IWritableItemDefManager
216 video::ITexture *inventory_texture;
217 scene::IMesh *wield_mesh;
220 inventory_texture(NULL),
231 m_main_thread = get_current_thread_id();
235 virtual ~CItemDefManager()
238 const std::list<ClientCached*> &values = m_clientcached.getValues();
239 for(std::list<ClientCached*>::const_iterator
240 i = values.begin(); i != values.end(); ++i)
242 ClientCached *cc = *i;
244 cc->wield_mesh->drop();
249 for (std::map<std::string, ItemDefinition*>::iterator iter =
250 m_item_definitions.begin(); iter != m_item_definitions.end();
254 m_item_definitions.clear();
256 virtual const ItemDefinition& get(const std::string &name_) const
258 // Convert name according to possible alias
259 std::string name = getAlias(name_);
260 // Get the definition
261 std::map<std::string, ItemDefinition*>::const_iterator i;
262 i = m_item_definitions.find(name);
263 if(i == m_item_definitions.end())
264 i = m_item_definitions.find("unknown");
265 assert(i != m_item_definitions.end());
268 virtual std::string getAlias(const std::string &name) const
270 std::map<std::string, std::string>::const_iterator i;
271 i = m_aliases.find(name);
272 if(i != m_aliases.end())
276 virtual std::set<std::string> getAll() const
278 std::set<std::string> result;
279 for(std::map<std::string, ItemDefinition*>::const_iterator
280 i = m_item_definitions.begin();
281 i != m_item_definitions.end(); i++)
283 result.insert(i->first);
285 for(std::map<std::string, std::string>::const_iterator
286 i = m_aliases.begin();
287 i != m_aliases.end(); i++)
289 result.insert(i->first);
293 virtual bool isKnown(const std::string &name_) const
295 // Convert name according to possible alias
296 std::string name = getAlias(name_);
297 // Get the definition
298 std::map<std::string, ItemDefinition*>::const_iterator i;
299 return m_item_definitions.find(name) != m_item_definitions.end();
303 ClientCached* createClientCachedDirect(const std::string &name,
304 IGameDef *gamedef) const
306 infostream<<"Lazily creating item texture and mesh for \""
307 <<name<<"\""<<std::endl;
309 // This is not thread-safe
310 assert(get_current_thread_id() == m_main_thread);
312 // Skip if already in cache
313 ClientCached *cc = NULL;
314 m_clientcached.get(name, &cc);
318 ITextureSource *tsrc = gamedef->getTextureSource();
319 INodeDefManager *nodedef = gamedef->getNodeDefManager();
320 IrrlichtDevice *device = tsrc->getDevice();
321 video::IVideoDriver *driver = device->getVideoDriver();
322 const ItemDefinition *def = &get(name);
324 // Create new ClientCached
325 cc = new ClientCached();
327 bool need_node_mesh = false;
329 // Create an inventory texture
330 cc->inventory_texture = NULL;
331 if(def->inventory_image != "")
333 cc->inventory_texture = tsrc->getTexture(def->inventory_image);
335 else if(def->type == ITEM_NODE)
337 need_node_mesh = true;
340 // Create a wield mesh
341 assert(cc->wield_mesh == NULL);
342 if(def->type == ITEM_NODE && def->wield_image == "")
344 need_node_mesh = true;
346 else if(def->wield_image != "" || def->inventory_image != "")
348 // Extrude the wield image into a mesh
350 std::string imagename;
351 if(def->wield_image != "")
352 imagename = def->wield_image;
354 imagename = def->inventory_image;
356 cc->wield_mesh = createExtrudedMesh(
357 tsrc->getTexture(imagename),
359 def->wield_scale * v3f(40.0, 40.0, 4.0));
360 if(cc->wield_mesh == NULL)
362 infostream<<"ItemDefManager: WARNING: "
363 <<"updateTexturesAndMeshes(): "
364 <<"Unable to create extruded mesh for item "
365 <<def->name<<std::endl;
374 content_t id = nodedef->getId(def->name);
375 const ContentFeatures &f = nodedef->get(id);
378 if(f.param_type == CPT_LIGHT)
382 Make a mesh from the node
384 MeshMakeData mesh_make_data(gamedef);
385 MapNode mesh_make_node(id, param1, 0);
386 mesh_make_data.fillSingleNode(&mesh_make_node);
387 MapBlockMesh mapblock_mesh(&mesh_make_data);
389 scene::IMesh *node_mesh = mapblock_mesh.getMesh();
391 video::SColor c(255, 255, 255, 255);
392 if(g_settings->getBool("enable_shaders"))
393 c = MapBlock_LightColor(255, 0xffff, decode_light(f.light_source));
394 setMeshColor(node_mesh, c);
397 Scale and translate the mesh so it's a unit cube
398 centered on the origin
400 scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
401 translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));
404 Draw node mesh into a render target texture
406 if(cc->inventory_texture == NULL)
408 TextureFromMeshParams params;
409 params.mesh = node_mesh;
410 params.dim.set(64, 64);
411 params.rtt_texture_name = "INVENTORY_"
412 + def->name + "_RTT";
413 params.delete_texture_on_shutdown = true;
414 params.camera_position.set(0, 1.0, -1.5);
415 params.camera_position.rotateXZBy(45);
416 params.camera_lookat.set(0, 0, 0);
417 // Set orthogonal projection
418 params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
420 params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
421 params.light_position.set(10, 100, -50);
422 params.light_color.set(1.0, 0.5, 0.5, 0.5);
423 params.light_radius = 1000;
425 cc->inventory_texture =
426 tsrc->generateTextureFromMesh(params);
428 // render-to-target didn't work
429 if(cc->inventory_texture == NULL)
431 cc->inventory_texture =
432 tsrc->getTexture(f.tiledef[0].name);
437 Use the node mesh as the wield mesh
440 // Scale to proper wield mesh proportions
441 scaleMesh(node_mesh, v3f(30.0, 30.0, 30.0)
444 cc->wield_mesh = node_mesh;
445 cc->wield_mesh->grab();
447 //no way reference count can be smaller than 2 in this place!
448 assert(cc->wield_mesh->getReferenceCount() >= 2);
452 m_clientcached.set(name, cc);
456 ClientCached* getClientCached(const std::string &name,
457 IGameDef *gamedef) const
459 ClientCached *cc = NULL;
460 m_clientcached.get(name, &cc);
464 if(get_current_thread_id() == m_main_thread)
466 return createClientCachedDirect(name, gamedef);
470 // We're gonna ask the result to be put into here
471 ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
472 // Throw a request in
473 m_get_clientcached_queue.add(name, 0, 0, &result_queue);
475 // Wait result for a second
476 GetResult<std::string, ClientCached*, u8, u8>
477 result = result_queue.pop_front(1000);
478 // Check that at least something worked OK
479 assert(result.key == name);
483 catch(ItemNotFoundException &e)
485 errorstream<<"Waiting for clientcached timed out."<<std::endl;
486 return &m_dummy_clientcached;
490 // Get item inventory texture
491 virtual video::ITexture* getInventoryTexture(const std::string &name,
492 IGameDef *gamedef) const
494 ClientCached *cc = getClientCached(name, gamedef);
497 return cc->inventory_texture;
499 // Get item wield mesh
500 virtual scene::IMesh* getWieldMesh(const std::string &name,
501 IGameDef *gamedef) const
503 ClientCached *cc = getClientCached(name, gamedef);
506 return cc->wield_mesh;
511 for(std::map<std::string, ItemDefinition*>::const_iterator
512 i = m_item_definitions.begin();
513 i != m_item_definitions.end(); i++)
517 m_item_definitions.clear();
520 // Add the four builtin items:
522 // "unknown" is returned whenever an undefined item
523 // is accessed (is also the unknown node)
524 // "air" is the air node
525 // "ignore" is the ignore node
527 ItemDefinition* hand_def = new ItemDefinition;
529 hand_def->wield_image = "wieldhand.png";
530 hand_def->tool_capabilities = new ToolCapabilities;
531 m_item_definitions.insert(std::make_pair("", hand_def));
533 ItemDefinition* unknown_def = new ItemDefinition;
534 unknown_def->type = ITEM_NODE;
535 unknown_def->name = "unknown";
536 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
538 ItemDefinition* air_def = new ItemDefinition;
539 air_def->type = ITEM_NODE;
540 air_def->name = "air";
541 m_item_definitions.insert(std::make_pair("air", air_def));
543 ItemDefinition* ignore_def = new ItemDefinition;
544 ignore_def->type = ITEM_NODE;
545 ignore_def->name = "ignore";
546 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
548 virtual void registerItem(const ItemDefinition &def)
550 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
551 // Ensure that the "" item (the hand) always has ToolCapabilities
553 assert(def.tool_capabilities != NULL);
555 if(m_item_definitions.count(def.name) == 0)
556 m_item_definitions[def.name] = new ItemDefinition(def);
558 *(m_item_definitions[def.name]) = def;
560 // Remove conflicting alias if it exists
561 bool alias_removed = (m_aliases.erase(def.name) != 0);
563 infostream<<"ItemDefManager: erased alias "<<def.name
564 <<" because item was defined"<<std::endl;
566 virtual void registerAlias(const std::string &name,
567 const std::string &convert_to)
569 if(m_item_definitions.find(name) == m_item_definitions.end())
571 verbosestream<<"ItemDefManager: setting alias "<<name
572 <<" -> "<<convert_to<<std::endl;
573 m_aliases[name] = convert_to;
576 void serialize(std::ostream &os, u16 protocol_version)
578 writeU8(os, 0); // version
579 u16 count = m_item_definitions.size();
581 for(std::map<std::string, ItemDefinition*>::const_iterator
582 i = m_item_definitions.begin();
583 i != m_item_definitions.end(); i++)
585 ItemDefinition *def = i->second;
586 // Serialize ItemDefinition and write wrapped in a string
587 std::ostringstream tmp_os(std::ios::binary);
588 def->serialize(tmp_os, protocol_version);
589 os<<serializeString(tmp_os.str());
591 writeU16(os, m_aliases.size());
592 for(std::map<std::string, std::string>::const_iterator
593 i = m_aliases.begin(); i != m_aliases.end(); i++)
595 os<<serializeString(i->first);
596 os<<serializeString(i->second);
599 void deSerialize(std::istream &is)
604 int version = readU8(is);
606 throw SerializationError("unsupported ItemDefManager version");
607 u16 count = readU16(is);
608 for(u16 i=0; i<count; i++)
610 // Deserialize a string and grab an ItemDefinition from it
611 std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
613 def.deSerialize(tmp_is);
617 u16 num_aliases = readU16(is);
618 for(u16 i=0; i<num_aliases; i++)
620 std::string name = deSerializeString(is);
621 std::string convert_to = deSerializeString(is);
622 registerAlias(name, convert_to);
625 void processQueue(IGameDef *gamedef)
628 while(!m_get_clientcached_queue.empty())
630 GetRequest<std::string, ClientCached*, u8, u8>
631 request = m_get_clientcached_queue.pop();
632 GetResult<std::string, ClientCached*, u8, u8>
634 result.key = request.key;
635 result.callers = request.callers;
636 result.item = createClientCachedDirect(request.key, gamedef);
637 request.dest->push_back(result);
643 std::map<std::string, ItemDefinition*> m_item_definitions;
645 std::map<std::string, std::string> m_aliases;
647 // The id of the thread that is allowed to use irrlicht directly
648 threadid_t m_main_thread;
649 // A reference to this can be returned when nothing is found, to avoid NULLs
650 mutable ClientCached m_dummy_clientcached;
651 // Cached textures and meshes
652 mutable MutexedMap<std::string, ClientCached*> m_clientcached;
653 // Queued clientcached fetches (to be processed by the main thread)
654 mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
658 IWritableItemDefManager* createItemDefManager()
660 return new CItemDefManager();