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/content_mapblock.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 8ce0f1e0a..a7134590b 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -26,7 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/tile.h" #include "mesh.h" #include -#include "gamedef.h" +#include "client.h" #include "log.h" #include "noise.h" @@ -188,8 +188,8 @@ static inline int NeighborToIndex(const v3s16 &pos) void mapblock_mesh_generate_special(MeshMakeData *data, MeshCollector &collector) { - INodeDefManager *nodedef = data->m_gamedef->ndef(); - scene::ISceneManager* smgr = data->m_gamedef->getSceneManager(); + INodeDefManager *nodedef = data->m_client->ndef(); + scene::ISceneManager* smgr = data->m_client->getSceneManager(); scene::IMeshManipulator* meshmanip = smgr->getMeshManipulator(); // 0ms -- cgit v1.2.3 From d04d8aba7029a2501854a2838fd282b81358a54e Mon Sep 17 00:00:00 2001 From: Dániel Juhász Date: Thu, 12 Jan 2017 15:46:30 +0100 Subject: Add hardware node coloring. Includes: - Increase ContentFeatures serialization version - Color property and palettes for nodes - paramtype2 = "color", "colored facedir" or "colored wallmounted" --- client/shaders/nodes_shader/opengl_vertex.glsl | 43 +- .../water_surface_shader/opengl_vertex.glsl | 45 +- client/shaders/wielded_shader/opengl_vertex.glsl | 1 - doc/lua_api.txt | 27 +- src/client/tile.cpp | 3 - src/client/tile.h | 34 +- src/clientenvironment.cpp | 4 +- src/content_mapblock.cpp | 326 ++++++++----- src/game.cpp | 30 +- src/mapblock_mesh.cpp | 263 ++++++----- src/mapblock_mesh.h | 57 ++- src/mapnode.cpp | 20 +- src/mapnode.h | 12 +- src/mesh.cpp | 47 +- src/mesh.h | 14 +- src/minimap.cpp | 31 +- src/minimap.h | 4 +- src/network/networkprotocol.h | 5 +- src/nodedef.cpp | 513 +++++++++++++++++---- src/nodedef.h | 108 +++-- src/particles.cpp | 65 ++- src/particles.h | 19 +- src/script/common/c_content.cpp | 18 + src/script/cpp_api/s_node.cpp | 3 + src/shader.cpp | 2 +- src/wieldmesh.cpp | 62 ++- src/wieldmesh.h | 5 + 27 files changed, 1207 insertions(+), 554 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/client/shaders/nodes_shader/opengl_vertex.glsl b/client/shaders/nodes_shader/opengl_vertex.glsl index 44c48cc4c..3ac79c26d 100644 --- a/client/shaders/nodes_shader/opengl_vertex.glsl +++ b/client/shaders/nodes_shader/opengl_vertex.glsl @@ -1,7 +1,8 @@ uniform mat4 mWorldViewProj; uniform mat4 mWorld; -uniform float dayNightRatio; +// Color of the light emitted by the sun. +uniform vec3 dayLight; uniform vec3 eyePosition; uniform float animationTimer; @@ -14,6 +15,8 @@ varying vec3 tsEyeVec; varying vec3 tsLightVec; varying float area_enable_parallax; +// Color of the light emitted by the light sources. +const vec3 artificialLight = vec3(1.04, 1.04, 1.04); const float e = 2.718281828459; const float BS = 10.0; @@ -119,31 +122,23 @@ float disp_z; v.z = dot(eyeVec, normal); tsEyeVec = normalize (v); + // Calculate color. + // Red, green and blue components are pre-multiplied with + // the brightness, so now we have to multiply these + // colors with the color of the incoming light. + // The pre-baked colors are halved to prevent overflow. vec4 color; - float day = gl_Color.r; - float night = gl_Color.g; - float light_source = gl_Color.b; - - float rg = mix(night, day, dayNightRatio); - rg += light_source * 2.5; // Make light sources brighter - float b = rg; - - // Moonlight is blue - b += (day - night) / 13.0; - rg -= (day - night) / 23.0; - + // The alpha gives the ratio of sunlight in the incoming light. + float nightRatio = 1 - gl_Color.a; + color.rgb = gl_Color.rgb * (gl_Color.a * dayLight.rgb + + nightRatio * artificialLight.rgb) * 2; + color.a = 1; + // Emphase blue a bit in darker places // See C++ implementation in mapblock_mesh.cpp finalColorBlend() - b += max(0.0, (1.0 - abs(b - 0.13) / 0.17) * 0.025); - - // Artificial light is yellow-ish - // See C++ implementation in mapblock_mesh.cpp finalColorBlend() - rg += max(0.0, (1.0 - abs(rg - 0.85) / 0.15) * 0.065); - - color.r = rg; - color.g = rg; - color.b = b; - - color.a = gl_Color.a; + float brightness = (color.r + color.g + color.b) / 3; + color.b += max(0.0, 0.021 - abs(0.2 * brightness - 0.021) + + 0.07 * brightness); + gl_FrontColor = gl_BackColor = clamp(color, 0.0, 1.0); } diff --git a/client/shaders/water_surface_shader/opengl_vertex.glsl b/client/shaders/water_surface_shader/opengl_vertex.glsl index a930e7b8f..112db9bb5 100644 --- a/client/shaders/water_surface_shader/opengl_vertex.glsl +++ b/client/shaders/water_surface_shader/opengl_vertex.glsl @@ -1,7 +1,8 @@ uniform mat4 mWorldViewProj; uniform mat4 mWorld; -uniform float dayNightRatio; +// Color of the light emitted by the sun. +uniform vec3 dayLight; uniform vec3 eyePosition; uniform float animationTimer; @@ -13,6 +14,8 @@ varying vec3 lightVec; varying vec3 tsEyeVec; varying vec3 tsLightVec; +// Color of the light emitted by the light sources. +const vec3 artificialLight = vec3(1.04, 1.04, 1.04); const float e = 2.718281828459; const float BS = 10.0; @@ -112,31 +115,23 @@ void main(void) eyeVec = (gl_ModelViewMatrix * gl_Vertex).xyz; tsEyeVec = eyeVec * tbnMatrix; + // Calculate color. + // Red, green and blue components are pre-multiplied with + // the brightness, so now we have to multiply these + // colors with the color of the incoming light. + // The pre-baked colors are halved to prevent overflow. vec4 color; - float day = gl_Color.r; - float night = gl_Color.g; - float light_source = gl_Color.b; - - float rg = mix(night, day, dayNightRatio); - rg += light_source * 2.5; // Make light sources brighter - float b = rg; - - // Moonlight is blue - b += (day - night) / 13.0; - rg -= (day - night) / 23.0; - + // The alpha gives the ratio of sunlight in the incoming light. + float nightRatio = 1 - gl_Color.a; + color.rgb = gl_Color.rgb * (gl_Color.a * dayLight.rgb + + nightRatio * artificialLight.rgb) * 2; + color.a = 1; + // Emphase blue a bit in darker places // See C++ implementation in mapblock_mesh.cpp finalColorBlend() - b += max(0.0, (1.0 - abs(b - 0.13)/0.17) * 0.025); - - // Artificial light is yellow-ish - // See C++ implementation in mapblock_mesh.cpp finalColorBlend() - rg += max(0.0, (1.0 - abs(rg - 0.85)/0.15) * 0.065); - - color.r = rg; - color.g = rg; - color.b = b; - - color.a = gl_Color.a; - gl_FrontColor = gl_BackColor = clamp(color,0.0,1.0); + float brightness = (color.r + color.g + color.b) / 3; + color.b += max(0.0, 0.021 - abs(0.2 * brightness - 0.021) + + 0.07 * brightness); + + gl_FrontColor = gl_BackColor = clamp(color, 0.0, 1.0); } diff --git a/client/shaders/wielded_shader/opengl_vertex.glsl b/client/shaders/wielded_shader/opengl_vertex.glsl index 86c626896..9f05b833a 100644 --- a/client/shaders/wielded_shader/opengl_vertex.glsl +++ b/client/shaders/wielded_shader/opengl_vertex.glsl @@ -1,7 +1,6 @@ uniform mat4 mWorldViewProj; uniform mat4 mWorld; -uniform float dayNightRatio; uniform vec3 eyePosition; uniform float animationTimer; diff --git a/doc/lua_api.txt b/doc/lua_api.txt index e5a3362ee..2a0b72053 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -638,6 +638,19 @@ node definition: bit 4 (0x10) - Makes the plant mesh 1.4x larger bit 5 (0x20) - Moves each face randomly a small bit down (1/8 max) bits 6-7 are reserved for future use. + paramtype2 == "color" + ^ `param2` tells which color is picked from the palette. + The palette should have 256 pixels. + paramtype2 == "colorfacedir" + ^ Same as `facedir`, but with colors. + The first three bits of `param2` tells which color + is picked from the palette. + The palette should have 8 pixels. + paramtype2 == "colorwallmounted" + ^ Same as `wallmounted`, but with colors. + The first five bits of `param2` tells which color + is picked from the palette. + The palette should have 32 pixels. collision_box = { type = "fixed", fixed = { @@ -3707,6 +3720,9 @@ Definition tables when displacement mapping is used Directions are from the point of view of the tile texture, not the node it's on +* `{name="image.png", color=ColorSpec}` + * the texture's color will be multiplied with this color. + * the tile's color overrides the owning node's color in all cases. * deprecated, yet still supported field names: * `image` (name) @@ -3749,8 +3765,17 @@ Definition tables 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 ]] - alpha = 255, + color = ColorSpec, --[[ + ^ The node's original color will be multiplied with this color. + ^ If the node has a palette, then this setting only has an effect + ^ in the inventory and on the wield item. ]] use_texture_alpha = false, -- Use texture's alpha channel + palette = "palette.png", --[[ + ^ The node's `param2` is used to select a pixel from the image + ^ (pixels are arranged from left to right and from top to bottom). + ^ The node's color will be multiplied with the selected pixel's + ^ color. Tiles can override this behavior. + ^ Only when `paramtype2` supports palettes. ]] post_effect_color = "green#0F", -- If player is inside node, see "ColorSpec" paramtype = "none", -- See "Nodes" --[[ ^ paramtype = "light" allows light to propagate from or through the node with light value diff --git a/src/client/tile.cpp b/src/client/tile.cpp index 4d2166342..539c29445 100644 --- a/src/client/tile.cpp +++ b/src/client/tile.cpp @@ -378,9 +378,6 @@ public: video::ITexture* generateTextureFromMesh( const TextureFromMeshParams ¶ms); - // Generates an image from a full string like - // "stone.png^mineral_coal.png^[crack:1:0". - // Shall be called from the main thread. video::IImage* generateImage(const std::string &name); video::ITexture* getNormalTexture(const std::string &name); diff --git a/src/client/tile.h b/src/client/tile.h index 452804801..d04ab918a 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -108,6 +108,12 @@ public: const std::string &name, u32 *id = NULL) = 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; @@ -192,7 +198,6 @@ struct TileSpec texture(NULL), normal_texture(NULL), flags_texture(NULL), - alpha(255), material_type(TILE_MATERIAL_BASIC), material_flags( //0 // <- DEBUG, Use the one below @@ -201,22 +206,30 @@ struct TileSpec shader_id(0), animation_frame_count(1), animation_frame_length_ms(0), - rotation(0) + rotation(0), + has_color(false), + color(), + emissive_light(0) { } + /*! + * Two tiles are equal if they can be appended to + * the same mesh buffer. + */ bool operator==(const TileSpec &other) const { return ( texture_id == other.texture_id && - /* texture == other.texture && */ - alpha == other.alpha && material_type == other.material_type && material_flags == other.material_flags && rotation == other.rotation ); } + /*! + * Two tiles are not equal if they must be in different mesh buffers. + */ bool operator!=(const TileSpec &other) const { return !(*this == other); @@ -233,7 +246,7 @@ struct TileSpec material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; break; case TILE_MATERIAL_LIQUID_TRANSPARENT: - material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; + material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; break; case TILE_MATERIAL_LIQUID_OPAQUE: material.MaterialType = video::EMT_SOLID; @@ -274,8 +287,6 @@ struct TileSpec video::ITexture *normal_texture; video::ITexture *flags_texture; - // Vertex alpha (when MATERIAL_ALPHA_VERTEX is used) - u8 alpha; // Material parameters u8 material_type; u8 material_flags; @@ -286,5 +297,14 @@ struct TileSpec std::vector frames; u8 rotation; + //! If true, the tile has its own color. + bool has_color; + /*! + * 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; + //! This much light does the tile emit. + u8 emissive_light; }; #endif diff --git a/src/clientenvironment.cpp b/src/clientenvironment.cpp index b32a02f2d..77f53d214 100644 --- a/src/clientenvironment.cpp +++ b/src/clientenvironment.cpp @@ -334,9 +334,7 @@ void ClientEnvironment::step(float dtime) node_at_lplayer = m_map->getNodeNoEx(p); u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef()); - u8 day = light & 0xff; - u8 night = (light >> 8) & 0xff; - finalColorBlend(lplayer->light_color, day, night, day_night_ratio); + final_color_blend(&lplayer->light_color, light, day_night_ratio); } /* diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index a7134590b..742bfb1fd 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -32,28 +32,29 @@ with this program; if not, write to the Free Software Foundation, Inc., // Create a cuboid. -// collector - the MeshCollector for the resulting polygons -// box - the position and size of the box -// tiles - the tiles (materials) to use (for all 6 faces) -// tilecount - number of entries in tiles, 1<=tilecount<=6 -// c - vertex colour - used for all -// txc - texture coordinates - this is a list of texture coordinates -// for the opposite corners of each face - therefore, there -// should be (2+2)*6=24 values in the list. Alternatively, pass -// NULL to use the entire texture for each face. The order of -// the faces in the list is up-down-right-left-back-front -// (compatible with ContentFeatures). If you specified 0,0,1,1 -// for each face, that would be the same as passing NULL. +// collector - the MeshCollector for the resulting polygons +// box - the position and size of the box +// tiles - the tiles (materials) to use (for all 6 faces) +// tilecount - number of entries in tiles, 1<=tilecount<=6 +// c - colors of the cuboid's six sides +// txc - texture coordinates - this is a list of texture coordinates +// for the opposite corners of each face - therefore, there +// should be (2+2)*6=24 values in the list. Alternatively, +// pass NULL to use the entire texture for each face. The +// order of the faces in the list is up-down-right-left-back- +// front (compatible with ContentFeatures). If you specified +// 0,0,1,1 for each face, that would be the same as +// passing NULL. +// light source - if greater than zero, the box's faces will not be shaded void makeCuboid(MeshCollector *collector, const aabb3f &box, - TileSpec *tiles, int tilecount, video::SColor &c, const f32* txc) + TileSpec *tiles, int tilecount, const video::SColor *c, + const f32* txc, const u8 light_source) { assert(tilecount >= 1 && tilecount <= 6); // pre-condition v3f min = box.MinEdge; v3f max = box.MaxEdge; - - if(txc == NULL) { static const f32 txc_default[24] = { 0,0,1,1, @@ -66,38 +67,53 @@ void makeCuboid(MeshCollector *collector, const aabb3f &box, txc = txc_default; } + video::SColor c1 = c[0]; + video::SColor c2 = c[1]; + video::SColor c3 = c[2]; + video::SColor c4 = c[3]; + video::SColor c5 = c[4]; + video::SColor c6 = c[5]; + if (!light_source) { + applyFacesShading(c1, v3f(0, 1, 0)); + applyFacesShading(c2, v3f(0, -1, 0)); + applyFacesShading(c3, v3f(1, 0, 0)); + applyFacesShading(c4, v3f(-1, 0, 0)); + applyFacesShading(c5, v3f(0, 0, 1)); + applyFacesShading(c6, v3f(0, 0, -1)); + } + video::S3DVertex vertices[24] = { // up - video::S3DVertex(min.X,max.Y,max.Z, 0,1,0, c, txc[0],txc[1]), - video::S3DVertex(max.X,max.Y,max.Z, 0,1,0, c, txc[2],txc[1]), - video::S3DVertex(max.X,max.Y,min.Z, 0,1,0, c, txc[2],txc[3]), - video::S3DVertex(min.X,max.Y,min.Z, 0,1,0, c, txc[0],txc[3]), + video::S3DVertex(min.X,max.Y,max.Z, 0,1,0, c1, txc[0],txc[1]), + video::S3DVertex(max.X,max.Y,max.Z, 0,1,0, c1, txc[2],txc[1]), + video::S3DVertex(max.X,max.Y,min.Z, 0,1,0, c1, txc[2],txc[3]), + video::S3DVertex(min.X,max.Y,min.Z, 0,1,0, c1, txc[0],txc[3]), // down - video::S3DVertex(min.X,min.Y,min.Z, 0,-1,0, c, txc[4],txc[5]), - video::S3DVertex(max.X,min.Y,min.Z, 0,-1,0, c, txc[6],txc[5]), - video::S3DVertex(max.X,min.Y,max.Z, 0,-1,0, c, txc[6],txc[7]), - video::S3DVertex(min.X,min.Y,max.Z, 0,-1,0, c, txc[4],txc[7]), + video::S3DVertex(min.X,min.Y,min.Z, 0,-1,0, c2, txc[4],txc[5]), + video::S3DVertex(max.X,min.Y,min.Z, 0,-1,0, c2, txc[6],txc[5]), + video::S3DVertex(max.X,min.Y,max.Z, 0,-1,0, c2, txc[6],txc[7]), + video::S3DVertex(min.X,min.Y,max.Z, 0,-1,0, c2, txc[4],txc[7]), // right - video::S3DVertex(max.X,max.Y,min.Z, 1,0,0, c, txc[ 8],txc[9]), - video::S3DVertex(max.X,max.Y,max.Z, 1,0,0, c, txc[10],txc[9]), - video::S3DVertex(max.X,min.Y,max.Z, 1,0,0, c, txc[10],txc[11]), - video::S3DVertex(max.X,min.Y,min.Z, 1,0,0, c, txc[ 8],txc[11]), + video::S3DVertex(max.X,max.Y,min.Z, 1,0,0, c3, txc[ 8],txc[9]), + video::S3DVertex(max.X,max.Y,max.Z, 1,0,0, c3, txc[10],txc[9]), + video::S3DVertex(max.X,min.Y,max.Z, 1,0,0, c3, txc[10],txc[11]), + video::S3DVertex(max.X,min.Y,min.Z, 1,0,0, c3, txc[ 8],txc[11]), // left - video::S3DVertex(min.X,max.Y,max.Z, -1,0,0, c, txc[12],txc[13]), - video::S3DVertex(min.X,max.Y,min.Z, -1,0,0, c, txc[14],txc[13]), - video::S3DVertex(min.X,min.Y,min.Z, -1,0,0, c, txc[14],txc[15]), - video::S3DVertex(min.X,min.Y,max.Z, -1,0,0, c, txc[12],txc[15]), + video::S3DVertex(min.X,max.Y,max.Z, -1,0,0, c4, txc[12],txc[13]), + video::S3DVertex(min.X,max.Y,min.Z, -1,0,0, c4, txc[14],txc[13]), + video::S3DVertex(min.X,min.Y,min.Z, -1,0,0, c4, txc[14],txc[15]), + video::S3DVertex(min.X,min.Y,max.Z, -1,0,0, c4, txc[12],txc[15]), // back - video::S3DVertex(max.X,max.Y,max.Z, 0,0,1, c, txc[16],txc[17]), - video::S3DVertex(min.X,max.Y,max.Z, 0,0,1, c, txc[18],txc[17]), - video::S3DVertex(min.X,min.Y,max.Z, 0,0,1, c, txc[18],txc[19]), - video::S3DVertex(max.X,min.Y,max.Z, 0,0,1, c, txc[16],txc[19]), + video::S3DVertex(max.X,max.Y,max.Z, 0,0,1, c5, txc[16],txc[17]), + video::S3DVertex(min.X,max.Y,max.Z, 0,0,1, c5, txc[18],txc[17]), + video::S3DVertex(min.X,min.Y,max.Z, 0,0,1, c5, txc[18],txc[19]), + video::S3DVertex(max.X,min.Y,max.Z, 0,0,1, c5, txc[16],txc[19]), // front - video::S3DVertex(min.X,max.Y,min.Z, 0,0,-1, c, txc[20],txc[21]), - video::S3DVertex(max.X,max.Y,min.Z, 0,0,-1, c, txc[22],txc[21]), - video::S3DVertex(max.X,min.Y,min.Z, 0,0,-1, c, txc[22],txc[23]), - video::S3DVertex(min.X,min.Y,min.Z, 0,0,-1, c, txc[20],txc[23]), + video::S3DVertex(min.X,max.Y,min.Z, 0,0,-1, c6, txc[20],txc[21]), + video::S3DVertex(max.X,max.Y,min.Z, 0,0,-1, c6, txc[22],txc[21]), + video::S3DVertex(max.X,min.Y,min.Z, 0,0,-1, c6, txc[22],txc[23]), + video::S3DVertex(min.X,min.Y,min.Z, 0,0,-1, c6, txc[20],txc[23]), }; for(int i = 0; i < 6; i++) @@ -164,6 +180,31 @@ void makeCuboid(MeshCollector *collector, const aabb3f &box, } } +// Create a cuboid. +// collector - the MeshCollector for the resulting polygons +// box - the position and size of the box +// tiles - the tiles (materials) to use (for all 6 faces) +// tilecount - number of entries in tiles, 1<=tilecount<=6 +// c - color of the cuboid +// txc - texture coordinates - this is a list of texture coordinates +// for the opposite corners of each face - therefore, there +// should be (2+2)*6=24 values in the list. Alternatively, +// pass NULL to use the entire texture for each face. The +// order of the faces in the list is up-down-right-left-back- +// front (compatible with ContentFeatures). If you specified +// 0,0,1,1 for each face, that would be the same as +// passing NULL. +// light source - if greater than zero, the box's faces will not be shaded +void makeCuboid(MeshCollector *collector, const aabb3f &box, TileSpec *tiles, + int tilecount, const video::SColor &c, const f32* txc, + const u8 light_source) +{ + video::SColor color[6]; + for (u8 i = 0; i < 6; i++) + color[i] = c; + makeCuboid(collector, box, tiles, tilecount, color, txc, light_source); +} + static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef, MeshMakeData *data, MapNode n, int v, int *neighbors) { @@ -181,6 +222,18 @@ static inline int NeighborToIndex(const v3s16 &pos) return 9 * pos.X + 3 * pos.Y + pos.Z + 13; } +/*! + * Returns the i-th special tile for a map node. + */ +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); + return copy; +} + /* TODO: Fix alpha blending for special nodes Currently only the last element rendered is blended correct @@ -227,8 +280,13 @@ void mapblock_mesh_generate_special(MeshMakeData *data, /* Add water sources to mesh if using new style */ - TileSpec tile_liquid = f.special_tiles[0]; + TileSpec tile_liquid = getSpecialTile(f, n, 0); TileSpec tile_liquid_bfculled = getNodeTile(n, p, v3s16(0,0,0), data); + u16 l = getInteriorLight(n, 0, nodedef); + video::SColor c1 = encode_light_and_color(l, + tile_liquid.color, f.light_source); + video::SColor c2 = encode_light_and_color(l, + tile_liquid_bfculled.color, f.light_source); bool top_is_same_liquid = false; MapNode ntop = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x,y+1,z)); @@ -237,9 +295,6 @@ void mapblock_mesh_generate_special(MeshMakeData *data, if(ntop.getContent() == c_flowing || ntop.getContent() == c_source) top_is_same_liquid = true; - u16 l = getInteriorLight(n, 0, nodedef); - video::SColor c = MapBlock_LightColor(f.alpha, l, f.light_source); - /* Generate sides */ @@ -285,15 +340,18 @@ void mapblock_mesh_generate_special(MeshMakeData *data, // Use backface culled material if neighbor doesn't have a // solidness of 0 const TileSpec *current_tile = &tile_liquid; - if(n_feat.solidness != 0 || n_feat.visual_solidness != 0) + video::SColor *c = &c1; + if(n_feat.solidness != 0 || n_feat.visual_solidness != 0) { current_tile = &tile_liquid_bfculled; + c = &c2; + } video::S3DVertex vertices[4] = { - video::S3DVertex(-BS/2,0,BS/2,0,0,0, c, 0,1), - video::S3DVertex(BS/2,0,BS/2,0,0,0, c, 1,1), - video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, 1,0), - video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, 0,0), + video::S3DVertex(-BS/2,0,BS/2,0,0,0, *c, 0,1), + video::S3DVertex(BS/2,0,BS/2,0,0,0, *c, 1,1), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, *c, 1,0), + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, *c, 0,0), }; /* @@ -359,10 +417,10 @@ void mapblock_mesh_generate_special(MeshMakeData *data, video::S3DVertex vertices[4] = { - video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, 0,1), - video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, 1,1), - video::S3DVertex(BS/2,0,-BS/2, 0,0,0, c, 1,0), - video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c, 0,0), + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c1, 0,1), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, c1, 1,1), + video::S3DVertex(BS/2,0,-BS/2, 0,0,0, c1, 1,0), + video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c1, 0,0), }; v3f offset(p.X * BS, (p.Y + 0.5) * BS, p.Z * BS); @@ -380,8 +438,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, /* Add flowing liquid to mesh */ - TileSpec tile_liquid = f.special_tiles[0]; - TileSpec tile_liquid_bfculled = f.special_tiles[1]; + TileSpec tile_liquid = getSpecialTile(f, n, 0); + TileSpec tile_liquid_bfculled = getSpecialTile(f, n, 1); bool top_is_same_liquid = false; MapNode ntop = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x,y+1,z)); @@ -404,7 +462,10 @@ void mapblock_mesh_generate_special(MeshMakeData *data, // Otherwise use the light of this node (the liquid) else l = getInteriorLight(n, 0, nodedef); - video::SColor c = MapBlock_LightColor(f.alpha, l, f.light_source); + video::SColor c1 = encode_light_and_color(l, + tile_liquid.color, f.light_source); + video::SColor c2 = encode_light_and_color(l, + tile_liquid_bfculled.color, f.light_source); u8 range = rangelim(nodedef->get(c_flowing).liquid_range, 1, 8); @@ -552,7 +613,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data, is liquid, don't draw side face */ if (top_is_same_liquid && - neighbor_data.flags & neighborflag_top_is_same_liquid) + (neighbor_data.flags & neighborflag_top_is_same_liquid)) continue; content_t neighbor_content = neighbor_data.content; @@ -574,15 +635,18 @@ void mapblock_mesh_generate_special(MeshMakeData *data, // Use backface culled material if neighbor doesn't have a // solidness of 0 const TileSpec *current_tile = &tile_liquid; - if(n_feat.solidness != 0 || n_feat.visual_solidness != 0) + video::SColor *c = &c1; + if(n_feat.solidness != 0 || n_feat.visual_solidness != 0) { current_tile = &tile_liquid_bfculled; + c = &c2; + } video::S3DVertex vertices[4] = { - video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, 0,1), - video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, 1,1), - video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, 1,0), - video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, 0,0), + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, *c, 0,1), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, *c, 1,1), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, *c, 1,0), + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, *c, 0,0), }; /* @@ -656,10 +720,10 @@ void mapblock_mesh_generate_special(MeshMakeData *data, { video::S3DVertex vertices[4] = { - video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, 0,1), - video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, 1,1), - video::S3DVertex(BS/2,0,-BS/2, 0,0,0, c, 1,0), - video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c, 0,0), + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c1, 0,1), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, c1, 1,1), + video::S3DVertex(BS/2,0,-BS/2, 0,0,0, c1, 1,0), + video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c1, 0,0), }; // To get backface culling right, the vertices need to go @@ -720,8 +784,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, TileSpec tile = getNodeTile(n, p, v3s16(0,0,0), data); u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = MapBlock_LightColor(255, l, f.light_source); - + video::SColor c = encode_light_and_color(l, tile.color, + f.light_source); for(u32 j=0; j<6; j++) { // Check this neighbor @@ -731,13 +795,17 @@ void mapblock_mesh_generate_special(MeshMakeData *data, // Don't make face if neighbor is of same type if(n2.getContent() == n.getContent()) continue; + video::SColor c2=c; + if(!f.light_source) + applyFacesShading(c2, v3f(dir.X, dir.Y, dir.Z)); + // The face at Z+ video::S3DVertex vertices[4] = { - video::S3DVertex(-BS/2,-BS/2,BS/2, dir.X,dir.Y,dir.Z, c, 1,1), - video::S3DVertex(BS/2,-BS/2,BS/2, dir.X,dir.Y,dir.Z, c, 0,1), - video::S3DVertex(BS/2,BS/2,BS/2, dir.X,dir.Y,dir.Z, c, 0,0), - video::S3DVertex(-BS/2,BS/2,BS/2, dir.X,dir.Y,dir.Z, c, 1,0), + video::S3DVertex(-BS/2,-BS/2,BS/2, dir.X,dir.Y,dir.Z, c2, 1,1), + video::S3DVertex(BS/2,-BS/2,BS/2, dir.X,dir.Y,dir.Z, c2, 0,1), + video::S3DVertex(BS/2,BS/2,BS/2, dir.X,dir.Y,dir.Z, c2, 0,0), + video::S3DVertex(-BS/2,BS/2,BS/2, dir.X,dir.Y,dir.Z, c2, 1,0), }; // Rotations in the g_6dirs format @@ -784,12 +852,20 @@ void mapblock_mesh_generate_special(MeshMakeData *data, v3s16( 0, 0,-1) }; + u16 l = getInteriorLight(n, 1, nodedef); u8 i; TileSpec tiles[6]; for (i = 0; i < 6; i++) tiles[i] = getNodeTile(n, p, dirs[i], data); + video::SColor tile0color = encode_light_and_color(l, + tiles[0].color, f.light_source); + video::SColor tile0colors[6]; + for (i = 0; i < 6; i++) + tile0colors[i] = tile0color; + TileSpec glass_tiles[6]; + video::SColor glasscolor[6]; if (tiles[1].texture && tiles[2].texture && tiles[3].texture) { glass_tiles[0] = tiles[2]; glass_tiles[1] = tiles[3]; @@ -801,14 +877,15 @@ void mapblock_mesh_generate_special(MeshMakeData *data, for (i = 0; i < 6; i++) glass_tiles[i] = tiles[1]; } + for (i = 0; i < 6; i++) + glasscolor[i] = encode_light_and_color(l, glass_tiles[i].color, + f.light_source); u8 param2 = n.getParam2(); bool H_merge = ! bool(param2 & 128); bool V_merge = ! bool(param2 & 64); param2 = param2 & 63; - u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = MapBlock_LightColor(255, l, f.light_source); v3f pos = intToFloat(p, BS); static const float a = BS / 2; static const float g = a - 0.003; @@ -947,7 +1024,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, 1-tx2, 1-ty2, 1-tx1, 1-ty1, tx1, 1-ty2, tx2, 1-ty1, }; - makeCuboid(&collector, box, &tiles[0], 1, c, txc1); + makeCuboid(&collector, box, &tiles[0], 1, tile0colors, + txc1, f.light_source); } for(i = 0; i < 6; i++) @@ -971,16 +1049,21 @@ void mapblock_mesh_generate_special(MeshMakeData *data, 1-tx2, 1-ty2, 1-tx1, 1-ty1, tx1, 1-ty2, tx2, 1-ty1, }; - makeCuboid(&collector, box, &glass_tiles[i], 1, c, txc2); + makeCuboid(&collector, box, &glass_tiles[i], 1, glasscolor, + txc2, f.light_source); } if (param2 > 0 && f.special_tiles[0].texture) { // Interior volume level is in range 0 .. 63, // convert it to -0.5 .. 0.5 float vlev = (((float)param2 / 63.0 ) * 2.0 - 1.0); + TileSpec tile=getSpecialTile(f, n, 0); + video::SColor special_color = encode_light_and_color(l, + tile.color, f.light_source); TileSpec interior_tiles[6]; for (i = 0; i < 6; i++) - interior_tiles[i] = f.special_tiles[0]; + interior_tiles[i] = tile; + float offset = 0.003; box = aabb3f(visible_faces[3] ? -b : -a + offset, visible_faces[1] ? -b : -a + offset, @@ -1004,22 +1087,24 @@ void mapblock_mesh_generate_special(MeshMakeData *data, 1-tx2, 1-ty2, 1-tx1, 1-ty1, tx1, 1-ty2, tx2, 1-ty1, }; - makeCuboid(&collector, box, interior_tiles, 6, c, txc3); + makeCuboid(&collector, box, interior_tiles, 6, special_color, + txc3, f.light_source); } break;} case NDT_ALLFACES: { TileSpec tile_leaves = getNodeTile(n, p, v3s16(0,0,0), data); - u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = MapBlock_LightColor(255, l, f.light_source); + video::SColor c = encode_light_and_color(l, + tile_leaves.color, f.light_source); v3f pos = intToFloat(p, BS); aabb3f box(-BS/2,-BS/2,-BS/2,BS/2,BS/2,BS/2); box.MinEdge += pos; box.MaxEdge += pos; - makeCuboid(&collector, box, &tile_leaves, 1, c, NULL); + makeCuboid(&collector, box, &tile_leaves, 1, c, NULL, + f.light_source); break;} case NDT_ALLFACES_OPTIONAL: // This is always pre-converted to something else @@ -1046,7 +1131,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = MapBlock_LightColor(255, l, f.light_source); + video::SColor c = encode_light_and_color(l, tile.color, + f.light_source); float s = BS/2*f.visual_scale; // Wall at X+ of node @@ -1087,7 +1173,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; u16 l = getInteriorLight(n, 0, nodedef); - video::SColor c = MapBlock_LightColor(255, l, f.light_source); + video::SColor c = encode_light_and_color(l, tile.color, + f.light_source); float d = (float)BS/16; float s = BS/2*f.visual_scale; @@ -1132,7 +1219,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = MapBlock_LightColor(255, l, f.light_source); + video::SColor c = encode_light_and_color(l, tile.color, + f.light_source); float s = BS / 2 * f.visual_scale; // add sqrt(2) visual scale @@ -1302,7 +1390,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = MapBlock_LightColor(255, l, f.light_source); + video::SColor c = encode_light_and_color(l, tile.color, + f.light_source); float s = BS / 2 * f.visual_scale; @@ -1437,7 +1526,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, tile_rot.rotation = 1; u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = MapBlock_LightColor(255, l, f.light_source); + video::SColor c = encode_light_and_color(l, tile.color, + f.light_source); const f32 post_rad=(f32)BS/8; const f32 bar_rad=(f32)BS/16; @@ -1456,7 +1546,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, 4/16.,0,8/16.,1, 8/16.,0,12/16.,1, 12/16.,0,16/16.,1}; - makeCuboid(&collector, post, &tile_rot, 1, c, postuv); + makeCuboid(&collector, post, &tile_rot, 1, c, postuv, + f.light_source); // Now a section of fence, +X, if there's a post there v3s16 p2 = p; @@ -1477,11 +1568,11 @@ void mapblock_mesh_generate_special(MeshMakeData *data, 0/16.,8/16.,16/16.,10/16., 0/16.,14/16.,16/16.,16/16.}; makeCuboid(&collector, bar, &tile_nocrack, 1, - c, xrailuv); + c, xrailuv, f.light_source); bar.MinEdge.Y -= BS/2; bar.MaxEdge.Y -= BS/2; makeCuboid(&collector, bar, &tile_nocrack, 1, - c, xrailuv); + c, xrailuv, f.light_source); } // Now a section of fence, +Z, if there's a post there @@ -1503,11 +1594,11 @@ void mapblock_mesh_generate_special(MeshMakeData *data, 6/16.,6/16.,8/16.,8/16., 10/16.,10/16.,12/16.,12/16.}; makeCuboid(&collector, bar, &tile_nocrack, 1, - c, zrailuv); + c, zrailuv, f.light_source); bar.MinEdge.Y -= BS/2; bar.MaxEdge.Y -= BS/2; makeCuboid(&collector, bar, &tile_nocrack, 1, - c, zrailuv); + c, zrailuv, f.light_source); } break;} case NDT_RAILLIKE: @@ -1616,7 +1707,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; u16 l = getInteriorLight(n, 0, nodedef); - video::SColor c = MapBlock_LightColor(255, l, f.light_source); + video::SColor c = encode_light_and_color(l, tile.color, + f.light_source); float d = (float)BS/64; float s = BS/2; @@ -1627,10 +1719,10 @@ void mapblock_mesh_generate_special(MeshMakeData *data, video::S3DVertex vertices[4] = { - video::S3DVertex(-s, -s+d,-s, 0,0,0, c,0,1), - video::S3DVertex( s, -s+d,-s, 0,0,0, c,1,1), - video::S3DVertex( s, g*s+d, s, 0,0,0, c,1,0), - video::S3DVertex(-s, g*s+d, s, 0,0,0, c,0,0), + video::S3DVertex(-s, -s+d, -s, 0, 0, 0, c, 0, 1), + video::S3DVertex( s, -s+d, -s, 0, 0, 0, c, 1, 1), + video::S3DVertex( s, g*s+d, s, 0, 0, 0, c, 1, 0), + video::S3DVertex(-s, g*s+d, s, 0, 0, 0, c, 0, 0), }; for(s32 i=0; i<4; i++) @@ -1653,10 +1745,16 @@ void mapblock_mesh_generate_special(MeshMakeData *data, v3s16(0, 0, 1), v3s16(0, 0, -1) }; - TileSpec tiles[6]; u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = MapBlock_LightColor(255, l, f.light_source); + TileSpec tiles[6]; + video::SColor colors[6]; + for(int j = 0; j < 6; j++) { + // Handles facedir rotation for textures + tiles[j] = getNodeTile(n, p, tile_dirs[j], data); + colors[j]= encode_light_and_color(l, tiles[j].color, + f.light_source); + } v3f pos = intToFloat(p, BS); @@ -1696,11 +1794,6 @@ void mapblock_mesh_generate_special(MeshMakeData *data, i = boxes.begin(); i != boxes.end(); ++i) { - for(int j = 0; j < 6; j++) - { - // Handles facedir rotation for textures - tiles[j] = getNodeTile(n, p, tile_dirs[j], data); - } aabb3f box = *i; box.MinEdge += pos; box.MaxEdge += pos; @@ -1747,18 +1840,19 @@ void mapblock_mesh_generate_special(MeshMakeData *data, // front tx1, 1-ty2, tx2, 1-ty1, }; - makeCuboid(&collector, box, tiles, 6, c, txc); + makeCuboid(&collector, box, tiles, 6, colors, txc, f.light_source); } break;} case NDT_MESH: { v3f pos = intToFloat(p, BS); - video::SColor c = MapBlock_LightColor(255, getInteriorLight(n, 1, nodedef), f.light_source); - + u16 l = getInteriorLight(n, 1, nodedef); u8 facedir = 0; - if (f.param_type_2 == CPT2_FACEDIR) { + if (f.param_type_2 == CPT2_FACEDIR || + f.param_type_2 == CPT2_COLORED_FACEDIR) { facedir = n.getFaceDir(nodedef); - } else if (f.param_type_2 == CPT2_WALLMOUNTED) { + } else if (f.param_type_2 == CPT2_WALLMOUNTED || + f.param_type_2 == CPT2_COLORED_WALLMOUNTED) { //convert wallmounted to 6dfacedir. //when cache enabled, it is already converted facedir = n.getWallMounted(nodedef); @@ -1771,10 +1865,13 @@ void mapblock_mesh_generate_special(MeshMakeData *data, if (f.mesh_ptr[facedir]) { // use cached meshes for(u16 j = 0; j < f.mesh_ptr[0]->getMeshBufferCount(); j++) { + const TileSpec &tile = getNodeTileN(n, p, j, data); scene::IMeshBuffer *buf = f.mesh_ptr[facedir]->getMeshBuffer(j); - collector.append(getNodeTileN(n, p, j, data), - (video::S3DVertex *)buf->getVertices(), buf->getVertexCount(), - buf->getIndices(), buf->getIndexCount(), pos, c); + collector.append(tile, (video::S3DVertex *) + buf->getVertices(), buf->getVertexCount(), + buf->getIndices(), buf->getIndexCount(), pos, + encode_light_and_color(l, tile.color, f.light_source), + f.light_source); } } else if (f.mesh_ptr[0]) { // no cache, clone and rotate mesh @@ -1783,10 +1880,13 @@ void mapblock_mesh_generate_special(MeshMakeData *data, recalculateBoundingBox(mesh); meshmanip->recalculateNormals(mesh, true, false); for(u16 j = 0; j < mesh->getMeshBufferCount(); j++) { + const TileSpec &tile = getNodeTileN(n, p, j, data); scene::IMeshBuffer *buf = mesh->getMeshBuffer(j); - collector.append(getNodeTileN(n, p, j, data), - (video::S3DVertex *)buf->getVertices(), buf->getVertexCount(), - buf->getIndices(), buf->getIndexCount(), pos, c); + collector.append(tile, (video::S3DVertex *) + buf->getVertices(), buf->getVertexCount(), + buf->getIndices(), buf->getIndexCount(), pos, + encode_light_and_color(l, tile.color, f.light_source), + f.light_source); } mesh->drop(); } diff --git a/src/game.cpp b/src/game.cpp index 1070cb1b2..07d429c6b 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -642,7 +642,7 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter CachedPixelShaderSetting m_fog_distance; CachedVertexShaderSetting m_animation_timer_vertex; CachedPixelShaderSetting m_animation_timer_pixel; - CachedPixelShaderSetting m_day_night_ratio; + CachedPixelShaderSetting m_day_light; CachedPixelShaderSetting m_eye_position_pixel; CachedVertexShaderSetting m_eye_position_vertex; CachedPixelShaderSetting m_minimap_yaw; @@ -674,7 +674,7 @@ public: m_fog_distance("fogDistance"), m_animation_timer_vertex("animationTimer"), m_animation_timer_pixel("animationTimer"), - m_day_night_ratio("dayNightRatio"), + m_day_light("dayLight"), m_eye_position_pixel("eyePosition"), m_eye_position_vertex("eyePosition"), m_minimap_yaw("yawVec"), @@ -717,8 +717,14 @@ public: m_fog_distance.set(&fog_distance, services); - float daynight_ratio = (float)m_client->getEnv().getDayNightRatio() / 1000.f; - m_day_night_ratio.set(&daynight_ratio, services); + u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio(); + video::SColorf sunlight; + get_sunlight_color(&sunlight, daynight_ratio); + float dnc[3] = { + sunlight.r, + sunlight.g, + sunlight.b }; + m_day_light.set(dnc, services); u32 animation_timer = porting::getTimeMs() % 100000; float animation_timer_f = (float)animation_timer / 100000.f; @@ -840,7 +846,8 @@ bool nodePlacementPrediction(Client &client, // Predict param2 for facedir and wallmounted nodes u8 param2 = 0; - if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) { + if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED || + nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) { v3s16 dir = nodepos - neighbourpos; if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) { @@ -852,7 +859,8 @@ bool nodePlacementPrediction(Client &client, } } - if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) { + if (nodedef->get(id).param_type_2 == CPT2_FACEDIR || + nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) { v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS); if (abs(dir.X) > abs(dir.Z)) { @@ -3749,11 +3757,9 @@ PointedThing Game::updatePointedThing( light_level = node_light; } - video::SColor c = MapBlock_LightColor(255, light_level, 0); - u8 day = c.getRed(); - u8 night = c.getGreen(); u32 daynight_ratio = client->getEnv().getDayNightRatio(); - finalColorBlend(c, day, night, daynight_ratio); + video::SColor c; + final_color_blend(&c, light_level, daynight_ratio); // Modify final color a bit with time u32 timer = porting::getTimeMs() % 5000; @@ -3964,7 +3970,7 @@ void Game::handleDigging(GameRunData *runData, const ContentFeatures &features = client->getNodeDefManager()->get(n); client->getParticleManager()->addPunchingParticles(client, smgr, - player, nodepos, features.tiles); + player, nodepos, n, features); } } @@ -4011,7 +4017,7 @@ void Game::handleDigging(GameRunData *runData, const ContentFeatures &features = client->getNodeDefManager()->get(wasnode); client->getParticleManager()->addDiggingParticles(client, smgr, - player, nodepos, features.tiles); + player, nodepos, wasnode, features); } runData->dig_time = 0; diff --git a/src/mapblock_mesh.cpp b/src/mapblock_mesh.cpp index 143adb410..dfd6f55a5 100644 --- a/src/mapblock_mesh.cpp +++ b/src/mapblock_mesh.cpp @@ -32,12 +32,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/directiontables.h" #include -static void applyFacesShading(video::SColor &color, const float factor) -{ - color.setRed(core::clamp(core::round32(color.getRed() * factor), 0, 255)); - color.setGreen(core::clamp(core::round32(color.getGreen() * factor), 0, 255)); -} - /* MeshMakeData */ @@ -321,19 +315,34 @@ u16 getSmoothLight(v3s16 p, v3s16 corner, MeshMakeData *data) return getSmoothLightCombined(p, data); } -/* - Converts from day + night color values (0..255) - and a given daynight_ratio to the final SColor shown on screen. -*/ -void finalColorBlend(video::SColor& result, - u8 day, u8 night, u32 daynight_ratio) +void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio){ + f32 rg = daynight_ratio / 1000.0f - 0.04f; + f32 b = (0.98f * daynight_ratio) / 1000.0f + 0.078f; + sunlight->r = rg; + sunlight->g = rg; + sunlight->b = b; +} + +void final_color_blend(video::SColor *result, + u16 light, u32 daynight_ratio) { - s32 rg = (day * daynight_ratio + night * (1000-daynight_ratio)) / 1000; - s32 b = rg; + video::SColorf dayLight; + get_sunlight_color(&dayLight, daynight_ratio); + final_color_blend(result, + encode_light_and_color(light, video::SColor(0xFFFFFFFF), 0), dayLight); +} - // Moonlight is blue - b += (day - night) / 13; - rg -= (day - night) / 23; +void final_color_blend(video::SColor *result, + const video::SColor &data, const video::SColorf &dayLight) +{ + static const video::SColorf artificialColor(1.04f, 1.04f, 1.04f); + + video::SColorf c(data); + f32 n = 1 - c.a; + + f32 r = c.r * (c.a * dayLight.r + n * artificialColor.r) * 2.0f; + f32 g = c.g * (c.a * dayLight.g + n * artificialColor.g) * 2.0f; + f32 b = c.b * (c.a * dayLight.b + n * artificialColor.b) * 2.0f; // Emphase blue a bit in darker places // Each entry of this array represents a range of 8 blue levels @@ -341,19 +350,13 @@ void finalColorBlend(video::SColor& result, 1, 4, 6, 6, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; - b += emphase_blue_when_dark[irr::core::clamp(b, 0, 255) / 8]; - b = irr::core::clamp(b, 0, 255); - // Artificial light is yellow-ish - static const u8 emphase_yellow_when_artificial[16] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 15, 15, 15 - }; - rg += emphase_yellow_when_artificial[night/16]; - rg = irr::core::clamp(rg, 0, 255); + b += emphase_blue_when_dark[irr::core::clamp((s32) ((r + g + b) / 3 * 255), + 0, 255) / 8] / 255.0f; - result.setRed(rg); - result.setGreen(rg); - result.setBlue(b); + result->setRed(core::clamp((s32) (r * 255.0f), 0, 255)); + result->setGreen(core::clamp((s32) (g * 255.0f), 0, 255)); + result->setBlue(core::clamp((s32) (b * 255.0f), 0, 255)); } /* @@ -430,7 +433,7 @@ struct FastFace }; static void makeFastFace(TileSpec tile, u16 li0, u16 li1, u16 li2, u16 li3, - v3f p, v3s16 dir, v3f scale, u8 light_source, std::vector &dest) + v3f p, v3s16 dir, v3f scale, std::vector &dest) { // Position is at the center of the cube. v3f pos = p * BS; @@ -580,24 +583,25 @@ static void makeFastFace(TileSpec tile, u16 li0, u16 li1, u16 li2, u16 li3, v3f normal(dir.X, dir.Y, dir.Z); - u8 alpha = tile.alpha; - dest.push_back(FastFace()); FastFace& face = *dest.rbegin(); - face.vertices[0] = video::S3DVertex(vertex_pos[0], normal, - MapBlock_LightColor(alpha, li0, light_source), - core::vector2d(x0+w*abs_scale, y0+h)); - face.vertices[1] = video::S3DVertex(vertex_pos[1], normal, - MapBlock_LightColor(alpha, li1, light_source), - core::vector2d(x0, y0+h)); - face.vertices[2] = video::S3DVertex(vertex_pos[2], normal, - MapBlock_LightColor(alpha, li2, light_source), - core::vector2d(x0, y0)); - face.vertices[3] = video::S3DVertex(vertex_pos[3], normal, - MapBlock_LightColor(alpha, li3, light_source), - core::vector2d(x0+w*abs_scale, y0)); + 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); + + face.vertices[i] = video::S3DVertex(vertex_pos[i], normal, c, f[i]); + } face.tile = tile; } @@ -664,7 +668,10 @@ static u8 face_contents(content_t m1, content_t m2, bool *equivalent, TileSpec getNodeTileN(MapNode mn, v3s16 p, u8 tileindex, MeshMakeData *data) { INodeDefManager *ndef = data->m_client->ndef(); - TileSpec spec = ndef->get(mn).tiles[tileindex]; + const ContentFeatures &f = ndef->get(mn); + TileSpec spec = f.tiles[tileindex]; + if (!spec.has_color) + mn.getColor(f, &spec.color); // Apply temporary crack if (p == data->m_crack_pos_relative) spec.material_flags |= MATERIAL_FLAG_CRACK; @@ -747,8 +754,7 @@ static void getTileInfo( v3s16 &p_corrected, v3s16 &face_dir_corrected, u16 *lights, - TileSpec &tile, - u8 &light_source + TileSpec &tile ) { VoxelManipulator &vmanip = data->m_vmanip; @@ -763,7 +769,8 @@ static void getTileInfo( return; } - const MapNode &n1 = vmanip.getNodeRefUnsafeCheckFlags(blockpos_nodes + p + face_dir); + const MapNode &n1 = vmanip.getNodeRefUnsafeCheckFlags( + blockpos_nodes + p + face_dir); if (n1.getContent() == CONTENT_IGNORE) { makes_face = false; @@ -783,26 +790,25 @@ static void getTileInfo( makes_face = true; - if(mf == 1) - { - tile = getNodeTile(n0, p, face_dir, data); + MapNode n = n0; + + if (mf == 1) { p_corrected = p; face_dir_corrected = face_dir; - light_source = ndef->get(n0).light_source; - } - else - { - tile = getNodeTile(n1, p + face_dir, -face_dir, data); + } else { + n = n1; p_corrected = p + face_dir; face_dir_corrected = -face_dir; - light_source = ndef->get(n1).light_source; } + tile = getNodeTile(n, p_corrected, face_dir_corrected, data); + const ContentFeatures &f = ndef->get(n); + tile.emissive_light = f.light_source; // eg. water and glass - if(equivalent) + if (equivalent) tile.material_flags |= MATERIAL_FLAG_BACKFACE_CULLING; - if(data->m_smooth_lighting == false) + if (data->m_smooth_lighting == false) { lights[0] = lights[1] = lights[2] = lights[3] = getFaceLight(n0, n1, face_dir, ndef); @@ -845,10 +851,9 @@ static void updateFastFaceRow( v3s16 face_dir_corrected; u16 lights[4] = {0,0,0,0}; TileSpec tile; - u8 light_source = 0; getTileInfo(data, p, face_dir, makes_face, p_corrected, face_dir_corrected, - lights, tile, light_source); + lights, tile); for(u16 j=0; javg("Meshgen: faces drawn by tiling", 0); for(int i = 1; i < continuous_tiles_count; i++){ @@ -958,7 +962,6 @@ static void updateFastFaceRow( lights[2] = next_lights[2]; lights[3] = next_lights[3]; tile = next_tile; - light_source = next_light_source; p = p_next; } } @@ -1083,12 +1086,14 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): const u16 *indices_p = indices; /* - Revert triangles for nicer looking gradient if vertices - 1 and 3 have same color or 0 and 2 have different color. - getRed() is the day color. + 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(f.vertices[0].Color.getRed() != f.vertices[2].Color.getRed() - || f.vertices[1].Color.getRed() == f.vertices[3].Color.getRed()) + if (abs(f.vertices[0].Color.getAverage() + - f.vertices[2].Color.getAverage()) + > abs(f.vertices[1].Color.getAverage() + - f.vertices[3].Color.getAverage())) indices_p = indices_alternate; collector.append(f.tile, f.vertices, 4, indices_p, 6); @@ -1148,43 +1153,30 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): p.tile.texture = animation_frame.texture; } - u32 vertex_count = m_use_tangent_vertices ? - p.tangent_vertices.size() : p.vertices.size(); - for (u32 j = 0; j < vertex_count; j++) { - v3f *Normal; - video::SColor *vc; - if (m_use_tangent_vertices) { - vc = &p.tangent_vertices[j].Color; - Normal = &p.tangent_vertices[j].Normal; - } else { - vc = &p.vertices[j].Color; - Normal = &p.vertices[j].Normal; - } - // Note applyFacesShading second parameter is precalculated sqrt - // value for speed improvement - // Skip it for lightsources and top faces. - if (!vc->getBlue()) { - if (Normal->Y < -0.5) { - applyFacesShading(*vc, 0.447213); - } else if (Normal->X > 0.5) { - applyFacesShading(*vc, 0.670820); - } else if (Normal->X < -0.5) { - applyFacesShading(*vc, 0.670820); - } else if (Normal->Z > 0.5) { - applyFacesShading(*vc, 0.836660); - } else if (Normal->Z < -0.5) { - applyFacesShading(*vc, 0.836660); - } - } - if (!m_enable_shaders) { - // - Classic lighting (shaders handle this by themselves) - // Set initial real color and store for later updates - u8 day = vc->getRed(); - u8 night = vc->getGreen(); - finalColorBlend(*vc, day, night, 1000); - if (day != night) { - m_daynight_diffs[i][j] = std::make_pair(day, night); + 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[i][j] = copy; + + // The sunlight ratio has been stored, + // delete alpha (for the final rendering). + vc->setAlpha(255); } } @@ -1358,19 +1350,19 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat if (m_enable_vbo) { m_mesh->setDirty(); } - for(std::map > >::iterator + video::SColorf day_color; + get_sunlight_color(&day_color, daynight_ratio); + for(std::map >::iterator i = m_daynight_diffs.begin(); i != m_daynight_diffs.end(); ++i) { scene::IMeshBuffer *buf = m_mesh->getMeshBuffer(i->first); video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices(); - for(std::map >::iterator + for(std::map::iterator j = i->second.begin(); j != i->second.end(); ++j) { - u8 day = j->second.first; - u8 night = j->second.second; - finalColorBlend(vertices[j->first].Color, day, night, daynight_ratio); + final_color_blend(&(vertices[j->first].Color), j->second, day_color); } } m_last_daynight_ratio = daynight_ratio; @@ -1452,7 +1444,7 @@ void MeshCollector::append(const TileSpec &tile, void MeshCollector::append(const TileSpec &tile, const video::S3DVertex *vertices, u32 numVertices, const u16 *indices, u32 numIndices, - v3f pos, video::SColor c) + v3f pos, video::SColor c, u8 light_source) { if (numIndices > 65535) { dstream<<"FIXME: MeshCollector::append() called with numIndices="<tangent_vertices.size(); for (u32 i = 0; i < numVertices; i++) { + if (!light_source) { + c = original_c; + applyFacesShading(c, vertices[i].Normal); + } video::S3DVertexTangents vert(vertices[i].Pos + pos, vertices[i].Normal, c, vertices[i].TCoords); p->tangent_vertices.push_back(vert); @@ -1489,8 +1486,12 @@ void MeshCollector::append(const TileSpec &tile, } else { vertex_count = p->vertices.size(); for (u32 i = 0; i < numVertices; i++) { - video::S3DVertex vert(vertices[i].Pos + pos, - vertices[i].Normal, c, vertices[i].TCoords); + if (!light_source) { + c = original_c; + applyFacesShading(c, vertices[i].Normal); + } + video::S3DVertex vert(vertices[i].Pos + pos, vertices[i].Normal, c, + vertices[i].TCoords); p->vertices.push_back(vert); } } @@ -1500,3 +1501,33 @@ void MeshCollector::append(const TileSpec &tile, p->indices.push_back(j); } } + +video::SColor encode_light_and_color(u16 light, const video::SColor &color, + u8 emissive_light) +{ + // Get components + f32 day = (light & 0xff) / 255.0f; + f32 night = (light >> 8) / 255.0f; + // Add emissive light + night += emissive_light * 0.01f; + if (night > 255) + night = 255; + // Since we don't know if the day light is sunlight or + // artificial light, assume it is artificial when the night + // light bank is also lit. + if (day < night) + day = 0; + else + day = day - night; + f32 sum = day + night; + // Ratio of sunlight: + float r; + if (sum > 0) + r = day / 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()); +} diff --git a/src/mapblock_mesh.h b/src/mapblock_mesh.h index 5adb7df3f..916703f3e 100644 --- a/src/mapblock_mesh.h +++ b/src/mapblock_mesh.h @@ -156,8 +156,8 @@ private: // Animation info: day/night transitions // Last daynight_ratio value passed to animate() u32 m_last_daynight_ratio; - // For each meshbuffer, maps vertex indices to (day,night) pairs - std::map > > m_daynight_diffs; + // For each meshbuffer, stores pre-baked colors of sunlit vertices + std::map > m_daynight_diffs; // Camera offset info -> do we have to translate the mesh? v3s16 m_camera_offset; @@ -192,28 +192,53 @@ struct MeshCollector void append(const TileSpec &material, const video::S3DVertex *vertices, u32 numVertices, const u16 *indices, u32 numIndices, - v3f pos, video::SColor c); + v3f pos, video::SColor c, u8 light_source); }; -// This encodes -// alpha in the A channel of the returned SColor -// day light (0-255) in the R channel of the returned SColor -// night light (0-255) in the G channel of the returned SColor -// light source (0-255) in the B channel of the returned SColor -inline video::SColor MapBlock_LightColor(u8 alpha, u16 light, u8 light_source=0) -{ - return video::SColor(alpha, (light & 0xff), (light >> 8), light_source); -} +/*! + * Encodes light and color of a node. + * The result is not the final color, but a + * half-baked vertex 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); // Compute light at node u16 getInteriorLight(MapNode n, s32 increment, INodeDefManager *ndef); u16 getFaceLight(MapNode n, MapNode n2, v3s16 face_dir, INodeDefManager *ndef); u16 getSmoothLight(v3s16 p, v3s16 corner, MeshMakeData *data); -// Converts from day + night color values (0..255) -// and a given daynight_ratio to the final SColor shown on screen. -void finalColorBlend(video::SColor& result, - u8 day, u8 night, u32 daynight_ratio); +/*! + * Returns the sunlight's color from the current + * day-night ratio. + */ +void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio); + +/*! + * Gives the final SColor shown on screen. + * + * \param result output color + * \param light first 8 bits are day light, second 8 bits are + * night light + */ +void final_color_blend(video::SColor *result, + u16 light, u32 daynight_ratio); + +/*! + * Gives the final SColor shown on screen. + * + * \param result output color + * \param data the half-baked vertex color + * \param dayLight color of the sunlight + */ +void final_color_blend(video::SColor *result, + const video::SColor &data, const video::SColorf &dayLight); // Retrieves the TileSpec of a face of a node // Adds MATERIAL_FLAG_CRACK if the node is cracked diff --git a/src/mapnode.cpp b/src/mapnode.cpp index f1a7f3e61..d835daba2 100644 --- a/src/mapnode.cpp +++ b/src/mapnode.cpp @@ -55,6 +55,15 @@ MapNode::MapNode(INodeDefManager *ndef, const std::string &name, param2 = a_param2; } +void MapNode::getColor(const ContentFeatures &f, video::SColor *color) const +{ + if (f.palette) { + *color = (*f.palette)[param2]; + return; + } + *color = f.color; +} + void MapNode::setLight(enum LightBank bank, u8 a_light, const ContentFeatures &f) { // If node doesn't contain light data, ignore this @@ -146,7 +155,8 @@ bool MapNode::getLightBanks(u8 &lightday, u8 &lightnight, INodeDefManager *nodem u8 MapNode::getFaceDir(INodeDefManager *nodemgr) const { const ContentFeatures &f = nodemgr->get(*this); - if(f.param_type_2 == CPT2_FACEDIR) + if (f.param_type_2 == CPT2_FACEDIR || + f.param_type_2 == CPT2_COLORED_FACEDIR) return (getParam2() & 0x1F) % 24; return 0; } @@ -154,7 +164,8 @@ u8 MapNode::getFaceDir(INodeDefManager *nodemgr) const u8 MapNode::getWallMounted(INodeDefManager *nodemgr) const { const ContentFeatures &f = nodemgr->get(*this); - if(f.param_type_2 == CPT2_WALLMOUNTED) + if (f.param_type_2 == CPT2_WALLMOUNTED || + f.param_type_2 == CPT2_COLORED_WALLMOUNTED) return getParam2() & 0x07; return 0; } @@ -176,7 +187,7 @@ void MapNode::rotateAlongYAxis(INodeDefManager *nodemgr, Rotation rot) { ContentParamType2 cpt2 = nodemgr->get(*this).param_type_2; - if (cpt2 == CPT2_FACEDIR) { + if (cpt2 == CPT2_FACEDIR || cpt2 == CPT2_COLORED_FACEDIR) { static const u8 rotate_facedir[24 * 4] = { // Table value = rotated facedir // Columns: 0, 90, 180, 270 degrees rotation around vertical axis @@ -216,7 +227,8 @@ void MapNode::rotateAlongYAxis(INodeDefManager *nodemgr, Rotation rot) u8 index = facedir * 4 + rot; param2 &= ~31; param2 |= rotate_facedir[index]; - } else if (cpt2 == CPT2_WALLMOUNTED) { + } else if (cpt2 == CPT2_WALLMOUNTED || + cpt2 == CPT2_COLORED_WALLMOUNTED) { u8 wmountface = (param2 & 7); if (wmountface <= 1) return; diff --git a/src/mapnode.h b/src/mapnode.h index ae0245cfe..9c56a7e17 100644 --- a/src/mapnode.h +++ b/src/mapnode.h @@ -20,9 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifndef MAPNODE_HEADER #define MAPNODE_HEADER -#include "irrlichttypes.h" -#include "irr_v3d.h" -#include "irr_aabb3d.h" +#include "irrlichttypes_bloated.h" #include "light.h" #include #include @@ -187,6 +185,14 @@ struct MapNode param2 = p; } + /*! + * Returns the color of the node. + * + * \param f content features of this node + * \param color output, contains the node's color. + */ + void getColor(const ContentFeatures &f, video::SColor *color) const; + void setLight(enum LightBank bank, u8 a_light, const ContentFeatures &f); void setLight(enum LightBank bank, u8 a_light, INodeDefManager *nodemgr); diff --git a/src/mesh.cpp b/src/mesh.cpp index 50465748c..84689b631 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -33,13 +33,25 @@ with this program; if not, write to the Free Software Foundation, Inc., #define MY_ETLM_READ_ONLY video::ETLM_READ_ONLY #endif -static void applyFacesShading(video::SColor& color, float factor) +inline static void applyShadeFactor(video::SColor& color, float factor) { color.setRed(core::clamp(core::round32(color.getRed()*factor), 0, 255)); color.setGreen(core::clamp(core::round32(color.getGreen()*factor), 0, 255)); color.setBlue(core::clamp(core::round32(color.getBlue()*factor), 0, 255)); } +void applyFacesShading(video::SColor &color, const v3f &normal) +{ + // Many special drawtypes have normals set to 0,0,0 and this + // must result in maximum brightness (no face shadng). + if (normal.Y < -0.5f) + applyShadeFactor (color, 0.447213f); + else if (normal.X > 0.5f || normal.X < -0.5f) + applyShadeFactor (color, 0.670820f); + else if (normal.Z > 0.5f || normal.Z < -0.5f) + applyShadeFactor (color, 0.836660f); +} + scene::IAnimatedMesh* createCubeMesh(v3f scale) { video::SColor c(255,255,255,255); @@ -172,29 +184,18 @@ void setMeshColor(scene::IMesh *mesh, const video::SColor &color) } } -void shadeMeshFaces(scene::IMesh *mesh) +void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolor) { - if (mesh == NULL) - 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 *vertex = (video::S3DVertex *)(vertices + i * stride); - video::SColor &vc = vertex->Color; - // Many special drawtypes have normals set to 0,0,0 and this - // must result in maximum brightness (no face shadng). - if (vertex->Normal.Y < -0.5f) - applyFacesShading (vc, 0.447213f); - else if (vertex->Normal.X > 0.5f || vertex->Normal.X < -0.5f) - applyFacesShading (vc, 0.670820f); - else if (vertex->Normal.Z > 0.5f || vertex->Normal.Z < -0.5f) - applyFacesShading (vc, 0.836660f); - } + 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 *vertex = (video::S3DVertex *) (vertices + i * stride); + video::SColor *vc = &(vertex->Color); + // Reset color + *vc = *buffercolor; + // Apply shading + applyFacesShading(*vc, vertex->Normal); } } diff --git a/src/mesh.h b/src/mesh.h index 10df97015..bcf0d771c 100644 --- a/src/mesh.h +++ b/src/mesh.h @@ -23,6 +23,12 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "irrlichttypes_extrabloated.h" #include "nodedef.h" +/*! + * Applies shading to a color based on the surface's + * normal vector. + */ +void applyFacesShading(video::SColor &color, const v3f &normal); + /* Create a new cube mesh. Vertices are at (+-scale.X/2, +-scale.Y/2, +-scale.Z/2). @@ -48,11 +54,7 @@ void translateMesh(scene::IMesh *mesh, v3f vec); */ void setMeshColor(scene::IMesh *mesh, const video::SColor &color); -/* - Shade mesh faces according to their normals -*/ - -void shadeMeshFaces(scene::IMesh *mesh); +void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolor); /* Set the color of all vertices in the mesh. @@ -87,7 +89,7 @@ void rotateMeshYZby (scene::IMesh *mesh, f64 degrees); scene::IMesh* cloneMesh(scene::IMesh *src_mesh); /* - Convert nodeboxes to mesh. + Convert nodeboxes to mesh. Each tile goes into a different buffer. boxes - set of nodeboxes to be converted into cuboids uv_coords[24] - table of texture uv coords for each cuboid face expand - factor by which cuboids will be resized diff --git a/src/minimap.cpp b/src/minimap.cpp index f49adb517..a2e501751 100644 --- a/src/minimap.cpp +++ b/src/minimap.cpp @@ -144,7 +144,7 @@ MinimapPixel *MinimapUpdateThread::getMinimapPixel(v3s16 pos, if (it != m_blocks_cache.end()) { MinimapMapblock *mmblock = it->second; MinimapPixel *pixel = &mmblock->data[relpos.Z * MAP_BLOCKSIZE + relpos.X]; - if (pixel->id != CONTENT_AIR) { + if (pixel->n.param0 != CONTENT_AIR) { *pixel_height = height + pixel->height; return pixel; } @@ -187,7 +187,7 @@ void MinimapUpdateThread::getMap(v3s16 pos, s16 size, s16 height, bool is_radar) for (s16 x = 0; x < size; x++) for (s16 z = 0; z < size; z++) { - u16 id = CONTENT_AIR; + MapNode n(CONTENT_AIR); MinimapPixel *mmpixel = &data->minimap_scan[x + z * size]; if (!is_radar) { @@ -195,14 +195,14 @@ void MinimapUpdateThread::getMap(v3s16 pos, s16 size, s16 height, bool is_radar) MinimapPixel *cached_pixel = getMinimapPixel(v3s16(p.X + x, p.Y, p.Z + z), height, &pixel_height); if (cached_pixel) { - id = cached_pixel->id; + n = cached_pixel->n; mmpixel->height = pixel_height; } } else { mmpixel->air_count = getAirCount(v3s16(p.X + x, p.Y, p.Z + z), height); } - mmpixel->id = id; + mmpixel->n = n; } } @@ -372,10 +372,21 @@ void Mapper::blitMinimapPixelsToImageSurface( for (s16 z = 0; z < data->map_size; z++) { MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size]; - video::SColor c = m_ndef->get(mmpixel->id).minimap_color; - c.setAlpha(240); - - map_image->setPixel(x, data->map_size - z - 1, c); + const ContentFeatures &f = m_ndef->get(mmpixel->n); + const TileDef *tile = &f.tiledef[0]; + // Color of the 0th tile (mostly this is the topmost) + video::SColor tilecolor; + if(tile->has_color) + tilecolor = tile->color; + else + mmpixel->n.getColor(f, &tilecolor); + tilecolor.setRed(tilecolor.getRed() * f.minimap_color.getRed() / 255); + tilecolor.setGreen(tilecolor.getGreen() * f.minimap_color.getGreen() + / 255); + tilecolor.setBlue(tilecolor.getBlue() * f.minimap_color.getBlue() / 255); + tilecolor.setAlpha(240); + + map_image->setPixel(x, data->map_size - z - 1, tilecolor); u32 h = mmpixel->height; heightmap_image->setPixel(x,data->map_size - z - 1, @@ -617,7 +628,7 @@ void MinimapMapblock::getMinimapNodes(VoxelManipulator *vmanip, v3s16 pos) MapNode n = vmanip->getNodeNoEx(pos + p); if (!surface_found && n.getContent() != CONTENT_AIR) { mmpixel->height = y; - mmpixel->id = n.getContent(); + mmpixel->n = n; surface_found = true; } else if (n.getContent() == CONTENT_AIR) { air_count++; @@ -625,7 +636,7 @@ void MinimapMapblock::getMinimapNodes(VoxelManipulator *vmanip, v3s16 pos) } if (!surface_found) - mmpixel->id = CONTENT_AIR; + mmpixel->n = MapNode(CONTENT_AIR); mmpixel->air_count = air_count; } diff --git a/src/minimap.h b/src/minimap.h index 743b2bff2..81ed0e49f 100644 --- a/src/minimap.h +++ b/src/minimap.h @@ -52,10 +52,10 @@ struct MinimapModeDef { }; struct MinimapPixel { - u16 id; + //! The topmost node that the minimap displays. + MapNode n; u16 height; u16 air_count; - u16 light; }; struct MinimapMapblock { diff --git a/src/network/networkprotocol.h b/src/network/networkprotocol.h index 23c8a665b..a511d169b 100644 --- a/src/network/networkprotocol.h +++ b/src/network/networkprotocol.h @@ -143,9 +143,12 @@ with this program; if not, write to the Free Software Foundation, Inc., serialization of TileAnimation params changed TAT_SHEET_2D Removed client-sided chat perdiction + PROTOCOL VERSION 30: + New ContentFeatures serialization version + Add node and tile color and palette */ -#define LATEST_PROTOCOL_VERSION 29 +#define LATEST_PROTOCOL_VERSION 30 // Server's supported network protocol range #define SERVER_PROTOCOL_VERSION_MIN 13 diff --git a/src/nodedef.cpp b/src/nodedef.cpp index a4af26e87..98f795c7a 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -189,7 +189,9 @@ void NodeBox::deSerialize(std::istream &is) void TileDef::serialize(std::ostream &os, u16 protocol_version) const { - if (protocol_version >= 29) + if (protocol_version >= 30) + writeU8(os, 4); + else if (protocol_version >= 29) writeU8(os, 3); else if (protocol_version >= 26) writeU8(os, 2); @@ -205,6 +207,14 @@ void TileDef::serialize(std::ostream &os, u16 protocol_version) const writeU8(os, tileable_horizontal); writeU8(os, tileable_vertical); } + if (protocol_version >= 30) { + writeU8(os, has_color); + if (has_color) { + writeU8(os, color.getRed()); + writeU8(os, color.getGreen()); + writeU8(os, color.getBlue()); + } + } } void TileDef::deSerialize(std::istream &is, const u8 contenfeatures_version, const NodeDrawType drawtype) @@ -218,6 +228,14 @@ void TileDef::deSerialize(std::istream &is, const u8 contenfeatures_version, con tileable_horizontal = readU8(is); tileable_vertical = readU8(is); } + if (version >= 4) { + has_color = readU8(is); + if (has_color) { + color.setRed(readU8(is)); + color.setGreen(readU8(is)); + color.setBlue(readU8(is)); + } + } if ((contenfeatures_version < 8) && ((drawtype == NDT_MESH) || @@ -351,172 +369,222 @@ void ContentFeatures::reset() connects_to.clear(); connects_to_ids.clear(); connect_sides = 0; + color = video::SColor(0xFFFFFFFF); + palette_name = ""; + palette = NULL; } void ContentFeatures::serialize(std::ostream &os, u16 protocol_version) const { - if(protocol_version < 24){ + if (protocol_version < 30) { serializeOld(os, protocol_version); return; } - writeU8(os, protocol_version < 27 ? 7 : 8); + // version + writeU8(os, 9); - os<first); + for (ItemGroupList::const_iterator i = groups.begin(); i != groups.end(); + ++i) { + os << serializeString(i->first); writeS16(os, i->second); } + writeU8(os, param_type); + writeU8(os, param_type_2); + + // visual writeU8(os, drawtype); + os << serializeString(mesh); writeF1000(os, visual_scale); writeU8(os, 6); - for(u32 i = 0; i < 6; i++) + for (u32 i = 0; i < 6; i++) tiledef[i].serialize(os, protocol_version); writeU8(os, CF_SPECIAL_COUNT); - for(u32 i = 0; i < CF_SPECIAL_COUNT; i++){ + for (u32 i = 0; i < CF_SPECIAL_COUNT; i++) { tiledef_special[i].serialize(os, protocol_version); } writeU8(os, alpha); + writeU8(os, color.getRed()); + writeU8(os, color.getGreen()); + writeU8(os, color.getBlue()); + os << serializeString(palette_name); + writeU8(os, waving); + writeU8(os, connect_sides); + writeU16(os, connects_to_ids.size()); + for (std::set::const_iterator i = connects_to_ids.begin(); + i != connects_to_ids.end(); ++i) + writeU16(os, *i); writeU8(os, post_effect_color.getAlpha()); writeU8(os, post_effect_color.getRed()); writeU8(os, post_effect_color.getGreen()); writeU8(os, post_effect_color.getBlue()); - writeU8(os, param_type); - if ((protocol_version < 28) && (param_type_2 == CPT2_MESHOPTIONS)) - writeU8(os, CPT2_NONE); - else - writeU8(os, param_type_2); - writeU8(os, is_ground_content); + writeU8(os, leveled); + + // lighting writeU8(os, light_propagates); writeU8(os, sunlight_propagates); + writeU8(os, light_source); + + // map generation + writeU8(os, is_ground_content); + + // interaction writeU8(os, walkable); writeU8(os, pointable); writeU8(os, diggable); writeU8(os, climbable); writeU8(os, buildable_to); - os<::const_iterator i = connects_to_ids.begin(); - i != connects_to_ids.end(); ++i) - writeU16(os, *i); - writeU8(os, connect_sides); + + // legacy + writeU8(os, legacy_facedir_simple); + writeU8(os, legacy_wallmounted); +} + +void ContentFeatures::correctAlpha() +{ + if (alpha == 0 || alpha == 255) + return; + + for (u32 i = 0; i < 6; i++) { + std::stringstream s; + s << tiledef[i].name << "^[noalpha^[opacity:" << ((int)alpha); + tiledef[i].name = s.str(); + } + + for (u32 i = 0; i < CF_SPECIAL_COUNT; i++) { + std::stringstream s; + s << tiledef_special[i].name << "^[noalpha^[opacity:" << ((int)alpha); + tiledef_special[i].name = s.str(); + } } void ContentFeatures::deSerialize(std::istream &is) { + // version detection int version = readU8(is); - if (version < 7) { + if (version < 9) { deSerializeOld(is, version); return; - } else if (version > 8) { + } else if (version > 9) { throw SerializationError("unsupported ContentFeatures version"); } + // general name = deSerializeString(is); groups.clear(); u32 groups_size = readU16(is); - for(u32 i = 0; i < groups_size; i++){ + for (u32 i = 0; i < groups_size; i++) { std::string name = deSerializeString(is); int value = readS16(is); groups[name] = value; } - drawtype = (enum NodeDrawType)readU8(is); + param_type = (enum ContentParamType) readU8(is); + param_type_2 = (enum ContentParamType2) readU8(is); + // visual + drawtype = (enum NodeDrawType) readU8(is); + mesh = deSerializeString(is); visual_scale = readF1000(is); - if(readU8(is) != 6) + if (readU8(is) != 6) throw SerializationError("unsupported tile count"); - for(u32 i = 0; i < 6; i++) + for (u32 i = 0; i < 6; i++) tiledef[i].deSerialize(is, version, drawtype); - if(readU8(is) != CF_SPECIAL_COUNT) + if (readU8(is) != CF_SPECIAL_COUNT) throw SerializationError("unsupported CF_SPECIAL_COUNT"); - for(u32 i = 0; i < CF_SPECIAL_COUNT; i++) + for (u32 i = 0; i < CF_SPECIAL_COUNT; i++) tiledef_special[i].deSerialize(is, version, drawtype); alpha = readU8(is); + color.setRed(readU8(is)); + color.setGreen(readU8(is)); + color.setBlue(readU8(is)); + palette_name = deSerializeString(is); + waving = readU8(is); + connect_sides = readU8(is); + u16 connects_to_size = readU16(is); + connects_to_ids.clear(); + for (u16 i = 0; i < connects_to_size; i++) + connects_to_ids.insert(readU16(is)); post_effect_color.setAlpha(readU8(is)); post_effect_color.setRed(readU8(is)); post_effect_color.setGreen(readU8(is)); post_effect_color.setBlue(readU8(is)); - param_type = (enum ContentParamType)readU8(is); - param_type_2 = (enum ContentParamType2)readU8(is); - is_ground_content = readU8(is); + leveled = readU8(is); + + // lighting-related light_propagates = readU8(is); sunlight_propagates = readU8(is); + light_source = readU8(is); + light_source = MYMIN(light_source, LIGHT_MAX); + + // map generation + is_ground_content = readU8(is); + + // interaction walkable = readU8(is); pointable = readU8(is); diggable = readU8(is); climbable = readU8(is); buildable_to = readU8(is); - deSerializeString(is); // legacy: used to be metadata_name - liquid_type = (enum LiquidType)readU8(is); + rightclickable = readU8(is); + damage_per_second = readU32(is); + + // liquid + liquid_type = (enum LiquidType) readU8(is); liquid_alternative_flowing = deSerializeString(is); liquid_alternative_source = deSerializeString(is); liquid_viscosity = readU8(is); liquid_renewable = readU8(is); - light_source = readU8(is); - light_source = MYMIN(light_source, LIGHT_MAX); - damage_per_second = readU32(is); + liquid_range = readU8(is); + drowning = readU8(is); + floodable = readU8(is); + + // node boxes node_box.deSerialize(is); selection_box.deSerialize(is); - legacy_facedir_simple = readU8(is); - legacy_wallmounted = readU8(is); + collision_box.deSerialize(is); + + // sounds deSerializeSimpleSoundSpec(sound_footstep, is); deSerializeSimpleSoundSpec(sound_dig, is); deSerializeSimpleSoundSpec(sound_dug, is); - rightclickable = readU8(is); - drowning = readU8(is); - leveled = readU8(is); - liquid_range = readU8(is); - waving = readU8(is); - // If you add anything here, insert it primarily inside the try-catch - // block to not need to increase the version. - try{ - // Stuff below should be moved to correct place in a version that - // otherwise changes the protocol version - mesh = deSerializeString(is); - collision_box.deSerialize(is); - floodable = readU8(is); - u16 connects_to_size = readU16(is); - connects_to_ids.clear(); - for (u16 i = 0; i < connects_to_size; i++) - connects_to_ids.insert(readU16(is)); - connect_sides = readU8(is); - }catch(SerializationError &e) {}; + + // read legacy properties + legacy_facedir_simple = readU8(is); + legacy_wallmounted = readU8(is); } #ifndef SERVER void ContentFeatures::fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, TileDef *tiledef, u32 shader_id, bool use_normal_texture, - bool backface_culling, u8 alpha, u8 material_type) + bool backface_culling, u8 material_type) { tile->shader_id = shader_id; tile->texture = tsrc->getTextureForMesh(tiledef->name, &tile->texture_id); - tile->alpha = alpha; tile->material_type = material_type; // Normal texture and shader flags texture @@ -536,6 +604,13 @@ void ContentFeatures::fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, if (tiledef->tileable_vertical) tile->material_flags |= MATERIAL_FLAG_TILEABLE_VERTICAL; + // Color + tile->has_color = tiledef->has_color; + if (tiledef->has_color) + tile->color = tiledef->color; + else + tile->color = color; + // Animation parameters int frame_count = 1; if (tile->material_flags & MATERIAL_FLAG_ANIMATION) { @@ -681,6 +756,9 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc is_water_surface = true; } + // Vertex alpha is no longer supported, correct if necessary. + correctAlpha(); + u32 tile_shader[6]; for (u16 j = 0; j < 6; j++) { tile_shader[j] = shdsrc->getShader("nodes_shader", @@ -696,14 +774,14 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc for (u16 j = 0; j < 6; j++) { fillTileAttribs(tsrc, &tiles[j], &tdef[j], tile_shader[j], tsettings.use_normal_texture, - tiledef[j].backface_culling, alpha, material_type); + 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], tile_shader[j], tsettings.use_normal_texture, - tiledef_special[j].backface_culling, alpha, material_type); + tiledef_special[j].backface_culling, material_type); } if ((drawtype == NDT_MESH) && (mesh != "")) { @@ -731,15 +809,19 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc } //Cache 6dfacedir and wallmounted rotated clones of meshes - if (tsettings.enable_mesh_cache && mesh_ptr[0] && (param_type_2 == CPT2_FACEDIR)) { + if (tsettings.enable_mesh_cache && mesh_ptr[0] && + (param_type_2 == CPT2_FACEDIR + || param_type_2 == CPT2_COLORED_FACEDIR)) { for (u16 j = 1; j < 24; j++) { mesh_ptr[j] = cloneMesh(mesh_ptr[0]); rotateMeshBy6dFacedir(mesh_ptr[j], j); recalculateBoundingBox(mesh_ptr[j]); meshmanip->recalculateNormals(mesh_ptr[j], true, false); } - } else if (tsettings.enable_mesh_cache && mesh_ptr[0] && (param_type_2 == CPT2_WALLMOUNTED)) { - static const u8 wm_to_6d[6] = {20, 0, 16+1, 12+3, 8, 4+2}; + } else if (tsettings.enable_mesh_cache && mesh_ptr[0] + && (param_type_2 == CPT2_WALLMOUNTED || + param_type_2 == CPT2_COLORED_WALLMOUNTED)) { + static const u8 wm_to_6d[6] = { 20, 0, 16 + 1, 12 + 3, 8, 4 + 2 }; for (u16 j = 1; j < 6; j++) { mesh_ptr[j] = cloneMesh(mesh_ptr[0]); rotateMeshBy6dFacedir(mesh_ptr[j], wm_to_6d[j]); @@ -775,6 +857,9 @@ 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); @@ -823,6 +908,9 @@ 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; @@ -1062,7 +1150,8 @@ void getNodeBoxUnion(const NodeBox &nodebox, const ContentFeatures &features, if (nodebox.type == NODEBOX_LEVELED) { half_processed.MaxEdge.Y = +BS / 2; } - if (features.param_type_2 == CPT2_FACEDIR) { + if (features.param_type_2 == CPT2_FACEDIR || + features.param_type_2 == CPT2_COLORED_FACEDIR) { // Get maximal coordinate f32 coords[] = { fabsf(half_processed.MinEdge.X), @@ -1309,6 +1398,78 @@ 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) @@ -1325,10 +1486,13 @@ 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++) { - m_content_features[i].updateTextures(tsrc, shdsrc, meshmanip, client, tsettings); + 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); } #endif @@ -1429,6 +1593,19 @@ IWritableNodeDefManager *createNodeDefManager() //// Serialization of old ContentFeatures formats void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const { + u8 compatible_param_type_2 = param_type_2; + if ((protocol_version < 28) + && (compatible_param_type_2 == CPT2_MESHOPTIONS)) + compatible_param_type_2 = CPT2_NONE; + else if (protocol_version < 30) { + if (compatible_param_type_2 == CPT2_COLOR) + compatible_param_type_2 = CPT2_NONE; + else if (compatible_param_type_2 == CPT2_COLORED_FACEDIR) + compatible_param_type_2 = CPT2_FACEDIR; + else if (compatible_param_type_2 == CPT2_COLORED_WALLMOUNTED) + compatible_param_type_2 = CPT2_WALLMOUNTED; + } + if (protocol_version == 13) { writeU8(os, 5); // version @@ -1454,7 +1631,7 @@ void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const writeU8(os, post_effect_color.getGreen()); writeU8(os, post_effect_color.getBlue()); writeU8(os, param_type); - writeU8(os, param_type_2); + writeU8(os, compatible_param_type_2); writeU8(os, is_ground_content); writeU8(os, light_propagates); writeU8(os, sunlight_propagates); @@ -1483,9 +1660,9 @@ void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const os<first); - writeS16(os, i->second); + i = groups.begin(); i != groups.end(); ++i) { + os<first); + writeS16(os, i->second); } writeU8(os, drawtype); writeF1000(os, visual_scale); @@ -1502,7 +1679,7 @@ void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const writeU8(os, post_effect_color.getGreen()); writeU8(os, post_effect_color.getBlue()); writeU8(os, param_type); - writeU8(os, param_type_2); + writeU8(os, compatible_param_type_2); writeU8(os, is_ground_content); writeU8(os, light_propagates); writeU8(os, sunlight_propagates); @@ -1530,6 +1707,68 @@ void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const writeU8(os, drowning); writeU8(os, leveled); writeU8(os, liquid_range); + } + else if(protocol_version >= 24 && protocol_version < 30) { + writeU8(os, protocol_version < 27 ? 7 : 8); + + os << serializeString(name); + writeU16(os, groups.size()); + for (ItemGroupList::const_iterator i = groups.begin(); + i != groups.end(); ++i) { + os << serializeString(i->first); + writeS16(os, i->second); + } + writeU8(os, drawtype); + writeF1000(os, visual_scale); + writeU8(os, 6); + for (u32 i = 0; i < 6; i++) + tiledef[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); + writeU8(os, alpha); + writeU8(os, post_effect_color.getAlpha()); + writeU8(os, post_effect_color.getRed()); + writeU8(os, post_effect_color.getGreen()); + writeU8(os, post_effect_color.getBlue()); + writeU8(os, param_type); + writeU8(os, compatible_param_type_2); + writeU8(os, is_ground_content); + writeU8(os, light_propagates); + writeU8(os, sunlight_propagates); + writeU8(os, walkable); + writeU8(os, pointable); + writeU8(os, diggable); + writeU8(os, climbable); + writeU8(os, buildable_to); + os << serializeString(""); // legacy: used to be metadata_name + writeU8(os, liquid_type); + os << serializeString(liquid_alternative_flowing); + os << serializeString(liquid_alternative_source); + writeU8(os, liquid_viscosity); + writeU8(os, liquid_renewable); + writeU8(os, light_source); + writeU32(os, damage_per_second); + node_box.serialize(os, protocol_version); + selection_box.serialize(os, protocol_version); + writeU8(os, legacy_facedir_simple); + writeU8(os, legacy_wallmounted); + serializeSimpleSoundSpec(sound_footstep, os); + serializeSimpleSoundSpec(sound_dig, os); + serializeSimpleSoundSpec(sound_dug, os); + writeU8(os, rightclickable); + writeU8(os, drowning); + writeU8(os, leveled); + writeU8(os, liquid_range); + writeU8(os, waving); + os << serializeString(mesh); + collision_box.serialize(os, protocol_version); + writeU8(os, floodable); + writeU16(os, connects_to_ids.size()); + for (std::set::const_iterator i = connects_to_ids.begin(); + i != connects_to_ids.end(); ++i) + writeU16(os, *i); + writeU8(os, connect_sides); } else throw SerializationError("ContentFeatures::serialize(): " "Unsupported version requested"); @@ -1642,7 +1881,73 @@ void ContentFeatures::deSerializeOld(std::istream &is, int version) drowning = readU8(is); leveled = readU8(is); liquid_range = readU8(is); - } else { + } else if (version == 7 || version == 8){ + name = deSerializeString(is); + groups.clear(); + u32 groups_size = readU16(is); + for (u32 i = 0; i < groups_size; i++) { + std::string name = deSerializeString(is); + int value = readS16(is); + groups[name] = value; + } + drawtype = (enum NodeDrawType) readU8(is); + + visual_scale = readF1000(is); + if (readU8(is) != 6) + throw SerializationError("unsupported tile count"); + for (u32 i = 0; i < 6; i++) + tiledef[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++) + tiledef_special[i].deSerialize(is, version, drawtype); + alpha = readU8(is); + post_effect_color.setAlpha(readU8(is)); + post_effect_color.setRed(readU8(is)); + post_effect_color.setGreen(readU8(is)); + post_effect_color.setBlue(readU8(is)); + param_type = (enum ContentParamType) readU8(is); + param_type_2 = (enum ContentParamType2) readU8(is); + is_ground_content = readU8(is); + light_propagates = readU8(is); + sunlight_propagates = readU8(is); + walkable = readU8(is); + pointable = readU8(is); + diggable = readU8(is); + climbable = readU8(is); + buildable_to = readU8(is); + deSerializeString(is); // legacy: used to be metadata_name + liquid_type = (enum LiquidType) readU8(is); + liquid_alternative_flowing = deSerializeString(is); + liquid_alternative_source = deSerializeString(is); + liquid_viscosity = readU8(is); + liquid_renewable = readU8(is); + light_source = readU8(is); + light_source = MYMIN(light_source, LIGHT_MAX); + damage_per_second = readU32(is); + node_box.deSerialize(is); + selection_box.deSerialize(is); + legacy_facedir_simple = readU8(is); + legacy_wallmounted = readU8(is); + deSerializeSimpleSoundSpec(sound_footstep, is); + deSerializeSimpleSoundSpec(sound_dig, is); + deSerializeSimpleSoundSpec(sound_dug, is); + rightclickable = readU8(is); + drowning = readU8(is); + leveled = readU8(is); + liquid_range = readU8(is); + waving = readU8(is); + try { + mesh = deSerializeString(is); + collision_box.deSerialize(is); + floodable = readU8(is); + u16 connects_to_size = readU16(is); + connects_to_ids.clear(); + for (u16 i = 0; i < connects_to_size; i++) + connects_to_ids.insert(readU16(is)); + connect_sides = readU8(is); + } catch (SerializationError &e) {}; + }else{ throw SerializationError("unsupported ContentFeatures version"); } } @@ -1736,19 +2041,23 @@ bool CNodeDefManager::nodeboxConnects(MapNode from, MapNode to, u8 connect_face) // does to node declare usable faces? if (f2.connect_sides > 0) { - if ((f2.param_type_2 == CPT2_FACEDIR) && (connect_face >= 4)) { - static const u8 rot[33 * 4] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 4, 32, 16, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 - back - 8, 4, 32, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 - right - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 8, 4, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - front - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 32, 16, 8, 4 // 32 - left - }; - return (f2.connect_sides & rot[(connect_face * 4) + to.param2]); + if ((f2.param_type_2 == CPT2_FACEDIR || + f2.param_type_2 == CPT2_COLORED_FACEDIR) + && (connect_face >= 4)) { + static const u8 rot[33 * 4] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 4, 32, 16, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 4 - back + 8, 4, 32, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 8 - right + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 8, 4, 32, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 16 - front + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 32, 16, 8, 4 // 32 - left + }; + return (f2.connect_sides + & rot[(connect_face * 4) + (to.param2 & 0x1F)]); } return (f2.connect_sides & connect_face); } diff --git a/src/nodedef.h b/src/nodedef.h index 183b95d87..6275b41ce 100644 --- a/src/nodedef.h +++ b/src/nodedef.h @@ -68,7 +68,13 @@ enum ContentParamType2 // 2D rotation for things like plants CPT2_DEGROTATE, // Mesh options for plants - CPT2_MESHOPTIONS + CPT2_MESHOPTIONS, + // Index for palette + CPT2_COLOR, + // 3 bits of palette index, then facedir + CPT2_COLORED_FACEDIR, + // 5 bits of palette index, then wallmounted + CPT2_COLORED_WALLMOUNTED }; enum LiquidType @@ -170,6 +176,11 @@ struct TileDef bool backface_culling; // Takes effect only in special cases bool tileable_horizontal; bool tileable_vertical; + //! If true, the tile has its own color. + bool has_color; + //! The color of the tile. + video::SColor color; + struct TileAnimationParams animation; TileDef() @@ -178,6 +189,8 @@ struct TileDef backface_culling = true; tileable_horizontal = true; tileable_vertical = true; + has_color = false; + color = video::SColor(0xFFFFFFFF); animation.type = TAT_NONE; } @@ -191,7 +204,7 @@ struct ContentFeatures { /* Cached stuff - */ + */ #ifndef SERVER // 0 1 2 3 4 5 // up down right left back front @@ -211,12 +224,19 @@ struct ContentFeatures /* Actual data - */ + */ + + // --- GENERAL PROPERTIES --- std::string name; // "" = undefined node ItemGroupList groups; // Same as in itemdef + // Type of MapNode::param1 + ContentParamType param_type; + // Type of MapNode::param2 + ContentParamType2 param_type_2; + + // --- VISUAL PROPERTIES --- - // Visual definition enum NodeDrawType drawtype; std::string mesh; #ifndef SERVER @@ -226,19 +246,38 @@ struct ContentFeatures float visual_scale; // Misc. scale parameter TileDef tiledef[6]; TileDef tiledef_special[CF_SPECIAL_COUNT]; // eg. flowing liquid + // If 255, the node is opaque. + // Otherwise it uses texture alpha. u8 alpha; - + // The color of the node. + video::SColor color; + std::string palette_name; + std::vector *palette; + // Used for waving leaves/plants + u8 waving; + // for NDT_CONNECTED pairing + u8 connect_sides; + std::vector connects_to; + std::set connects_to_ids; // Post effect color, drawn when the camera is inside the node. video::SColor post_effect_color; + // Flowing liquid or snow, value = default level + u8 leveled; + + // --- LIGHTING-RELATED --- - // Type of MapNode::param1 - ContentParamType param_type; - // Type of MapNode::param2 - ContentParamType2 param_type_2; - // True for all ground-like things like stone and mud, false for eg. trees - bool is_ground_content; bool light_propagates; bool sunlight_propagates; + // Amount of light the node emits + u8 light_source; + + // --- MAP GENERATION --- + + // True for all ground-like things like stone and mud, false for eg. trees + bool is_ground_content; + + // --- INTERACTION PROPERTIES --- + // This is used for collision detection. // Also for general solidness queries. bool walkable; @@ -250,12 +289,12 @@ struct ContentFeatures bool climbable; // Player can build on these bool buildable_to; - // Liquids flow into and replace node - bool floodable; // Player cannot build to these (placement prediction disabled) bool rightclickable; - // Flowing liquid or snow, value = default level - u8 leveled; + u32 damage_per_second; + + // --- LIQUID PROPERTIES --- + // Whether the node is non-liquid, source liquid or flowing liquid enum LiquidType liquid_type; // If the content is liquid, this is the flowing version of the liquid. @@ -271,29 +310,28 @@ struct ContentFeatures // Number of flowing liquids surrounding source u8 liquid_range; u8 drowning; - // Amount of light the node emits - u8 light_source; - u32 damage_per_second; + // Liquids flow into and replace node + bool floodable; + + // --- NODEBOXES --- + NodeBox node_box; NodeBox selection_box; NodeBox collision_box; - // Used for waving leaves/plants - u8 waving; - // Compatibility with old maps - // Set to true if paramtype used to be 'facedir_simple' - bool legacy_facedir_simple; - // Set to true if wall_mounted used to be set to true - bool legacy_wallmounted; - // for NDT_CONNECTED pairing - u8 connect_sides; - // Sound properties + // --- SOUND PROPERTIES --- + SimpleSoundSpec sound_footstep; SimpleSoundSpec sound_dig; SimpleSoundSpec sound_dug; - std::vector connects_to; - std::set connects_to_ids; + // --- LEGACY --- + + // Compatibility with old maps + // Set to true if paramtype used to be 'facedir_simple' + bool legacy_facedir_simple; + // Set to true if wall_mounted used to be set to true + bool legacy_wallmounted; /* Methods @@ -306,6 +344,14 @@ struct ContentFeatures void deSerialize(std::istream &is); void serializeOld(std::ostream &os, u16 protocol_version) const; void deSerializeOld(std::istream &is, int version); + /*! + * Since vertex alpha is no lnger supported, this method + * adds instructions to the texture names to blend alpha there. + * + * tiledef, tiledef_special and alpha must be initialized + * before calling this. + */ + void correctAlpha(); /* Some handy methods @@ -321,7 +367,7 @@ struct ContentFeatures #ifndef SERVER void fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, TileDef *tiledef, u32 shader_id, bool use_normal_texture, bool backface_culling, - u8 alpha, u8 material_type); + u8 material_type); void updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc, scene::IMeshManipulator *meshmanip, Client *client, const TextureSettings &tsettings); #endif diff --git a/src/particles.cpp b/src/particles.cpp index 5f17763e0..e1f292fb6 100644 --- a/src/particles.cpp +++ b/src/particles.cpp @@ -56,7 +56,8 @@ Particle::Particle( v2f texpos, v2f texsize, const struct TileAnimationParams &anim, - u8 glow + u8 glow, + video::SColor color ): scene::ISceneNode(smgr->getRootSceneNode(), smgr) { @@ -77,6 +78,10 @@ Particle::Particle( m_animation_frame = 0; m_animation_time = 0.0; + // Color + m_base_color = color; + m_color = color; + // Particle related m_pos = pos; m_velocity = velocity; @@ -183,12 +188,15 @@ void Particle::updateLight() else light = blend_light(m_env->getDayNightRatio(), LIGHT_SUN, 0); - m_light = decode_light(light + m_glow); + u8 m_light = decode_light(light + m_glow); + m_color.set(255, + m_light * m_base_color.getRed() / 255, + m_light * m_base_color.getGreen() / 255, + m_light * m_base_color.getBlue() / 255); } void Particle::updateVertices() { - video::SColor c(255, m_light, m_light, m_light); f32 tx0, tx1, ty0, ty1; if (m_animation.type != TAT_NONE) { @@ -210,14 +218,14 @@ void Particle::updateVertices() ty1 = m_texpos.Y + m_texsize.Y; } - m_vertices[0] = video::S3DVertex(-m_size/2,-m_size/2,0, 0,0,0, - c, tx0, ty1); - m_vertices[1] = video::S3DVertex(m_size/2,-m_size/2,0, 0,0,0, - c, tx1, ty1); - m_vertices[2] = video::S3DVertex(m_size/2,m_size/2,0, 0,0,0, - c, tx1, ty0); - m_vertices[3] = video::S3DVertex(-m_size/2,m_size/2,0, 0,0,0, - c, tx0, ty0); + m_vertices[0] = video::S3DVertex(-m_size / 2, -m_size / 2, + 0, 0, 0, 0, m_color, tx0, ty1); + m_vertices[1] = video::S3DVertex(m_size / 2, -m_size / 2, + 0, 0, 0, 0, m_color, tx1, ty1); + m_vertices[2] = video::S3DVertex(m_size / 2, m_size / 2, + 0, 0, 0, 0, m_color, tx1, ty0); + m_vertices[3] = video::S3DVertex(-m_size / 2, m_size / 2, + 0, 0, 0, 0, m_color, tx0, ty0); v3s16 camera_offset = m_env->getCameraOffset(); for(u16 i=0; i<4; i++) @@ -589,35 +597,39 @@ void ParticleManager::handleParticleEvent(ClientEvent *event, Client *client, } } -void ParticleManager::addDiggingParticles(IGameDef* gamedef, scene::ISceneManager* smgr, - LocalPlayer *player, v3s16 pos, const TileSpec tiles[]) +void ParticleManager::addDiggingParticles(IGameDef* gamedef, + scene::ISceneManager* smgr, LocalPlayer *player, v3s16 pos, + const MapNode &n, const ContentFeatures &f) { for (u16 j = 0; j < 32; j++) // set the amount of particles here { - addNodeParticle(gamedef, smgr, player, pos, tiles); + addNodeParticle(gamedef, smgr, player, pos, n, f); } } -void ParticleManager::addPunchingParticles(IGameDef* gamedef, scene::ISceneManager* smgr, - LocalPlayer *player, v3s16 pos, const TileSpec tiles[]) +void ParticleManager::addPunchingParticles(IGameDef* gamedef, + scene::ISceneManager* smgr, LocalPlayer *player, v3s16 pos, + const MapNode &n, const ContentFeatures &f) { - addNodeParticle(gamedef, smgr, player, pos, tiles); + addNodeParticle(gamedef, smgr, player, pos, n, f); } -void ParticleManager::addNodeParticle(IGameDef* gamedef, scene::ISceneManager* smgr, - LocalPlayer *player, v3s16 pos, const TileSpec tiles[]) +void ParticleManager::addNodeParticle(IGameDef* gamedef, + scene::ISceneManager* smgr, LocalPlayer *player, v3s16 pos, + const MapNode &n, const ContentFeatures &f) { // Texture u8 texid = myrand_range(0, 5); + const TileSpec &tile = f.tiles[texid]; video::ITexture *texture; struct TileAnimationParams anim; anim.type = TAT_NONE; // Only use first frame of animated texture - if (tiles[texid].material_flags & MATERIAL_FLAG_ANIMATION) - texture = tiles[texid].frames[0].texture; + if (tile.material_flags & MATERIAL_FLAG_ANIMATION) + texture = tile.frames[0].texture; else - texture = tiles[texid].texture; + texture = tile.texture; float size = rand() % 64 / 512.; float visual_size = BS * size; @@ -638,6 +650,12 @@ void ParticleManager::addNodeParticle(IGameDef* gamedef, scene::ISceneManager* s (f32) pos.Z + rand() %100 /200. - 0.25 ); + video::SColor color; + if (tile.has_color) + color = tile.color; + else + n.getColor(f, &color); + Particle* toadd = new Particle( gamedef, smgr, @@ -655,7 +673,8 @@ void ParticleManager::addNodeParticle(IGameDef* gamedef, scene::ISceneManager* s texpos, texsize, anim, - 0); + 0, + color); addParticle(toadd); } diff --git a/src/particles.h b/src/particles.h index 5464e6672..3177f2cfd 100644 --- a/src/particles.h +++ b/src/particles.h @@ -32,6 +32,8 @@ with this program; if not, write to the Free Software Foundation, Inc., struct ClientEvent; class ParticleManager; class ClientEnvironment; +class MapNode; +class ContentFeatures; class Particle : public scene::ISceneNode { @@ -53,7 +55,8 @@ class Particle : public scene::ISceneNode v2f texpos, v2f texsize, const struct TileAnimationParams &anim, - u8 glow + u8 glow, + video::SColor color = video::SColor(0xFFFFFFFF) ); ~Particle(); @@ -100,7 +103,10 @@ private: v3f m_acceleration; LocalPlayer *m_player; float m_size; - u8 m_light; + //! Color without lighting + video::SColor m_base_color; + //! Final rendered color + video::SColor m_color; bool m_collisiondetection; bool m_collision_removal; bool m_vertical; @@ -184,13 +190,16 @@ public: scene::ISceneManager* smgr, LocalPlayer *player); void addDiggingParticles(IGameDef* gamedef, scene::ISceneManager* smgr, - LocalPlayer *player, v3s16 pos, const TileSpec tiles[]); + LocalPlayer *player, v3s16 pos, const MapNode &n, + const ContentFeatures &f); void addPunchingParticles(IGameDef* gamedef, scene::ISceneManager* smgr, - LocalPlayer *player, v3s16 pos, const TileSpec tiles[]); + LocalPlayer *player, v3s16 pos, const MapNode &n, + const ContentFeatures &f); void addNodeParticle(IGameDef* gamedef, scene::ISceneManager* smgr, - LocalPlayer *player, v3s16 pos, const TileSpec tiles[]); + LocalPlayer *player, v3s16 pos, const MapNode &n, + const ContentFeatures &f); protected: void addParticle(Particle* toadd); diff --git a/src/script/common/c_content.cpp b/src/script/common/c_content.cpp index 84af4583b..ebc951295 100644 --- a/src/script/common/c_content.cpp +++ b/src/script/common/c_content.cpp @@ -332,6 +332,10 @@ TileDef read_tiledef(lua_State *L, int index, u8 drawtype) L, index, "tileable_horizontal", default_tiling); tiledef.tileable_vertical = getboolfield_default( L, index, "tileable_vertical", default_tiling); + // color = ... + lua_getfield(L, index, "color"); + tiledef.has_color = read_color(L, -1, &tiledef.color); + lua_pop(L, 1); // animation = {} lua_getfield(L, index, "animation"); tiledef.animation = read_animation_definition(L, -1); @@ -450,6 +454,13 @@ ContentFeatures read_content_features(lua_State *L, int index) if (usealpha) f.alpha = 0; + // Read node color. + lua_getfield(L, index, "color"); + read_color(L, -1, &f.color); + lua_pop(L, 1); + + getstringfield(L, index, "palette", f.palette_name); + /* Other stuff */ lua_getfield(L, index, "post_effect_color"); @@ -461,6 +472,13 @@ ContentFeatures read_content_features(lua_State *L, int index) f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2", ScriptApiNode::es_ContentParamType2, CPT2_NONE); + if (f.palette_name != "" && + !(f.param_type_2 == CPT2_COLOR || + f.param_type_2 == CPT2_COLORED_FACEDIR || + f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) + warningstream << "Node " << f.name.c_str() + << " has a palette, but not a suitable paramtype2." << std::endl; + // Warn about some deprecated fields warn_if_field_exists(L, index, "wall_mounted", "Deprecated; use paramtype2 = 'wallmounted'"); diff --git a/src/script/cpp_api/s_node.cpp b/src/script/cpp_api/s_node.cpp index 379ed773f..23c8f43b9 100644 --- a/src/script/cpp_api/s_node.cpp +++ b/src/script/cpp_api/s_node.cpp @@ -59,6 +59,9 @@ struct EnumString ScriptApiNode::es_ContentParamType2[] = {CPT2_LEVELED, "leveled"}, {CPT2_DEGROTATE, "degrotate"}, {CPT2_MESHOPTIONS, "meshoptions"}, + {CPT2_COLOR, "color"}, + {CPT2_COLORED_FACEDIR, "colorfacedir"}, + {CPT2_COLORED_WALLMOUNTED, "colorwallmounted"}, {0, NULL}, }; diff --git a/src/shader.cpp b/src/shader.cpp index c0ecf738d..79485025b 100644 --- a/src/shader.cpp +++ b/src/shader.cpp @@ -543,7 +543,7 @@ ShaderInfo generate_shader(std::string name, u8 material_type, u8 drawtype, shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL; break; case TILE_MATERIAL_LIQUID_TRANSPARENT: - shaderinfo.base_material = video::EMT_TRANSPARENT_VERTEX_ALPHA; + shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL; break; case TILE_MATERIAL_LIQUID_OPAQUE: shaderinfo.base_material = video::EMT_SOLID; diff --git a/src/wieldmesh.cpp b/src/wieldmesh.cpp index c305238fe..089a67f33 100644 --- a/src/wieldmesh.cpp +++ b/src/wieldmesh.cpp @@ -318,6 +318,7 @@ 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; } + m_colors.clear(); // If wield_image is defined, it overrides everything else if (def.wield_image != "") { @@ -358,28 +359,30 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client) 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 = (f.tiles[i].animation_frame_count > 1); + bool animated = (tile->animation_frame_count > 1); if (animated) { - FrameSpec animation_frame = f.tiles[i].frames[0]; + FrameSpec animation_frame = tile->frames[0]; material.setTexture(0, animation_frame.texture); } else { - material.setTexture(0, f.tiles[i].texture); + material.setTexture(0, tile->texture); } + m_colors.push_back(tile->color); material.MaterialType = m_material_type; if (m_enable_shaders) { - if (f.tiles[i].normal_texture) { + if (tile->normal_texture) { if (animated) { - FrameSpec animation_frame = f.tiles[i].frames[0]; + FrameSpec animation_frame = tile->frames[0]; material.setTexture(1, animation_frame.normal_texture); } else { - material.setTexture(1, f.tiles[i].normal_texture); + material.setTexture(1, tile->normal_texture); } } - material.setTexture(2, f.tiles[i].flags_texture); + material.setTexture(2, tile->flags_texture); } } return; @@ -393,11 +396,28 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client) changeToMesh(NULL); } -void WieldMeshSceneNode::setColor(video::SColor color) +void WieldMeshSceneNode::setColor(video::SColor c) { assert(!m_lighting); - setMeshColor(m_meshnode->getMesh(), color); - shadeMeshFaces(m_meshnode->getMesh()); + scene::IMesh *mesh=m_meshnode->getMesh(); + if (mesh == NULL) + return; + + u8 red = c.getRed(); + u8 green = c.getGreen(); + 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 buffercolor(255, + bc.getRed() * red / 255, + bc.getGreen() * green / 255, + bc.getBlue() * blue / 255); + scene::IMeshBuffer *buf = mesh->getMeshBuffer(j); + colorizeMeshBuffer(buf, &buffercolor); + } } void WieldMeshSceneNode::render() @@ -464,7 +484,6 @@ scene::IMesh *getItemMesh(Client *client, const ItemStack &item) } else if (f.drawtype == NDT_PLANTLIKE) { mesh = getExtrudedMesh(tsrc, tsrc->getTextureName(f.tiles[0].texture_id)); - return mesh; } 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()); @@ -477,8 +496,6 @@ scene::IMesh *getItemMesh(Client *client, const ItemStack &item) mesh = cloneMesh(mapblock_mesh.getMesh()); translateMesh(mesh, v3f(-BS, -BS, -BS)); scaleMesh(mesh, v3f(0.12, 0.12, 0.12)); - rotateMeshXZby(mesh, -45); - rotateMeshYZby(mesh, -30); u32 mc = mesh->getMeshBufferCount(); for (u32 i = 0; i < mc; ++i) { @@ -492,28 +509,29 @@ scene::IMesh *getItemMesh(Client *client, const ItemStack &item) material1.setTexture(3, material2.getTexture(3)); material1.MaterialType = material2.MaterialType; } - return mesh; } - shadeMeshFaces(mesh); - rotateMeshXZby(mesh, -45); - rotateMeshYZby(mesh, -30); - u32 mc = mesh->getMeshBufferCount(); for (u32 i = 0; i < mc; ++i) { - video::SMaterial &material = mesh->getMeshBuffer(i)->getMaterial(); + const TileSpec *tile = &(f.tiles[i]); + scene::IMeshBuffer *buf = mesh->getMeshBuffer(i); + 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 (f.tiles[i].animation_frame_count > 1) { - FrameSpec animation_frame = f.tiles[i].frames[0]; + if (tile->animation_frame_count > 1) { + FrameSpec animation_frame = tile->frames[0]; material.setTexture(0, animation_frame.texture); } else { - material.setTexture(0, f.tiles[i].texture); + material.setTexture(0, tile->texture); } } + + rotateMeshXZby(mesh, -45); + rotateMeshYZby(mesh, -30); return mesh; } return NULL; diff --git a/src/wieldmesh.h b/src/wieldmesh.h index 0162c5e5a..2e78232ae 100644 --- a/src/wieldmesh.h +++ b/src/wieldmesh.h @@ -70,6 +70,11 @@ private: bool m_anisotropic_filter; bool m_bilinear_filter; bool m_trilinear_filter; + /*! + * Stores the colors of the mesh's mesh buffers. + * This does not include lighting. + */ + std::vector m_colors; // Bounding box culling is disabled for this type of scene node, // so this variable is just required so we can implement -- cgit v1.2.3 From 33e0eedbfb116111fa79cbc506d9e94ffbb1543b Mon Sep 17 00:00:00 2001 From: number Zero Date: Wed, 25 Jan 2017 00:33:01 +0300 Subject: Add smooth lighting for all nodes Note: Smooth lighting disables the mesh cache. --- src/content_mapblock.cpp | 518 +++++++++++++++++++++++++++++++++++------------ src/mapblock_mesh.cpp | 2 +- src/nodedef.cpp | 5 + 3 files changed, 396 insertions(+), 129 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 742bfb1fd..45822666f 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -30,6 +30,27 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "noise.h" +// Distance of light extrapolation (for oversized nodes) +// After this distance, it gives up and considers light level constant +#define SMOOTH_LIGHTING_OVERSIZE 1.0 + +struct LightFrame +{ + f32 lightsA[8]; + f32 lightsB[8]; + u8 light_source; +}; + +static const v3s16 light_dirs[8] = { + v3s16(-1, -1, -1), + v3s16(-1, -1, 1), + v3s16(-1, 1, -1), + v3s16(-1, 1, 1), + v3s16( 1, -1, -1), + v3s16( 1, -1, 1), + v3s16( 1, 1, -1), + v3s16( 1, 1, 1), +}; // Create a cuboid. // collector - the MeshCollector for the resulting polygons @@ -180,6 +201,150 @@ void makeCuboid(MeshCollector *collector, const aabb3f &box, } } +// Create a cuboid. +// collector - the MeshCollector for the resulting polygons +// box - the position and size of the box +// tiles - the tiles (materials) to use (for all 6 faces) +// tilecount - number of entries in tiles, 1<=tilecount<=6 +// lights - vertex light levels. The order is the same as in light_dirs +// txc - texture coordinates - this is a list of texture coordinates +// for the opposite corners of each face - therefore, there +// should be (2+2)*6=24 values in the list. Alternatively, pass +// NULL to use the entire texture for each face. The order of +// the faces in the list is up-down-right-left-back-front +// (compatible with ContentFeatures). If you specified 0,0,1,1 +// for each face, that would be the same as passing NULL. +// light_source - node light emission +static void makeSmoothLightedCuboid(MeshCollector *collector, const aabb3f &box, + TileSpec *tiles, int tilecount, const u16 *lights , const f32 *txc, + const u8 light_source) +{ + assert(tilecount >= 1 && tilecount <= 6); // pre-condition + + v3f min = box.MinEdge; + v3f max = box.MaxEdge; + + if (txc == NULL) { + static const f32 txc_default[24] = { + 0,0,1,1, + 0,0,1,1, + 0,0,1,1, + 0,0,1,1, + 0,0,1,1, + 0,0,1,1 + }; + txc = txc_default; + } + static const u8 light_indices[24] = { + 3, 7, 6, 2, + 0, 4, 5, 1, + 6, 7, 5, 4, + 3, 2, 0, 1, + 7, 3, 1, 5, + 2, 6, 4, 0 + }; + video::S3DVertex vertices[24] = { + // up + video::S3DVertex(min.X, max.Y, max.Z, 0, 1, 0, video::SColor(), txc[0], txc[1]), + video::S3DVertex(max.X, max.Y, max.Z, 0, 1, 0, video::SColor(), txc[2], txc[1]), + video::S3DVertex(max.X, max.Y, min.Z, 0, 1, 0, video::SColor(), txc[2], txc[3]), + video::S3DVertex(min.X, max.Y, min.Z, 0, 1, 0, video::SColor(), txc[0], txc[3]), + // down + video::S3DVertex(min.X, min.Y, min.Z, 0, -1, 0, video::SColor(), txc[4], txc[5]), + video::S3DVertex(max.X, min.Y, min.Z, 0, -1, 0, video::SColor(), txc[6], txc[5]), + video::S3DVertex(max.X, min.Y, max.Z, 0, -1, 0, video::SColor(), txc[6], txc[7]), + video::S3DVertex(min.X, min.Y, max.Z, 0, -1, 0, video::SColor(), txc[4], txc[7]), + // right + video::S3DVertex(max.X, max.Y, min.Z, 1, 0, 0, video::SColor(), txc[ 8], txc[9]), + video::S3DVertex(max.X, max.Y, max.Z, 1, 0, 0, video::SColor(), txc[10], txc[9]), + video::S3DVertex(max.X, min.Y, max.Z, 1, 0, 0, video::SColor(), txc[10], txc[11]), + video::S3DVertex(max.X, min.Y, min.Z, 1, 0, 0, video::SColor(), txc[ 8], txc[11]), + // left + video::S3DVertex(min.X, max.Y, max.Z, -1, 0, 0, video::SColor(), txc[12], txc[13]), + video::S3DVertex(min.X, max.Y, min.Z, -1, 0, 0, video::SColor(), txc[14], txc[13]), + video::S3DVertex(min.X, min.Y, min.Z, -1, 0, 0, video::SColor(), txc[14], txc[15]), + video::S3DVertex(min.X, min.Y, max.Z, -1, 0, 0, video::SColor(), txc[12], txc[15]), + // back + video::S3DVertex(max.X, max.Y, max.Z, 0, 0, 1, video::SColor(), txc[16], txc[17]), + video::S3DVertex(min.X, max.Y, max.Z, 0, 0, 1, video::SColor(), txc[18], txc[17]), + video::S3DVertex(min.X, min.Y, max.Z, 0, 0, 1, video::SColor(), txc[18], txc[19]), + video::S3DVertex(max.X, min.Y, max.Z, 0, 0, 1, video::SColor(), txc[16], txc[19]), + // front + video::S3DVertex(min.X, max.Y, min.Z, 0, 0, -1, video::SColor(), txc[20], txc[21]), + video::S3DVertex(max.X, max.Y, min.Z, 0, 0, -1, video::SColor(), txc[22], txc[21]), + video::S3DVertex(max.X, min.Y, min.Z, 0, 0, -1, video::SColor(), txc[22], txc[23]), + video::S3DVertex(min.X, min.Y, min.Z, 0, 0, -1, video::SColor(), txc[20], txc[23]), + }; + + for(int i = 0; i < 6; i++) { + switch (tiles[MYMIN(i, tilecount-1)].rotation) { + case 0: + break; + case 1: //R90 + for (int x = 0; x < 4; x++) + vertices[i*4+x].TCoords.rotateBy(90,irr::core::vector2df(0, 0)); + break; + case 2: //R180 + for (int x = 0; x < 4; x++) + vertices[i*4+x].TCoords.rotateBy(180,irr::core::vector2df(0, 0)); + break; + case 3: //R270 + for (int x = 0; x < 4; x++) + vertices[i*4+x].TCoords.rotateBy(270,irr::core::vector2df(0, 0)); + break; + case 4: //FXR90 + for (int x = 0; x < 4; x++) { + vertices[i*4+x].TCoords.X = 1.0 - vertices[i*4+x].TCoords.X; + vertices[i*4+x].TCoords.rotateBy(90,irr::core::vector2df(0, 0)); + } + break; + case 5: //FXR270 + for (int x = 0; x < 4; x++) { + vertices[i*4+x].TCoords.X = 1.0 - vertices[i*4+x].TCoords.X; + vertices[i*4+x].TCoords.rotateBy(270,irr::core::vector2df(0, 0)); + } + break; + case 6: //FYR90 + for (int x = 0; x < 4; x++) { + vertices[i*4+x].TCoords.Y = 1.0 - vertices[i*4+x].TCoords.Y; + vertices[i*4+x].TCoords.rotateBy(90,irr::core::vector2df(0, 0)); + } + break; + case 7: //FYR270 + for (int x = 0; x < 4; x++) { + vertices[i*4+x].TCoords.Y = 1.0 - vertices[i*4+x].TCoords.Y; + vertices[i*4+x].TCoords.rotateBy(270,irr::core::vector2df(0, 0)); + } + break; + case 8: //FX + for (int x = 0; x < 4; x++) { + vertices[i*4+x].TCoords.X = 1.0 - vertices[i*4+x].TCoords.X; + } + break; + case 9: //FY + for (int x = 0; x < 4; x++) { + vertices[i*4+x].TCoords.Y = 1.0 - vertices[i*4+x].TCoords.Y; + } + break; + default: + break; + } + } + u16 indices[] = {0,1,2,2,3,0}; + for (s32 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, light_source); + if (!light_source) + applyFacesShading(vertices[j].Color, vertices[j].Normal); + } + // Add to mesh collector + for (s32 k = 0; k < 6; ++k) { + int tileindex = MYMIN(k, tilecount - 1); + collector->append(tiles[tileindex], vertices + 4 * k, 4, indices, 6); + } +} + // Create a cuboid. // collector - the MeshCollector for the resulting polygons // box - the position and size of the box @@ -205,6 +370,64 @@ void makeCuboid(MeshCollector *collector, const aabb3f &box, TileSpec *tiles, makeCuboid(collector, box, tiles, tilecount, color, txc, light_source); } +// Gets the base lighting values for a node +// frame - resulting (opaque) data +// p - node position (absolute) +// data - ... +// light_source - node light emission level +static void getSmoothLightFrame(LightFrame *frame, const v3s16 &p, MeshMakeData *data, u8 light_source) +{ + for (int k = 0; k < 8; ++k) { + u16 light = getSmoothLight(p, light_dirs[k], data); + frame->lightsA[k] = light & 0xff; + frame->lightsB[k] = light >> 8; + } + frame->light_source = light_source; +} + +// Calculates vertex light level +// frame - light values from getSmoothLightFrame() +// vertex_pos - vertex position in the node (coordinates are clamped to [0.0, 1.0] or so) +static u16 blendLight(const LightFrame &frame, const core::vector3df& vertex_pos) +{ + f32 x = core::clamp(vertex_pos.X / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE); + f32 y = core::clamp(vertex_pos.Y / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE); + f32 z = core::clamp(vertex_pos.Z / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE); + f32 lightA = 0.0; + f32 lightB = 0.0; + for (int k = 0; k < 8; ++k) { + f32 dx = (k & 4) ? x : 1 - x; + f32 dy = (k & 2) ? y : 1 - y; + f32 dz = (k & 1) ? z : 1 - z; + lightA += dx * dy * dz * frame.lightsA[k]; + lightB += dx * dy * dz * frame.lightsB[k]; + } + return + core::clamp(core::round32(lightA), 0, 255) | + core::clamp(core::round32(lightB), 0, 255) << 8; +} + +// Calculates vertex color to be used in mapblock mesh +// frame - light values from getSmoothLightFrame() +// vertex_pos - vertex position in the node (coordinates are clamped to [0.0, 1.0] or so) +// tile_color - node's tile color +static video::SColor blendLight(const LightFrame &frame, + const core::vector3df& vertex_pos, video::SColor tile_color) +{ + u16 light = blendLight(frame, vertex_pos); + return encode_light_and_color(light, tile_color, frame.light_source); +} + +static video::SColor blendLight(const LightFrame &frame, + const core::vector3df& vertex_pos, const core::vector3df& vertex_normal, + video::SColor tile_color) +{ + video::SColor color = blendLight(frame, vertex_pos, tile_color); + if (!frame.light_source) + applyFacesShading(color, vertex_normal); + return color; +} + static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef, MeshMakeData *data, MapNode n, int v, int *neighbors) { @@ -213,6 +436,74 @@ static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef, *neighbors |= v; } +static void makeAutoLightedCuboid(MeshCollector *collector, MeshMakeData *data, + const v3f &pos, aabb3f box, TileSpec &tile, + /* pre-computed, for non-smooth lighting only */ const video::SColor color, + /* for smooth lighting only */ const LightFrame &frame) +{ + f32 dx1 = box.MinEdge.X; + f32 dy1 = box.MinEdge.Y; + f32 dz1 = box.MinEdge.Z; + f32 dx2 = box.MaxEdge.X; + f32 dy2 = box.MaxEdge.Y; + f32 dz2 = box.MaxEdge.Z; + box.MinEdge += pos; + box.MaxEdge += pos; + f32 tx1 = (box.MinEdge.X / BS) + 0.5; + f32 ty1 = (box.MinEdge.Y / BS) + 0.5; + f32 tz1 = (box.MinEdge.Z / BS) + 0.5; + f32 tx2 = (box.MaxEdge.X / BS) + 0.5; + f32 ty2 = (box.MaxEdge.Y / BS) + 0.5; + f32 tz2 = (box.MaxEdge.Z / BS) + 0.5; + f32 txc[24] = { + tx1, 1-tz2, tx2, 1-tz1, // up + tx1, tz1, tx2, tz2, // down + tz1, 1-ty2, tz2, 1-ty1, // right + 1-tz2, 1-ty2, 1-tz1, 1-ty1, // left + 1-tx2, 1-ty2, 1-tx1, 1-ty1, // back + tx1, 1-ty2, tx2, 1-ty1, // front + }; + if (data->m_smooth_lighting) { + u16 lights[8]; + for (int j = 0; j < 8; ++j) { + f32 x = (j & 4) ? dx2 : dx1; + f32 y = (j & 2) ? dy2 : dy1; + f32 z = (j & 1) ? dz2 : dz1; + lights[j] = blendLight(frame, core::vector3df(x, y, z)); + } + makeSmoothLightedCuboid(collector, box, &tile, 1, lights, txc, frame.light_source); + } else { + makeCuboid(collector, box, &tile, 1, color, txc, frame.light_source); + } +} + +static void makeAutoLightedCuboidEx(MeshCollector *collector, MeshMakeData *data, + const v3f &pos, aabb3f box, TileSpec &tile, f32 *txc, + /* pre-computed, for non-smooth lighting only */ const video::SColor color, + /* for smooth lighting only */ const LightFrame &frame) +{ + f32 dx1 = box.MinEdge.X; + f32 dy1 = box.MinEdge.Y; + f32 dz1 = box.MinEdge.Z; + f32 dx2 = box.MaxEdge.X; + f32 dy2 = box.MaxEdge.Y; + f32 dz2 = box.MaxEdge.Z; + box.MinEdge += pos; + box.MaxEdge += pos; + if (data->m_smooth_lighting) { + u16 lights[8]; + for (int j = 0; j < 8; ++j) { + f32 x = (j & 4) ? dx2 : dx1; + f32 y = (j & 2) ? dy2 : dy1; + f32 z = (j & 1) ? dz2 : dz1; + lights[j] = blendLight(frame, core::vector3df(x, y, z)); + } + makeSmoothLightedCuboid(collector, box, &tile, 1, lights, txc, frame.light_source); + } else { + makeCuboid(collector, box, &tile, 1, color, txc, frame.light_source); + } +} + // For use in mapblock_mesh_generate_special // X,Y,Z of position must be -1,0,1 // This expression is a simplification of @@ -251,7 +542,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, /* Some settings */ - bool enable_mesh_cache = g_settings->getBool("enable_mesh_cache"); + bool enable_mesh_cache = g_settings->getBool("enable_mesh_cache") && + !data->m_smooth_lighting; // Mesh cache is not supported with smooth lighting v3s16 blockpos_nodes = data->m_blockpos*MAP_BLOCKSIZE; @@ -268,13 +560,20 @@ void mapblock_mesh_generate_special(MeshMakeData *data, if(f.solidness != 0) continue; - switch(f.drawtype){ + if (f.drawtype == NDT_AIRLIKE) + continue; + + LightFrame frame; + if (data->m_smooth_lighting) + getSmoothLightFrame(&frame, blockpos_nodes + p, data, f.light_source); + else + frame.light_source = f.light_source; + + switch(f.drawtype) { default: infostream << "Got " << f.drawtype << std::endl; FATAL_ERROR("Unknown drawtype"); break; - case NDT_AIRLIKE: - break; case NDT_LIQUID: { /* @@ -383,8 +682,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data, vertices[1].Pos.Y = -0.5 * BS; } - for(s32 j=0; j<4; j++) - { + for (s32 j = 0; j < 4; j++) { if(dir == v3s16(0,0,1)) vertices[j].Pos.rotateXZBy(0); if(dir == v3s16(0,0,-1)) @@ -401,6 +699,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, vertices[j].Pos.Z *= 0.98; }*/ + if (data->m_smooth_lighting) + vertices[j].Color = blendLight(frame, vertices[j].Pos, current_tile->color); vertices[j].Pos += intToFloat(p, BS); } @@ -423,10 +723,11 @@ void mapblock_mesh_generate_special(MeshMakeData *data, video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c1, 0,0), }; - v3f offset(p.X * BS, (p.Y + 0.5) * BS, p.Z * BS); - for(s32 i=0; i<4; i++) - { - vertices[i].Pos += offset; + for (s32 i = 0; i < 4; i++) { + vertices[i].Pos.Y += 0.5 * BS; + if (data->m_smooth_lighting) + vertices[i].Color = blendLight(frame, vertices[i].Pos, tile_liquid.color); + vertices[i].Pos += intToFloat(p, BS); } u16 indices[] = {0,1,2,2,3,0}; @@ -704,6 +1005,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, vertices[j].Pos.Z *= 0.98; }*/ + if (data->m_smooth_lighting) + vertices[j].Color = blendLight(frame, vertices[j].Pos, current_tile->color); vertices[j].Pos += intToFloat(p, BS); } @@ -737,6 +1040,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, //vertices[i].Pos.Y += neighbor_levels[v3s16(0,0,0)]; s32 j = corner_resolve[i]; vertices[i].Pos.Y += corner_levels[j]; + if (data->m_smooth_lighting) + vertices[i].Color = blendLight(frame, vertices[i].Pos, tile_liquid.color); vertices[i].Pos += intToFloat(p, BS); } @@ -828,7 +1133,9 @@ void mapblock_mesh_generate_special(MeshMakeData *data, for(u16 i=0; i<4; i++) vertices[i].Pos.rotateXZBy(90); - for(u16 i=0; i<4; i++){ + for (u16 i = 0; i < 4; i++) { + if (data->m_smooth_lighting) + vertices[i].Color = blendLight(frame, vertices[i].Pos, vertices[i].Normal, tile.color); vertices[i].Pos += intToFloat(p, BS); } @@ -860,9 +1167,6 @@ void mapblock_mesh_generate_special(MeshMakeData *data, video::SColor tile0color = encode_light_and_color(l, tiles[0].color, f.light_source); - video::SColor tile0colors[6]; - for (i = 0; i < 6; i++) - tile0colors[i] = tile0color; TileSpec glass_tiles[6]; video::SColor glasscolor[6]; @@ -995,7 +1299,6 @@ void mapblock_mesh_generate_special(MeshMakeData *data, 0,1, 8, 0,4,16, 3,4,17, 3,1, 9 }; - f32 tx1, ty1, tz1, tx2, ty2, tz2; aabb3f box; for(i = 0; i < 12; i++) @@ -1008,24 +1311,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data, if (edge_invisible) continue; box = frame_edges[i]; - box.MinEdge += pos; - box.MaxEdge += pos; - tx1 = (box.MinEdge.X / BS) + 0.5; - ty1 = (box.MinEdge.Y / BS) + 0.5; - tz1 = (box.MinEdge.Z / BS) + 0.5; - tx2 = (box.MaxEdge.X / BS) + 0.5; - ty2 = (box.MaxEdge.Y / BS) + 0.5; - tz2 = (box.MaxEdge.Z / BS) + 0.5; - f32 txc1[24] = { - tx1, 1-tz2, tx2, 1-tz1, - tx1, tz1, tx2, tz2, - tz1, 1-ty2, tz2, 1-ty1, - 1-tz2, 1-ty2, 1-tz1, 1-ty1, - 1-tx2, 1-ty2, 1-tx1, 1-ty1, - tx1, 1-ty2, tx2, 1-ty1, - }; - makeCuboid(&collector, box, &tiles[0], 1, tile0colors, - txc1, f.light_source); + makeAutoLightedCuboid(&collector, data, pos, box, tiles[0], tile0color, frame); } for(i = 0; i < 6; i++) @@ -1033,37 +1319,16 @@ void mapblock_mesh_generate_special(MeshMakeData *data, if (!visible_faces[i]) continue; box = glass_faces[i]; - box.MinEdge += pos; - box.MaxEdge += pos; - tx1 = (box.MinEdge.X / BS) + 0.5; - ty1 = (box.MinEdge.Y / BS) + 0.5; - tz1 = (box.MinEdge.Z / BS) + 0.5; - tx2 = (box.MaxEdge.X / BS) + 0.5; - ty2 = (box.MaxEdge.Y / BS) + 0.5; - tz2 = (box.MaxEdge.Z / BS) + 0.5; - f32 txc2[24] = { - tx1, 1-tz2, tx2, 1-tz1, - tx1, tz1, tx2, tz2, - tz1, 1-ty2, tz2, 1-ty1, - 1-tz2, 1-ty2, 1-tz1, 1-ty1, - 1-tx2, 1-ty2, 1-tx1, 1-ty1, - tx1, 1-ty2, tx2, 1-ty1, - }; - makeCuboid(&collector, box, &glass_tiles[i], 1, glasscolor, - txc2, f.light_source); + makeAutoLightedCuboid(&collector, data, pos, box, glass_tiles[i], glasscolor[i], frame); } if (param2 > 0 && f.special_tiles[0].texture) { // Interior volume level is in range 0 .. 63, // convert it to -0.5 .. 0.5 float vlev = (((float)param2 / 63.0 ) * 2.0 - 1.0); - TileSpec tile=getSpecialTile(f, n, 0); + TileSpec tile = getSpecialTile(f, n, 0); video::SColor special_color = encode_light_and_color(l, tile.color, f.light_source); - TileSpec interior_tiles[6]; - for (i = 0; i < 6; i++) - interior_tiles[i] = tile; - float offset = 0.003; box = aabb3f(visible_faces[3] ? -b : -a + offset, visible_faces[1] ? -b : -a + offset, @@ -1071,24 +1336,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data, visible_faces[2] ? b : a - offset, visible_faces[0] ? b * vlev : a * vlev - offset, visible_faces[4] ? b : a - offset); - box.MinEdge += pos; - box.MaxEdge += pos; - tx1 = (box.MinEdge.X / BS) + 0.5; - ty1 = (box.MinEdge.Y / BS) + 0.5; - tz1 = (box.MinEdge.Z / BS) + 0.5; - tx2 = (box.MaxEdge.X / BS) + 0.5; - ty2 = (box.MaxEdge.Y / BS) + 0.5; - tz2 = (box.MaxEdge.Z / BS) + 0.5; - f32 txc3[24] = { - tx1, 1-tz2, tx2, 1-tz1, - tx1, tz1, tx2, tz2, - tz1, 1-ty2, tz2, 1-ty1, - 1-tz2, 1-ty2, 1-tz1, 1-ty1, - 1-tx2, 1-ty2, 1-tx1, 1-ty1, - tx1, 1-ty2, tx2, 1-ty1, - }; - makeCuboid(&collector, box, interior_tiles, 6, special_color, - txc3, f.light_source); + makeAutoLightedCuboid(&collector, data, pos, box, tile, special_color, frame); } break;} case NDT_ALLFACES: @@ -1101,10 +1349,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data, v3f pos = intToFloat(p, BS); aabb3f box(-BS/2,-BS/2,-BS/2,BS/2,BS/2,BS/2); - box.MinEdge += pos; - box.MaxEdge += pos; - makeCuboid(&collector, box, &tile_leaves, 1, c, NULL, - f.light_source); + makeAutoLightedCuboid(&collector, data, pos, box, tile_leaves, c, frame); break;} case NDT_ALLFACES_OPTIONAL: // This is always pre-converted to something else @@ -1144,7 +1389,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data, video::S3DVertex(-s, s,0, 0,0,0, c, 0,0), }; - for(s32 i=0; i<4; i++) + for (s32 i = 0; i < 4; i++) { if(dir == v3s16(1,0,0)) vertices[i].Pos.rotateXZBy(0); @@ -1159,6 +1404,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, if(dir == v3s16(0,1,0)) vertices[i].Pos.rotateXZBy(-45); + if (data->m_smooth_lighting) + vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); vertices[i].Pos += intToFloat(p, BS); } @@ -1189,7 +1436,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data, v3s16 dir = n.getWallMountedDir(nodedef); - for(s32 i=0; i<4; i++) + for (s32 i = 0; i < 4; i++) { if(dir == v3s16(1,0,0)) vertices[i].Pos.rotateXZBy(0); @@ -1204,6 +1451,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, if(dir == v3s16(0,1,0)) vertices[i].Pos.rotateXYBy(90); + if (data->m_smooth_lighting) + vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); vertices[i].Pos += intToFloat(p, BS); } @@ -1355,6 +1604,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, for (int i = 0; i < 4; i++) { vertices[i].Pos *= f.visual_scale; vertices[i].Pos.Y += BS/2 * (f.visual_scale - 1); + if (data->m_smooth_lighting) + vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); vertices[i].Pos += intToFloat(p, BS); // move to a random spot to avoid moire if ((f.param_type_2 == CPT2_MESHOPTIONS) && ((n.param2 & 0x8) != 0)) { @@ -1507,6 +1758,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, for (int i = 0; i < 4; i++) { vertices[i].Pos *= f.visual_scale; + if (data->m_smooth_lighting) + vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); vertices[i].Pos += intToFloat(p, BS); } @@ -1537,8 +1790,6 @@ void mapblock_mesh_generate_special(MeshMakeData *data, // The post - always present aabb3f post(-post_rad,-BS/2,-post_rad,post_rad,BS/2,post_rad); - post.MinEdge += pos; - post.MaxEdge += pos; f32 postuv[24]={ 6/16.,6/16.,10/16.,10/16., 6/16.,6/16.,10/16.,10/16., @@ -1546,8 +1797,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data, 4/16.,0,8/16.,1, 8/16.,0,12/16.,1, 12/16.,0,16/16.,1}; - makeCuboid(&collector, post, &tile_rot, 1, c, postuv, - f.light_source); + makeAutoLightedCuboidEx(&collector, data, pos, post, tile_rot, postuv, c, frame); // Now a section of fence, +X, if there's a post there v3s16 p2 = p; @@ -1558,8 +1808,6 @@ void mapblock_mesh_generate_special(MeshMakeData *data, { aabb3f bar(-bar_len+BS/2,-bar_rad+BS/4,-bar_rad, bar_len+BS/2,bar_rad+BS/4,bar_rad); - bar.MinEdge += pos; - bar.MaxEdge += pos; f32 xrailuv[24]={ 0/16.,2/16.,16/16.,4/16., 0/16.,4/16.,16/16.,6/16., @@ -1567,12 +1815,10 @@ void mapblock_mesh_generate_special(MeshMakeData *data, 10/16.,10/16.,12/16.,12/16., 0/16.,8/16.,16/16.,10/16., 0/16.,14/16.,16/16.,16/16.}; - makeCuboid(&collector, bar, &tile_nocrack, 1, - c, xrailuv, f.light_source); + makeAutoLightedCuboidEx(&collector, data, pos, bar, tile_nocrack, xrailuv, c, frame); bar.MinEdge.Y -= BS/2; bar.MaxEdge.Y -= BS/2; - makeCuboid(&collector, bar, &tile_nocrack, 1, - c, xrailuv, f.light_source); + makeAutoLightedCuboidEx(&collector, data, pos, bar, tile_nocrack, xrailuv, c, frame); } // Now a section of fence, +Z, if there's a post there @@ -1584,8 +1830,6 @@ void mapblock_mesh_generate_special(MeshMakeData *data, { aabb3f bar(-bar_rad,-bar_rad+BS/4,-bar_len+BS/2, bar_rad,bar_rad+BS/4,bar_len+BS/2); - bar.MinEdge += pos; - bar.MaxEdge += pos; f32 zrailuv[24]={ 3/16.,1/16.,5/16.,5/16., // cannot rotate; stretch 4/16.,1/16.,6/16.,5/16., // for wood texture instead @@ -1593,12 +1837,10 @@ void mapblock_mesh_generate_special(MeshMakeData *data, 0/16.,6/16.,16/16.,8/16., 6/16.,6/16.,8/16.,8/16., 10/16.,10/16.,12/16.,12/16.}; - makeCuboid(&collector, bar, &tile_nocrack, 1, - c, zrailuv, f.light_source); + makeAutoLightedCuboidEx(&collector, data, pos, bar, tile_nocrack, zrailuv, c, frame); bar.MinEdge.Y -= BS/2; bar.MaxEdge.Y -= BS/2; - makeCuboid(&collector, bar, &tile_nocrack, 1, - c, zrailuv, f.light_source); + makeAutoLightedCuboidEx(&collector, data, pos, bar, tile_nocrack, zrailuv, c, frame); } break;} case NDT_RAILLIKE: @@ -1729,6 +1971,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, { if(angle != 0) vertices[i].Pos.rotateXZBy(angle); + if (data->m_smooth_lighting) + vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); vertices[i].Pos += intToFloat(p, BS); } @@ -1746,14 +1990,16 @@ void mapblock_mesh_generate_special(MeshMakeData *data, v3s16(0, 0, -1) }; - u16 l = getInteriorLight(n, 1, nodedef); TileSpec tiles[6]; video::SColor colors[6]; - for(int j = 0; j < 6; j++) { + for (int j = 0; j < 6; j++) { // Handles facedir rotation for textures tiles[j] = getNodeTile(n, p, tile_dirs[j], data); - colors[j]= encode_light_and_color(l, tiles[j].color, - f.light_source); + } + if (!data->m_smooth_lighting) { + u16 l = getInteriorLight(n, 1, nodedef); + for (int j = 0; j < 6; j++) + colors[j] = encode_light_and_color(l, tiles[j].color, f.light_source); } v3f pos = intToFloat(p, BS); @@ -1790,33 +2036,27 @@ void mapblock_mesh_generate_special(MeshMakeData *data, std::vector boxes; n.getNodeBoxes(nodedef, &boxes, neighbors); - for(std::vector::iterator + for (std::vector::iterator i = boxes.begin(); - i != boxes.end(); ++i) - { + i != boxes.end(); ++i) { aabb3f box = *i; + + f32 dx1 = box.MinEdge.X; + f32 dy1 = box.MinEdge.Y; + f32 dz1 = box.MinEdge.Z; + f32 dx2 = box.MaxEdge.X; + f32 dy2 = box.MaxEdge.Y; + f32 dz2 = box.MaxEdge.Z; + box.MinEdge += pos; box.MaxEdge += pos; - f32 temp; if (box.MinEdge.X > box.MaxEdge.X) - { - temp=box.MinEdge.X; - box.MinEdge.X=box.MaxEdge.X; - box.MaxEdge.X=temp; - } + std::swap(box.MinEdge.X, box.MaxEdge.X); if (box.MinEdge.Y > box.MaxEdge.Y) - { - temp=box.MinEdge.Y; - box.MinEdge.Y=box.MaxEdge.Y; - box.MaxEdge.Y=temp; - } + std::swap(box.MinEdge.Y, box.MaxEdge.Y); if (box.MinEdge.Z > box.MaxEdge.Z) - { - temp=box.MinEdge.Z; - box.MinEdge.Z=box.MaxEdge.Z; - box.MaxEdge.Z=temp; - } + std::swap(box.MinEdge.Z, box.MaxEdge.Z); // // Compute texture coords @@ -1840,7 +2080,18 @@ void mapblock_mesh_generate_special(MeshMakeData *data, // front tx1, 1-ty2, tx2, 1-ty1, }; - makeCuboid(&collector, box, tiles, 6, colors, txc, f.light_source); + if (data->m_smooth_lighting) { + u16 lights[8]; + for (int j = 0; j < 8; ++j) { + f32 x = (j & 4) ? dx2 : dx1; + f32 y = (j & 2) ? dy2 : dy1; + f32 z = (j & 1) ? dz2 : dz1; + lights[j] = blendLight(frame, core::vector3df(x, y, z)); + } + makeSmoothLightedCuboid(&collector, box, tiles, 6, lights, txc, f.light_source); + } else { + makeCuboid(&collector, box, tiles, 6, colors, txc, f.light_source); + } } break;} case NDT_MESH: @@ -1862,9 +2113,9 @@ void mapblock_mesh_generate_special(MeshMakeData *data, } } - if (f.mesh_ptr[facedir]) { + if (!data->m_smooth_lighting && f.mesh_ptr[facedir]) { // use cached meshes - for(u16 j = 0; j < f.mesh_ptr[0]->getMeshBufferCount(); j++) { + for (u16 j = 0; j < f.mesh_ptr[0]->getMeshBufferCount(); j++) { const TileSpec &tile = getNodeTileN(n, p, j, data); scene::IMeshBuffer *buf = f.mesh_ptr[facedir]->getMeshBuffer(j); collector.append(tile, (video::S3DVertex *) @@ -1879,14 +2130,25 @@ void mapblock_mesh_generate_special(MeshMakeData *data, rotateMeshBy6dFacedir(mesh, facedir); recalculateBoundingBox(mesh); meshmanip->recalculateNormals(mesh, true, false); - for(u16 j = 0; j < mesh->getMeshBufferCount(); j++) { + for (u16 j = 0; j < mesh->getMeshBufferCount(); j++) { const TileSpec &tile = getNodeTileN(n, p, j, data); scene::IMeshBuffer *buf = mesh->getMeshBuffer(j); - collector.append(tile, (video::S3DVertex *) - buf->getVertices(), buf->getVertexCount(), - buf->getIndices(), buf->getIndexCount(), pos, - encode_light_and_color(l, tile.color, f.light_source), - f.light_source); + video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices(); + u32 vertex_count = buf->getVertexCount(); + if (data->m_smooth_lighting) { + for (u16 m = 0; m < vertex_count; ++m) { + video::S3DVertex &vertex = vertices[m]; + vertex.Color = blendLight(frame, vertex.Pos, vertex.Normal, tile.color); + vertex.Pos += pos; + } + collector.append(tile, vertices, vertex_count, + buf->getIndices(), buf->getIndexCount()); + } else { + collector.append(tile, vertices, vertex_count, + buf->getIndices(), buf->getIndexCount(), pos, + encode_light_and_color(l, tile.color, f.light_source), + f.light_source); + } } mesh->drop(); } diff --git a/src/mapblock_mesh.cpp b/src/mapblock_mesh.cpp index dfd6f55a5..0744cd527 100644 --- a/src/mapblock_mesh.cpp +++ b/src/mapblock_mesh.cpp @@ -236,7 +236,7 @@ static u16 getSmoothLightCombined(v3s16 p, MeshMakeData *data) for (u32 i = 0; i < 8; i++) { - const MapNode &n = data->m_vmanip.getNodeRefUnsafeCheckFlags(p - dirs8[i]); + MapNode n = data->m_vmanip.getNodeNoExNoEmerge(p - dirs8[i]); // if it's CONTENT_IGNORE we can't do any light calculations if (n.getContent() == CONTENT_IGNORE) { diff --git a/src/nodedef.cpp b/src/nodedef.cpp index 98f795c7a..0bb150267 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -269,10 +269,15 @@ void TextureSettings::readSettings() bool enable_shaders = g_settings->getBool("enable_shaders"); bool enable_bumpmapping = g_settings->getBool("enable_bumpmapping"); bool enable_parallax_occlusion = g_settings->getBool("enable_parallax_occlusion"); + bool smooth_lighting = g_settings->getBool("smooth_lighting"); enable_mesh_cache = g_settings->getBool("enable_mesh_cache"); enable_minimap = g_settings->getBool("enable_minimap"); std::string leaves_style_str = g_settings->get("leaves_style"); + // Mesh cache is not supported in combination with smooth lighting + if (smooth_lighting) + enable_mesh_cache = false; + use_normal_texture = enable_shaders && (enable_bumpmapping || enable_parallax_occlusion); if (leaves_style_str == "fancy") { -- cgit v1.2.3 From 953cbb3b15997a0e7c7c32af2365cb5046a9e476 Mon Sep 17 00:00:00 2001 From: Paramat Date: Sat, 28 Jan 2017 10:07:35 +0000 Subject: Plantlike: Fix visual_scale being applied squared (#5115) Visual_scale was applied twice to plantlike by accident sometime between 2011 and 2013, squaring the requested scale value. Visual_scale is correctly applied once in it's other uses in signlike and torchlike. Two lines of code are removed, they also had no effect for the vast majority of nodes with the default visual_scale of 1.0. The texture continues to have it's base at ground level. --- src/content_mapblock.cpp | 2 -- 1 file changed, 2 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 45822666f..9923647bc 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -1602,8 +1602,6 @@ void mapblock_mesh_generate_special(MeshMakeData *data, } for (int i = 0; i < 4; i++) { - vertices[i].Pos *= f.visual_scale; - vertices[i].Pos.Y += BS/2 * (f.visual_scale - 1); if (data->m_smooth_lighting) vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); vertices[i].Pos += intToFloat(p, BS); -- cgit v1.2.3 From 7760948b7ca436ce0c7d26140dcd3867e81c99c9 Mon Sep 17 00:00:00 2001 From: Craig Robbins Date: Fri, 10 Feb 2017 22:21:49 +1000 Subject: Revert "Plantlike: Fix visual_scale being applied squared (#5115)" This reverts commit 953cbb3b15997a0e7c7c32af2365cb5046a9e476. --- src/content_mapblock.cpp | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 9923647bc..45822666f 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -1602,6 +1602,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data, } for (int i = 0; i < 4; i++) { + vertices[i].Pos *= f.visual_scale; + vertices[i].Pos.Y += BS/2 * (f.visual_scale - 1); if (data->m_smooth_lighting) vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); vertices[i].Pos += intToFloat(p, BS); -- cgit v1.2.3 From 1de08e196182498a931b496f79b1c1eaf3de7ca4 Mon Sep 17 00:00:00 2001 From: paramat Date: Fri, 10 Feb 2017 17:15:22 +0000 Subject: Plantlike: Fix visual_scale being applied squared This re-applies 2 commits that were reverted. Visual_scale was applied twice to plantlike by accident sometime between 2011 and 2013, squaring the requested scale value. Visual_scale is correctly applied once in it's other uses in signlike and torchlike. Two lines of code are removed, they also had no effect for the vast majority of nodes with the default visual_scale of 1.0. The texture continues to have it's base at ground level. Send sqrt(visual_scale) to old clients. Keep compatibility with protocol < 30 clients now that visual_scale is no longer applied twice to plantlike drawtype and mods are being updated to a new value. --- src/content_mapblock.cpp | 2 -- src/network/networkprotocol.h | 2 ++ src/nodedef.cpp | 10 +++++++--- 3 files changed, 9 insertions(+), 5 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 45822666f..9923647bc 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -1602,8 +1602,6 @@ void mapblock_mesh_generate_special(MeshMakeData *data, } for (int i = 0; i < 4; i++) { - vertices[i].Pos *= f.visual_scale; - vertices[i].Pos.Y += BS/2 * (f.visual_scale - 1); if (data->m_smooth_lighting) vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); vertices[i].Pos += intToFloat(p, BS); diff --git a/src/network/networkprotocol.h b/src/network/networkprotocol.h index a511d169b..5301cc91c 100644 --- a/src/network/networkprotocol.h +++ b/src/network/networkprotocol.h @@ -146,6 +146,8 @@ with this program; if not, write to the Free Software Foundation, Inc., PROTOCOL VERSION 30: New ContentFeatures serialization version 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) */ #define LATEST_PROTOCOL_VERSION 30 diff --git a/src/nodedef.cpp b/src/nodedef.cpp index 0bb150267..c717b62b9 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -1611,6 +1611,10 @@ void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const compatible_param_type_2 = CPT2_WALLMOUNTED; } + float compatible_visual_scale = visual_scale; + if (protocol_version < 30 && drawtype == NDT_PLANTLIKE) + compatible_visual_scale = sqrt(visual_scale); + if (protocol_version == 13) { writeU8(os, 5); // version @@ -1622,7 +1626,7 @@ void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const writeS16(os, i->second); } writeU8(os, drawtype); - writeF1000(os, visual_scale); + writeF1000(os, compatible_visual_scale); writeU8(os, 6); for (u32 i = 0; i < 6; i++) tiledef[i].serialize(os, protocol_version); @@ -1670,7 +1674,7 @@ void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const writeS16(os, i->second); } writeU8(os, drawtype); - writeF1000(os, visual_scale); + writeF1000(os, compatible_visual_scale); writeU8(os, 6); for (u32 i = 0; i < 6; i++) tiledef[i].serialize(os, protocol_version); @@ -1724,7 +1728,7 @@ void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const writeS16(os, i->second); } writeU8(os, drawtype); - writeF1000(os, visual_scale); + writeF1000(os, compatible_visual_scale); writeU8(os, 6); for (u32 i = 0; i < 6; i++) tiledef[i].serialize(os, protocol_version); -- cgit v1.2.3 From d4e0c0f9b818120286369b33b1bdb5eb6ece7a83 Mon Sep 17 00:00:00 2001 From: number Zero Date: Mon, 13 Feb 2017 19:31:43 +0300 Subject: Content_mapblock.cpp: Refactor --- src/content_mapblock.cpp | 3032 ++++++++++++++++---------------------------- src/content_mapblock.h | 124 +- src/mapblock_mesh.cpp | 5 +- src/nodedef.h | 18 + src/util/directiontables.h | 56 +- 5 files changed, 1295 insertions(+), 1940 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 9923647bc..18b4ef6dd 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -20,7 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "content_mapblock.h" #include "util/numeric.h" #include "util/directiontables.h" -#include "mapblock_mesh.h" // For MapBlock_LightColor() and MeshCollector +#include "mapblock_mesh.h" #include "settings.h" #include "nodedef.h" #include "client/tile.h" @@ -34,12 +34,13 @@ with this program; if not, write to the Free Software Foundation, Inc., // After this distance, it gives up and considers light level constant #define SMOOTH_LIGHTING_OVERSIZE 1.0 -struct LightFrame -{ - f32 lightsA[8]; - f32 lightsB[8]; - u8 light_source; -}; +// Node edge count (for glasslike-framed) +#define FRAMED_EDGE_COUNT 12 + +// Node neighbor count, including edge-connected, but not vertex-connected +// (for glasslike-framed) +// Corresponding offsets are listed in g_27dirs +#define FRAMED_NEIGHBOR_COUNT 18 static const v3s16 light_dirs[8] = { v3s16(-1, -1, -1), @@ -52,189 +53,135 @@ static const v3s16 light_dirs[8] = { v3s16( 1, 1, 1), }; -// Create a cuboid. -// collector - the MeshCollector for the resulting polygons -// box - the position and size of the box -// tiles - the tiles (materials) to use (for all 6 faces) -// tilecount - number of entries in tiles, 1<=tilecount<=6 -// c - colors of the cuboid's six sides -// txc - texture coordinates - this is a list of texture coordinates -// for the opposite corners of each face - therefore, there -// should be (2+2)*6=24 values in the list. Alternatively, -// pass NULL to use the entire texture for each face. The -// order of the faces in the list is up-down-right-left-back- -// front (compatible with ContentFeatures). If you specified -// 0,0,1,1 for each face, that would be the same as -// passing NULL. -// light source - if greater than zero, the box's faces will not be shaded -void makeCuboid(MeshCollector *collector, const aabb3f &box, - TileSpec *tiles, int tilecount, const video::SColor *c, - const f32* txc, const u8 light_source) +// Standard index set to make a quad on 4 vertices +static const u16 quad_indices[] = {0, 1, 2, 2, 3, 0}; + +const std::string MapblockMeshGenerator::raillike_groupname = "connect_to_raillike"; + +MapblockMeshGenerator::MapblockMeshGenerator(MeshMakeData *input, MeshCollector *output) { - assert(tilecount >= 1 && tilecount <= 6); // pre-condition + data = input; + collector = output; - v3f min = box.MinEdge; - v3f max = box.MaxEdge; + nodedef = data->m_client->ndef(); + smgr = data->m_client->getSceneManager(); + meshmanip = smgr->getMeshManipulator(); - if(txc == NULL) { - static const f32 txc_default[24] = { - 0,0,1,1, - 0,0,1,1, - 0,0,1,1, - 0,0,1,1, - 0,0,1,1, - 0,0,1,1 - }; - txc = txc_default; - } + enable_mesh_cache = g_settings->getBool("enable_mesh_cache") && + !data->m_smooth_lighting; // Mesh cache is not supported with smooth lighting - video::SColor c1 = c[0]; - video::SColor c2 = c[1]; - video::SColor c3 = c[2]; - video::SColor c4 = c[3]; - video::SColor c5 = c[4]; - video::SColor c6 = c[5]; - if (!light_source) { - applyFacesShading(c1, v3f(0, 1, 0)); - applyFacesShading(c2, v3f(0, -1, 0)); - applyFacesShading(c3, v3f(1, 0, 0)); - applyFacesShading(c4, v3f(-1, 0, 0)); - applyFacesShading(c5, v3f(0, 0, 1)); - applyFacesShading(c6, v3f(0, 0, -1)); - } + blockpos_nodes = data->m_blockpos * MAP_BLOCKSIZE; +} - video::S3DVertex vertices[24] = - { - // up - video::S3DVertex(min.X,max.Y,max.Z, 0,1,0, c1, txc[0],txc[1]), - video::S3DVertex(max.X,max.Y,max.Z, 0,1,0, c1, txc[2],txc[1]), - video::S3DVertex(max.X,max.Y,min.Z, 0,1,0, c1, txc[2],txc[3]), - video::S3DVertex(min.X,max.Y,min.Z, 0,1,0, c1, txc[0],txc[3]), - // down - video::S3DVertex(min.X,min.Y,min.Z, 0,-1,0, c2, txc[4],txc[5]), - video::S3DVertex(max.X,min.Y,min.Z, 0,-1,0, c2, txc[6],txc[5]), - video::S3DVertex(max.X,min.Y,max.Z, 0,-1,0, c2, txc[6],txc[7]), - video::S3DVertex(min.X,min.Y,max.Z, 0,-1,0, c2, txc[4],txc[7]), - // right - video::S3DVertex(max.X,max.Y,min.Z, 1,0,0, c3, txc[ 8],txc[9]), - video::S3DVertex(max.X,max.Y,max.Z, 1,0,0, c3, txc[10],txc[9]), - video::S3DVertex(max.X,min.Y,max.Z, 1,0,0, c3, txc[10],txc[11]), - video::S3DVertex(max.X,min.Y,min.Z, 1,0,0, c3, txc[ 8],txc[11]), - // left - video::S3DVertex(min.X,max.Y,max.Z, -1,0,0, c4, txc[12],txc[13]), - video::S3DVertex(min.X,max.Y,min.Z, -1,0,0, c4, txc[14],txc[13]), - video::S3DVertex(min.X,min.Y,min.Z, -1,0,0, c4, txc[14],txc[15]), - video::S3DVertex(min.X,min.Y,max.Z, -1,0,0, c4, txc[12],txc[15]), - // back - video::S3DVertex(max.X,max.Y,max.Z, 0,0,1, c5, txc[16],txc[17]), - video::S3DVertex(min.X,max.Y,max.Z, 0,0,1, c5, txc[18],txc[17]), - video::S3DVertex(min.X,min.Y,max.Z, 0,0,1, c5, txc[18],txc[19]), - video::S3DVertex(max.X,min.Y,max.Z, 0,0,1, c5, txc[16],txc[19]), - // front - video::S3DVertex(min.X,max.Y,min.Z, 0,0,-1, c6, txc[20],txc[21]), - video::S3DVertex(max.X,max.Y,min.Z, 0,0,-1, c6, txc[22],txc[21]), - video::S3DVertex(max.X,min.Y,min.Z, 0,0,-1, c6, txc[22],txc[23]), - video::S3DVertex(min.X,min.Y,min.Z, 0,0,-1, c6, txc[20],txc[23]), - }; +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; +} - for(int i = 0; i < 6; i++) - { - switch (tiles[MYMIN(i, tilecount-1)].rotation) - { - case 0: - break; - case 1: //R90 - for (int x = 0; x < 4; x++) - vertices[i*4+x].TCoords.rotateBy(90,irr::core::vector2df(0, 0)); - break; - case 2: //R180 - for (int x = 0; x < 4; x++) - vertices[i*4+x].TCoords.rotateBy(180,irr::core::vector2df(0, 0)); - break; - case 3: //R270 - for (int x = 0; x < 4; x++) - vertices[i*4+x].TCoords.rotateBy(270,irr::core::vector2df(0, 0)); - break; - case 4: //FXR90 - for (int x = 0; x < 4; x++){ - vertices[i*4+x].TCoords.X = 1.0 - vertices[i*4+x].TCoords.X; - vertices[i*4+x].TCoords.rotateBy(90,irr::core::vector2df(0, 0)); - } - break; - case 5: //FXR270 - for (int x = 0; x < 4; x++){ - vertices[i*4+x].TCoords.X = 1.0 - vertices[i*4+x].TCoords.X; - vertices[i*4+x].TCoords.rotateBy(270,irr::core::vector2df(0, 0)); - } - break; - case 6: //FYR90 - for (int x = 0; x < 4; x++){ - vertices[i*4+x].TCoords.Y = 1.0 - vertices[i*4+x].TCoords.Y; - vertices[i*4+x].TCoords.rotateBy(90,irr::core::vector2df(0, 0)); - } - break; - case 7: //FYR270 - for (int x = 0; x < 4; x++){ - vertices[i*4+x].TCoords.Y = 1.0 - vertices[i*4+x].TCoords.Y; - vertices[i*4+x].TCoords.rotateBy(270,irr::core::vector2df(0, 0)); - } - break; - case 8: //FX - for (int x = 0; x < 4; x++){ - vertices[i*4+x].TCoords.X = 1.0 - vertices[i*4+x].TCoords.X; - } - break; - case 9: //FY - for (int x = 0; x < 4; x++){ - vertices[i*4+x].TCoords.Y = 1.0 - vertices[i*4+x].TCoords.Y; - } - break; - default: - break; - } - } - u16 indices[] = {0,1,2,2,3,0}; - // Add to mesh collector - for (s32 j = 0; j < 24; j += 4) { - int tileindex = MYMIN(j / 4, tilecount - 1); - collector->append(tiles[tileindex], vertices + j, 4, indices, 6); +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); +} + +TileSpec MapblockMeshGenerator::getTile(const v3s16& direction) +{ + return getNodeTile(n, p, direction, data); +} + +void MapblockMeshGenerator::drawQuad(v3f *coords, const v3s16 &normal) +{ + static const v2f tcoords[4] = {v2f(0, 1), v2f(1, 1), v2f(1, 0), v2f(0, 0)}; + video::S3DVertex vertices[4]; + bool shade_face = !f->light_source && (normal != v3s16(0, 0, 0)); + v3f normal2(normal.X, normal.Y, normal.Z); + for (int j = 0; j < 4; j++) { + vertices[j].Pos = coords[j] + origin; + vertices[j].Normal = normal2; + if (data->m_smooth_lighting) + vertices[j].Color = blendLight(coords[j], tile.color); + else + vertices[j].Color = color; + if (shade_face) + applyFacesShading(vertices[j].Color, normal2); + vertices[j].TCoords = tcoords[j]; } + collector->append(tile, vertices, 4, quad_indices, 6); } // Create a cuboid. -// collector - the MeshCollector for the resulting polygons -// box - the position and size of the box // tiles - the tiles (materials) to use (for all 6 faces) // tilecount - number of entries in tiles, 1<=tilecount<=6 -// lights - vertex light levels. The order is the same as in light_dirs +// lights - vertex light levels. The order is the same as in light_dirs. +// NULL may be passed if smooth lighting is disabled. // txc - texture coordinates - this is a list of texture coordinates // for the opposite corners of each face - therefore, there -// should be (2+2)*6=24 values in the list. Alternatively, pass -// NULL to use the entire texture for each face. The order of +// should be (2+2)*6=24 values in the list. The order of // the faces in the list is up-down-right-left-back-front -// (compatible with ContentFeatures). If you specified 0,0,1,1 -// for each face, that would be the same as passing NULL. -// light_source - node light emission -static void makeSmoothLightedCuboid(MeshCollector *collector, const aabb3f &box, - TileSpec *tiles, int tilecount, const u16 *lights , const f32 *txc, - const u8 light_source) +// (compatible with ContentFeatures). +void MapblockMeshGenerator::drawCuboid(const aabb3f &box, + TileSpec *tiles, int tilecount, const u16 *lights, const f32 *txc) { assert(tilecount >= 1 && tilecount <= 6); // pre-condition v3f min = box.MinEdge; v3f max = box.MaxEdge; - if (txc == NULL) { - static const f32 txc_default[24] = { - 0,0,1,1, - 0,0,1,1, - 0,0,1,1, - 0,0,1,1, - 0,0,1,1, - 0,0,1,1 - }; - txc = txc_default; + 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); + } + if (!f->light_source) { + applyFacesShading(colors[0], v3f(0, 1, 0)); + applyFacesShading(colors[1], v3f(0, -1, 0)); + applyFacesShading(colors[2], v3f(1, 0, 0)); + applyFacesShading(colors[3], v3f(-1, 0, 0)); + applyFacesShading(colors[4], v3f(0, 0, 1)); + applyFacesShading(colors[5], v3f(0, 0, -1)); + } } + + video::S3DVertex vertices[24] = { + // top + video::S3DVertex(min.X, max.Y, max.Z, 0, 1, 0, colors[0], txc[0], txc[1]), + video::S3DVertex(max.X, max.Y, max.Z, 0, 1, 0, colors[0], txc[2], txc[1]), + video::S3DVertex(max.X, max.Y, min.Z, 0, 1, 0, colors[0], txc[2], txc[3]), + video::S3DVertex(min.X, max.Y, min.Z, 0, 1, 0, colors[0], txc[0], txc[3]), + // bottom + video::S3DVertex(min.X, min.Y, min.Z, 0, -1, 0, colors[1], txc[4], txc[5]), + video::S3DVertex(max.X, min.Y, min.Z, 0, -1, 0, colors[1], txc[6], txc[5]), + video::S3DVertex(max.X, min.Y, max.Z, 0, -1, 0, colors[1], txc[6], txc[7]), + video::S3DVertex(min.X, min.Y, max.Z, 0, -1, 0, colors[1], txc[4], txc[7]), + // right + video::S3DVertex(max.X, max.Y, min.Z, 1, 0, 0, colors[2], txc[ 8], txc[9]), + video::S3DVertex(max.X, max.Y, max.Z, 1, 0, 0, colors[2], txc[10], txc[9]), + video::S3DVertex(max.X, min.Y, max.Z, 1, 0, 0, colors[2], txc[10], txc[11]), + video::S3DVertex(max.X, min.Y, min.Z, 1, 0, 0, colors[2], txc[ 8], txc[11]), + // left + video::S3DVertex(min.X, max.Y, max.Z, -1, 0, 0, colors[3], txc[12], txc[13]), + video::S3DVertex(min.X, max.Y, min.Z, -1, 0, 0, colors[3], txc[14], txc[13]), + video::S3DVertex(min.X, min.Y, min.Z, -1, 0, 0, colors[3], txc[14], txc[15]), + video::S3DVertex(min.X, min.Y, max.Z, -1, 0, 0, colors[3], txc[12], txc[15]), + // back + video::S3DVertex(max.X, max.Y, max.Z, 0, 0, 1, colors[4], txc[16], txc[17]), + video::S3DVertex(min.X, max.Y, max.Z, 0, 0, 1, colors[4], txc[18], txc[17]), + video::S3DVertex(min.X, min.Y, max.Z, 0, 0, 1, colors[4], txc[18], txc[19]), + video::S3DVertex(max.X, min.Y, max.Z, 0, 0, 1, colors[4], txc[16], txc[19]), + // front + video::S3DVertex(min.X, max.Y, min.Z, 0, 0, -1, colors[5], txc[20], txc[21]), + video::S3DVertex(max.X, max.Y, min.Z, 0, 0, -1, colors[5], txc[22], txc[21]), + video::S3DVertex(max.X, min.Y, min.Z, 0, 0, -1, colors[5], txc[22], txc[23]), + video::S3DVertex(min.X, min.Y, min.Z, 0, 0, -1, colors[5], txc[20], txc[23]), + }; + static const u8 light_indices[24] = { 3, 7, 6, 2, 0, 4, 5, 1, @@ -243,152 +190,83 @@ static void makeSmoothLightedCuboid(MeshCollector *collector, const aabb3f &box, 7, 3, 1, 5, 2, 6, 4, 0 }; - video::S3DVertex vertices[24] = { - // up - video::S3DVertex(min.X, max.Y, max.Z, 0, 1, 0, video::SColor(), txc[0], txc[1]), - video::S3DVertex(max.X, max.Y, max.Z, 0, 1, 0, video::SColor(), txc[2], txc[1]), - video::S3DVertex(max.X, max.Y, min.Z, 0, 1, 0, video::SColor(), txc[2], txc[3]), - video::S3DVertex(min.X, max.Y, min.Z, 0, 1, 0, video::SColor(), txc[0], txc[3]), - // down - video::S3DVertex(min.X, min.Y, min.Z, 0, -1, 0, video::SColor(), txc[4], txc[5]), - video::S3DVertex(max.X, min.Y, min.Z, 0, -1, 0, video::SColor(), txc[6], txc[5]), - video::S3DVertex(max.X, min.Y, max.Z, 0, -1, 0, video::SColor(), txc[6], txc[7]), - video::S3DVertex(min.X, min.Y, max.Z, 0, -1, 0, video::SColor(), txc[4], txc[7]), - // right - video::S3DVertex(max.X, max.Y, min.Z, 1, 0, 0, video::SColor(), txc[ 8], txc[9]), - video::S3DVertex(max.X, max.Y, max.Z, 1, 0, 0, video::SColor(), txc[10], txc[9]), - video::S3DVertex(max.X, min.Y, max.Z, 1, 0, 0, video::SColor(), txc[10], txc[11]), - video::S3DVertex(max.X, min.Y, min.Z, 1, 0, 0, video::SColor(), txc[ 8], txc[11]), - // left - video::S3DVertex(min.X, max.Y, max.Z, -1, 0, 0, video::SColor(), txc[12], txc[13]), - video::S3DVertex(min.X, max.Y, min.Z, -1, 0, 0, video::SColor(), txc[14], txc[13]), - video::S3DVertex(min.X, min.Y, min.Z, -1, 0, 0, video::SColor(), txc[14], txc[15]), - video::S3DVertex(min.X, min.Y, max.Z, -1, 0, 0, video::SColor(), txc[12], txc[15]), - // back - video::S3DVertex(max.X, max.Y, max.Z, 0, 0, 1, video::SColor(), txc[16], txc[17]), - video::S3DVertex(min.X, max.Y, max.Z, 0, 0, 1, video::SColor(), txc[18], txc[17]), - video::S3DVertex(min.X, min.Y, max.Z, 0, 0, 1, video::SColor(), txc[18], txc[19]), - video::S3DVertex(max.X, min.Y, max.Z, 0, 0, 1, video::SColor(), txc[16], txc[19]), - // front - video::S3DVertex(min.X, max.Y, min.Z, 0, 0, -1, video::SColor(), txc[20], txc[21]), - video::S3DVertex(max.X, max.Y, min.Z, 0, 0, -1, video::SColor(), txc[22], txc[21]), - video::S3DVertex(max.X, min.Y, min.Z, 0, 0, -1, video::SColor(), txc[22], txc[23]), - video::S3DVertex(min.X, min.Y, min.Z, 0, 0, -1, video::SColor(), txc[20], txc[23]), - }; - for(int i = 0; i < 6; i++) { - switch (tiles[MYMIN(i, tilecount-1)].rotation) { - case 0: - break; - case 1: //R90 - for (int x = 0; x < 4; x++) - vertices[i*4+x].TCoords.rotateBy(90,irr::core::vector2df(0, 0)); - break; - case 2: //R180 - for (int x = 0; x < 4; x++) - vertices[i*4+x].TCoords.rotateBy(180,irr::core::vector2df(0, 0)); - break; - case 3: //R270 - for (int x = 0; x < 4; x++) - vertices[i*4+x].TCoords.rotateBy(270,irr::core::vector2df(0, 0)); - break; - case 4: //FXR90 - for (int x = 0; x < 4; x++) { - vertices[i*4+x].TCoords.X = 1.0 - vertices[i*4+x].TCoords.X; - vertices[i*4+x].TCoords.rotateBy(90,irr::core::vector2df(0, 0)); - } - break; - case 5: //FXR270 - for (int x = 0; x < 4; x++) { - vertices[i*4+x].TCoords.X = 1.0 - vertices[i*4+x].TCoords.X; - vertices[i*4+x].TCoords.rotateBy(270,irr::core::vector2df(0, 0)); - } - break; - case 6: //FYR90 - for (int x = 0; x < 4; x++) { - vertices[i*4+x].TCoords.Y = 1.0 - vertices[i*4+x].TCoords.Y; - vertices[i*4+x].TCoords.rotateBy(90,irr::core::vector2df(0, 0)); - } - break; - case 7: //FYR270 - for (int x = 0; x < 4; x++) { - vertices[i*4+x].TCoords.Y = 1.0 - vertices[i*4+x].TCoords.Y; - vertices[i*4+x].TCoords.rotateBy(270,irr::core::vector2df(0, 0)); - } - break; - case 8: //FX - for (int x = 0; x < 4; x++) { - vertices[i*4+x].TCoords.X = 1.0 - vertices[i*4+x].TCoords.X; - } - break; - case 9: //FY - for (int x = 0; x < 4; x++) { - vertices[i*4+x].TCoords.Y = 1.0 - vertices[i*4+x].TCoords.Y; + for (int face = 0; face < 6; face++) { + int tileindex = MYMIN(face, tilecount - 1); + const TileSpec &tile = tiles[tileindex]; + for (int j = 0; j < 4; j++) { + video::S3DVertex &vertex = vertices[face * 4 + j]; + v2f &tcoords = vertex.TCoords; + switch (tile.rotation) { + case 0: + break; + case 1: // R90 + tcoords.rotateBy(90, irr::core::vector2df(0, 0)); + break; + case 2: // R180 + tcoords.rotateBy(180, irr::core::vector2df(0, 0)); + break; + case 3: // R270 + tcoords.rotateBy(270, irr::core::vector2df(0, 0)); + break; + case 4: // FXR90 + tcoords.X = 1.0 - tcoords.X; + tcoords.rotateBy(90, irr::core::vector2df(0, 0)); + break; + case 5: // FXR270 + tcoords.X = 1.0 - tcoords.X; + tcoords.rotateBy(270, irr::core::vector2df(0, 0)); + break; + case 6: // FYR90 + tcoords.Y = 1.0 - tcoords.Y; + tcoords.rotateBy(90, irr::core::vector2df(0, 0)); + break; + case 7: // FYR270 + tcoords.Y = 1.0 - tcoords.Y; + tcoords.rotateBy(270, irr::core::vector2df(0, 0)); + break; + case 8: // FX + tcoords.X = 1.0 - tcoords.X; + break; + case 9: // FY + tcoords.Y = 1.0 - tcoords.Y; + break; + default: + break; } - break; - default: - break; } } - u16 indices[] = {0,1,2,2,3,0}; - for (s32 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, light_source); - if (!light_source) - applyFacesShading(vertices[j].Color, vertices[j].Normal); + + 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); + if (!f->light_source) + applyFacesShading(vertices[j].Color, vertices[j].Normal); + } } + // Add to mesh collector - for (s32 k = 0; k < 6; ++k) { + for (int k = 0; k < 6; ++k) { int tileindex = MYMIN(k, tilecount - 1); - collector->append(tiles[tileindex], vertices + 4 * k, 4, indices, 6); + collector->append(tiles[tileindex], vertices + 4 * k, 4, quad_indices, 6); } } -// Create a cuboid. -// collector - the MeshCollector for the resulting polygons -// box - the position and size of the box -// tiles - the tiles (materials) to use (for all 6 faces) -// tilecount - number of entries in tiles, 1<=tilecount<=6 -// c - color of the cuboid -// txc - texture coordinates - this is a list of texture coordinates -// for the opposite corners of each face - therefore, there -// should be (2+2)*6=24 values in the list. Alternatively, -// pass NULL to use the entire texture for each face. The -// order of the faces in the list is up-down-right-left-back- -// front (compatible with ContentFeatures). If you specified -// 0,0,1,1 for each face, that would be the same as -// passing NULL. -// light source - if greater than zero, the box's faces will not be shaded -void makeCuboid(MeshCollector *collector, const aabb3f &box, TileSpec *tiles, - int tilecount, const video::SColor &c, const f32* txc, - const u8 light_source) -{ - video::SColor color[6]; - for (u8 i = 0; i < 6; i++) - color[i] = c; - makeCuboid(collector, box, tiles, tilecount, color, txc, light_source); -} - // Gets the base lighting values for a node -// frame - resulting (opaque) data -// p - node position (absolute) -// data - ... -// light_source - node light emission level -static void getSmoothLightFrame(LightFrame *frame, const v3s16 &p, MeshMakeData *data, u8 light_source) +void MapblockMeshGenerator::getSmoothLightFrame() { for (int k = 0; k < 8; ++k) { - u16 light = getSmoothLight(p, light_dirs[k], data); - frame->lightsA[k] = light & 0xff; - frame->lightsB[k] = light >> 8; + u16 light = getSmoothLight(blockpos_nodes + p, light_dirs[k], data); + frame.lightsA[k] = light & 0xff; + frame.lightsB[k] = light >> 8; } - frame->light_source = light_source; } // Calculates vertex light level -// frame - light values from getSmoothLightFrame() -// vertex_pos - vertex position in the node (coordinates are clamped to [0.0, 1.0] or so) -static u16 blendLight(const LightFrame &frame, const core::vector3df& vertex_pos) +// vertex_pos - vertex position in the node (coordinates are clamped to [0.0, 1.0] or so) +u16 MapblockMeshGenerator::blendLight(const v3f &vertex_pos) { f32 x = core::clamp(vertex_pos.X / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE); f32 y = core::clamp(vertex_pos.Y / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE); @@ -408,47 +286,26 @@ static u16 blendLight(const LightFrame &frame, const core::vector3df& vertex_pos } // Calculates vertex color to be used in mapblock mesh -// frame - light values from getSmoothLightFrame() -// vertex_pos - vertex position in the node (coordinates are clamped to [0.0, 1.0] or so) -// tile_color - node's tile color -static video::SColor blendLight(const LightFrame &frame, - const core::vector3df& vertex_pos, video::SColor tile_color) -{ - u16 light = blendLight(frame, vertex_pos); - return encode_light_and_color(light, tile_color, frame.light_source); -} - -static video::SColor blendLight(const LightFrame &frame, - const core::vector3df& vertex_pos, const core::vector3df& vertex_normal, +// 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 color = blendLight(frame, vertex_pos, tile_color); - if (!frame.light_source) - applyFacesShading(color, vertex_normal); - return color; + u16 light = blendLight(vertex_pos); + return encode_light_and_color(light, tile_color, f->light_source); } -static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef, - MeshMakeData *data, MapNode n, int v, int *neighbors) +video::SColor MapblockMeshGenerator::blendLight(const v3f &vertex_pos, + const v3f &vertex_normal, video::SColor tile_color) { - MapNode n2 = data->m_vmanip.getNodeNoEx(p); - if (nodedef->nodeboxConnects(n, n2, v)) - *neighbors |= v; + video::SColor color = blendLight(vertex_pos, tile_color); + if (!f->light_source) + applyFacesShading(color, vertex_normal); + return color; } -static void makeAutoLightedCuboid(MeshCollector *collector, MeshMakeData *data, - const v3f &pos, aabb3f box, TileSpec &tile, - /* pre-computed, for non-smooth lighting only */ const video::SColor color, - /* for smooth lighting only */ const LightFrame &frame) +void MapblockMeshGenerator::generateCuboidTextureCoords(const aabb3f &box, f32 *coords) { - f32 dx1 = box.MinEdge.X; - f32 dy1 = box.MinEdge.Y; - f32 dz1 = box.MinEdge.Z; - f32 dx2 = box.MaxEdge.X; - f32 dy2 = box.MaxEdge.Y; - f32 dz2 = box.MaxEdge.Z; - box.MinEdge += pos; - box.MaxEdge += pos; f32 tx1 = (box.MinEdge.X / BS) + 0.5; f32 ty1 = (box.MinEdge.Y / BS) + 0.5; f32 tz1 = (box.MinEdge.Z / BS) + 0.5; @@ -456,63 +313,52 @@ static void makeAutoLightedCuboid(MeshCollector *collector, MeshMakeData *data, f32 ty2 = (box.MaxEdge.Y / BS) + 0.5; f32 tz2 = (box.MaxEdge.Z / BS) + 0.5; f32 txc[24] = { - tx1, 1-tz2, tx2, 1-tz1, // up - tx1, tz1, tx2, tz2, // down - tz1, 1-ty2, tz2, 1-ty1, // right - 1-tz2, 1-ty2, 1-tz1, 1-ty1, // left - 1-tx2, 1-ty2, 1-tx1, 1-ty1, // back - tx1, 1-ty2, tx2, 1-ty1, // front + tx1, 1 - tz2, tx2, 1 - tz1, // up + tx1, tz1, tx2, tz2, // down + tz1, 1 - ty2, tz2, 1 - ty1, // right + 1 - tz2, 1 - ty2, 1 - tz1, 1 - ty1, // left + 1 - tx2, 1 - ty2, 1 - tx1, 1 - ty1, // back + tx1, 1 - ty2, tx2, 1 - ty1, // front }; - if (data->m_smooth_lighting) { - u16 lights[8]; - for (int j = 0; j < 8; ++j) { - f32 x = (j & 4) ? dx2 : dx1; - f32 y = (j & 2) ? dy2 : dy1; - f32 z = (j & 1) ? dz2 : dz1; - lights[j] = blendLight(frame, core::vector3df(x, y, z)); - } - makeSmoothLightedCuboid(collector, box, &tile, 1, lights, txc, frame.light_source); - } else { - makeCuboid(collector, box, &tile, 1, color, txc, frame.light_source); - } + for (int i = 0; i != 24; ++i) + coords[i] = txc[i]; } -static void makeAutoLightedCuboidEx(MeshCollector *collector, MeshMakeData *data, - const v3f &pos, aabb3f box, TileSpec &tile, f32 *txc, - /* pre-computed, for non-smooth lighting only */ const video::SColor color, - /* for smooth lighting only */ const LightFrame &frame) +void MapblockMeshGenerator::drawAutoLightedCuboid(aabb3f box, const f32 *txc, + TileSpec *tiles, int tile_count) { + f32 texture_coord_buf[24]; f32 dx1 = box.MinEdge.X; f32 dy1 = box.MinEdge.Y; f32 dz1 = box.MinEdge.Z; f32 dx2 = box.MaxEdge.X; f32 dy2 = box.MaxEdge.Y; f32 dz2 = box.MaxEdge.Z; - box.MinEdge += pos; - box.MaxEdge += pos; + box.MinEdge += origin; + box.MaxEdge += origin; + if (!txc) { + generateCuboidTextureCoords(box, texture_coord_buf); + txc = texture_coord_buf; + } + if (!tiles) { + tiles = &tile; + tile_count = 1; + } if (data->m_smooth_lighting) { u16 lights[8]; for (int j = 0; j < 8; ++j) { - f32 x = (j & 4) ? dx2 : dx1; - f32 y = (j & 2) ? dy2 : dy1; - f32 z = (j & 1) ? dz2 : dz1; - lights[j] = blendLight(frame, core::vector3df(x, y, z)); + v3f d; + d.X = (j & 4) ? dx2 : dx1; + d.Y = (j & 2) ? dy2 : dy1; + d.Z = (j & 1) ? dz2 : dz1; + lights[j] = blendLight(d); } - makeSmoothLightedCuboid(collector, box, &tile, 1, lights, txc, frame.light_source); + drawCuboid(box, tiles, tile_count, lights, txc); } else { - makeCuboid(collector, box, &tile, 1, color, txc, frame.light_source); + drawCuboid(box, tiles, tile_count, NULL, txc); } } -// For use in mapblock_mesh_generate_special -// X,Y,Z of position must be -1,0,1 -// This expression is a simplification of -// 3 * 3 * (pos.X + 1) + 3 * (pos.Y + 1) + (pos.Z + 1) -static inline int NeighborToIndex(const v3s16 &pos) -{ - return 9 * pos.X + 3 * pos.Y + pos.Z + 13; -} - /*! * Returns the i-th special tile for a map node. */ @@ -525,1633 +371,949 @@ static TileSpec getSpecialTile(const ContentFeatures &f, return copy; } -/* - TODO: Fix alpha blending for special nodes - Currently only the last element rendered is blended correct -*/ -void mapblock_mesh_generate_special(MeshMakeData *data, - MeshCollector &collector) +void MapblockMeshGenerator::prepareLiquidNodeDrawing(bool flowing) { - INodeDefManager *nodedef = data->m_client->ndef(); - scene::ISceneManager* smgr = data->m_client->getSceneManager(); - scene::IMeshManipulator* meshmanip = smgr->getMeshManipulator(); - - // 0ms - //TimeTaker timer("mapblock_mesh_generate_special()"); - - /* - Some settings - */ - bool enable_mesh_cache = g_settings->getBool("enable_mesh_cache") && - !data->m_smooth_lighting; // Mesh cache is not supported with smooth lighting - - v3s16 blockpos_nodes = data->m_blockpos*MAP_BLOCKSIZE; - - for(s16 z = 0; z < MAP_BLOCKSIZE; z++) - for(s16 y = 0; y < MAP_BLOCKSIZE; y++) - for(s16 x = 0; x < MAP_BLOCKSIZE; x++) - { - v3s16 p(x,y,z); + tile_liquid_top = getSpecialTile(*f, n, 0); + tile_liquid = getSpecialTile(*f, n, flowing ? 1 : 0); + + MapNode ntop = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(p.X, p.Y + 1, p.Z)); + c_flowing = nodedef->getId(f->liquid_alternative_flowing); + c_source = nodedef->getId(f->liquid_alternative_source); + top_is_same_liquid = (ntop.getContent() == c_flowing) || (ntop.getContent() == c_source); + + if (data->m_smooth_lighting) + return; // don't need to pre-compute anything in this case + + if (f->light_source != 0) { + // If this liquid emits light and doesn't contain light, draw + // it at what it emits, for an increased effect + light = decode_light(f->light_source); + light = light | (light << 8); + } else if (nodedef->get(ntop).param_type == CPT_LIGHT) { + // Otherwise, use the light of the node on top if possible + light = getInteriorLight(ntop, 0, nodedef); + } - MapNode n = data->m_vmanip.getNodeNoEx(blockpos_nodes + p); - const ContentFeatures &f = nodedef->get(n); + 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); +} - // Only solidness=0 stuff is drawn here - if(f.solidness != 0) - continue; +void MapblockMeshGenerator::getLiquidNeighborhood(bool flowing) +{ + u8 range = rangelim(nodedef->get(c_flowing).liquid_range, 1, 8); - if (f.drawtype == NDT_AIRLIKE) + for (int w = -1; w <= 1; w++) + for (int u = -1; u <= 1; u++) { + // Skip getting unneeded data + if (!flowing && u && w) continue; - LightFrame frame; - if (data->m_smooth_lighting) - getSmoothLightFrame(&frame, blockpos_nodes + p, data, f.light_source); - else - frame.light_source = f.light_source; - - switch(f.drawtype) { - default: - infostream << "Got " << f.drawtype << std::endl; - FATAL_ERROR("Unknown drawtype"); - break; - case NDT_LIQUID: - { - /* - Add water sources to mesh if using new style - */ - TileSpec tile_liquid = getSpecialTile(f, n, 0); - TileSpec tile_liquid_bfculled = getNodeTile(n, p, v3s16(0,0,0), data); - u16 l = getInteriorLight(n, 0, nodedef); - video::SColor c1 = encode_light_and_color(l, - tile_liquid.color, f.light_source); - video::SColor c2 = encode_light_and_color(l, - tile_liquid_bfculled.color, f.light_source); - - bool top_is_same_liquid = false; - MapNode ntop = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x,y+1,z)); - content_t c_flowing = nodedef->getId(f.liquid_alternative_flowing); - content_t c_source = nodedef->getId(f.liquid_alternative_source); - if(ntop.getContent() == c_flowing || ntop.getContent() == c_source) - top_is_same_liquid = true; - - /* - Generate sides - */ - v3s16 side_dirs[4] = { - v3s16(1,0,0), - v3s16(-1,0,0), - v3s16(0,0,1), - v3s16(0,0,-1), - }; - for(u32 i=0; i<4; i++) - { - v3s16 dir = side_dirs[i]; - - MapNode neighbor = data->m_vmanip.getNodeNoEx(blockpos_nodes + p + dir); - content_t neighbor_content = neighbor.getContent(); - const ContentFeatures &n_feat = nodedef->get(neighbor_content); - MapNode n_top = data->m_vmanip.getNodeNoEx(blockpos_nodes + p + dir+ v3s16(0,1,0)); - content_t n_top_c = n_top.getContent(); - - if(neighbor_content == CONTENT_IGNORE) - continue; - - /* - If our topside is liquid and neighbor's topside - is liquid, don't draw side face - */ - if(top_is_same_liquid && (n_top_c == c_flowing || - n_top_c == c_source || n_top_c == CONTENT_IGNORE)) - continue; - - // Don't draw face if neighbor is blocking the view - if(n_feat.solidness == 2) - continue; - - bool neighbor_is_same_liquid = (neighbor_content == c_source - || neighbor_content == c_flowing); - - // Don't draw any faces if neighbor same is liquid and top is - // same liquid - if(neighbor_is_same_liquid && !top_is_same_liquid) - continue; - - // Use backface culled material if neighbor doesn't have a - // solidness of 0 - const TileSpec *current_tile = &tile_liquid; - video::SColor *c = &c1; - if(n_feat.solidness != 0 || n_feat.visual_solidness != 0) { - current_tile = &tile_liquid_bfculled; - c = &c2; - } - - video::S3DVertex vertices[4] = - { - video::S3DVertex(-BS/2,0,BS/2,0,0,0, *c, 0,1), - video::S3DVertex(BS/2,0,BS/2,0,0,0, *c, 1,1), - video::S3DVertex(BS/2,0,BS/2, 0,0,0, *c, 1,0), - video::S3DVertex(-BS/2,0,BS/2, 0,0,0, *c, 0,0), - }; - - /* - If our topside is liquid, set upper border of face - at upper border of node - */ - if (top_is_same_liquid) { - vertices[2].Pos.Y = 0.5 * BS; - vertices[3].Pos.Y = 0.5 * BS; - } else { - /* - Otherwise upper position of face is liquid level - */ - vertices[2].Pos.Y = 0.5 * BS; - vertices[3].Pos.Y = 0.5 * BS; - } - /* - If neighbor is liquid, lower border of face is liquid level - */ - if (neighbor_is_same_liquid) { - vertices[0].Pos.Y = 0.5 * BS; - vertices[1].Pos.Y = 0.5 * BS; - } else { - /* - If neighbor is not liquid, lower border of face is - lower border of node - */ - vertices[0].Pos.Y = -0.5 * BS; - vertices[1].Pos.Y = -0.5 * BS; - } - - for (s32 j = 0; j < 4; j++) { - if(dir == v3s16(0,0,1)) - vertices[j].Pos.rotateXZBy(0); - if(dir == v3s16(0,0,-1)) - vertices[j].Pos.rotateXZBy(180); - if(dir == v3s16(-1,0,0)) - vertices[j].Pos.rotateXZBy(90); - if(dir == v3s16(1,0,-0)) - vertices[j].Pos.rotateXZBy(-90); - - // Do this to not cause glitches when two liquids are - // side-by-side - /*if(neighbor_is_same_liquid == false){ - vertices[j].Pos.X *= 0.98; - vertices[j].Pos.Z *= 0.98; - }*/ - - if (data->m_smooth_lighting) - vertices[j].Color = blendLight(frame, vertices[j].Pos, current_tile->color); - vertices[j].Pos += intToFloat(p, BS); - } - - u16 indices[] = {0,1,2,2,3,0}; - // Add to mesh collector - collector.append(*current_tile, vertices, 4, indices, 6); - } + NeighborData &neighbor = liquid_neighbors[w + 1][u + 1]; + v3s16 p2 = p + v3s16(u, 0, w); + MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); + neighbor.content = n2.getContent(); + neighbor.level = -0.5 * BS; + neighbor.is_same_liquid = false; + neighbor.top_is_same_liquid = false; - /* - Generate top - */ - if(top_is_same_liquid) - continue; + if (neighbor.content == CONTENT_IGNORE) + continue; - video::S3DVertex vertices[4] = - { - video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c1, 0,1), - video::S3DVertex(BS/2,0,BS/2, 0,0,0, c1, 1,1), - video::S3DVertex(BS/2,0,-BS/2, 0,0,0, c1, 1,0), - video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c1, 0,0), - }; + if (neighbor.content == c_source) { + neighbor.is_same_liquid = true; + neighbor.level = 0.5 * BS; + } else if (neighbor.content == c_flowing) { + neighbor.is_same_liquid = true; + u8 liquid_level = (n2.param2 & LIQUID_LEVEL_MASK); + if (liquid_level <= LIQUID_LEVEL_MAX + 1 - range) + liquid_level = 0; + else + liquid_level -= (LIQUID_LEVEL_MAX + 1 - range); + neighbor.level = (-0.5 + (liquid_level + 0.5) / range) * BS; + } - for (s32 i = 0; i < 4; i++) { - vertices[i].Pos.Y += 0.5 * BS; - if (data->m_smooth_lighting) - vertices[i].Color = blendLight(frame, vertices[i].Pos, tile_liquid.color); - vertices[i].Pos += intToFloat(p, BS); - } + // Check node above neighbor. + // NOTE: This doesn't get executed if neighbor + // doesn't exist + p2.Y++; + n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); + if (n2.getContent() == c_source || n2.getContent() == c_flowing) + neighbor.top_is_same_liquid = true; + } +} - u16 indices[] = {0,1,2,2,3,0}; - // Add to mesh collector - collector.append(tile_liquid, vertices, 4, indices, 6); - break;} - case NDT_FLOWINGLIQUID: - { - /* - Add flowing liquid to mesh - */ - TileSpec tile_liquid = getSpecialTile(f, n, 0); - TileSpec tile_liquid_bfculled = getSpecialTile(f, n, 1); - - bool top_is_same_liquid = false; - MapNode ntop = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x,y+1,z)); - content_t c_flowing = nodedef->getId(f.liquid_alternative_flowing); - content_t c_source = nodedef->getId(f.liquid_alternative_source); - if(ntop.getContent() == c_flowing || ntop.getContent() == c_source) - top_is_same_liquid = true; - - u16 l = 0; - // If this liquid emits light and doesn't contain light, draw - // it at what it emits, for an increased effect - u8 light_source = nodedef->get(n).light_source; - if(light_source != 0){ - l = decode_light(light_source); - l = l | (l<<8); - } - // Use the light of the node on top if possible - else if(nodedef->get(ntop).param_type == CPT_LIGHT) - l = getInteriorLight(ntop, 0, nodedef); - // Otherwise use the light of this node (the liquid) - else - l = getInteriorLight(n, 0, nodedef); - video::SColor c1 = encode_light_and_color(l, - tile_liquid.color, f.light_source); - video::SColor c2 = encode_light_and_color(l, - tile_liquid_bfculled.color, f.light_source); +void MapblockMeshGenerator::resetCornerLevels() +{ + for (int k = 0; k < 2; k++) + for (int i = 0; i < 2; i++) + corner_levels[k][i] = 0.5 * BS; +} - u8 range = rangelim(nodedef->get(c_flowing).liquid_range, 1, 8); +void MapblockMeshGenerator::calculateCornerLevels() +{ + for (int k = 0; k < 2; k++) + for (int i = 0; i < 2; i++) + corner_levels[k][i] = getCornerLevel(i, k); +} - // Neighbor liquid levels (key = relative position) - // Includes current node +f32 MapblockMeshGenerator::getCornerLevel(int i, int k) +{ + float sum = 0; + int count = 0; + int air_count = 0; + for (int dk = 0; dk < 2; dk++) + for (int di = 0; di < 2; di++) { + NeighborData &neighbor_data = liquid_neighbors[k + dk][i + di]; + content_t content = neighbor_data.content; + + // If top is liquid, draw starting from top of node + if (neighbor_data.top_is_same_liquid) + return 0.5 * BS; + + // Source always has the full height + if (content == c_source) + return 0.5 * BS; + + // Flowing liquid has level information + if (content == c_flowing) { + sum += neighbor_data.level; + count++; + } else if (content == CONTENT_AIR) { + air_count++; + if (air_count >= 2) + return -0.5 * BS + 0.2; + } + } + if (count > 0) + return sum / count; + return 0; +} - struct NeighborData { - f32 level; - content_t content; - u8 flags; - }; - NeighborData neighbor_data_matrix[27]; - - const u8 neighborflag_top_is_same_liquid = 0x01; - v3s16 neighbor_dirs[9] = { - v3s16(0,0,0), - v3s16(0,0,1), - v3s16(0,0,-1), - v3s16(1,0,0), - v3s16(-1,0,0), - v3s16(1,0,1), - v3s16(-1,0,-1), - v3s16(1,0,-1), - v3s16(-1,0,1), - }; - for(u32 i=0; i<9; i++) - { - content_t content = CONTENT_AIR; - float level = -0.5 * BS; - u8 flags = 0; - // Check neighbor - v3s16 p2 = p + neighbor_dirs[i]; - MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); - if(n2.getContent() != CONTENT_IGNORE) - { - content = n2.getContent(); - - if(n2.getContent() == c_source) - level = 0.5 * BS; - else if(n2.getContent() == c_flowing){ - u8 liquid_level = (n2.param2&LIQUID_LEVEL_MASK); - if (liquid_level <= LIQUID_LEVEL_MAX+1-range) - liquid_level = 0; - else - liquid_level -= (LIQUID_LEVEL_MAX+1-range); - level = (-0.5 + ((float)liquid_level + 0.5) / (float)range) * BS; - } - - // Check node above neighbor. - // NOTE: This doesn't get executed if neighbor - // doesn't exist - p2.Y += 1; - n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); - if(n2.getContent() == c_source || - n2.getContent() == c_flowing) - flags |= neighborflag_top_is_same_liquid; - } - - NeighborData &neighbor_data = - neighbor_data_matrix[NeighborToIndex(neighbor_dirs[i])]; - - neighbor_data.level = level; - neighbor_data.content = content; - neighbor_data.flags = flags; - } +void MapblockMeshGenerator::drawLiquidSides(bool flowing) +{ + struct LiquidFaceDesc { + v3s16 dir; // XZ + v3s16 p[2]; // XZ only; 1 means +, 0 means - + }; + struct UV { + int u, v; + }; + static const LiquidFaceDesc base_faces[4] = { + {v3s16( 1, 0, 0), {v3s16(1, 0, 1), v3s16(1, 0, 0)}}, + {v3s16(-1, 0, 0), {v3s16(0, 0, 0), v3s16(0, 0, 1)}}, + {v3s16( 0, 0, 1), {v3s16(0, 0, 1), v3s16(1, 0, 1)}}, + {v3s16( 0, 0, -1), {v3s16(1, 0, 0), v3s16(0, 0, 0)}}, + }; + static const UV base_vertices[4] = { + {0, 1}, + {1, 1}, + {1, 0}, + {0, 0} + }; + for (int i = 0; i < 4; i++) { + const LiquidFaceDesc &face = base_faces[i]; + const NeighborData &neighbor = liquid_neighbors[face.dir.Z + 1][face.dir.X + 1]; + + // No face between nodes of the same liquid, unless there is node + // at the top to which it should be connected. Again, unless the face + // there would be inside the liquid + if (neighbor.is_same_liquid) { + if (!flowing) + continue; + if (!top_is_same_liquid) + continue; + if (neighbor.top_is_same_liquid) + continue; + } - // Corner heights (average between four liquids) - f32 corner_levels[4]; + if (!flowing && (neighbor.content == CONTENT_IGNORE)) + continue; - v3s16 halfdirs[4] = { - v3s16(0,0,0), - v3s16(1,0,0), - v3s16(1,0,1), - v3s16(0,0,1), - }; - for(u32 i=0; i<4; i++) - { - v3s16 cornerdir = halfdirs[i]; - float cornerlevel = 0; - u32 valid_count = 0; - u32 air_count = 0; - for(u32 j=0; j<4; j++) - { - v3s16 neighbordir = cornerdir - halfdirs[j]; - - NeighborData &neighbor_data = - neighbor_data_matrix[NeighborToIndex(neighbordir)]; - content_t content = neighbor_data.content; - // If top is liquid, draw starting from top of node - if (neighbor_data.flags & neighborflag_top_is_same_liquid) - { - cornerlevel = 0.5*BS; - valid_count = 1; - break; - } - // Source is always the same height - else if(content == c_source) - { - cornerlevel = 0.5 * BS; - valid_count = 1; - break; - } - // Flowing liquid has level information - else if(content == c_flowing) - { - cornerlevel += neighbor_data.level; - valid_count++; - } - else if(content == CONTENT_AIR) - { - air_count++; - } - } - if(air_count >= 2) - cornerlevel = -0.5*BS+0.2; - else if(valid_count > 0) - cornerlevel /= valid_count; - corner_levels[i] = cornerlevel; - } + const ContentFeatures &neighbor_features = nodedef->get(neighbor.content); + // Don't draw face if neighbor is blocking the view + if (neighbor_features.solidness == 2) + continue; - /* - Generate sides - */ + video::S3DVertex vertices[4]; + for (int j = 0; j < 4; j++) { + const UV &vertex = base_vertices[j]; + const v3s16 &base = face.p[vertex.u]; + v3f pos; + pos.X = (base.X - 0.5) * BS; + pos.Z = (base.Z - 0.5) * BS; + if (vertex.v) + pos.Y = neighbor.is_same_liquid ? corner_levels[base.Z][base.X] : -0.5 * BS; + 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); + pos += origin; + vertices[j] = video::S3DVertex(pos.X, pos.Y, pos.Z, 0, 0, 0, color, vertex.u, vertex.v); + }; + collector->append(tile_liquid, vertices, 4, quad_indices, 6); + } +} - v3s16 side_dirs[4] = { - v3s16(1,0,0), - v3s16(-1,0,0), - v3s16(0,0,1), - v3s16(0,0,-1), - }; - s16 side_corners[4][2] = { - {1, 2}, - {3, 0}, - {2, 3}, - {0, 1}, - }; - for(u32 i=0; i<4; i++) - { - v3s16 dir = side_dirs[i]; - - NeighborData& neighbor_data = - neighbor_data_matrix[NeighborToIndex(dir)]; - /* - If our topside is liquid and neighbor's topside - is liquid, don't draw side face - */ - if (top_is_same_liquid && - (neighbor_data.flags & neighborflag_top_is_same_liquid)) - continue; - - content_t neighbor_content = neighbor_data.content; - const ContentFeatures &n_feat = nodedef->get(neighbor_content); - - // Don't draw face if neighbor is blocking the view - if(n_feat.solidness == 2) - continue; - - bool neighbor_is_same_liquid = (neighbor_content == c_source - || neighbor_content == c_flowing); - - // Don't draw any faces if neighbor same is liquid and top is - // same liquid - if(neighbor_is_same_liquid == true - && top_is_same_liquid == false) - continue; - - // Use backface culled material if neighbor doesn't have a - // solidness of 0 - const TileSpec *current_tile = &tile_liquid; - video::SColor *c = &c1; - if(n_feat.solidness != 0 || n_feat.visual_solidness != 0) { - current_tile = &tile_liquid_bfculled; - c = &c2; - } - - video::S3DVertex vertices[4] = - { - video::S3DVertex(-BS/2,0,BS/2, 0,0,0, *c, 0,1), - video::S3DVertex(BS/2,0,BS/2, 0,0,0, *c, 1,1), - video::S3DVertex(BS/2,0,BS/2, 0,0,0, *c, 1,0), - video::S3DVertex(-BS/2,0,BS/2, 0,0,0, *c, 0,0), - }; - - /* - If our topside is liquid, set upper border of face - at upper border of node - */ - if(top_is_same_liquid) - { - vertices[2].Pos.Y = 0.5*BS; - vertices[3].Pos.Y = 0.5*BS; - } - /* - Otherwise upper position of face is corner levels - */ - else - { - vertices[2].Pos.Y = corner_levels[side_corners[i][0]]; - vertices[3].Pos.Y = corner_levels[side_corners[i][1]]; - } - - /* - If neighbor is liquid, lower border of face is corner - liquid levels - */ - if(neighbor_is_same_liquid) - { - vertices[0].Pos.Y = corner_levels[side_corners[i][1]]; - vertices[1].Pos.Y = corner_levels[side_corners[i][0]]; - } - /* - If neighbor is not liquid, lower border of face is - lower border of node - */ - else - { - vertices[0].Pos.Y = -0.5*BS; - vertices[1].Pos.Y = -0.5*BS; - } - - for(s32 j=0; j<4; j++) - { - if(dir == v3s16(0,0,1)) - vertices[j].Pos.rotateXZBy(0); - if(dir == v3s16(0,0,-1)) - vertices[j].Pos.rotateXZBy(180); - if(dir == v3s16(-1,0,0)) - vertices[j].Pos.rotateXZBy(90); - if(dir == v3s16(1,0,-0)) - vertices[j].Pos.rotateXZBy(-90); - - // Do this to not cause glitches when two liquids are - // side-by-side - /*if(neighbor_is_same_liquid == false){ - vertices[j].Pos.X *= 0.98; - vertices[j].Pos.Z *= 0.98; - }*/ - - if (data->m_smooth_lighting) - vertices[j].Color = blendLight(frame, vertices[j].Pos, current_tile->color); - vertices[j].Pos += intToFloat(p, BS); - } - - u16 indices[] = {0,1,2,2,3,0}; - // Add to mesh collector - collector.append(*current_tile, vertices, 4, indices, 6); - } +void MapblockMeshGenerator::drawLiquidTop(bool flowing) +{ + // To get backface culling right, the vertices need to go + // clockwise around the front of the face. And we happened to + // calculate corner levels in exact reverse order. + static const int corner_resolve[4][2] = {{0, 1}, {1, 1}, {1, 0}, {0, 0}}; + + video::S3DVertex vertices[4] = { + video::S3DVertex(-BS / 2, 0, BS / 2, 0, 0, 0, color_liquid_top, 0, 1), + video::S3DVertex( BS / 2, 0, BS / 2, 0, 0, 0, color_liquid_top, 1, 1), + video::S3DVertex( BS / 2, 0, -BS / 2, 0, 0, 0, color_liquid_top, 1, 0), + video::S3DVertex(-BS / 2, 0, -BS / 2, 0, 0, 0, color_liquid_top, 0, 0), + }; - /* - Generate top side, if appropriate - */ - - if(top_is_same_liquid == false) - { - video::S3DVertex vertices[4] = - { - video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c1, 0,1), - video::S3DVertex(BS/2,0,BS/2, 0,0,0, c1, 1,1), - video::S3DVertex(BS/2,0,-BS/2, 0,0,0, c1, 1,0), - video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c1, 0,0), - }; - - // To get backface culling right, the vertices need to go - // clockwise around the front of the face. And we happened to - // calculate corner levels in exact reverse order. - s32 corner_resolve[4] = {3,2,1,0}; - - for(s32 i=0; i<4; i++) - { - //vertices[i].Pos.Y += liquid_level; - //vertices[i].Pos.Y += neighbor_levels[v3s16(0,0,0)]; - s32 j = corner_resolve[i]; - vertices[i].Pos.Y += corner_levels[j]; - if (data->m_smooth_lighting) - vertices[i].Color = blendLight(frame, vertices[i].Pos, tile_liquid.color); - vertices[i].Pos += intToFloat(p, BS); - } - - // Default downwards-flowing texture animation goes from - // -Z towards +Z, thus the direction is +Z. - // Rotate texture to make animation go in flow direction - // Positive if liquid moves towards +Z - f32 dz = (corner_levels[side_corners[3][0]] + - corner_levels[side_corners[3][1]]) - - (corner_levels[side_corners[2][0]] + - corner_levels[side_corners[2][1]]); - // Positive if liquid moves towards +X - f32 dx = (corner_levels[side_corners[1][0]] + - corner_levels[side_corners[1][1]]) - - (corner_levels[side_corners[0][0]] + - corner_levels[side_corners[0][1]]); - f32 tcoord_angle = atan2(dz, dx) * core::RADTODEG ; - v2f tcoord_center(0.5, 0.5); - v2f tcoord_translate( - blockpos_nodes.Z + z, - blockpos_nodes.X + x); - tcoord_translate.rotateBy(tcoord_angle); - tcoord_translate.X -= floor(tcoord_translate.X); - tcoord_translate.Y -= floor(tcoord_translate.Y); - - for(s32 i=0; i<4; i++) - { - vertices[i].TCoords.rotateBy( - tcoord_angle, - tcoord_center); - vertices[i].TCoords += tcoord_translate; - } - - v2f t = vertices[0].TCoords; - vertices[0].TCoords = vertices[2].TCoords; - vertices[2].TCoords = t; - - u16 indices[] = {0,1,2,2,3,0}; - // Add to mesh collector - collector.append(tile_liquid, vertices, 4, indices, 6); - } - break;} - case NDT_GLASSLIKE: - { - TileSpec tile = getNodeTile(n, p, v3s16(0,0,0), data); - - u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = encode_light_and_color(l, tile.color, - f.light_source); - for(u32 j=0; j<6; j++) - { - // Check this neighbor - v3s16 dir = g_6dirs[j]; - v3s16 n2p = blockpos_nodes + p + dir; - MapNode n2 = data->m_vmanip.getNodeNoEx(n2p); - // Don't make face if neighbor is of same type - if(n2.getContent() == n.getContent()) - continue; - video::SColor c2=c; - if(!f.light_source) - applyFacesShading(c2, v3f(dir.X, dir.Y, dir.Z)); - - - // The face at Z+ - video::S3DVertex vertices[4] = { - video::S3DVertex(-BS/2,-BS/2,BS/2, dir.X,dir.Y,dir.Z, c2, 1,1), - video::S3DVertex(BS/2,-BS/2,BS/2, dir.X,dir.Y,dir.Z, c2, 0,1), - video::S3DVertex(BS/2,BS/2,BS/2, dir.X,dir.Y,dir.Z, c2, 0,0), - video::S3DVertex(-BS/2,BS/2,BS/2, dir.X,dir.Y,dir.Z, c2, 1,0), - }; - - // Rotations in the g_6dirs format - if(j == 0) // Z+ - for(u16 i=0; i<4; i++) - vertices[i].Pos.rotateXZBy(0); - else if(j == 1) // Y+ - for(u16 i=0; i<4; i++) - vertices[i].Pos.rotateYZBy(-90); - else if(j == 2) // X+ - for(u16 i=0; i<4; i++) - vertices[i].Pos.rotateXZBy(-90); - else if(j == 3) // Z- - for(u16 i=0; i<4; i++) - vertices[i].Pos.rotateXZBy(180); - else if(j == 4) // Y- - for(u16 i=0; i<4; i++) - vertices[i].Pos.rotateYZBy(90); - else if(j == 5) // X- - for(u16 i=0; i<4; i++) - vertices[i].Pos.rotateXZBy(90); - - for (u16 i = 0; i < 4; i++) { - if (data->m_smooth_lighting) - vertices[i].Color = blendLight(frame, vertices[i].Pos, vertices[i].Normal, tile.color); - vertices[i].Pos += intToFloat(p, BS); - } - - u16 indices[] = {0,1,2,2,3,0}; - // Add to mesh collector - collector.append(tile, vertices, 4, indices, 6); - } - break;} - case NDT_GLASSLIKE_FRAMED_OPTIONAL: - // This is always pre-converted to something else - FATAL_ERROR("NDT_GLASSLIKE_FRAMED_OPTIONAL not pre-converted as expected"); - break; - case NDT_GLASSLIKE_FRAMED: - { - static const v3s16 dirs[6] = { - v3s16( 0, 1, 0), - v3s16( 0,-1, 0), - v3s16( 1, 0, 0), - v3s16(-1, 0, 0), - v3s16( 0, 0, 1), - v3s16( 0, 0,-1) - }; + for (int i = 0; i < 4; i++) { + int u = corner_resolve[i][0]; + 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].Pos += origin; + } - u16 l = getInteriorLight(n, 1, nodedef); - u8 i; - TileSpec tiles[6]; - for (i = 0; i < 6; i++) - tiles[i] = getNodeTile(n, p, dirs[i], data); - - video::SColor tile0color = encode_light_and_color(l, - tiles[0].color, f.light_source); - - TileSpec glass_tiles[6]; - video::SColor glasscolor[6]; - if (tiles[1].texture && tiles[2].texture && tiles[3].texture) { - glass_tiles[0] = tiles[2]; - glass_tiles[1] = tiles[3]; - glass_tiles[2] = tiles[1]; - glass_tiles[3] = tiles[1]; - glass_tiles[4] = tiles[1]; - glass_tiles[5] = tiles[1]; - } else { - for (i = 0; i < 6; i++) - glass_tiles[i] = tiles[1]; - } - for (i = 0; i < 6; i++) - glasscolor[i] = encode_light_and_color(l, glass_tiles[i].color, - f.light_source); - - u8 param2 = n.getParam2(); - bool H_merge = ! bool(param2 & 128); - bool V_merge = ! bool(param2 & 64); - param2 = param2 & 63; - - v3f pos = intToFloat(p, BS); - static const float a = BS / 2; - static const float g = a - 0.003; - static const float b = .876 * ( BS / 2 ); - - static const aabb3f frame_edges[12] = { - aabb3f( b, b,-a, a, a, a), // y+ - aabb3f(-a, b,-a,-b, a, a), // y+ - aabb3f( b,-a,-a, a,-b, a), // y- - aabb3f(-a,-a,-a,-b,-b, a), // y- - aabb3f( b,-a, b, a, a, a), // x+ - aabb3f( b,-a,-a, a, a,-b), // x+ - aabb3f(-a,-a, b,-b, a, a), // x- - aabb3f(-a,-a,-a,-b, a,-b), // x- - aabb3f(-a, b, b, a, a, a), // z+ - aabb3f(-a,-a, b, a,-b, a), // z+ - aabb3f(-a,-a,-a, a,-b,-b), // z- - aabb3f(-a, b,-a, a, a,-b) // z- - }; - static const aabb3f glass_faces[6] = { - aabb3f(-g, g,-g, g, g, g), // y+ - aabb3f(-g,-g,-g, g,-g, g), // y- - aabb3f( g,-g,-g, g, g, g), // x+ - aabb3f(-g,-g,-g,-g, g, g), // x- - aabb3f(-g,-g, g, g, g, g), // z+ - aabb3f(-g,-g,-g, g, g,-g) // z- - }; + if (flowing) { + // Default downwards-flowing texture animation goes from + // -Z towards +Z, thus the direction is +Z. + // Rotate texture to make animation go in flow direction + // Positive if liquid moves towards +Z + f32 dz = (corner_levels[0][0] + corner_levels[0][1]) - + (corner_levels[1][0] + corner_levels[1][1]); + // Positive if liquid moves towards +X + f32 dx = (corner_levels[0][0] + corner_levels[1][0]) - + (corner_levels[0][1] + corner_levels[1][1]); + f32 tcoord_angle = atan2(dz, dx) * core::RADTODEG; + v2f tcoord_center(0.5, 0.5); + v2f tcoord_translate(blockpos_nodes.Z + p.Z, blockpos_nodes.X + p.X); + tcoord_translate.rotateBy(tcoord_angle); + tcoord_translate.X -= floor(tcoord_translate.X); + tcoord_translate.Y -= floor(tcoord_translate.Y); + + for (int i = 0; i < 4; i++) { + vertices[i].TCoords.rotateBy(tcoord_angle, tcoord_center); + vertices[i].TCoords += tcoord_translate; + } - // table of node visible faces, 0 = invisible - int visible_faces[6] = {0,0,0,0,0,0}; - - // table of neighbours, 1 = same type, checked with g_26dirs - int nb[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - - // g_26dirs to check when only horizontal merge is allowed - int nb_H_dirs[8] = {0,2,3,5,10,11,12,13}; - - content_t current = n.getContent(); - content_t n2c; - MapNode n2; - v3s16 n2p; - - // neighbours checks for frames visibility - - if (!H_merge && V_merge) { - n2p = blockpos_nodes + p + g_26dirs[1]; - n2 = data->m_vmanip.getNodeNoEx(n2p); - n2c = n2.getContent(); - if (n2c == current || n2c == CONTENT_IGNORE) - nb[1] = 1; - n2p = blockpos_nodes + p + g_26dirs[4]; - n2 = data->m_vmanip.getNodeNoEx(n2p); - n2c = n2.getContent(); - if (n2c == current || n2c == CONTENT_IGNORE) - nb[4] = 1; - } else if (H_merge && !V_merge) { - for(i = 0; i < 8; i++) { - n2p = blockpos_nodes + p + g_26dirs[nb_H_dirs[i]]; - n2 = data->m_vmanip.getNodeNoEx(n2p); - n2c = n2.getContent(); - if (n2c == current || n2c == CONTENT_IGNORE) - nb[nb_H_dirs[i]] = 1; - } - } else if (H_merge && V_merge) { - for(i = 0; i < 18; i++) { - n2p = blockpos_nodes + p + g_26dirs[i]; - n2 = data->m_vmanip.getNodeNoEx(n2p); - n2c = n2.getContent(); - if (n2c == current || n2c == CONTENT_IGNORE) - nb[i] = 1; - } - } + std::swap(vertices[0].TCoords, vertices[2].TCoords); + } - // faces visibility checks - - if (!V_merge) { - visible_faces[0] = 1; - visible_faces[1] = 1; - } else { - for(i = 0; i < 2; i++) { - n2p = blockpos_nodes + p + dirs[i]; - n2 = data->m_vmanip.getNodeNoEx(n2p); - n2c = n2.getContent(); - if (n2c != current) - visible_faces[i] = 1; - } - } + collector->append(tile_liquid_top, vertices, 4, quad_indices, 6); +} - if (!H_merge) { - visible_faces[2] = 1; - visible_faces[3] = 1; - visible_faces[4] = 1; - visible_faces[5] = 1; - } else { - for(i = 2; i < 6; i++) { - n2p = blockpos_nodes + p + dirs[i]; - n2 = data->m_vmanip.getNodeNoEx(n2p); - n2c = n2.getContent(); - if (n2c != current) - visible_faces[i] = 1; - } - } +void MapblockMeshGenerator::drawLiquidNode(bool flowing) +{ + prepareLiquidNodeDrawing(flowing); + getLiquidNeighborhood(flowing); + if (flowing) + calculateCornerLevels(); + else + resetCornerLevels(); + drawLiquidSides(flowing); + if (!top_is_same_liquid) + drawLiquidTop(flowing); +} - static const u8 nb_triplet[12*3] = { - 1,2, 7, 1,5, 6, 4,2,15, 4,5,14, - 2,0,11, 2,3,13, 5,0,10, 5,3,12, - 0,1, 8, 0,4,16, 3,4,17, 3,1, 9 +void MapblockMeshGenerator::drawGlasslikeNode() +{ + useDefaultTile(); + + for (int face = 0; face < 6; face++) { + // Check this neighbor + v3s16 dir = g_6dirs[face]; + v3s16 neighbor_pos = blockpos_nodes + p + dir; + MapNode neighbor = data->m_vmanip.getNodeNoExNoEmerge(neighbor_pos); + // Don't make face if neighbor is of same type + if (neighbor.getContent() == n.getContent()) + continue; + v3f vertices[4] = { + v3f(-BS / 2, -BS / 2, BS / 2), + v3f( BS / 2, -BS / 2, BS / 2), + v3f( BS / 2, BS / 2, BS / 2), + v3f(-BS / 2, BS / 2, BS / 2), + }; + for (int i = 0; i < 4; i++) { + // Rotations in the g_6dirs format + switch (face) { + case 0: vertices[i].rotateXZBy( 0); break; // Z+ + case 1: vertices[i].rotateYZBy(-90); break; // Y+ + case 2: vertices[i].rotateXZBy(-90); break; // X+ + case 3: vertices[i].rotateXZBy(180); break; // Z- + case 4: vertices[i].rotateYZBy( 90); break; // Y- + case 5: vertices[i].rotateXZBy( 90); break; // X- }; + } + drawQuad(vertices, dir); + } +} - aabb3f box; - - for(i = 0; i < 12; i++) - { - int edge_invisible; - if (nb[nb_triplet[i*3+2]]) - edge_invisible = nb[nb_triplet[i*3]] & nb[nb_triplet[i*3+1]]; - else - edge_invisible = nb[nb_triplet[i*3]] ^ nb[nb_triplet[i*3+1]]; - if (edge_invisible) - continue; - box = frame_edges[i]; - makeAutoLightedCuboid(&collector, data, pos, box, tiles[0], tile0color, frame); - } +void MapblockMeshGenerator::drawGlasslikeFramedNode() +{ + TileSpec tiles[6]; + for (int face = 0; face < 6; face++) + tiles[face] = getTile(g_6dirs[face]); + + TileSpec glass_tiles[6]; + if (tiles[0].texture && tiles[3].texture && tiles[4].texture) { + glass_tiles[0] = tiles[4]; + glass_tiles[1] = tiles[0]; + glass_tiles[2] = tiles[4]; + glass_tiles[3] = tiles[4]; + glass_tiles[4] = tiles[3]; + glass_tiles[5] = tiles[4]; + } else { + for (int face = 0; face < 6; face++) + glass_tiles[face] = tiles[4]; + } - for(i = 0; i < 6; i++) - { - if (!visible_faces[i]) - continue; - box = glass_faces[i]; - makeAutoLightedCuboid(&collector, data, pos, box, glass_tiles[i], glasscolor[i], frame); - } + u8 param2 = n.getParam2(); + bool H_merge = !(param2 & 128); + bool V_merge = !(param2 & 64); + param2 &= 63; + + static const float a = BS / 2; + static const float g = a - 0.003; + static const float b = .876 * ( BS / 2 ); + + static const aabb3f frame_edges[FRAMED_EDGE_COUNT] = { + aabb3f( b, b, -a, a, a, a), // y+ + aabb3f(-a, b, -a, -b, a, a), // y+ + aabb3f( b, -a, -a, a, -b, a), // y- + aabb3f(-a, -a, -a, -b, -b, a), // y- + aabb3f( b, -a, b, a, a, a), // x+ + aabb3f( b, -a, -a, a, a, -b), // x+ + aabb3f(-a, -a, b, -b, a, a), // x- + aabb3f(-a, -a, -a, -b, a, -b), // x- + aabb3f(-a, b, b, a, a, a), // z+ + aabb3f(-a, -a, b, a, -b, a), // z+ + aabb3f(-a, -a, -a, a, -b, -b), // z- + aabb3f(-a, b, -a, a, a, -b), // z- + }; + static const aabb3f glass_faces[6] = { + aabb3f(-g, -g, g, g, g, g), // z+ + aabb3f(-g, g, -g, g, g, g), // y+ + aabb3f( g, -g, -g, g, g, g), // x+ + aabb3f(-g, -g, -g, g, g, -g), // z- + aabb3f(-g, -g, -g, g, -g, g), // y- + aabb3f(-g, -g, -g, -g, g, g), // x- + }; - if (param2 > 0 && f.special_tiles[0].texture) { - // Interior volume level is in range 0 .. 63, - // convert it to -0.5 .. 0.5 - float vlev = (((float)param2 / 63.0 ) * 2.0 - 1.0); - TileSpec tile = getSpecialTile(f, n, 0); - video::SColor special_color = encode_light_and_color(l, - tile.color, f.light_source); - float offset = 0.003; - box = aabb3f(visible_faces[3] ? -b : -a + offset, - visible_faces[1] ? -b : -a + offset, - visible_faces[5] ? -b : -a + offset, - visible_faces[2] ? b : a - offset, - visible_faces[0] ? b * vlev : a * vlev - offset, - visible_faces[4] ? b : a - offset); - makeAutoLightedCuboid(&collector, data, pos, box, tile, special_color, frame); - } - break;} - case NDT_ALLFACES: - { - TileSpec tile_leaves = getNodeTile(n, p, - v3s16(0,0,0), data); - u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = encode_light_and_color(l, - tile_leaves.color, f.light_source); - - v3f pos = intToFloat(p, BS); - aabb3f box(-BS/2,-BS/2,-BS/2,BS/2,BS/2,BS/2); - makeAutoLightedCuboid(&collector, data, pos, box, tile_leaves, c, frame); - break;} - case NDT_ALLFACES_OPTIONAL: - // This is always pre-converted to something else - FATAL_ERROR("NDT_ALLFACES_OPTIONAL not pre-converted"); - break; - case NDT_TORCHLIKE: - { - v3s16 dir = n.getWallMountedDir(nodedef); - - u8 tileindex = 0; - if(dir == v3s16(0,-1,0)){ - tileindex = 0; // floor - } else if(dir == v3s16(0,1,0)){ - tileindex = 1; // ceiling - // For backwards compatibility - } else if(dir == v3s16(0,0,0)){ - tileindex = 0; // floor - } else { - tileindex = 2; // side - } + // tables of neighbour (connect if same type and merge allowed), + // checked with g_26dirs + + // 1 = connect, 0 = face visible + bool nb[FRAMED_NEIGHBOR_COUNT] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + + // 1 = check + static const bool check_nb_vertical [FRAMED_NEIGHBOR_COUNT] = {0,1,0,0,1,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; + static const bool check_nb_horizontal [FRAMED_NEIGHBOR_COUNT] = {1,0,1,1,0,1, 0,0,0,0, 1,1,1,1, 0,0,0,0}; + static const bool check_nb_all [FRAMED_NEIGHBOR_COUNT] = {1,1,1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1}; + const bool *check_nb = check_nb_all; + + // neighbours checks for frames visibility + if (H_merge || V_merge) { + if (!H_merge) + check_nb = check_nb_vertical; // vertical-only merge + if (!V_merge) + check_nb = check_nb_horizontal; // horizontal-only merge + content_t current = n.getContent(); + for (int i = 0; i < FRAMED_NEIGHBOR_COUNT; i++) { + if (!check_nb[i]) + continue; + v3s16 n2p = blockpos_nodes + p + g_26dirs[i]; + MapNode n2 = data->m_vmanip.getNodeNoEx(n2p); + content_t n2c = n2.getContent(); + if (n2c == current || n2c == CONTENT_IGNORE) + nb[i] = 1; + } + } - TileSpec tile = getNodeTileN(n, p, tileindex, data); - tile.material_flags &= ~MATERIAL_FLAG_BACKFACE_CULLING; - tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; - - u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = encode_light_and_color(l, tile.color, - f.light_source); - - float s = BS/2*f.visual_scale; - // Wall at X+ of node - video::S3DVertex vertices[4] = - { - video::S3DVertex(-s,-s,0, 0,0,0, c, 0,1), - video::S3DVertex( s,-s,0, 0,0,0, c, 1,1), - video::S3DVertex( s, s,0, 0,0,0, c, 1,0), - video::S3DVertex(-s, s,0, 0,0,0, c, 0,0), - }; + // edge visibility - for (s32 i = 0; i < 4; i++) - { - if(dir == v3s16(1,0,0)) - vertices[i].Pos.rotateXZBy(0); - if(dir == v3s16(-1,0,0)) - vertices[i].Pos.rotateXZBy(180); - if(dir == v3s16(0,0,1)) - vertices[i].Pos.rotateXZBy(90); - if(dir == v3s16(0,0,-1)) - vertices[i].Pos.rotateXZBy(-90); - if(dir == v3s16(0,-1,0)) - vertices[i].Pos.rotateXZBy(45); - if(dir == v3s16(0,1,0)) - vertices[i].Pos.rotateXZBy(-45); - - if (data->m_smooth_lighting) - vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); - vertices[i].Pos += intToFloat(p, BS); - } - - u16 indices[] = {0,1,2,2,3,0}; - // Add to mesh collector - collector.append(tile, vertices, 4, indices, 6); - break;} - case NDT_SIGNLIKE: - { - TileSpec tile = getNodeTileN(n, p, 0, data); - tile.material_flags &= ~MATERIAL_FLAG_BACKFACE_CULLING; - tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; - - u16 l = getInteriorLight(n, 0, nodedef); - video::SColor c = encode_light_and_color(l, tile.color, - f.light_source); - - float d = (float)BS/16; - float s = BS/2*f.visual_scale; - // Wall at X+ of node - video::S3DVertex vertices[4] = - { - video::S3DVertex(BS/2-d, s, s, 0,0,0, c, 0,0), - video::S3DVertex(BS/2-d, s, -s, 0,0,0, c, 1,0), - video::S3DVertex(BS/2-d, -s, -s, 0,0,0, c, 1,1), - video::S3DVertex(BS/2-d, -s, s, 0,0,0, c, 0,1), - }; + static const u8 nb_triplet[FRAMED_EDGE_COUNT][3] = { + {1, 2, 7}, {1, 5, 6}, {4, 2, 15}, {4, 5, 14}, + {2, 0, 11}, {2, 3, 13}, {5, 0, 10}, {5, 3, 12}, + {0, 1, 8}, {0, 4, 16}, {3, 4, 17}, {3, 1, 9}, + }; - v3s16 dir = n.getWallMountedDir(nodedef); - - for (s32 i = 0; i < 4; i++) - { - if(dir == v3s16(1,0,0)) - vertices[i].Pos.rotateXZBy(0); - if(dir == v3s16(-1,0,0)) - vertices[i].Pos.rotateXZBy(180); - if(dir == v3s16(0,0,1)) - vertices[i].Pos.rotateXZBy(90); - if(dir == v3s16(0,0,-1)) - vertices[i].Pos.rotateXZBy(-90); - if(dir == v3s16(0,-1,0)) - vertices[i].Pos.rotateXYBy(-90); - if(dir == v3s16(0,1,0)) - vertices[i].Pos.rotateXYBy(90); - - if (data->m_smooth_lighting) - vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); - vertices[i].Pos += intToFloat(p, BS); - } + tile = tiles[1]; + for (int edge = 0; edge < FRAMED_EDGE_COUNT; edge++) { + bool edge_invisible; + if (nb[nb_triplet[edge][2]]) + edge_invisible = nb[nb_triplet[edge][0]] & nb[nb_triplet[edge][1]]; + else + edge_invisible = nb[nb_triplet[edge][0]] ^ nb[nb_triplet[edge][1]]; + if (edge_invisible) + continue; + drawAutoLightedCuboid(frame_edges[edge]); + } - u16 indices[] = {0,1,2,2,3,0}; - // Add to mesh collector - collector.append(tile, vertices, 4, indices, 6); - break;} - case NDT_PLANTLIKE: - { - PseudoRandom rng(x<<8 | z | y<<16); - - TileSpec tile = getNodeTileN(n, p, 0, data); - tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; - - u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = encode_light_and_color(l, tile.color, - f.light_source); - - float s = BS / 2 * f.visual_scale; - // add sqrt(2) visual scale - if ((f.param_type_2 == CPT2_MESHOPTIONS) && ((n.param2 & 0x10) != 0)) - s *= 1.41421; - - float random_offset_X = .0; - float random_offset_Z = .0; - if ((f.param_type_2 == CPT2_MESHOPTIONS) && ((n.param2 & 0x8) != 0)) { - random_offset_X = BS * ((rng.next() % 16 / 16.0) * 0.29 - 0.145); - random_offset_Z = BS * ((rng.next() % 16 / 16.0) * 0.29 - 0.145); - } + for (int face = 0; face < 6; face++) { + if (nb[face]) + continue; + tile = glass_tiles[face]; + drawAutoLightedCuboid(glass_faces[face]); + } - for (int j = 0; j < 4; j++) { - video::S3DVertex vertices[4] = - { - video::S3DVertex(-s,-BS/2, 0, 0,0,0, c, 0,1), - video::S3DVertex( s,-BS/2, 0, 0,0,0, c, 1,1), - video::S3DVertex( s,-BS/2 + s*2,0, 0,0,0, c, 1,0), - video::S3DVertex(-s,-BS/2 + s*2,0, 0,0,0, c, 0,0), - }; - - float rotate_degree = 0; - u8 p2mesh = 0; - if (f.param_type_2 == CPT2_DEGROTATE) - rotate_degree = n.param2 * 2; - if (f.param_type_2 != CPT2_MESHOPTIONS) { - if (j == 0) { - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(46 + rotate_degree); - } else if (j == 1) { - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(-44 + rotate_degree); - } - } else { - p2mesh = n.param2 & 0x7; - switch (p2mesh) { - case 0: - // x - if (j == 0) { - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(46); - } else if (j == 1) { - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(-44); - } - break; - case 1: - // + - if (j == 0) { - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(91); - } else if (j == 1) { - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(1); - } - break; - case 2: - // * - if (j == 0) { - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(121); - } else if (j == 1) { - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(241); - } else { // (j == 2) - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(1); - } - break; - case 3: - // # - switch (j) { - case 0: - for (u16 i = 0; i < 4; i++) { - vertices[i].Pos.rotateXZBy(1); - vertices[i].Pos.Z += BS / 4; - } - break; - case 1: - for (u16 i = 0; i < 4; i++) { - vertices[i].Pos.rotateXZBy(91); - vertices[i].Pos.X += BS / 4; - } - break; - case 2: - for (u16 i = 0; i < 4; i++) { - vertices[i].Pos.rotateXZBy(181); - vertices[i].Pos.Z -= BS / 4; - } - break; - case 3: - for (u16 i = 0; i < 4; i++) { - vertices[i].Pos.rotateXZBy(271); - vertices[i].Pos.X -= BS / 4; - } - break; - } - break; - case 4: - // outward leaning #-like - switch (j) { - case 0: - for (u16 i = 2; i < 4; i++) - vertices[i].Pos.Z -= BS / 2; - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(1); - break; - case 1: - for (u16 i = 2; i < 4; i++) - vertices[i].Pos.Z -= BS / 2; - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(91); - break; - case 2: - for (u16 i = 2; i < 4; i++) - vertices[i].Pos.Z -= BS / 2; - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(181); - break; - case 3: - for (u16 i = 2; i < 4; i++) - vertices[i].Pos.Z -= BS / 2; - for (u16 i = 0; i < 4; i++) - vertices[i].Pos.rotateXZBy(271); - break; - } - break; - } - } - - for (int i = 0; i < 4; i++) { - if (data->m_smooth_lighting) - vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); - vertices[i].Pos += intToFloat(p, BS); - // move to a random spot to avoid moire - if ((f.param_type_2 == CPT2_MESHOPTIONS) && ((n.param2 & 0x8) != 0)) { - vertices[i].Pos.X += random_offset_X; - vertices[i].Pos.Z += random_offset_Z; - } - // randomly move each face up/down - if ((f.param_type_2 == CPT2_MESHOPTIONS) && ((n.param2 & 0x20) != 0)) { - PseudoRandom yrng(j | x<<16 | z<<8 | y<<24 ); - vertices[i].Pos.Y -= BS * ((yrng.next() % 16 / 16.0) * 0.125); - } - } - - u16 indices[] = {0, 1, 2, 2, 3, 0}; - // Add to mesh collector - collector.append(tile, vertices, 4, indices, 6); - - // stop adding faces for meshes with less than 4 faces - if (f.param_type_2 == CPT2_MESHOPTIONS) { - if (((p2mesh == 0) || (p2mesh == 1)) && (j == 1)) - break; - else if ((p2mesh == 2) && (j == 2)) - break; - } else if (j == 1) { - break; - } + if (param2 > 0 && f->special_tiles[0].texture) { + // Interior volume level is in range 0 .. 63, + // convert it to -0.5 .. 0.5 + float vlev = (param2 / 63.0) * 2.0 - 1.0; + tile = getSpecialTile(*f, n, 0); + drawAutoLightedCuboid(aabb3f(-(nb[5] ? g : b), + -(nb[4] ? g : b), + -(nb[3] ? g : b), + (nb[2] ? g : b), + (nb[1] ? g : b) * vlev, + (nb[0] ? g : b))); + } +} - } - break;} - case NDT_FIRELIKE: - { - TileSpec tile = getNodeTileN(n, p, 0, data); - tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; - - u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = encode_light_and_color(l, tile.color, - f.light_source); - - float s = BS / 2 * f.visual_scale; - - content_t current = n.getContent(); - content_t n2c; - MapNode n2; - v3s16 n2p; - - static const v3s16 dirs[6] = { - v3s16( 0, 1, 0), - v3s16( 0, -1, 0), - v3s16( 1, 0, 0), - v3s16(-1, 0, 0), - v3s16( 0, 0, 1), - v3s16( 0, 0, -1) - }; +void MapblockMeshGenerator::drawAllfacesNode() +{ + static const aabb3f box(-BS / 2, -BS / 2, -BS / 2, BS / 2, BS / 2, BS / 2); + useDefaultTile(false); + drawAutoLightedCuboid(box); +} - int doDraw[6] = {0, 0, 0, 0, 0, 0}; +void MapblockMeshGenerator::drawTorchlikeNode() +{ + u8 wall = n.getWallMounted(nodedef); + u8 tileindex = 0; + switch (wall) { + case DWM_YP: tileindex = 1; break; // ceiling + case DWM_YN: tileindex = 0; break; // floor + default: tileindex = 2; // side (or invalid—should we care?) + } + useTile(tileindex, true); + + float size = BS / 2 * f->visual_scale; + v3f vertices[4] = { + v3f(-size, -size, 0), + v3f( size, -size, 0), + v3f( size, size, 0), + v3f(-size, size, 0), + }; + for (int i = 0; i < 4; i++) { + switch (wall) { + case DWM_YP: vertices[i].rotateXZBy(-45); break; + case DWM_YN: vertices[i].rotateXZBy( 45); break; + case DWM_XP: vertices[i].rotateXZBy( 0); break; + case DWM_XN: vertices[i].rotateXZBy(180); break; + case DWM_ZP: vertices[i].rotateXZBy( 90); break; + case DWM_ZN: vertices[i].rotateXZBy(-90); break; + } + } + drawQuad(vertices); +} - bool drawAllFaces = true; +void MapblockMeshGenerator::drawSignlikeNode() +{ + u8 wall = n.getWallMounted(nodedef); + useTile(0, true); + static const float offset = BS / 16; + float size = BS / 2 * f->visual_scale; + // Wall at X+ of node + v3f vertices[4] = { + v3f(BS / 2 - offset, size, size), + v3f(BS / 2 - offset, size, -size), + v3f(BS / 2 - offset, -size, -size), + v3f(BS / 2 - offset, -size, size), + }; + for (int i = 0; i < 4; i++) { + switch (wall) { + case DWM_YP: vertices[i].rotateXYBy( 90); break; + case DWM_YN: vertices[i].rotateXYBy(-90); break; + case DWM_XP: vertices[i].rotateXZBy( 0); break; + case DWM_XN: vertices[i].rotateXZBy(180); break; + case DWM_ZP: vertices[i].rotateXZBy( 90); break; + case DWM_ZN: vertices[i].rotateXZBy(-90); break; + } + } + drawQuad(vertices); +} - // Check for adjacent nodes - for (int i = 0; i < 6; i++) { - n2p = blockpos_nodes + p + dirs[i]; - n2 = data->m_vmanip.getNodeNoEx(n2p); - n2c = n2.getContent(); - if (n2c != CONTENT_IGNORE && n2c != CONTENT_AIR && n2c != current) { - doDraw[i] = 1; - if (drawAllFaces) - drawAllFaces = false; +void MapblockMeshGenerator::drawPlantlikeQuad(float rotation, float quad_offset, + bool offset_top_only) +{ + v3f vertices[4] = { + v3f(-scale, -BS / 2, 0), + v3f( scale, -BS / 2, 0), + v3f( scale, -BS / 2 + scale * 2, 0), + v3f(-scale, -BS / 2 + scale * 2, 0), + }; + if (random_offset_Y) { + PseudoRandom yrng(face_num++ | p.X << 16 | p.Z << 8 | p.Y << 24); + offset.Y = BS * ((yrng.next() % 16 / 16.0) * 0.125); + } + int offset_first_index = offset_top_only ? 2 : 0; + for (int i = 0; i < 4; i++) { + if (i >= offset_first_index) + vertices[i].Z += quad_offset; + vertices[i].rotateXZBy(rotation + rotate_degree); + vertices[i] += offset; + } + drawQuad(vertices); +} - } - } +void MapblockMeshGenerator::drawPlantlikeNode() +{ + useTile(0, false); + draw_style = PLANT_STYLE_CROSS; + scale = BS / 2 * f->visual_scale; + offset = v3f(0, 0, 0); + rotate_degree = 0; + random_offset_Y = false; + face_num = 0; + + switch (f->param_type_2) { + case CPT2_MESHOPTIONS: + draw_style = PlantlikeStyle(n.param2 & MO_MASK_STYLE); + if (n.param2 & MO_BIT_SCALE_SQRT2) + scale *= 1.41421; + if (n.param2 & MO_BIT_RANDOM_OFFSET) { + PseudoRandom rng(p.X << 8 | p.Z | p.Y << 16); + offset.X = BS * ((rng.next() % 16 / 16.0) * 0.29 - 0.145); + offset.Z = BS * ((rng.next() % 16 / 16.0) * 0.29 - 0.145); + } + if (n.param2 & MO_BIT_RANDOM_OFFSET_Y) + random_offset_Y = true; + break; - for (int j = 0; j < 6; j++) { - - video::S3DVertex vertices[4] = { - video::S3DVertex(-s, -BS / 2, 0, 0, 0, 0, c, 0, 1), - video::S3DVertex( s, -BS / 2, 0, 0, 0, 0, c, 1, 1), - video::S3DVertex( s, -BS / 2 + s * 2, 0, 0, 0, 0, c, 1, 0), - video::S3DVertex(-s, -BS / 2 + s * 2, 0, 0, 0, 0, c, 0, 0), - }; - - // Calculate which faces should be drawn, (top or sides) - if (j == 0 && (drawAllFaces || - (doDraw[3] == 1 || doDraw[1] == 1))) { - for (int i = 0; i < 4; i++) { - vertices[i].Pos.rotateXZBy(90); - vertices[i].Pos.rotateXYBy(-10); - vertices[i].Pos.X -= 4.0; - } - } else if (j == 1 && (drawAllFaces || - (doDraw[5] == 1 || doDraw[1] == 1))) { - for (int i = 0; i < 4; i++) { - vertices[i].Pos.rotateXZBy(180); - vertices[i].Pos.rotateYZBy(10); - vertices[i].Pos.Z -= 4.0; - } - } else if (j == 2 && (drawAllFaces || - (doDraw[2] == 1 || doDraw[1] == 1))) { - for (int i = 0; i < 4; i++) { - vertices[i].Pos.rotateXZBy(270); - vertices[i].Pos.rotateXYBy(10); - vertices[i].Pos.X += 4.0; - } - } else if (j == 3 && (drawAllFaces || - (doDraw[4] == 1 || doDraw[1] == 1))) { - for (int i = 0; i < 4; i++) { - vertices[i].Pos.rotateYZBy(-10); - vertices[i].Pos.Z += 4.0; - } - // Center cross-flames - } else if (j == 4 && (drawAllFaces || doDraw[1] == 1)) { - for (int i = 0; i < 4; i++) { - vertices[i].Pos.rotateXZBy(45); - } - } else if (j == 5 && (drawAllFaces || doDraw[1] == 1)) { - for (int i = 0; i < 4; i++) { - vertices[i].Pos.rotateXZBy(-45); - } - // Render flames on bottom of node above - } else if (j == 0 && doDraw[0] == 1 && doDraw[1] == 0) { - for (int i = 0; i < 4; i++) { - vertices[i].Pos.rotateYZBy(70); - vertices[i].Pos.rotateXZBy(90); - vertices[i].Pos.Y += 4.84; - vertices[i].Pos.X -= 4.7; - } - } else if (j == 1 && doDraw[0] == 1 && doDraw[1] == 0) { - for (int i = 0; i < 4; i++) { - vertices[i].Pos.rotateYZBy(70); - vertices[i].Pos.rotateXZBy(180); - vertices[i].Pos.Y += 4.84; - vertices[i].Pos.Z -= 4.7; - } - } else if (j == 2 && doDraw[0] == 1 && doDraw[1] == 0) { - for (int i = 0; i < 4; i++) { - vertices[i].Pos.rotateYZBy(70); - vertices[i].Pos.rotateXZBy(270); - vertices[i].Pos.Y += 4.84; - vertices[i].Pos.X += 4.7; - } - } else if (j == 3 && doDraw[0] == 1 && doDraw[1] == 0) { - for (int i = 0; i < 4; i++) { - vertices[i].Pos.rotateYZBy(70); - vertices[i].Pos.Y += 4.84; - vertices[i].Pos.Z += 4.7; - } - } else { - // Skip faces that aren't adjacent to a node - continue; - } - - for (int i = 0; i < 4; i++) { - vertices[i].Pos *= f.visual_scale; - if (data->m_smooth_lighting) - vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); - vertices[i].Pos += intToFloat(p, BS); - } - - u16 indices[] = {0, 1, 2, 2, 3, 0}; - // Add to mesh collector - collector.append(tile, vertices, 4, indices, 6); - } - break;} - case NDT_FENCELIKE: - { - TileSpec tile = getNodeTile(n, p, v3s16(0,0,0), data); - TileSpec tile_nocrack = tile; - tile_nocrack.material_flags &= ~MATERIAL_FLAG_CRACK; - - // Put wood the right way around in the posts - TileSpec tile_rot = tile; - tile_rot.rotation = 1; - - u16 l = getInteriorLight(n, 1, nodedef); - video::SColor c = encode_light_and_color(l, tile.color, - f.light_source); - - const f32 post_rad=(f32)BS/8; - const f32 bar_rad=(f32)BS/16; - const f32 bar_len=(f32)(BS/2)-post_rad; - - v3f pos = intToFloat(p, BS); - - // The post - always present - aabb3f post(-post_rad,-BS/2,-post_rad,post_rad,BS/2,post_rad); - f32 postuv[24]={ - 6/16.,6/16.,10/16.,10/16., - 6/16.,6/16.,10/16.,10/16., - 0/16.,0,4/16.,1, - 4/16.,0,8/16.,1, - 8/16.,0,12/16.,1, - 12/16.,0,16/16.,1}; - makeAutoLightedCuboidEx(&collector, data, pos, post, tile_rot, postuv, c, frame); - - // Now a section of fence, +X, if there's a post there - v3s16 p2 = p; - p2.X++; - MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); - const ContentFeatures *f2 = &nodedef->get(n2); - if(f2->drawtype == NDT_FENCELIKE) - { - aabb3f bar(-bar_len+BS/2,-bar_rad+BS/4,-bar_rad, - bar_len+BS/2,bar_rad+BS/4,bar_rad); - f32 xrailuv[24]={ - 0/16.,2/16.,16/16.,4/16., - 0/16.,4/16.,16/16.,6/16., - 6/16.,6/16.,8/16.,8/16., - 10/16.,10/16.,12/16.,12/16., - 0/16.,8/16.,16/16.,10/16., - 0/16.,14/16.,16/16.,16/16.}; - makeAutoLightedCuboidEx(&collector, data, pos, bar, tile_nocrack, xrailuv, c, frame); - bar.MinEdge.Y -= BS/2; - bar.MaxEdge.Y -= BS/2; - makeAutoLightedCuboidEx(&collector, data, pos, bar, tile_nocrack, xrailuv, c, frame); - } + case CPT2_DEGROTATE: + rotate_degree = n.param2 * 2; + break; - // Now a section of fence, +Z, if there's a post there - p2 = p; - p2.Z++; - n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); - f2 = &nodedef->get(n2); - if(f2->drawtype == NDT_FENCELIKE) - { - aabb3f bar(-bar_rad,-bar_rad+BS/4,-bar_len+BS/2, - bar_rad,bar_rad+BS/4,bar_len+BS/2); - f32 zrailuv[24]={ - 3/16.,1/16.,5/16.,5/16., // cannot rotate; stretch - 4/16.,1/16.,6/16.,5/16., // for wood texture instead - 0/16.,9/16.,16/16.,11/16., - 0/16.,6/16.,16/16.,8/16., - 6/16.,6/16.,8/16.,8/16., - 10/16.,10/16.,12/16.,12/16.}; - makeAutoLightedCuboidEx(&collector, data, pos, bar, tile_nocrack, zrailuv, c, frame); - bar.MinEdge.Y -= BS/2; - bar.MaxEdge.Y -= BS/2; - makeAutoLightedCuboidEx(&collector, data, pos, bar, tile_nocrack, zrailuv, c, frame); - } - break;} - case NDT_RAILLIKE: - { - bool is_rail_x[6]; /* (-1,-1,0) X (1,-1,0) (-1,0,0) X (1,0,0) (-1,1,0) X (1,1,0) */ - bool is_rail_z[6]; - - content_t thiscontent = n.getContent(); - std::string groupname = "connect_to_raillike"; // name of the group that enables connecting to raillike nodes of different kind - int self_group = ((ItemGroupList) nodedef->get(n).groups)[groupname]; - - u8 index = 0; - for (s8 y0 = -1; y0 <= 1; y0++) { - // Prevent from indexing never used coordinates - for (s8 xz = -1; xz <= 1; xz++) { - if (xz == 0) - continue; - MapNode n_xy = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x + xz, y + y0, z)); - MapNode n_zy = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x, y + y0, z + xz)); - const ContentFeatures &def_xy = nodedef->get(n_xy); - const ContentFeatures &def_zy = nodedef->get(n_zy); - - // Check if current node would connect with the rail - is_rail_x[index] = ((def_xy.drawtype == NDT_RAILLIKE - && ((ItemGroupList) def_xy.groups)[groupname] == self_group) - || n_xy.getContent() == thiscontent); - - is_rail_z[index] = ((def_zy.drawtype == NDT_RAILLIKE - && ((ItemGroupList) def_zy.groups)[groupname] == self_group) - || n_zy.getContent() == thiscontent); - index++; - } - } + default: + break; + } - bool is_rail_x_all[2]; // [0] = negative x, [1] = positive x coordinate from the current node position - bool is_rail_z_all[2]; - is_rail_x_all[0] = is_rail_x[0] || is_rail_x[2] || is_rail_x[4]; - is_rail_x_all[1] = is_rail_x[1] || is_rail_x[3] || is_rail_x[5]; - is_rail_z_all[0] = is_rail_z[0] || is_rail_z[2] || is_rail_z[4]; - is_rail_z_all[1] = is_rail_z[1] || is_rail_z[3] || is_rail_z[5]; - - // reasonable default, flat straight unrotated rail - bool is_straight = true; - int adjacencies = 0; - int angle = 0; - u8 tileindex = 0; - - // check for sloped rail - if (is_rail_x[4] || is_rail_x[5] || is_rail_z[4] || is_rail_z[5]) { - adjacencies = 5; // 5 means sloped - is_straight = true; // sloped is always straight - } else { - // is really straight, rails on both sides - is_straight = (is_rail_x_all[0] && is_rail_x_all[1]) || (is_rail_z_all[0] && is_rail_z_all[1]); - adjacencies = is_rail_x_all[0] + is_rail_x_all[1] + is_rail_z_all[0] + is_rail_z_all[1]; - } + switch (draw_style) { + case PLANT_STYLE_CROSS: + drawPlantlikeQuad(46); + drawPlantlikeQuad(-44); + break; + + case PLANT_STYLE_CROSS2: + drawPlantlikeQuad(91); + drawPlantlikeQuad(1); + break; + + case PLANT_STYLE_STAR: + drawPlantlikeQuad(121); + drawPlantlikeQuad(241); + drawPlantlikeQuad(1); + break; + + case PLANT_STYLE_HASH: + drawPlantlikeQuad( 1, BS / 4); + drawPlantlikeQuad( 91, BS / 4); + drawPlantlikeQuad(181, BS / 4); + drawPlantlikeQuad(271, BS / 4); + break; + + case PLANT_STYLE_HASH2: + drawPlantlikeQuad( 1, -BS / 2, true); + drawPlantlikeQuad( 91, -BS / 2, true); + drawPlantlikeQuad(181, -BS / 2, true); + drawPlantlikeQuad(271, -BS / 2, true); + break; + } +} - switch (adjacencies) { - case 1: - if (is_rail_x_all[0] || is_rail_x_all[1]) - angle = 90; - break; - case 2: - if (!is_straight) - tileindex = 1; // curved - if (is_rail_x_all[0] && is_rail_x_all[1]) - angle = 90; - if (is_rail_z_all[0] && is_rail_z_all[1]) { - if (is_rail_z[4]) - angle = 180; - } - else if (is_rail_x_all[0] && is_rail_z_all[0]) - angle = 270; - else if (is_rail_x_all[0] && is_rail_z_all[1]) - angle = 180; - else if (is_rail_x_all[1] && is_rail_z_all[1]) - angle = 90; - break; - case 3: - // here is where the potential to 'switch' a junction is, but not implemented at present - tileindex = 2; // t-junction - if(!is_rail_x_all[1]) - angle = 180; - if(!is_rail_z_all[0]) - angle = 90; - if(!is_rail_z_all[1]) - angle = 270; - break; - case 4: - tileindex = 3; // crossing - break; - case 5: //sloped - if (is_rail_z[4]) - angle = 180; - if (is_rail_x[4]) - angle = 90; - if (is_rail_x[5]) - angle = -90; - break; - default: - break; - } +void MapblockMeshGenerator::drawFirelikeQuad(float rotation, float opening_angle, + float offset_h, float offset_v) +{ + v3f vertices[4] = { + v3f(-scale, -BS / 2, 0), + v3f( scale, -BS / 2, 0), + v3f( scale, -BS / 2 + scale * 2, 0), + v3f(-scale, -BS / 2 + scale * 2, 0), + }; + for (int i = 0; i < 4; i++) { + vertices[i].rotateYZBy(opening_angle); + vertices[i].Z += offset_h; + vertices[i].rotateXZBy(rotation); + vertices[i].Y += offset_v; + } + drawQuad(vertices); +} - TileSpec tile = getNodeTileN(n, p, tileindex, data); - tile.material_flags &= ~MATERIAL_FLAG_BACKFACE_CULLING; - tile.material_flags |= MATERIAL_FLAG_CRACK_OVERLAY; +void MapblockMeshGenerator::drawFirelikeNode() +{ + useTile(0, false); + scale = BS / 2 * f->visual_scale; + + // Check for adjacent nodes + bool neighbors = false; + bool neighbor[6] = {0, 0, 0, 0, 0, 0}; + content_t current = n.getContent(); + for (int i = 0; i < 6; i++) { + v3s16 n2p = blockpos_nodes + p + g_6dirs[i]; + MapNode n2 = data->m_vmanip.getNodeNoEx(n2p); + content_t n2c = n2.getContent(); + if (n2c != CONTENT_IGNORE && n2c != CONTENT_AIR && n2c != current) { + neighbor[i] = true; + neighbors = true; + } + } + bool drawBasicFire = neighbor[D6D_YN] || !neighbors; + bool drawBottomFire = neighbor[D6D_YP]; + + if (drawBasicFire || neighbor[D6D_ZP]) + drawFirelikeQuad(0, -10, 0.4 * BS); + else if (drawBottomFire) + drawFirelikeQuad(0, 70, 0.47 * BS, 0.484 * BS); + + if (drawBasicFire || neighbor[D6D_XN]) + drawFirelikeQuad(90, -10, 0.4 * BS); + else if (drawBottomFire) + drawFirelikeQuad(90, 70, 0.47 * BS, 0.484 * BS); + + if (drawBasicFire || neighbor[D6D_ZN]) + drawFirelikeQuad(180, -10, 0.4 * BS); + else if (drawBottomFire) + drawFirelikeQuad(180, 70, 0.47 * BS, 0.484 * BS); + + if (drawBasicFire || neighbor[D6D_XP]) + drawFirelikeQuad(270, -10, 0.4 * BS); + else if (drawBottomFire) + drawFirelikeQuad(270, 70, 0.47 * BS, 0.484 * BS); + + if (drawBasicFire) { + drawFirelikeQuad(45, 0, 0.0); + drawFirelikeQuad(-45, 0, 0.0); + } +} - u16 l = getInteriorLight(n, 0, nodedef); - video::SColor c = encode_light_and_color(l, tile.color, - f.light_source); +void MapblockMeshGenerator::drawFencelikeNode() +{ + useDefaultTile(false); + TileSpec tile_nocrack = tile; + tile_nocrack.material_flags &= ~MATERIAL_FLAG_CRACK; + + // Put wood the right way around in the posts + TileSpec tile_rot = tile; + tile_rot.rotation = 1; + + static const f32 post_rad = BS / 8; + static const f32 bar_rad = BS / 16; + static const f32 bar_len = BS / 2 - post_rad; + + // The post - always present + static const aabb3f post(-post_rad, -BS / 2, -post_rad, + post_rad, BS / 2, post_rad); + static const f32 postuv[24] = { + 0.375, 0.375, 0.625, 0.625, + 0.375, 0.375, 0.625, 0.625, + 0.000, 0.000, 0.250, 1.000, + 0.250, 0.000, 0.500, 1.000, + 0.500, 0.000, 0.750, 1.000, + 0.750, 0.000, 1.000, 1.000, + }; + tile = tile_rot; + drawAutoLightedCuboid(post, postuv); + + tile = tile_nocrack; + + // Now a section of fence, +X, if there's a post there + v3s16 p2 = p; + p2.X++; + MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); + const ContentFeatures *f2 = &nodedef->get(n2); + if (f2->drawtype == NDT_FENCELIKE) { + static const aabb3f bar_x1(BS / 2 - bar_len, BS / 4 - bar_rad, -bar_rad, + BS / 2 + bar_len, BS / 4 + bar_rad, bar_rad); + static const aabb3f bar_x2(BS / 2 - bar_len, -BS / 4 - bar_rad, -bar_rad, + BS / 2 + bar_len, -BS / 4 + bar_rad, bar_rad); + static const f32 xrailuv[24] = { + 0.000, 0.125, 1.000, 0.250, + 0.000, 0.250, 1.000, 0.375, + 0.375, 0.375, 0.500, 0.500, + 0.625, 0.625, 0.750, 0.750, + 0.000, 0.500, 1.000, 0.625, + 0.000, 0.875, 1.000, 1.000, + }; + drawAutoLightedCuboid(bar_x1, xrailuv); + drawAutoLightedCuboid(bar_x2, xrailuv); + } - float d = (float)BS/64; - float s = BS/2; + // Now a section of fence, +Z, if there's a post there + p2 = p; + p2.Z++; + n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); + f2 = &nodedef->get(n2); + if (f2->drawtype == NDT_FENCELIKE) { + static const aabb3f bar_z1(-bar_rad, BS / 4 - bar_rad, BS / 2 - bar_len, + bar_rad, BS / 4 + bar_rad, BS / 2 + bar_len); + static const aabb3f bar_z2(-bar_rad, -BS / 4 - bar_rad, BS / 2 - bar_len, + bar_rad, -BS / 4 + bar_rad, BS / 2 + bar_len); + static const f32 zrailuv[24] = { + 0.1875, 0.0625, 0.3125, 0.3125, // cannot rotate; stretch + 0.2500, 0.0625, 0.3750, 0.3125, // for wood texture instead + 0.0000, 0.5625, 1.0000, 0.6875, + 0.0000, 0.3750, 1.0000, 0.5000, + 0.3750, 0.3750, 0.5000, 0.5000, + 0.6250, 0.6250, 0.7500, 0.7500, + }; + drawAutoLightedCuboid(bar_z1, zrailuv); + drawAutoLightedCuboid(bar_z2, zrailuv); + } +} - short g = -1; - if (is_rail_x[4] || is_rail_x[5] || is_rail_z[4] || is_rail_z[5]) - g = 1; //Object is at a slope +bool MapblockMeshGenerator::isSameRail(v3s16 dir) +{ + MapNode node2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p + dir); + if (node2.getContent() == n.getContent()) + return true; + const ContentFeatures &def2 = nodedef->get(node2); + return ((def2.drawtype == NDT_RAILLIKE) && + (def2.getGroup(raillike_groupname) == raillike_group)); +} - video::S3DVertex vertices[4] = - { - video::S3DVertex(-s, -s+d, -s, 0, 0, 0, c, 0, 1), - video::S3DVertex( s, -s+d, -s, 0, 0, 0, c, 1, 1), - video::S3DVertex( s, g*s+d, s, 0, 0, 0, c, 1, 0), - video::S3DVertex(-s, g*s+d, s, 0, 0, 0, c, 0, 0), - }; +void MapblockMeshGenerator::drawRaillikeNode() +{ + static const v3s16 direction[4] = { + v3s16( 0, 0, 1), + v3s16( 0, 0, -1), + v3s16(-1, 0, 0), + v3s16( 1, 0, 0), + }; + static const int slope_angle[4] = {0, 180, 90, -90}; - for(s32 i=0; i<4; i++) - { - if(angle != 0) - vertices[i].Pos.rotateXZBy(angle); - if (data->m_smooth_lighting) - vertices[i].Color = blendLight(frame, vertices[i].Pos, tile.color); - vertices[i].Pos += intToFloat(p, BS); - } + enum RailTile { + straight, + curved, + junction, + cross, + }; + struct RailDesc { + int tile_index; + int angle; + }; + static const RailDesc rail_kinds[16] = { + // +x -x -z +z + //------------- + {straight, 0}, // . . . . + {straight, 0}, // . . . +Z + {straight, 0}, // . . -Z . + {straight, 0}, // . . -Z +Z + {straight, 90}, // . -X . . + { curved, 180}, // . -X . +Z + { curved, 270}, // . -X -Z . + {junction, 180}, // . -X -Z +Z + {straight, 90}, // +X . . . + { curved, 90}, // +X . . +Z + { curved, 0}, // +X . -Z . + {junction, 0}, // +X . -Z +Z + {straight, 90}, // +X -X . . + {junction, 90}, // +X -X . +Z + {junction, 270}, // +X -X -Z . + { cross, 0}, // +X -X -Z +Z + }; - u16 indices[] = {0,1,2,2,3,0}; - collector.append(tile, vertices, 4, indices, 6); - break;} - case NDT_NODEBOX: - { - static const v3s16 tile_dirs[6] = { - v3s16(0, 1, 0), - v3s16(0, -1, 0), - v3s16(1, 0, 0), - v3s16(-1, 0, 0), - v3s16(0, 0, 1), - v3s16(0, 0, -1) - }; + raillike_group = nodedef->get(n).getGroup(raillike_groupname); + + int code = 0; + int angle; + int tile_index; + bool sloped = false; + for (int dir = 0; dir < 4; dir++) { + bool rail_above = isSameRail(direction[dir] + v3s16(0, 1, 0)); + if (rail_above) { + sloped = true; + angle = slope_angle[dir]; + } + if (rail_above || + isSameRail(direction[dir]) || + isSameRail(direction[dir] + v3s16(0, -1, 0))) + code |= 1 << dir; + } - TileSpec tiles[6]; - video::SColor colors[6]; - for (int j = 0; j < 6; j++) { - // Handles facedir rotation for textures - tiles[j] = getNodeTile(n, p, tile_dirs[j], data); - } - if (!data->m_smooth_lighting) { - u16 l = getInteriorLight(n, 1, nodedef); - for (int j = 0; j < 6; j++) - colors[j] = encode_light_and_color(l, tiles[j].color, f.light_source); - } + if (sloped) { + tile_index = straight; + } else { + tile_index = rail_kinds[code].tile_index; + angle = rail_kinds[code].angle; + } - v3f pos = intToFloat(p, BS); + useTile(tile_index, true); - int neighbors = 0; + static const float offset = BS / 64; + static const float size = BS / 2; + float y2 = sloped ? size : -size; + v3f vertices[4] = { + v3f(-size, -size + offset, -size), + v3f( size, -size + offset, -size), + v3f( size, y2 + offset, size), + v3f(-size, y2 + offset, size), + }; + if (angle) + for (int i = 0; i < 4; i++) + vertices[i].rotateXZBy(angle); + drawQuad(vertices); +} - // locate possible neighboring nodes to connect to - if (f.node_box.type == NODEBOX_CONNECTED) { - v3s16 p2 = p; +void MapblockMeshGenerator::drawNodeboxNode() +{ + static const v3s16 tile_dirs[6] = { + v3s16(0, 1, 0), + v3s16(0, -1, 0), + v3s16(1, 0, 0), + v3s16(-1, 0, 0), + v3s16(0, 0, 1), + v3s16(0, 0, -1) + }; - p2.Y++; - getNeighborConnectingFace(blockpos_nodes + p2, nodedef, data, n, 1, &neighbors); + // we have this order for some reason... + static const v3s16 connection_dirs[6] = { + v3s16( 0, 1, 0), // top + v3s16( 0, -1, 0), // bottom + v3s16( 0, 0, -1), // front + v3s16(-1, 0, 0), // left + v3s16( 0, 0, 1), // back + v3s16( 1, 0, 0), // right + }; - p2 = p; - p2.Y--; - getNeighborConnectingFace(blockpos_nodes + p2, nodedef, data, n, 2, &neighbors); + TileSpec tiles[6]; + for (int face = 0; face < 6; face++) { + // Handles facedir rotation for textures + tiles[face] = getTile(tile_dirs[face]); + } - p2 = p; - p2.Z--; - getNeighborConnectingFace(blockpos_nodes + p2, nodedef, data, n, 4, &neighbors); + // locate possible neighboring nodes to connect to + int neighbors_set = 0; + if (f->node_box.type == NODEBOX_CONNECTED) { + for (int dir = 0; dir != 6; dir++) { + int flag = 1 << dir; + v3s16 p2 = blockpos_nodes + p + connection_dirs[dir]; + MapNode n2 = data->m_vmanip.getNodeNoEx(p2); + if (nodedef->nodeboxConnects(n, n2, flag)) + neighbors_set |= flag; + } + } - p2 = p; - p2.X--; - getNeighborConnectingFace(blockpos_nodes + p2, nodedef, data, n, 8, &neighbors); + std::vector boxes; + n.getNodeBoxes(nodedef, &boxes, neighbors_set); + for (std::vector::iterator i = boxes.begin(); i != boxes.end(); ++i) + drawAutoLightedCuboid(*i, NULL, tiles, 6); +} - p2 = p; - p2.Z++; - getNeighborConnectingFace(blockpos_nodes + p2, nodedef, data, n, 16, &neighbors); +void MapblockMeshGenerator::drawMeshNode() +{ + u8 facedir = 0; + scene::IMesh* mesh; + bool private_mesh; // as a grab/drop pair is not thread-safe + + if (f->param_type_2 == CPT2_FACEDIR || + f->param_type_2 == CPT2_COLORED_FACEDIR) { + facedir = n.getFaceDir(nodedef); + } else if (f->param_type_2 == CPT2_WALLMOUNTED || + f->param_type_2 == CPT2_COLORED_WALLMOUNTED) { + // Convert wallmounted to 6dfacedir. + // When cache enabled, it is already converted. + facedir = n.getWallMounted(nodedef); + if (!enable_mesh_cache) { + static const u8 wm_to_6d[6] = {20, 0, 16 + 1, 12 + 3, 8, 4 + 2}; + facedir = wm_to_6d[facedir]; + } + } - p2 = p; - p2.X++; - getNeighborConnectingFace(blockpos_nodes + p2, nodedef, data, n, 32, &neighbors); + if (!data->m_smooth_lighting && f->mesh_ptr[facedir]) { + // use cached meshes + private_mesh = false; + mesh = f->mesh_ptr[facedir]; + } else if (f->mesh_ptr[0]) { + // no cache, clone and rotate mesh + private_mesh = true; + mesh = cloneMesh(f->mesh_ptr[0]); + rotateMeshBy6dFacedir(mesh, facedir); + recalculateBoundingBox(mesh); + meshmanip->recalculateNormals(mesh, true, false); + } else + return; + + int mesh_buffer_count = mesh->getMeshBufferCount(); + for (int j = 0; j < mesh_buffer_count; j++) { + useTile(j, false); + scene::IMeshBuffer *buf = mesh->getMeshBuffer(j); + video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices(); + int vertex_count = buf->getVertexCount(); + + if (data->m_smooth_lighting) { + // Mesh is always private here. So the lighting is applied to each + // 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.Pos += origin; } + collector->append(tile, vertices, vertex_count, + buf->getIndices(), buf->getIndexCount()); + } else { + // Don't modify the mesh, it may not be private here. + // Instead, let the collector process colors, etc. + collector->append(tile, vertices, vertex_count, + buf->getIndices(), buf->getIndexCount(), origin, + color, f->light_source); + } + } + if (private_mesh) + mesh->drop(); +} - std::vector boxes; - n.getNodeBoxes(nodedef, &boxes, neighbors); - for (std::vector::iterator - i = boxes.begin(); - i != boxes.end(); ++i) { - aabb3f box = *i; - - f32 dx1 = box.MinEdge.X; - f32 dy1 = box.MinEdge.Y; - f32 dz1 = box.MinEdge.Z; - f32 dx2 = box.MaxEdge.X; - f32 dy2 = box.MaxEdge.Y; - f32 dz2 = box.MaxEdge.Z; - - box.MinEdge += pos; - box.MaxEdge += pos; - - if (box.MinEdge.X > box.MaxEdge.X) - std::swap(box.MinEdge.X, box.MaxEdge.X); - if (box.MinEdge.Y > box.MaxEdge.Y) - std::swap(box.MinEdge.Y, box.MaxEdge.Y); - if (box.MinEdge.Z > box.MaxEdge.Z) - std::swap(box.MinEdge.Z, box.MaxEdge.Z); - - // - // Compute texture coords - f32 tx1 = (box.MinEdge.X/BS)+0.5; - f32 ty1 = (box.MinEdge.Y/BS)+0.5; - f32 tz1 = (box.MinEdge.Z/BS)+0.5; - f32 tx2 = (box.MaxEdge.X/BS)+0.5; - f32 ty2 = (box.MaxEdge.Y/BS)+0.5; - f32 tz2 = (box.MaxEdge.Z/BS)+0.5; - f32 txc[24] = { - // up - tx1, 1-tz2, tx2, 1-tz1, - // down - tx1, tz1, tx2, tz2, - // right - tz1, 1-ty2, tz2, 1-ty1, - // left - 1-tz2, 1-ty2, 1-tz1, 1-ty1, - // back - 1-tx2, 1-ty2, 1-tx1, 1-ty1, - // front - tx1, 1-ty2, tx2, 1-ty1, - }; - if (data->m_smooth_lighting) { - u16 lights[8]; - for (int j = 0; j < 8; ++j) { - f32 x = (j & 4) ? dx2 : dx1; - f32 y = (j & 2) ? dy2 : dy1; - f32 z = (j & 1) ? dz2 : dz1; - lights[j] = blendLight(frame, core::vector3df(x, y, z)); - } - makeSmoothLightedCuboid(&collector, box, tiles, 6, lights, txc, f.light_source); - } else { - makeCuboid(&collector, box, tiles, 6, colors, txc, f.light_source); - } - } - break;} - case NDT_MESH: - { - v3f pos = intToFloat(p, BS); - u16 l = getInteriorLight(n, 1, nodedef); - u8 facedir = 0; - if (f.param_type_2 == CPT2_FACEDIR || - f.param_type_2 == CPT2_COLORED_FACEDIR) { - facedir = n.getFaceDir(nodedef); - } else if (f.param_type_2 == CPT2_WALLMOUNTED || - f.param_type_2 == CPT2_COLORED_WALLMOUNTED) { - //convert wallmounted to 6dfacedir. - //when cache enabled, it is already converted - facedir = n.getWallMounted(nodedef); - if (!enable_mesh_cache) { - static const u8 wm_to_6d[6] = {20, 0, 16+1, 12+3, 8, 4+2}; - facedir = wm_to_6d[facedir]; - } - } +// also called when the drawtype is known but should have been pre-converted +void MapblockMeshGenerator::errorUnknownDrawtype() +{ + infostream << "Got drawtype " << f->drawtype << std::endl; + FATAL_ERROR("Unknown drawtype"); +} - if (!data->m_smooth_lighting && f.mesh_ptr[facedir]) { - // use cached meshes - for (u16 j = 0; j < f.mesh_ptr[0]->getMeshBufferCount(); j++) { - const TileSpec &tile = getNodeTileN(n, p, j, data); - scene::IMeshBuffer *buf = f.mesh_ptr[facedir]->getMeshBuffer(j); - collector.append(tile, (video::S3DVertex *) - buf->getVertices(), buf->getVertexCount(), - buf->getIndices(), buf->getIndexCount(), pos, - encode_light_and_color(l, tile.color, f.light_source), - f.light_source); - } - } else if (f.mesh_ptr[0]) { - // no cache, clone and rotate mesh - scene::IMesh* mesh = cloneMesh(f.mesh_ptr[0]); - rotateMeshBy6dFacedir(mesh, facedir); - recalculateBoundingBox(mesh); - meshmanip->recalculateNormals(mesh, true, false); - for (u16 j = 0; j < mesh->getMeshBufferCount(); j++) { - const TileSpec &tile = getNodeTileN(n, p, j, data); - scene::IMeshBuffer *buf = mesh->getMeshBuffer(j); - video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices(); - u32 vertex_count = buf->getVertexCount(); - if (data->m_smooth_lighting) { - for (u16 m = 0; m < vertex_count; ++m) { - video::S3DVertex &vertex = vertices[m]; - vertex.Color = blendLight(frame, vertex.Pos, vertex.Normal, tile.color); - vertex.Pos += pos; - } - collector.append(tile, vertices, vertex_count, - buf->getIndices(), buf->getIndexCount()); - } else { - collector.append(tile, vertices, vertex_count, - buf->getIndices(), buf->getIndexCount(), pos, - encode_light_and_color(l, tile.color, f.light_source), - f.light_source); - } - } - mesh->drop(); - } - break;} - } +void MapblockMeshGenerator::drawNode() +{ + if (data->m_smooth_lighting) + getSmoothLightFrame(); + else + light = getInteriorLight(n, 1, nodedef); + switch (f->drawtype) { + case NDT_LIQUID: drawLiquidNode(false); break; + case NDT_FLOWINGLIQUID: drawLiquidNode(true); break; + case NDT_GLASSLIKE: drawGlasslikeNode(); break; + case NDT_GLASSLIKE_FRAMED: drawGlasslikeFramedNode(); break; + case NDT_ALLFACES: drawAllfacesNode(); break; + case NDT_TORCHLIKE: drawTorchlikeNode(); break; + case NDT_SIGNLIKE: drawSignlikeNode(); break; + case NDT_PLANTLIKE: drawPlantlikeNode(); break; + case NDT_FIRELIKE: drawFirelikeNode(); break; + case NDT_FENCELIKE: drawFencelikeNode(); break; + case NDT_RAILLIKE: drawRaillikeNode(); break; + case NDT_NODEBOX: drawNodeboxNode(); break; + case NDT_MESH: drawMeshNode(); break; + default: errorUnknownDrawtype(); break; } } +/* + TODO: Fix alpha blending for special nodes + Currently only the last element rendered is blended correct +*/ +void MapblockMeshGenerator::generate() +{ + for (p.Z = 0; p.Z < MAP_BLOCKSIZE; p.Z++) + for (p.Y = 0; p.Y < MAP_BLOCKSIZE; p.Y++) + for (p.X = 0; p.X < MAP_BLOCKSIZE; p.X++) { + n = data->m_vmanip.getNodeNoEx(blockpos_nodes + p); + f = &nodedef->get(n); + // Solid nodes are drawn by MapBlockMesh + if (f->solidness != 0) + continue; + if (f->drawtype == NDT_AIRLIKE) + continue; + origin = intToFloat(p, BS); + drawNode(); + } +} diff --git a/src/content_mapblock.h b/src/content_mapblock.h index bb1e129da..c8425024f 100644 --- a/src/content_mapblock.h +++ b/src/content_mapblock.h @@ -19,11 +19,129 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifndef CONTENT_MAPBLOCK_HEADER #define CONTENT_MAPBLOCK_HEADER +#include "util/numeric.h" +#include "nodedef.h" +#include struct MeshMakeData; struct MeshCollector; -void mapblock_mesh_generate_special(MeshMakeData *data, - MeshCollector &collector); -#endif +struct LightFrame +{ + f32 lightsA[8]; + f32 lightsB[8]; +}; + +class MapblockMeshGenerator +{ +public: + MeshMakeData *data; + MeshCollector *collector; + + INodeDefManager *nodedef; + scene::ISceneManager *smgr; + scene::IMeshManipulator *meshmanip; + +// options + bool enable_mesh_cache; + +// current node + v3s16 blockpos_nodes; + v3s16 p; + v3f origin; + MapNode n; + const ContentFeatures *f; + u16 light; + LightFrame frame; + video::SColor color; + TileSpec tile; + float scale; + +// 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); + + void useTile(int index, bool disable_backface_culling); + void useDefaultTile(bool set_color = true); + TileSpec getTile(const v3s16 &direction); + +// face drawing + void drawQuad(v3f *vertices, const v3s16 &normal = v3s16(0, 0, 0)); + +// cuboid drawing! + void drawCuboid(const aabb3f &box, TileSpec *tiles, int tilecount, + const u16 *lights , const f32 *txc); + void generateCuboidTextureCoords(aabb3f const &box, f32 *coords); + void drawAutoLightedCuboid(aabb3f box, const f32 *txc = NULL, + TileSpec *tiles = NULL, int tile_count = 0); + +// liquid-specific + bool top_is_same_liquid; + TileSpec tile_liquid; + TileSpec tile_liquid_top; + content_t c_flowing; + content_t c_source; + video::SColor color_liquid_top; + struct NeighborData { + f32 level; + content_t content; + bool is_same_liquid; + bool top_is_same_liquid; + }; + NeighborData liquid_neighbors[3][3]; + f32 corner_levels[2][2]; + void prepareLiquidNodeDrawing(bool flowing); + void getLiquidNeighborhood(bool flowing); + void resetCornerLevels(); + void calculateCornerLevels(); + f32 getCornerLevel(int i, int k); + void drawLiquidSides(bool flowing); + void drawLiquidTop(bool flowing); + +// raillike-specific + // name of the group that enables connecting to raillike nodes of different kind + static const std::string raillike_groupname; + int raillike_group; + bool isSameRail(v3s16 dir); + +// plantlike-specific + PlantlikeStyle draw_style; + v3f offset; + int rotate_degree; + bool random_offset_Y; + int face_num; + + void drawPlantlikeQuad(float rotation, float quad_offset = 0, + bool offset_top_only = false); + +// firelike-specific + void drawFirelikeQuad(float rotation, float opening_angle, + float offset_h, float offset_v = 0.0); + +// drawtypes + void drawLiquidNode(bool flowing); + void drawGlasslikeNode(); + void drawGlasslikeFramedNode(); + void drawAllfacesNode(); + void drawTorchlikeNode(); + void drawSignlikeNode(); + void drawPlantlikeNode(); + void drawFirelikeNode(); + void drawFencelikeNode(); + void drawRaillikeNode(); + void drawNodeboxNode(); + void drawMeshNode(); + +// common + void errorUnknownDrawtype(); + void drawNode(); + +public: + MapblockMeshGenerator(MeshMakeData *input, MeshCollector *output); + void generate(); +}; + +#endif diff --git a/src/mapblock_mesh.cpp b/src/mapblock_mesh.cpp index 2520b5459..f76033ea8 100644 --- a/src/mapblock_mesh.cpp +++ b/src/mapblock_mesh.cpp @@ -1108,7 +1108,10 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): - whatever */ - mapblock_mesh_generate_special(data, collector); + { + MapblockMeshGenerator generator(data, &collector); + generator.generate(); + } /* Convert MeshCollector to SMesh diff --git a/src/nodedef.h b/src/nodedef.h index 6275b41ce..4a9908ecc 100644 --- a/src/nodedef.h +++ b/src/nodedef.h @@ -166,6 +166,19 @@ enum NodeDrawType NDT_MESH, // Uses static meshes }; +// Mesh options for NDT_PLANTLIKE with CPT2_MESHOPTIONS +static const u8 MO_MASK_STYLE = 0x07; +static const u8 MO_BIT_RANDOM_OFFSET = 0x08; +static const u8 MO_BIT_SCALE_SQRT2 = 0x10; +static const u8 MO_BIT_RANDOM_OFFSET_Y = 0x20; +enum PlantlikeStyle { + PLANT_STYLE_CROSS, + PLANT_STYLE_CROSS2, + PLANT_STYLE_STAR, + PLANT_STYLE_HASH, + PLANT_STYLE_HASH2, +}; + /* Stand-alone definition of a TileSpec (basically a server-side TileSpec) */ @@ -364,6 +377,11 @@ struct ContentFeatures return (liquid_alternative_flowing == f.liquid_alternative_flowing); } + int getGroup(const std::string &group) const + { + return itemgroup_get(groups, group); + } + #ifndef SERVER void fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, TileDef *tiledef, u32 shader_id, bool use_normal_texture, bool backface_culling, diff --git a/src/util/directiontables.h b/src/util/directiontables.h index 0dd3aab09..3cfe0fb3e 100644 --- a/src/util/directiontables.h +++ b/src/util/directiontables.h @@ -30,5 +30,59 @@ extern const v3s16 g_26dirs[26]; // 26th is (0,0,0) extern const v3s16 g_27dirs[27]; -#endif +/// Direction in the 6D format. g_27dirs contains corresponding vectors. +/// Here P means Positive, N stands for Negative. +enum Direction6D { +// 0 + D6D_ZP, + D6D_YP, + D6D_XP, + D6D_ZN, + D6D_YN, + D6D_XN, +// 6 + D6D_XN_YP, + D6D_XP_YP, + D6D_YP_ZP, + D6D_YP_ZN, + D6D_XN_ZP, + D6D_XP_ZP, + D6D_XN_ZN, + D6D_XP_ZN, + D6D_XN_YN, + D6D_XP_YN, + D6D_YN_ZP, + D6D_YN_ZN, +// 18 + D6D_XN_YP_ZP, + D6D_XP_YP_ZP, + D6D_XN_YP_ZN, + D6D_XP_YP_ZN, + D6D_XN_YN_ZP, + D6D_XP_YN_ZP, + D6D_XN_YN_ZN, + D6D_XP_YN_ZN, +// 26 + D6D, + +// aliases + D6D_BACK = D6D_ZP, + D6D_TOP = D6D_YP, + D6D_RIGHT = D6D_XP, + D6D_FRONT = D6D_ZN, + D6D_BOTTOM = D6D_YN, + D6D_LEFT = D6D_XN, +}; +/// Direction in the wallmounted format. +/// P is Positive, N is Negative. +enum DirectionWallmounted { + DWM_YP, + DWM_YN, + DWM_XP, + DWM_XN, + DWM_ZP, + DWM_ZN, +}; + +#endif -- cgit v1.2.3 From b605b95749aad90b53e6c58a1ee43b50f8217e7c Mon Sep 17 00:00:00 2001 From: Loïc Blot Date: Wed, 29 Mar 2017 13:34:57 +0200 Subject: Add CPP11 header to define nullptr & constexpr (#5471) This header permit to use nullptr & constexpr keywords in portable code segments and benefit from nullptr & constexpr when using C++11 and greater --- src/content_mapblock.cpp | 5 +++-- src/reflowscan.cpp | 5 +++-- src/util/cpp11.h | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 src/util/cpp11.h (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 18b4ef6dd..d0cb50db3 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -29,6 +29,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client.h" #include "log.h" #include "noise.h" +#include "util/cpp11.h" // Distance of light extrapolation (for oversized nodes) // After this distance, it gives up and considers light level constant @@ -42,7 +43,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // Corresponding offsets are listed in g_27dirs #define FRAMED_NEIGHBOR_COUNT 18 -static const v3s16 light_dirs[8] = { +static constexpr v3s16 light_dirs[8] = { v3s16(-1, -1, -1), v3s16(-1, -1, 1), v3s16(-1, 1, -1), @@ -54,7 +55,7 @@ static const v3s16 light_dirs[8] = { }; // Standard index set to make a quad on 4 vertices -static const u16 quad_indices[] = {0, 1, 2, 2, 3, 0}; +static constexpr u16 quad_indices[] = {0, 1, 2, 2, 3, 0}; const std::string MapblockMeshGenerator::raillike_groupname = "connect_to_raillike"; diff --git a/src/reflowscan.cpp b/src/reflowscan.cpp index 49b9406d7..eec371022 100644 --- a/src/reflowscan.cpp +++ b/src/reflowscan.cpp @@ -22,12 +22,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapblock.h" #include "nodedef.h" #include "util/timetaker.h" +#include "util/cpp11.h" ReflowScan::ReflowScan(Map *map, INodeDefManager *ndef) : m_map(map), m_ndef(ndef), - m_liquid_queue(NULL) + m_liquid_queue(nullptr) { } @@ -41,7 +42,7 @@ void ReflowScan::scan(MapBlock *block, UniqueQueue *liquid_queue) // scanned block. Blocks are only added to the lookup if they are really // needed. The lookup is indexed manually to use the same index in a // bit-array (of uint32 type) which stores for unloaded blocks that they - // were already fetched from Map but were actually NULL. + // were already fetched from Map but were actually nullptr. memset(m_lookup, 0, sizeof(m_lookup)); int block_idx = 1 + (1 * 9) + (1 * 3); m_lookup[block_idx] = block; diff --git a/src/util/cpp11.h b/src/util/cpp11.h new file mode 100644 index 000000000..14913cb86 --- /dev/null +++ b/src/util/cpp11.h @@ -0,0 +1,32 @@ +/* +Minetest +Copyright (C) 2016 nerzhul, Loic Blot + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MT_CPP11_HEADER +#define MT_CPP11_HEADER + +#if __cplusplus < 201103L || _MSC_VER < 1600 +#define USE_CPP11_FAKE_KEYWORD +#endif + +#ifdef USE_CPP11_FAKE_KEYWORD +#define constexpr const +#define nullptr NULL +#endif + +#endif -- cgit v1.2.3 From ea549bbae3650d246db7b70a2b07485a4b404409 Mon Sep 17 00:00:00 2001 From: paramat Date: Wed, 29 Mar 2017 03:40:30 +0100 Subject: Paramtype2: Add missing type CPT2_GLASSLIKE_LIQUID_LEVEL Add the missing paramtype2 for param2 controlling the liquid level inside the glasslike_framed drawtype. Add missing documentation of the feature to lua_api.txt. Update and improve comments for drawtype enumerations in nodedef.h. --- doc/lua_api.txt | 4 ++++ src/content_mapblock.cpp | 7 ++++-- src/nodedef.h | 52 ++++++++++++++++++++++++++++++------------- src/script/cpp_api/s_node.cpp | 1 + 4 files changed, 47 insertions(+), 17 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 72599cb7c..0ca3767f9 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -658,6 +658,10 @@ node definition: The first five bits of `param2` tells which color is picked from the palette. The palette should have 32 pixels. + paramtype2 == "glasslikeliquidlevel" + ^ Only valid for "glasslike_framed" or "glasslike_framed_optional" drawtypes. + param2 defines 64 levels of internal liquid. + Liquid texture is defined using `special_tiles = {"modname_tilename.png"},` collision_box = { type = "fixed", fixed = { diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index d0cb50db3..d18aff879 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -760,8 +760,11 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode() drawAutoLightedCuboid(glass_faces[face]); } - if (param2 > 0 && f->special_tiles[0].texture) { - // Interior volume level is in range 0 .. 63, + // 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) { + // Internal liquid level has param2 range 0 .. 63, // convert it to -0.5 .. 0.5 float vlev = (param2 / 63.0) * 2.0 - 1.0; tile = getSpecialTile(*f, n, 0); diff --git a/src/nodedef.h b/src/nodedef.h index 4a9908ecc..da3345d80 100644 --- a/src/nodedef.h +++ b/src/nodedef.h @@ -74,7 +74,9 @@ enum ContentParamType2 // 3 bits of palette index, then facedir CPT2_COLORED_FACEDIR, // 5 bits of palette index, then wallmounted - CPT2_COLORED_WALLMOUNTED + CPT2_COLORED_WALLMOUNTED, + // Glasslike framed drawtype internal liquid level, param2 values 0 to 63 + CPT2_GLASSLIKE_LIQUID_LEVEL, }; enum LiquidType @@ -144,26 +146,46 @@ public: enum NodeDrawType { - NDT_NORMAL, // A basic solid block - NDT_AIRLIKE, // Nothing is drawn - NDT_LIQUID, // Do not draw face towards same kind of flowing/source liquid - NDT_FLOWINGLIQUID, // A very special kind of thing - NDT_GLASSLIKE, // Glass-like, don't draw faces towards other glass - NDT_ALLFACES, // Leaves-like, draw all faces no matter what - NDT_ALLFACES_OPTIONAL, // Fancy -> allfaces, fast -> normal + // A basic solid block + NDT_NORMAL, + // Nothing is drawn + NDT_AIRLIKE, + // Do not draw face towards same kind of flowing/source liquid + NDT_LIQUID, + // A very special kind of thing + NDT_FLOWINGLIQUID, + // Glass-like, don't draw faces towards other glass + NDT_GLASSLIKE, + // Leaves-like, draw all faces no matter what + NDT_ALLFACES, + // Enabled -> ndt_allfaces, disabled -> ndt_normal + NDT_ALLFACES_OPTIONAL, + // Single plane perpendicular to a surface NDT_TORCHLIKE, + // Single plane parallel to a surface NDT_SIGNLIKE, + // 2 vertical planes in a 'X' shape diagonal to XZ axes. + // paramtype2 = "meshoptions" allows various forms, sizes and + // vertical and horizontal random offsets. NDT_PLANTLIKE, + // Fenceposts that connect to neighbouring fenceposts with horizontal bars NDT_FENCELIKE, + // Selects appropriate junction texture to connect like rails to + // neighbouring raillikes. NDT_RAILLIKE, + // Custom Lua-definable structure of multiple cuboids NDT_NODEBOX, - NDT_GLASSLIKE_FRAMED, // Glass-like, draw connected frames and all all - // visible faces - // uses 2 textures, one for frames, second for faces - NDT_FIRELIKE, // Draw faces slightly rotated and only on connecting nodes, - NDT_GLASSLIKE_FRAMED_OPTIONAL, // enabled -> connected, disabled -> Glass-like - // uses 2 textures, one for frames, second for faces - NDT_MESH, // Uses static meshes + // Glass-like, draw connected frames and all visible faces. + // param2 > 0 defines 64 levels of internal liquid + // Uses 3 textures, one for frames, second for faces, + // optional third is a 'special tile' for the liquid. + NDT_GLASSLIKE_FRAMED, + // Draw faces slightly rotated and only on neighbouring nodes + NDT_FIRELIKE, + // Enabled -> ndt_glasslike_framed, disabled -> ndt_glasslike + NDT_GLASSLIKE_FRAMED_OPTIONAL, + // Uses static meshes + NDT_MESH, }; // Mesh options for NDT_PLANTLIKE with CPT2_MESHOPTIONS diff --git a/src/script/cpp_api/s_node.cpp b/src/script/cpp_api/s_node.cpp index 23c8f43b9..adad01e45 100644 --- a/src/script/cpp_api/s_node.cpp +++ b/src/script/cpp_api/s_node.cpp @@ -62,6 +62,7 @@ struct EnumString ScriptApiNode::es_ContentParamType2[] = {CPT2_COLOR, "color"}, {CPT2_COLORED_FACEDIR, "colorfacedir"}, {CPT2_COLORED_WALLMOUNTED, "colorwallmounted"}, + {CPT2_GLASSLIKE_LIQUID_LEVEL, "glasslikeliquidlevel"}, {0, NULL}, }; -- cgit v1.2.3 From 813a9a36b22a4e2d7383622311b6f52e31a94733 Mon Sep 17 00:00:00 2001 From: number Zero Date: Sat, 25 Mar 2017 21:01:27 +0300 Subject: Signlike, glasslike drawtypes: Fix inverted textures --- src/content_mapblock.cpp | 56 ++++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 28 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index d18aff879..153dacf42 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -98,7 +98,7 @@ TileSpec MapblockMeshGenerator::getTile(const v3s16& direction) void MapblockMeshGenerator::drawQuad(v3f *coords, const v3s16 &normal) { - static const v2f tcoords[4] = {v2f(0, 1), v2f(1, 1), v2f(1, 0), v2f(0, 0)}; + static const v2f tcoords[4] = {v2f(0, 0), v2f(1, 0), v2f(1, 1), v2f(0, 1)}; video::S3DVertex vertices[4]; bool shade_face = !f->light_source && (normal != v3s16(0, 0, 0)); v3f normal2(normal.X, normal.Y, normal.Z); @@ -631,22 +631,22 @@ void MapblockMeshGenerator::drawGlasslikeNode() // Don't make face if neighbor is of same type if (neighbor.getContent() == n.getContent()) continue; + // Face at Z- v3f vertices[4] = { - v3f(-BS / 2, -BS / 2, BS / 2), - v3f( BS / 2, -BS / 2, BS / 2), - v3f( BS / 2, BS / 2, BS / 2), - v3f(-BS / 2, BS / 2, BS / 2), + v3f(-BS / 2, BS / 2, -BS / 2), + v3f( BS / 2, BS / 2, -BS / 2), + v3f( BS / 2, -BS / 2, -BS / 2), + v3f(-BS / 2, -BS / 2, -BS / 2), }; for (int i = 0; i < 4; i++) { - // Rotations in the g_6dirs format switch (face) { - case 0: vertices[i].rotateXZBy( 0); break; // Z+ - case 1: vertices[i].rotateYZBy(-90); break; // Y+ - case 2: vertices[i].rotateXZBy(-90); break; // X+ - case 3: vertices[i].rotateXZBy(180); break; // Z- - case 4: vertices[i].rotateYZBy( 90); break; // Y- - case 5: vertices[i].rotateXZBy( 90); break; // X- - }; + case D6D_ZP: vertices[i].rotateXZBy(180); break; + case D6D_YP: vertices[i].rotateYZBy( 90); break; + case D6D_XP: vertices[i].rotateXZBy( 90); break; + case D6D_ZN: vertices[i].rotateXZBy( 0); break; + case D6D_YN: vertices[i].rotateYZBy(-90); break; + case D6D_XN: vertices[i].rotateXZBy(-90); break; + } } drawQuad(vertices, dir); } @@ -797,10 +797,10 @@ void MapblockMeshGenerator::drawTorchlikeNode() float size = BS / 2 * f->visual_scale; v3f vertices[4] = { - v3f(-size, -size, 0), - v3f( size, -size, 0), - v3f( size, size, 0), v3f(-size, size, 0), + v3f( size, size, 0), + v3f( size, -size, 0), + v3f(-size, -size, 0), }; for (int i = 0; i < 4; i++) { switch (wall) { @@ -845,19 +845,19 @@ void MapblockMeshGenerator::drawPlantlikeQuad(float rotation, float quad_offset, bool offset_top_only) { v3f vertices[4] = { - v3f(-scale, -BS / 2, 0), - v3f( scale, -BS / 2, 0), - v3f( scale, -BS / 2 + scale * 2, 0), v3f(-scale, -BS / 2 + scale * 2, 0), + v3f( scale, -BS / 2 + scale * 2, 0), + v3f( scale, -BS / 2, 0), + v3f(-scale, -BS / 2, 0), }; if (random_offset_Y) { PseudoRandom yrng(face_num++ | p.X << 16 | p.Z << 8 | p.Y << 24); offset.Y = BS * ((yrng.next() % 16 / 16.0) * 0.125); } - int offset_first_index = offset_top_only ? 2 : 0; + int offset_count = offset_top_only ? 2 : 4; + for (int i = 0; i < offset_count; i++) + vertices[i].Z += quad_offset; for (int i = 0; i < 4; i++) { - if (i >= offset_first_index) - vertices[i].Z += quad_offset; vertices[i].rotateXZBy(rotation + rotate_degree); vertices[i] += offset; } @@ -933,10 +933,10 @@ void MapblockMeshGenerator::drawFirelikeQuad(float rotation, float opening_angle float offset_h, float offset_v) { v3f vertices[4] = { - v3f(-scale, -BS / 2, 0), - v3f( scale, -BS / 2, 0), - v3f( scale, -BS / 2 + scale * 2, 0), v3f(-scale, -BS / 2 + scale * 2, 0), + v3f( scale, -BS / 2 + scale * 2, 0), + v3f( scale, -BS / 2, 0), + v3f(-scale, -BS / 2, 0), }; for (int i = 0; i < 4; i++) { vertices[i].rotateYZBy(opening_angle); @@ -1151,10 +1151,10 @@ void MapblockMeshGenerator::drawRaillikeNode() static const float size = BS / 2; float y2 = sloped ? size : -size; v3f vertices[4] = { - v3f(-size, -size + offset, -size), - v3f( size, -size + offset, -size), - v3f( size, y2 + offset, size), v3f(-size, y2 + offset, size), + v3f( size, y2 + offset, size), + v3f( size, -size + offset, -size), + v3f(-size, -size + offset, -size), }; if (angle) for (int i = 0; i < 4; i++) -- 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/content_mapblock.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 900b816162401a6d9006334e2e8e8a9a26a1613b Mon Sep 17 00:00:00 2001 From: Dániel Juhász Date: Fri, 21 Apr 2017 18:04:06 +0200 Subject: Fix after soft node overlays This removes a segmentation fault and makes node meshes well colorized. --- src/content_mapblock.cpp | 4 ++-- src/wieldmesh.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 9f4223bac..6673e2bd9 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -108,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]); + vertices[j].Color = blendLightColor(coords[j]); else vertices[j].Color = color; if (shade_face) @@ -298,7 +298,7 @@ video::SColor MapblockMeshGenerator::blendLightColor(const v3f &vertex_pos) video::SColor MapblockMeshGenerator::blendLightColor(const v3f &vertex_pos, const v3f &vertex_normal) { - video::SColor color = blendLight(vertex_pos); + video::SColor color = blendLightColor(vertex_pos); if (!f->light_source) applyFacesShading(color, vertex_normal); return color; diff --git a/src/wieldmesh.cpp b/src/wieldmesh.cpp index 2b23d9e02..8b1477bb7 100644 --- a/src/wieldmesh.cpp +++ b/src/wieldmesh.cpp @@ -438,7 +438,7 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) g_extrusion_mesh_cache->grab(); } - scene::SMesh *mesh; + scene::SMesh *mesh = NULL; // If inventory_image is defined, it overrides everything else if (def.inventory_image != "") { -- cgit v1.2.3 From 95409da87d009c352f27c737621972c2225796c9 Mon Sep 17 00:00:00 2001 From: Loïc Blot Date: Sat, 29 Apr 2017 20:36:09 +0200 Subject: Optimize updateFastFaceRow processing by removing some TileSpec copy (#5678) * Optimize updateFastFaceRow processing by removing some TileSpec copy It permit to decrease this function from 54% runtime to 45% and reduce copy from 14% runtime to 12.5% getTileInfo also reduced from 27% to 23% * makeFastFace should use a const ref too this trigger a const pointer need in the underlying function Also fix some code style and prevent calculating 4 times the same position at a point * Reduce a comparison cost for lights in updateFastFaceRow --- src/content_mapblock.cpp | 12 +++++----- src/content_mapblock.h | 2 +- src/mapblock_mesh.cpp | 58 ++++++++++++++++++++---------------------------- src/mapblock_mesh.h | 6 +++-- 4 files changed, 35 insertions(+), 43 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 6673e2bd9..8be0a7d7b 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -76,7 +76,7 @@ MapblockMeshGenerator::MapblockMeshGenerator(MeshMakeData *input, MeshCollector void MapblockMeshGenerator::useTile(int index, bool disable_backface_culling) { - tile = getNodeTileN(n, p, index, data); + getNodeTileN(n, p, index, data, tile); if (!data->m_smooth_lighting) color = encode_light(light, f->light_source); for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { @@ -88,14 +88,14 @@ void MapblockMeshGenerator::useTile(int index, bool disable_backface_culling) void MapblockMeshGenerator::useDefaultTile(bool set_color) { - tile = getNodeTile(n, p, v3s16(0, 0, 0), data); + getNodeTile(n, p, v3s16(0, 0, 0), data, tile); if (set_color && !data->m_smooth_lighting) color = encode_light(light, f->light_source); } -TileSpec MapblockMeshGenerator::getTile(const v3s16& direction) +void MapblockMeshGenerator::getTile(const v3s16& direction, TileSpec &tile) { - return getNodeTile(n, p, direction, data); + getNodeTile(n, p, direction, data, tile); } void MapblockMeshGenerator::drawQuad(v3f *coords, const v3s16 &normal) @@ -660,7 +660,7 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode() { TileSpec tiles[6]; for (int face = 0; face < 6; face++) - tiles[face] = getTile(g_6dirs[face]); + getTile(g_6dirs[face], tiles[face]); TileSpec glass_tiles[6]; if (tiles[1].layers[0].texture && @@ -1193,7 +1193,7 @@ void MapblockMeshGenerator::drawNodeboxNode() TileSpec tiles[6]; for (int face = 0; face < 6; face++) { // Handles facedir rotation for textures - tiles[face] = getTile(tile_dirs[face]); + getTile(tile_dirs[face], tiles[face]); } // locate possible neighboring nodes to connect to diff --git a/src/content_mapblock.h b/src/content_mapblock.h index 6866a4498..310e38e7c 100644 --- a/src/content_mapblock.h +++ b/src/content_mapblock.h @@ -65,7 +65,7 @@ public: void useTile(int index, bool disable_backface_culling); void useDefaultTile(bool set_color = true); - TileSpec getTile(const v3s16 &direction); + void getTile(const v3s16 &direction, TileSpec &tile); // face drawing void drawQuad(v3f *vertices, const v3s16 &normal = v3s16(0, 0, 0)); diff --git a/src/mapblock_mesh.cpp b/src/mapblock_mesh.cpp index 0bba644e6..6781f21af 100644 --- a/src/mapblock_mesh.cpp +++ b/src/mapblock_mesh.cpp @@ -433,7 +433,7 @@ struct FastFace u8 layernum; }; -static void makeFastFace(TileSpec tile, u16 li0, u16 li1, u16 li2, u16 li3, +static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li3, v3f p, v3s16 dir, v3f scale, std::vector &dest) { // Position is at the center of the cube. @@ -603,7 +603,7 @@ static void makeFastFace(TileSpec tile, u16 li0, u16 li1, u16 li2, u16 li3, core::vector2d(x0 + w * abs_scale, y0) }; for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) { - TileLayer *layer = &tile.layers[layernum]; + const TileLayer *layer = &tile.layers[layernum]; if (layer->texture_id == 0) continue; @@ -689,11 +689,11 @@ static u8 face_contents(content_t m1, content_t m2, bool *equivalent, /* Gets nth node tile (0 <= n <= 5). */ -TileSpec getNodeTileN(MapNode mn, v3s16 p, u8 tileindex, MeshMakeData *data) +void getNodeTileN(MapNode mn, v3s16 p, u8 tileindex, MeshMakeData *data, TileSpec &tile) { INodeDefManager *ndef = data->m_client->ndef(); const ContentFeatures &f = ndef->get(mn); - TileSpec tile = f.tiles[tileindex]; + tile = f.tiles[tileindex]; TileLayer *top_layer = NULL; for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) { TileLayer *layer = &tile.layers[layernum]; @@ -706,13 +706,12 @@ TileSpec getNodeTileN(MapNode mn, v3s16 p, u8 tileindex, MeshMakeData *data) // Apply temporary crack if (p == data->m_crack_pos_relative) top_layer->material_flags |= MATERIAL_FLAG_CRACK; - return tile; } /* Gets node tile given a face direction. */ -TileSpec getNodeTile(MapNode mn, v3s16 p, v3s16 dir, MeshMakeData *data) +void getNodeTile(MapNode mn, v3s16 p, v3s16 dir, MeshMakeData *data, TileSpec &tile) { INodeDefManager *ndef = data->m_client->ndef(); @@ -769,9 +768,8 @@ TileSpec getNodeTile(MapNode mn, v3s16 p, v3s16 dir, MeshMakeData *data) }; u16 tile_index=facedir*16 + dir_i; - TileSpec tile = getNodeTileN(mn, p, dir_to_tile[tile_index], data); + getNodeTileN(mn, p, dir_to_tile[tile_index], data, tile); tile.rotation = dir_to_tile[tile_index + 1]; - return tile; } static void getTileInfo( @@ -791,7 +789,7 @@ static void getTileInfo( INodeDefManager *ndef = data->m_client->ndef(); v3s16 blockpos_nodes = data->m_blockpos * MAP_BLOCKSIZE; - MapNode &n0 = vmanip.getNodeRefUnsafe(blockpos_nodes + p); + const MapNode &n0 = vmanip.getNodeRefUnsafe(blockpos_nodes + p); // Don't even try to get n1 if n0 is already CONTENT_IGNORE if (n0.getContent() == CONTENT_IGNORE) { @@ -799,8 +797,7 @@ static void getTileInfo( return; } - const MapNode &n1 = vmanip.getNodeRefUnsafeCheckFlags( - blockpos_nodes + p + face_dir); + const MapNode &n1 = vmanip.getNodeRefUnsafeCheckFlags(blockpos_nodes + p + face_dir); if (n1.getContent() == CONTENT_IGNORE) { makes_face = false; @@ -812,8 +809,7 @@ static void getTileInfo( u8 mf = face_contents(n0.getContent(), n1.getContent(), &equivalent, ndef); - if(mf == 0) - { + if (mf == 0) { makes_face = false; return; } @@ -830,34 +826,31 @@ static void getTileInfo( p_corrected = p + face_dir; face_dir_corrected = -face_dir; } - tile = getNodeTile(n, p_corrected, face_dir_corrected, data); + + getNodeTile(n, p_corrected, face_dir_corrected, data, tile); const ContentFeatures &f = ndef->get(n); tile.emissive_light = f.light_source; // eg. water and glass - if (equivalent) + if (equivalent) { for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) tile.layers[layernum].material_flags |= MATERIAL_FLAG_BACKFACE_CULLING; + } - if (data->m_smooth_lighting == false) - { + if (!data->m_smooth_lighting) { lights[0] = lights[1] = lights[2] = lights[3] = getFaceLight(n0, n1, face_dir, ndef); } - else - { + else { v3s16 vertex_dirs[4]; getNodeVertexDirs(face_dir_corrected, vertex_dirs); - for(u16 i=0; i<4; i++) - { - lights[i] = getSmoothLight( - blockpos_nodes + p_corrected, - vertex_dirs[i], data); + + v3s16 light_p = blockpos_nodes + p_corrected; + for (u16 i = 0; i < 4; i++) { + lights[i] = getSmoothLight(light_p, vertex_dirs[i], data); } } - - return; } /* @@ -914,10 +907,7 @@ static void updateFastFaceRow( if (next_makes_face == makes_face && next_p_corrected == p_corrected + translate_dir && next_face_dir_corrected == face_dir_corrected - && next_lights[0] == lights[0] - && next_lights[1] == lights[1] - && next_lights[2] == lights[2] - && next_lights[3] == lights[3] + && memcmp(next_lights, lights, ARRLEN(lights) * sizeof(u16)) == 0 && next_tile.isTileable(tile)) { next_is_different = false; continuous_tiles_count++; @@ -932,7 +922,8 @@ static void updateFastFaceRow( // Floating point conversion of the position vector v3f pf(p_corrected.X, p_corrected.Y, p_corrected.Z); // Center point of face (kind of) - v3f sp = pf - ((f32)continuous_tiles_count / 2.0 - 0.5) * translate_dir_f; + v3f sp = pf - + ((f32)continuous_tiles_count / 2.0f - 0.5f) * translate_dir_f; v3f scale(1,1,1); if(translate_dir.X != 0) { @@ -1148,8 +1139,7 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): m_animation_frame_offsets[std::pair(layer, i)] = 0; } // Replace tile texture with the first animation frame - FrameSpec animation_frame = p.layer.frames[0]; - p.layer.texture = animation_frame.texture; + p.layer.texture = p.layer.frames[0].texture; } if (!m_enable_shaders) { @@ -1337,7 +1327,7 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat scene::IMeshBuffer *buf = m_mesh[i->first.first]-> getMeshBuffer(i->first.second); - FrameSpec animation_frame = tile.frames[frame]; + const FrameSpec &animation_frame = tile.frames[frame]; buf->getMaterial().setTexture(0, animation_frame.texture); if (m_enable_shaders) { if (animation_frame.normal_texture) { diff --git a/src/mapblock_mesh.h b/src/mapblock_mesh.h index f32df3958..93d932a7b 100644 --- a/src/mapblock_mesh.h +++ b/src/mapblock_mesh.h @@ -267,8 +267,10 @@ void final_color_blend(video::SColor *result, // Retrieves the TileSpec of a face of a node // Adds MATERIAL_FLAG_CRACK if the node is cracked -TileSpec getNodeTileN(MapNode mn, v3s16 p, u8 tileindex, MeshMakeData *data); -TileSpec getNodeTile(MapNode mn, v3s16 p, v3s16 dir, MeshMakeData *data); +// TileSpec should be passed as reference due to the underlying TileFrame and its vector +// TileFrame vector copy cost very much to client +void getNodeTileN(MapNode mn, v3s16 p, u8 tileindex, MeshMakeData *data, TileSpec &tile); +void getNodeTile(MapNode mn, v3s16 p, v3s16 dir, MeshMakeData *data, TileSpec &tile); #endif -- cgit v1.2.3 From 7779bac3a5cb93e3336f096ba0a55d965e6123b5 Mon Sep 17 00:00:00 2001 From: numberZero Date: Sat, 20 May 2017 14:29:54 +0400 Subject: Cleanup in content_mapblock (#5746) NDT_LIQUID is being drawn by MapBlockMesh since a long time ago... --- src/content_mapblock.cpp | 86 ++++++++++++++++++------------------------------ src/content_mapblock.h | 11 +++---- 2 files changed, 37 insertions(+), 60 deletions(-) (limited to 'src/content_mapblock.cpp') diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp index 8be0a7d7b..e6dd8e83e 100644 --- a/src/content_mapblock.cpp +++ b/src/content_mapblock.cpp @@ -376,10 +376,10 @@ static TileSpec getSpecialTile(const ContentFeatures &f, return copy; } -void MapblockMeshGenerator::prepareLiquidNodeDrawing(bool flowing) +void MapblockMeshGenerator::prepareLiquidNodeDrawing() { tile_liquid_top = getSpecialTile(*f, n, 0); - tile_liquid = getSpecialTile(*f, n, flowing ? 1 : 0); + tile_liquid = getSpecialTile(*f, n, 1); MapNode ntop = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(p.X, p.Y + 1, p.Z)); c_flowing = nodedef->getId(f->liquid_alternative_flowing); @@ -403,16 +403,12 @@ void MapblockMeshGenerator::prepareLiquidNodeDrawing(bool flowing) color = encode_light(light, f->light_source); } -void MapblockMeshGenerator::getLiquidNeighborhood(bool flowing) +void MapblockMeshGenerator::getLiquidNeighborhood() { u8 range = rangelim(nodedef->get(c_flowing).liquid_range, 1, 8); for (int w = -1; w <= 1; w++) for (int u = -1; u <= 1; u++) { - // Skip getting unneeded data - if (!flowing && u && w) - continue; - NeighborData &neighbor = liquid_neighbors[w + 1][u + 1]; v3s16 p2 = p + v3s16(u, 0, w); MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); @@ -447,13 +443,6 @@ void MapblockMeshGenerator::getLiquidNeighborhood(bool flowing) } } -void MapblockMeshGenerator::resetCornerLevels() -{ - for (int k = 0; k < 2; k++) - for (int i = 0; i < 2; i++) - corner_levels[k][i] = 0.5 * BS; -} - void MapblockMeshGenerator::calculateCornerLevels() { for (int k = 0; k < 2; k++) @@ -494,7 +483,7 @@ f32 MapblockMeshGenerator::getCornerLevel(int i, int k) return 0; } -void MapblockMeshGenerator::drawLiquidSides(bool flowing) +void MapblockMeshGenerator::drawLiquidSides() { struct LiquidFaceDesc { v3s16 dir; // XZ @@ -523,17 +512,12 @@ void MapblockMeshGenerator::drawLiquidSides(bool flowing) // at the top to which it should be connected. Again, unless the face // there would be inside the liquid if (neighbor.is_same_liquid) { - if (!flowing) - continue; if (!top_is_same_liquid) continue; if (neighbor.top_is_same_liquid) continue; } - if (!flowing && (neighbor.content == CONTENT_IGNORE)) - continue; - const ContentFeatures &neighbor_features = nodedef->get(neighbor.content); // Don't draw face if neighbor is blocking the view if (neighbor_features.solidness == 2) @@ -559,7 +543,7 @@ void MapblockMeshGenerator::drawLiquidSides(bool flowing) } } -void MapblockMeshGenerator::drawLiquidTop(bool flowing) +void MapblockMeshGenerator::drawLiquidTop() { // To get backface culling right, the vertices need to go // clockwise around the front of the face. And we happened to @@ -582,45 +566,40 @@ void MapblockMeshGenerator::drawLiquidTop(bool flowing) vertices[i].Pos += origin; } - if (flowing) { - // Default downwards-flowing texture animation goes from - // -Z towards +Z, thus the direction is +Z. - // Rotate texture to make animation go in flow direction - // Positive if liquid moves towards +Z - f32 dz = (corner_levels[0][0] + corner_levels[0][1]) - - (corner_levels[1][0] + corner_levels[1][1]); - // Positive if liquid moves towards +X - f32 dx = (corner_levels[0][0] + corner_levels[1][0]) - - (corner_levels[0][1] + corner_levels[1][1]); - f32 tcoord_angle = atan2(dz, dx) * core::RADTODEG; - v2f tcoord_center(0.5, 0.5); - v2f tcoord_translate(blockpos_nodes.Z + p.Z, blockpos_nodes.X + p.X); - tcoord_translate.rotateBy(tcoord_angle); - tcoord_translate.X -= floor(tcoord_translate.X); - tcoord_translate.Y -= floor(tcoord_translate.Y); - - for (int i = 0; i < 4; i++) { - vertices[i].TCoords.rotateBy(tcoord_angle, tcoord_center); - vertices[i].TCoords += tcoord_translate; - } + // Default downwards-flowing texture animation goes from + // -Z towards +Z, thus the direction is +Z. + // Rotate texture to make animation go in flow direction + // Positive if liquid moves towards +Z + f32 dz = (corner_levels[0][0] + corner_levels[0][1]) - + (corner_levels[1][0] + corner_levels[1][1]); + // Positive if liquid moves towards +X + f32 dx = (corner_levels[0][0] + corner_levels[1][0]) - + (corner_levels[0][1] + corner_levels[1][1]); + f32 tcoord_angle = atan2(dz, dx) * core::RADTODEG; + v2f tcoord_center(0.5, 0.5); + v2f tcoord_translate(blockpos_nodes.Z + p.Z, blockpos_nodes.X + p.X); + tcoord_translate.rotateBy(tcoord_angle); + tcoord_translate.X -= floor(tcoord_translate.X); + tcoord_translate.Y -= floor(tcoord_translate.Y); - std::swap(vertices[0].TCoords, vertices[2].TCoords); + for (int i = 0; i < 4; i++) { + vertices[i].TCoords.rotateBy(tcoord_angle, tcoord_center); + vertices[i].TCoords += tcoord_translate; } + std::swap(vertices[0].TCoords, vertices[2].TCoords); + collector->append(tile_liquid_top, vertices, 4, quad_indices, 6); } -void MapblockMeshGenerator::drawLiquidNode(bool flowing) +void MapblockMeshGenerator::drawLiquidNode() { - prepareLiquidNodeDrawing(flowing); - getLiquidNeighborhood(flowing); - if (flowing) - calculateCornerLevels(); - else - resetCornerLevels(); - drawLiquidSides(flowing); + prepareLiquidNodeDrawing(); + getLiquidNeighborhood(); + calculateCornerLevels(); + drawLiquidSides(); if (!top_is_same_liquid) - drawLiquidTop(flowing); + drawLiquidTop(); } void MapblockMeshGenerator::drawGlasslikeNode() @@ -1291,8 +1270,7 @@ void MapblockMeshGenerator::drawNode() else light = getInteriorLight(n, 1, nodedef); switch (f->drawtype) { - case NDT_LIQUID: drawLiquidNode(false); break; - case NDT_FLOWINGLIQUID: drawLiquidNode(true); break; + case NDT_FLOWINGLIQUID: drawLiquidNode(); break; case NDT_GLASSLIKE: drawGlasslikeNode(); break; case NDT_GLASSLIKE_FRAMED: drawGlasslikeFramedNode(); break; case NDT_ALLFACES: drawAllfacesNode(); break; diff --git a/src/content_mapblock.h b/src/content_mapblock.h index 310e38e7c..2c6a4969e 100644 --- a/src/content_mapblock.h +++ b/src/content_mapblock.h @@ -93,13 +93,12 @@ public: NeighborData liquid_neighbors[3][3]; f32 corner_levels[2][2]; - void prepareLiquidNodeDrawing(bool flowing); - void getLiquidNeighborhood(bool flowing); - void resetCornerLevels(); + void prepareLiquidNodeDrawing(); + void getLiquidNeighborhood(); void calculateCornerLevels(); f32 getCornerLevel(int i, int k); - void drawLiquidSides(bool flowing); - void drawLiquidTop(bool flowing); + void drawLiquidSides(); + void drawLiquidTop(); // raillike-specific // name of the group that enables connecting to raillike nodes of different kind @@ -122,7 +121,7 @@ public: float offset_h, float offset_v = 0.0); // drawtypes - void drawLiquidNode(bool flowing); + void drawLiquidNode(); void drawGlasslikeNode(); void drawGlasslikeFramedNode(); void drawAllfacesNode(); -- cgit v1.2.3