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),
229 for (std::map<std::string, ItemDefinition*>::iterator iter =
230 m_item_definitions.begin(); iter != m_item_definitions.end();
234 m_item_definitions.clear();
236 m_main_thread = get_current_thread_id();
242 virtual ~CItemDefManager()
245 const std::list<ClientCached*> &values = m_clientcached.getValues();
246 for(std::list<ClientCached*>::const_iterator
247 i = values.begin(); i != values.end(); ++i)
249 ClientCached *cc = *i;
250 cc->wield_mesh->drop();
254 if (m_driver != NULL) {
255 for (unsigned int i = 0; i < m_extruded_textures.size(); i++) {
256 m_driver->removeTexture(m_extruded_textures[i]);
258 m_extruded_textures.clear();
263 virtual const ItemDefinition& get(const std::string &name_) const
265 // Convert name according to possible alias
266 std::string name = getAlias(name_);
267 // Get the definition
268 std::map<std::string, ItemDefinition*>::const_iterator i;
269 i = m_item_definitions.find(name);
270 if(i == m_item_definitions.end())
271 i = m_item_definitions.find("unknown");
272 assert(i != m_item_definitions.end());
275 virtual std::string getAlias(const std::string &name) const
277 std::map<std::string, std::string>::const_iterator i;
278 i = m_aliases.find(name);
279 if(i != m_aliases.end())
283 virtual std::set<std::string> getAll() const
285 std::set<std::string> result;
286 for(std::map<std::string, ItemDefinition*>::const_iterator
287 i = m_item_definitions.begin();
288 i != m_item_definitions.end(); i++)
290 result.insert(i->first);
292 for(std::map<std::string, std::string>::const_iterator
293 i = m_aliases.begin();
294 i != m_aliases.end(); i++)
296 result.insert(i->first);
300 virtual bool isKnown(const std::string &name_) const
302 // Convert name according to possible alias
303 std::string name = getAlias(name_);
304 // Get the definition
305 std::map<std::string, ItemDefinition*>::const_iterator i;
306 return m_item_definitions.find(name) != m_item_definitions.end();
310 static video::IVideoDriver * m_driver;
311 static std::vector<video::ITexture*> m_extruded_textures;
313 ClientCached* createClientCachedDirect(const std::string &name,
314 IGameDef *gamedef) const
316 infostream<<"Lazily creating item texture and mesh for \""
317 <<name<<"\""<<std::endl;
319 // This is not thread-safe
320 assert(get_current_thread_id() == m_main_thread);
322 // Skip if already in cache
323 ClientCached *cc = NULL;
324 m_clientcached.get(name, &cc);
328 ITextureSource *tsrc = gamedef->getTextureSource();
329 INodeDefManager *nodedef = gamedef->getNodeDefManager();
330 IrrlichtDevice *device = tsrc->getDevice();
331 video::IVideoDriver *driver = device->getVideoDriver();
332 const ItemDefinition *def = &get(name);
334 // Create new ClientCached
335 cc = new ClientCached();
337 bool need_node_mesh = false;
339 // Create an inventory texture
340 cc->inventory_texture = NULL;
341 if(def->inventory_image != "")
343 cc->inventory_texture = tsrc->getTextureRaw(def->inventory_image);
345 else if(def->type == ITEM_NODE)
347 need_node_mesh = true;
350 // Create a wield mesh
351 assert(cc->wield_mesh == NULL);
352 if(def->type == ITEM_NODE && def->wield_image == "")
354 need_node_mesh = true;
356 else if(def->wield_image != "" || def->inventory_image != "")
358 // Extrude the wield image into a mesh
360 std::string imagename;
361 if(def->wield_image != "")
362 imagename = def->wield_image;
364 imagename = def->inventory_image;
366 cc->wield_mesh = createExtrudedMesh(
367 tsrc->getTextureRaw(imagename),
369 def->wield_scale * v3f(40.0, 40.0, 4.0));
370 if(cc->wield_mesh == NULL)
372 infostream<<"ItemDefManager: WARNING: "
373 <<"updateTexturesAndMeshes(): "
374 <<"Unable to create extruded mesh for item "
375 <<def->name<<std::endl;
384 content_t id = nodedef->getId(def->name);
385 const ContentFeatures &f = nodedef->get(id);
388 if(f.param_type == CPT_LIGHT)
392 Make a mesh from the node
394 MeshMakeData mesh_make_data(gamedef);
395 MapNode mesh_make_node(id, param1, 0);
396 mesh_make_data.fillSingleNode(&mesh_make_node);
397 MapBlockMesh mapblock_mesh(&mesh_make_data);
399 scene::IMesh *node_mesh = mapblock_mesh.getMesh();
401 video::SColor c(255, 255, 255, 255);
402 if(g_settings->getS32("enable_shaders") != 0)
403 c = MapBlock_LightColor(255, 0xffff, decode_light(f.light_source));
404 setMeshColor(node_mesh, c);
407 Scale and translate the mesh so it's a unit cube
408 centered on the origin
410 scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
411 translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));
414 Draw node mesh into a render target texture
416 if(cc->inventory_texture == NULL)
418 core::dimension2d<u32> dim(64,64);
419 std::string rtt_texture_name = "INVENTORY_"
420 + def->name + "_RTT";
421 v3f camera_position(0, 1.0, -1.5);
422 camera_position.rotateXZBy(45);
423 v3f camera_lookat(0, 0, 0);
424 core::CMatrix4<f32> camera_projection_matrix;
425 // Set orthogonal projection
426 camera_projection_matrix.buildProjectionMatrixOrthoLH(
429 video::SColorf ambient_light(0.2,0.2,0.2);
430 v3f light_position(10, 100, -50);
431 video::SColorf light_color(0.5,0.5,0.5);
432 f32 light_radius = 1000;
434 cc->inventory_texture = generateTextureFromMesh(
435 node_mesh, device, dim, rtt_texture_name,
438 camera_projection_matrix,
444 // render-to-target didn't work
445 if(cc->inventory_texture == NULL)
447 cc->inventory_texture =
448 tsrc->getTextureRaw(f.tiledef[0].name);
456 m_extruded_textures.push_back(cc->inventory_texture);
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);
475 m_clientcached.set(name, cc);
479 ClientCached* getClientCached(const std::string &name,
480 IGameDef *gamedef) const
482 ClientCached *cc = NULL;
483 m_clientcached.get(name, &cc);
487 if(get_current_thread_id() == m_main_thread)
489 return createClientCachedDirect(name, gamedef);
493 // We're gonna ask the result to be put into here
494 ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
495 // Throw a request in
496 m_get_clientcached_queue.add(name, 0, 0, &result_queue);
498 // Wait result for a second
499 GetResult<std::string, ClientCached*, u8, u8>
500 result = result_queue.pop_front(1000);
501 // Check that at least something worked OK
502 assert(result.key == name);
506 catch(ItemNotFoundException &e)
508 errorstream<<"Waiting for clientcached timed out."<<std::endl;
509 return &m_dummy_clientcached;
513 // Get item inventory texture
514 virtual video::ITexture* getInventoryTexture(const std::string &name,
515 IGameDef *gamedef) const
517 ClientCached *cc = getClientCached(name, gamedef);
520 return cc->inventory_texture;
522 // Get item wield mesh
523 virtual scene::IMesh* getWieldMesh(const std::string &name,
524 IGameDef *gamedef) const
526 ClientCached *cc = getClientCached(name, gamedef);
529 return cc->wield_mesh;
534 for(std::map<std::string, ItemDefinition*>::const_iterator
535 i = m_item_definitions.begin();
536 i != m_item_definitions.end(); i++)
540 m_item_definitions.clear();
543 // Add the four builtin items:
545 // "unknown" is returned whenever an undefined item is accessed
546 // "air" is the air node
547 // "ignore" is the ignore node
549 ItemDefinition* hand_def = new ItemDefinition;
551 hand_def->wield_image = "wieldhand.png";
552 hand_def->tool_capabilities = new ToolCapabilities;
553 m_item_definitions.insert(std::make_pair("", hand_def));
555 ItemDefinition* unknown_def = new ItemDefinition;
556 unknown_def->name = "unknown";
557 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
559 ItemDefinition* air_def = new ItemDefinition;
560 air_def->type = ITEM_NODE;
561 air_def->name = "air";
562 m_item_definitions.insert(std::make_pair("air", air_def));
564 ItemDefinition* ignore_def = new ItemDefinition;
565 ignore_def->type = ITEM_NODE;
566 ignore_def->name = "ignore";
567 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
569 virtual void registerItem(const ItemDefinition &def)
571 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
572 // Ensure that the "" item (the hand) always has ToolCapabilities
574 assert(def.tool_capabilities != NULL);
576 if(m_item_definitions.count(def.name) == 0)
577 m_item_definitions[def.name] = new ItemDefinition(def);
579 *(m_item_definitions[def.name]) = def;
581 // Remove conflicting alias if it exists
582 bool alias_removed = (m_aliases.erase(def.name) != 0);
584 infostream<<"ItemDefManager: erased alias "<<def.name
585 <<" because item was defined"<<std::endl;
587 virtual void registerAlias(const std::string &name,
588 const std::string &convert_to)
590 if(m_item_definitions.find(name) == m_item_definitions.end())
592 verbosestream<<"ItemDefManager: setting alias "<<name
593 <<" -> "<<convert_to<<std::endl;
594 m_aliases[name] = convert_to;
597 void serialize(std::ostream &os, u16 protocol_version)
599 writeU8(os, 0); // version
600 u16 count = m_item_definitions.size();
602 for(std::map<std::string, ItemDefinition*>::const_iterator
603 i = m_item_definitions.begin();
604 i != m_item_definitions.end(); i++)
606 ItemDefinition *def = i->second;
607 // Serialize ItemDefinition and write wrapped in a string
608 std::ostringstream tmp_os(std::ios::binary);
609 def->serialize(tmp_os, protocol_version);
610 os<<serializeString(tmp_os.str());
612 writeU16(os, m_aliases.size());
613 for(std::map<std::string, std::string>::const_iterator
614 i = m_aliases.begin(); i != m_aliases.end(); i++)
616 os<<serializeString(i->first);
617 os<<serializeString(i->second);
620 void deSerialize(std::istream &is)
625 int version = readU8(is);
627 throw SerializationError("unsupported ItemDefManager version");
628 u16 count = readU16(is);
629 for(u16 i=0; i<count; i++)
631 // Deserialize a string and grab an ItemDefinition from it
632 std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
634 def.deSerialize(tmp_is);
638 u16 num_aliases = readU16(is);
639 for(u16 i=0; i<num_aliases; i++)
641 std::string name = deSerializeString(is);
642 std::string convert_to = deSerializeString(is);
643 registerAlias(name, convert_to);
646 void processQueue(IGameDef *gamedef)
649 while(!m_get_clientcached_queue.empty())
651 GetRequest<std::string, ClientCached*, u8, u8>
652 request = m_get_clientcached_queue.pop();
653 GetResult<std::string, ClientCached*, u8, u8>
655 result.key = request.key;
656 result.callers = request.callers;
657 result.item = createClientCachedDirect(request.key, gamedef);
658 request.dest->push_back(result);
664 std::map<std::string, ItemDefinition*> m_item_definitions;
666 std::map<std::string, std::string> m_aliases;
668 // The id of the thread that is allowed to use irrlicht directly
669 threadid_t m_main_thread;
670 // A reference to this can be returned when nothing is found, to avoid NULLs
671 mutable ClientCached m_dummy_clientcached;
672 // Cached textures and meshes
673 mutable MutexedMap<std::string, ClientCached*> m_clientcached;
674 // Queued clientcached fetches (to be processed by the main thread)
675 mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
679 IWritableItemDefManager* createItemDefManager()
681 return new CItemDefManager();
685 //TODO very very very dirty hack!
686 video::IVideoDriver * CItemDefManager::m_driver = 0;
687 std::vector<video::ITexture*> CItemDefManager::m_extruded_textures;