Code modernization: src/m* (part 3)
[oweals/minetest.git] / src / minimap.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2015 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 "minimap.h"
21 #include "client.h"
22 #include "clientmap.h"
23 #include "settings.h"
24 #include "shader.h"
25 #include "mapblock.h"
26 #include "client/renderingengine.h"
27
28
29 ////
30 //// MinimapUpdateThread
31 ////
32
33 MinimapUpdateThread::~MinimapUpdateThread()
34 {
35         for (auto &it : m_blocks_cache) {
36                 delete it.second;
37         }
38
39         for (auto &q : m_update_queue) {
40                 delete q.data;
41         }
42 }
43
44 bool MinimapUpdateThread::pushBlockUpdate(v3s16 pos, MinimapMapblock *data)
45 {
46         MutexAutoLock lock(m_queue_mutex);
47
48         // Find if block is already in queue.
49         // If it is, update the data and quit.
50         for (QueuedMinimapUpdate &q : m_update_queue) {
51                 if (q.pos == pos) {
52                         delete q.data;
53                         q.data = data;
54                         return false;
55                 }
56         }
57
58         // Add the block
59         QueuedMinimapUpdate q;
60         q.pos  = pos;
61         q.data = data;
62         m_update_queue.push_back(q);
63
64         return true;
65 }
66
67 bool MinimapUpdateThread::popBlockUpdate(QueuedMinimapUpdate *update)
68 {
69         MutexAutoLock lock(m_queue_mutex);
70
71         if (m_update_queue.empty())
72                 return false;
73
74         *update = m_update_queue.front();
75         m_update_queue.pop_front();
76
77         return true;
78 }
79
80 void MinimapUpdateThread::enqueueBlock(v3s16 pos, MinimapMapblock *data)
81 {
82         pushBlockUpdate(pos, data);
83         deferUpdate();
84 }
85
86
87 void MinimapUpdateThread::doUpdate()
88 {
89         QueuedMinimapUpdate update;
90
91         while (popBlockUpdate(&update)) {
92                 if (update.data) {
93                         // Swap two values in the map using single lookup
94                         std::pair<std::map<v3s16, MinimapMapblock*>::iterator, bool>
95                             result = m_blocks_cache.insert(std::make_pair(update.pos, update.data));
96                         if (!result.second) {
97                                 delete result.first->second;
98                                 result.first->second = update.data;
99                         }
100                 } else {
101                         std::map<v3s16, MinimapMapblock *>::iterator it;
102                         it = m_blocks_cache.find(update.pos);
103                         if (it != m_blocks_cache.end()) {
104                                 delete it->second;
105                                 m_blocks_cache.erase(it);
106                         }
107                 }
108         }
109
110         if (data->map_invalidated && data->mode != MINIMAP_MODE_OFF) {
111                 getMap(data->pos, data->map_size, data->scan_height);
112                 data->map_invalidated = false;
113         }
114 }
115
116 void MinimapUpdateThread::getMap(v3s16 pos, s16 size, s16 height)
117 {
118         v3s16 pos_min(pos.X - size / 2, pos.Y - height / 2, pos.Z - size / 2);
119         v3s16 pos_max(pos_min.X + size - 1, pos.Y + height / 2, pos_min.Z + size - 1);
120         v3s16 blockpos_min = getNodeBlockPos(pos_min);
121         v3s16 blockpos_max = getNodeBlockPos(pos_max);
122
123 // clear the map
124         for (int z = 0; z < size; z++)
125         for (int x = 0; x < size; x++) {
126                 MinimapPixel &mmpixel = data->minimap_scan[x + z * size];
127                 mmpixel.air_count = 0;
128                 mmpixel.height = 0;
129                 mmpixel.n = MapNode(CONTENT_AIR);
130         }
131
132 // draw the map
133         v3s16 blockpos;
134         for (blockpos.Z = blockpos_min.Z; blockpos.Z <= blockpos_max.Z; ++blockpos.Z)
135         for (blockpos.Y = blockpos_min.Y; blockpos.Y <= blockpos_max.Y; ++blockpos.Y)
136         for (blockpos.X = blockpos_min.X; blockpos.X <= blockpos_max.X; ++blockpos.X) {
137                 std::map<v3s16, MinimapMapblock *>::const_iterator pblock =
138                         m_blocks_cache.find(blockpos);
139                 if (pblock == m_blocks_cache.end())
140                         continue;
141                 const MinimapMapblock &block = *pblock->second;
142
143                 v3s16 block_node_min(blockpos * MAP_BLOCKSIZE);
144                 v3s16 block_node_max(block_node_min + MAP_BLOCKSIZE - 1);
145                 // clip
146                 v3s16 range_min = componentwise_max(block_node_min, pos_min);
147                 v3s16 range_max = componentwise_min(block_node_max, pos_max);
148
149                 v3s16 pos;
150                 pos.Y = range_min.Y;
151                 for (pos.Z = range_min.Z; pos.Z <= range_max.Z; ++pos.Z)
152                 for (pos.X = range_min.X; pos.X <= range_max.X; ++pos.X) {
153                         v3s16 inblock_pos = pos - block_node_min;
154                         const MinimapPixel &in_pixel =
155                                 block.data[inblock_pos.Z * MAP_BLOCKSIZE + inblock_pos.X];
156
157                         v3s16 inmap_pos = pos - pos_min;
158                         MinimapPixel &out_pixel =
159                                 data->minimap_scan[inmap_pos.X + inmap_pos.Z * size];
160
161                         out_pixel.air_count += in_pixel.air_count;
162                         if (in_pixel.n.param0 != CONTENT_AIR) {
163                                 out_pixel.n = in_pixel.n;
164                                 out_pixel.height = inmap_pos.Y + in_pixel.height;
165                         }
166                 }
167         }
168 }
169
170 ////
171 //// Mapper
172 ////
173
174 Minimap::Minimap(Client *client)
175 {
176         this->client    = client;
177         this->driver    = RenderingEngine::get_video_driver();
178         this->m_tsrc    = client->getTextureSource();
179         this->m_shdrsrc = client->getShaderSource();
180         this->m_ndef    = client->getNodeDefManager();
181
182         m_angle = 0.f;
183
184         // Initialize static settings
185         m_enable_shaders = g_settings->getBool("enable_shaders");
186         m_surface_mode_scan_height =
187                 g_settings->getBool("minimap_double_scan_height") ? 256 : 128;
188
189         // Initialize minimap data
190         data = new MinimapData;
191         data->mode              = MINIMAP_MODE_OFF;
192         data->is_radar          = false;
193         data->map_invalidated   = true;
194         data->texture           = NULL;
195         data->heightmap_texture = NULL;
196         data->minimap_shape_round = g_settings->getBool("minimap_shape_round");
197
198         // Get round minimap textures
199         data->minimap_mask_round = driver->createImage(
200                 m_tsrc->getTexture("minimap_mask_round.png"),
201                 core::position2d<s32>(0, 0),
202                 core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
203         data->minimap_overlay_round = m_tsrc->getTexture("minimap_overlay_round.png");
204
205         // Get square minimap textures
206         data->minimap_mask_square = driver->createImage(
207                 m_tsrc->getTexture("minimap_mask_square.png"),
208                 core::position2d<s32>(0, 0),
209                 core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
210         data->minimap_overlay_square = m_tsrc->getTexture("minimap_overlay_square.png");
211
212         // Create player marker texture
213         data->player_marker = m_tsrc->getTexture("player_marker.png");
214         // Create object marker texture
215         data->object_marker_red = m_tsrc->getTexture("object_marker_red.png");
216
217         // Create mesh buffer for minimap
218         m_meshbuffer = getMinimapMeshBuffer();
219
220         // Initialize and start thread
221         m_minimap_update_thread = new MinimapUpdateThread();
222         m_minimap_update_thread->data = data;
223         m_minimap_update_thread->start();
224 }
225
226 Minimap::~Minimap()
227 {
228         m_minimap_update_thread->stop();
229         m_minimap_update_thread->wait();
230
231         m_meshbuffer->drop();
232
233         data->minimap_mask_round->drop();
234         data->minimap_mask_square->drop();
235
236         driver->removeTexture(data->texture);
237         driver->removeTexture(data->heightmap_texture);
238         driver->removeTexture(data->minimap_overlay_round);
239         driver->removeTexture(data->minimap_overlay_square);
240         driver->removeTexture(data->object_marker_red);
241
242         delete data;
243         delete m_minimap_update_thread;
244 }
245
246 void Minimap::addBlock(v3s16 pos, MinimapMapblock *data)
247 {
248         m_minimap_update_thread->enqueueBlock(pos, data);
249 }
250
251 void Minimap::toggleMinimapShape()
252 {
253         MutexAutoLock lock(m_mutex);
254
255         data->minimap_shape_round = !data->minimap_shape_round;
256         g_settings->setBool("minimap_shape_round", data->minimap_shape_round);
257         m_minimap_update_thread->deferUpdate();
258 }
259
260 void Minimap::setMinimapShape(MinimapShape shape)
261 {
262         MutexAutoLock lock(m_mutex);
263
264         if (shape == MINIMAP_SHAPE_SQUARE)
265                 data->minimap_shape_round = false;
266         else if (shape == MINIMAP_SHAPE_ROUND)
267                 data->minimap_shape_round = true;
268
269         g_settings->setBool("minimap_shape_round", data->minimap_shape_round);
270         m_minimap_update_thread->deferUpdate();
271 }
272
273 MinimapShape Minimap::getMinimapShape()
274 {
275         if (data->minimap_shape_round) {
276                 return MINIMAP_SHAPE_ROUND;
277         }
278
279         return MINIMAP_SHAPE_SQUARE;
280 }
281
282 void Minimap::setMinimapMode(MinimapMode mode)
283 {
284         static const MinimapModeDef modedefs[MINIMAP_MODE_COUNT] = {
285                 {false, 0, 0},
286                 {false, m_surface_mode_scan_height, 256},
287                 {false, m_surface_mode_scan_height, 128},
288                 {false, m_surface_mode_scan_height, 64},
289                 {true, 32, 128},
290                 {true, 32, 64},
291                 {true, 32, 32}
292         };
293
294         if (mode >= MINIMAP_MODE_COUNT)
295                 return;
296
297         MutexAutoLock lock(m_mutex);
298
299         data->is_radar    = modedefs[mode].is_radar;
300         data->scan_height = modedefs[mode].scan_height;
301         data->map_size    = modedefs[mode].map_size;
302         data->mode        = mode;
303
304         m_minimap_update_thread->deferUpdate();
305 }
306
307 void Minimap::setPos(v3s16 pos)
308 {
309         bool do_update = false;
310
311         {
312                 MutexAutoLock lock(m_mutex);
313
314                 if (pos != data->old_pos) {
315                         data->old_pos = data->pos;
316                         data->pos = pos;
317                         do_update = true;
318                 }
319         }
320
321         if (do_update)
322                 m_minimap_update_thread->deferUpdate();
323 }
324
325 void Minimap::setAngle(f32 angle)
326 {
327         m_angle = angle;
328 }
329
330 void Minimap::blitMinimapPixelsToImageRadar(video::IImage *map_image)
331 {
332         video::SColor c(240, 0, 0, 0);
333         for (s16 x = 0; x < data->map_size; x++)
334         for (s16 z = 0; z < data->map_size; z++) {
335                 MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size];
336
337                 if (mmpixel->air_count > 0)
338                         c.setGreen(core::clamp(core::round32(32 + mmpixel->air_count * 8), 0, 255));
339                 else
340                         c.setGreen(0);
341
342                 map_image->setPixel(x, data->map_size - z - 1, c);
343         }
344 }
345
346 void Minimap::blitMinimapPixelsToImageSurface(
347         video::IImage *map_image, video::IImage *heightmap_image)
348 {
349         // This variable creation/destruction has a 1% cost on rendering minimap
350         video::SColor tilecolor;
351         for (s16 x = 0; x < data->map_size; x++)
352         for (s16 z = 0; z < data->map_size; z++) {
353                 MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size];
354
355                 const ContentFeatures &f = m_ndef->get(mmpixel->n);
356                 const TileDef *tile = &f.tiledef[0];
357
358                 // Color of the 0th tile (mostly this is the topmost)
359                 if(tile->has_color)
360                         tilecolor = tile->color;
361                 else
362                         mmpixel->n.getColor(f, &tilecolor);
363
364                 tilecolor.setRed(tilecolor.getRed() * f.minimap_color.getRed() / 255);
365                 tilecolor.setGreen(tilecolor.getGreen() * f.minimap_color.getGreen() / 255);
366                 tilecolor.setBlue(tilecolor.getBlue() * f.minimap_color.getBlue() / 255);
367                 tilecolor.setAlpha(240);
368
369                 map_image->setPixel(x, data->map_size - z - 1, tilecolor);
370
371                 u32 h = mmpixel->height;
372                 heightmap_image->setPixel(x,data->map_size - z - 1,
373                         video::SColor(255, h, h, h));
374         }
375 }
376
377 video::ITexture *Minimap::getMinimapTexture()
378 {
379         // update minimap textures when new scan is ready
380         if (data->map_invalidated)
381                 return data->texture;
382
383         // create minimap and heightmap images in memory
384         core::dimension2d<u32> dim(data->map_size, data->map_size);
385         video::IImage *map_image       = driver->createImage(video::ECF_A8R8G8B8, dim);
386         video::IImage *heightmap_image = driver->createImage(video::ECF_A8R8G8B8, dim);
387         video::IImage *minimap_image   = driver->createImage(video::ECF_A8R8G8B8,
388                 core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
389
390         // Blit MinimapPixels to images
391         if (data->is_radar)
392                 blitMinimapPixelsToImageRadar(map_image);
393         else
394                 blitMinimapPixelsToImageSurface(map_image, heightmap_image);
395
396         map_image->copyToScaling(minimap_image);
397         map_image->drop();
398
399         video::IImage *minimap_mask = data->minimap_shape_round ?
400                 data->minimap_mask_round : data->minimap_mask_square;
401
402         if (minimap_mask) {
403                 for (s16 y = 0; y < MINIMAP_MAX_SY; y++)
404                 for (s16 x = 0; x < MINIMAP_MAX_SX; x++) {
405                         const video::SColor &mask_col = minimap_mask->getPixel(x, y);
406                         if (!mask_col.getAlpha())
407                                 minimap_image->setPixel(x, y, video::SColor(0,0,0,0));
408                 }
409         }
410
411         if (data->texture)
412                 driver->removeTexture(data->texture);
413         if (data->heightmap_texture)
414                 driver->removeTexture(data->heightmap_texture);
415
416         data->texture = driver->addTexture("minimap__", minimap_image);
417         data->heightmap_texture =
418                 driver->addTexture("minimap_heightmap__", heightmap_image);
419         minimap_image->drop();
420         heightmap_image->drop();
421
422         data->map_invalidated = true;
423
424         return data->texture;
425 }
426
427 v3f Minimap::getYawVec()
428 {
429         if (data->minimap_shape_round) {
430                 return v3f(
431                         cos(m_angle * core::DEGTORAD),
432                         sin(m_angle * core::DEGTORAD),
433                         1.0);
434         }
435
436         return v3f(1.0, 0.0, 1.0);
437 }
438
439 scene::SMeshBuffer *Minimap::getMinimapMeshBuffer()
440 {
441         scene::SMeshBuffer *buf = new scene::SMeshBuffer();
442         buf->Vertices.set_used(4);
443         buf->Indices.set_used(6);
444         static const video::SColor c(255, 255, 255, 255);
445
446         buf->Vertices[0] = video::S3DVertex(-1, -1, 0, 0, 0, 1, c, 0, 1);
447         buf->Vertices[1] = video::S3DVertex(-1,  1, 0, 0, 0, 1, c, 0, 0);
448         buf->Vertices[2] = video::S3DVertex( 1,  1, 0, 0, 0, 1, c, 1, 0);
449         buf->Vertices[3] = video::S3DVertex( 1, -1, 0, 0, 0, 1, c, 1, 1);
450
451         buf->Indices[0] = 0;
452         buf->Indices[1] = 1;
453         buf->Indices[2] = 2;
454         buf->Indices[3] = 2;
455         buf->Indices[4] = 3;
456         buf->Indices[5] = 0;
457
458         return buf;
459 }
460
461 void Minimap::drawMinimap()
462 {
463         video::ITexture *minimap_texture = getMinimapTexture();
464         if (!minimap_texture)
465                 return;
466
467         updateActiveMarkers();
468         v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();
469         const u32 size = 0.25 * screensize.Y;
470
471         core::rect<s32> oldViewPort = driver->getViewPort();
472         core::matrix4 oldProjMat = driver->getTransform(video::ETS_PROJECTION);
473         core::matrix4 oldViewMat = driver->getTransform(video::ETS_VIEW);
474
475         driver->setViewPort(core::rect<s32>(
476                 screensize.X - size - 10, 10,
477                 screensize.X - 10, size + 10));
478         driver->setTransform(video::ETS_PROJECTION, core::matrix4());
479         driver->setTransform(video::ETS_VIEW, core::matrix4());
480
481         core::matrix4 matrix;
482         matrix.makeIdentity();
483
484         video::SMaterial &material = m_meshbuffer->getMaterial();
485         material.setFlag(video::EMF_TRILINEAR_FILTER, true);
486         material.Lighting = false;
487         material.TextureLayer[0].Texture = minimap_texture;
488         material.TextureLayer[1].Texture = data->heightmap_texture;
489
490         if (m_enable_shaders && !data->is_radar) {
491                 u16 sid = m_shdrsrc->getShader("minimap_shader", 1, 1);
492                 material.MaterialType = m_shdrsrc->getShaderInfo(sid).material;
493         } else {
494                 material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
495         }
496
497         if (data->minimap_shape_round)
498                 matrix.setRotationDegrees(core::vector3df(0, 0, 360 - m_angle));
499
500         // Draw minimap
501         driver->setTransform(video::ETS_WORLD, matrix);
502         driver->setMaterial(material);
503         driver->drawMeshBuffer(m_meshbuffer);
504
505         // Draw overlay
506         video::ITexture *minimap_overlay = data->minimap_shape_round ?
507                 data->minimap_overlay_round : data->minimap_overlay_square;
508         material.TextureLayer[0].Texture = minimap_overlay;
509         material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
510         driver->setMaterial(material);
511         driver->drawMeshBuffer(m_meshbuffer);
512
513         // If round minimap, draw player marker
514         if (!data->minimap_shape_round) {
515                 matrix.setRotationDegrees(core::vector3df(0, 0, m_angle));
516                 material.TextureLayer[0].Texture = data->player_marker;
517
518                 driver->setTransform(video::ETS_WORLD, matrix);
519                 driver->setMaterial(material);
520                 driver->drawMeshBuffer(m_meshbuffer);
521         }
522
523         // Reset transformations
524         driver->setTransform(video::ETS_VIEW, oldViewMat);
525         driver->setTransform(video::ETS_PROJECTION, oldProjMat);
526         driver->setViewPort(oldViewPort);
527
528         // Draw player markers
529         v2s32 s_pos(screensize.X - size - 10, 10);
530         core::dimension2di imgsize(data->object_marker_red->getOriginalSize());
531         core::rect<s32> img_rect(0, 0, imgsize.Width, imgsize.Height);
532         static const video::SColor col(255, 255, 255, 255);
533         static const video::SColor c[4] = {col, col, col, col};
534         f32 sin_angle = sin(m_angle * core::DEGTORAD);
535         f32 cos_angle = cos(m_angle * core::DEGTORAD);
536         s32 marker_size2 =  0.025 * (float)size;
537         for (std::list<v2f>::const_iterator
538                         i = m_active_markers.begin();
539                         i != m_active_markers.end(); ++i) {
540                 v2f posf = *i;
541                 if (data->minimap_shape_round) {
542                         f32 t1 = posf.X * cos_angle - posf.Y * sin_angle;
543                         f32 t2 = posf.X * sin_angle + posf.Y * cos_angle;
544                         posf.X = t1;
545                         posf.Y = t2;
546                 }
547                 posf.X = (posf.X + 0.5) * (float)size;
548                 posf.Y = (posf.Y + 0.5) * (float)size;
549                 core::rect<s32> dest_rect(
550                         s_pos.X + posf.X - marker_size2,
551                         s_pos.Y + posf.Y - marker_size2,
552                         s_pos.X + posf.X + marker_size2,
553                         s_pos.Y + posf.Y + marker_size2);
554                 driver->draw2DImage(data->object_marker_red, dest_rect,
555                         img_rect, &dest_rect, &c[0], true);
556         }
557 }
558
559 void Minimap::updateActiveMarkers()
560 {
561         video::IImage *minimap_mask = data->minimap_shape_round ?
562                 data->minimap_mask_round : data->minimap_mask_square;
563
564         const std::list<Nametag *> &nametags = client->getCamera()->getNametags();
565
566         m_active_markers.clear();
567
568         for (Nametag *nametag : nametags) {
569                 v3s16 pos = floatToInt(nametag->parent_node->getPosition() +
570                         intToFloat(client->getCamera()->getOffset(), BS), BS);
571                 pos -= data->pos - v3s16(data->map_size / 2,
572                                 data->scan_height / 2,
573                                 data->map_size / 2);
574                 if (pos.X < 0 || pos.X > data->map_size ||
575                                 pos.Y < 0 || pos.Y > data->scan_height ||
576                                 pos.Z < 0 || pos.Z > data->map_size) {
577                         continue;
578                 }
579                 pos.X = ((float)pos.X / data->map_size) * MINIMAP_MAX_SX;
580                 pos.Z = ((float)pos.Z / data->map_size) * MINIMAP_MAX_SY;
581                 const video::SColor &mask_col = minimap_mask->getPixel(pos.X, pos.Z);
582                 if (!mask_col.getAlpha()) {
583                         continue;
584                 }
585
586                 m_active_markers.emplace_back(((float)pos.X / (float)MINIMAP_MAX_SX) - 0.5,
587                         (1.0 - (float)pos.Z / (float)MINIMAP_MAX_SY) - 0.5);
588         }
589 }
590
591 ////
592 //// MinimapMapblock
593 ////
594
595 void MinimapMapblock::getMinimapNodes(VoxelManipulator *vmanip, const v3s16 &pos)
596 {
597
598         for (s16 x = 0; x < MAP_BLOCKSIZE; x++)
599         for (s16 z = 0; z < MAP_BLOCKSIZE; z++) {
600                 s16 air_count = 0;
601                 bool surface_found = false;
602                 MinimapPixel *mmpixel = &data[z * MAP_BLOCKSIZE + x];
603
604                 for (s16 y = MAP_BLOCKSIZE -1; y >= 0; y--) {
605                         v3s16 p(x, y, z);
606                         MapNode n = vmanip->getNodeNoEx(pos + p);
607                         if (!surface_found && n.getContent() != CONTENT_AIR) {
608                                 mmpixel->height = y;
609                                 mmpixel->n = n;
610                                 surface_found = true;
611                         } else if (n.getContent() == CONTENT_AIR) {
612                                 air_count++;
613                         }
614                 }
615
616                 if (!surface_found)
617                         mmpixel->n = MapNode(CONTENT_AIR);
618
619                 mmpixel->air_count = air_count;
620         }
621 }