]> git.lizzy.rs Git - minetest.git/blob - src/client/mapblock_mesh.h
8x block meshes (#13133)
[minetest.git] / src / client / mapblock_mesh.h
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #pragma once
21
22 #include "irrlichttypes_extrabloated.h"
23 #include "client/tile.h"
24 #include "voxel.h"
25 #include <array>
26 #include <map>
27 #include <unordered_map>
28
29 class Client;
30 class IShaderSource;
31
32 /*
33         Mesh making stuff
34 */
35
36
37 class MapBlock;
38 struct MinimapMapblock;
39
40 struct MeshMakeData
41 {
42         VoxelManipulator m_vmanip;
43         v3s16 m_blockpos = v3s16(-1337,-1337,-1337);
44         v3s16 m_crack_pos_relative = v3s16(-1337,-1337,-1337);
45         bool m_smooth_lighting = false;
46         u16 side_length = MAP_BLOCKSIZE;
47
48         Client *m_client;
49         bool m_use_shaders;
50
51         MeshMakeData(Client *client, bool use_shaders);
52
53         /*
54                 Copy block data manually (to allow optimizations by the caller)
55         */
56         void fillBlockDataBegin(const v3s16 &blockpos);
57         void fillBlockData(const v3s16 &block_offset, MapNode *data);
58
59         /*
60                 Set the (node) position of a crack
61         */
62         void setCrack(int crack_level, v3s16 crack_pos);
63
64         /*
65                 Enable or disable smooth lighting
66         */
67         void setSmoothLighting(bool smooth_lighting);
68 };
69
70 // represents a triangle as indexes into the vertex buffer in SMeshBuffer
71 class MeshTriangle
72 {
73 public:
74         scene::SMeshBuffer *buffer;
75         u16 p1, p2, p3;
76         v3f centroid;
77         float areaSQ;
78
79         void updateAttributes()
80         {
81                 v3f v1 = buffer->getPosition(p1);
82                 v3f v2 = buffer->getPosition(p2);
83                 v3f v3 = buffer->getPosition(p3);
84
85                 centroid = (v1 + v2 + v3) / 3;
86                 areaSQ = (v2-v1).crossProduct(v3-v1).getLengthSQ() / 4;
87         }
88
89         v3f getNormal() const {
90                 v3f v1 = buffer->getPosition(p1);
91                 v3f v2 = buffer->getPosition(p2);
92                 v3f v3 = buffer->getPosition(p3);
93
94                 return (v2-v1).crossProduct(v3-v1);
95         }
96 };
97
98 /**
99  * Implements a binary space partitioning tree
100  * See also: https://en.wikipedia.org/wiki/Binary_space_partitioning
101  */
102 class MapBlockBspTree
103 {
104 public:
105         MapBlockBspTree() {}
106
107         void buildTree(const std::vector<MeshTriangle> *triangles, u16 side_lingth);
108
109         void traverse(v3f viewpoint, std::vector<s32> &output) const
110         {
111                 traverse(root, viewpoint, output);
112         }
113
114 private:
115         // Tree node definition;
116         struct TreeNode
117         {
118                 v3f normal;
119                 v3f origin;
120                 std::vector<s32> triangle_refs;
121                 s32 front_ref;
122                 s32 back_ref;
123
124                 TreeNode() = default;
125                 TreeNode(v3f normal, v3f origin, const std::vector<s32> &triangle_refs, s32 front_ref, s32 back_ref) :
126                                 normal(normal), origin(origin), triangle_refs(triangle_refs), front_ref(front_ref), back_ref(back_ref)
127                 {}
128         };
129
130
131         s32 buildTree(v3f normal, v3f origin, float delta, const std::vector<s32> &list, u32 depth);
132         void traverse(s32 node, v3f viewpoint, std::vector<s32> &output) const;
133
134         const std::vector<MeshTriangle> *triangles = nullptr; // this reference is managed externally
135         std::vector<TreeNode> nodes; // list of nodes
136         s32 root = -1; // index of the root node
137 };
138
139 /*
140  * PartialMeshBuffer
141  *
142  * Attach alternate `Indices` to an existing mesh buffer, to make it possible to use different
143  * indices with the same vertex buffer.
144  *
145  * Irrlicht does not currently support this: `CMeshBuffer` ties together a single vertex buffer
146  * and a single index buffer. There's no way to share these between mesh buffers.
147  *
148  */
149 class PartialMeshBuffer
150 {
151 public:
152         PartialMeshBuffer(scene::SMeshBuffer *buffer, std::vector<u16> &&vertex_indexes) :
153                         m_buffer(buffer), m_vertex_indexes(std::move(vertex_indexes))
154         {}
155
156         scene::IMeshBuffer *getBuffer() const { return m_buffer; }
157         const std::vector<u16> &getVertexIndexes() const { return m_vertex_indexes; }
158
159         void beforeDraw() const;
160         void afterDraw() const;
161 private:
162         scene::SMeshBuffer *m_buffer;
163         mutable std::vector<u16> m_vertex_indexes;
164 };
165
166 /*
167         Holds a mesh for a mapblock.
168
169         Besides the SMesh*, this contains information used for animating
170         the vertex positions, colors and texture coordinates of the mesh.
171         For example:
172         - cracks [implemented]
173         - day/night transitions [implemented]
174         - animated flowing liquids [not implemented]
175         - animating vertex positions for e.g. axles [not implemented]
176 */
177 class MapBlockMesh
178 {
179 public:
180         // Builds the mesh given
181         MapBlockMesh(MeshMakeData *data, v3s16 camera_offset);
182         ~MapBlockMesh();
183
184         // Main animation function, parameters:
185         //   faraway: whether the block is far away from the camera (~50 nodes)
186         //   time: the global animation time, 0 .. 60 (repeats every minute)
187         //   daynight_ratio: 0 .. 1000
188         //   crack: -1 .. CRACK_ANIMATION_LENGTH-1 (-1 for off)
189         // Returns true if anything has been changed.
190         bool animate(bool faraway, float time, int crack, u32 daynight_ratio);
191
192         scene::IMesh *getMesh()
193         {
194                 return m_mesh[0];
195         }
196
197         scene::IMesh *getMesh(u8 layer)
198         {
199                 return m_mesh[layer];
200         }
201
202         std::vector<MinimapMapblock*> moveMinimapMapblocks()
203         {
204                 std::vector<MinimapMapblock*> minimap_mapblocks;
205                 minimap_mapblocks.swap(m_minimap_mapblocks);
206                 return minimap_mapblocks;
207         }
208
209         bool isAnimationForced() const
210         {
211                 return m_animation_force_timer == 0;
212         }
213
214         void decreaseAnimationForceTimer()
215         {
216                 if(m_animation_force_timer > 0)
217                         m_animation_force_timer--;
218         }
219
220         /// Radius of the bounding-sphere, in BS-space.
221         f32 getBoundingRadius() const { return m_bounding_radius; }
222
223         /// Center of the bounding-sphere, in BS-space, relative to block pos.
224         v3f getBoundingSphereCenter() const { return m_bounding_sphere_center; }
225
226         /// update transparent buffers to render towards the camera
227         void updateTransparentBuffers(v3f camera_pos, v3s16 block_pos);
228         void consolidateTransparentBuffers();
229
230         /// get the list of transparent buffers
231         const std::vector<PartialMeshBuffer> &getTransparentBuffers() const
232         {
233                 return this->m_transparent_buffers;
234         }
235
236 private:
237         struct AnimationInfo {
238                 int frame; // last animation frame
239                 int frame_offset;
240                 TileLayer tile;
241         };
242
243         scene::IMesh *m_mesh[MAX_TILE_LAYERS];
244         std::vector<MinimapMapblock*> m_minimap_mapblocks;
245         ITextureSource *m_tsrc;
246         IShaderSource *m_shdrsrc;
247
248         f32 m_bounding_radius;
249         // MapblockMeshGenerator uses the same as mapblock center
250         v3f m_bounding_sphere_center = v3f((MAP_BLOCKSIZE * 0.5f - 0.5f) * BS);
251
252         bool m_enable_shaders;
253         bool m_enable_vbo;
254
255         // Must animate() be called before rendering?
256         bool m_has_animation;
257         int m_animation_force_timer;
258
259         // Animation info: cracks
260         // Last crack value passed to animate()
261         int m_last_crack;
262         // Maps mesh and mesh buffer (i.e. material) indices to base texture names
263         std::map<std::pair<u8, u32>, std::string> m_crack_materials;
264
265         // Animation info: texture animation
266         // Maps mesh and mesh buffer indices to TileSpecs
267         // Keys are pairs of (mesh index, buffer index in the mesh)
268         std::map<std::pair<u8, u32>, AnimationInfo> m_animation_info;
269
270         // Animation info: day/night transitions
271         // Last daynight_ratio value passed to animate()
272         u32 m_last_daynight_ratio;
273         // For each mesh and mesh buffer, stores pre-baked colors
274         // of sunlit vertices
275         // Keys are pairs of (mesh index, buffer index in the mesh)
276         std::map<std::pair<u8, u32>, std::map<u32, video::SColor > > m_daynight_diffs;
277
278         // list of all semitransparent triangles in the mapblock
279         std::vector<MeshTriangle> m_transparent_triangles;
280         // Binary Space Partitioning tree for the block
281         MapBlockBspTree m_bsp_tree;
282         // Ordered list of references to parts of transparent buffers to draw
283         std::vector<PartialMeshBuffer> m_transparent_buffers;
284 };
285
286 /*!
287  * Encodes light of a node.
288  * The result is not the final color, but a
289  * half-baked vertex color.
290  * You have to multiply the resulting color
291  * with the node's color.
292  *
293  * \param light the first 8 bits are day light,
294  * the last 8 bits are night light
295  * \param emissive_light amount of light the surface emits,
296  * from 0 to LIGHT_SUN.
297  */
298 video::SColor encode_light(u16 light, u8 emissive_light);
299
300 // Compute light at node
301 u16 getInteriorLight(MapNode n, s32 increment, const NodeDefManager *ndef);
302 u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir,
303         const NodeDefManager *ndef);
304 u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner, MeshMakeData *data);
305 u16 getSmoothLightTransparent(const v3s16 &p, const v3s16 &corner, MeshMakeData *data);
306
307 /*!
308  * Returns the sunlight's color from the current
309  * day-night ratio.
310  */
311 void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio);
312
313 /*!
314  * Gives the final  SColor shown on screen.
315  *
316  * \param result output color
317  * \param light first 8 bits are day light, second 8 bits are
318  * night light
319  */
320 void final_color_blend(video::SColor *result,
321                 u16 light, u32 daynight_ratio);
322
323 /*!
324  * Gives the final  SColor shown on screen.
325  *
326  * \param result output color
327  * \param data the half-baked vertex color
328  * \param dayLight color of the sunlight
329  */
330 void final_color_blend(video::SColor *result,
331                 const video::SColor &data, const video::SColorf &dayLight);
332
333 // Retrieves the TileSpec of a face of a node
334 // Adds MATERIAL_FLAG_CRACK if the node is cracked
335 // TileSpec should be passed as reference due to the underlying TileFrame and its vector
336 // TileFrame vector copy cost very much to client
337 void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data, TileSpec &tile);
338 void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data, TileSpec &tile);
339
340 /// Return bitset of the sides of the mapblock that consist of solid nodes only
341 /// Bits:
342 /// 0 0 -Z +Z -X +X -Y +Y
343 std::unordered_map<v3s16, u8> get_solid_sides(MeshMakeData *data);