From 8e7449e09253e138716d8dbad6a2ab5c6e089e28 Mon Sep 17 00:00:00 2001 From: Ner'zhul Date: Mon, 9 Jan 2017 20:39:22 +0100 Subject: Environment & IGameDef code refactoring (#4985) * Environment code refactoring * Cleanup includes & class declarations in client & server environment to improve build speed * ServerEnvironment::m_gamedef is now a pointer to Server instead of IGameDef, permitting to cleanup many casts. * Cleanup IGameDef * Move ITextureSource* IGameDef::getTextureSource() to Client only. * Also move ITextureSource *IGameDef::tsrc() helper * drop getShaderSource, getSceneManager, getSoundManager & getCamera abstract call * drop unused emerge() call * cleanup server unused functions (mentionned before) * Drop one unused parameter from ContentFeatures::updateTextures * move checkLocalPrivilege to Client * Remove some unnecessary casts * create_formspec_menu: remove IWritableTextureSource pointer, as client already knows it * Fix some comments * Change required IGameDef to Server/Client pointers * Previous change that game.cpp sometimes calls functions with Client + InventoryManager + IGameDef in same functions but it's the same objects * Remove duplicate Client pointer in GUIFormSpecMenu::GUIFormSpecMenu * drop ClientMap::sectorWasDrawn which is unused --- src/hud.cpp | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) (limited to 'src/hud.cpp') diff --git a/src/hud.cpp b/src/hud.cpp index 43d957380..a602125e3 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -22,10 +22,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "hud.h" #include "settings.h" #include "util/numeric.h" -#include "util/string.h" #include "log.h" -#include "gamedef.h" -#include "itemdef.h" +#include "client.h" #include "inventory.h" #include "client/tile.h" #include "localplayer.h" @@ -41,13 +39,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #endif Hud::Hud(video::IVideoDriver *driver, scene::ISceneManager* smgr, - gui::IGUIEnvironment* guienv, IGameDef *gamedef, LocalPlayer *player, + gui::IGUIEnvironment* guienv, Client *client, LocalPlayer *player, Inventory *inventory) { this->driver = driver; this->smgr = smgr; this->guienv = guienv; - this->gamedef = gamedef; + this->client = client; this->player = player; this->inventory = inventory; @@ -61,7 +59,7 @@ Hud::Hud(video::IVideoDriver *driver, scene::ISceneManager* smgr, for (unsigned int i = 0; i < 4; i++) hbar_colors[i] = video::SColor(255, 255, 255, 255); - tsrc = gamedef->getTextureSource(); + tsrc = client->getTextureSource(); v3f crosshair_color = g_settings->getV3F("crosshair_color"); u32 cross_r = rangelim(myround(crosshair_color.X), 0, 255); @@ -92,7 +90,7 @@ Hud::Hud(video::IVideoDriver *driver, scene::ISceneManager* smgr, m_selection_material.Lighting = false; if (g_settings->getBool("enable_shaders")) { - IShaderSource *shdrsrc = gamedef->getShaderSource(); + IShaderSource *shdrsrc = client->getShaderSource(); u16 shader_id = shdrsrc->getShader( mode == "halo" ? "selection_shader" : "default_shader", 1, 1); m_selection_material.MaterialType = shdrsrc->getShaderInfo(shader_id).material; @@ -193,7 +191,7 @@ void Hud::drawItem(const ItemStack &item, const core::rect& rect, if (!use_hotbar_image) driver->draw2DRectangle(bgcolor2, rect, NULL); drawItemStack(driver, g_fontengine->getFont(), item, rect, NULL, - gamedef, selected ? IT_ROT_SELECTED : IT_ROT_NONE); + client, selected ? IT_ROT_SELECTED : IT_ROT_NONE); } //NOTE: selectitem = 0 -> no selected; selectitem 1-based @@ -629,7 +627,7 @@ void drawItemStack(video::IVideoDriver *driver, const ItemStack &item, const core::rect &rect, const core::rect *clip, - IGameDef *gamedef, + Client *client, ItemRotationKind rotation_kind) { static MeshTimeInfo rotation_time_infos[IT_ROT_NONE]; @@ -643,8 +641,8 @@ void drawItemStack(video::IVideoDriver *driver, return; } - const ItemDefinition &def = item.getDefinition(gamedef->idef()); - scene::IMesh* mesh = gamedef->idef()->getWieldMesh(def.name, gamedef); + const ItemDefinition &def = item.getDefinition(client->idef()); + scene::IMesh* mesh = client->idef()->getWieldMesh(def.name, client); if (mesh) { driver->clearZBuffer(); -- cgit v1.2.3 From 58d83a7bb2f992194c3df304b1dcbb81f98f78c0 Mon Sep 17 00:00:00 2001 From: Dániel Juhász Date: Fri, 10 Mar 2017 18:25:58 +0100 Subject: Hardware coloring for itemstacks Adds the possibility to colorize item stacks based on their metadata. In the item/node definition you can specify palette (an image file) and color (fallback color if the item has no palette or metadata). Then you can add palette_index to the metadata. Dropped itemstacks with different colors do not merge. --- builtin/game/item_entity.lua | 31 +++++++++---- doc/lua_api.txt | 18 ++++++++ src/camera.cpp | 3 +- src/client/tile.cpp | 69 +++++++++++++++++++++++++++- src/client/tile.h | 15 ++++--- src/content_cao.cpp | 39 +++++++++------- src/hud.cpp | 20 +++++++-- src/itemdef.cpp | 55 +++++++++++++++++++---- src/itemdef.h | 18 +++++++- src/nodedef.cpp | 82 +--------------------------------- src/object_properties.cpp | 2 + src/object_properties.h | 2 + src/script/common/c_content.cpp | 14 +++++- src/script/common/c_content.h | 3 +- src/script/cpp_api/s_entity.cpp | 5 ++- src/script/lua_api/l_itemstackmeta.cpp | 5 +++ src/script/lua_api/l_metadata.cpp | 14 ++++++ src/script/lua_api/l_metadata.h | 3 ++ src/script/lua_api/l_nodemeta.cpp | 5 +++ src/script/lua_api/l_object.cpp | 2 +- src/script/lua_api/l_storage.cpp | 5 +++ src/wieldmesh.cpp | 19 +++++--- src/wieldmesh.h | 18 +++++++- 23 files changed, 308 insertions(+), 139 deletions(-) (limited to 'src/hud.cpp') diff --git a/builtin/game/item_entity.lua b/builtin/game/item_entity.lua index be158c119..7b8247116 100644 --- a/builtin/game/item_entity.lua +++ b/builtin/game/item_entity.lua @@ -53,6 +53,8 @@ core.register_entity(":__builtin:item", { if itemtable then itemname = stack:to_table().name end + -- Backwards compatibility: old clients use the texture + -- to get the type of the item local item_texture = nil local item_type = "" if core.registered_items[itemname] then @@ -66,6 +68,7 @@ core.register_entity(":__builtin:item", { visual_size = {x = s, y = s}, collisionbox = {-c, -c, -c, c, c, c}, automatic_rotate = math.pi * 0.5, + wield_item = itemstring, } self.object:set_properties(prop) end, @@ -101,31 +104,39 @@ core.register_entity(":__builtin:item", { self:set_item(self.itemstring) end, + -- moves items from this stack to an other stack try_merge_with = function(self, own_stack, object, obj) + -- other item's stack local stack = ItemStack(obj.itemstring) - if own_stack:get_name() == stack:get_name() and stack:get_free_space() > 0 then + -- only merge if items are the same + if own_stack:get_name() == stack:get_name() and + own_stack:get_meta() == stack:get_meta() and + own_stack:get_wear() == stack:get_wear() and + stack:get_free_space() > 0 then local overflow = false local count = stack:get_count() + own_stack:get_count() local max_count = stack:get_stack_max() if count > max_count then overflow = true + stack:set_count(max_count) count = count - max_count + own_stack:set_count(count) else self.itemstring = '' + stack:set_count(count) end local pos = object:getpos() pos.y = pos.y + (count - stack:get_count()) / max_count * 0.15 object:moveto(pos, false) local s, c - local max_count = stack:get_stack_max() - local name = stack:get_name() if not overflow then - obj.itemstring = name .. " " .. count + obj.itemstring = stack:to_string() s = 0.2 + 0.1 * (count / max_count) c = s object:set_properties({ visual_size = {x = s, y = s}, - collisionbox = {-c, -c, -c, c, c, c} + collisionbox = {-c, -c, -c, c, c, c}, + wield_item = obj.itemstring }) self.object:remove() -- merging succeeded @@ -133,18 +144,20 @@ core.register_entity(":__builtin:item", { else s = 0.4 c = 0.3 + obj.itemstring = stack:to_string() object:set_properties({ visual_size = {x = s, y = s}, - collisionbox = {-c, -c, -c, c, c, c} + collisionbox = {-c, -c, -c, c, c, c}, + wield_item = obj.itemstring }) - obj.itemstring = name .. " " .. max_count s = 0.2 + 0.1 * (count / max_count) c = s + self.itemstring = own_stack:to_string() self.object:set_properties({ visual_size = {x = s, y = s}, - collisionbox = {-c, -c, -c, c, c, c} + collisionbox = {-c, -c, -c, c, c, c}, + wield_item = self.itemstring }) - self.itemstring = name .. " " .. count end end -- merging didn't succeed diff --git a/doc/lua_api.txt b/doc/lua_api.txt index ca1b5d14c..721f5448a 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -1480,6 +1480,9 @@ Item metadata only contains a key-value store. Some of the values in the key-value store are handled specially: * `description`: Set the itemstack's description. Defaults to idef.description +* `color`: A `ColorString`, which sets the stack's color. +* `palette_index`: If the item has a palette, this is used to get the + current color from the palette. Example stuff: @@ -2855,6 +2858,8 @@ See `StorageRef`, `NodeMetaRef` and `ItemStackMetaRef`. * Any non-table value will clear the metadata * See "Node Metadata" for an example * returns `true` on success +* `equals(other)` + * returns `true` if this metadata has the same key-value pairs as `other` ### `NodeMetaRef` Node metadata: reference extra data and functionality stored in a node. @@ -3735,6 +3740,19 @@ Definition tables {hard = 1, metal = 1, spikes = 1} inventory_image = "default_tool_steelaxe.png", wield_image = "", + palette = "", + --[[ + ^ An image file containing the palette of a node. + ^ You can set the currently used color as the + ^ "palette_index" field of the item stack metadata. + ^ The palette is always stretched to fit indices + ^ between 0 and 255, to ensure compatibility with + ^ "colorfacedir" and "colorwallmounted" nodes. + ]] + color = "0xFFFFFFFF", + --[[ + ^ The color of the item. The palette overrides this. + ]] wield_scale = {x = 1, y = 1, z = 1}, stack_max = 99, range = 4.0, diff --git a/src/camera.cpp b/src/camera.cpp index d5c337fe8..7e83dadeb 100644 --- a/src/camera.cpp +++ b/src/camera.cpp @@ -501,7 +501,8 @@ void Camera::setDigging(s32 button) void Camera::wield(const ItemStack &item) { - if (item.name != m_wield_item_next.name) { + if (item.name != m_wield_item_next.name || + item.metadata != m_wield_item_next.metadata) { m_wield_item_next = item; if (m_wield_change_timer > 0) m_wield_change_timer = -m_wield_change_timer; diff --git a/src/client/tile.cpp b/src/client/tile.cpp index 86ca7d422..0aa06980c 100644 --- a/src/client/tile.cpp +++ b/src/client/tile.cpp @@ -341,6 +341,8 @@ public: */ video::ITexture* getTextureForMesh(const std::string &name, u32 *id); + virtual Palette* getPalette(const std::string &name); + // Returns a pointer to the irrlicht device virtual IrrlichtDevice* getDevice() { @@ -377,8 +379,6 @@ public: video::ITexture* generateTextureFromMesh( const TextureFromMeshParams ¶ms); - video::IImage* generateImage(const std::string &name); - video::ITexture* getNormalTexture(const std::string &name); video::SColor getTextureAverageColor(const std::string &name); video::ITexture *getShaderFlagsTexture(bool normamap_present); @@ -401,6 +401,13 @@ private: // if baseimg is NULL, it is created. Otherwise stuff is made on it. bool generateImagePart(std::string part_of_name, video::IImage *& baseimg); + /*! Generates an image from a full string like + * "stone.png^mineral_coal.png^[crack:1:0". + * Shall be called from the main thread. + * The returned Image should be dropped. + */ + video::IImage* generateImage(const std::string &name); + // Thread-safe cache of what source images are known (true = known) MutexedMap m_source_image_existence; @@ -419,6 +426,9 @@ private: // but can't be deleted because the ITexture* might still be used std::vector m_texture_trash; + // Maps image file names to loaded palettes. + UNORDERED_MAP m_palettes; + // Cached settings needed for making textures from meshes bool m_setting_trilinear_filter; bool m_setting_bilinear_filter; @@ -682,6 +692,61 @@ video::ITexture* TextureSource::getTextureForMesh(const std::string &name, u32 * return getTexture(name + "^[applyfiltersformesh", id); } +Palette* TextureSource::getPalette(const std::string &name) +{ + // Only the main thread may load images + sanity_check(thr_is_current_thread(m_main_thread)); + + if (name == "") + return NULL; + + UNORDERED_MAP::iterator it = m_palettes.find(name); + if (it == m_palettes.end()) { + // Create palette + video::IImage *img = generateImage(name); + if (!img) { + warningstream << "TextureSource::getPalette(): palette \"" << name + << "\" could not be loaded." << std::endl; + return NULL; + } + Palette new_palette; + u32 w = img->getDimension().Width; + u32 h = img->getDimension().Height; + // Real area of the image + u32 area = h * w; + if (area == 0) + return NULL; + if (area > 256) { + warningstream << "TextureSource::getPalette(): the specified" + << " palette image \"" << name << "\" is larger than 256" + << " pixels, using the first 256." << std::endl; + area = 256; + } else if (256 % area != 0) + warningstream << "TextureSource::getPalette(): the " + << "specified palette image \"" << name << "\" does not " + << "contain power of two pixels." << std::endl; + // We stretch the palette so it will fit 256 values + // This many param2 values will have the same color + u32 step = 256 / area; + // For each pixel in the image + for (u32 i = 0; i < area; i++) { + video::SColor c = img->getPixel(i % w, i / w); + // Fill in palette with 'step' colors + for (u32 j = 0; j < step; j++) + new_palette.push_back(c); + } + img->drop(); + // Fill in remaining elements + while (new_palette.size() < 256) + new_palette.push_back(video::SColor(0xFFFFFFFF)); + m_palettes[name] = new_palette; + it = m_palettes.find(name); + } + if (it != m_palettes.end()) + return &((*it).second); + return NULL; +} + void TextureSource::processQueue() { /* diff --git a/src/client/tile.h b/src/client/tile.h index d04ab918a..5eec0f2ea 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -33,6 +33,8 @@ class IGameDef; struct TileSpec; struct TileDef; +typedef std::vector Palette; + /* tile.{h,cpp}: Texture handling stuff. */ @@ -106,14 +108,15 @@ public: const std::string &name, u32 *id = NULL)=0; virtual video::ITexture* getTextureForMesh( const std::string &name, u32 *id = NULL) = 0; + /*! + * Returns a palette from the given texture name. + * The pointer is valid until the texture source is + * destructed. + * Should be called from the main thread. + */ + virtual Palette* getPalette(const std::string &name) = 0; virtual IrrlichtDevice* getDevice()=0; virtual bool isKnownSourceImage(const std::string &name)=0; - /*! Generates an image from a full string like - * "stone.png^mineral_coal.png^[crack:1:0". - * Shall be called from the main thread. - * The returned Image should be dropped. - */ - virtual video::IImage* generateImage(const std::string &name)=0; virtual video::ITexture* generateTextureFromMesh( const TextureFromMeshParams ¶ms)=0; virtual video::ITexture* getNormalTexture(const std::string &name)=0; diff --git a/src/content_cao.cpp b/src/content_cao.cpp index e0b1c4cd2..84f198b75 100644 --- a/src/content_cao.cpp +++ b/src/content_cao.cpp @@ -933,23 +933,30 @@ void GenericCAO::addToScene(scene::ISceneManager *smgr, errorstream<<"GenericCAO::addToScene(): Could not load mesh "<= 1){ - infostream<<"textures[0]: "<idef(); - ItemStack item(m_prop.textures[0], 1, 0, idef); - - m_wield_meshnode = new WieldMeshSceneNode( - smgr->getRootSceneNode(), smgr, -1); - m_wield_meshnode->setItem(item, m_client); - - m_wield_meshnode->setScale(v3f(m_prop.visual_size.X/2, - m_prop.visual_size.Y/2, - m_prop.visual_size.X/2)); - u8 li = m_last_light; - m_wield_meshnode->setColor(video::SColor(255,li,li,li)); + ItemStack item; + infostream << "GenericCAO::addToScene(): wielditem" << std::endl; + if (m_prop.wield_item == "") { + // Old format, only textures are specified. + infostream << "textures: " << m_prop.textures.size() << std::endl; + if (m_prop.textures.size() >= 1) { + infostream << "textures[0]: " << m_prop.textures[0] + << std::endl; + IItemDefManager *idef = m_client->idef(); + item = ItemStack(m_prop.textures[0], 1, 0, idef); + } + } else { + infostream << "serialized form: " << m_prop.wield_item << std::endl; + item.deSerialize(m_prop.wield_item, m_client->idef()); } + m_wield_meshnode = new WieldMeshSceneNode(smgr->getRootSceneNode(), + smgr, -1); + m_wield_meshnode->setItem(item, m_client); + + m_wield_meshnode->setScale( + v3f(m_prop.visual_size.X / 2, m_prop.visual_size.Y / 2, + m_prop.visual_size.X / 2)); + u8 li = m_last_light; + m_wield_meshnode->setColor(video::SColor(255, li, li, li)); } else { infostream<<"GenericCAO::addToScene(): \""< #ifdef HAVE_TOUCHSCREENGUI @@ -642,9 +643,10 @@ void drawItemStack(video::IVideoDriver *driver, } const ItemDefinition &def = item.getDefinition(client->idef()); - scene::IMesh* mesh = client->idef()->getWieldMesh(def.name, client); + ItemMesh *imesh = client->idef()->getWieldMesh(def.name, client); - if (mesh) { + if (imesh && imesh->mesh) { + scene::IMesh *mesh = imesh->mesh; driver->clearZBuffer(); s32 delta = 0; if (rotation_kind < IT_ROT_NONE) { @@ -667,16 +669,28 @@ void drawItemStack(video::IVideoDriver *driver, matrix.makeIdentity(); if (enable_animations) { - float timer_f = (float)delta / 5000.0; + float timer_f = (float) delta / 5000.0; matrix.setRotationDegrees(core::vector3df(0, 360 * timer_f, 0)); } driver->setTransform(video::ETS_WORLD, matrix); driver->setViewPort(rect); + video::SColor basecolor = + client->idef()->getItemstackColor(item, client); + u32 mc = mesh->getMeshBufferCount(); for (u32 j = 0; j < mc; ++j) { scene::IMeshBuffer *buf = mesh->getMeshBuffer(j); + // we can modify vertices relatively fast, + // because these meshes are not buffered. + assert(buf->getHardwareMappingHint_Vertex() == scene::EHM_NEVER); + video::SColor c = basecolor; + if (imesh->buffer_colors.size() > j) { + std::pair p = imesh->buffer_colors[j]; + c = p.first ? p.second : basecolor; + } + colorizeMeshBuffer(buf, &c); video::SMaterial &material = buf->getMaterial(); material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; material.Lighting = false; diff --git a/src/itemdef.cpp b/src/itemdef.cpp index 627ad1b6c..51d8f1d5d 100644 --- a/src/itemdef.cpp +++ b/src/itemdef.cpp @@ -82,6 +82,8 @@ ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def) sound_place = def.sound_place; sound_place_failed = def.sound_place_failed; range = def.range; + palette_image = def.palette_image; + color = def.color; return *this; } @@ -104,6 +106,8 @@ void ItemDefinition::reset() description = ""; inventory_image = ""; wield_image = ""; + palette_image = ""; + color = video::SColor(0xFFFFFFFF); wield_scale = v3f(1.0, 1.0, 1.0); stack_max = 99; usable = false; @@ -153,6 +157,8 @@ void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const writeF1000(os, range); os << serializeString(sound_place_failed.name); writeF1000(os, sound_place_failed.gain); + os << serializeString(palette_image); + writeU32(os, color.color); } void ItemDefinition::deSerialize(std::istream &is) @@ -209,6 +215,8 @@ void ItemDefinition::deSerialize(std::istream &is) try { sound_place_failed.name = deSerializeString(is); sound_place_failed.gain = readF1000(is); + palette_image = deSerializeString(is); + color.set(readU32(is)); } catch(SerializationError &e) {}; } @@ -224,11 +232,13 @@ class CItemDefManager: public IWritableItemDefManager struct ClientCached { video::ITexture *inventory_texture; - scene::IMesh *wield_mesh; + ItemMesh wield_mesh; + Palette *palette; ClientCached(): inventory_texture(NULL), - wield_mesh(NULL) + wield_mesh(), + palette(NULL) {} }; #endif @@ -250,8 +260,8 @@ public: i = values.begin(); i != values.end(); ++i) { ClientCached *cc = *i; - if (cc->wield_mesh) - cc->wield_mesh->drop(); + if (cc->wield_mesh.mesh) + cc->wield_mesh.mesh->drop(); delete cc; } @@ -335,8 +345,9 @@ public: ItemStack item = ItemStack(); item.name = def.name; - scene::IMesh *mesh = getItemMesh(client, item); - cc->wield_mesh = mesh; + getItemMesh(client, item, &(cc->wield_mesh)); + + cc->palette = tsrc->getPalette(def.palette_image); // Put in cache m_clientcached.set(name, cc); @@ -390,13 +401,41 @@ public: return cc->inventory_texture; } // Get item wield mesh - virtual scene::IMesh* getWieldMesh(const std::string &name, + virtual ItemMesh* getWieldMesh(const std::string &name, Client *client) const { ClientCached *cc = getClientCached(name, client); if(!cc) return NULL; - return cc->wield_mesh; + return &(cc->wield_mesh); + } + + // Get item palette + virtual Palette* getPalette(const std::string &name, + Client *client) const + { + ClientCached *cc = getClientCached(name, client); + if(!cc) + return NULL; + return cc->palette; + } + + virtual video::SColor getItemstackColor(const ItemStack &stack, + Client *client) const + { + // Look for direct color definition + const std::string &colorstring = stack.metadata.getString("color", 0); + video::SColor directcolor; + if ((colorstring != "") + && parseColorString(colorstring, directcolor, true)) + return directcolor; + // See if there is a palette + Palette *palette = getPalette(stack.name, client); + const std::string &index = stack.metadata.getString("palette_index", 0); + if ((palette != NULL) && (index != "")) + return (*palette)[mystoi(index, 0, 255)]; + // Fallback color + return get(stack.name).color; } #endif void clear() diff --git a/src/itemdef.h b/src/itemdef.h index 01ec4fa2f..2d7ff570d 100644 --- a/src/itemdef.h +++ b/src/itemdef.h @@ -30,6 +30,11 @@ with this program; if not, write to the Free Software Foundation, Inc., class IGameDef; class Client; struct ToolCapabilities; +#ifndef SERVER +#include "client/tile.h" +struct ItemMesh; +struct ItemStack; +#endif /* Base item definition @@ -57,6 +62,8 @@ struct ItemDefinition */ std::string inventory_image; // Optional for nodes, mandatory for tools/craftitems std::string wield_image; // If empty, inventory_image or mesh (only nodes) is used + std::string palette_image; // If specified, the item will be colorized based on this + video::SColor color; // The fallback color of the node. v3f wield_scale; /* @@ -110,8 +117,15 @@ public: virtual video::ITexture* getInventoryTexture(const std::string &name, Client *client) const=0; // Get item wield mesh - virtual scene::IMesh* getWieldMesh(const std::string &name, + virtual ItemMesh* getWieldMesh(const std::string &name, Client *client) const=0; + // Get item palette + virtual Palette* getPalette(const std::string &name, + Client *client) const = 0; + // Returns the base color of an item stack: the color of all + // tiles that do not define their own color. + virtual video::SColor getItemstackColor(const ItemStack &stack, + Client *client) const = 0; #endif virtual void serialize(std::ostream &os, u16 protocol_version)=0; @@ -136,7 +150,7 @@ public: virtual video::ITexture* getInventoryTexture(const std::string &name, Client *client) const=0; // Get item wield mesh - virtual scene::IMesh* getWieldMesh(const std::string &name, + virtual ItemMesh* getWieldMesh(const std::string &name, Client *client) const=0; #endif diff --git a/src/nodedef.cpp b/src/nodedef.cpp index 2745a45e8..558acafd6 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -786,6 +786,8 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc tiledef_special[j].backface_culling, material_type); } + palette = tsrc->getPalette(palette_name); + if ((drawtype == NDT_MESH) && (mesh != "")) { // Meshnode drawtype // Read the mesh and apply scale @@ -859,9 +861,6 @@ public: virtual void removeNode(const std::string &name); virtual void updateAliases(IItemDefManager *idef); virtual void applyTextureOverrides(const std::string &override_filepath); - //! Returns a palette or NULL if not found. Only on client. - std::vector *getPalette(const ContentFeatures &f, - const IGameDef *gamedef); virtual void updateTextures(IGameDef *gamedef, void (*progress_cbk)(void *progress_args, u32 progress, u32 max_progress), void *progress_cbk_args); @@ -910,9 +909,6 @@ private: // Next possibly free id content_t m_next_id; - // Maps image file names to loaded palettes. - UNORDERED_MAP > m_palettes; - // NodeResolvers to callback once node registration has ended std::vector m_pending_resolve_callbacks; @@ -1401,78 +1397,6 @@ void CNodeDefManager::applyTextureOverrides(const std::string &override_filepath } } -std::vector *CNodeDefManager::getPalette( - const ContentFeatures &f, const IGameDef *gamedef) -{ -#ifndef SERVER - // This works because colors always use the most significant bits - // of param2. If you add a new colored type which uses param2 - // in a more advanced way, you should change this code, too. - u32 palette_pixels = 0; - switch (f.param_type_2) { - case CPT2_COLOR: - palette_pixels = 256; - break; - case CPT2_COLORED_FACEDIR: - palette_pixels = 8; - break; - case CPT2_COLORED_WALLMOUNTED: - palette_pixels = 32; - break; - default: - return NULL; - } - // This many param2 values will have the same color - u32 step = 256 / palette_pixels; - const std::string &name = f.palette_name; - if (name == "") - return NULL; - Client *client = (Client *) gamedef; - ITextureSource *tsrc = client->tsrc(); - - UNORDERED_MAP >::iterator it = - m_palettes.find(name); - if (it == m_palettes.end()) { - // Create palette - if (!tsrc->isKnownSourceImage(name)) { - warningstream << "CNodeDefManager::getPalette(): palette \"" << name - << "\" could not be loaded." << std::endl; - return NULL; - } - video::IImage *img = tsrc->generateImage(name); - std::vector new_palette; - u32 w = img->getDimension().Width; - u32 h = img->getDimension().Height; - // Real area of the image - u32 area = h * w; - if (area != palette_pixels) - warningstream << "CNodeDefManager::getPalette(): the " - << "specified palette image \"" << name << "\" does not " - << "contain exactly " << palette_pixels - << " pixels." << std::endl; - if (area > palette_pixels) - area = palette_pixels; - // For each pixel in the image - for (u32 i = 0; i < area; i++) { - video::SColor c = img->getPixel(i % w, i / w); - // Fill in palette with 'step' colors - for (u32 j = 0; j < step; j++) - new_palette.push_back(c); - } - img->drop(); - // Fill in remaining elements - while (new_palette.size() < 256) - new_palette.push_back(video::SColor(0xFFFFFFFF)); - m_palettes[name] = new_palette; - it = m_palettes.find(name); - } - if (it != m_palettes.end()) - return &((*it).second); - -#endif - return NULL; -} - void CNodeDefManager::updateTextures(IGameDef *gamedef, void (*progress_callback)(void *progress_args, u32 progress, u32 max_progress), void *progress_callback_args) @@ -1489,12 +1413,10 @@ void CNodeDefManager::updateTextures(IGameDef *gamedef, TextureSettings tsettings; tsettings.readSettings(); - m_palettes.clear(); u32 size = m_content_features.size(); for (u32 i = 0; i < size; i++) { ContentFeatures *f = &(m_content_features[i]); - f->palette = getPalette(*f, gamedef); f->updateTextures(tsrc, shdsrc, meshmanip, client, tsettings); progress_callback(progress_callback_args, i, size); } diff --git a/src/object_properties.cpp b/src/object_properties.cpp index f4e4953ba..a77368151 100644 --- a/src/object_properties.cpp +++ b/src/object_properties.cpp @@ -117,6 +117,7 @@ void ObjectProperties::serialize(std::ostream &os) const writeARGB8(os, nametag_color); writeF1000(os, automatic_face_movement_max_rotation_per_sec); os << serializeString(infotext); + os << serializeString(wield_item); // Add stuff only at the bottom. // Never remove anything, because we don't want new versions of this @@ -159,6 +160,7 @@ void ObjectProperties::deSerialize(std::istream &is) nametag_color = readARGB8(is); automatic_face_movement_max_rotation_per_sec = readF1000(is); infotext = deSerializeString(is); + wield_item = deSerializeString(is); }catch(SerializationError &e){} } else diff --git a/src/object_properties.h b/src/object_properties.h index 082d9a529..908757a64 100644 --- a/src/object_properties.h +++ b/src/object_properties.h @@ -52,6 +52,8 @@ struct ObjectProperties video::SColor nametag_color; f32 automatic_face_movement_max_rotation_per_sec; std::string infotext; + //! For dropped items, this contains item information. + std::string wield_item; ObjectProperties(); std::string dump(); diff --git a/src/script/common/c_content.cpp b/src/script/common/c_content.cpp index 99e12cd82..bcae874b9 100644 --- a/src/script/common/c_content.cpp +++ b/src/script/common/c_content.cpp @@ -58,6 +58,12 @@ ItemDefinition read_item_definition(lua_State* L,int index, getstringfield(L, index, "description", def.description); getstringfield(L, index, "inventory_image", def.inventory_image); getstringfield(L, index, "wield_image", def.wield_image); + getstringfield(L, index, "palette", def.palette_image); + + // Read item color. + lua_getfield(L, index, "color"); + read_color(L, -1, &def.color); + lua_pop(L, 1); lua_getfield(L, index, "wield_scale"); if(lua_istable(L, -1)){ @@ -118,7 +124,7 @@ ItemDefinition read_item_definition(lua_State* L,int index, /******************************************************************************/ void read_object_properties(lua_State *L, int index, - ObjectProperties *prop) + ObjectProperties *prop, IItemDefManager *idef) { if(index < 0) index = lua_gettop(L) + 1 + index; @@ -216,6 +222,10 @@ void read_object_properties(lua_State *L, int index, } lua_pop(L, 1); getstringfield(L, -1, "infotext", prop->infotext); + lua_getfield(L, -1, "wield_item"); + if (!lua_isnil(L, -1)) + prop->wield_item = read_item(L, -1, idef).getItemString(); + lua_pop(L, 1); } /******************************************************************************/ @@ -284,6 +294,8 @@ void push_object_properties(lua_State *L, ObjectProperties *prop) lua_setfield(L, -2, "automatic_face_movement_max_rotation_per_sec"); lua_pushlstring(L, prop->infotext.c_str(), prop->infotext.size()); lua_setfield(L, -2, "infotext"); + lua_pushlstring(L, prop->wield_item.c_str(), prop->wield_item.size()); + lua_setfield(L, -2, "wield_item"); } /******************************************************************************/ diff --git a/src/script/common/c_content.h b/src/script/common/c_content.h index 10cccbb01..949b136eb 100644 --- a/src/script/common/c_content.h +++ b/src/script/common/c_content.h @@ -89,7 +89,8 @@ void push_tool_capabilities (lua_State *L, ItemDefinition read_item_definition (lua_State *L, int index, ItemDefinition default_def); void read_object_properties (lua_State *L, int index, - ObjectProperties *prop); + ObjectProperties *prop, + IItemDefManager *idef); void push_object_properties (lua_State *L, ObjectProperties *prop); diff --git a/src/script/cpp_api/s_entity.cpp b/src/script/cpp_api/s_entity.cpp index 9e2193970..2e1d277e4 100644 --- a/src/script/cpp_api/s_entity.cpp +++ b/src/script/cpp_api/s_entity.cpp @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "object_properties.h" #include "common/c_converter.h" #include "common/c_content.h" +#include "server.h" bool ScriptApiEntity::luaentity_Add(u16 id, const char *name) { @@ -187,11 +188,11 @@ void ScriptApiEntity::luaentity_GetProperties(u16 id, getstringfield(L, -1, "mesh", prop->mesh); // Deprecated: read object properties directly - read_object_properties(L, -1, prop); + read_object_properties(L, -1, prop, getServer()->idef()); // Read initial_properties lua_getfield(L, -1, "initial_properties"); - read_object_properties(L, -1, prop); + read_object_properties(L, -1, prop, getServer()->idef()); lua_pop(L, 1); } diff --git a/src/script/lua_api/l_itemstackmeta.cpp b/src/script/lua_api/l_itemstackmeta.cpp index efdd77b51..c37a82116 100644 --- a/src/script/lua_api/l_itemstackmeta.cpp +++ b/src/script/lua_api/l_itemstackmeta.cpp @@ -92,6 +92,10 @@ void ItemStackMetaRef::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); + lua_pushliteral(L, "__eq"); + lua_pushcfunction(L, l_equals); + lua_settable(L, metatable); + lua_pop(L, 1); // drop metatable luaL_openlib(L, 0, methods, 0); // fill methodtable @@ -111,5 +115,6 @@ const luaL_Reg ItemStackMetaRef::methods[] = { luamethod(MetaDataRef, set_float), luamethod(MetaDataRef, to_table), luamethod(MetaDataRef, from_table), + luamethod(MetaDataRef, equals), {0,0} }; diff --git a/src/script/lua_api/l_metadata.cpp b/src/script/lua_api/l_metadata.cpp index b54005bac..5f4e984cb 100644 --- a/src/script/lua_api/l_metadata.cpp +++ b/src/script/lua_api/l_metadata.cpp @@ -250,3 +250,17 @@ bool MetaDataRef::handleFromTable(lua_State *L, int table, Metadata *meta) return true; } + +// equals(self, other) +int MetaDataRef::l_equals(lua_State *L) +{ + MetaDataRef *ref1 = checkobject(L, 1); + Metadata *data1 = ref1->getmeta(false); + MetaDataRef *ref2 = checkobject(L, 2); + Metadata *data2 = ref2->getmeta(false); + if (data1 == NULL || data2 == NULL) + lua_pushboolean(L, data1 == data2); + else + lua_pushboolean(L, *data1 == *data2); + return 1; +} diff --git a/src/script/lua_api/l_metadata.h b/src/script/lua_api/l_metadata.h index be31d95ad..a4d8214d3 100644 --- a/src/script/lua_api/l_metadata.h +++ b/src/script/lua_api/l_metadata.h @@ -67,6 +67,9 @@ protected: // from_table(self, table) static int l_from_table(lua_State *L); + + // equals(self, other) + static int l_equals(lua_State *L); }; #endif /* L_NODEMETA_H_ */ diff --git a/src/script/lua_api/l_nodemeta.cpp b/src/script/lua_api/l_nodemeta.cpp index 55d11fc13..c65d56f14 100644 --- a/src/script/lua_api/l_nodemeta.cpp +++ b/src/script/lua_api/l_nodemeta.cpp @@ -204,6 +204,10 @@ void NodeMetaRef::RegisterCommon(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); + lua_pushliteral(L, "__eq"); + lua_pushcfunction(L, l_equals); + lua_settable(L, metatable); + lua_pop(L, 1); // drop metatable } @@ -225,6 +229,7 @@ const luaL_Reg NodeMetaRef::methodsServer[] = { luamethod(MetaDataRef, to_table), luamethod(MetaDataRef, from_table), luamethod(NodeMetaRef, get_inventory), + luamethod(MetaDataRef, equals), {0,0} }; diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index f9d2754e7..0699705cb 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -737,7 +737,7 @@ int ObjectRef::l_set_properties(lua_State *L) ObjectProperties *prop = co->accessObjectProperties(); if (!prop) return 0; - read_object_properties(L, 2, prop); + read_object_properties(L, 2, prop, getServer(L)->idef()); co->notifyObjectPropertiesModified(); return 0; } diff --git a/src/script/lua_api/l_storage.cpp b/src/script/lua_api/l_storage.cpp index 59906dda5..4c6b2a182 100644 --- a/src/script/lua_api/l_storage.cpp +++ b/src/script/lua_api/l_storage.cpp @@ -98,6 +98,10 @@ void StorageRef::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); + lua_pushliteral(L, "__eq"); + lua_pushcfunction(L, l_equals); + lua_settable(L, metatable); + lua_pop(L, 1); // drop metatable luaL_openlib(L, 0, methods, 0); // fill methodtable @@ -138,5 +142,6 @@ const luaL_Reg StorageRef::methods[] = { luamethod(MetaDataRef, set_float), luamethod(MetaDataRef, to_table), luamethod(MetaDataRef, from_table), + luamethod(MetaDataRef, equals), {0,0} }; diff --git a/src/wieldmesh.cpp b/src/wieldmesh.cpp index 089a67f33..40af0be5f 100644 --- a/src/wieldmesh.cpp +++ b/src/wieldmesh.cpp @@ -318,11 +318,15 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client) u32 shader_id = shdrsrc->getShader("wielded_shader", TILE_MATERIAL_BASIC, NDT_NORMAL); m_material_type = shdrsrc->getShaderInfo(shader_id).material; } + + // Color-related m_colors.clear(); + video::SColor basecolor = idef->getItemstackColor(item, client); // If wield_image is defined, it overrides everything else if (def.wield_image != "") { setExtruded(def.wield_image, def.wield_scale, tsrc, 1); + m_colors.push_back(basecolor); return; } // Handle nodes @@ -371,7 +375,7 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client) } else { material.setTexture(0, tile->texture); } - m_colors.push_back(tile->color); + m_colors.push_back(tile->has_color ? tile->color : basecolor); material.MaterialType = m_material_type; if (m_enable_shaders) { if (tile->normal_texture) { @@ -389,6 +393,7 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client) } else if (def.inventory_image != "") { setExtruded(def.inventory_image, def.wield_scale, tsrc, 1); + m_colors.push_back(basecolor); return; } @@ -455,7 +460,7 @@ void WieldMeshSceneNode::changeToMesh(scene::IMesh *mesh) m_meshnode->setVisible(true); } -scene::IMesh *getItemMesh(Client *client, const ItemStack &item) +void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) { ITextureSource *tsrc = client->getTextureSource(); IItemDefManager *idef = client->getItemDefManager(); @@ -475,12 +480,13 @@ scene::IMesh *getItemMesh(Client *client, const ItemStack &item) // If inventory_image is defined, it overrides everything else if (def.inventory_image != "") { mesh = getExtrudedMesh(tsrc, def.inventory_image); - return mesh; + result->mesh = mesh; + result->buffer_colors.push_back( + std::pair(false, video::SColor(0xFFFFFFFF))); } else if (def.type == ITEM_NODE) { if (f.mesh_ptr[0]) { mesh = cloneMesh(f.mesh_ptr[0]); scaleMesh(mesh, v3f(0.12, 0.12, 0.12)); - setMeshColor(mesh, video::SColor (255, 255, 255, 255)); } else if (f.drawtype == NDT_PLANTLIKE) { mesh = getExtrudedMesh(tsrc, tsrc->getTextureName(f.tiles[0].texture_id)); @@ -515,6 +521,8 @@ scene::IMesh *getItemMesh(Client *client, const ItemStack &item) for (u32 i = 0; i < mc; ++i) { const TileSpec *tile = &(f.tiles[i]); scene::IMeshBuffer *buf = mesh->getMeshBuffer(i); + result->buffer_colors.push_back( + std::pair(tile->has_color, tile->color)); colorizeMeshBuffer(buf, &tile->color); video::SMaterial &material = buf->getMaterial(); material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; @@ -532,9 +540,8 @@ scene::IMesh *getItemMesh(Client *client, const ItemStack &item) rotateMeshXZby(mesh, -45); rotateMeshYZby(mesh, -30); - return mesh; + result->mesh = mesh; } - return NULL; } scene::IMesh * getExtrudedMesh(ITextureSource *tsrc, diff --git a/src/wieldmesh.h b/src/wieldmesh.h index 200587058..94edb1de6 100644 --- a/src/wieldmesh.h +++ b/src/wieldmesh.h @@ -28,6 +28,22 @@ class Client; class ITextureSource; struct TileSpec; +struct ItemMesh +{ + scene::IMesh* mesh; + /*! + * Stores the color of each mesh buffer. + * If the boolean is true, the color is fixed, else + * palettes can modify it. + */ + std::vector > buffer_colors; + + ItemMesh(): + mesh(NULL), + buffer_colors() + {} +}; + /* Wield item scene node, renders the wield mesh of some item */ @@ -79,7 +95,7 @@ private: aabb3f m_bounding_box; }; -scene::IMesh *getItemMesh(Client *client, const ItemStack &item); +void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result); scene::IMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename); #endif -- cgit v1.2.3 From 1ffb180868ffcec6812cd3aac8f56ffefb91c8bc Mon Sep 17 00:00:00 2001 From: Dániel Juhász Date: Fri, 21 Apr 2017 15:34:59 +0200 Subject: Soft node overlay (#5186) This commit adds node overlays, which are tiles that are drawn on top of other tiles. --- doc/lua_api.txt | 6 + src/client.cpp | 16 +- src/client/tile.h | 96 +++++--- src/clientmap.cpp | 56 +++-- src/content_mapblock.cpp | 61 ++--- src/content_mapblock.h | 4 +- src/hud.cpp | 5 +- src/mapblock_mesh.cpp | 525 ++++++++++++++++++++++++---------------- src/mapblock_mesh.h | 57 +++-- src/mesh.cpp | 80 +++--- src/mesh.h | 7 +- src/network/networkprotocol.h | 4 +- src/nodedef.cpp | 36 ++- src/nodedef.h | 4 +- src/particles.cpp | 2 +- src/script/common/c_content.cpp | 28 +++ src/wieldmesh.cpp | 188 +++++++------- src/wieldmesh.h | 55 ++++- 18 files changed, 763 insertions(+), 467 deletions(-) (limited to 'src/hud.cpp') diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 16e662e0c..4e328ac76 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -3908,6 +3908,12 @@ Definition tables tiles = {tile definition 1, def2, def3, def4, def5, def6}, --[[ ^ Textures of node; +Y, -Y, +X, -X, +Z, -Z (old field name: tile_images) ^ List can be shortened to needed length ]] + overlay_tiles = {tile definition 1, def2, def3, def4, def5, def6}, --[[ + ^ Same as `tiles`, but these textures are drawn on top of the + ^ base tiles. You can use this to colorize only specific parts of + ^ your texture. If the texture name is an empty string, that + ^ overlay is not drawn. Since such tiles are drawn twice, it + ^ is not recommended to use overlays on very common nodes. special_tiles = {tile definition 1, Tile definition 2}, --[[ ^ Special textures of node; used rarely (old field name: special_materials) ^ List can be shortened to needed length ]] diff --git a/src/client.cpp b/src/client.cpp index 3cea4fbf4..ce42d025e 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -487,13 +487,17 @@ void Client::step(float dtime) minimap_mapblock = r.mesh->moveMinimapMapblock(); if (minimap_mapblock == NULL) do_mapper_update = false; - } - if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) { - delete r.mesh; - } else { - // Replace with the new mesh - block->mesh = r.mesh; + bool is_empty = true; + for (int l = 0; l < MAX_TILE_LAYERS; l++) + if (r.mesh->getMesh(l)->getMeshBufferCount() != 0) + is_empty = false; + + if (is_empty) + delete r.mesh; + else + // Replace with the new mesh + block->mesh = r.mesh; } } else { delete r.mesh; diff --git a/src/client/tile.h b/src/client/tile.h index ef01d2a1f..c6ebee006 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -194,19 +194,22 @@ struct FrameSpec video::ITexture *flags_texture; }; -struct TileSpec +#define MAX_TILE_LAYERS 2 + +//! Defines a layer of a tile. +struct TileLayer { - TileSpec(): + TileLayer(): texture(NULL), texture_id(0), color(), material_type(TILE_MATERIAL_BASIC), material_flags( //0 // <- DEBUG, Use the one below - MATERIAL_FLAG_BACKFACE_CULLING + MATERIAL_FLAG_BACKFACE_CULLING | + MATERIAL_FLAG_TILEABLE_HORIZONTAL| + MATERIAL_FLAG_TILEABLE_VERTICAL ), - rotation(0), - emissive_light(0), shader_id(0), normal_texture(NULL), flags_texture(NULL), @@ -217,49 +220,41 @@ struct TileSpec } /*! - * Two tiles are equal if they can be appended to - * the same mesh buffer. + * Two layers are equal if they can be merged. */ - bool operator==(const TileSpec &other) const + bool operator==(const TileLayer &other) const { - return ( + return texture_id == other.texture_id && material_type == other.material_type && material_flags == other.material_flags && - rotation == other.rotation - ); + color == other.color; } /*! - * Two tiles are not equal if they must be in different mesh buffers. + * Two tiles are not equal if they must have different vertices. */ - bool operator!=(const TileSpec &other) const + bool operator!=(const TileLayer &other) const { return !(*this == other); } - + // Sets everything else except the texture in the material void applyMaterialOptions(video::SMaterial &material) const { switch (material_type) { case TILE_MATERIAL_BASIC: + case TILE_MATERIAL_WAVING_LEAVES: + case TILE_MATERIAL_WAVING_PLANTS: material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; break; case TILE_MATERIAL_ALPHA: - material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; - break; case TILE_MATERIAL_LIQUID_TRANSPARENT: material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; break; case TILE_MATERIAL_LIQUID_OPAQUE: material.MaterialType = video::EMT_SOLID; break; - case TILE_MATERIAL_WAVING_LEAVES: - material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; - break; - case TILE_MATERIAL_WAVING_PLANTS: - material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; - break; } material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) ? true : false; @@ -285,26 +280,26 @@ struct TileSpec } } - // ordered for performance! please do not reorder unless you pahole it first. + bool isTileable() const + { + return (material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL) + && (material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL); + } + video::ITexture *texture; u32 texture_id; - // The color of the tile, or if the tile does not own - // a color then the color of the node owning this tile. + /*! + * The color of the tile, or if the tile does not own + * a color then the color of the node owning this tile. + */ video::SColor color; // Material parameters u8 material_type; u8 material_flags; - - u8 rotation; - //! This much light does the tile emit. - u8 emissive_light; - u32 shader_id; - video::ITexture *normal_texture; - // cacheline (64) - video::ITexture *flags_texture; + // Animation parameters u16 animation_frame_length_ms; u8 animation_frame_count; @@ -313,4 +308,39 @@ struct TileSpec std::vector frames; }; + +/*! + * Defines a face of a node. May have up to two layers. + */ +struct TileSpec +{ + TileSpec(): + rotation(0), + emissive_light(0) + { + for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) + layers[layer] = TileLayer(); + } + + /*! + * Returns true if this tile can be merged with the other tile. + */ + bool isTileable(const TileSpec &other) const { + for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { + if (layers[layer] != other.layers[layer]) + return false; + if (!layers[layer].isTileable()) + return false; + } + return rotation == 0 + && rotation == other.rotation + && emissive_light == other.emissive_light; + } + + u8 rotation; + //! This much light does the tile emit. + u8 emissive_light; + //! The first is base texture, the second is overlay. + TileLayer layers[MAX_TILE_LAYERS]; +}; #endif diff --git a/src/clientmap.cpp b/src/clientmap.cpp index 4cae03bf2..6cd24ffc6 100644 --- a/src/clientmap.cpp +++ b/src/clientmap.cpp @@ -290,6 +290,11 @@ void ClientMap::updateDrawList(video::IVideoDriver* driver) struct MeshBufList { + /*! + * Specifies in which layer the list is. + * All lists which are in a lower layer are rendered before this list. + */ + u8 layer; video::SMaterial m; std::vector bufs; }; @@ -303,7 +308,7 @@ struct MeshBufListList lists.clear(); } - void add(scene::IMeshBuffer *buf) + void add(scene::IMeshBuffer *buf, u8 layer) { const video::SMaterial &m = buf->getMaterial(); for(std::vector::iterator i = lists.begin(); @@ -315,12 +320,16 @@ struct MeshBufListList if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture) continue; + if(l.layer != layer) + continue; + if (l.m == m) { l.bufs.push_back(buf); return; } } MeshBufList l; + l.layer = layer; l.m = m; l.bufs.push_back(buf); lists.push_back(l); @@ -434,29 +443,34 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) MapBlockMesh *mapBlockMesh = block->mesh; assert(mapBlockMesh); - scene::IMesh *mesh = mapBlockMesh->getMesh(); - assert(mesh); + for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { + scene::IMesh *mesh = mapBlockMesh->getMesh(layer); + assert(mesh); - u32 c = mesh->getMeshBufferCount(); - for (u32 i = 0; i < c; i++) - { - scene::IMeshBuffer *buf = mesh->getMeshBuffer(i); + u32 c = mesh->getMeshBufferCount(); + for (u32 i = 0; i < c; i++) { + scene::IMeshBuffer *buf = mesh->getMeshBuffer(i); - video::SMaterial& material = buf->getMaterial(); - video::IMaterialRenderer* rnd = + video::SMaterial& material = buf->getMaterial(); + video::IMaterialRenderer* rnd = driver->getMaterialRenderer(material.MaterialType); - bool transparent = (rnd && rnd->isTransparent()); - if (transparent == is_transparent_pass) { - if (buf->getVertexCount() == 0) - errorstream << "Block [" << analyze_block(block) - << "] contains an empty meshbuf" << std::endl; - - material.setFlag(video::EMF_TRILINEAR_FILTER, m_cache_trilinear_filter); - material.setFlag(video::EMF_BILINEAR_FILTER, m_cache_bilinear_filter); - material.setFlag(video::EMF_ANISOTROPIC_FILTER, m_cache_anistropic_filter); - material.setFlag(video::EMF_WIREFRAME, m_control.show_wireframe); - - drawbufs.add(buf); + bool transparent = (rnd && rnd->isTransparent()); + if (transparent == is_transparent_pass) { + if (buf->getVertexCount() == 0) + errorstream << "Block [" << analyze_block(block) + << "] contains an empty meshbuf" << std::endl; + + material.setFlag(video::EMF_TRILINEAR_FILTER, + m_cache_trilinear_filter); + material.setFlag(video::EMF_BILINEAR_FILTER, + m_cache_bilinear_filter); + material.setFlag(video::EMF_ANISOTROPIC_FILTER, + m_cache_anistropic_filter); + material.setFlag(video::EMF_WIREFRAME, + m_control.show_wireframe); + + drawbufs.add(buf, layer); + } } } } diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 153dacf42..9f4223bac 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -78,17 +78,19 @@ void MapblockMeshGenerator::useTile(int index, bool disable_backface_culling) { tile = getNodeTileN(n, p, index, data); if (!data->m_smooth_lighting) - color = encode_light_and_color(light, tile.color, f->light_source); - if (disable_backface_culling) - tile.material_flags &= ~MATERIAL_FLAG_BACKFACE_CULLING; - tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; + color = encode_light(light, f->light_source); + for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { + tile.layers[layer].material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; + if (disable_backface_culling) + tile.layers[layer].material_flags &= ~MATERIAL_FLAG_BACKFACE_CULLING; + } } void MapblockMeshGenerator::useDefaultTile(bool set_color) { tile = getNodeTile(n, p, v3s16(0, 0, 0), data); if (set_color && !data->m_smooth_lighting) - color = encode_light_and_color(light, tile.color, f->light_source); + color = encode_light(light, f->light_source); } TileSpec MapblockMeshGenerator::getTile(const v3s16& direction) @@ -106,7 +108,7 @@ void MapblockMeshGenerator::drawQuad(v3f *coords, const v3s16 &normal) vertices[j].Pos = coords[j] + origin; vertices[j].Normal = normal2; if (data->m_smooth_lighting) - vertices[j].Color = blendLight(coords[j], tile.color); + vertices[j].Color = blendLight(coords[j]); else vertices[j].Color = color; if (shade_face) @@ -137,8 +139,7 @@ void MapblockMeshGenerator::drawCuboid(const aabb3f &box, video::SColor colors[6]; if (!data->m_smooth_lighting) { for (int face = 0; face != 6; ++face) { - int tileindex = MYMIN(face, tilecount - 1); - colors[face] = encode_light_and_color(light, tiles[tileindex].color, f->light_source); + colors[face] = encode_light(light, f->light_source); } if (!f->light_source) { applyFacesShading(colors[0], v3f(0, 1, 0)); @@ -240,9 +241,8 @@ void MapblockMeshGenerator::drawCuboid(const aabb3f &box, if (data->m_smooth_lighting) { for (int j = 0; j < 24; ++j) { - int tileindex = MYMIN(j / 4, tilecount - 1); - vertices[j].Color = encode_light_and_color(lights[light_indices[j]], - tiles[tileindex].color, f->light_source); + vertices[j].Color = encode_light(lights[light_indices[j]], + f->light_source); if (!f->light_source) applyFacesShading(vertices[j].Color, vertices[j].Normal); } @@ -289,17 +289,16 @@ u16 MapblockMeshGenerator::blendLight(const v3f &vertex_pos) // Calculates vertex color to be used in mapblock mesh // vertex_pos - vertex position in the node (coordinates are clamped to [0.0, 1.0] or so) // tile_color - node's tile color -video::SColor MapblockMeshGenerator::blendLight(const v3f &vertex_pos, - video::SColor tile_color) +video::SColor MapblockMeshGenerator::blendLightColor(const v3f &vertex_pos) { u16 light = blendLight(vertex_pos); - return encode_light_and_color(light, tile_color, f->light_source); + return encode_light(light, f->light_source); } -video::SColor MapblockMeshGenerator::blendLight(const v3f &vertex_pos, - const v3f &vertex_normal, video::SColor tile_color) +video::SColor MapblockMeshGenerator::blendLightColor(const v3f &vertex_pos, + const v3f &vertex_normal) { - video::SColor color = blendLight(vertex_pos, tile_color); + video::SColor color = blendLight(vertex_pos); if (!f->light_source) applyFacesShading(color, vertex_normal); return color; @@ -367,8 +366,13 @@ static TileSpec getSpecialTile(const ContentFeatures &f, const MapNode &n, u8 i) { TileSpec copy = f.special_tiles[i]; - if (!copy.has_color) - n.getColor(f, ©.color); + for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) { + TileLayer *layer = ©.layers[layernum]; + if (layer->texture_id == 0) + continue; + if (!layer->has_color) + n.getColor(f, &(layer->color)); + } return copy; } @@ -395,8 +399,8 @@ void MapblockMeshGenerator::prepareLiquidNodeDrawing(bool flowing) light = getInteriorLight(ntop, 0, nodedef); } - color_liquid_top = encode_light_and_color(light, tile_liquid_top.color, f->light_source); - color = encode_light_and_color(light, tile_liquid.color, f->light_source); + color_liquid_top = encode_light(light, f->light_source); + color = encode_light(light, f->light_source); } void MapblockMeshGenerator::getLiquidNeighborhood(bool flowing) @@ -547,7 +551,7 @@ void MapblockMeshGenerator::drawLiquidSides(bool flowing) else pos.Y = !top_is_same_liquid ? corner_levels[base.Z][base.X] : 0.5 * BS; if (data->m_smooth_lighting) - color = blendLight(pos, tile_liquid.color); + color = blendLightColor(pos); pos += origin; vertices[j] = video::S3DVertex(pos.X, pos.Y, pos.Z, 0, 0, 0, color, vertex.u, vertex.v); }; @@ -574,7 +578,7 @@ void MapblockMeshGenerator::drawLiquidTop(bool flowing) int w = corner_resolve[i][1]; vertices[i].Pos.Y += corner_levels[w][u]; if (data->m_smooth_lighting) - vertices[i].Color = blendLight(vertices[i].Pos, tile_liquid_top.color); + vertices[i].Color = blendLightColor(vertices[i].Pos); vertices[i].Pos += origin; } @@ -659,7 +663,9 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode() tiles[face] = getTile(g_6dirs[face]); TileSpec glass_tiles[6]; - if (tiles[0].texture && tiles[3].texture && tiles[4].texture) { + if (tiles[1].layers[0].texture && + tiles[2].layers[0].texture && + tiles[3].layers[0].texture) { glass_tiles[0] = tiles[4]; glass_tiles[1] = tiles[0]; glass_tiles[2] = tiles[4]; @@ -763,7 +769,7 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode() // Optionally render internal liquid level defined by param2 // Liquid is textured with 1 tile defined in nodedef 'special_tiles' if (param2 > 0 && f->param_type_2 == CPT2_GLASSLIKE_LIQUID_LEVEL && - f->special_tiles[0].texture) { + f->special_tiles[0].layers[0].texture) { // Internal liquid level has param2 range 0 .. 63, // convert it to -0.5 .. 0.5 float vlev = (param2 / 63.0) * 2.0 - 1.0; @@ -998,7 +1004,8 @@ void MapblockMeshGenerator::drawFencelikeNode() { useDefaultTile(false); TileSpec tile_nocrack = tile; - tile_nocrack.material_flags &= ~MATERIAL_FLAG_CRACK; + for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) + tile_nocrack.layers[layer].material_flags &= ~MATERIAL_FLAG_CRACK; // Put wood the right way around in the posts TileSpec tile_rot = tile; @@ -1253,7 +1260,7 @@ void MapblockMeshGenerator::drawMeshNode() // vertex right here. for (int k = 0; k < vertex_count; k++) { video::S3DVertex &vertex = vertices[k]; - vertex.Color = blendLight(vertex.Pos, vertex.Normal, tile.color); + vertex.Color = blendLightColor(vertex.Pos, vertex.Normal); vertex.Pos += origin; } collector->append(tile, vertices, vertex_count, diff --git a/src/content_mapblock.h b/src/content_mapblock.h index c8425024f..6866a4498 100644 --- a/src/content_mapblock.h +++ b/src/content_mapblock.h @@ -60,8 +60,8 @@ public: // lighting void getSmoothLightFrame(); u16 blendLight(const v3f &vertex_pos); - video::SColor blendLight(const v3f &vertex_pos, video::SColor tile_color); - video::SColor blendLight(const v3f &vertex_pos, const v3f &vertex_normal, video::SColor tile_color); + video::SColor blendLightColor(const v3f &vertex_pos); + video::SColor blendLightColor(const v3f &vertex_pos, const v3f &vertex_normal); void useTile(int index, bool disable_backface_culling); void useDefaultTile(bool set_color = true); diff --git a/src/hud.cpp b/src/hud.cpp index f558acf1e..c482912e9 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -687,8 +687,9 @@ void drawItemStack(video::IVideoDriver *driver, assert(buf->getHardwareMappingHint_Vertex() == scene::EHM_NEVER); video::SColor c = basecolor; if (imesh->buffer_colors.size() > j) { - std::pair p = imesh->buffer_colors[j]; - c = p.first ? p.second : basecolor; + ItemPartColor *p = &imesh->buffer_colors[j]; + if (p->override_base) + c = p->color; } colorizeMeshBuffer(buf, &c); video::SMaterial &material = buf->getMaterial(); diff --git a/src/mapblock_mesh.cpp b/src/mapblock_mesh.cpp index 933dfc32a..0bba644e6 100644 --- a/src/mapblock_mesh.cpp +++ b/src/mapblock_mesh.cpp @@ -323,7 +323,7 @@ void final_color_blend(video::SColor *result, video::SColorf dayLight; get_sunlight_color(&dayLight, daynight_ratio); final_color_blend(result, - encode_light_and_color(light, video::SColor(0xFFFFFFFF), 0), dayLight); + encode_light(light, 0), dayLight); } void final_color_blend(video::SColor *result, @@ -422,12 +422,19 @@ static void getNodeVertexDirs(v3s16 dir, v3s16 *vertex_dirs) struct FastFace { - TileSpec tile; + TileLayer layer; video::S3DVertex vertices[4]; // Precalculated vertices + /*! + * The face is divided into two triangles. If this is true, + * vertices 0 and 2 are connected, othervise vertices 1 and 3 + * are connected. + */ + bool vertex_0_2_connected; + u8 layernum; }; static void makeFastFace(TileSpec tile, u16 li0, u16 li1, u16 li2, u16 li3, - v3f p, v3s16 dir, v3f scale, std::vector &dest) + v3f p, v3s16 dir, v3f scale, std::vector &dest) { // Position is at the center of the cube. v3f pos = p * BS; @@ -577,27 +584,50 @@ static void makeFastFace(TileSpec tile, u16 li0, u16 li1, u16 li2, u16 li3, v3f normal(dir.X, dir.Y, dir.Z); - dest.push_back(FastFace()); + u16 li[4] = { li0, li1, li2, li3 }; + u16 day[4]; + u16 night[4]; - FastFace& face = *dest.rbegin(); + for (u8 i = 0; i < 4; i++) { + day[i] = li[i] >> 8; + night[i] = li[i] & 0xFF; + } + + bool vertex_0_2_connected = abs(day[0] - day[2]) + abs(night[0] - night[2]) + < abs(day[1] - day[3]) + abs(night[1] - night[3]); - u16 li[4] = { li0, li1, li2, li3 }; v2f32 f[4] = { core::vector2d(x0 + w * abs_scale, y0 + h), core::vector2d(x0, y0 + h), core::vector2d(x0, y0), core::vector2d(x0 + w * abs_scale, y0) }; - for (u8 i = 0; i < 4; i++) { - video::SColor c = encode_light_and_color(li[i], tile.color, - tile.emissive_light); - if (!tile.emissive_light) - applyFacesShading(c, normal); + for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) { + TileLayer *layer = &tile.layers[layernum]; + if (layer->texture_id == 0) + continue; - face.vertices[i] = video::S3DVertex(vertex_pos[i], normal, c, f[i]); - } + dest.push_back(FastFace()); + FastFace& face = *dest.rbegin(); + + for (u8 i = 0; i < 4; i++) { + video::SColor c = encode_light(li[i], tile.emissive_light); + if (!tile.emissive_light) + applyFacesShading(c, normal); - face.tile = tile; + face.vertices[i] = video::S3DVertex(vertex_pos[i], normal, c, f[i]); + } + + /* + Revert triangles for nicer looking gradient if the + brightness of vertices 1 and 3 differ less than + the brightness of vertices 0 and 2. + */ + face.vertex_0_2_connected = vertex_0_2_connected; + + face.layer = *layer; + face.layernum = layernum; + } } /* @@ -663,13 +693,20 @@ TileSpec getNodeTileN(MapNode mn, v3s16 p, u8 tileindex, MeshMakeData *data) { INodeDefManager *ndef = data->m_client->ndef(); const ContentFeatures &f = ndef->get(mn); - TileSpec spec = f.tiles[tileindex]; - if (!spec.has_color) - mn.getColor(f, &spec.color); + TileSpec tile = f.tiles[tileindex]; + TileLayer *top_layer = NULL; + for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) { + TileLayer *layer = &tile.layers[layernum]; + if (layer->texture_id == 0) + continue; + top_layer = layer; + if (!layer->has_color) + mn.getColor(f, &(layer->color)); + } // Apply temporary crack if (p == data->m_crack_pos_relative) - spec.material_flags |= MATERIAL_FLAG_CRACK; - return spec; + top_layer->material_flags |= MATERIAL_FLAG_CRACK; + return tile; } /* @@ -732,10 +769,9 @@ TileSpec getNodeTile(MapNode mn, v3s16 p, v3s16 dir, MeshMakeData *data) }; u16 tile_index=facedir*16 + dir_i; - TileSpec spec = getNodeTileN(mn, p, dir_to_tile[tile_index], data); - spec.rotation=dir_to_tile[tile_index + 1]; - spec.texture = data->m_client->tsrc()->getTexture(spec.texture_id); - return spec; + TileSpec tile = getNodeTileN(mn, p, dir_to_tile[tile_index], data); + tile.rotation = dir_to_tile[tile_index + 1]; + return tile; } static void getTileInfo( @@ -800,7 +836,9 @@ static void getTileInfo( // eg. water and glass if (equivalent) - tile.material_flags |= MATERIAL_FLAG_BACKFACE_CULLING; + for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) + tile.layers[layernum].material_flags |= + MATERIAL_FLAG_BACKFACE_CULLING; if (data->m_smooth_lighting == false) { @@ -880,12 +918,7 @@ static void updateFastFaceRow( && next_lights[1] == lights[1] && next_lights[2] == lights[2] && next_lights[3] == lights[3] - && next_tile == tile - && tile.rotation == 0 - && (tile.material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL) - && (tile.material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL) - && tile.color == next_tile.color - && tile.emissive_light == next_tile.emissive_light) { + && next_tile.isTileable(tile)) { next_is_different = false; continuous_tiles_count++; } @@ -988,7 +1021,6 @@ static void updateAllFastFaceRows(MeshMakeData *data, */ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): - m_mesh(new scene::SMesh()), m_minimap_mapblock(NULL), m_client(data->m_client), m_driver(m_client->tsrc()->getDevice()->getVideoDriver()), @@ -1000,6 +1032,8 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): m_last_daynight_ratio((u32) -1), m_daynight_diffs() { + for (int m = 0; m < MAX_TILE_LAYERS; m++) + m_mesh[m] = new scene::SMesh(); m_enable_shaders = data->m_use_shaders; m_use_tangent_vertices = data->m_use_tangent_vertices; m_enable_vbo = g_settings->getBool("enable_vbo"); @@ -1048,23 +1082,14 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): const u16 indices[] = {0,1,2,2,3,0}; const u16 indices_alternate[] = {0,1,3,2,3,1}; - if(f.tile.texture == NULL) + if (f.layer.texture == NULL) continue; - const u16 *indices_p = indices; + const u16 *indices_p = + f.vertex_0_2_connected ? indices : indices_alternate; - /* - Revert triangles for nicer looking gradient if the - brightness of vertices 1 and 3 differ less than - the brightness of vertices 0 and 2. - */ - if (fabs(f.vertices[0].Color.getLuminance() - - f.vertices[2].Color.getLuminance()) - > fabs(f.vertices[1].Color.getLuminance() - - f.vertices[3].Color.getLuminance())) - indices_p = indices_alternate; - - collector.append(f.tile, f.vertices, 4, indices_p, 6); + collector.append(f.layer, f.vertices, 4, indices_p, 6, + f.layernum); } } @@ -1081,146 +1106,151 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): generator.generate(); } + collector.applyTileColors(); + /* Convert MeshCollector to SMesh */ - for(u32 i = 0; i < collector.prebuffers.size(); i++) - { - PreMeshBuffer &p = collector.prebuffers[i]; - - // Generate animation data - // - Cracks - if(p.tile.material_flags & MATERIAL_FLAG_CRACK) + for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { + for(u32 i = 0; i < collector.prebuffers[layer].size(); i++) { - // Find the texture name plus ^[crack:N: - std::ostringstream os(std::ios::binary); - os<getTextureName(p.tile.texture_id)<<"^[crack"; - if(p.tile.material_flags & MATERIAL_FLAG_CRACK_OVERLAY) - os<<"o"; // use ^[cracko - os<<":"<<(u32)p.tile.animation_frame_count<<":"; - m_crack_materials.insert(std::make_pair(i, os.str())); - // Replace tile texture with the cracked one - p.tile.texture = m_tsrc->getTextureForMesh( - os.str()+"0", - &p.tile.texture_id); - } - // - Texture animation - if (p.tile.material_flags & MATERIAL_FLAG_ANIMATION) { - // Add to MapBlockMesh in order to animate these tiles - m_animation_tiles[i] = p.tile; - m_animation_frames[i] = 0; - if(g_settings->getBool("desynchronize_mapblock_texture_animation")){ - // Get starting position from noise - m_animation_frame_offsets[i] = 100000 * (2.0 + noise3d( - data->m_blockpos.X, data->m_blockpos.Y, - data->m_blockpos.Z, 0)); - } else { - // Play all synchronized - m_animation_frame_offsets[i] = 0; - } - // Replace tile texture with the first animation frame - FrameSpec animation_frame = p.tile.frames[0]; - p.tile.texture = animation_frame.texture; - } + PreMeshBuffer &p = collector.prebuffers[layer][i]; - if (!m_enable_shaders) { - // Extract colors for day-night animation - // Dummy sunlight to handle non-sunlit areas - video::SColorf sunlight; - get_sunlight_color(&sunlight, 0); - u32 vertex_count = - m_use_tangent_vertices ? - p.tangent_vertices.size() : p.vertices.size(); - for (u32 j = 0; j < vertex_count; j++) { - video::SColor *vc; - if (m_use_tangent_vertices) { - vc = &p.tangent_vertices[j].Color; + // Generate animation data + // - Cracks + if(p.layer.material_flags & MATERIAL_FLAG_CRACK) + { + // Find the texture name plus ^[crack:N: + std::ostringstream os(std::ios::binary); + os<getTextureName(p.layer.texture_id)<<"^[crack"; + if(p.layer.material_flags & MATERIAL_FLAG_CRACK_OVERLAY) + os<<"o"; // use ^[cracko + os<<":"<<(u32)p.layer.animation_frame_count<<":"; + m_crack_materials.insert(std::make_pair(std::pair(layer, i), os.str())); + // Replace tile texture with the cracked one + p.layer.texture = m_tsrc->getTextureForMesh( + os.str()+"0", + &p.layer.texture_id); + } + // - Texture animation + if (p.layer.material_flags & MATERIAL_FLAG_ANIMATION) { + // Add to MapBlockMesh in order to animate these tiles + m_animation_tiles[std::pair(layer, i)] = p.layer; + m_animation_frames[std::pair(layer, i)] = 0; + if(g_settings->getBool("desynchronize_mapblock_texture_animation")){ + // Get starting position from noise + m_animation_frame_offsets[std::pair(layer, i)] = 100000 * (2.0 + noise3d( + data->m_blockpos.X, data->m_blockpos.Y, + data->m_blockpos.Z, 0)); } else { - vc = &p.vertices[j].Color; + // Play all synchronized + m_animation_frame_offsets[std::pair(layer, i)] = 0; } - video::SColor copy(*vc); - if (vc->getAlpha() == 0) // No sunlight - no need to animate - final_color_blend(vc, copy, sunlight); // Finalize color - else // Record color to animate - m_daynight_diffs[i][j] = copy; - - // The sunlight ratio has been stored, - // delete alpha (for the final rendering). - vc->setAlpha(255); + // Replace tile texture with the first animation frame + FrameSpec animation_frame = p.layer.frames[0]; + p.layer.texture = animation_frame.texture; } - } - // Create material - video::SMaterial material; - material.setFlag(video::EMF_LIGHTING, false); - material.setFlag(video::EMF_BACK_FACE_CULLING, true); - material.setFlag(video::EMF_BILINEAR_FILTER, false); - material.setFlag(video::EMF_FOG_ENABLE, true); - material.setTexture(0, p.tile.texture); + if (!m_enable_shaders) { + // Extract colors for day-night animation + // Dummy sunlight to handle non-sunlit areas + video::SColorf sunlight; + get_sunlight_color(&sunlight, 0); + u32 vertex_count = + m_use_tangent_vertices ? + p.tangent_vertices.size() : p.vertices.size(); + for (u32 j = 0; j < vertex_count; j++) { + video::SColor *vc; + if (m_use_tangent_vertices) { + vc = &p.tangent_vertices[j].Color; + } else { + vc = &p.vertices[j].Color; + } + video::SColor copy(*vc); + if (vc->getAlpha() == 0) // No sunlight - no need to animate + final_color_blend(vc, copy, sunlight); // Finalize color + else // Record color to animate + m_daynight_diffs[std::pair(layer, i)][j] = copy; + + // The sunlight ratio has been stored, + // delete alpha (for the final rendering). + vc->setAlpha(255); + } + } - if (m_enable_shaders) { - material.MaterialType = m_shdrsrc->getShaderInfo(p.tile.shader_id).material; - p.tile.applyMaterialOptionsWithShaders(material); - if (p.tile.normal_texture) { - material.setTexture(1, p.tile.normal_texture); + // Create material + video::SMaterial material; + material.setFlag(video::EMF_LIGHTING, false); + material.setFlag(video::EMF_BACK_FACE_CULLING, true); + material.setFlag(video::EMF_BILINEAR_FILTER, false); + material.setFlag(video::EMF_FOG_ENABLE, true); + material.setTexture(0, p.layer.texture); + + if (m_enable_shaders) { + material.MaterialType = m_shdrsrc->getShaderInfo(p.layer.shader_id).material; + p.layer.applyMaterialOptionsWithShaders(material); + if (p.layer.normal_texture) { + material.setTexture(1, p.layer.normal_texture); + } + material.setTexture(2, p.layer.flags_texture); + } else { + p.layer.applyMaterialOptions(material); + } + + scene::SMesh *mesh = (scene::SMesh *)m_mesh[layer]; + + // Create meshbuffer, add to mesh + if (m_use_tangent_vertices) { + scene::SMeshBufferTangents *buf = new scene::SMeshBufferTangents(); + // Set material + buf->Material = material; + // Add to mesh + mesh->addMeshBuffer(buf); + // Mesh grabbed it + buf->drop(); + buf->append(&p.tangent_vertices[0], p.tangent_vertices.size(), + &p.indices[0], p.indices.size()); + } else { + scene::SMeshBuffer *buf = new scene::SMeshBuffer(); + // Set material + buf->Material = material; + // Add to mesh + mesh->addMeshBuffer(buf); + // Mesh grabbed it + buf->drop(); + buf->append(&p.vertices[0], p.vertices.size(), + &p.indices[0], p.indices.size()); } - material.setTexture(2, p.tile.flags_texture); - } else { - p.tile.applyMaterialOptions(material); } - scene::SMesh *mesh = (scene::SMesh *)m_mesh; - // Create meshbuffer, add to mesh + /* + Do some stuff to the mesh + */ + m_camera_offset = camera_offset; + translateMesh(m_mesh[layer], + intToFloat(data->m_blockpos * MAP_BLOCKSIZE - camera_offset, BS)); + if (m_use_tangent_vertices) { - scene::SMeshBufferTangents *buf = new scene::SMeshBufferTangents(); - // Set material - buf->Material = material; - // Add to mesh - mesh->addMeshBuffer(buf); - // Mesh grabbed it - buf->drop(); - buf->append(&p.tangent_vertices[0], p.tangent_vertices.size(), - &p.indices[0], p.indices.size()); - } else { - scene::SMeshBuffer *buf = new scene::SMeshBuffer(); - // Set material - buf->Material = material; - // Add to mesh - mesh->addMeshBuffer(buf); - // Mesh grabbed it - buf->drop(); - buf->append(&p.vertices[0], p.vertices.size(), - &p.indices[0], p.indices.size()); + scene::IMeshManipulator* meshmanip = + m_client->getSceneManager()->getMeshManipulator(); + meshmanip->recalculateTangents(m_mesh[layer], true, false, false); } - } - - /* - Do some stuff to the mesh - */ - m_camera_offset = camera_offset; - translateMesh(m_mesh, - intToFloat(data->m_blockpos * MAP_BLOCKSIZE - camera_offset, BS)); - if (m_use_tangent_vertices) { - scene::IMeshManipulator* meshmanip = - m_client->getSceneManager()->getMeshManipulator(); - meshmanip->recalculateTangents(m_mesh, true, false, false); - } - - if (m_mesh) - { + if (m_mesh[layer]) + { #if 0 - // Usually 1-700 faces and 1-7 materials - std::cout<<"Updated MapBlock has "<getMeshBufferCount() - <<" materials (meshbuffers)"<getMeshBufferCount() + <<" materials (meshbuffers)"<setHardwareMappingHint(scene::EHM_STATIC); + // Use VBO for mesh (this just would set this for ever buffer) + if (m_enable_vbo) { + m_mesh[layer]->setHardwareMappingHint(scene::EHM_STATIC); + } } } @@ -1235,14 +1265,15 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): MapBlockMesh::~MapBlockMesh() { - if (m_enable_vbo && m_mesh) { - for (u32 i = 0; i < m_mesh->getMeshBufferCount(); i++) { - scene::IMeshBuffer *buf = m_mesh->getMeshBuffer(i); - m_driver->removeHardwareBuffer(buf); - } + for (int m = 0; m < MAX_TILE_LAYERS; m++) { + if (m_enable_vbo && m_mesh[m]) + for (u32 i = 0; i < m_mesh[m]->getMeshBufferCount(); i++) { + scene::IMeshBuffer *buf = m_mesh[m]->getMeshBuffer(i); + m_driver->removeHardwareBuffer(buf); + } + m_mesh[m]->drop(); + m_mesh[m] = NULL; } - m_mesh->drop(); - m_mesh = NULL; delete m_minimap_mapblock; } @@ -1259,9 +1290,10 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat // Cracks if(crack != m_last_crack) { - for (UNORDERED_MAP::iterator i = m_crack_materials.begin(); - i != m_crack_materials.end(); ++i) { - scene::IMeshBuffer *buf = m_mesh->getMeshBuffer(i->first); + for (std::map, std::string>::iterator i = + m_crack_materials.begin(); i != m_crack_materials.end(); ++i) { + scene::IMeshBuffer *buf = m_mesh[i->first.first]-> + getMeshBuffer(i->first.second); std::string basename = i->second; // Create new texture name from original @@ -1274,10 +1306,10 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat // If the current material is also animated, // update animation info - UNORDERED_MAP::iterator anim_iter = - m_animation_tiles.find(i->first); + std::map, TileLayer>::iterator anim_iter = + m_animation_tiles.find(i->first); if (anim_iter != m_animation_tiles.end()){ - TileSpec &tile = anim_iter->second; + TileLayer &tile = anim_iter->second; tile.texture = new_texture; tile.texture_id = new_texture_id; // force animation update @@ -1289,9 +1321,9 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat } // Texture animation - for (UNORDERED_MAP::iterator i = m_animation_tiles.begin(); - i != m_animation_tiles.end(); ++i) { - const TileSpec &tile = i->second; + for (std::map, TileLayer>::iterator i = + m_animation_tiles.begin(); i != m_animation_tiles.end(); ++i) { + const TileLayer &tile = i->second; // Figure out current frame int frameoffset = m_animation_frame_offsets[i->first]; int frame = (int)(time * 1000 / tile.animation_frame_length_ms @@ -1302,7 +1334,8 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat m_animation_frames[i->first] = frame; - scene::IMeshBuffer *buf = m_mesh->getMeshBuffer(i->first); + scene::IMeshBuffer *buf = m_mesh[i->first.first]-> + getMeshBuffer(i->first.second); FrameSpec animation_frame = tile.frames[frame]; buf->getMaterial().setTexture(0, animation_frame.texture); @@ -1318,22 +1351,24 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat if(!m_enable_shaders && (daynight_ratio != m_last_daynight_ratio)) { // Force reload mesh to VBO - if (m_enable_vbo) { - m_mesh->setDirty(); - } + if (m_enable_vbo) + for (int m = 0; m < MAX_TILE_LAYERS; m++) + m_mesh[m]->setDirty(); video::SColorf day_color; get_sunlight_color(&day_color, daynight_ratio); - for(std::map >::iterator + for(std::map, std::map >::iterator i = m_daynight_diffs.begin(); i != m_daynight_diffs.end(); ++i) { - scene::IMeshBuffer *buf = m_mesh->getMeshBuffer(i->first); + scene::IMeshBuffer *buf = m_mesh[i->first.first]-> + getMeshBuffer(i->first.second); video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices(); for(std::map::iterator j = i->second.begin(); j != i->second.end(); ++j) { - final_color_blend(&(vertices[j->first].Color), j->second, day_color); + final_color_blend(&(vertices[j->first].Color), + j->second, day_color); } } m_last_daynight_ratio = daynight_ratio; @@ -1345,9 +1380,12 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat void MapBlockMesh::updateCameraOffset(v3s16 camera_offset) { if (camera_offset != m_camera_offset) { - translateMesh(m_mesh, intToFloat(m_camera_offset-camera_offset, BS)); - if (m_enable_vbo) { - m_mesh->setDirty(); + for (u8 layer = 0; layer < 2; layer++) { + translateMesh(m_mesh[layer], + intToFloat(m_camera_offset - camera_offset, BS)); + if (m_enable_vbo) { + m_mesh[layer]->setDirty(); + } } m_camera_offset = camera_offset; } @@ -1360,16 +1398,30 @@ void MapBlockMesh::updateCameraOffset(v3s16 camera_offset) void MeshCollector::append(const TileSpec &tile, const video::S3DVertex *vertices, u32 numVertices, const u16 *indices, u32 numIndices) +{ + for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) { + const TileLayer *layer = &tile.layers[layernum]; + if (layer->texture_id == 0) + continue; + append(*layer, vertices, numVertices, indices, numIndices, + layernum); + } +} + +void MeshCollector::append(const TileLayer &layer, + const video::S3DVertex *vertices, u32 numVertices, + const u16 *indices, u32 numIndices, u8 layernum) { if (numIndices > 65535) { dstream<<"FIXME: MeshCollector::append() called with numIndices="< *buffers = &prebuffers[layernum]; PreMeshBuffer *p = NULL; - for (u32 i = 0; i < prebuffers.size(); i++) { - PreMeshBuffer &pp = prebuffers[i]; - if (pp.tile != tile) + for (u32 i = 0; i < buffers->size(); i++) { + PreMeshBuffer &pp = (*buffers)[i]; + if (pp.layer != layer) continue; if (pp.indices.size() + numIndices > 65535) continue; @@ -1380,9 +1432,9 @@ void MeshCollector::append(const TileSpec &tile, if (p == NULL) { PreMeshBuffer pp; - pp.tile = tile; - prebuffers.push_back(pp); - p = &prebuffers[prebuffers.size() - 1]; + pp.layer = layer; + buffers->push_back(pp); + p = &(*buffers)[buffers->size() - 1]; } u32 vertex_count; @@ -1416,16 +1468,31 @@ void MeshCollector::append(const TileSpec &tile, const video::S3DVertex *vertices, u32 numVertices, const u16 *indices, u32 numIndices, v3f pos, video::SColor c, u8 light_source) +{ + for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) { + const TileLayer *layer = &tile.layers[layernum]; + if (layer->texture_id == 0) + continue; + append(*layer, vertices, numVertices, indices, numIndices, pos, + c, light_source, layernum); + } +} + +void MeshCollector::append(const TileLayer &layer, + const video::S3DVertex *vertices, u32 numVertices, + const u16 *indices, u32 numIndices, + v3f pos, video::SColor c, u8 light_source, u8 layernum) { if (numIndices > 65535) { dstream<<"FIXME: MeshCollector::append() called with numIndices="< *buffers = &prebuffers[layernum]; PreMeshBuffer *p = NULL; - for (u32 i = 0; i < prebuffers.size(); i++) { - PreMeshBuffer &pp = prebuffers[i]; - if(pp.tile != tile) + for (u32 i = 0; i < buffers->size(); i++) { + PreMeshBuffer &pp = (*buffers)[i]; + if(pp.layer != layer) continue; if(pp.indices.size() + numIndices > 65535) continue; @@ -1436,9 +1503,9 @@ void MeshCollector::append(const TileSpec &tile, if (p == NULL) { PreMeshBuffer pp; - pp.tile = tile; - prebuffers.push_back(pp); - p = &prebuffers[prebuffers.size() - 1]; + pp.layer = layer; + buffers->push_back(pp); + p = &(*buffers)[buffers->size() - 1]; } video::SColor original_c = c; @@ -1473,14 +1540,49 @@ void MeshCollector::append(const TileSpec &tile, } } -video::SColor encode_light_and_color(u16 light, const video::SColor &color, - u8 emissive_light) +void MeshCollector::applyTileColors() +{ + if (m_use_tangent_vertices) + for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { + std::vector *p = &prebuffers[layer]; + for (std::vector::iterator it = p->begin(); + it != p->end(); ++it) { + video::SColor tc = it->layer.color; + if (tc == video::SColor(0xFFFFFFFF)) + continue; + for (u32 index = 0; index < it->tangent_vertices.size(); index++) { + video::SColor *c = &it->tangent_vertices[index].Color; + c->set(c->getAlpha(), c->getRed() * tc.getRed() / 255, + c->getGreen() * tc.getGreen() / 255, + c->getBlue() * tc.getBlue() / 255); + } + } + } + else + for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { + std::vector *p = &prebuffers[layer]; + for (std::vector::iterator it = p->begin(); + it != p->end(); ++it) { + video::SColor tc = it->layer.color; + if (tc == video::SColor(0xFFFFFFFF)) + continue; + for (u32 index = 0; index < it->vertices.size(); index++) { + video::SColor *c = &it->vertices[index].Color; + c->set(c->getAlpha(), c->getRed() * tc.getRed() / 255, + c->getGreen() * tc.getGreen() / 255, + c->getBlue() * tc.getBlue() / 255); + } + } + } +} + +video::SColor encode_light(u16 light, u8 emissive_light) { // Get components - f32 day = (light & 0xff) / 255.0f; - f32 night = (light >> 8) / 255.0f; + u32 day = (light & 0xff); + u32 night = (light >> 8); // Add emissive light - night += emissive_light * 0.01f; + night += emissive_light * 2.5f; if (night > 255) night = 255; // Since we don't know if the day light is sunlight or @@ -1490,15 +1592,14 @@ video::SColor encode_light_and_color(u16 light, const video::SColor &color, day = 0; else day = day - night; - f32 sum = day + night; + u32 sum = day + night; // Ratio of sunlight: - float r; + u32 r; if (sum > 0) - r = day / sum; + r = day * 255 / sum; else r = 0; // Average light: float b = (day + night) / 2; - return video::SColor(r * 255, b * color.getRed(), b * color.getGreen(), - b * color.getBlue()); + return video::SColor(r, b, b, b); } diff --git a/src/mapblock_mesh.h b/src/mapblock_mesh.h index 25c699e1c..f32df3958 100644 --- a/src/mapblock_mesh.h +++ b/src/mapblock_mesh.h @@ -108,7 +108,12 @@ public: scene::IMesh *getMesh() { - return m_mesh; + return m_mesh[0]; + } + + scene::IMesh *getMesh(u8 layer) + { + return m_mesh[layer]; } MinimapMapblock *moveMinimapMapblock() @@ -132,7 +137,7 @@ public: void updateCameraOffset(v3s16 camera_offset); private: - scene::IMesh *m_mesh; + scene::IMesh *m_mesh[MAX_TILE_LAYERS]; MinimapMapblock *m_minimap_mapblock; Client *m_client; video::IVideoDriver *m_driver; @@ -150,20 +155,23 @@ private: // Animation info: cracks // Last crack value passed to animate() int m_last_crack; - // Maps mesh buffer (i.e. material) indices to base texture names - UNORDERED_MAP m_crack_materials; + // Maps mesh and mesh buffer (i.e. material) indices to base texture names + std::map, std::string> m_crack_materials; // Animation info: texture animationi - // Maps meshbuffers to TileSpecs - UNORDERED_MAP m_animation_tiles; - UNORDERED_MAP m_animation_frames; // last animation frame - UNORDERED_MAP m_animation_frame_offsets; + // Maps mesh and mesh buffer indices to TileSpecs + // Keys are pairs of (mesh index, buffer index in the mesh) + std::map, TileLayer> m_animation_tiles; + std::map, int> m_animation_frames; // last animation frame + std::map, int> m_animation_frame_offsets; // Animation info: day/night transitions // Last daynight_ratio value passed to animate() u32 m_last_daynight_ratio; - // For each meshbuffer, stores pre-baked colors of sunlit vertices - std::map > m_daynight_diffs; + // For each mesh and mesh buffer, stores pre-baked colors + // of sunlit vertices + // Keys are pairs of (mesh index, buffer index in the mesh) + std::map, std::map > m_daynight_diffs; // Camera offset info -> do we have to translate the mesh? v3s16 m_camera_offset; @@ -176,7 +184,7 @@ private: */ struct PreMeshBuffer { - TileSpec tile; + TileLayer layer; std::vector indices; std::vector vertices; std::vector tangent_vertices; @@ -184,7 +192,7 @@ struct PreMeshBuffer struct MeshCollector { - std::vector prebuffers; + std::vector prebuffers[MAX_TILE_LAYERS]; bool m_use_tangent_vertices; MeshCollector(bool use_tangent_vertices): @@ -193,27 +201,38 @@ struct MeshCollector } void append(const TileSpec &material, + const video::S3DVertex *vertices, u32 numVertices, + const u16 *indices, u32 numIndices); + void append(const TileLayer &material, const video::S3DVertex *vertices, u32 numVertices, - const u16 *indices, u32 numIndices); + const u16 *indices, u32 numIndices, u8 layernum); void append(const TileSpec &material, + const video::S3DVertex *vertices, u32 numVertices, + const u16 *indices, u32 numIndices, v3f pos, + video::SColor c, u8 light_source); + void append(const TileLayer &material, const video::S3DVertex *vertices, u32 numVertices, - const u16 *indices, u32 numIndices, - v3f pos, video::SColor c, u8 light_source); + const u16 *indices, u32 numIndices, v3f pos, + video::SColor c, u8 light_source, u8 layernum); + /*! + * Colorizes all vertices in the collector. + */ + void applyTileColors(); }; /*! - * Encodes light and color of a node. + * Encodes light of a node. * The result is not the final color, but a * half-baked vertex color. + * You have to multiply the resulting color + * with the node's color. * * \param light the first 8 bits are day light, * the last 8 bits are night light - * \param color the node's color * \param emissive_light amount of light the surface emits, * from 0 to LIGHT_SUN. */ -video::SColor encode_light_and_color(u16 light, const video::SColor &color, - u8 emissive_light); +video::SColor encode_light(u16 light, u8 emissive_light); // Compute light at node u16 getInteriorLight(MapNode n, s32 increment, INodeDefManager *ndef); diff --git a/src/mesh.cpp b/src/mesh.cpp index a79264ef0..d776f6185 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -385,48 +385,50 @@ void recalculateBoundingBox(scene::IMesh *src_mesh) src_mesh->setBoundingBox(bbox); } -scene::IMesh* cloneMesh(scene::IMesh *src_mesh) +scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer) +{ + scene::IMeshBuffer *clone = NULL; + switch (mesh_buffer->getVertexType()) { + case video::EVT_STANDARD: { + video::S3DVertex *v = (video::S3DVertex *) mesh_buffer->getVertices(); + u16 *indices = (u16*) mesh_buffer->getIndices(); + scene::SMeshBuffer *temp_buf = new scene::SMeshBuffer(); + temp_buf->append(v, mesh_buffer->getVertexCount(), indices, + mesh_buffer->getIndexCount()); + return temp_buf; + break; + } + case video::EVT_2TCOORDS: { + video::S3DVertex2TCoords *v = + (video::S3DVertex2TCoords *) mesh_buffer->getVertices(); + u16 *indices = (u16*) mesh_buffer->getIndices(); + scene::SMeshBufferTangents *temp_buf = new scene::SMeshBufferTangents(); + temp_buf->append(v, mesh_buffer->getVertexCount(), indices, + mesh_buffer->getIndexCount()); + break; + } + case video::EVT_TANGENTS: { + video::S3DVertexTangents *v = + (video::S3DVertexTangents *) mesh_buffer->getVertices(); + u16 *indices = (u16*) mesh_buffer->getIndices(); + scene::SMeshBufferTangents *temp_buf = new scene::SMeshBufferTangents(); + temp_buf->append(v, mesh_buffer->getVertexCount(), indices, + mesh_buffer->getIndexCount()); + break; + } + } + return clone; +} + +scene::SMesh* cloneMesh(scene::IMesh *src_mesh) { scene::SMesh* dst_mesh = new scene::SMesh(); for (u16 j = 0; j < src_mesh->getMeshBufferCount(); j++) { - scene::IMeshBuffer *buf = src_mesh->getMeshBuffer(j); - switch (buf->getVertexType()) { - case video::EVT_STANDARD: { - video::S3DVertex *v = - (video::S3DVertex *) buf->getVertices(); - u16 *indices = (u16*)buf->getIndices(); - scene::SMeshBuffer *temp_buf = new scene::SMeshBuffer(); - temp_buf->append(v, buf->getVertexCount(), - indices, buf->getIndexCount()); - dst_mesh->addMeshBuffer(temp_buf); - temp_buf->drop(); - break; - } - case video::EVT_2TCOORDS: { - video::S3DVertex2TCoords *v = - (video::S3DVertex2TCoords *) buf->getVertices(); - u16 *indices = (u16*)buf->getIndices(); - scene::SMeshBufferTangents *temp_buf = - new scene::SMeshBufferTangents(); - temp_buf->append(v, buf->getVertexCount(), - indices, buf->getIndexCount()); - dst_mesh->addMeshBuffer(temp_buf); - temp_buf->drop(); - break; - } - case video::EVT_TANGENTS: { - video::S3DVertexTangents *v = - (video::S3DVertexTangents *) buf->getVertices(); - u16 *indices = (u16*)buf->getIndices(); - scene::SMeshBufferTangents *temp_buf = - new scene::SMeshBufferTangents(); - temp_buf->append(v, buf->getVertexCount(), - indices, buf->getIndexCount()); - dst_mesh->addMeshBuffer(temp_buf); - temp_buf->drop(); - break; - } - } + scene::IMeshBuffer *temp_buf = cloneMeshBuffer( + src_mesh->getMeshBuffer(j)); + dst_mesh->addMeshBuffer(temp_buf); + temp_buf->drop(); + } return dst_mesh; } diff --git a/src/mesh.h b/src/mesh.h index bcf0d771c..0e946caab 100644 --- a/src/mesh.h +++ b/src/mesh.h @@ -82,11 +82,16 @@ void rotateMeshBy6dFacedir(scene::IMesh *mesh, int facedir); void rotateMeshXYby (scene::IMesh *mesh, f64 degrees); void rotateMeshXZby (scene::IMesh *mesh, f64 degrees); void rotateMeshYZby (scene::IMesh *mesh, f64 degrees); + +/* + * Clone the mesh buffer. + */ +scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer); /* Clone the mesh. */ -scene::IMesh* cloneMesh(scene::IMesh *src_mesh); +scene::SMesh* cloneMesh(scene::IMesh *src_mesh); /* Convert nodeboxes to mesh. Each tile goes into a different buffer. diff --git a/src/network/networkprotocol.h b/src/network/networkprotocol.h index ea532d9e0..b586fa70b 100644 --- a/src/network/networkprotocol.h +++ b/src/network/networkprotocol.h @@ -148,9 +148,11 @@ with this program; if not, write to the Free Software Foundation, Inc., Add node and tile color and palette Fix plantlike visual_scale being applied squared and add compatibility with pre-30 clients by sending sqrt(visual_scale) + PROTOCOL VERSION 31: + Add tile overlay */ -#define LATEST_PROTOCOL_VERSION 30 +#define LATEST_PROTOCOL_VERSION 31 // Server's supported network protocol range #define SERVER_PROTOCOL_VERSION_MIN 24 diff --git a/src/nodedef.cpp b/src/nodedef.cpp index ce3e378a0..db28325aa 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -378,13 +378,13 @@ void ContentFeatures::reset() void ContentFeatures::serialize(std::ostream &os, u16 protocol_version) const { - if (protocol_version < 30) { + if (protocol_version < 31) { serializeOld(os, protocol_version); return; } // version - writeU8(os, 9); + writeU8(os, 10); // general os << serializeString(name); @@ -404,6 +404,8 @@ void ContentFeatures::serialize(std::ostream &os, u16 protocol_version) const writeU8(os, 6); for (u32 i = 0; i < 6; i++) tiledef[i].serialize(os, protocol_version); + for (u32 i = 0; i < 6; i++) + tiledef_overlay[i].serialize(os, protocol_version); writeU8(os, CF_SPECIAL_COUNT); for (u32 i = 0; i < CF_SPECIAL_COUNT; i++) { tiledef_special[i].serialize(os, protocol_version); @@ -492,7 +494,7 @@ void ContentFeatures::deSerialize(std::istream &is) if (version < 9) { deSerializeOld(is, version); return; - } else if (version > 9) { + } else if (version > 10) { throw SerializationError("unsupported ContentFeatures version"); } @@ -516,6 +518,9 @@ void ContentFeatures::deSerialize(std::istream &is) throw SerializationError("unsupported tile count"); for (u32 i = 0; i < 6; i++) tiledef[i].deSerialize(is, version, drawtype); + if (version >= 10) + for (u32 i = 0; i < 6; i++) + tiledef_overlay[i].deSerialize(is, version, drawtype); if (readU8(is) != CF_SPECIAL_COUNT) throw SerializationError("unsupported CF_SPECIAL_COUNT"); for (u32 i = 0; i < CF_SPECIAL_COUNT; i++) @@ -581,7 +586,7 @@ void ContentFeatures::deSerialize(std::istream &is) } #ifndef SERVER -void ContentFeatures::fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, +void ContentFeatures::fillTileAttribs(ITextureSource *tsrc, TileLayer *tile, TileDef *tiledef, u32 shader_id, bool use_normal_texture, bool backface_culling, u8 material_type) { @@ -774,14 +779,18 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc // Tiles (fill in f->tiles[]) for (u16 j = 0; j < 6; j++) { - fillTileAttribs(tsrc, &tiles[j], &tdef[j], tile_shader[j], + fillTileAttribs(tsrc, &tiles[j].layers[0], &tdef[j], tile_shader[j], tsettings.use_normal_texture, tiledef[j].backface_culling, material_type); + if (tiledef_overlay[j].name!="") + fillTileAttribs(tsrc, &tiles[j].layers[1], &tiledef_overlay[j], + tile_shader[j], tsettings.use_normal_texture, + tiledef[j].backface_culling, material_type); } // Special tiles (fill in f->special_tiles[]) for (u16 j = 0; j < CF_SPECIAL_COUNT; j++) { - fillTileAttribs(tsrc, &special_tiles[j], &tiledef_special[j], + fillTileAttribs(tsrc, &special_tiles[j].layers[0], &tiledef_special[j], tile_shader[j], tsettings.use_normal_texture, tiledef_special[j].backface_culling, material_type); } @@ -1538,8 +1547,19 @@ void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const if (protocol_version < 30 && drawtype == NDT_PLANTLIKE) compatible_visual_scale = sqrt(visual_scale); + TileDef compatible_tiles[6]; + for (u8 i = 0; i < 6; i++) { + compatible_tiles[i] = tiledef[i]; + if (tiledef_overlay[i].name != "") { + std::stringstream s; + s << "(" << tiledef[i].name << ")^(" << tiledef_overlay[i].name + << ")"; + compatible_tiles[i].name = s.str(); + } + } + // Protocol >= 24 - if (protocol_version < 30) { + if (protocol_version < 31) { writeU8(os, protocol_version < 27 ? 7 : 8); os << serializeString(name); @@ -1553,7 +1573,7 @@ void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const writeF1000(os, compatible_visual_scale); writeU8(os, 6); for (u32 i = 0; i < 6; i++) - tiledef[i].serialize(os, protocol_version); + compatible_tiles[i].serialize(os, protocol_version); writeU8(os, CF_SPECIAL_COUNT); for (u32 i = 0; i < CF_SPECIAL_COUNT; i++) tiledef_special[i].serialize(os, protocol_version); diff --git a/src/nodedef.h b/src/nodedef.h index 83968ce27..4d3bacc6c 100644 --- a/src/nodedef.h +++ b/src/nodedef.h @@ -280,6 +280,8 @@ struct ContentFeatures #endif float visual_scale; // Misc. scale parameter TileDef tiledef[6]; + // These will be drawn over the base tiles. + TileDef tiledef_overlay[6]; TileDef tiledef_special[CF_SPECIAL_COUNT]; // eg. flowing liquid // If 255, the node is opaque. // Otherwise it uses texture alpha. @@ -405,7 +407,7 @@ struct ContentFeatures } #ifndef SERVER - void fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, TileDef *tiledef, + void fillTileAttribs(ITextureSource *tsrc, TileLayer *tile, TileDef *tiledef, u32 shader_id, bool use_normal_texture, bool backface_culling, u8 material_type); void updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc, diff --git a/src/particles.cpp b/src/particles.cpp index e1f292fb6..7f406d874 100644 --- a/src/particles.cpp +++ b/src/particles.cpp @@ -620,7 +620,7 @@ void ParticleManager::addNodeParticle(IGameDef* gamedef, { // Texture u8 texid = myrand_range(0, 5); - const TileSpec &tile = f.tiles[texid]; + const TileLayer &tile = f.tiles[texid].layers[0]; video::ITexture *texture; struct TileAnimationParams anim; anim.type = TAT_NONE; diff --git a/src/script/common/c_content.cpp b/src/script/common/c_content.cpp index 8dfb851e6..573347b4c 100644 --- a/src/script/common/c_content.cpp +++ b/src/script/common/c_content.cpp @@ -426,6 +426,34 @@ ContentFeatures read_content_features(lua_State *L, int index) } lua_pop(L, 1); + // overlay_tiles = {} + lua_getfield(L, index, "overlay_tiles"); + if (lua_istable(L, -1)) { + int table = lua_gettop(L); + lua_pushnil(L); + int i = 0; + while (lua_next(L, table) != 0) { + // Read tiledef from value + f.tiledef_overlay[i] = read_tiledef(L, -1, f.drawtype); + // removes value, keeps key for next iteration + lua_pop(L, 1); + i++; + if (i == 6) { + lua_pop(L, 1); + break; + } + } + // Copy last value to all remaining textures + if (i >= 1) { + TileDef lasttile = f.tiledef_overlay[i - 1]; + while (i < 6) { + f.tiledef_overlay[i] = lasttile; + i++; + } + } + } + lua_pop(L, 1); + // special_tiles = {} lua_getfield(L, index, "special_tiles"); // If nil, try the deprecated name "special_materials" instead diff --git a/src/wieldmesh.cpp b/src/wieldmesh.cpp index 40af0be5f..2b23d9e02 100644 --- a/src/wieldmesh.cpp +++ b/src/wieldmesh.cpp @@ -235,27 +235,16 @@ WieldMeshSceneNode::~WieldMeshSceneNode() g_extrusion_mesh_cache = NULL; } -void WieldMeshSceneNode::setCube(const TileSpec tiles[6], +void WieldMeshSceneNode::setCube(const ContentFeatures &f, v3f wield_scale, ITextureSource *tsrc) { scene::IMesh *cubemesh = g_extrusion_mesh_cache->createCube(); - changeToMesh(cubemesh); + scene::SMesh *copy = cloneMesh(cubemesh); cubemesh->drop(); - + postProcessNodeMesh(copy, f, false, true, &m_material_type, &m_colors); + changeToMesh(copy); + copy->drop(); m_meshnode->setScale(wield_scale * WIELD_SCALE_FACTOR); - - // Customize materials - for (u32 i = 0; i < m_meshnode->getMaterialCount(); ++i) { - assert(i < 6); - video::SMaterial &material = m_meshnode->getMaterial(i); - if (tiles[i].animation_frame_count == 1) { - material.setTexture(0, tiles[i].texture); - } else { - FrameSpec animation_frame = tiles[i].frames[0]; - material.setTexture(0, animation_frame.texture); - } - tiles[i].applyMaterialOptions(material); - } } void WieldMeshSceneNode::setExtruded(const std::string &imagename, @@ -274,8 +263,10 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename, dim = core::dimension2d(dim.Width, frame_height); } scene::IMesh *mesh = g_extrusion_mesh_cache->create(dim); - changeToMesh(mesh); + scene::SMesh *copy = cloneMesh(mesh); mesh->drop(); + changeToMesh(copy); + copy->drop(); m_meshnode->setScale(wield_scale * WIELD_SCALE_FACTOR_EXTRUDED); @@ -321,12 +312,12 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client) // Color-related m_colors.clear(); - video::SColor basecolor = idef->getItemstackColor(item, client); + m_base_color = idef->getItemstackColor(item, client); // If wield_image is defined, it overrides everything else if (def.wield_image != "") { setExtruded(def.wield_image, def.wield_scale, tsrc, 1); - m_colors.push_back(basecolor); + m_colors.push_back(ItemPartColor()); return; } // Handle nodes @@ -334,66 +325,50 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client) else if (def.type == ITEM_NODE) { if (f.mesh_ptr[0]) { // e.g. mesh nodes and nodeboxes - changeToMesh(f.mesh_ptr[0]); - // mesh_ptr[0] is pre-scaled by BS * f->visual_scale + scene::SMesh *mesh = cloneMesh(f.mesh_ptr[0]); + postProcessNodeMesh(mesh, f, m_enable_shaders, true, + &m_material_type, &m_colors); + changeToMesh(mesh); + mesh->drop(); + // mesh is pre-scaled by BS * f->visual_scale m_meshnode->setScale( def.wield_scale * WIELD_SCALE_FACTOR / (BS * f.visual_scale)); } else if (f.drawtype == NDT_AIRLIKE) { changeToMesh(NULL); } else if (f.drawtype == NDT_PLANTLIKE) { - setExtruded(tsrc->getTextureName(f.tiles[0].texture_id), def.wield_scale, tsrc, f.tiles[0].animation_frame_count); + setExtruded(tsrc->getTextureName(f.tiles[0].layers[0].texture_id), + def.wield_scale, tsrc, + f.tiles[0].layers[0].animation_frame_count); } else if (f.drawtype == NDT_NORMAL || f.drawtype == NDT_ALLFACES) { - setCube(f.tiles, def.wield_scale, tsrc); + setCube(f, def.wield_scale, tsrc); } else { MeshMakeData mesh_make_data(client, false); MapNode mesh_make_node(id, 255, 0); mesh_make_data.fillSingleNode(&mesh_make_node); MapBlockMesh mapblock_mesh(&mesh_make_data, v3s16(0, 0, 0)); - changeToMesh(mapblock_mesh.getMesh()); - translateMesh(m_meshnode->getMesh(), v3f(-BS, -BS, -BS)); + scene::SMesh *mesh = cloneMesh(mapblock_mesh.getMesh()); + translateMesh(mesh, v3f(-BS, -BS, -BS)); + postProcessNodeMesh(mesh, f, m_enable_shaders, true, + &m_material_type, &m_colors); + changeToMesh(mesh); + mesh->drop(); m_meshnode->setScale( def.wield_scale * WIELD_SCALE_FACTOR / (BS * f.visual_scale)); } u32 material_count = m_meshnode->getMaterialCount(); - if (material_count > 6) { - errorstream << "WieldMeshSceneNode::setItem: Invalid material " - "count " << material_count << ", truncating to 6" << std::endl; - material_count = 6; - } for (u32 i = 0; i < material_count; ++i) { - const TileSpec *tile = &(f.tiles[i]); video::SMaterial &material = m_meshnode->getMaterial(i); material.setFlag(video::EMF_BACK_FACE_CULLING, true); material.setFlag(video::EMF_BILINEAR_FILTER, m_bilinear_filter); material.setFlag(video::EMF_TRILINEAR_FILTER, m_trilinear_filter); - bool animated = (tile->animation_frame_count > 1); - if (animated) { - FrameSpec animation_frame = tile->frames[0]; - material.setTexture(0, animation_frame.texture); - } else { - material.setTexture(0, tile->texture); - } - m_colors.push_back(tile->has_color ? tile->color : basecolor); - material.MaterialType = m_material_type; - if (m_enable_shaders) { - if (tile->normal_texture) { - if (animated) { - FrameSpec animation_frame = tile->frames[0]; - material.setTexture(1, animation_frame.normal_texture); - } else { - material.setTexture(1, tile->normal_texture); - } - } - material.setTexture(2, tile->flags_texture); - } } return; } else if (def.inventory_image != "") { setExtruded(def.inventory_image, def.wield_scale, tsrc, 1); - m_colors.push_back(basecolor); + m_colors.push_back(ItemPartColor()); return; } @@ -413,9 +388,9 @@ void WieldMeshSceneNode::setColor(video::SColor c) u8 blue = c.getBlue(); u32 mc = mesh->getMeshBufferCount(); for (u32 j = 0; j < mc; j++) { - video::SColor bc(0xFFFFFFFF); - if (m_colors.size() > j) - bc = m_colors[j]; + video::SColor bc(m_base_color); + if ((m_colors.size() > j) && (m_colors[j].override_base)) + bc = m_colors[j].color; video::SColor buffercolor(255, bc.getRed() * red / 255, bc.getGreen() * green / 255, @@ -439,19 +414,7 @@ void WieldMeshSceneNode::changeToMesh(scene::IMesh *mesh) m_meshnode->setMesh(dummymesh); dummymesh->drop(); // m_meshnode grabbed it } else { - if (m_lighting) { - m_meshnode->setMesh(mesh); - } else { - /* - Lighting is disabled, this means the caller can (and probably will) - call setColor later. We therefore need to clone the mesh so that - setColor will only modify this scene node's mesh, not others'. - */ - scene::IMeshManipulator *meshmanip = SceneManager->getMeshManipulator(); - scene::IMesh *new_mesh = meshmanip->createMeshCopy(mesh); - m_meshnode->setMesh(new_mesh); - new_mesh->drop(); // m_meshnode grabbed it - } + m_meshnode->setMesh(mesh); } m_meshnode->setMaterialFlag(video::EMF_LIGHTING, m_lighting); @@ -475,24 +438,24 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) g_extrusion_mesh_cache->grab(); } - scene::IMesh *mesh; + scene::SMesh *mesh; // If inventory_image is defined, it overrides everything else if (def.inventory_image != "") { mesh = getExtrudedMesh(tsrc, def.inventory_image); - result->mesh = mesh; - result->buffer_colors.push_back( - std::pair(false, video::SColor(0xFFFFFFFF))); + result->buffer_colors.push_back(ItemPartColor()); } else if (def.type == ITEM_NODE) { if (f.mesh_ptr[0]) { mesh = cloneMesh(f.mesh_ptr[0]); scaleMesh(mesh, v3f(0.12, 0.12, 0.12)); } else if (f.drawtype == NDT_PLANTLIKE) { mesh = getExtrudedMesh(tsrc, - tsrc->getTextureName(f.tiles[0].texture_id)); + tsrc->getTextureName(f.tiles[0].layers[0].texture_id)); } else if (f.drawtype == NDT_NORMAL || f.drawtype == NDT_ALLFACES || f.drawtype == NDT_LIQUID || f.drawtype == NDT_FLOWINGLIQUID) { - mesh = cloneMesh(g_extrusion_mesh_cache->createCube()); + scene::IMesh *cube = g_extrusion_mesh_cache->createCube(); + mesh = cloneMesh(cube); + cube->drop(); scaleMesh(mesh, v3f(1.2, 1.2, 1.2)); } else { MeshMakeData mesh_make_data(client, false); @@ -519,32 +482,27 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) u32 mc = mesh->getMeshBufferCount(); for (u32 i = 0; i < mc; ++i) { - const TileSpec *tile = &(f.tiles[i]); scene::IMeshBuffer *buf = mesh->getMeshBuffer(i); - result->buffer_colors.push_back( - std::pair(tile->has_color, tile->color)); - colorizeMeshBuffer(buf, &tile->color); video::SMaterial &material = buf->getMaterial(); material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; material.setFlag(video::EMF_BILINEAR_FILTER, false); material.setFlag(video::EMF_TRILINEAR_FILTER, false); material.setFlag(video::EMF_BACK_FACE_CULLING, true); material.setFlag(video::EMF_LIGHTING, false); - if (tile->animation_frame_count > 1) { - FrameSpec animation_frame = tile->frames[0]; - material.setTexture(0, animation_frame.texture); - } else { - material.setTexture(0, tile->texture); - } } rotateMeshXZby(mesh, -45); rotateMeshYZby(mesh, -30); - result->mesh = mesh; + + postProcessNodeMesh(mesh, f, false, false, NULL, + &result->buffer_colors); } + result->mesh = mesh; } -scene::IMesh * getExtrudedMesh(ITextureSource *tsrc, + + +scene::SMesh * getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename) { video::ITexture *texture = tsrc->getTextureForMesh(imagename); @@ -553,7 +511,9 @@ scene::IMesh * getExtrudedMesh(ITextureSource *tsrc, } core::dimension2d dim = texture->getSize(); - scene::IMesh *mesh = cloneMesh(g_extrusion_mesh_cache->create(dim)); + scene::IMesh *original = g_extrusion_mesh_cache->create(dim); + scene::SMesh *mesh = cloneMesh(original); + original->drop(); // Customize material video::SMaterial &material = mesh->getMeshBuffer(0)->getMaterial(); @@ -569,3 +529,57 @@ scene::IMesh * getExtrudedMesh(ITextureSource *tsrc, return mesh; } + +void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, + bool use_shaders, bool set_material, video::E_MATERIAL_TYPE *mattype, + std::vector *colors) +{ + u32 mc = mesh->getMeshBufferCount(); + // Allocate colors for existing buffers + colors->clear(); + for (u32 i = 0; i < mc; ++i) + colors->push_back(ItemPartColor()); + + for (u32 i = 0; i < mc; ++i) { + const TileSpec *tile = &(f.tiles[i]); + scene::IMeshBuffer *buf = mesh->getMeshBuffer(i); + for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) { + const TileLayer *layer = &tile->layers[layernum]; + if (layer->texture_id == 0) + continue; + if (layernum != 0) { + scene::IMeshBuffer *copy = cloneMeshBuffer(buf); + copy->getMaterial() = buf->getMaterial(); + mesh->addMeshBuffer(copy); + copy->drop(); + buf = copy; + colors->push_back( + ItemPartColor(layer->has_color, layer->color)); + } else { + (*colors)[i] = ItemPartColor(layer->has_color, layer->color); + } + video::SMaterial &material = buf->getMaterial(); + if (set_material) + layer->applyMaterialOptions(material); + if (mattype) { + material.MaterialType = *mattype; + } + if (layer->animation_frame_count > 1) { + FrameSpec animation_frame = layer->frames[0]; + material.setTexture(0, animation_frame.texture); + } else { + material.setTexture(0, layer->texture); + } + if (use_shaders) { + if (layer->normal_texture) { + if (layer->animation_frame_count > 1) { + FrameSpec animation_frame = layer->frames[0]; + material.setTexture(1, animation_frame.normal_texture); + } else + material.setTexture(1, layer->normal_texture); + } + material.setTexture(2, layer->flags_texture); + } + } + } +} diff --git a/src/wieldmesh.h b/src/wieldmesh.h index d3946b4e0..c98b469d9 100644 --- a/src/wieldmesh.h +++ b/src/wieldmesh.h @@ -26,17 +26,41 @@ with this program; if not, write to the Free Software Foundation, Inc., struct ItemStack; class Client; class ITextureSource; -struct TileSpec; +struct ContentFeatures; + +/*! + * Holds color information of an item mesh's buffer. + */ +struct ItemPartColor { + /*! + * If this is false, the global base color of the item + * will be used instead of the specific color of the + * buffer. + */ + bool override_base; + /*! + * The color of the buffer. + */ + video::SColor color; + + ItemPartColor(): + override_base(false), + color(0) + {} + + ItemPartColor(bool override, video::SColor color): + override_base(override), + color(color) + {} +}; struct ItemMesh { scene::IMesh *mesh; /*! * Stores the color of each mesh buffer. - * If the boolean is true, the color is fixed, else - * palettes can modify it. */ - std::vector > buffer_colors; + std::vector buffer_colors; ItemMesh() : mesh(NULL), buffer_colors() {} }; @@ -51,7 +75,8 @@ public: s32 id = -1, bool lighting = false); virtual ~WieldMeshSceneNode(); - void setCube(const TileSpec tiles[6], v3f wield_scale, ITextureSource *tsrc); + void setCube(const ContentFeatures &f, v3f wield_scale, + ITextureSource *tsrc); void setExtruded(const std::string &imagename, v3f wield_scale, ITextureSource *tsrc, u8 num_frames); void setItem(const ItemStack &item, Client *client); @@ -84,7 +109,12 @@ private: * Stores the colors of the mesh's mesh buffers. * This does not include lighting. */ - std::vector m_colors; + std::vector m_colors; + /*! + * The base color of this mesh. This is the default + * for all mesh buffers. + */ + video::SColor m_base_color; // Bounding box culling is disabled for this type of scene node, // so this variable is just required so we can implement @@ -94,5 +124,16 @@ private: void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result); -scene::IMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename); +scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename); + +/*! + * Applies overlays, textures and optionally materials to the given mesh and + * extracts tile colors for colorization. + * \param mattype overrides the buffer's material type, but can also + * be NULL to leave the original material. + * \param colors returns the colors of the mesh buffers in the mesh. + */ +void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, + bool use_shaders, bool set_material, video::E_MATERIAL_TYPE *mattype, + std::vector *colors); #endif -- cgit v1.2.3 From b662a4577d692329b9ca83525e6039f2ddcd1ac1 Mon Sep 17 00:00:00 2001 From: ShadowNinja Date: Sun, 6 Mar 2016 14:31:16 -0500 Subject: Clean up getTime helpers This increases size of the getTime return values to 64 bits. It also removes the TimeGetter classes since the getTime functions are now very precise. --- src/client.cpp | 6 +- src/client/clientlauncher.cpp | 19 ----- src/client/clientlauncher.h | 36 -------- src/client/joystick_controller.cpp | 3 +- src/clientiface.cpp | 2 +- src/clientiface.h | 3 +- src/database-sqlite3.cpp | 2 +- src/gettime.h | 21 +---- src/guiChatConsole.cpp | 8 +- src/guiChatConsole.h | 2 +- src/guiFormSpecMenu.cpp | 8 +- src/guiFormSpecMenu.h | 4 +- src/guiTable.cpp | 2 +- src/guiTable.h | 2 +- src/hud.cpp | 6 +- src/main.cpp | 18 ---- src/map.cpp | 2 +- src/porting.cpp | 13 +++ src/porting.h | 163 ++++++++++++++++--------------------- src/touchscreengui.cpp | 2 +- src/touchscreengui.h | 2 +- src/util/timetaker.cpp | 8 +- 22 files changed, 116 insertions(+), 216 deletions(-) (limited to 'src/hud.cpp') diff --git a/src/client.cpp b/src/client.cpp index 019693f1d..43b58d819 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1618,7 +1618,7 @@ float Client::mediaReceiveProgress() typedef struct TextureUpdateArgs { IrrlichtDevice *device; gui::IGUIEnvironment *guienv; - u32 last_time_ms; + u64 last_time_ms; u16 last_percent; const wchar_t* text_base; ITextureSource *tsrc; @@ -1634,7 +1634,7 @@ void texture_update_progress(void *args, u32 progress, u32 max_progress) u32 time_ms = targs->last_time_ms; if (cur_percent != targs->last_percent) { targs->last_percent = cur_percent; - time_ms = getTimeMs(); + time_ms = porting::getTimeMs(); // only draw when the user will notice something: do_draw = (time_ms - targs->last_time_ms > 100); } @@ -1692,7 +1692,7 @@ void Client::afterContentReceived(IrrlichtDevice *device) TextureUpdateArgs tu_args; tu_args.device = device; tu_args.guienv = guienv; - tu_args.last_time_ms = getTimeMs(); + tu_args.last_time_ms = porting::getTimeMs(); tu_args.last_percent = 0; tu_args.text_base = wgettext("Initializing nodes"); tu_args.tsrc = m_tsrc; diff --git a/src/client/clientlauncher.cpp b/src/client/clientlauncher.cpp index 249f6727a..be4e82134 100644 --- a/src/client/clientlauncher.cpp +++ b/src/client/clientlauncher.cpp @@ -51,22 +51,6 @@ bool noMenuActive() MainGameCallback *g_gamecallback = NULL; -// Instance of the time getter -static TimeGetter *g_timegetter = NULL; - -u32 getTimeMs() -{ - if (g_timegetter == NULL) - return 0; - return g_timegetter->getTime(PRECISION_MILLI); -} - -u32 getTime(TimePrecision prec) { - if (g_timegetter == NULL) - return 0; - return g_timegetter->getTime(prec); -} - ClientLauncher::~ClientLauncher() { if (receiver) @@ -96,9 +80,6 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) return false; } - // Create time getter - g_timegetter = new IrrlichtTimeGetter(device); - // Speed tests (done after irrlicht is loaded to get timer) if (cmd_args.getFlag("speedtests")) { dstream << "Running speed tests" << std::endl; diff --git a/src/client/clientlauncher.h b/src/client/clientlauncher.h index ab22d7aaa..4ff77bc03 100644 --- a/src/client/clientlauncher.h +++ b/src/client/clientlauncher.h @@ -24,42 +24,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/inputhandler.h" #include "gameparams.h" -// A small helper class -class TimeGetter -{ -public: - virtual u32 getTime(TimePrecision prec) = 0; -}; - -// A precise irrlicht one -class IrrlichtTimeGetter: public TimeGetter -{ -public: - IrrlichtTimeGetter(IrrlichtDevice *device): - m_device(device) - {} - u32 getTime(TimePrecision prec) - { - if (prec == PRECISION_MILLI) { - if (m_device == NULL) - return 0; - return m_device->getTimer()->getRealTime(); - } else { - return porting::getTime(prec); - } - } -private: - IrrlichtDevice *m_device; -}; -// Not so precise one which works without irrlicht -class SimpleTimeGetter: public TimeGetter -{ -public: - u32 getTime(TimePrecision prec) - { - return porting::getTime(prec); - } -}; class ClientLauncher { diff --git a/src/client/joystick_controller.cpp b/src/client/joystick_controller.cpp index cb9d64b9f..905ca6420 100644 --- a/src/client/joystick_controller.cpp +++ b/src/client/joystick_controller.cpp @@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "keys.h" #include "settings.h" #include "gettime.h" +#include "porting.h" #include "../util/string.h" bool JoystickButtonCmb::isTriggered(const irr::SEvent::SJoystickEvent &ev) const @@ -199,7 +200,7 @@ bool JoystickController::handleEvent(const irr::SEvent::SJoystickEvent &ev) if (ev.Joystick != m_joystick_id) return false; - m_internal_time = getTimeMs() / 1000.f; + m_internal_time = porting::getTimeMs() / 1000.f; std::bitset keys_pressed; diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 64fa1c6b7..7f476f0ea 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -592,7 +592,7 @@ void RemoteClient::notifyEvent(ClientStateEvent event) u32 RemoteClient::uptime() { - return getTime(PRECISION_SECONDS) - m_connection_time; + return porting::getTime(PRECISION_SECONDS) - m_connection_time; } ClientInterface::ClientInterface(con::Connection* con) diff --git a/src/clientiface.h b/src/clientiface.h index 11ebdaab6..49101fbc1 100644 --- a/src/clientiface.h +++ b/src/clientiface.h @@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "threading/mutex.h" #include "network/networkpacket.h" #include "util/cpp11_container.h" +#include "porting.h" #include #include @@ -265,7 +266,7 @@ public: m_version_patch(0), m_full_version("unknown"), m_deployed_compression(0), - m_connection_time(getTime(PRECISION_SECONDS)) + m_connection_time(porting::getTime(PRECISION_SECONDS)) { } ~RemoteClient() diff --git a/src/database-sqlite3.cpp b/src/database-sqlite3.cpp index 714f56c39..7bc87a7d0 100644 --- a/src/database-sqlite3.cpp +++ b/src/database-sqlite3.cpp @@ -71,7 +71,7 @@ int Database_SQLite3::busyHandler(void *data, int count) { s64 &first_time = reinterpret_cast(data)[0]; s64 &prev_time = reinterpret_cast(data)[1]; - s64 cur_time = getTimeMs(); + s64 cur_time = porting::getTimeMs(); if (count == 0) { first_time = cur_time; diff --git a/src/gettime.h b/src/gettime.h index b2f09a7bb..a93eee387 100644 --- a/src/gettime.h +++ b/src/gettime.h @@ -21,33 +21,18 @@ with this program; if not, write to the Free Software Foundation, Inc., #define GETTIME_HEADER #include "irrlichttypes.h" +#include +#include -/* - Get a millisecond counter value. - Precision depends on implementation. - Overflows at any value above 10000000. - Implementation of this is done in: - Normal build: main.cpp - Server build: servermain.cpp -*/ enum TimePrecision { - PRECISION_SECONDS = 0, + PRECISION_SECONDS, PRECISION_MILLI, PRECISION_MICRO, PRECISION_NANO }; -extern u32 getTimeMs(); -extern u32 getTime(TimePrecision prec); - -/* - Timestamp stuff -*/ - -#include -#include inline std::string getTimestamp() { diff --git a/src/guiChatConsole.cpp b/src/guiChatConsole.cpp index bea5571f4..b3c119555 100644 --- a/src/guiChatConsole.cpp +++ b/src/guiChatConsole.cpp @@ -55,7 +55,7 @@ GUIChatConsole::GUIChatConsole( m_client(client), m_menumgr(menumgr), m_screensize(v2u32(0,0)), - m_animate_time_old(0), + m_animate_time_old(porting::getTimeMs()), m_open(false), m_close_on_enter(false), m_height(0), @@ -71,8 +71,6 @@ GUIChatConsole::GUIChatConsole( m_font(NULL), m_fontsize(0, 0) { - m_animate_time_old = getTimeMs(); - // load background settings s32 console_alpha = g_settings->getS32("console_alpha"); m_background_color.setAlpha(clamp_u8(console_alpha)); @@ -124,7 +122,7 @@ void GUIChatConsole::openConsole(f32 scale) m_desired_height_fraction = scale; m_desired_height = scale * m_screensize.Y; reformatConsole(); - m_animate_time_old = getTimeMs(); + m_animate_time_old = porting::getTimeMs(); IGUIElement::setVisible(true); Environment->setFocus(this); m_menumgr->createdMenu(this); @@ -212,7 +210,7 @@ void GUIChatConsole::draw() } // Animation - u32 now = getTimeMs(); + u64 now = porting::getTimeMs(); animate(now - m_animate_time_old); m_animate_time_old = now; diff --git a/src/guiChatConsole.h b/src/guiChatConsole.h index 4e3cae13f..0332678c7 100644 --- a/src/guiChatConsole.h +++ b/src/guiChatConsole.h @@ -98,7 +98,7 @@ private: v2u32 m_screensize; // used to compute how much time passed since last animate() - u32 m_animate_time_old; + u64 m_animate_time_old; // should the console be opened or closed? bool m_open; diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index 14d576f8f..64642cf1f 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -2664,9 +2664,9 @@ void GUIFormSpecMenu::drawMenu() m_old_tooltip = L""; } else { if (id == m_old_tooltip_id) { - delta = porting::getDeltaMs(m_hovered_time, getTimeMs()); + delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs()); } else { - m_hovered_time = getTimeMs(); + m_hovered_time = porting::getTimeMs(); m_old_tooltip_id = id; } } @@ -3244,10 +3244,10 @@ bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event) m_doubleclickdetect[0].time = m_doubleclickdetect[1].time; m_doubleclickdetect[1].pos = m_pointer; - m_doubleclickdetect[1].time = getTimeMs(); + m_doubleclickdetect[1].time = porting::getTimeMs(); } else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { - u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, getTimeMs()); + u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs()); if (delta > 400) { return false; } diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index af2d3f45e..18ccf1c3a 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -421,7 +421,7 @@ protected: gui::IGUIStaticText *m_tooltip_element; u32 m_tooltip_show_delay; - s32 m_hovered_time; + s64 m_hovered_time; s32 m_old_tooltip_id; std::wstring m_old_tooltip; @@ -527,7 +527,7 @@ private: struct clickpos { v2s32 pos; - s32 time; + s64 time; }; clickpos m_doubleclickdetect[2]; diff --git a/src/guiTable.cpp b/src/guiTable.cpp index 6b33b8266..d223e3069 100644 --- a/src/guiTable.cpp +++ b/src/guiTable.cpp @@ -828,7 +828,7 @@ bool GUITable::OnEvent(const SEvent &event) } else if (event.KeyInput.PressedDown && event.KeyInput.Char) { // change selection based on text as it is typed - s32 now = getTimeMs(); + u64 now = porting::getTimeMs(); if (now - m_keynav_time >= 500) m_keynav_buffer = L""; m_keynav_time = now; diff --git a/src/guiTable.h b/src/guiTable.h index 9fbe1c9da..02e8af00b 100644 --- a/src/guiTable.h +++ b/src/guiTable.h @@ -196,7 +196,7 @@ protected: bool m_sel_doubleclick; // Keyboard navigation stuff - s32 m_keynav_time; + u64 m_keynav_time; core::stringw m_keynav_buffer; // Drawing and geometry information diff --git a/src/hud.cpp b/src/hud.cpp index c482912e9..9729013ee 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -619,7 +619,7 @@ void Hud::resizeHotbar() { } struct MeshTimeInfo { - s32 time; + s64 time; scene::IMesh *mesh; }; @@ -653,9 +653,9 @@ void drawItemStack(video::IVideoDriver *driver, MeshTimeInfo &ti = rotation_time_infos[rotation_kind]; if (mesh != ti.mesh) { ti.mesh = mesh; - ti.time = getTimeMs(); + ti.time = porting::getTimeMs(); } else { - delta = porting::getDeltaMs(ti.time, getTimeMs()) % 100000; + delta = porting::getDeltaMs(ti.time, porting::getTimeMs()) % 100000; } } core::rect oldViewPort = driver->getViewPort(); diff --git a/src/main.cpp b/src/main.cpp index 2ad4e2780..6a2e89f7a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -107,24 +107,6 @@ static bool migrate_map_database(const GameParams &game_params, const Settings & /**********************************************************************/ -/* - gettime.h implementation -*/ - -#ifdef SERVER - -u32 getTimeMs() -{ - /* Use imprecise system calls directly (from porting.h) */ - return porting::getTime(PRECISION_MILLI); -} - -u32 getTime(TimePrecision prec) -{ - return porting::getTime(prec); -} - -#endif FileLogOutput file_log_output; diff --git a/src/map.cpp b/src/map.cpp index 9e8823f84..63e1e4ccd 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -981,7 +981,7 @@ void Map::transformLiquids(std::map &modified_blocks, time_until_purge *= 1000; // seconds -> milliseconds - u32 curr_time = getTime(PRECISION_MILLI); + u32 curr_time = porting::getTime(PRECISION_MILLI); u32 prev_unprocessed = m_unprocessed_count; m_unprocessed_count = m_transforming_liquid.size(); diff --git a/src/porting.cpp b/src/porting.cpp index 8c92a3cba..10b6fc940 100644 --- a/src/porting.cpp +++ b/src/porting.cpp @@ -942,5 +942,18 @@ void attachOrCreateConsole(void) #endif } +// Load performance counter frequency only once at startup +#ifdef _WIN32 + +inline double get_perf_freq() +{ + LARGE_INTEGER freq; + QueryPerformanceFrequency(&freq); + return freq.QuadPart; +} + +double perf_freq = get_perf_freq(); + +#endif } //namespace porting diff --git a/src/porting.h b/src/porting.h index aa389d02c..7034d956b 100644 --- a/src/porting.h +++ b/src/porting.h @@ -181,124 +181,99 @@ std::string get_sysinfo(); void initIrrlicht(irr::IrrlichtDevice * ); -/* - Resolution is 10-20ms. - Remember to check for overflows. - Overflow can occur at any value higher than 10000000. -*/ -#ifdef _WIN32 // Windows - inline u32 getTimeS() - { - return GetTickCount() / 1000; - } +// Monotonic counter getters. - inline u32 getTimeMs() - { - return GetTickCount(); - } +#ifdef _WIN32 // Windows - inline u32 getTimeUs() - { - LARGE_INTEGER freq, t; - QueryPerformanceFrequency(&freq); - QueryPerformanceCounter(&t); - return (double)(t.QuadPart) / ((double)(freq.QuadPart) / 1000000.0); - } +extern double perf_freq; - inline u32 getTimeNs() - { - LARGE_INTEGER freq, t; - QueryPerformanceFrequency(&freq); - QueryPerformanceCounter(&t); - return (double)(t.QuadPart) / ((double)(freq.QuadPart) / 1000000000.0); - } +inline u64 os_get_time(double mult) +{ + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return static_cast(t.QuadPart) / (perf_freq / mult); +} + +// Resolution is <1us. +inline u64 getTimeS() { return os_get_time(1); } +inline u64 getTimeMs() { return os_get_time(1000); } +inline u64 getTimeUs() { return os_get_time(1000*1000); } +inline u64 getTimeNs() { return os_get_time(1000*1000*1000); } #else // Posix - inline void _os_get_clock(struct timespec *ts) - { + +inline void os_get_clock(struct timespec *ts) +{ #if defined(__MACH__) && defined(__APPLE__) - // from http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x - // OS X does not have clock_gettime, use clock_get_time - clock_serv_t cclock; - mach_timespec_t mts; - host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); - clock_get_time(cclock, &mts); - mach_port_deallocate(mach_task_self(), cclock); - ts->tv_sec = mts.tv_sec; - ts->tv_nsec = mts.tv_nsec; +// From http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x +// OS X does not have clock_gettime, use clock_get_time + clock_serv_t cclock; + mach_timespec_t mts; + host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); + clock_get_time(cclock, &mts); + mach_port_deallocate(mach_task_self(), cclock); + ts->tv_sec = mts.tv_sec; + ts->tv_nsec = mts.tv_nsec; #elif defined(CLOCK_MONOTONIC_RAW) - clock_gettime(CLOCK_MONOTONIC_RAW, ts); + clock_gettime(CLOCK_MONOTONIC_RAW, ts); #elif defined(_POSIX_MONOTONIC_CLOCK) - clock_gettime(CLOCK_MONOTONIC, ts); + clock_gettime(CLOCK_MONOTONIC, ts); #else - struct timeval tv; - gettimeofday(&tv, NULL); - TIMEVAL_TO_TIMESPEC(&tv, ts); -#endif // defined(__MACH__) && defined(__APPLE__) - } + struct timeval tv; + gettimeofday(&tv, NULL); + TIMEVAL_TO_TIMESPEC(&tv, ts); +#endif +} - // Note: these clock functions do not return wall time, but - // generally a clock that starts at 0 when the process starts. - inline u32 getTimeS() - { - struct timespec ts; - _os_get_clock(&ts); - return ts.tv_sec; - } +inline u64 getTimeS() +{ + struct timespec ts; + os_get_clock(&ts); + return ts.tv_sec; +} - inline u32 getTimeMs() - { - struct timespec ts; - _os_get_clock(&ts); - return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; - } +inline u64 getTimeMs() +{ + struct timespec ts; + os_get_clock(&ts); + return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} - inline u32 getTimeUs() - { - struct timespec ts; - _os_get_clock(&ts); - return ts.tv_sec * 1000000 + ts.tv_nsec / 1000; - } +inline u64 getTimeUs() +{ + struct timespec ts; + os_get_clock(&ts); + return ts.tv_sec * 1000000 + ts.tv_nsec / 1000; +} - inline u32 getTimeNs() - { - struct timespec ts; - _os_get_clock(&ts); - return ts.tv_sec * 1000000000 + ts.tv_nsec; - } +inline u64 getTimeNs() +{ + struct timespec ts; + os_get_clock(&ts); + return ts.tv_sec * 1000000000 + ts.tv_nsec; +} - /*#include - inline u32 getTimeMs() - { - struct timeb tb; - ftime(&tb); - return tb.time * 1000 + tb.millitm; - }*/ #endif -inline u32 getTime(TimePrecision prec) +inline u64 getTime(TimePrecision prec) { switch (prec) { - case PRECISION_SECONDS: - return getTimeS(); - case PRECISION_MILLI: - return getTimeMs(); - case PRECISION_MICRO: - return getTimeUs(); - case PRECISION_NANO: - return getTimeNs(); + case PRECISION_SECONDS: return getTimeS(); + case PRECISION_MILLI: return getTimeMs(); + case PRECISION_MICRO: return getTimeUs(); + case PRECISION_NANO: return getTimeNs(); } - return 0; + FATAL_ERROR("Called getTime with invalid time precision"); } /** - * Delta calculation function taking two 32bit arguments. - * @param old_time_ms old time for delta calculation (order is relevant!) - * @param new_time_ms new time for delta calculation (order is relevant!) - * @return positive 32bit delta value + * Delta calculation function arguments. + * @param old_time_ms old time for delta calculation + * @param new_time_ms new time for delta calculation + * @return positive delta value */ -inline u32 getDeltaMs(u32 old_time_ms, u32 new_time_ms) +inline u64 getDeltaMs(u64 old_time_ms, u64 new_time_ms) { if (new_time_ms >= old_time_ms) { return (new_time_ms - old_time_ms); diff --git a/src/touchscreengui.cpp b/src/touchscreengui.cpp index 8d210c63a..1f80da691 100644 --- a/src/touchscreengui.cpp +++ b/src/touchscreengui.cpp @@ -794,7 +794,7 @@ void TouchScreenGUI::translateEvent(const SEvent &event) if (m_move_id == -1) { m_move_id = event.TouchInput.ID; m_move_has_really_moved = false; - m_move_downtime = getTimeMs(); + m_move_downtime = porting::getTimeMs(); m_move_downlocation = v2s32(event.TouchInput.X, event.TouchInput.Y); m_move_sent_as_mouse_event = false; } diff --git a/src/touchscreengui.h b/src/touchscreengui.h index 1308d78ae..f4f1766c9 100644 --- a/src/touchscreengui.h +++ b/src/touchscreengui.h @@ -186,7 +186,7 @@ private: int m_move_id; bool m_move_has_really_moved; - s32 m_move_downtime; + s64 m_move_downtime; bool m_move_sent_as_mouse_event; v2s32 m_move_downlocation; diff --git a/src/util/timetaker.cpp b/src/util/timetaker.cpp index dcf07dc0d..0e92696ac 100644 --- a/src/util/timetaker.cpp +++ b/src/util/timetaker.cpp @@ -19,7 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "timetaker.h" -#include "../gettime.h" +#include "../porting.h" #include "../log.h" #include @@ -29,14 +29,14 @@ TimeTaker::TimeTaker(const char *name, u32 *result, TimePrecision prec) m_result = result; m_running = true; m_precision = prec; - m_time1 = getTime(prec); + m_time1 = porting::getTime(prec); } u32 TimeTaker::stop(bool quiet) { if(m_running) { - u32 time2 = getTime(m_precision); + u32 time2 = porting::getTime(m_precision); u32 dtime = time2 - m_time1; if(m_result != NULL) { @@ -64,7 +64,7 @@ u32 TimeTaker::stop(bool quiet) u32 TimeTaker::getTimerTime() { - u32 time2 = getTime(m_precision); + u32 time2 = porting::getTime(m_precision); u32 dtime = time2 - m_time1; return dtime; } -- cgit v1.2.3 From 018217f6b2058db44b59a86e170614e1c6925f9f Mon Sep 17 00:00:00 2001 From: ezhh Date: Thu, 11 May 2017 23:18:36 +0100 Subject: Add option to use neither node highlighting nor outlining --- builtin/mainmenu/tab_settings.lua | 5 +++-- builtin/settingtypes.txt | 2 +- minetest.conf.example | 2 +- src/hud.cpp | 25 ++++++++++++++++--------- src/hud.h | 6 +++++- 5 files changed, 26 insertions(+), 14 deletions(-) (limited to 'src/hud.cpp') diff --git a/builtin/mainmenu/tab_settings.lua b/builtin/mainmenu/tab_settings.lua index 69683eaa3..5a8cc19b8 100644 --- a/builtin/mainmenu/tab_settings.lua +++ b/builtin/mainmenu/tab_settings.lua @@ -25,7 +25,8 @@ local labels = { }, node_highlighting = { fgettext("Node Outlining"), - fgettext("Node Highlighting") + fgettext("Node Highlighting"), + fgettext("None") }, filters = { fgettext("No Filter"), @@ -52,7 +53,7 @@ local dd_options = { }, node_highlighting = { table.concat(labels.node_highlighting, ","), - {"box", "halo"} + {"box", "halo", "none"} }, filters = { table.concat(labels.filters, ","), diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 61c04e616..463ca0be9 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -344,7 +344,7 @@ enable_clouds (Clouds) bool true enable_3d_clouds (3D clouds) bool true # Method used to highlight selected object. -node_highlighting (Node highlighting) enum box box,halo +node_highlighting (Node highlighting) enum box box,halo,none # Adds particles when digging a node. enable_particles (Digging particles) bool true diff --git a/minetest.conf.example b/minetest.conf.example index 6c6ce91b8..e9add1597 100644 --- a/minetest.conf.example +++ b/minetest.conf.example @@ -382,7 +382,7 @@ # enable_3d_clouds = true # Method used to highlight selected object. -# type: enum values: box, halo +# type: enum values: box, halo, none # node_highlighting = box # Adds particles when digging a node. diff --git a/src/hud.cpp b/src/hud.cpp index 9729013ee..3e4162b64 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -87,24 +87,31 @@ Hud::Hud(video::IVideoDriver *driver, scene::ISceneManager* smgr, m_halo_boxes.clear(); m_selection_pos = v3f(0.0, 0.0, 0.0); - std::string mode = g_settings->get("node_highlighting"); + std::string mode_setting = g_settings->get("node_highlighting"); + + if (mode_setting == "halo") { + m_mode = HIGHLIGHT_HALO; + } else if (mode_setting == "none") { + m_mode = HIGHLIGHT_NONE; + } else { + m_mode = HIGHLIGHT_BOX; + } + m_selection_material.Lighting = false; if (g_settings->getBool("enable_shaders")) { IShaderSource *shdrsrc = client->getShaderSource(); u16 shader_id = shdrsrc->getShader( - mode == "halo" ? "selection_shader" : "default_shader", 1, 1); + m_mode == HIGHLIGHT_HALO ? "selection_shader" : "default_shader", 1, 1); m_selection_material.MaterialType = shdrsrc->getShaderInfo(shader_id).material; } else { m_selection_material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; } - if (mode == "box") { - m_use_selection_mesh = false; + if (m_mode == HIGHLIGHT_BOX) { m_selection_material.Thickness = rangelim(g_settings->getS16("selectionbox_width"), 1, 5); - } else if (mode == "halo") { - m_use_selection_mesh = true; + } else if (m_mode == HIGHLIGHT_HALO) { m_selection_material.setTexture(0, tsrc->getTextureForMesh("halo.png")); m_selection_material.setFlag(video::EMF_BACK_FACE_CULLING, true); } else { @@ -518,7 +525,7 @@ void Hud::setSelectionPos(const v3f &pos, const v3s16 &camera_offset) void Hud::drawSelectionMesh() { - if (!m_use_selection_mesh) { + if (m_mode == HIGHLIGHT_BOX) { // Draw 3D selection boxes video::SMaterial oldmaterial = driver->getMaterial2D(); driver->setMaterial(m_selection_material); @@ -538,7 +545,7 @@ void Hud::drawSelectionMesh() driver->draw3DBox(box, video::SColor(255, r, g, b)); } driver->setMaterial(oldmaterial); - } else if (m_selection_mesh) { + } else if (m_mode == HIGHLIGHT_HALO && m_selection_mesh) { // Draw selection mesh video::SMaterial oldmaterial = driver->getMaterial2D(); driver->setMaterial(m_selection_material); @@ -564,7 +571,7 @@ void Hud::drawSelectionMesh() void Hud::updateSelectionMesh(const v3s16 &camera_offset) { m_camera_offset = camera_offset; - if (!m_use_selection_mesh) + if (m_mode != HIGHLIGHT_HALO) return; if (m_selection_mesh) { diff --git a/src/hud.h b/src/hud.h index efa0c3648..15c115d89 100644 --- a/src/hud.h +++ b/src/hud.h @@ -175,7 +175,11 @@ private: v3f m_selected_face_normal; video::SMaterial m_selection_material; - bool m_use_selection_mesh; + + enum { + HIGHLIGHT_BOX, + HIGHLIGHT_HALO, + HIGHLIGHT_NONE } m_mode; }; enum ItemRotationKind { -- cgit v1.2.3 From d99b6fed5517797bfafe4bbb307963967f0ca749 Mon Sep 17 00:00:00 2001 From: SmallJoker Date: Fri, 26 May 2017 14:03:36 +0200 Subject: Time: Change old `u32` timestamps to 64-bit (#5818) MacOSX build fix + cleanups --- src/clientiface.cpp | 4 ++-- src/clientiface.h | 6 +++--- src/guiFormSpecMenu.cpp | 4 ++-- src/guiFormSpecMenu.h | 4 ++-- src/hud.cpp | 2 +- src/intlGUIEditBox.h | 2 +- src/map.cpp | 2 +- src/map.h | 2 +- src/network/connection.h | 2 +- src/profiler.cpp | 30 ++++++++++++++++++++++++++++++ src/profiler.h | 44 ++------------------------------------------ src/touchscreengui.cpp | 4 ++-- src/unittest/test.cpp | 8 ++++---- src/unittest/test.h | 4 ++-- src/util/timetaker.cpp | 23 ++++++++--------------- src/util/timetaker.h | 14 +++++++------- src/voxel.cpp | 12 ++++-------- src/voxel.h | 4 ++-- 18 files changed, 75 insertions(+), 96 deletions(-) (limited to 'src/hud.cpp') diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 356281ca6..68bd4afe7 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -590,9 +590,9 @@ void RemoteClient::notifyEvent(ClientStateEvent event) } } -u32 RemoteClient::uptime() const +u64 RemoteClient::uptime() const { - return porting::getTime(PRECISION_SECONDS) - m_connection_time; + return porting::getTimeS() - m_connection_time; } ClientInterface::ClientInterface(con::Connection* con) diff --git a/src/clientiface.h b/src/clientiface.h index a219ed5fc..d2299c879 100644 --- a/src/clientiface.h +++ b/src/clientiface.h @@ -266,7 +266,7 @@ public: m_version_patch(0), m_full_version("unknown"), m_deployed_compression(0), - m_connection_time(porting::getTime(PRECISION_SECONDS)) + m_connection_time(porting::getTimeS()) { } ~RemoteClient() @@ -345,7 +345,7 @@ public: { serialization_version = m_pending_serialization_version; } /* get uptime */ - u32 uptime() const; + u64 uptime() const; /* set version information */ void setVersionInfo(u8 major, u8 minor, u8 patch, const std::string &full) @@ -432,7 +432,7 @@ private: /* time this client was created */ - const u32 m_connection_time; + const u64 m_connection_time; }; class ClientInterface { diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index 64642cf1f..971d505fd 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -2658,7 +2658,7 @@ void GUIFormSpecMenu::drawMenu() if (hovered != NULL) { s32 id = hovered->getID(); - u32 delta = 0; + u64 delta = 0; if (id == -1) { m_old_tooltip_id = id; m_old_tooltip = L""; @@ -3247,7 +3247,7 @@ bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event) m_doubleclickdetect[1].time = porting::getTimeMs(); } else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { - u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs()); + u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs()); if (delta > 400) { return false; } diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 18ccf1c3a..557a1cc9f 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -420,8 +420,8 @@ protected: v2s32 m_old_pointer; // Mouse position after previous mouse event gui::IGUIStaticText *m_tooltip_element; - u32 m_tooltip_show_delay; - s64 m_hovered_time; + u64 m_tooltip_show_delay; + u64 m_hovered_time; s32 m_old_tooltip_id; std::wstring m_old_tooltip; diff --git a/src/hud.cpp b/src/hud.cpp index 3e4162b64..72145b4da 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -626,7 +626,7 @@ void Hud::resizeHotbar() { } struct MeshTimeInfo { - s64 time; + u64 time; scene::IMesh *mesh; }; diff --git a/src/intlGUIEditBox.h b/src/intlGUIEditBox.h index e3ee15a30..bb617476c 100644 --- a/src/intlGUIEditBox.h +++ b/src/intlGUIEditBox.h @@ -155,7 +155,7 @@ namespace gui gui::IGUIFont *OverrideFont, *LastBreakFont; IOSOperator* Operator; - u32 BlinkStartTime; + u64 BlinkStartTime; s32 CursorPos; s32 HScrollPos, VScrollPos; // scroll position in characters u32 Max; diff --git a/src/map.cpp b/src/map.cpp index 63e1e4ccd..641b7d2dd 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -981,7 +981,7 @@ void Map::transformLiquids(std::map &modified_blocks, time_until_purge *= 1000; // seconds -> milliseconds - u32 curr_time = porting::getTime(PRECISION_MILLI); + u64 curr_time = porting::getTimeMs(); u32 prev_unprocessed = m_unprocessed_count; m_unprocessed_count = m_transforming_liquid.size(); diff --git a/src/map.h b/src/map.h index 7e597bef6..41a1a246b 100644 --- a/src/map.h +++ b/src/map.h @@ -343,7 +343,7 @@ protected: private: f32 m_transforming_liquid_loop_count_multiplier; u32 m_unprocessed_count; - u32 m_inc_trending_up_start_time; // milliseconds + u64 m_inc_trending_up_start_time; // milliseconds bool m_queue_size_timer_started; DISABLE_CLASS_COPY(Map); diff --git a/src/network/connection.h b/src/network/connection.h index 3a8388522..8b7ed9773 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -769,7 +769,7 @@ class Peer { // Seconds from last receive float m_timeout_counter; - u32 m_last_timeout_check; + u64 m_last_timeout_check; }; class UDPPeer : public Peer diff --git a/src/profiler.cpp b/src/profiler.cpp index 197e094f6..8e997442c 100644 --- a/src/profiler.cpp +++ b/src/profiler.cpp @@ -21,3 +21,33 @@ with this program; if not, write to the Free Software Foundation, Inc., static Profiler main_profiler; Profiler *g_profiler = &main_profiler; +ScopeProfiler::ScopeProfiler( + Profiler *profiler, const std::string &name, ScopeProfilerType type) + : m_profiler(profiler), m_name(name), m_timer(NULL), m_type(type) +{ + if (m_profiler) + m_timer = new TimeTaker(m_name); +} + +ScopeProfiler::~ScopeProfiler() +{ + if (!m_timer) + return; + + float duration_ms = m_timer->stop(true); + float duration = duration_ms / 1000.0; + if (m_profiler) { + switch (m_type) { + case SPT_ADD: + m_profiler->add(m_name, duration); + break; + case SPT_AVG: + m_profiler->avg(m_name, duration); + break; + case SPT_GRAPH_ADD: + m_profiler->graphAdd(m_name, duration); + break; + } + } + delete m_timer; +} diff --git a/src/profiler.h b/src/profiler.h index 6da115972..ce60c6262 100644 --- a/src/profiler.h +++ b/src/profiler.h @@ -193,48 +193,8 @@ class ScopeProfiler { public: ScopeProfiler(Profiler *profiler, const std::string &name, - enum ScopeProfilerType type = SPT_ADD): - m_profiler(profiler), - m_name(name), - m_timer(NULL), - m_type(type) - { - if(m_profiler) - m_timer = new TimeTaker(m_name.c_str()); - } - // name is copied - ScopeProfiler(Profiler *profiler, const char *name, - enum ScopeProfilerType type = SPT_ADD): - m_profiler(profiler), - m_name(name), - m_timer(NULL), - m_type(type) - { - if(m_profiler) - m_timer = new TimeTaker(m_name.c_str()); - } - ~ScopeProfiler() - { - if(m_timer) - { - float duration_ms = m_timer->stop(true); - float duration = duration_ms / 1000.0; - if(m_profiler){ - switch(m_type){ - case SPT_ADD: - m_profiler->add(m_name, duration); - break; - case SPT_AVG: - m_profiler->avg(m_name, duration); - break; - case SPT_GRAPH_ADD: - m_profiler->graphAdd(m_name, duration); - break; - } - } - delete m_timer; - } - } + ScopeProfilerType type = SPT_ADD); + ~ScopeProfiler(); private: Profiler *m_profiler; std::string m_name; diff --git a/src/touchscreengui.cpp b/src/touchscreengui.cpp index f32679ca4..0139b8c4f 100644 --- a/src/touchscreengui.cpp +++ b/src/touchscreengui.cpp @@ -922,7 +922,7 @@ bool TouchScreenGUI::doubleTapDetection() m_key_events[1].x = m_move_downlocation.X; m_key_events[1].y = m_move_downlocation.Y; - u32 delta = porting::getDeltaMs(m_key_events[0].down_time, porting::getTimeMs()); + u64 delta = porting::getDeltaMs(m_key_events[0].down_time, porting::getTimeMs()); if (delta > 400) return false; @@ -1006,7 +1006,7 @@ void TouchScreenGUI::step(float dtime) (!m_move_has_really_moved) && (!m_move_sent_as_mouse_event)) { - u32 delta = porting::getDeltaMs(m_move_downtime, porting::getTimeMs()); + u64 delta = porting::getDeltaMs(m_move_downtime, porting::getTimeMs()); if (delta > MIN_DIG_TIME_MS) { m_shootline = m_device diff --git a/src/unittest/test.cpp b/src/unittest/test.cpp index 9d223b82d..570807ba7 100644 --- a/src/unittest/test.cpp +++ b/src/unittest/test.cpp @@ -229,7 +229,7 @@ bool run_tests() { DSTACK(FUNCTION_NAME); - u32 t1 = porting::getTime(PRECISION_MILLI); + u64 t1 = porting::getTimeMs(); TestGameDef gamedef; g_logger.setLevelSilenced(LL_ERROR, true); @@ -246,7 +246,7 @@ bool run_tests() num_total_tests_run += testmods[i]->num_tests_run; } - u32 tdiff = porting::getTime(PRECISION_MILLI) - t1; + u64 tdiff = porting::getTimeMs() - t1; g_logger.setLevelSilenced(LL_ERROR, false); @@ -273,12 +273,12 @@ bool run_tests() bool TestBase::testModule(IGameDef *gamedef) { rawstream << "======== Testing module " << getName() << std::endl; - u32 t1 = porting::getTime(PRECISION_MILLI); + u64 t1 = porting::getTimeMs(); runTests(gamedef); - u32 tdiff = porting::getTime(PRECISION_MILLI) - t1; + u64 tdiff = porting::getTimeMs() - t1; rawstream << "======== Module " << getName() << " " << (num_tests_failed ? "failed" : "passed") << " (" << num_tests_failed << " failures / " << num_tests_run << " tests) - " << tdiff diff --git a/src/unittest/test.h b/src/unittest/test.h index e60e657cc..bf76e8bb2 100644 --- a/src/unittest/test.h +++ b/src/unittest/test.h @@ -33,7 +33,7 @@ class TestFailedException : public std::exception { // Runs a unit test and reports results #define TEST(fxn, ...) do { \ - u32 t1 = porting::getTime(PRECISION_MILLI); \ + u64 t1 = porting::getTimeMs(); \ try { \ fxn(__VA_ARGS__); \ rawstream << "[PASS] "; \ @@ -46,7 +46,7 @@ class TestFailedException : public std::exception { num_tests_failed++; \ } \ num_tests_run++; \ - u32 tdiff = porting::getTime(PRECISION_MILLI) - t1; \ + u64 tdiff = porting::getTimeMs() - t1; \ rawstream << #fxn << " - " << tdiff << "ms" << std::endl; \ } while (0) diff --git a/src/util/timetaker.cpp b/src/util/timetaker.cpp index 0e92696ac..ac686c3a3 100644 --- a/src/util/timetaker.cpp +++ b/src/util/timetaker.cpp @@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "../log.h" #include -TimeTaker::TimeTaker(const char *name, u32 *result, TimePrecision prec) +TimeTaker::TimeTaker(const std::string &name, u64 *result, TimePrecision prec) { m_name = name; m_result = result; @@ -32,18 +32,13 @@ TimeTaker::TimeTaker(const char *name, u32 *result, TimePrecision prec) m_time1 = porting::getTime(prec); } -u32 TimeTaker::stop(bool quiet) +u64 TimeTaker::stop(bool quiet) { - if(m_running) - { - u32 time2 = porting::getTime(m_precision); - u32 dtime = time2 - m_time1; - if(m_result != NULL) - { + if (m_running) { + u64 dtime = porting::getTime(m_precision) - m_time1; + if (m_result != NULL) { (*m_result) += dtime; - } - else - { + } else { if (!quiet) { static const char* const units[] = { "s" /* PRECISION_SECONDS */, @@ -62,10 +57,8 @@ u32 TimeTaker::stop(bool quiet) return 0; } -u32 TimeTaker::getTimerTime() +u64 TimeTaker::getTimerTime() { - u32 time2 = porting::getTime(m_precision); - u32 dtime = time2 - m_time1; - return dtime; + return porting::getTime(m_precision) - m_time1; } diff --git a/src/util/timetaker.h b/src/util/timetaker.h index 5512c205f..c10f4f535 100644 --- a/src/util/timetaker.h +++ b/src/util/timetaker.h @@ -30,24 +30,24 @@ with this program; if not, write to the Free Software Foundation, Inc., class TimeTaker { public: - TimeTaker(const char *name, u32 *result=NULL, - TimePrecision=PRECISION_MILLI); + TimeTaker(const std::string &name, u64 *result=NULL, + TimePrecision prec=PRECISION_MILLI); ~TimeTaker() { stop(); } - u32 stop(bool quiet=false); + u64 stop(bool quiet=false); - u32 getTimerTime(); + u64 getTimerTime(); private: - const char *m_name; - u32 m_time1; + std::string m_name; + u64 m_time1; bool m_running; TimePrecision m_precision; - u32 *m_result; + u64 *m_result; }; #endif diff --git a/src/voxel.cpp b/src/voxel.cpp index 87773b240..78efde5bb 100644 --- a/src/voxel.cpp +++ b/src/voxel.cpp @@ -27,14 +27,10 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Debug stuff */ -u32 addarea_time = 0; -u32 emerge_time = 0; -u32 emerge_load_time = 0; -u32 clearflag_time = 0; -//u32 getwaterpressure_time = 0; -//u32 spreadwaterpressure_time = 0; -u32 updateareawaterpressure_time = 0; -u32 flowwater_pre_time = 0; +u64 addarea_time = 0; +u64 emerge_time = 0; +u64 emerge_load_time = 0; +u64 clearflag_time = 0; VoxelManipulator::VoxelManipulator(): diff --git a/src/voxel.h b/src/voxel.h index 58ad39be4..3a64ccc79 100644 --- a/src/voxel.h +++ b/src/voxel.h @@ -49,8 +49,8 @@ class INodeDefManager; /* Debug stuff */ -extern u32 emerge_time; -extern u32 emerge_load_time; +extern u64 emerge_time; +extern u64 emerge_load_time; /* This class resembles aabbox3d a lot, but has inclusive -- cgit v1.2.3 From 001de6ffbac83bcd41ecda075d79d265a69c7d42 Mon Sep 17 00:00:00 2001 From: Dániel Juhász Date: Thu, 1 Jun 2017 23:18:55 +0200 Subject: Do not shade inventory items with textures (#5869) This commit restores the old behavior: if an inventory item has an own inventory texture, it will not be shaded. --- src/hud.cpp | 5 ++++- src/mesh.cpp | 18 ++++++++++-------- src/mesh.h | 9 +++++++++ src/wieldmesh.cpp | 5 +++++ src/wieldmesh.h | 7 ++++++- 5 files changed, 34 insertions(+), 10 deletions(-) (limited to 'src/hud.cpp') diff --git a/src/hud.cpp b/src/hud.cpp index 72145b4da..a2f031b4c 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -698,7 +698,10 @@ void drawItemStack(video::IVideoDriver *driver, if (p->override_base) c = p->color; } - colorizeMeshBuffer(buf, &c); + if (imesh->needs_shading) + colorizeMeshBuffer(buf, &c); + else + setMeshBufferColor(buf, c); video::SMaterial &material = buf->getMaterial(); material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; material.Lighting = false; diff --git a/src/mesh.cpp b/src/mesh.cpp index 824d6891b..3ab67510a 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -175,6 +175,14 @@ void translateMesh(scene::IMesh *mesh, v3f vec) mesh->setBoundingBox(bbox); } +void setMeshBufferColor(scene::IMeshBuffer *buf, const video::SColor &color) +{ + const u32 stride = getVertexPitchFromType(buf->getVertexType()); + u32 vertex_count = buf->getVertexCount(); + u8 *vertices = (u8 *) buf->getVertices(); + for (u32 i = 0; i < vertex_count; i++) + ((video::S3DVertex *) (vertices + i * stride))->Color = color; +} void setMeshColor(scene::IMesh *mesh, const video::SColor &color) { @@ -182,14 +190,8 @@ void setMeshColor(scene::IMesh *mesh, const video::SColor &color) return; u32 mc = mesh->getMeshBufferCount(); - for (u32 j = 0; j < mc; j++) { - scene::IMeshBuffer *buf = mesh->getMeshBuffer(j); - const u32 stride = getVertexPitchFromType(buf->getVertexType()); - u32 vertex_count = buf->getVertexCount(); - u8 *vertices = (u8 *)buf->getVertices(); - for (u32 i = 0; i < vertex_count; i++) - ((video::S3DVertex *)(vertices + i * stride))->Color = color; - } + for (u32 j = 0; j < mc; j++) + setMeshBufferColor(mesh->getMeshBuffer(j), color); } void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolor) diff --git a/src/mesh.h b/src/mesh.h index adaf0c836..423e43aee 100644 --- a/src/mesh.h +++ b/src/mesh.h @@ -49,11 +49,20 @@ void scaleMesh(scene::IMesh *mesh, v3f scale); */ void translateMesh(scene::IMesh *mesh, v3f vec); +/*! + * Sets a constant color for all vertices in the mesh buffer. + */ +void setMeshBufferColor(scene::IMeshBuffer *buf, const video::SColor &color); + /* Set a constant color for all vertices in the mesh */ void setMeshColor(scene::IMesh *mesh, const video::SColor &color); +/*! + * Overwrites the color of a mesh buffer. + * The color is darkened based on the normal vector of the vertices. + */ void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolor); /* diff --git a/src/wieldmesh.cpp b/src/wieldmesh.cpp index 8b1477bb7..7736ec2a2 100644 --- a/src/wieldmesh.cpp +++ b/src/wieldmesh.cpp @@ -440,10 +440,15 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) scene::SMesh *mesh = NULL; + // Shading is on by default + result->needs_shading = true; + // If inventory_image is defined, it overrides everything else if (def.inventory_image != "") { mesh = getExtrudedMesh(tsrc, def.inventory_image); result->buffer_colors.push_back(ItemPartColor()); + // Items with inventory images do not need shading + result->needs_shading = false; } else if (def.type == ITEM_NODE) { if (f.mesh_ptr[0]) { mesh = cloneMesh(f.mesh_ptr[0]); diff --git a/src/wieldmesh.h b/src/wieldmesh.h index ef164c11f..faedce484 100644 --- a/src/wieldmesh.h +++ b/src/wieldmesh.h @@ -59,8 +59,13 @@ struct ItemMesh * Stores the color of each mesh buffer. */ std::vector buffer_colors; + /*! + * If false, all faces of the item should have the same brightness. + * Disables shading based on normal vectors. + */ + bool needs_shading; - ItemMesh() : mesh(NULL), buffer_colors() {} + ItemMesh() : mesh(NULL), buffer_colors(), needs_shading(true) {} }; /* -- cgit v1.2.3