diff --git a/.github/plans/Vector-Rendering-Performance-Improvement.md b/.github/plans/Vector-Rendering-Performance-Improvement.md index 041f53a..bc9ef5b 100644 --- a/.github/plans/Vector-Rendering-Performance-Improvement.md +++ b/.github/plans/Vector-Rendering-Performance-Improvement.md @@ -13,7 +13,11 @@ Copilot: Update this checklist as each phase is implemented. Only mark a phase c - Normal scene construction now preserves source rings and bounds without triangulating polygons; fill meshes remain available through explicit preparation. - GDI fills directly from source rings, and OpenGL can draw mesh-free polygon outlines while fill requests retain the existing mesh requirement and GDI fallback. - Limitation: OpenGL fill meshes are prepared explicitly rather than generated lazily; lazy triangulation and cache reuse remain Phase 3 and Phase 4 work. -- [ ] **Phase 3 – Implement lazy polygon triangulation** (PR 3) +- [x] **Phase 3 – Implement lazy polygon triangulation** (PR 3) + - OpenGL fill draws now generate missing polygon meshes on demand and reuse them for later draws of the same immutable scene, including temporary scaled draws. + - Explicitly prepared meshes remain preferred; outline and GDI paths continue to use source rings without requiring fill meshes. + - Triangulation failures, including exceptions from GDAL logging callbacks, return to the coordinator for GDI fallback without preventing outline rendering. + - Limitation: triangulation remains synchronous, and broader cache ownership, memory limits, and invalidation rules remain Phase 4 work. - [ ] **Phase 4 – Add intelligent caching and invalidation** (PR 4) - [ ] **Phase 5 – Introduce viewport-aware geometry processing** (PR 5) - [ ] **Phase 6 – Optimize OpenGL rendering and data transfer** (PR 6) @@ -524,6 +528,7 @@ Each PR must: 5. Avoid unrelated refactoring. 6. Be independently reviewable. 7. Include a clear description of limitations and remaining work. +8. The PR title should reflect the title of the plan combined with the title of the phase. Do not wait for all phases to be completed before creating PRs. Each phase should result in a separate PR against the `development` branch, following the repository's existing contribution workflow. diff --git a/README.md b/README.md index 12f77a8..5fc0b0e 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,8 @@ release the loaded datasets before switching or refreshing them. Core stores polygon coordinates in flat buffers and caches prepared geometry per map layer. Visibility changes reuse that geometry without rereading -datasets or triangulating polygons again. +datasets or triangulating polygons again. OpenGL generates missing fill +meshes on the first fill draw and reuses them for that render scene. ## Build and test diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 14133c7..03c0929 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -331,10 +331,12 @@ rings and has no mesh. `ViewTransform` captures the `Viewport` once per frame so both backends transform every vertex of every layer with the same arithmetic as `Viewport::MapToScreen`; GDI draws a screen position in the pixel that contains it (`ToPixel`). One backend draws the whole frame. -The coordinator tries the OpenGL backend when every polygon of every layer -has a triangulated fill mesh for a fill draw. OpenGL outline mode draws the -source rings without requiring fill meshes. GDI checks each layer before -drawing it; a layer with non-finite or out-of-range device coordinates is +For an OpenGL fill draw, the backend accepts a mesh-free source scene and +triangulates each polygon that has no prepared fill mesh. +The generated meshes remain associated with that immutable scene and are +reused by later draws; they do not mutate the Core scene. OpenGL outline +mode draws the source rings without requiring fill meshes. GDI checks each +layer before drawing it; a layer with non-finite or out-of-range device coordinates is skipped and reported (`GetFailedLayers`, `RenderingStatus`) while the other layers are still drawn. OpenGL uses a context created on a hidden, never-presented window, draws with @@ -344,16 +346,18 @@ buffer before copying them to the host device context. BGRA stores blue, green, red, and alpha bytes in that order. The screen renderer retains its staging allocation and GPU framebuffer. Alternate-size draws use a temporary OpenGL renderer that releases both after -the draw and leaves the screen resources unchanged. +the draw and shares the screen renderer's lazy fill meshes, leaving the screen +resources unchanged. A separate vertex buffer is reused across polygons within each layer. This avoids a fresh allocation for every polygon's transformed triangle vertices. Rendering into a framebuffer object avoids undefined pixels from window pixel-ownership rules. Presentation still copies pixels through GDI. Interior rings and concave boundaries draw identically in both backends -because both consume the same scene. A fill request without a usable mesh, -missing framebuffer-object support, initialization failures, and drawing -failures use the GDI backend. GDI fills and outlines the original rings, so -a self-intersecting ring that GEOS cannot triangulate can still be displayed. +because both consume the same scene. A failed lazy triangulation, an unusable +explicitly prepared mesh, missing framebuffer-object support, initialization +failures, and drawing failures use the GDI backend. GDI fills and outlines +the original rings, so a self-intersecting ring that GEOS cannot triangulate +can still be displayed. The GDI backend draws the original rings of the whole supported polygon scene, including its interior rings and concave boundaries. Both backends draw source coordinates without reprojection, and scene preparation currently supports Polygon, MultiPolygon, CurvePolygon, @@ -487,14 +491,14 @@ and `Ring` types remain available for caller-created triangulation input. There is no tiling, paging, or clipping to the visible extent. GDI skips a layer whose device coordinates exceed its range. It clips drawing to the requested target rectangle and the host's existing clip region, then restores -the device context. Fill triangulation runs only when scene preparation -explicitly requests it; view changes (resize, zoom, pan) and redraws reuse -the retained meshes. The opt-in +the device context. Fill triangulation runs when scene preparation explicitly +requests it or when OpenGL first needs a missing mesh. View changes (resize, +zoom, pan) and redraws reuse the retained meshes. The opt-in rendering baseline (see [TESTING.md](TESTING.md#rendering-performance-baseline)) tracks scene preparation, mesh storage, and backend frame costs on both a convex grid and a complex mix of concave, holed multipart, and many-vertex -polygons. OpenGL fills every polygon from its retained triangle mesh and -copies each frame through CPU memory. Its reusable CPU +polygons. OpenGL fills every polygon from a supplied or lazily generated +triangle mesh and copies each frame through CPU memory. Its reusable CPU staging buffer is limited to 64 MiB per frame; target dimensions are also limited by the detected framebuffer and viewport capabilities. GDI is the supported Windows CPU fallback; Core has no independent platform-neutral renderer. diff --git a/docs/TESTING.md b/docs/TESTING.md index f21b862..595e164 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -208,7 +208,9 @@ and configuration C for OpenGL outline-only rendering). `MeasuresCoreSceneAndBackendCosts` explicitly requests fill-mesh preparation (configurations B and D). Successful backends report first and steady frame times, plus pan and zoom frames, for a 1280x720 off-screen target. Normal scene -creation does not perform triangulation. +creation does not perform triangulation. OpenGL fill rendering lazily +triangulates source-only scenes on their first fill draw and reuses those +backend-owned meshes on later draws. Performance diagnostics are disabled by default and aggregate process-wide timings with `std::chrono::steady_clock`. The collector records dataset diff --git a/src/MapWinGIS.ActiveX/MapWinGISControl.cpp b/src/MapWinGIS.ActiveX/MapWinGISControl.cpp index 945a55e..37409c8 100644 --- a/src/MapWinGIS.ActiveX/MapWinGISControl.cpp +++ b/src/MapWinGIS.ActiveX/MapWinGISControl.cpp @@ -1117,6 +1117,7 @@ STDMETHODIMP CMapWinGISControl::ClearLayers() InvalidateLayerCache(); FireViewChange(); } + _renderer.InvalidateSceneCache(); return S_OK; } diff --git a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp index 911e1b6..ce4a322 100644 --- a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp +++ b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp @@ -6,11 +6,12 @@ * * Owns one reusable OpenGL context and draws into a framebuffer object so * pixel readback is not subject to window pixel-ownership rules. Polygon - * fills use indexed triangle meshes prepared explicitly by Core; outlines - * follow the original rings and do not require meshes. Each polygon is drawn - * completely before the next one, matching the GDI backend's painter order. - * Fill scenes with polygons that lack a usable mesh, or systems without - * framebuffer objects, return S_FALSE so the coordinator can use GDI. + * fills use indexed triangle meshes supplied by Core or generated lazily and + * cached for repeated draws of the same scene. Outlines follow the original + * rings and do not require meshes. Each polygon is drawn completely before + * the next one, matching the GDI backend's painter order. Fill scenes whose + * mesh preparation fails, or systems without framebuffer objects, return + * S_FALSE so the coordinator can use GDI. */ #include "OpenGlVectorLayerRenderer.h" @@ -29,7 +30,9 @@ #pragma comment(lib, "opengl32.lib") #include "ViewTransform.h" +#include "mapwingis/core/Error.h" #include "mapwingis/diagnostics/PerformanceDiagnostics.h" +#include "mapwingis/rendering/PolygonTriangulation.h" namespace mwg::activex { @@ -184,13 +187,12 @@ namespace mwg::activex } const rendering::VectorRenderScene& vectorScene = *layer.scene; if (renderMode == VectorRenderMode::Fill && - vectorScene.fillMeshes.size() != vectorScene.polygons.size()) - { - return false; - } - - if (renderMode == VectorRenderMode::Fill) + !vectorScene.fillMeshes.empty()) { + if (vectorScene.fillMeshes.size() != vectorScene.polygons.size()) + { + return false; + } for (std::size_t index = 0; index < vectorScene.polygons.size(); ++index) @@ -294,6 +296,7 @@ namespace mwg::activex /// the same painter order as the GDI backend. [[nodiscard]] HRESULT DrawLayer( const rendering::VectorRenderScene& scene, + const std::span> fillMeshes, const ViewTransform& transform, const VectorRenderMode renderMode) noexcept { @@ -310,7 +313,7 @@ namespace mwg::activex { glColor3ub(61, 122, 169); const HRESULT fillResult = - DrawPolygonFill(*scene.fillMeshes[index], transform, deviceVertices); + DrawPolygonFill(*fillMeshes[index], transform, deviceVertices); if (FAILED(fillResult)) { glDisableClientState(GL_VERTEX_ARRAY); @@ -341,6 +344,19 @@ namespace mwg::activex OpenGlVectorLayerRenderer::OpenGlVectorLayerRenderer() noexcept = default; + struct OpenGlVectorLayerRenderer::FillMeshCache final + { + struct Layer final + { + std::weak_ptr scene; + std::vector> generatedMeshes; + }; + + std::vector layers; + bool failed = false; + std::uint64_t generation = 0; + }; + bool OpenGlVectorLayerRenderer::IsSceneSupported( const rendering::MapRenderScene& scene, const VectorRenderMode renderMode) noexcept @@ -678,6 +694,178 @@ namespace mwg::activex return true; } + HRESULT OpenGlVectorLayerRenderer::PrepareFillMeshes( + const rendering::MapRenderScene& scene) noexcept + { + if (_fillMeshCache != nullptr && + _fillMeshCache->layers.size() == scene.layers.size()) + { + bool matches = true; + for (std::size_t index = 0; index < scene.layers.size(); ++index) + { + if (_fillMeshCache->layers[index].scene.lock() != + scene.layers[index].scene) + { + matches = false; + break; + } + } + if (matches) + { + if (_fillMeshCache->failed) + { + _lastFailureReason = + L"The OpenGL backend could not triangulate a polygon for fill " + L"rendering; this frame was rendered with GDI."; + return S_FALSE; + } + return S_OK; + } + } + + try + { + if (_fillMeshCache == nullptr) + { + _fillMeshCache = std::make_shared(); + } + FillMeshCache prepared; + prepared.layers.reserve(scene.layers.size()); + for (const rendering::LayerRenderScene& layer : scene.layers) + { + FillMeshCache::Layer cachedLayer; + cachedLayer.scene = layer.scene; + if (!prepared.failed && + layer.scene != nullptr && + layer.scene->fillMeshes.empty()) + { + cachedLayer.generatedMeshes.reserve(layer.scene->polygons.size()); + for (std::size_t index = 0; + index < layer.scene->polygons.size(); + ++index) + { + try + { + rendering::TriangleMesh mesh = + rendering::TriangulatePolygon(layer.scene->polygons[index]); + if (!IsMeshUsable(mesh)) + { + prepared.failed = true; + cachedLayer.generatedMeshes.resize( + layer.scene->polygons.size()); + break; + } + cachedLayer.generatedMeshes.push_back(std::move(mesh)); + } + catch (const mwg::CoreError&) + { + prepared.failed = true; + cachedLayer.generatedMeshes.resize( + layer.scene->polygons.size()); + break; + } + catch (const std::bad_alloc&) + { + throw; + } + catch (const std::length_error&) + { + throw; + } + catch (const std::exception&) + { + prepared.failed = true; + cachedLayer.generatedMeshes.resize( + layer.scene->polygons.size()); + break; + } + catch (...) + { + prepared.failed = true; + cachedLayer.generatedMeshes.resize( + layer.scene->polygons.size()); + break; + } + } + } + prepared.layers.push_back(std::move(cachedLayer)); + } + if (prepared.failed) + { + for (FillMeshCache::Layer& layer : prepared.layers) + { + layer.generatedMeshes.clear(); + } + } + _fillMeshCache->layers = std::move(prepared.layers); + _fillMeshCache->failed = prepared.failed; + } + catch (const std::bad_alloc&) + { + _lastFailureReason = + L"The OpenGL backend could not allocate lazily generated fill meshes."; + return S_FALSE; + } + catch (const std::length_error&) + { + _lastFailureReason = + L"The OpenGL backend could not represent its lazily generated fill meshes."; + return S_FALSE; + } + + if (_fillMeshCache->failed) + { + _lastFailureReason = + L"The OpenGL backend could not triangulate a polygon for fill " + L"rendering; this frame was rendered with GDI."; + return S_FALSE; + } + return S_OK; + } + + std::span> + OpenGlVectorLayerRenderer::GetFillMeshes( + const std::size_t layerIndex, + const rendering::VectorRenderScene& scene) const noexcept + { + const FillMeshCache::Layer& cached = _fillMeshCache->layers[layerIndex]; + if (!scene.fillMeshes.empty()) + { + return scene.fillMeshes; + } + return cached.generatedMeshes; + } + + void OpenGlVectorLayerRenderer::ClearFillMeshCache() noexcept + { + if (_fillMeshCache == nullptr) + { + return; + } + _fillMeshCache->layers.clear(); + _fillMeshCache->failed = false; + ++_fillMeshCache->generation; + } + + std::size_t OpenGlVectorLayerRenderer::FillMeshCacheSize() const noexcept + { + return _fillMeshCache == nullptr ? 0U : _fillMeshCache->layers.size(); + } + + std::size_t OpenGlVectorLayerRenderer::CachedGeneratedMeshStorage() const noexcept + { + if (_fillMeshCache == nullptr) + { + return 0U; + } + std::size_t storage = 0; + for (const FillMeshCache::Layer& layer : _fillMeshCache->layers) + { + storage += layer.generatedMeshes.size(); + } + return storage; + } + HRESULT OpenGlVectorLayerRenderer::RenderScene( const rendering::MapRenderScene& scene, const Viewport& viewport, @@ -737,11 +925,20 @@ namespace mwg::activex 1.0F); glClear(GL_COLOR_BUFFER_BIT); - for (const rendering::LayerRenderScene& layer : scene.layers) + for (std::size_t index = 0; index < scene.layers.size(); ++index) { // IsSupported above rejected null layer scenes. + const rendering::LayerRenderScene& layer = scene.layers[index]; + const std::span> fillMeshes = + renderMode == VectorRenderMode::Fill + ? GetFillMeshes(index, *layer.scene) + : std::span>(); const HRESULT layerResult = - DrawLayer(*layer.scene, *transform, renderMode); + DrawLayer( + *layer.scene, + fillMeshes, + *transform, + renderMode); if (FAILED(layerResult)) { _lastFailureReason = L"OpenGL could not allocate its vertex buffers."; @@ -858,6 +1055,20 @@ namespace mwg::activex // unchanged. The temporary renderer releases all scaled resources, // while retry bookkeeping survives between temporary draws. OpenGlVectorLayerRenderer temporaryRenderer; + if (_fillMeshCache == nullptr) + { + try + { + _fillMeshCache = std::make_shared(); + } + catch (const std::bad_alloc&) + { + _lastFailureReason = + L"The OpenGL backend could not allocate its fill-mesh cache."; + return S_FALSE; + } + } + temporaryRenderer._fillMeshCache = _fillMeshCache; temporaryRenderer._initializationFailed = _initializationFailed; temporaryRenderer._initializationFailureReason = _initializationFailureReason; temporaryRenderer._retryTargetWidth = _retryTargetWidth; @@ -880,11 +1091,27 @@ namespace mwg::activex temporaryRenderer._initializationRetryDrawsRemaining; return result; } + rendering::MapRenderScene stableScene; + try + { + stableScene = scene; + } + catch (const std::bad_alloc&) + { + _lastFailureReason = L"The OpenGL backend could not snapshot the render scene."; + return E_OUTOFMEMORY; + } + catch (const std::length_error&) + { + _lastFailureReason = + L"The OpenGL backend could not represent its render-scene snapshot."; + return S_FALSE; + } const diagnostics::PerformanceScope frameScope( diagnostics::PerformanceOperation::FrameRender); _lastFailureReason = L"OpenGL did not render this frame."; const TargetValidation validation = - ValidateTarget(deviceContext, bounds, scene, viewport, renderMode); + ValidateTarget(deviceContext, bounds, stableScene, viewport, renderMode); if (!validation.target.has_value()) { return validation.result; @@ -947,13 +1174,38 @@ namespace mwg::activex return S_FALSE; } + const std::uint64_t cacheGeneration = + _fillMeshCache == nullptr ? 0U : _fillMeshCache->generation; + if (renderMode == VectorRenderMode::Fill && + PrepareFillMeshes(stableScene) != S_OK) + { + if (_fillMeshCache != nullptr && + _fillMeshCache->generation != cacheGeneration) + { + ClearFillMeshCache(); + } + return S_FALSE; + } + const HRESULT renderResult = - RenderScene(scene, viewport, target, renderMode); + RenderScene(stableScene, viewport, target, renderMode); if (FAILED(renderResult) || renderResult == S_FALSE) { + if (_fillMeshCache != nullptr && + _fillMeshCache->generation != cacheGeneration) + { + ClearFillMeshCache(); + } return renderResult; } - return CopyToDeviceContext(deviceContext, bounds, target); + const HRESULT copyResult = + CopyToDeviceContext(deviceContext, bounds, target); + if (_fillMeshCache != nullptr && + _fillMeshCache->generation != cacheGeneration) + { + ClearFillMeshCache(); + } + return copyResult; } } diff --git a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h index f737eee..279d752 100644 --- a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h +++ b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -27,6 +28,7 @@ namespace mwg::activex class OpenGlVectorLayerRendererTestAccess; class MapWinGISControlTestAccess; } + class VectorLayerRenderer; class OpenGlVectorLayerRenderer final : public IVectorRenderBackend { @@ -54,14 +56,16 @@ namespace mwg::activex /** * @brief Draws polygon fills or outlines through OpenGL. * - * Fill mode uses a Core-prepared triangle mesh for each polygon and - * draws boundaries from the original rings. Outline mode draws the - * original rings without requiring fill meshes. Polygons retain the - * GDI backend's painter order within a layer. + * Fill mode uses a Core-prepared triangle mesh when one is present, + * otherwise triangulating the polygon on demand and reusing the + * generated mesh for later draws of the same scene. It draws + * boundaries from the original rings. Outline mode draws the original + * rings without requiring fill meshes. Polygons retain the GDI + * backend's painter order within a layer. * Draws all layers into one frame, bottom first. Returns S_FALSE - * without drawing when fill mode lacks a usable mesh or when no - * OpenGL context with framebuffer-object support is available, so - * callers can fall back to another backend for the whole frame. + * without drawing when fill-mesh preparation fails or when no OpenGL + * context with framebuffer-object support is available, so callers + * can fall back to another backend for the whole frame. * When retainStagingBuffer is false, a temporary renderer owns the * draw's CPU and GPU buffers, leaving the screen resources unchanged. */ @@ -81,10 +85,12 @@ namespace mwg::activex private: friend class testing::OpenGlVectorLayerRendererTestAccess; friend class testing::MapWinGISControlTestAccess; + friend class VectorLayerRenderer; /// True when the scene can be drawn in the requested mode. Outline - /// mode needs finite ring coordinates; fill mode additionally needs - /// a usable mesh for every polygon. Exposed for tests. + /// mode needs finite ring coordinates; fill mode may lazily prepare + /// missing meshes but rejects unusable explicitly prepared meshes. + /// Exposed for tests. [[nodiscard]] static bool IsSceneSupported( const rendering::MapRenderScene& scene, VectorRenderMode renderMode) noexcept; @@ -116,6 +122,15 @@ namespace mwg::activex const Viewport& viewport, VectorRenderMode renderMode) noexcept; [[nodiscard]] bool EnsureStaging(std::size_t stagingBytes) noexcept; + [[nodiscard]] HRESULT PrepareFillMeshes( + const rendering::MapRenderScene& scene) noexcept; + [[nodiscard]] std::span> + GetFillMeshes( + std::size_t layerIndex, + const rendering::VectorRenderScene& scene) const noexcept; + void ClearFillMeshCache() noexcept; + [[nodiscard]] std::size_t FillMeshCacheSize() const noexcept; + [[nodiscard]] std::size_t CachedGeneratedMeshStorage() const noexcept; [[nodiscard]] HRESULT RenderScene( const rendering::MapRenderScene& scene, const Viewport& viewport, @@ -142,6 +157,8 @@ namespace mwg::activex L"OpenGL was not selected for this frame."; std::wstring_view _initializationFailureReason; std::vector _pixelBuffer; + struct FillMeshCache; + std::shared_ptr _fillMeshCache; int _retryTargetWidth = 0; int _retryTargetHeight = 0; unsigned int _initializationRetryDrawsRemaining = 0; diff --git a/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp b/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp index 31217b6..da27363 100644 --- a/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp +++ b/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp @@ -9,6 +9,9 @@ */ #include "VectorLayerRenderer.h" +#include +#include + namespace mwg::activex { HRESULT VectorLayerRenderer::Draw( @@ -21,13 +24,29 @@ namespace mwg::activex { _activeBackend.reset(); + rendering::MapRenderScene stableScene; + try + { + stableScene = scene; + } + catch (const std::bad_alloc&) + { + _diagnostic = L"The renderer could not snapshot the render scene."; + return E_OUTOFMEMORY; + } + catch (const std::length_error&) + { + _diagnostic = L"The renderer could not represent its render-scene snapshot."; + return S_FALSE; + } + if (_preference != VectorRenderBackendPreference::Gdi) { const HRESULT openGlResult = _openGlRenderer.Draw( deviceContext, bounds, - scene, + stableScene, viewport, retainStagingBuffer, renderMode); @@ -51,7 +70,13 @@ namespace mwg::activex } const HRESULT gdiResult = - _gdiRenderer.Draw(deviceContext, bounds, scene, viewport, true, renderMode); + _gdiRenderer.Draw( + deviceContext, + bounds, + stableScene, + viewport, + true, + renderMode); if (SUCCEEDED(gdiResult)) { _activeBackend = VectorRenderBackendKind::Gdi; diff --git a/src/MapWinGIS.ActiveX/VectorLayerRenderer.h b/src/MapWinGIS.ActiveX/VectorLayerRenderer.h index fcc40aa..15b2da3 100644 --- a/src/MapWinGIS.ActiveX/VectorLayerRenderer.h +++ b/src/MapWinGIS.ActiveX/VectorLayerRenderer.h @@ -69,6 +69,11 @@ namespace mwg::activex return _diagnostic; } + void InvalidateSceneCache() noexcept + { + _openGlRenderer.ClearFillMeshCache(); + } + private: friend class testing::MapWinGISControlTestAccess; diff --git a/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp b/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp index ea55f77..f06883b 100644 --- a/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp @@ -2334,6 +2334,29 @@ TEST_F(ActiveXMapTest, ScaledDrawsKeepScreenBuffersAtTheClientSize) EXPECT_EQ(Access::StagingCapacity(control), capacity); } +TEST_F(ActiveXMapTest, ClearLayersReleasesLazyFillMeshes) +{ + using Access = mwg::activex::testing::MapWinGISControlTestAccess; + ASSERT_EQ(Resize(120, 100), S_OK); + ASSERT_EQ(LoadRectangles({{0, 0, 10, 5}}), S_OK); + ASSERT_EQ(_control->put_RenderingBackendPreference(ATL::CComBSTR(L"OpenGL")), S_OK); + + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + ASSERT_EQ(Draw(surface.Get(), 120, 100), S_OK); + ATL::CComBSTR backend; + ASSERT_EQ(_control->get_RenderingBackend(&backend), S_OK); + if (backend == nullptr || std::wcscmp(backend, L"OpenGL") != 0) + { + GTEST_SKIP() << "The control selected GDI for the OpenGL preference."; + } + + const auto& control = Access::Control(_control.Get()); + EXPECT_GT(Access::FillMeshCacheSize(control), 0U); + ASSERT_EQ(_control->ClearLayers(), S_OK); + EXPECT_EQ(Access::FillMeshCacheSize(control), 0U); +} + TEST_F(ActiveXMapTest, DragDrawBlitsWholePixelShiftsAndRendersFractionalOrHugeShifts) { using Access = mwg::activex::testing::MapWinGISControlTestAccess; diff --git a/tests/MapWinGIS.ActiveX.Tests/MapWinGISControlTestAccess.h b/tests/MapWinGIS.ActiveX.Tests/MapWinGISControlTestAccess.h index 14001b4..0ad36ea 100644 --- a/tests/MapWinGIS.ActiveX.Tests/MapWinGISControlTestAccess.h +++ b/tests/MapWinGIS.ActiveX.Tests/MapWinGISControlTestAccess.h @@ -46,6 +46,12 @@ namespace mwg::activex::testing return control._renderer._openGlRenderer._pixelBuffer.capacity(); } + [[nodiscard]] static std::size_t FillMeshCacheSize( + const CMapWinGISControl& control) noexcept + { + return control._renderer._openGlRenderer.FillMeshCacheSize(); + } + static LayerId AddLayerWithFillMeshes( CMapWinGISControl& control, std::shared_ptr dataset) diff --git a/tests/MapWinGIS.ActiveX.Tests/OpenGlVectorLayerRendererTestAccess.h b/tests/MapWinGIS.ActiveX.Tests/OpenGlVectorLayerRendererTestAccess.h index 64ee6a2..a15f799 100644 --- a/tests/MapWinGIS.ActiveX.Tests/OpenGlVectorLayerRendererTestAccess.h +++ b/tests/MapWinGIS.ActiveX.Tests/OpenGlVectorLayerRendererTestAccess.h @@ -55,5 +55,24 @@ namespace mwg::activex::testing { return OpenGlVectorLayerRenderer::IsSceneSupported(scene, renderMode); } + + [[nodiscard]] static HRESULT PrepareFillMeshes( + OpenGlVectorLayerRenderer& renderer, + const rendering::MapRenderScene& scene) noexcept + { + return renderer.PrepareFillMeshes(scene); + } + + [[nodiscard]] static std::size_t FillMeshCacheSize( + const OpenGlVectorLayerRenderer& renderer) noexcept + { + return renderer.FillMeshCacheSize(); + } + + [[nodiscard]] static std::size_t CachedGeneratedMeshStorage( + const OpenGlVectorLayerRenderer& renderer) noexcept + { + return renderer.CachedGeneratedMeshStorage(); + } }; } diff --git a/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp b/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp index 6dfac29..40b8f98 100644 --- a/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -27,6 +28,7 @@ #include "mapwingis/core/Error.h" #include "mapwingis/diagnostics/PerformanceDiagnostics.h" +#include "mapwingis/gdal/GdalEnvironment.h" #include "mapwingis/rendering/PolygonTriangulation.h" namespace @@ -240,6 +242,20 @@ namespace } }; + class LogHandlerScope final + { + public: + explicit LogHandlerScope(mwg::LogHandler handler) + { + mwg::GdalEnvironment::SetLogHandler(std::move(handler)); + } + + ~LogHandlerScope() + { + mwg::GdalEnvironment::SetLogHandler({}); + } + }; + /// Checks the pixels of MakeTwoLayerScene drawn through viewport. void ExpectTwoLayerPixels(const HDC surface, const mwg::Viewport& viewport) { @@ -250,6 +266,22 @@ namespace EXPECT_EQ(MapPixel(surface, viewport, 1.0, 4.0), background) << "above first layer"; EXPECT_EQ(MapPixel(surface, viewport, 9.0, 1.0), background) << "below second layer"; } + + [[nodiscard]] std::size_t CountPixels( + const HDC surface, + const RECT& bounds, + const COLORREF color) + { + std::size_t count = 0; + for (int y = bounds.top; y < bounds.bottom; ++y) + { + for (int x = bounds.left; x < bounds.right; ++x) + { + count += GetPixel(surface, x, y) == color; + } + } + return count; + } } TEST(VectorLayerRenderer, RecordsGdiFrameDurationWhenDiagnosticsAreEnabled) @@ -274,25 +306,36 @@ TEST(VectorLayerRenderer, RecordsGdiFrameDurationWhenDiagnosticsAreEnabled) EXPECT_GE(frame.durationNanoseconds, 0); } -TEST(VectorLayerRenderer, UsesOpenGlForConvexPolygonWhenAvailable) +TEST(VectorLayerRenderer, UsesOpenGlForLazyConvexPolygonWhenAvailable) { BitmapSurface surface(120, 100); ASSERT_TRUE(surface.IsValid()); ASSERT_TRUE(PatBlt(surface.Get(), 0, 0, 120, 100, BLACKNESS)); const RECT bounds{0, 0, 120, 100}; - const mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); + mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); + Edit(scene.layers.front()).fillMeshes.clear(); const mwg::Viewport viewport = FitViewport(bounds); - // Only an unavailable OpenGL target may skip; drawing, readback or - // presentation failures in the backend must fail the test. - mwg::activex::OpenGlVectorLayerRenderer openGlRenderer; - const HRESULT openGlResult = openGlRenderer.Draw(surface.Get(), bounds, scene, viewport); - if (openGlResult == S_FALSE) + BitmapSurface probeSurface(120, 100); + ASSERT_TRUE(probeSurface.IsValid()); + mwg::activex::OpenGlVectorLayerRenderer availabilityProbe; + const HRESULT probeResult = + availabilityProbe.Draw( + probeSurface.Get(), + bounds, + MakeConvexPolygonScene(), + viewport); + if (probeResult == S_FALSE) { GTEST_SKIP() << "No OpenGL context with framebuffer objects is available."; } + ASSERT_EQ(probeResult, S_OK); + + mwg::activex::OpenGlVectorLayerRenderer openGlRenderer; + const HRESULT openGlResult = openGlRenderer.Draw(surface.Get(), bounds, scene, viewport); ASSERT_EQ(openGlResult, S_OK); + EXPECT_TRUE(scene.layers.front().scene->fillMeshes.empty()); EXPECT_EQ(GetPixel(surface.Get(), 60, 50), kFill); EXPECT_EQ(GetPixel(surface.Get(), 5, 5), GetSysColor(COLOR_WINDOW)); @@ -384,6 +427,245 @@ TEST(VectorLayerRenderer, OpenGlRejectsPolygonWithoutFillMesh) L"every polygon; this frame was rendered with GDI."); } +TEST(VectorLayerRenderer, OpenGlLazilyTriangulatesAndReusesFillMeshes) +{ + mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); + Edit(scene.layers.front()).fillMeshes.clear(); + PerformanceCapture diagnostics; + + mwg::activex::OpenGlVectorLayerRenderer renderer; + ASSERT_EQ( + mwg::activex::testing::OpenGlVectorLayerRendererTestAccess::PrepareFillMeshes( + renderer, + scene), + S_OK); + ASSERT_EQ( + mwg::activex::testing::OpenGlVectorLayerRendererTestAccess::PrepareFillMeshes( + renderer, + scene), + S_OK); + + const mwg::diagnostics::PerformanceSnapshot snapshot = + mwg::diagnostics::PerformanceDiagnostics::Snapshot(); + EXPECT_EQ( + snapshot.Timing( + mwg::diagnostics::PerformanceOperation::PolygonTriangulation).callCount, + 1); + EXPECT_EQ( + snapshot.Counter( + mwg::diagnostics::PerformanceCounter::PolygonsTriangulated), + 1); + EXPECT_TRUE(scene.layers.front().scene->fillMeshes.empty()); +} + +TEST(VectorLayerRenderer, OpenGlSharesLazyMeshesWithTemporaryRenderers) +{ + BitmapSurface surface(240, 201); + ASSERT_TRUE(surface.IsValid()); + const RECT screenBounds{0, 0, 120, 100}; + const RECT scaledBounds{0, 0, 240, 201}; + const auto screenViewport = FitViewport(screenBounds); + const auto scaledViewport = FitViewport(scaledBounds); + + mwg::activex::OpenGlVectorLayerRenderer availabilityProbe; + const auto probeScene = MakeConvexPolygonScene(); + const HRESULT probeResult = availabilityProbe.Draw( + surface.Get(), + screenBounds, + probeScene, + screenViewport); + if (probeResult == S_FALSE) + { + GTEST_SKIP() << "No OpenGL context with framebuffer objects is available."; + } + ASSERT_EQ(probeResult, S_OK); + + auto normalFirstScene = MakeConvexPolygonScene(); + Edit(normalFirstScene.layers.front()).fillMeshes.clear(); + auto temporaryFirstScene = MakeConvexPolygonScene(); + Edit(temporaryFirstScene.layers.front()).fillMeshes.clear(); + PerformanceCapture diagnostics; + mwg::activex::OpenGlVectorLayerRenderer renderer; + ASSERT_EQ( + renderer.Draw( + surface.Get(), + screenBounds, + normalFirstScene, + screenViewport), + S_OK); + ASSERT_EQ( + renderer.Draw( + surface.Get(), + scaledBounds, + normalFirstScene, + scaledViewport, + false), + S_OK); + EXPECT_EQ(MapPixel(surface.Get(), scaledViewport, 5.0, 5.0), kFill); + ASSERT_EQ( + renderer.Draw( + surface.Get(), + screenBounds, + normalFirstScene, + screenViewport), + S_OK); + + ASSERT_EQ( + renderer.Draw( + surface.Get(), + scaledBounds, + temporaryFirstScene, + scaledViewport, + false), + S_OK); + ASSERT_EQ( + renderer.Draw( + surface.Get(), + screenBounds, + temporaryFirstScene, + screenViewport), + S_OK); + EXPECT_EQ(MapPixel(surface.Get(), screenViewport, 5.0, 5.0), kFill); + + const auto snapshot = mwg::diagnostics::PerformanceDiagnostics::Snapshot(); + EXPECT_EQ( + snapshot.Timing( + mwg::diagnostics::PerformanceOperation::PolygonTriangulation).callCount, + 2); +} + +TEST(VectorLayerRenderer, OpenGlLazyTriangulationFailureFallsBackAndPreservesOutlines) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 120, 100}; + ASSERT_NE(FillRect(surface.Get(), &bounds, GetSysColorBrush(COLOR_WINDOW)), 0); + + mwg::rendering::MapRenderScene scene = MakeMapScene({{ + mwg::Extent{-3.0, -3.0, 3.0, 3.0}, + 0, + 0, + {{{{0.0, 3.0}, {2.0, -3.0}, {-3.0, 1.0}, {3.0, 1.0}, {-2.0, -3.0}, {0.0, 3.0}}}}}}); + Edit(scene.layers.front()).fillMeshes.clear(); + const auto viewport = FitViewport(bounds, {-3.0, -3.0, 3.0, 3.0}); + PerformanceCapture diagnostics; + LogHandlerScope throwingLogHandler( + [](const mwg::LogLevel, const std::string_view) + { + throw std::runtime_error("Test GDAL logger failure"); + }); + + using Access = mwg::activex::testing::OpenGlVectorLayerRendererTestAccess; + mwg::activex::OpenGlVectorLayerRenderer cacheProbe; + ASSERT_EQ( + Access::PrepareFillMeshes(cacheProbe, scene), + S_FALSE); + EXPECT_EQ(Access::CachedGeneratedMeshStorage(cacheProbe), 0U); + ASSERT_EQ( + Access::PrepareFillMeshes(cacheProbe, scene), + S_FALSE); + EXPECT_EQ(Access::CachedGeneratedMeshStorage(cacheProbe), 0U); + + EXPECT_TRUE( + Access::IsSceneSupported( + scene, + mwg::activex::VectorRenderMode::Outline)); + + BitmapSurface probeSurface(120, 100); + ASSERT_TRUE(probeSurface.IsValid()); + mwg::activex::OpenGlVectorLayerRenderer availabilityProbe; + const HRESULT probeResult = availabilityProbe.Draw( + probeSurface.Get(), + bounds, + MakeConvexPolygonScene(), + FitViewport(bounds)); + if (probeResult == S_FALSE) + { + GTEST_SKIP() << "No OpenGL context with framebuffer objects is available."; + } + ASSERT_EQ(probeResult, S_OK); + + mwg::activex::VectorLayerRenderer renderer; + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ( + renderer.GetActiveBackend(), + mwg::activex::VectorRenderBackendKind::Gdi); + EXPECT_GT(CountPixels(surface.Get(), bounds, kFill), 0U); + + ASSERT_NE(FillRect(surface.Get(), &bounds, GetSysColorBrush(COLOR_WINDOW)), 0); + ASSERT_EQ( + renderer.Draw( + surface.Get(), + bounds, + scene, + viewport, + true, + mwg::activex::VectorRenderMode::Outline), + S_OK); + EXPECT_EQ( + renderer.GetActiveBackend(), + mwg::activex::VectorRenderBackendKind::OpenGL); + EXPECT_GT(CountPixels(surface.Get(), bounds, RGB(24, 58, 82)), 0U); + + const mwg::diagnostics::PerformanceSnapshot snapshot = + mwg::diagnostics::PerformanceDiagnostics::Snapshot(); + EXPECT_EQ( + snapshot.Counter( + mwg::diagnostics::PerformanceCounter::TriangulationFailures), + 2); +} + +TEST(VectorLayerRenderer, SnapshotsSceneAcrossReentrantTriangulationCallback) +{ + BitmapSurface probeSurface(120, 100); + ASSERT_TRUE(probeSurface.IsValid()); + const RECT bounds{0, 0, 120, 100}; + const auto viewport = FitViewport(bounds, {-3.0, -3.0, 3.0, 3.0}); + + mwg::activex::OpenGlVectorLayerRenderer availabilityProbe; + const HRESULT probeResult = availabilityProbe.Draw( + probeSurface.Get(), + bounds, + MakeConvexPolygonScene(), + FitViewport(bounds)); + if (probeResult == S_FALSE) + { + GTEST_SKIP() << "No OpenGL context with framebuffer objects is available."; + } + ASSERT_EQ(probeResult, S_OK); + + mwg::rendering::MapRenderScene scene = MakeMapScene({{ + mwg::Extent{-3.0, -3.0, 3.0, 3.0}, + 0, + 0, + {{{{0.0, 3.0}, {2.0, -3.0}, {-3.0, 1.0}, {3.0, 1.0}, {-2.0, -3.0}, {0.0, 3.0}}}}}}); + Edit(scene.layers.front()).fillMeshes.clear(); + bool callbackRan = false; + mwg::activex::VectorLayerRenderer renderer; + LogHandlerScope reentrantHandler( + [&scene, &callbackRan, &renderer]( + const mwg::LogLevel, + const std::string_view) + { + if (!callbackRan) + { + callbackRan = true; + scene.layers.clear(); + renderer.InvalidateSceneCache(); + } + }); + + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_TRUE(callbackRan); + EXPECT_TRUE(scene.layers.empty()); + EXPECT_EQ( + renderer.GetActiveBackend(), + mwg::activex::VectorRenderBackendKind::Gdi); + EXPECT_GT(CountPixels(surface.Get(), bounds, kFill), 0U); +} + TEST(VectorLayerRenderer, OpenGlDrawsOutlinesWithoutFillMeshes) { BitmapSurface surface(120, 100); @@ -676,10 +958,10 @@ TEST(VectorLayerRenderer, OpenGlFillSupportRequiresAMeshForEveryPolygon) EXPECT_TRUE( mwg::activex::testing::OpenGlVectorLayerRendererTestAccess::IsSceneSupported(scene)); - // No meshes at all. + // No meshes at all; fill support can prepare them lazily. mwg::rendering::MapRenderScene withoutMeshes = MakeConvexPolygonScene(); Edit(withoutMeshes.layers.front()).fillMeshes.clear(); - EXPECT_FALSE( + EXPECT_TRUE( mwg::activex::testing::OpenGlVectorLayerRendererTestAccess::IsSceneSupported( withoutMeshes)); EXPECT_TRUE(