]> git.lizzy.rs Git - minetest.git/blob - src/client/mesh_generator_thread.cpp
Switch MeshUpdateQueue to better data structure
[minetest.git] / src / client / mesh_generator_thread.cpp
1 /*
2 Minetest
3 Copyright (C) 2013, 2017 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 #include "mesh_generator_thread.h"
21 #include "settings.h"
22 #include "profiler.h"
23 #include "client.h"
24 #include "mapblock.h"
25 #include "map.h"
26 #include "util/directiontables.h"
27
28 /*
29         CachedMapBlockData
30 */
31
32 CachedMapBlockData::~CachedMapBlockData()
33 {
34         assert(refcount_from_queue == 0);
35
36         delete[] data;
37 }
38
39 /*
40         QueuedMeshUpdate
41 */
42
43 QueuedMeshUpdate::~QueuedMeshUpdate()
44 {
45         delete data;
46 }
47
48 /*
49         MeshUpdateQueue
50 */
51
52 MeshUpdateQueue::MeshUpdateQueue(Client *client):
53         m_client(client),
54         m_next_cache_cleanup(0)
55 {
56         m_cache_enable_shaders = g_settings->getBool("enable_shaders");
57         m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
58         m_meshgen_block_cache_size = g_settings->getS32("meshgen_block_cache_size");
59 }
60
61 MeshUpdateQueue::~MeshUpdateQueue()
62 {
63         MutexAutoLock lock(m_mutex);
64
65         for (auto &i : m_cache) {
66                 delete i.second;
67         }
68
69         for (QueuedMeshUpdate *q : m_queue) {
70                 delete q;
71         }
72 }
73
74 bool MeshUpdateQueue::addBlock(Map *map, v3s16 p, bool ack_block_to_server, bool urgent)
75 {
76         MutexAutoLock lock(m_mutex);
77
78         cleanupCache();
79
80         /*
81                 Cache the block data (force-update the center block, don't update the
82                 neighbors but get them if they aren't already cached)
83         */
84         std::vector<CachedMapBlockData*> cached_blocks;
85         size_t cache_hit_counter = 0;
86         CachedMapBlockData *cached_block = cacheBlock(map, p, FORCE_UPDATE);
87         if (!cached_block->data)
88                 return false; // nothing to update
89         cached_blocks.reserve(3*3*3);
90         cached_blocks.push_back(cached_block);
91         for (v3s16 dp : g_26dirs)
92                 cached_blocks.push_back(cacheBlock(map, p + dp,
93                                 SKIP_UPDATE_IF_ALREADY_CACHED,
94                                 &cache_hit_counter));
95         g_profiler->avg("MeshUpdateQueue: MapBlocks from cache [%]",
96                         100.0f * cache_hit_counter / cached_blocks.size());
97
98         /*
99                 Mark the block as urgent if requested
100         */
101         if (urgent)
102                 m_urgents.insert(p);
103
104         /*
105                 Find if block is already in queue.
106                 If it is, update the data and quit.
107         */
108         for (QueuedMeshUpdate *q : m_queue) {
109                 if (q->p == p) {
110                         // NOTE: We are not adding a new position to the queue, thus
111                         //       refcount_from_queue stays the same.
112                         if(ack_block_to_server)
113                                 q->ack_block_to_server = true;
114                         q->crack_level = m_client->getCrackLevel();
115                         q->crack_pos = m_client->getCrackPos();
116                         return true;
117                 }
118         }
119
120         /*
121                 Add the block
122         */
123         QueuedMeshUpdate *q = new QueuedMeshUpdate;
124         q->p = p;
125         q->ack_block_to_server = ack_block_to_server;
126         q->crack_level = m_client->getCrackLevel();
127         q->crack_pos = m_client->getCrackPos();
128         m_queue.push_back(q);
129
130         // This queue entry is a new reference to the cached blocks
131         for (CachedMapBlockData *cached_block : cached_blocks) {
132                 cached_block->refcount_from_queue++;
133         }
134         return true;
135 }
136
137 // Returned pointer must be deleted
138 // Returns NULL if queue is empty
139 QueuedMeshUpdate *MeshUpdateQueue::pop()
140 {
141         MutexAutoLock lock(m_mutex);
142
143         bool must_be_urgent = !m_urgents.empty();
144         for (std::vector<QueuedMeshUpdate*>::iterator i = m_queue.begin();
145                         i != m_queue.end(); ++i) {
146                 QueuedMeshUpdate *q = *i;
147                 if(must_be_urgent && m_urgents.count(q->p) == 0)
148                         continue;
149                 m_queue.erase(i);
150                 m_urgents.erase(q->p);
151                 fillDataFromMapBlockCache(q);
152                 return q;
153         }
154         return NULL;
155 }
156
157 CachedMapBlockData* MeshUpdateQueue::cacheBlock(Map *map, v3s16 p, UpdateMode mode,
158                         size_t *cache_hit_counter)
159 {
160         CachedMapBlockData *cached_block = nullptr;
161         auto it = m_cache.find(p);
162
163         if (it != m_cache.end()) {
164                 cached_block = it->second;
165
166                 if (mode == SKIP_UPDATE_IF_ALREADY_CACHED) {
167                         if (cache_hit_counter)
168                                 (*cache_hit_counter)++;
169                         return cached_block;
170                 }
171         }
172
173         if (!cached_block) {
174                 // Not yet in cache
175                 cached_block = new CachedMapBlockData();
176                 m_cache[p] = cached_block;
177         }
178
179         MapBlock *b = map->getBlockNoCreateNoEx(p);
180         if (b) {
181                 if (!cached_block->data)
182                         cached_block->data =
183                                         new MapNode[MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE];
184                 memcpy(cached_block->data, b->getData(),
185                                 MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE * sizeof(MapNode));
186         } else {
187                 delete[] cached_block->data;
188                 cached_block->data = nullptr;
189         }
190         return cached_block;
191 }
192
193 CachedMapBlockData* MeshUpdateQueue::getCachedBlock(const v3s16 &p)
194 {
195         auto it = m_cache.find(p);
196         if (it != m_cache.end()) {
197                 return it->second;
198         }
199         return NULL;
200 }
201
202 void MeshUpdateQueue::fillDataFromMapBlockCache(QueuedMeshUpdate *q)
203 {
204         MeshMakeData *data = new MeshMakeData(m_client, m_cache_enable_shaders);
205         q->data = data;
206
207         data->fillBlockDataBegin(q->p);
208
209         std::time_t t_now = std::time(0);
210
211         // Collect data for 3*3*3 blocks from cache
212         for (v3s16 dp : g_27dirs) {
213                 v3s16 p = q->p + dp;
214                 CachedMapBlockData *cached_block = getCachedBlock(p);
215                 if (cached_block) {
216                         cached_block->refcount_from_queue--;
217                         cached_block->last_used_timestamp = t_now;
218                         if (cached_block->data)
219                                 data->fillBlockData(dp, cached_block->data);
220                 }
221         }
222
223         data->setCrack(q->crack_level, q->crack_pos);
224         data->setSmoothLighting(m_cache_smooth_lighting);
225 }
226
227 void MeshUpdateQueue::cleanupCache()
228 {
229         const int mapblock_kB = MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE *
230                         sizeof(MapNode) / 1000;
231         g_profiler->avg("MeshUpdateQueue MapBlock cache size kB",
232                         mapblock_kB * m_cache.size());
233
234         // Iterating the entire cache can get pretty expensive so don't do it too often
235         {
236                 constexpr int cleanup_interval = 250;
237                 const u64 now = porting::getTimeMs();
238                 if (m_next_cache_cleanup > now)
239                         return;
240                 m_next_cache_cleanup = now + cleanup_interval;
241         }
242
243         // The cache size is kept roughly below cache_soft_max_size, not letting
244         // anything get older than cache_seconds_max or deleted before 2 seconds.
245         const int cache_seconds_max = 10;
246         const int cache_soft_max_size = m_meshgen_block_cache_size * 1000 / mapblock_kB;
247         int cache_seconds = MYMAX(2, cache_seconds_max -
248                         m_cache.size() / (cache_soft_max_size / cache_seconds_max));
249
250         int t_now = time(0);
251
252         for (auto it = m_cache.begin(); it != m_cache.end(); ) {
253                 CachedMapBlockData *cached_block = it->second;
254                 if (cached_block->refcount_from_queue == 0 &&
255                                 cached_block->last_used_timestamp < t_now - cache_seconds) {
256                         it = m_cache.erase(it);
257                         delete cached_block;
258                 } else {
259                         ++it;
260                 }
261         }
262 }
263
264 /*
265         MeshUpdateThread
266 */
267
268 MeshUpdateThread::MeshUpdateThread(Client *client):
269         UpdateThread("Mesh"),
270         m_queue_in(client)
271 {
272         m_generation_interval = g_settings->getU16("mesh_generation_interval");
273         m_generation_interval = rangelim(m_generation_interval, 0, 50);
274 }
275
276 void MeshUpdateThread::updateBlock(Map *map, v3s16 p, bool ack_block_to_server,
277                 bool urgent, bool update_neighbors)
278 {
279         static thread_local const bool many_neighbors =
280                         g_settings->getBool("smooth_lighting")
281                         && !g_settings->getFlag("performance_tradeoffs");
282         if (!m_queue_in.addBlock(map, p, ack_block_to_server, urgent)) {
283                 warningstream << "Update requested for non-existent block at ("
284                                 << p.X << ", " << p.Y << ", " << p.Z << ")" << std::endl;
285                 return;
286         }
287         if (update_neighbors) {
288                 if (many_neighbors) {
289                         for (v3s16 dp : g_26dirs)
290                                 m_queue_in.addBlock(map, p + dp, false, urgent);
291                 } else {
292                         for (v3s16 dp : g_6dirs)
293                                 m_queue_in.addBlock(map, p + dp, false, urgent);
294                 }
295         }
296         deferUpdate();
297 }
298
299 void MeshUpdateThread::doUpdate()
300 {
301         QueuedMeshUpdate *q;
302         while ((q = m_queue_in.pop())) {
303                 if (m_generation_interval)
304                         sleep_ms(m_generation_interval);
305                 ScopeProfiler sp(g_profiler, "Client: Mesh making (sum)");
306
307                 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
308
309                 MeshUpdateResult r;
310                 r.p = q->p;
311                 r.mesh = mesh_new;
312                 r.ack_block_to_server = q->ack_block_to_server;
313
314                 m_queue_out.push_back(r);
315
316                 delete q;
317         }
318 }