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