diff --git a/.ai/memory/architecture/activex.md b/.ai/memory/architecture/activex.md index 4211109..7f894b5 100644 --- a/.ai/memory/architecture/activex.md +++ b/.ai/memory/architecture/activex.md @@ -24,7 +24,14 @@ remain in Core. The ActiveX rendering coordinator selects a backend for a Core render scene. GDI is the CPU fallback; OpenGL has a narrower supported-scene range and can -fall back to GDI. Backends consume Core-produced geometry and do not own +fall back to GDI. With the `Automatic` preference, a Fill-mode frame whose +layers have no fill meshes yet is painted with GDI (reported via +`RenderingBackend`/`RenderingStatus`) so the paint path never triangulates; +OpenGL is retried on later frames once meshes exist. Nothing prepares those +meshes during `Automatic` drawing today (Phase 2 adds background +preparation), so default Fill stays on GDI until an explicit `OpenGL` draw +caches the meshes or a scene supplies them. Only the explicit +`OpenGL` preference triangulates lazily on the drawing thread. Backends consume Core-produced geometry and do not own datasets or view state. The OCX owns the host-specific rendering resources. The control composes ordinary screen frames in an offscreen DIB-section `FrameBuffer` and presents them with a single `BitBlt`; alternate-size diff --git a/.ai/memory/build/cmake.md b/.ai/memory/build/cmake.md index 9c8c5b9..2c19a15 100644 --- a/.ai/memory/build/cmake.md +++ b/.ai/memory/build/cmake.md @@ -14,6 +14,13 @@ Generated Visual Studio projects set `WindowsTargetPlatformVersion` before importing `Directory.Build.props`; its legacy SDK default must not override that selection, including in CMake's `VCTargetsPath` probe. +On the primary development machine `cmake` is not on PATH; it ships with +Visual Studio 18 Community under `Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin`. +The `x64-debug`/`x64-release` Ninja presets also require `cl.exe` on PATH +(a Developer prompt). From a plain shell, use the `vs2026-x64` configure +preset and the `vs2026-x64-debug`/`vs2026-x64-release` build and test presets; +the Visual Studio generator locates the v145 toolset itself. + The `cmake-parity` job fails (`-FailOnLostFlags`) when a translation unit is compiled by MSBuild but missing from the CMake target — including test projects. Adding a source file to a `.vcxproj` therefore requires the same diff --git a/.github/plans/Vector-Rendering-First-Frame-Performance.md b/.github/plans/Vector-Rendering-First-Frame-Performance.md new file mode 100644 index 0000000..777da6f --- /dev/null +++ b/.github/plans/Vector-Rendering-First-Frame-Performance.md @@ -0,0 +1,281 @@ +# MapWinGIS6 – Vector Rendering First-Frame Performance Plan + +## Implementation checklist + +Copilot: Update this checklist as each phase is implemented. Only mark a phase +complete when its acceptance criteria have been met and its PR is ready. + +- [x] **Phase 1 – End-to-end benchmark + keep triangulation off the paint path** (PR 1) +- [ ] **Phase 2 – Fast triangulation + background mesh preparation** (PR 2) +- [ ] **Phase 3 – Remaining costs + documentation** (PR 3) + +**Target branch:** `development` + +**Predecessor:** [Vector-Rendering-Performance-Improvement.md](Vector-Rendering-Performance-Improvement.md) + +## Context + +The previous plan removed triangulation from dataset opening and scene +construction. It did not remove triangulation from the user-visible load path. +Opening +`F:\dev\GIS-data\Siebe\20200116 Clip\afwateringseenheden_2019_copy_join_pgb_20190704.shp` +(10.3 MB, 2,459 features / 2,470 polygons, 586,414 triangles) in +`ActiveXTestHost.exe` still takes 7+ seconds before the polygons appear. +MapWinGIS5 shows the same file almost instantly. + +This plan consolidates the follow-up analysis into **3 PRs** (GitHub CI checks +take over an hour per PR, so the work is grouped accordingly). + +The test dataset is not committed. Use `MWG_RENDERING_BASELINE_DATASET` to +point the benchmarks at it. + +## Benchmark results (2026-11-25, real shapefile, 1280x720, one workstation) + +`RenderingBaseline.*` against the real shapefile, plus the Debug comparison. +Results are from single runs, so use them as an indication. + +| Measurement | Release | Debug | +|---|---:|---:| +| Source-only scene (OGR read + conversion) | 89–186 ms | 543 ms | +| GEOS `IsValid` precheck (2,470 polygons) | 51–56 ms | 400 ms | +| GEOS constrained Delaunay triangulation | 1,730–1,799 ms | ~11,700 ms | +| GDI fill first frame (direct from source rings, no meshes) | 18–31 ms | 62–96 ms | +| OpenGL outline first frame (incl. context creation) | 268–276 ms | 314 ms | +| **OpenGL lazy-fill first frame (= time to first pixel)** | **~1,900 ms** | **~12,400 ms** | +| OpenGL steady / pan / zoom | 10–15 ms | 44–45 ms | +| `glReadPixels` (8 frames total) | 36–66 ms | 64 ms | + +## Root causes (verified against the code) + +1. **First paint blocks on full-layer triangulation.** The renderer defaults + to `Automatic` backend + `Fill` mode + (`src/MapWinGIS.ActiveX/VectorLayerRenderer.h:87`), so the first `OnDraw` + uses OpenGL, which synchronously triangulates all 2,470 polygons on the UI + thread (`OpenGlVectorLayerRenderer.cpp` `PrepareFillMeshes`, + all-or-nothing per layer) before any pixel is presented. Triangulation is + ~94% of time-to-first-pixel. The lazy-triangulation phases moved the cost + from load to first paint; they did not remove it. +2. **The 7+ s was measured on Debug binaries** (debug GDAL/GEOS from vcpkg + make triangulation ~6.5x slower: ~12.4 s first frame). Release is ~2.0 s + end-to-end — still far from MapWinGIS5. +3. **GDI fill needs no triangulation** — it fills source rings in ~20 ms + (Release), which is exactly why MapWinGIS5 feels instant. The default + backend order never uses it for the first frame. +4. **Secondary costs:** OGR reads 81 ms; OpenGL context/FBO creation + ~50–250 ms on first draw; per-frame O(total-vertices) validity scans + (`OpenGlVectorLayerRenderer.cpp:287`, `GdiVectorLayerRenderer.cpp:128-144`); + GPU buffer build/upload uninstrumented + (`OpenGlVectorLayerRenderer.cpp:819-951`); the `FrameRender` scope + double-counts triangulation. +5. **Measurement gap:** no benchmark drives the real + `LoadVectorDatasetEx` → first presented `OnDraw` path through + `CMapWinGISControl`; the existing baselines test renderers in isolation. + Viewport filtering (previous plan, Phase 5) does not help here: the control + seeds a complete scene (`MapWinGISControl.cpp:104-137` → + `MapView.cpp:213-216`) and at full extent every feature is visible anyway. + +## Target (Release, test dataset, default settings `Automatic` + `Fill`) + +- `LoadVectorDatasetEx` → first presented filled frame: **≤ 250 ms**. +- No frame blocks the UI thread more than **100 ms** for mesh generation. +- Debug stays usable: **≤ 1.5 s** to first frame. +- No regression in steady pan/zoom, visual output, or the existing test + suites. + +--- + +# Phase 1 – End-to-end benchmark + keep triangulation off the paint path (PR 1) + +Measurement and the primary fix land together; the new benchmark proves the +fix. + +### 1.1 End-to-end benchmark + +Add an opt-in `RenderingBaseline` test that hosts `CMapWinGISControl`, calls +`LoadVectorDatasetEx` (and the `BeginLoadVectorDataset`/`EndLoadVectorDataset` +path), forces the first `OnDraw` into a memory DC with default settings, and +reports load time, first-presented-frame time, and the diagnostic breakdown. +Fix the `FrameRender`/`PolygonTriangulation` scope overlap and instrument the +GPU buffer build/upload so the breakdown is accurate. + +### 1.2 GDI-first first paint + +In `Automatic` mode, when a layer has no cached fill meshes, draw the frame +with the existing GDI direct-ring fill path (~20 ms) instead of triangulating +during the draw; switch that layer to OpenGL on a later frame once meshes +exist. Do not mix backends within one frame. An explicit `OpenGL` preference +keeps the current lazy behavior (documented) until Phase 2 provides background +preparation. + +### 1.3 Report the active backend + +`RenderingBackend` and the rendering status must state that GDI is in use +while the meshes are pending. + +### 1.4 Test-host timings + +Show the load time and the first-paint time in the `ActiveXTestHost` status +bar for debugger-free comparison with MapWinGIS5. + +### 1.5 Structural regression assertion + +No timing thresholds: with default settings the first frame performs **0 +triangulations**. Visual parity between GDI ALTERNATE fill and OpenGL meshes +for holed polygons and multipolygons stays within the existing pixel-test +tolerances. + +### 1.6 Record the baseline + +Record the Release and Debug results for the test dataset in +`docs/TESTING.md`. State clearly that comparisons with MapWinGIS5 must use +Release builds. + +### Acceptance criteria + +- One command reproduces the user-visible delay and shows how it divides into + load, scene, triangulation, and draw. +- With the default settings, the first frame does not call + `TriangulatePolygon`. +- Release first frame ≤ 250 ms on the test dataset. +- The full CTest suites pass. + +### Status after Phase 1 + +Measured on the test dataset (2026-11-25, one workstation, recorded in +`docs/TESTING.md`): `LoadVectorDatasetEx` → first presented frame is +213 ms Release / 1,164 ms Debug; the async path is 198 ms Release / +1,162 ms Debug. Every first frame reported GDI and performed zero +triangulations. Debug and Release CTest suites (484 tests) pass. + +Remaining limitations: + +- With `Automatic`, fill rendering stays on GDI until fill meshes exist; + nothing prepares them in the background yet. Phase 2 adds the worker and + the view invalidation that switches the layer to OpenGL on a later frame. +- The OGR scene read (~165 ms Release for 2,459 features) now dominates the + load path; Phase 3 evaluates batch reading and the remaining costs. + +--- + +# Phase 2 – Fast triangulation + background mesh preparation (PR 2) + +Even with GDI-first paint, OpenGL fill should arrive quickly and never block +the UI thread. + +### 2.1 Replace GEOS CDT for fill meshes with earcut + +Evaluate and adopt [mapbox/earcut.hpp](https://github.com/mapbox/earcut.hpp) +(ISC license, vcpkg port `earcut-hpp`, header-only). It handles holes, works +directly on the scene's ring buffers (no OGR/GEOS object creation), and is +typically one to two orders of magnitude faster than constrained Delaunay +triangulation. Target ≤ 100 ms for all 2,470 polygons in Release. + +Before adopting, confirm: + +- The license is compatible with MPL-2.0 and the vcpkg port builds with the + overlay triplets. +- Output parity with GDI fill for holes, multipolygons, touching rings, and + self-intersecting (invalid) polygons. + +`TriangulatePolygon` stays the single entry point; earcut — like GEOS — +remains an internal implementation detail and never appears in public headers. +Keep GEOS as the second-level fallback for polygons earcut cannot mesh (mark +failed → existing GDI fallback otherwise). Do not modify source geometry to +make triangulation succeed. + +### 2.2 Remove the `IsValid` precheck from the fill path + +Earcut does not need valid OGC geometry. Removing the precheck saves 55 ms +(Release) / 400 ms (Debug) per layer. + +### 2.3 Background preparation + +After a layer is added, generate meshes on a worker with bounded parallelism +(earcut has no shared state; the GEOS fallback uses per-thread contexts). The +worker reads only the immutable, owned `VectorRenderScene` — never OGR/GDAL +objects. Key results by stable layer ID and scene identity (the existing cache +key). Cancel or discard the work when the layer is removed, replaced, or +invalidated. Post a message to the control window to invalidate the view when +the meshes are ready, so the next frame switches from GDI to OpenGL. + +### 2.4 Optional investigation (only if earcut falls short) + +Stencil-then-cover OpenGL fill: draw ring fans into the stencil buffer with +`GL_INVERT` (even-odd rule, matches GDI ALTERNATE), then cover with the +bounding box. Needs no triangulation and reuses the outline buffers. Adopt +only if clearly better than earcut plus background preparation. + +### Acceptance criteria + +- Lazy fill triangulation of the test dataset takes ≤ 100 ms in Release. +- No UI-thread stall over 100 ms for mesh generation. +- Removing or reloading a layer during preparation does not crash, leak + memory, or publish stale meshes. +- Tests cover the pending, ready, cancelled, and failed states. +- Existing triangulation, holed, concave, and degenerate tests pass; pixel + comparisons with GDI fill stay within the current tolerances. + +--- + +# Phase 3 – Remaining costs + documentation (PR 3) + +Do this work only where the Phase 1 measurements justify it. + +- **OpenGL context warm-up:** create the context and FBO when the control is + created or idle, not during the first draw (~50–250 ms). +- **Async load in the test host:** use `BeginLoadVectorDataset` (scene build + is 89 ms Release / 543 ms Debug on the UI thread), or document why not. +- **Display-resolution vertex reduction:** at the full extent, ~590 k vertices + go into 1280 x 720 pixels. Reduce consecutive vertices that fall in the same + pixel for GDI and outline drawing (MapWinGIS 5 uses a similar method). Never + modify cached source geometry. +- **OGR read throughput:** measure whether `OGRLayer::GetArrowStream` or batch + reading beats per-feature `GetNextFeature` (81 ms). Keep the GDAL + abstraction. +- **Docs and memory:** update `docs/TESTING.md`, `docs/ARCHITECTURE.md`, and + the test host README. Record verified lessons in + `.ai/memory/lessons/lessons.md` (for example: "lazy is not enough when the + paint path is the first consumer" and "measure Debug and Release + separately"). Keep benchmarks opt-in and threshold-free; regressions are + caught by structural assertions. + +--- + +# Key files + +- `src/MapWinGIS.ActiveX/MapWinGISControl.cpp` (`PrepareVectorDataset` :104, + `OnDraw` :1894, `DrawLayersAndUpdateCache` :1831) +- `src/MapWinGIS.ActiveX/VectorLayerRenderer.h` (backend/mode defaults :87) +- `src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp` (`PrepareFillMeshes` + :1242, `DrawLayerWithGpuBuffers` :781, readback :1673) +- `src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.cpp` (direct-ring fill :128) +- `src/MapWinGIS.Core/src/rendering/PolygonTriangulation.cpp` (GEOS CDT :261) +- `src/MapWinGIS.Core/src/map/MapView.cpp` (complete-scene seeding :213) +- `tests/MapWinGIS.ActiveX.Tests/RenderingBaselineTests.cpp` (benchmark + harness) +- `samples/CSharp/ActiveXTestHost/` (status-bar timings, async load) + +# Verification + +- The new end-to-end benchmark on the real shapefile + (`MWG_RENDERING_BASELINE_DATASET`), Release and Debug: first presented + filled frame ≤ 250 ms Release / ≤ 1.5 s Debug; the first default frame + performs 0 triangulations. +- `ctest --preset x64-debug` (plus the Release build) green, including + lazy-fill lifecycle, GDI/OpenGL pixel parity, backend switching, and + cancellation tests. +- Manual: Release `ActiveXTestHost.exe` shows the shapefile essentially + immediately; pan, zoom, resize, layer removal/reload, and backend switching + behave as before; the status bar shows the active backend and timings. +- `docs/TESTING.md` records the new baseline numbers. + +# Assumptions + +- Performance targets apply to Release; Debug only needs to stay usable. + Phase 1 verifies the Debug/Release split end-to-end before optimization + lands. +- GDI ALTERNATE fill and OpenGL mesh fill are visually equivalent for this + dataset (covered by existing pixel tests; confirmed again in Phase 1). +- No public ActiveX API changes; earcut is an internal dependency only. +- Three PRs is the right granularity given over an hour of CI per PR; each PR + is still independently reviewable and leaves the tree green. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6bcd49a..4d2b3e7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -347,7 +347,15 @@ 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 +mode draws the source rings without requiring fill meshes. With the +`Automatic` preference, the coordinator instead paints a Fill-mode frame +whose layers have no fill meshes yet with the GDI backend, so the paint +path never blocks on triangulation. Nothing prepares those meshes during +`Automatic` drawing today — they exist only when a scene supplies them or +an explicit `OpenGL` draw caches them — so under the control's default +settings Fill stays on GDI until background preparation (planned) fills +the cache and the frame is redrawn. Only an explicit `OpenGL` +preference keeps lazy on-draw triangulation. 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. @@ -383,10 +391,13 @@ and scene preparation currently supports Polygon, MultiPolygon, CurvePolygon, and MultiSurface features. The `RenderingBackendPreference` automation property is configurable as -`Automatic`, `OpenGL`, or `GDI`. `Automatic` and `OpenGL` try the OpenGL -backend first and fall back to GDI when the scene, hardware, allocation, or -drawing operation is unsupported. The control reports the active backend and -the reason for a fallback through `RenderingBackend` and `RenderingStatus`. +`Automatic`, `OpenGL`, or `GDI`. `Automatic` paints with GDI while fill +meshes are pending and otherwise tries the OpenGL backend first; it falls +back to GDI when the scene, hardware, allocation, or drawing operation is +unsupported. `OpenGL` always tries OpenGL first, triangulating lazily on +the calling thread when a fill mesh is missing. The control reports the +active backend and the reason for a fallback through `RenderingBackend` and +`RenderingStatus`. These rendering properties are on `IMapWinGISControl2`, which derives from `IMapWinGISControl`. `IMapWinGISControl3` adds `ClearLayers` at DISPID 8. `IMapWinGISControl4` derives from `IMapWinGISControl3` and adds map navigation, diff --git a/docs/TESTING.md b/docs/TESTING.md index 9a304f6..8252b6b 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -209,27 +209,54 @@ 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. OpenGL fill rendering lazily -triangulates source-only scenes on their first fill draw and reuses those -backend-owned meshes on later draws. `MeasuresLazyOpenGlFillCosts` measures +creation does not perform triangulation. When the OpenGL backend draws a +source-only fill scene (the explicit `OpenGL` preference), it lazily +triangulates on that draw and reuses those backend-owned meshes on later +draws. With the default `Automatic` preference the coordinator instead paints a +mesh-pending Fill frame with GDI, so the first frame never triangulates, and +selects OpenGL again once every layer's meshes exist — today only via an +explicit OpenGL-preference draw or scene-provided meshes; Phase 2 adds +background preparation, so under the control's default settings Fill stays +on GDI until then. +`MeasuresLazyOpenGlFillCosts` measures that production path separately and verifies that scene preparation creates no meshes and later steady, pan, and zoom draws do not triangulate again. The renderer regression suite also checks lazy triangulation of concave and holed polygons across outline/fill changes, viewport changes, cache invalidation, and -scene removal. Point and line datasets are explicitly covered as unsupported +scene removal, and asserts the GDI-first Automatic contract: the first +mesh-pending frame reports GDI as the active backend, performs zero +triangulations, and a frame switches back to OpenGL once meshes exist +(primed by an explicit OpenGL draw or scene-provided meshes). Point and line datasets are explicitly covered as unsupported by the polygon-only renderer rather than being silently accepted. OpenGL pixel and buffer-lifecycle tests that require a framebuffer-capable context are conditional on that capability. GitHub-hosted Windows CI can skip those tests, so run them locally on an FBO-capable OpenGL driver to verify that coverage. +`MeasuresEndToEndFirstFrameThroughTheControl` and +`MeasuresEndToEndAsyncLoadFirstFrameThroughTheControl` close the measurement +gap between the isolated renderer baselines and the user-visible load path. +They host the control through its class factory (no registry registration), +load `MWG_RENDERING_BASELINE_DATASET` through `LoadVectorDatasetEx` or +`BeginLoadVectorDataset`/`EndLoadVectorDataset`, and force the first `OnDraw` +into a 1280x720 memory DC with the default `Automatic` settings. They report +the load time, the first presented frame time, the active backend, and the +diagnostic breakdown. Without timing thresholds, they assert that the first +frame reports GDI as the active backend and performs zero triangulations. + Performance diagnostics are disabled by default and aggregate process-wide timings with `std::chrono::steady_clock`. The collector records dataset opening, layer metadata, OGR feature reads, internal geometry conversion, scene construction, GEOS validation, triangulation, OpenGL geometry submission, complete backend rendering, and `glReadPixels`. It also records feature/geometry counts, triangles, invalid and failed triangulations, -viewport skips, and scene-cache hits and misses. OpenGL records GPU-buffer -preparation and draw submission in the geometry-submission scope. On systems +viewport skips, and scene-cache hits and misses. OpenGL records the build and +upload of layer GPU buffers in their own scope, separate from draw +submission. The complete-frame scope covers rendering, readback, and +presentation; context recovery, WGL context and framebuffer creation, and +the staging allocation are recorded in the OpenGL context-initialization +scope, and mesh preparation (triangulation) is recorded separately — none +of these is part of the frame scope, so the breakdown does not +double-count them. On systems with OpenGL 1.5 or the ARB buffer-object extension, unchanged source geometry is uploaded once; other systems retain the client-array fallback. @@ -348,6 +375,25 @@ operations, so the retained lazy meshes remained within normal run-to-run variation while 2,459 polygons triangulated exactly once. This measurement is diagnostic rather than a CI timing threshold. +First-frame plan Phase 1 (2026-11-25) validated the user-visible path +end-to-end on one developer workstation against the real 10.3 MB, 2,459-feature +shapefile (`MWG_RENDERING_BASELINE_DATASET`), 1280x720 target, default +`Automatic` settings, both load entry points. Every first frame reported GDI +as the active backend and performed zero triangulations: + +| Measurement | Release | Debug | +|---|---:|---:| +| `LoadVectorDatasetEx` → first presented frame | 182 + 31 = 213 ms | 1073 + 91 = 1164 ms | +| `Begin/EndLoadVectorDataset` → first presented frame | 166 + 32 = 198 ms | 1071 + 91 = 1162 ms | + +Comparisons with MapWinGIS 5 must use Release builds: the same workstation +spent 1,797 ms in the OpenGL lazy-fill first frame before this phase +(triangulation 1,689 ms of it; GPU buffer build+upload 28 ms; frame render +88 ms excluding triangulation; eight `glReadPixels` calls 36 ms total), and +Debug builds of GDAL/GEOS inflate triangulation roughly six-fold. The scene +read dominates the remaining load time (about 165 ms Release / one second +Debug for the 2,459 features); Phase 3 of the first-frame plan addresses it. + Scene preparation reads geometries sequentially through OGR and copies their coordinates directly, avoiding indexed lookups, WKT serialization, and reparsing. The 100k-feature measurement dropped from 15,225 ms to 91.5 ms on diff --git a/samples/CSharp/ActiveXTestHost/MainForm.cs b/samples/CSharp/ActiveXTestHost/MainForm.cs index c2eaa27..5b31676 100644 --- a/samples/CSharp/ActiveXTestHost/MainForm.cs +++ b/samples/CSharp/ActiveXTestHost/MainForm.cs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 +using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; using System.Text; @@ -37,6 +38,10 @@ internal sealed class MainForm : Form private readonly ToolStripStatusLabel _featureCountLabel; private readonly ToolStripStatusLabel _backendLabel; private readonly ToolStripStatusLabel _renderingStatusLabel; + private readonly ToolStripStatusLabel _timingLabel; + private double? _lastLoadMilliseconds; + private double? _firstPaintMilliseconds; + private bool _awaitingFirstPaint; private readonly List _results = []; private readonly object _resultsLock = new(); private readonly object _reportLock = new(); @@ -147,6 +152,7 @@ public MainForm(HostOptions options) Spring = true, TextAlign = ContentAlignment.MiddleLeft }; + _timingLabel = new ToolStripStatusLabel("Last load: - | First frame: -"); statusStrip.Items.AddRange( [ _coreStatusLabel, @@ -157,7 +163,9 @@ public MainForm(HostOptions options) new ToolStripStatusLabel("|"), _backendLabel, new ToolStripStatusLabel("|"), - _renderingStatusLabel + _renderingStatusLabel, + new ToolStripStatusLabel("|"), + _timingLabel ]); Controls.Add(layout); @@ -481,7 +489,13 @@ private LoadedLayer AddVectorDataset(string path, List warnings) dynamic automation = automationObject; int previousLayerCount = (int)automation.LayerCount; long previousFeatureCount = (long)automation.FeatureCount; + var loadWatch = Stopwatch.StartNew(); long layerId = (long)automation.LoadVectorDatasetEx(path); + loadWatch.Stop(); + _lastLoadMilliseconds = loadWatch.Elapsed.TotalMilliseconds; + _awaitingFirstPaint = true; + _firstPaintMilliseconds = null; + UpdateTimingLabel(); var layer = new LoadedLayer( layerId, Path.GetFileNameWithoutExtension(path), null, path); ListViewItem item = AddLayerListItem(layer); @@ -1081,10 +1095,28 @@ private async Task VerifyGdalEventSinksAsync() private void RepaintHost() { + if (_awaitingFirstPaint) + { + var paintWatch = Stopwatch.StartNew(); + _host?.Invalidate(true); + _host?.Update(); + paintWatch.Stop(); + _firstPaintMilliseconds = paintWatch.Elapsed.TotalMilliseconds; + _awaitingFirstPaint = false; + UpdateTimingLabel(); + return; + } _host?.Invalidate(true); _host?.Update(); } + private void UpdateTimingLabel() + { + string load = _lastLoadMilliseconds is { } loadMs ? $"{loadMs:0.0} ms" : "-"; + string firstFrame = _firstPaintMilliseconds is { } paintMs ? $"{paintMs:0.0} ms" : "-"; + _timingLabel.Text = $"Last load: {load} | First frame: {firstFrame}"; + } + private void VerifyResize() { if (_host is null) diff --git a/samples/CSharp/ActiveXTestHost/README.md b/samples/CSharp/ActiveXTestHost/README.md index 9124321..433c4f6 100644 --- a/samples/CSharp/ActiveXTestHost/README.md +++ b/samples/CSharp/ActiveXTestHost/README.md @@ -41,6 +41,16 @@ Choose `Repaint` to request a redraw. Choose `Recreate` to dispose of the contro The status bar shows the active rendering backend and rendering status. Automated mode selects GDI, then requests OpenGL. The OpenGL request can fall back to GDI when the scene or system does not support OpenGL. +With the default `Automatic` preference, Fill frames are painted with GDI +until the OpenGL fill meshes exist. Nothing prepares them in the background +yet (planned), so the status keeps reporting GDI and `RenderingStatus` +explains it; only an explicit `OpenGL` preference draw prepares the meshes +today. + +## Read the load and first-frame timings + +The rightmost status-bar field shows how long the last `LoadVectorDatasetEx` call took and how long the first repaint after that load took. Use it for a debugger-free comparison with MapWinGIS 5; meaningful timings require a Release build. + ## Run automated checks Run automated mode from an interactive Windows desktop session: diff --git a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp index 28234d8..04b5433 100644 --- a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp +++ b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp @@ -252,9 +252,16 @@ namespace mwg::activex return true; } - /// Returns true when the scene has finite ring coordinates and, in - /// fill mode, one usable mesh per polygon. - [[nodiscard]] bool IsSupported( + constexpr std::wstring_view kFillMeshRejection = + L"The OpenGL backend requires a triangulated fill mesh for " + L"every polygon; this frame was rendered with GDI."; + constexpr std::wstring_view kOutlineRejection = + L"The OpenGL backend requires finite polygon coordinates for " + L"outline rendering; this frame was rendered with GDI."; + + /// Returns why the scene cannot be drawn in the requested mode + /// without generating geometry, or nullopt when it is drawable. + [[nodiscard]] std::optional GetSceneRejection( const rendering::MapRenderScene& scene, const VectorRenderMode renderMode) noexcept { @@ -262,7 +269,9 @@ namespace mwg::activex { if (layer.scene == nullptr) { - return false; + return renderMode == VectorRenderMode::Fill + ? kFillMeshRejection + : kOutlineRejection; } const rendering::VectorRenderScene& vectorScene = *layer.scene; if (renderMode == VectorRenderMode::Fill && @@ -270,7 +279,7 @@ namespace mwg::activex { if (vectorScene.fillMeshes.size() != vectorScene.polygons.size()) { - return false; + return kFillMeshRejection; } for (std::size_t index = 0; index < vectorScene.polygons.size(); @@ -280,7 +289,7 @@ namespace mwg::activex vectorScene.fillMeshes[index]; if (!mesh.has_value() || !IsMeshUsable(*mesh)) { - return false; + return kFillMeshRejection; } } } @@ -288,12 +297,23 @@ namespace mwg::activex { if (!std::isfinite(point.x) || !std::isfinite(point.y)) { - return false; + return renderMode == VectorRenderMode::Fill + ? kFillMeshRejection + : kOutlineRejection; } } } - return true; + return std::nullopt; + } + + /// Returns true when the scene has finite ring coordinates and, in + /// fill mode, one usable mesh per polygon. + [[nodiscard]] bool IsSupported( + const rendering::MapRenderScene& scene, + const VectorRenderMode renderMode) noexcept + { + return !GetSceneRejection(scene, renderMode).has_value(); } /// Draws one polygon's triangulated fill as indexed triangles through @@ -474,6 +494,68 @@ namespace mwg::activex return IsSupported(scene, renderMode); } + OpenGlVectorLayerRenderer::FillMeshReadiness + OpenGlVectorLayerRenderer::GetFillMeshReadiness( + const rendering::MapRenderScene& scene) const noexcept + { + for (const rendering::LayerRenderScene& layer : scene.layers) + { + if (layer.scene == nullptr) + { + return FillMeshReadiness::Failed; + } + const rendering::VectorRenderScene& vectorScene = *layer.scene; + if (vectorScene.polygons.empty()) + { + // A polygon-free layer needs no meshes; only a mismatched + // explicit mesh list rejects it. + if (vectorScene.fillMeshes.empty()) + { + continue; + } + return FillMeshReadiness::Failed; + } + if (!vectorScene.fillMeshes.empty()) + { + // Presence and coverage only: full mesh validation stays in + // Draw, which already falls back to GDI on unusable meshes, + // so the readiness scan stays cheap on the paint path. + if (vectorScene.fillMeshes.size() != vectorScene.polygons.size()) + { + return FillMeshReadiness::Failed; + } + continue; + } + if (_fillMeshCache == nullptr) + { + return FillMeshReadiness::Pending; + } + const auto cached = _fillMeshCache->layers.find(layer.layerId); + if (cached == _fillMeshCache->layers.end()) + { + return FillMeshReadiness::Pending; + } + if (cached->second.scene.lock() != layer.scene) + { + return FillMeshReadiness::Pending; + } + if (cached->second.failed || + cached->second.generatedMeshes.size() != vectorScene.polygons.size()) + { + return FillMeshReadiness::Failed; + } + } + return FillMeshReadiness::Ready; + } + + std::optional + OpenGlVectorLayerRenderer::GetSceneRejectionReason( + const rendering::MapRenderScene& scene, + const VectorRenderMode renderMode) noexcept + { + return GetSceneRejection(scene, renderMode); + } + OpenGlVectorLayerRenderer::~OpenGlVectorLayerRenderer() { Release(); @@ -812,6 +894,8 @@ namespace mwg::activex if (cached == _gpuBufferCache->layers.end()) { + const diagnostics::PerformanceScope uploadScope( + diagnostics::PerformanceOperation::OpenGlGpuBufferUpload); GpuBufferCache::Layer prepared; prepared.scene = scene; prepared.hasFill = needFill; @@ -1178,13 +1262,10 @@ namespace mwg::activex return {E_INVALIDARG, std::nullopt}; } - if (!IsSupported(scene, renderMode)) + if (const auto rejection = GetSceneRejection(scene, renderMode); + rejection.has_value()) { - _lastFailureReason = renderMode == VectorRenderMode::Fill - ? L"The OpenGL backend requires a triangulated fill mesh for " - L"every polygon; this frame was rendered with GDI." - : L"The OpenGL backend requires finite polygon coordinates for " - L"outline rendering; this frame was rendered with GDI."; + _lastFailureReason = *rejection; return {S_FALSE, std::nullopt}; } @@ -1582,14 +1663,6 @@ namespace mwg::activex return E_FAIL; } - if (!ResizeFramebuffer(target.width, target.height)) - { - _lastFailureReason = - L"OpenGL could not allocate a complete framebuffer for this target."; - OutputDebugStringW(L"MapWinGIS: no complete OpenGL framebuffer for this size.\n"); - return S_FALSE; - } - if (_contextInvalid) { _lastFailureReason = @@ -1817,8 +1890,6 @@ namespace mwg::activex { return S_FALSE; } - const diagnostics::PerformanceScope frameScope( - diagnostics::PerformanceOperation::FrameRender); _lastFailureReason = L"OpenGL did not render this frame."; const TargetValidation validation = ValidateTarget(deviceContext, bounds, stableScene, viewport, renderMode); @@ -1828,60 +1899,88 @@ namespace mwg::activex } const Target& target = *validation.target; - // Release a lost context once. If replacement initialization fails, - // preserve its failure state so later draws respect the retry delay. - if (_contextInvalid) { - Release(); + // Covers lost-context recovery, WGL context and framebuffer + // creation, the retry bookkeeping, and the staging allocation, + // so the frame scope below measures only rendering work. + const diagnostics::PerformanceScope contextScope( + diagnostics::PerformanceOperation::OpenGlContextInitialization); + + // Release a lost context once. If replacement initialization fails, + // preserve its failure state so later draws respect the retry delay. + if (_contextInvalid) + { + Release(); + _contextInvalid = false; + } + + if (_initializationFailed && + (target.width != _retryTargetWidth || target.height != _retryTargetHeight)) + { + // A resize is a useful retry boundary: drivers can reject one + // context/target combination yet support a later target. + Release(); + _initializationFailed = false; + _initializationFailureReason = {}; + _initializationRetryDrawsRemaining = 0; + } + if (_initializationFailed) + { + if (_initializationRetryDrawsRemaining > 0) + { + --_initializationRetryDrawsRemaining; + _lastFailureReason = _initializationFailureReason; + return S_FALSE; + } + _initializationFailed = false; + _initializationFailureReason = {}; + } + if (!Initialize()) + { + _retryTargetWidth = target.width; + _retryTargetHeight = target.height; + _initializationRetryDrawsRemaining = kInitializationRetryDraws; + return S_FALSE; + } _contextInvalid = false; - } - if (_initializationFailed && - (target.width != _retryTargetWidth || target.height != _retryTargetHeight)) - { - // A resize is a useful retry boundary: drivers can reject one - // context/target combination yet support a later target. - Release(); - _initializationFailed = false; - _initializationFailureReason = {}; - _initializationRetryDrawsRemaining = 0; - } - if (_initializationFailed) - { - if (_initializationRetryDrawsRemaining > 0) + const auto rejectionReason = GetTargetRejectionReason( + target.width, + target.height, + _maximumTargetWidth, + _maximumTargetHeight); + if (rejectionReason.has_value()) { - --_initializationRetryDrawsRemaining; - _lastFailureReason = _initializationFailureReason; + _lastFailureReason = *rejectionReason; return S_FALSE; } - _initializationFailed = false; - _initializationFailureReason = {}; - } - if (!Initialize()) - { - _retryTargetWidth = target.width; - _retryTargetHeight = target.height; - _initializationRetryDrawsRemaining = kInitializationRetryDraws; - return S_FALSE; - } - _contextInvalid = false; - const auto rejectionReason = GetTargetRejectionReason( - target.width, - target.height, - _maximumTargetWidth, - _maximumTargetHeight); - if (rejectionReason.has_value()) - { - _lastFailureReason = *rejectionReason; - return S_FALSE; - } + const std::size_t stagingBytes = + target.pixelWidth * target.pixelHeight * kBytesPerPixel; + if (!EnsureStaging(stagingBytes)) + { + return S_FALSE; + } - const std::size_t stagingBytes = - target.pixelWidth * target.pixelHeight * kBytesPerPixel; - if (!EnsureStaging(stagingBytes)) - { - return S_FALSE; + const ScopedCurrentContext currentContext( + _deviceContext, _renderingContext); + if (!currentContext.IsValid()) + { + _lastFailureReason = + L"OpenGL could not activate its rendering context."; + OutputDebugStringW( + L"MapWinGIS: could not activate the OpenGL rendering context.\n"); + _contextInvalid = true; + return E_FAIL; + } + if (!ResizeFramebuffer(target.width, target.height)) + { + _lastFailureReason = + L"OpenGL could not allocate a complete framebuffer for this target."; + OutputDebugStringW( + L"MapWinGIS: no complete OpenGL framebuffer for this size.\n"); + return S_FALSE; + } } if (renderMode == VectorRenderMode::Fill && @@ -1890,6 +1989,11 @@ namespace mwg::activex return S_FALSE; } + // The frame scope starts after mesh preparation so its breakdown does + // not double-count triangulation; it covers rendering, readback, and + // presentation. + const diagnostics::PerformanceScope frameScope( + diagnostics::PerformanceOperation::FrameRender); const HRESULT renderResult = RenderScene(stableScene, viewport, target, renderMode); if (FAILED(renderResult) || renderResult == S_FALSE) diff --git a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h index 1a38c4b..1c43590 100644 --- a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h +++ b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h @@ -84,6 +84,30 @@ namespace mwg::activex return _lastFailureReason; } + /// Reports whether Fill-mode drawing can proceed for this scene + /// without generating geometry on the calling thread. Ready means + /// every drawable layer has meshes from the scene or the cache; + /// Pending means at least one layer still needs preparation; Failed + /// means the frame must stay on GDI (a missing scene, unusable + /// meshes, or a failed triangulation). + enum class FillMeshReadiness : int + { + Ready, + Pending, + Failed + }; + + [[nodiscard]] FillMeshReadiness GetFillMeshReadiness( + const rendering::MapRenderScene& scene) const noexcept; + + /// Returns why the scene cannot be drawn in the requested mode + /// without generating geometry, or nullopt when it is drawable. + /// Does not create a context or touch the fill-mesh cache. + [[nodiscard]] static std::optional + GetSceneRejectionReason( + const rendering::MapRenderScene& scene, + VectorRenderMode renderMode) noexcept; + private: friend class testing::OpenGlVectorLayerRendererTestAccess; friend class testing::MapWinGISControlTestAccess; diff --git a/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp b/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp index cebedbf..9a0a3b0 100644 --- a/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp +++ b/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp @@ -42,26 +42,70 @@ namespace mwg::activex if (_preference != VectorRenderBackendPreference::Gdi) { - const HRESULT openGlResult = - _openGlRenderer.Draw( - deviceContext, - bounds, - stableScene, - viewport, - retainStagingBuffer, - renderMode); - if (openGlResult == S_OK) + const bool automaticFill = + _preference == VectorRenderBackendPreference::Automatic && + renderMode == VectorRenderMode::Fill; + const auto readiness = automaticFill + ? _openGlRenderer.GetFillMeshReadiness(stableScene) + : OpenGlVectorLayerRenderer::FillMeshReadiness::Ready; + + if (automaticFill && + readiness != OpenGlVectorLayerRenderer::FillMeshReadiness::Ready) { - _activeBackend = VectorRenderBackendKind::OpenGL; - _diagnostic = L"OpenGL rendered the frame successfully."; - return S_OK; + // Drawing with OpenGL here would either triangulate missing + // meshes on this thread before presenting a pixel (Pending) + // or reuse a failed preparation while triangulating other + // layers (Failed). Paint the frame with GDI instead; a later + // frame retries once every layer's meshes exist. One frame + // still uses a single backend. + if (!_openGlRenderer.PruneFillMeshCache(stableScene)) + { + _diagnostic = _openGlRenderer.GetLastFailureReason(); + } + else if ( + readiness == + OpenGlVectorLayerRenderer::FillMeshReadiness::Pending) + { + _diagnostic = + L"GDI rendered the frame; the Automatic preference " + L"paints with GDI until the OpenGL fill meshes are " + L"prepared."; + } + else + { + const auto reason = + OpenGlVectorLayerRenderer::GetSceneRejectionReason( + stableScene, renderMode); + _diagnostic = reason.has_value() + ? *reason + : L"The OpenGL backend could not triangulate a " + L"polygon for fill rendering; this frame was " + L"rendered with GDI."; + } } - - _diagnostic = _openGlRenderer.GetLastFailureReason(); - if (FAILED(openGlResult)) + else { - ::OutputDebugStringW( - L"MapWinGIS: OpenGL rendering failed; using the GDI backend.\n"); + const HRESULT openGlResult = + _openGlRenderer.Draw( + deviceContext, + bounds, + stableScene, + viewport, + retainStagingBuffer, + renderMode); + if (openGlResult == S_OK) + { + _activeBackend = VectorRenderBackendKind::OpenGL; + _diagnostic = L"OpenGL rendered the frame successfully."; + return S_OK; + } + + _diagnostic = _openGlRenderer.GetLastFailureReason(); + if (FAILED(openGlResult)) + { + ::OutputDebugStringW( + L"MapWinGIS: OpenGL rendering failed; using the GDI backend.\n"); + } } } else diff --git a/src/MapWinGIS.ActiveX/VectorLayerRenderer.h b/src/MapWinGIS.ActiveX/VectorLayerRenderer.h index 1a8f081..bf1cf28 100644 --- a/src/MapWinGIS.ActiveX/VectorLayerRenderer.h +++ b/src/MapWinGIS.ActiveX/VectorLayerRenderer.h @@ -5,8 +5,16 @@ * @brief Declares the backend coordinator for vector scene rendering. * * Tries OpenGL rendering first and uses the GDI backend for unsupported - * geometry or when OpenGL cannot be initialized. One backend draws the whole - * frame, so all layers share its viewport transform and pixel conventions. + * geometry or when OpenGL cannot be initialized. With the Automatic + * preference, a Fill-mode frame whose layers have no fill meshes yet is + * painted entirely with GDI so the paint path never triangulates; nothing + * prepares those meshes during Automatic drawing, so Fill stays on GDI + * until meshes exist — scene-provided, cached by an explicit OpenGL draw, + * or later prepared in the background — and a later frame then selects + * OpenGL again. An explicit OpenGL preference keeps drawing with OpenGL + * and triangulates lazily on the calling thread. One backend draws the + * whole frame, so all layers share its viewport transform and pixel + * conventions. */ #pragma once diff --git a/src/MapWinGIS.Core/include/mapwingis/diagnostics/PerformanceDiagnostics.h b/src/MapWinGIS.Core/include/mapwingis/diagnostics/PerformanceDiagnostics.h index d098e67..3381807 100644 --- a/src/MapWinGIS.Core/include/mapwingis/diagnostics/PerformanceDiagnostics.h +++ b/src/MapWinGIS.Core/include/mapwingis/diagnostics/PerformanceDiagnostics.h @@ -31,6 +31,8 @@ namespace mwg::diagnostics OpenGlGeometrySubmission, FrameRender, FramebufferReadback, + OpenGlGpuBufferUpload, + OpenGlContextInitialization, Count, }; diff --git a/tests/MapWinGIS.ActiveX.Tests/RenderingBaselineTests.cpp b/tests/MapWinGIS.ActiveX.Tests/RenderingBaselineTests.cpp index cfa54d6..ea90357 100644 --- a/tests/MapWinGIS.ActiveX.Tests/RenderingBaselineTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/RenderingBaselineTests.cpp @@ -15,6 +15,10 @@ #include #include +#include +#include +#include + #include #include @@ -30,6 +34,7 @@ #include #include #include +#include #include #include @@ -38,6 +43,7 @@ #include "OpenGlVectorLayerRenderer.h" #include "GdiVectorLayerRenderer.h" +#include "MapWinGIS.ActiveX_i.h" #include "TestData.h" #include "mapwingis/diagnostics/PerformanceDiagnostics.h" #include "mapwingis/gdal/GdalEnvironment.h" @@ -57,6 +63,7 @@ namespace constexpr int kTargetWidth = 1280; constexpr int kTargetHeight = 720; constexpr int kSteadyFrames = 5; + constexpr COLORREF kFillColor = RGB(61, 122, 169); using Clock = std::chrono::steady_clock; @@ -383,6 +390,142 @@ namespace HGDIOBJ _previous{}; }; + /// Initializes COM on the calling thread for the object's lifetime. + class ComApartment final + { + public: + ComApartment() noexcept + : _result(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED)) + { + } + + ~ComApartment() + { + if (SUCCEEDED(_result)) + { + CoUninitialize(); + } + } + + ComApartment(const ComApartment&) = delete; + ComApartment& operator=(const ComApartment&) = delete; + + [[nodiscard]] HRESULT Result() const noexcept { return _result; } + + private: + HRESULT _result; + }; + + /// Creates the ActiveX control through its class factory, without + /// registry registration, exactly like a COM host activates it. The + /// rendering backend preference stays at its Automatic default. + class HostedControl final + { + public: + HostedControl() + { + wchar_t executablePath[MAX_PATH]{}; + const DWORD length = GetModuleFileNameW(nullptr, executablePath, MAX_PATH); + if (length == 0 || length >= MAX_PATH) + { + return; + } + + _module = LoadLibraryW( + (std::filesystem::path(executablePath).parent_path() / L"MapWinGIS.ocx").c_str()); + if (_module == nullptr) + { + return; + } + + using GetClassObject = HRESULT(STDAPICALLTYPE*)(REFCLSID, REFIID, LPVOID*); + const auto getClassObject = reinterpret_cast( + GetProcAddress(_module, "DllGetClassObject")); + Microsoft::WRL::ComPtr factory; + if (getClassObject == nullptr || + FAILED(getClassObject( + __uuidof(MapWinGISControl), IID_PPV_ARGS(&factory))) || + FAILED(factory->CreateInstance(nullptr, IID_PPV_ARGS(&_control))) || + FAILED(_control.As(&_window)) || + FAILED(_control.As(&_viewObject))) + { + return; + } + _created = true; + } + + ~HostedControl() + { + _viewObject.Reset(); + _window.Reset(); + _control.Reset(); + if (_module != nullptr) + { + // COM checks DllCanUnloadNow before unloading. An in-flight + // asynchronous load may still own a worker or the dispatch + // window; in that case leave the module loaded for the + // process lifetime rather than crashing a later test. + using DllCanUnloadNow = HRESULT(STDAPICALLTYPE*)(); + const auto canUnload = reinterpret_cast( + GetProcAddress(_module, "DllCanUnloadNow")); + if (canUnload == nullptr || canUnload() == S_OK) + { + FreeLibrary(_module); + } + } + } + + HostedControl(const HostedControl&) = delete; + HostedControl& operator=(const HostedControl&) = delete; + + [[nodiscard]] bool IsCreated() const noexcept { return _created; } + + [[nodiscard]] const Microsoft::WRL::ComPtr& Control() const noexcept + { + return _control; + } + + [[nodiscard]] HRESULT Resize(const int width, const int height) + { + LRESULT result = 0; + return _window->OnWindowMessage( + WM_SIZE, 0, MAKELPARAM(width, height), &result); + } + + [[nodiscard]] HRESULT Draw( + const HDC target, const int width, const int height) + { + const RECTL bounds{0, 0, width, height}; + return _viewObject->Draw( + DVASPECT_CONTENT, -1, nullptr, nullptr, nullptr, target, + &bounds, nullptr, nullptr, 0); + } + + private: + HMODULE _module{}; + Microsoft::WRL::ComPtr _control; + Microsoft::WRL::ComPtr _window; + Microsoft::WRL::ComPtr _viewObject; + bool _created = false; + }; + + /// Drains the thread's dispatch queue; used to deliver the asynchronous + /// vector-load completion while polling EndLoadVectorDataset. + void PumpDispatchMessages() + { + MSG message{}; + while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE) != FALSE) + { + if (message.message == WM_QUIT) + { + PostQuitMessage(static_cast(message.wParam)); + break; + } + TranslateMessage(&message); + DispatchMessageW(&message); + } + } + class RenderingBaseline : public testing::Test { protected: @@ -409,6 +552,8 @@ namespace {PerformanceOperation::GeometryValidation, "Diagnostic geometry validation"}, {PerformanceOperation::PolygonTriangulation, "Diagnostic polygon triangulation"}, {PerformanceOperation::OpenGlGeometrySubmission, "Diagnostic OpenGL geometry submission"}, + {PerformanceOperation::OpenGlGpuBufferUpload, "Diagnostic OpenGL GPU buffer build+upload"}, + {PerformanceOperation::OpenGlContextInitialization, "Diagnostic OpenGL context initialization"}, {PerformanceOperation::FrameRender, "Diagnostic complete frame render"}, {PerformanceOperation::FramebufferReadback, "Diagnostic framebuffer readback"}}; constexpr std::pair counters[] = { @@ -437,6 +582,64 @@ namespace } } + /// Draws the first frame through the hosted control and asserts the + /// GDI-first contract: the frame presents filled content, the control + /// reports GDI as the active backend, and no polygon was + /// triangulated on the paint path. Reports the load time, the + /// first-frame time, and the diagnostic breakdown. + void ExpectGdiFirstFrameAndReport( + HostedControl& hosted, + const std::string& loadName, + const double loadMs, + const HDC surface) + { + Microsoft::WRL::ComPtr rendering; + ASSERT_EQ(hosted.Control().As(&rendering), S_OK); + + ASSERT_EQ(hosted.Resize(kTargetWidth, kTargetHeight), S_OK); + + Clock::time_point start = Clock::now(); + ASSERT_EQ(hosted.Draw(surface, kTargetWidth, kTargetHeight), S_OK); + const double firstFrameMs = ElapsedMilliseconds(start); + + ATL::CComBSTR backend; + ASSERT_EQ(rendering->get_RenderingBackend(&backend), S_OK); + ASSERT_NE(backend.m_str, nullptr); + EXPECT_EQ(std::wstring_view(backend.m_str), L"GDI"); + + const diagnostics::PerformanceSnapshot snapshot = + diagnostics::PerformanceDiagnostics::Snapshot(); + const std::int64_t triangulated = snapshot.Counter( + diagnostics::PerformanceCounter::PolygonsTriangulated); + EXPECT_EQ(triangulated, 0); + EXPECT_EQ( + snapshot.Counter( + diagnostics::PerformanceCounter::TriangulationFailures), + 0); + + std::size_t paintedSamples = 0; + for (int y = 0; y < kTargetHeight; y += 16) + { + for (int x = 0; x < kTargetWidth; x += 16) + { + paintedSamples += GetPixel(surface, x, y) == kFillColor; + } + } + EXPECT_GT(paintedSamples, 0U) + << "the first frame must present polygon fills"; + + std::wcout << L"End-to-end first frame: " << kTargetWidth << L'x' << kTargetHeight + << L" target, active backend " + << static_cast(backend.m_str) << L'\n'; + Report(loadName, loadMs, "ms"); + Report("End-to-end first presented frame", firstFrameMs, "ms"); + Report( + "End-to-end polygons triangulated on the first frame", + static_cast(triangulated), + ""); + ReportPerformanceDiagnostics(); + } + class DiagnosticCapture final { public: @@ -784,6 +987,108 @@ TEST_F(RenderingBaseline, MeasuresLazyOpenGlFillCosts) ReportPerformanceDiagnostics(); } +TEST_F(RenderingBaseline, MeasuresEndToEndFirstFrameThroughTheControl) +{ + const char* enabled = std::getenv("MWG_RUN_RENDERING_BASELINE"); + if (enabled == nullptr || std::string(enabled) != "1") + { + GTEST_SKIP() << "Set MWG_RUN_RENDERING_BASELINE=1 to measure the rendering baseline."; + } + + ComApartment apartment; + ASSERT_TRUE(SUCCEEDED(apartment.Result())); + HostedControl hosted; + ASSERT_TRUE(hosted.IsCreated()) + << "MapWinGIS.ocx could not be loaded next to the test executable."; + + DiagnosticCapture diagnostics; + const int featureCount = FeatureCountFromEnvironment(); + TempDirectory directory; + const std::filesystem::path path = + BaselineDatasetPath(directory.Path(), featureCount); + + Microsoft::WRL::ComPtr control; + ASSERT_EQ(hosted.Control().As(&control), S_OK); + + Clock::time_point start = Clock::now(); + LONGLONG layerId = 0; + ASSERT_EQ(control->LoadVectorDatasetEx(ATL::CComBSTR(path.c_str()), &layerId), S_OK); + const double loadMs = ElapsedMilliseconds(start); + ASSERT_GT(layerId, 0); + + DibSurface surface(kTargetWidth, kTargetHeight); + ASSERT_TRUE(surface.IsValid()); + ExpectGdiFirstFrameAndReport( + hosted, "End-to-end load (LoadVectorDatasetEx)", loadMs, surface.Get()); +} + +TEST_F(RenderingBaseline, MeasuresEndToEndAsyncLoadFirstFrameThroughTheControl) +{ + const char* enabled = std::getenv("MWG_RUN_RENDERING_BASELINE"); + if (enabled == nullptr || std::string(enabled) != "1") + { + GTEST_SKIP() << "Set MWG_RUN_RENDERING_BASELINE=1 to measure the rendering baseline."; + } + + ComApartment apartment; + ASSERT_TRUE(SUCCEEDED(apartment.Result())); + HostedControl hosted; + ASSERT_TRUE(hosted.IsCreated()) + << "MapWinGIS.ocx could not be loaded next to the test executable."; + + DiagnosticCapture diagnostics; + const int featureCount = FeatureCountFromEnvironment(); + TempDirectory directory; + const std::filesystem::path path = + BaselineDatasetPath(directory.Path(), featureCount); + + Clock::time_point start = Clock::now(); + LONGLONG operationId = 0; + ASSERT_EQ( + hosted.Control()->BeginLoadVectorDataset( + ATL::CComBSTR(path.c_str()), &operationId), + S_OK); + ASSERT_GT(operationId, 0); + + // EndLoadVectorDataset stays E_PENDING until the worker commits and the + // completion is delivered; pump this thread's queue to let it finalize. + VARIANT_BOOL succeeded = VARIANT_FALSE; + VARIANT_BOOL cancelled = VARIANT_TRUE; + LONGLONG layerId = 0; + BSTR summary = nullptr; + BSTR loadDiagnostics = nullptr; + HRESULT endResult = E_PENDING; + const auto deadline = Clock::now() + std::chrono::seconds(60); + while (Clock::now() < deadline) + { + endResult = hosted.Control()->EndLoadVectorDataset( + operationId, + &succeeded, + &cancelled, + &layerId, + &summary, + &loadDiagnostics); + if (endResult != E_PENDING) + { + break; + } + PumpDispatchMessages(); + Sleep(1); + } + const double loadMs = ElapsedMilliseconds(start); + ::SysFreeString(summary); + ::SysFreeString(loadDiagnostics); + ASSERT_EQ(endResult, S_OK); + EXPECT_EQ(succeeded, VARIANT_TRUE); + EXPECT_EQ(cancelled, VARIANT_FALSE); + ASSERT_GT(layerId, 0); + + DibSurface surface(kTargetWidth, kTargetHeight); + ASSERT_TRUE(surface.IsValid()); + ExpectGdiFirstFrameAndReport( + hosted, "End-to-end load (Begin/EndLoadVectorDataset)", loadMs, surface.Get()); +} + TEST_F(RenderingBaseline, MeasuresComplexPolygonCosts) { const char* enabled = std::getenv("MWG_RUN_RENDERING_BASELINE"); diff --git a/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp b/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp index 59b3ea6..bf6d11c 100644 --- a/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp @@ -175,6 +175,18 @@ namespace return MakeMapScene({MakeRectangleLayer({1.0, 1.0, 9.0, 9.0})}); } + /// A self-intersecting polygon that Core triangulation rejects, used to + /// force a cached triangulation failure. + [[nodiscard]] mwg::rendering::VectorRenderScene MakeFailingPolygonLayer() + { + return { + mwg::Extent{-3.0, -3.0, 3.0, 3.0}, + 1, + 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}}}}}; + } + /// Rebuilds the single-polygon fixture with one additional interior ring. void AddInteriorRing(mwg::rendering::MapRenderScene& scene, mwg::rendering::Ring ring) { @@ -342,6 +354,10 @@ TEST(VectorLayerRenderer, UsesOpenGlForLazyConvexPolygonWhenAvailable) ASSERT_TRUE(PatBlt(surface.Get(), 0, 0, 120, 100, BLACKNESS)); mwg::activex::VectorLayerRenderer renderer; + // The explicit OpenGL preference keeps the lazy on-draw triangulation; + // Automatic instead paints the first frame with GDI (see + // AutomaticFillPaintsGdiWhileFillMeshesArePending). + renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::OpenGL); ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); EXPECT_EQ( renderer.GetActiveBackend(), @@ -352,6 +368,305 @@ TEST(VectorLayerRenderer, UsesOpenGlForLazyConvexPolygonWhenAvailable) EXPECT_EQ(GetPixel(surface.Get(), 5, 5), GetSysColor(COLOR_WINDOW)); } +TEST(VectorLayerRenderer, AutomaticFillPaintsGdiWhileFillMeshesArePending) +{ + 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 = MakeConvexPolygonScene(); + Edit(scene.layers.front()).fillMeshes.clear(); + const mwg::Viewport viewport = FitViewport(bounds); + PerformanceCapture diagnostics; + + mwg::activex::VectorLayerRenderer renderer; + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + + // The Automatic preference must not triangulate on the paint path: the + // first frame is painted with GDI while the meshes are pending. + EXPECT_EQ(renderer.GetActiveBackend(), mwg::activex::VectorRenderBackendKind::Gdi); + EXPECT_EQ( + renderer.GetDiagnostic(), + L"GDI rendered the frame; the Automatic preference paints with GDI " + L"until the OpenGL fill meshes are prepared."); + EXPECT_EQ( + mwg::diagnostics::PerformanceDiagnostics::Snapshot().Counter( + mwg::diagnostics::PerformanceCounter::PolygonsTriangulated), + 0); + EXPECT_EQ(MapPixel(surface.Get(), viewport, 5.0, 5.0), kFill); + EXPECT_TRUE(scene.layers.front().scene->fillMeshes.empty()); +} + +TEST(VectorLayerRenderer, AutomaticFillSwitchesToOpenGlOnceFillMeshesExist) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 120, 100}; + mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); + Edit(scene.layers.front()).fillMeshes.clear(); + const mwg::Viewport viewport = FitViewport(bounds); + + 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::VectorLayerRenderer renderer; + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ(renderer.GetActiveBackend(), mwg::activex::VectorRenderBackendKind::Gdi); + + // Prime the fill-mesh cache with an explicit OpenGL draw; Automatic then + // reuses it on later frames. + renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::OpenGL); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ( + renderer.GetActiveBackend(), mwg::activex::VectorRenderBackendKind::OpenGL); + + renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::Automatic); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ( + renderer.GetActiveBackend(), mwg::activex::VectorRenderBackendKind::OpenGL); + EXPECT_EQ(renderer.GetDiagnostic(), L"OpenGL rendered the frame successfully."); +} + +TEST(VectorLayerRenderer, AutomaticFillWithSceneMeshesUsesOpenGl) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 120, 100}; + // Scene-provided meshes make the Automatic frame OpenGL-eligible + // immediately; nothing is pending. + const mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); + const mwg::Viewport viewport = FitViewport(bounds); + + // Run the probe through the coordinator itself so the assertion only + // applies where OpenGL can actually present a frame. The coordinator + // returns the successful GDI fallback's S_OK when OpenGL is unavailable, + // so the active backend decides, not the HRESULT. + mwg::activex::VectorLayerRenderer probe; + probe.SetPreference(mwg::activex::VectorRenderBackendPreference::OpenGL); + const HRESULT probeResult = + probe.Draw(surface.Get(), bounds, scene, viewport); + if (probeResult == S_FALSE || + probe.GetActiveBackend() != + mwg::activex::VectorRenderBackendKind::OpenGL) + { + 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::OpenGL); + EXPECT_EQ(renderer.GetDiagnostic(), L"OpenGL rendered the frame successfully."); +} + +TEST(VectorLayerRenderer, AutomaticFillStaysOnGdiUntilMeshesArePrepared) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 120, 100}; + mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); + Edit(scene.layers.front()).fillMeshes.clear(); + const mwg::Viewport viewport = FitViewport(bounds); + PerformanceCapture diagnostics; + mwg::activex::VectorLayerRenderer renderer; + + // Nothing prepares fill meshes during Automatic drawing today, so every + // Fill frame stays on GDI until meshes exist (Phase 2 adds background + // preparation). Pin that intended behaviour. + for (int frame = 0; frame < 3; ++frame) + { + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK) + << "frame " << frame; + EXPECT_EQ( + renderer.GetActiveBackend(), + mwg::activex::VectorRenderBackendKind::Gdi) + << "frame " << frame; + } + EXPECT_EQ( + renderer.GetDiagnostic(), + L"GDI rendered the frame; the Automatic preference paints with GDI " + L"until the OpenGL fill meshes are prepared."); + EXPECT_EQ( + mwg::diagnostics::PerformanceDiagnostics::Snapshot().Counter( + mwg::diagnostics::PerformanceCounter::PolygonsTriangulated), + 0); +} + +TEST(VectorLayerRenderer, AutomaticFillTreatsAnEmptyLayerAsReady) +{ + 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 = MakeConvexPolygonScene(); + mwg::rendering::VectorRenderScene empty; + empty.extent = {20.0, 0.0, 30.0, 10.0}; + empty.sourceFeatureCount = 0; + scene.layers.push_back({mwg::LayerId{2}, Share(std::move(empty))}); + const mwg::Viewport viewport = FitViewport(bounds); + + 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::OpenGL); + EXPECT_EQ(MapPixel(surface.Get(), viewport, 5.0, 5.0), kFill); +} + +TEST(VectorLayerRenderer, AutomaticFillDoesNotTriangulateWhenAFailedLayerPrecedesAPendingLayer) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 120, 100}; + mwg::rendering::MapRenderScene scene = MakeMapScene({ + MakeFailingPolygonLayer(), + MakeRectangleLayer({10.0, 0.0, 20.0, 10.0})}); + Edit(scene.layers[0]).fillMeshes.clear(); + Edit(scene.layers[1]).fillMeshes.clear(); + const mwg::Viewport viewport = + FitViewport(bounds, {-3.0, -3.0, 20.0, 10.0}); + PerformanceCapture diagnostics; + + // OpenGL is needed to prime a failed cache entry. + 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::diagnostics::PerformanceDiagnostics::Reset(); + + mwg::activex::VectorLayerRenderer renderer; + renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::OpenGL); + { + LogHandlerScope throwingLogHandler( + [](const mwg::LogLevel, const std::string_view) + { + throw std::runtime_error("Test GDAL logger failure"); + }); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + } + // Priming: the failing layer recorded its failed attempt; the rectangle + // triangulated successfully. + const std::int64_t primed = mwg::diagnostics::PerformanceDiagnostics::Snapshot().Counter( + mwg::diagnostics::PerformanceCounter::PolygonsTriangulated); + ASSERT_EQ(primed, 1); + + // A new mesh-free layer behind the failed one must not be triangulated + // on the Automatic paint path. + scene.layers.push_back( + {mwg::LayerId{3}, Share(MakeRectangleLayer({30.0, 0.0, 40.0, 10.0}))}); + renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::Automatic); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ( + renderer.GetActiveBackend(), mwg::activex::VectorRenderBackendKind::Gdi); + EXPECT_EQ( + renderer.GetDiagnostic(), + L"The OpenGL backend could not triangulate a polygon for fill " + L"rendering; this frame was rendered with GDI."); + EXPECT_EQ( + mwg::diagnostics::PerformanceDiagnostics::Snapshot().Counter( + mwg::diagnostics::PerformanceCounter::PolygonsTriangulated), + primed); +} + +TEST(VectorLayerRenderer, AutomaticFillDoesNotTriangulateAfterAFailedLayerSceneIsReplaced) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 120, 100}; + mwg::rendering::MapRenderScene scene = MakeMapScene({ + MakeFailingPolygonLayer(), + MakeRectangleLayer({10.0, 0.0, 20.0, 10.0})}); + Edit(scene.layers[0]).fillMeshes.clear(); + Edit(scene.layers[1]).fillMeshes.clear(); + const mwg::Viewport viewport = + FitViewport(bounds, {-3.0, -3.0, 20.0, 10.0}); + PerformanceCapture diagnostics; + + 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::diagnostics::PerformanceDiagnostics::Reset(); + + mwg::activex::VectorLayerRenderer renderer; + renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::OpenGL); + { + LogHandlerScope throwingLogHandler( + [](const mwg::LogLevel, const std::string_view) + { + throw std::runtime_error("Test GDAL logger failure"); + }); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + } + EXPECT_EQ( + mwg::diagnostics::PerformanceDiagnostics::Snapshot().Counter( + mwg::diagnostics::PerformanceCounter::PolygonsTriangulated), + 1); + + // Replacing the failed layer's scene with a fresh mesh-free one keeps the + // Automatic paint path free of triangulation. + scene.layers.front().scene = Share(MakeRectangleLayer({0.0, 0.0, 10.0, 10.0})); + renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::Automatic); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ( + renderer.GetActiveBackend(), mwg::activex::VectorRenderBackendKind::Gdi); + EXPECT_EQ( + renderer.GetDiagnostic(), + L"GDI rendered the frame; the Automatic preference paints with GDI " + L"until the OpenGL fill meshes are prepared."); + EXPECT_EQ( + mwg::diagnostics::PerformanceDiagnostics::Snapshot().Counter( + mwg::diagnostics::PerformanceCounter::PolygonsTriangulated), + 1); +} + + TEST(VectorLayerRenderer, OpenGlRecreatesLostContextOnLaterDraw) { BitmapSurface surface(120, 100); @@ -695,6 +1010,10 @@ TEST(VectorLayerRenderer, OpenGlLazyTriangulationFailureFallsBackAndPreservesOut ASSERT_EQ(probeResult, S_OK); mwg::activex::VectorLayerRenderer renderer; + // The explicit OpenGL preference drives the lazy triangulation path that + // this test exercises; Automatic would paint the pending-mesh frame with + // GDI without attempting OpenGL. + renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::OpenGL); ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); EXPECT_EQ( renderer.GetActiveBackend(), @@ -751,6 +1070,10 @@ TEST(VectorLayerRenderer, SnapshotsSceneAcrossReentrantTriangulationCallback) Edit(scene.layers.front()).fillMeshes.clear(); bool callbackRan = false; mwg::activex::VectorLayerRenderer renderer; + // The explicit OpenGL preference drives the lazy triangulation whose + // reentrant logging callback this test relies on; Automatic would paint + // the pending-mesh frame with GDI without attempting OpenGL. + renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::OpenGL); LogHandlerScope reentrantHandler( [&scene, &callbackRan, &renderer]( const mwg::LogLevel,