LCOV - code coverage report
Current view: top level - source/gui/ObjectTypes - CMiniMap.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 0 229 0.0 %
Date: 2026-12-03 01:19:39 Functions: 0 16 0.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "CMiniMap.h"
      21             : 
      22             : #include "graphics/Camera.h"
      23             : #include "graphics/Canvas2D.h"
      24             : #include "graphics/GameView.h"
      25             : #include "graphics/MiniMapTexture.h"
      26             : #include "graphics/Terrain.h"
      27             : #include "graphics/TextureManager.h"
      28             : #include "gui/CGUI.h"
      29             : #include "gui/GUIManager.h"
      30             : #include "gui/SGUIMessage.h"
      31             : #include "lib/debug.h"
      32             : #include "lib/path.h"
      33             : #include "lib/timer.h"
      34             : #include "maths/MathUtil.h"
      35             : #include "maths/Matrix3D.h"
      36             : #include "maths/Rect.h"
      37             : #include "maths/Size2D.h"
      38             : #include "maths/Vector3D.h"
      39             : #include "ps/CLogger.h"
      40             : #include "ps/Game.h"
      41             : #include "ps/Profile.h"
      42             : #include "ps/World.h"
      43             : #include "renderer/Renderer.h"
      44             : #include "renderer/SceneRenderer.h"
      45             : #include "renderer/WaterManager.h"
      46             : #include "scriptinterface/Object.h"
      47             : #include "scriptinterface/Conversions.h"
      48             : #include "scriptinterface/Request.h"
      49             : #include "simulation2/components/ICmpRangeManager.h"
      50             : #include "simulation2/system/Component.h"
      51             : #include "simulation2/system/Entity.h"
      52             : 
      53             : #include <SDL_mouse.h>
      54             : #include <algorithm>
      55             : #include <array>
      56             : #include <cmath>
      57             : #include <cstddef>
      58             : #include <fmt/printf.h>
      59             : #include <js/GCVector.h>
      60             : #include <js/RootingAPI.h>
      61             : #include <js/TypeDecls.h>
      62             : #include <js/Value.h>
      63             : #include <js/ValueArray.h>
      64             : #include <memory>
      65             : #include <string>
      66             : #include <tuple>
      67             : #include <vector>
      68             : 
      69             : class CSimulation2;
      70             : 
      71             : namespace
      72             : {
      73             : 
      74             : // Adds segments pieces lying inside the circle to lines.
      75           0 : void CropPointsByCircle(const std::array<CVector3D, 4>& points, const CVector3D& center, const float radius, std::vector<CVector3D>* lines)
      76             : {
      77           0 :     constexpr float EPS = 1e-3f;
      78           0 :     lines->reserve(points.size() * 2);
      79           0 :     for (size_t idx = 0; idx < points.size(); ++idx)
      80             :     {
      81           0 :         const CVector3D& currentPoint = points[idx];
      82           0 :         const CVector3D& nextPoint = points[(idx + 1) % points.size()];
      83           0 :         const CVector3D direction = (nextPoint - currentPoint).Normalized();
      84           0 :         const CVector3D normal(direction.Z, 0.0f, -direction.X);
      85           0 :         const float offset = normal.Dot(currentPoint) - normal.Dot(center);
      86             :         // We need to have lines only inside the circle.
      87           0 :         if (std::abs(offset) + EPS >= radius)
      88           0 :             continue;
      89           0 :         const CVector3D closestPoint = center + normal * offset;
      90           0 :         const float halfChordLength = sqrt(radius * radius - offset * offset);
      91           0 :         const CVector3D intersectionA = closestPoint - direction * halfChordLength;
      92           0 :         const CVector3D intersectionB = closestPoint + direction * halfChordLength;
      93             :         // We have no intersection if the segment is lying outside of the circle.
      94           0 :         if (direction.Dot(currentPoint) + EPS > direction.Dot(intersectionB) ||
      95           0 :             direction.Dot(nextPoint) - EPS < direction.Dot(intersectionA))
      96           0 :             continue;
      97             : 
      98           0 :         lines->emplace_back(
      99           0 :             direction.Dot(currentPoint) > direction.Dot(intersectionA) ? currentPoint : intersectionA);
     100           0 :         lines->emplace_back(
     101           0 :             direction.Dot(nextPoint) < direction.Dot(intersectionB) ? nextPoint : intersectionB);
     102             :     }
     103           0 : }
     104             : 
     105             : } // anonymous namespace
     106             : 
     107             : const CStr CMiniMap::EventNameWorldClick = "WorldClick";
     108             : 
     109           0 : CMiniMap::CMiniMap(CGUI& pGUI) :
     110             :     IGUIObject(pGUI),
     111           0 :     m_MapSize(0), m_MapScale(1.f), m_Mask(this, "mask", false),
     112           0 :     m_FlareTextureCount(this, "flare_texture_count", 0), m_FlareRenderSize(this, "flare_render_size", 0),
     113           0 :     m_FlareInterleave(this, "flare_interleave", false), m_FlareAnimationSpeed(this, "flare_animation_speed", 0.0f),
     114           0 :     m_FlareLifetimeSeconds(this, "flare_lifetime_seconds", 0.0f),
     115           0 :     m_FlareStartFadeSeconds(this, "flare_start_fade_seconds", 0.0f),
     116           0 :     m_FlareStopFadeSeconds(this, "flare_stop_fade_seconds", 0.0f)
     117             : {
     118           0 :     m_Clicking = false;
     119           0 :     m_MouseHovering = false;
     120           0 : }
     121             : 
     122           0 : void CMiniMap::Tick()
     123             : {
     124           0 :     if (!g_Game || !g_Game->GetView() || !g_Game->IsGameStarted())
     125             :         return;
     126             : 
     127           0 :     g_Game->GetView()->GetMiniMapTexture().RequestRendering();
     128             : }
     129             : 
     130           0 : void CMiniMap::HandleMessage(SGUIMessage& Message)
     131             : {
     132           0 :     IGUIObject::HandleMessage(Message);
     133           0 :     switch (Message.type)
     134             :     {
     135           0 :     case GUIM_LOAD:
     136           0 :         RecreateFlareTextures();
     137           0 :         break;
     138           0 :     case GUIM_SETTINGS_UPDATED:
     139           0 :         if (Message.value == "flare_texture_count")
     140           0 :             RecreateFlareTextures();
     141             :         break;
     142           0 :     case GUIM_MOUSE_PRESS_LEFT:
     143           0 :         if (m_MouseHovering)
     144             :         {
     145           0 :             if (!CMiniMap::FireWorldClickEvent(SDL_BUTTON_LEFT, 1))
     146             :             {
     147           0 :                 SetCameraPositionFromMousePosition();
     148           0 :                 m_Clicking = true;
     149             :             }
     150             :         }
     151             :         break;
     152           0 :     case GUIM_MOUSE_RELEASE_LEFT:
     153           0 :         if (m_MouseHovering && m_Clicking)
     154           0 :             SetCameraPositionFromMousePosition();
     155           0 :         m_Clicking = false;
     156           0 :         break;
     157           0 :     case GUIM_MOUSE_DBLCLICK_LEFT:
     158           0 :         if (m_MouseHovering && m_Clicking)
     159           0 :             SetCameraPositionFromMousePosition();
     160           0 :         m_Clicking = false;
     161           0 :         break;
     162           0 :     case GUIM_MOUSE_ENTER:
     163           0 :         m_MouseHovering = true;
     164           0 :         break;
     165           0 :     case GUIM_MOUSE_LEAVE:
     166           0 :         m_Clicking = false;
     167           0 :         m_MouseHovering = false;
     168           0 :         break;
     169           0 :     case GUIM_MOUSE_RELEASE_RIGHT:
     170           0 :         CMiniMap::FireWorldClickEvent(SDL_BUTTON_RIGHT, 1);
     171           0 :         break;
     172           0 :     case GUIM_MOUSE_DBLCLICK_RIGHT:
     173           0 :         CMiniMap::FireWorldClickEvent(SDL_BUTTON_RIGHT, 2);
     174           0 :         break;
     175           0 :     case GUIM_MOUSE_MOTION:
     176           0 :         if (m_MouseHovering && m_Clicking)
     177           0 :             SetCameraPositionFromMousePosition();
     178             :         break;
     179           0 :     case GUIM_MOUSE_WHEEL_DOWN:
     180           0 :     case GUIM_MOUSE_WHEEL_UP:
     181           0 :         Message.Skip();
     182             :         break;
     183             : 
     184             :     default:
     185             :         break;
     186             :     }
     187           0 : }
     188             : 
     189           0 : void CMiniMap::RecreateFlareTextures()
     190             : {
     191             :     // Catch invalid values.
     192           0 :     if (m_FlareTextureCount > 99)
     193             :     {
     194           0 :         LOGERROR("Invalid value for flare texture count. Valid range is 0-99.");
     195           0 :         return;
     196             :     }
     197           0 :     const CStr textureNumberingFormat = "art/textures/animated/minimap-flare/frame%02u.png";
     198           0 :     m_FlareTextures.clear();
     199           0 :     m_FlareTextures.reserve(m_FlareTextureCount);
     200           0 :     for (std::uint32_t i = 0; i < m_FlareTextureCount; ++i)
     201             :     {
     202           0 :         CTextureProperties textureProps(fmt::sprintf(textureNumberingFormat, i).c_str());
     203           0 :         textureProps.SetIgnoreQuality(true);
     204           0 :         m_FlareTextures.emplace_back(g_Renderer.GetTextureManager().CreateTexture(textureProps));
     205           0 :     }
     206           0 : }
     207             : 
     208           0 : bool CMiniMap::IsMouseOver() const
     209             : {
     210           0 :     const CVector2D& mousePos = m_pGUI.GetMousePos();
     211             :     // Take the magnitude of the difference of the mouse position and minimap center.
     212           0 :     const float distanceFromCenter = (mousePos - GetActualSize().CenterPoint()).Length();
     213             :     // If the distance is less then the radius of the minimap (half the width) the mouse is over the minimap.
     214           0 :     return distanceFromCenter < GetActualSize().GetWidth() / 2.0;
     215             : }
     216             : 
     217           0 : void CMiniMap::GetMouseWorldCoordinates(float& x, float& z) const
     218             : {
     219             :     // Determine X and Z according to proportion of mouse position and minimap.
     220           0 :     const CVector2D& mousePos = m_pGUI.GetMousePos();
     221             : 
     222           0 :     float px = (mousePos.X - GetActualSize().left) / GetActualSize().GetWidth();
     223           0 :     float py = (GetActualSize().bottom - mousePos.Y) / GetActualSize().GetHeight();
     224             : 
     225           0 :     float angle = GetAngle();
     226             : 
     227             :     // Scale world coordinates for shrunken square map
     228           0 :     x = TERRAIN_TILE_SIZE * m_MapSize * (m_MapScale * (cos(angle)*(px-0.5) - sin(angle)*(py-0.5)) + 0.5);
     229           0 :     z = TERRAIN_TILE_SIZE * m_MapSize * (m_MapScale * (cos(angle)*(py-0.5) + sin(angle)*(px-0.5)) + 0.5);
     230           0 : }
     231             : 
     232           0 : void CMiniMap::SetCameraPositionFromMousePosition()
     233             : {
     234           0 :     const CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
     235             : 
     236           0 :     CVector3D target;
     237           0 :     GetMouseWorldCoordinates(target.X, target.Z);
     238           0 :     target.Y = terrain.GetExactGroundLevel(target.X, target.Z);
     239           0 :     g_Game->GetView()->MoveCameraTarget(target);
     240           0 : }
     241             : 
     242           0 : float CMiniMap::GetAngle() const
     243             : {
     244           0 :     CVector3D cameraIn = g_Game->GetView()->GetCamera().GetOrientation().GetIn();
     245           0 :     return -atan2(cameraIn.X, cameraIn.Z);
     246             : }
     247             : 
     248           0 : CVector2D CMiniMap::WorldSpaceToMiniMapSpace(const CVector3D& worldPosition) const
     249             : {
     250             :     // Coordinates with 0,0 in the middle of the minimap and +-0.5 as max.
     251           0 :     const float invTileMapSize = 1.0f / static_cast<float>(TERRAIN_TILE_SIZE * m_MapSize);
     252           0 :     const float relativeX = (worldPosition.X * invTileMapSize - 0.5) / m_MapScale;
     253           0 :     const float relativeY = (worldPosition.Z * invTileMapSize - 0.5) / m_MapScale;
     254             : 
     255             :     // Rotate coordinates.
     256           0 :     const float angle = GetAngle();
     257           0 :     const float rotatedX = cos(angle) * relativeX + sin(angle) * relativeY;
     258           0 :     const float rotatedY = -sin(angle) * relativeX + cos(angle) * relativeY;
     259             : 
     260             :     // Calculate coordinates in GUI space.
     261           0 :     return CVector2D(
     262           0 :         GetActualSize().left + (0.5f + rotatedX) * GetActualSize().GetWidth(),
     263           0 :         GetActualSize().bottom - (0.5f + rotatedY) * GetActualSize().GetHeight());
     264             : }
     265             : 
     266           0 : bool CMiniMap::FireWorldClickEvent(int button, int /*clicks*/)
     267             : {
     268           0 :     Script::Request rq(g_GUI->GetActiveGUI()->GetScriptInterface());
     269             : 
     270           0 :     float x, z;
     271           0 :     GetMouseWorldCoordinates(x, z);
     272             : 
     273           0 :     JS::RootedValue coords(rq.cx);
     274           0 :     Script::CreateObject(rq, &coords, "x", x, "z", z);
     275             : 
     276           0 :     JS::RootedValue buttonJs(rq.cx);
     277           0 :     Script::ToJSVal(rq, &buttonJs, button);
     278             : 
     279           0 :     JS::RootedValueVector paramData(rq.cx);
     280           0 :     std::ignore = paramData.append(coords);
     281           0 :     std::ignore = paramData.append(buttonJs);
     282             : 
     283           0 :     return ScriptEvent(EventNameWorldClick, paramData);
     284           0 : }
     285             : 
     286             : // This sets up and draws the rectangle on the minimap
     287             : //  which represents the view of the camera in the world.
     288           0 : void CMiniMap::DrawViewRect(CCanvas2D& canvas) const
     289             : {
     290             :     // Compute the camera frustum intersected with a fixed-height plane.
     291             :     // Use the water height as a fixed base height, which should be the lowest we can go
     292           0 :     const float sampleHeight = g_Renderer.GetSceneRenderer().GetWaterManager().m_WaterHeight;
     293             : 
     294           0 :     const CCamera& camera{g_Game->GetView()->GetCamera()};
     295           0 :     const std::array<CVector3D, 4> hitPoints = {
     296           0 :         camera.GetWorldCoordinates(0, g_Renderer.GetHeight(), sampleHeight),
     297           0 :         camera.GetWorldCoordinates(g_Renderer.GetWidth(), g_Renderer.GetHeight(), sampleHeight),
     298           0 :         camera.GetWorldCoordinates(g_Renderer.GetWidth(), 0, sampleHeight),
     299           0 :         camera.GetWorldCoordinates(0, 0, sampleHeight)
     300             :     };
     301             : 
     302           0 :     std::vector<CVector3D> worldSpaceLines;
     303             :     // We need to prevent drawing view bounds out of the map.
     304           0 :     const float halfMapSize = static_cast<float>((m_MapSize - 1) * TERRAIN_TILE_SIZE) * 0.5f;
     305           0 :     CropPointsByCircle(hitPoints, CVector3D(halfMapSize, 0.0f, halfMapSize), halfMapSize * m_MapScale, &worldSpaceLines);
     306           0 :     if (worldSpaceLines.empty())
     307           0 :         return;
     308             : 
     309           0 :     for (size_t index = 0; index < worldSpaceLines.size() && index + 1 < worldSpaceLines.size(); index += 2)
     310             :     {
     311           0 :         const CVector2D from = WorldSpaceToMiniMapSpace(worldSpaceLines[index]);
     312           0 :         const CVector2D to = WorldSpaceToMiniMapSpace(worldSpaceLines[index + 1]);
     313           0 :         canvas.DrawLine({from, to}, 2.0f, CColor(1.0f, 0.3f, 0.3f, 1.0f));
     314             :     }
     315           0 : }
     316             : 
     317           0 : void CMiniMap::DrawFlare(CCanvas2D& canvas, const MapFlare& flare, double currentTime) const
     318             : {
     319           0 :     if (m_FlareTextures.empty())
     320           0 :         return;
     321             : 
     322           0 :     const CVector2D flareCenter = WorldSpaceToMiniMapSpace(CVector3D(flare.pos.X, 0.0f, flare.pos.Y));
     323             : 
     324           0 :     const CRect destination(
     325           0 :         flareCenter.X - m_FlareRenderSize, flareCenter.Y - m_FlareRenderSize,
     326           0 :         flareCenter.X + m_FlareRenderSize, flareCenter.Y + m_FlareRenderSize);
     327             : 
     328           0 :     const double deltaTime = currentTime - flare.time;
     329           0 :     const double remainingTime = m_FlareLifetimeSeconds - deltaTime;
     330           0 :     const std::uint32_t flooredStep = floor(deltaTime * m_FlareAnimationSpeed);
     331             : 
     332           0 :     const float startFadeAlpha = m_FlareStartFadeSeconds > 0.0f ? deltaTime / m_FlareStartFadeSeconds : 1.0f;
     333           0 :     const float stopFadeAlpha = m_FlareStopFadeSeconds > 0.0f ? remainingTime / m_FlareStopFadeSeconds : 1.0f;
     334           0 :     const float alpha = Clamp(std::min(
     335           0 :         SmoothStep(0.0f, 1.0f, startFadeAlpha), SmoothStep(0.0f, 1.0f, stopFadeAlpha)),
     336             :         0.0f, 1.0f);
     337             : 
     338           0 :     DrawFlareFrame(canvas, flooredStep % m_FlareTextures.size(), destination, flare.color, alpha);
     339             : 
     340             :     // Draw a second circle if the first has reached half of the animation.
     341           0 :     if (m_FlareInterleave && flooredStep >= m_FlareTextures.size() / 2)
     342             :     {
     343           0 :         DrawFlareFrame(canvas, (flooredStep - m_FlareTextures.size() / 2) % m_FlareTextures.size(),
     344             :             destination, flare.color, alpha);
     345             :     }
     346             : }
     347             : 
     348           0 : void CMiniMap::DrawFlareFrame(CCanvas2D& canvas, const std::uint32_t frameIndex,
     349             :     const CRect& destination, const CColor& color, float alpha) const
     350             : {
     351             :     // TODO: Only draw inside the minimap circle.
     352           0 :     CTexturePtr texture = m_FlareTextures[frameIndex % m_FlareTextures.size()];
     353           0 :     CColor finalColor = color;
     354           0 :     finalColor.a *= alpha;
     355           0 :     canvas.DrawTexture(texture, destination,
     356           0 :         CRect(0, 0, texture->GetWidth(), texture->GetHeight()), finalColor,
     357           0 :         CColor(0.0f, 0.0f, 0.0f, 0.0f), 0.0f);
     358           0 : }
     359             : 
     360           0 : void CMiniMap::Draw(CCanvas2D& canvas)
     361             : {
     362           0 :     PROFILE3("render minimap");
     363             : 
     364             :     // The terrain isn't actually initialized until the map is loaded, which
     365             :     // happens when the game is started, so abort until then.
     366           0 :     if (!g_Game || !g_Game->IsGameStarted())
     367           0 :         return;
     368             : 
     369           0 :     if (!m_Mask)
     370           0 :         canvas.DrawRect(GetActualSize(), CColor(0.0f, 0.0f, 0.0f, 1.0f));
     371             : 
     372           0 :     CSimulation2* sim = g_Game->GetSimulation2();
     373           0 :     CmpPtr<ICmpRangeManager> cmpRangeManager(*sim, SYSTEM_ENTITY);
     374           0 :     ENSURE(cmpRangeManager);
     375             : 
     376             :     // Set our globals in case they hadn't been set before
     377           0 :     const CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
     378           0 :     m_MapSize = terrain.GetVerticesPerSide();
     379           0 :     m_MapScale = (cmpRangeManager->GetLosCircular() ? 1.f : 1.414f);
     380             : 
     381             :     // Draw the main textured quad
     382           0 :     CMiniMapTexture& miniMapTexture = g_Game->GetView()->GetMiniMapTexture();
     383           0 :     if (miniMapTexture.GetTexture())
     384             :     {
     385           0 :         const CVector2D center = GetActualSize().CenterPoint();
     386           0 :         const CRect source(
     387             :             0,
     388           0 :             miniMapTexture.IsFlipped() ? 0 : miniMapTexture.GetTexture()->GetHeight(),
     389           0 :             miniMapTexture.GetTexture()->GetWidth(),
     390           0 :             miniMapTexture.IsFlipped() ? miniMapTexture.GetTexture()->GetHeight() : 0);
     391           0 :         const CSize2D size(GetActualSize().GetSize() / m_MapScale);
     392           0 :         const CRect destination(center - size / 2.0f, size);
     393           0 :         canvas.DrawRotatedTexture(
     394             :             miniMapTexture.GetTexture(), destination, source,
     395           0 :             CColor(1.0f, 1.0f, 1.0f, 1.0f), CColor(0.0f, 0.0f, 0.0f, 0.0f), 0.0f,
     396             :             center, GetAngle());
     397             :     }
     398             : 
     399           0 :     for (const CMiniMapTexture::Icon& icon : miniMapTexture.GetIcons())
     400             :     {
     401           0 :         const CVector2D center = WorldSpaceToMiniMapSpace(
     402           0 :             CVector3D(icon.worldPosition.X, 0.0f, icon.worldPosition.Y));
     403           0 :         const CRect destination(
     404             :             center.X - icon.halfSize, center.Y - icon.halfSize,
     405           0 :             center.X + icon.halfSize, center.Y + icon.halfSize);
     406           0 :         const CRect source(0, 0, icon.texture->GetWidth(), icon.texture->GetHeight());
     407           0 :         canvas.DrawTexture(
     408           0 :             icon.texture, destination, source,
     409           0 :             icon.color, CColor(0.0f, 0.0f, 0.0f, 0.0f), 0.0f);
     410             :     }
     411             : 
     412           0 :     PROFILE_START("minimap flares");
     413             : 
     414           0 :     DrawViewRect(canvas);
     415             : 
     416           0 :     const double currentTime = timer_Time();
     417           0 :     while (!m_MapFlares.empty() && m_FlareLifetimeSeconds + m_MapFlares.front().time < currentTime)
     418           0 :         m_MapFlares.pop_front();
     419             : 
     420           0 :     for (const MapFlare& flare : m_MapFlares)
     421           0 :         DrawFlare(canvas, flare, currentTime);
     422             : 
     423           0 :     PROFILE_END("minimap flares");
     424           0 : }
     425             : 
     426           0 : bool CMiniMap::Flare(const CVector2D& pos, const CStr& colorStr)
     427             : {
     428           0 :     CColor color;
     429           0 :     if (!color.ParseString(colorStr))
     430             :     {
     431           0 :         LOGERROR("CMiniMap::Flare: Couldn't parse color string");
     432           0 :         return false;
     433             :     }
     434           0 :     m_MapFlares.push_back({ pos, color, timer_Time() });
     435           0 :     return true;
     436             : }

Generated by: LCOV version 1.16