core/opengl: port filter dim cache from D3D backends

OpenGL parity port of the filter dim cache that landed for D3D12
in 10c53b8 and for D3D11 in 00cf11f. Same motivation: after
418eb14 the cbuffer-refactor series made resolution_scale /
true_color / scaled_dithering toggles instant on OpenGL, but a
texture_filter flip still drove CompilePrograms and walked the
144-cell batch program matrix from scratch in Enabled precompile
mode, or worse, dropped the previous filter's compiled programs
and re-compiled them on the runloop the next time the user
flipped back.

Add GPUTextureFilter::Count (7) as the outermost dimension of
m_render_programs:

  std::array<...<GL::Program, 2>, 2>, 9>, 4>, 7>
                                          ^
                                       filter

(OpenGL keeps its existing nested-std::array style rather than
switching to DimensionalArray, matching the D3D11 dim-cache port
at 00cf11f; D3D12 uses DimensionalArray, but the indexing
semantics are the same.)

GetBatchProgram gains a GPUTextureFilter filter parameter as the
first argument, indexes m_render_programs with [filter_idx][...],
and constructs a per-call GPU_HW_ShaderGen against the requested
filter rather than reusing m_shadergen. The single-threaded GL
context never reaches the helper with a non-current filter
today, but the per-call shadergen keeps the API symmetric with
the D3D / Vulkan ports and future-proofs the helper if a worker
ever gets added (or if pre-baked GLSL ever wants to land here
the way pre-baked SPIR-V did for Vulkan). The
'GetBatchProgram called before CompilePrograms constructed the
shadergen' defensive check is dropped for the same reason - the
per-call shadergen has no dependency on the lifetime of
m_shadergen.

CompilePrograms gains a new clear_existing_render_programs
parameter (default true). On the only_dim_changed fast path
UpdateSettings passes false, so the previously-built filter
sub-cubes are preserved instead of being walked and reset to
default-constructed GL::Programs (which would glDeleteProgram
each one and force a fresh link on the next visit). The
precompile_sync loop walks just the current filter's sub-cube
- snapshots cur_filter = m_texture_filtering once and uses it
for every GetBatchProgram call inside the loop, matching the
D3D11 / D3D12 / Vulkan precompile patterns. Slots that were
already populated by a previous visit short-circuit on
IsValid() in GetBatchProgram and return without doing any work;
empty slots (first visit to this filter) get compiled.

CompilePrograms's clear loop gains a fifth level of nesting to
walk the new 5-D shape when clear_existing_render_programs is
true.

DrawBatchVertices passes m_texture_filtering as the first arg to
GetBatchProgram so the lookup hits the active sub-cube.

UpdateSettings's rebuild gate stays a single-branch
'if (shader_source_changed) CompilePrograms(...)' but the call
now takes the only_dim_changed-derived flag:

  if (shader_source_changed)
    CompilePrograms(/*clear_existing_render_programs=*/!only_dim_changed);

Cycling back to a previously-visited filter (Nearest -> Bilinear
-> Nearest) is now a slot-validity walk on OpenGL in any
precompile mode - the second Nearest hit walks the precompile_sync
loop, every cell short-circuits on IsValid(), no shader compile,
no program link. A fresh-cold filter flip (first time visiting
Bilinear) still pays the full matrix walk to populate the new
sub-cube, but the OLD filter's programs stay alive in their
slots and are reachable the moment the user flips back.

Cost matrix after this patch (OpenGL,
shader_precompile_mode = Enabled, 144 batch program cells):

  Toggle                  Before        After this patch
  texture_filter (cold)   ~5-15 sec     ~5-15 sec (necessary,
                                        new sub-cube)
  texture_filter (warm)   ~5-15 sec     instant (IsValid() walk)
  resolution_scale        zero          unchanged
  true_color              zero          unchanged
  scaled_dithering        zero          unchanged
  multisamples            ~5-15 sec     unchanged (necessary -
                                        invalidates every filter
                                        sub-cube)
  per_sample_shading      ~5-15 sec     unchanged (necessary)
  uv_limits               ~5-15 sec     unchanged (necessary)
  pgxp_depth              ~5-15 sec     unchanged (necessary)
  disable_color_persp.    ~5-15 sec     unchanged (necessary)
  chroma_smoothing        ~5-15 sec     unchanged (suboptimal,
                                        splittable as a follow-up
                                        analogous to 57ac62e /
                                        93e5db5)
  shader_precompile_mode  ~5-15 sec     unchanged (intentional)

OpenGL's absolute cost is on par with D3D11 (same 144-cell matrix,
similar link cost per cell). The relative improvement on warm
filter cycling is the same as the D3D11 / D3D12 / Vulkan ports.

Test:
  - OpenGL, shader_precompile = Enabled. First boot: matrix walks
    only Nearest's sub-cube. Program compile count and progress
    bar match pre-patch.
  - Toggle texture filter Nearest -> Bilinear: precompile_sync
    walks Bilinear's sub-cube, Bilinear programs link for the
    first time. Old Nearest sub-cube stays populated.
  - Toggle back Bilinear -> Nearest: precompile_sync loop hits
    every Nearest slot on its IsValid() fast path and returns
    instantly. No GL_FRAGMENT_SHADER compile, no glLinkProgram,
    no progress OSD spike.
  - Toggle Nearest -> Bilinear again: every Bilinear slot is
    already populated. Instant.
  - Toggle resolution scale / true_color / scaled_dithering:
    still pays zero per 418eb14, unchanged.
  - Toggle MSAA / per_sample / UV limits / PGXP depth / colour
    perspective: CompilePrograms with clear_existing=true wipes
    all sub-cubes, full rebuild walks the current filter's sub-
    cube. Same cost as pre-patch.
  - shader_precompile_mode = Lazy / Disabled: GetBatchProgram
    faults each cell on first draw, same as before. Filter
    toggle doesn't clear previously-visited sub-cubes; revisits
    are instant once the cells are populated.
This commit is contained in:
LibretroAdmin 2026-05-18 05:34:25 +00:00 • committed by U-DESKTOP-SPFP6AQ\twistedtechre
commit f8b4a41bd9
2 changed files with 99 additions and 25 deletions

View file

@ -798,8 +798,17 @@ void GPU_HW_OpenGL::UpdateSettings()
// CompilePrograms (which would otherwise relink every program in
// the batch matrix). The new values ride the per-batch UBO
// upload on the next FlushRender.
bool framebuffer_changed, shaders_changed, shader_source_changed;
UpdateHWSettings(&framebuffer_changed, &shaders_changed, nullptr, nullptr, &shader_source_changed);
//
// only_dim_changed: dim-cube setting (filter / true_color /
// scaled_dithering) changed and nothing in non_dim_diff. With
// the dim cache (filter outermost) this means "filter sub-cube
// can be lazy-populated, other filters' sub-cubes stay valid".
// CompilePrograms takes a clear_existing_render_programs flag so
// this path can call through without throwing away the previous
// filter's compiled programs. Mirrors the D3D11 / D3D12 / Vulkan
// dim-cache fast paths.
bool framebuffer_changed, shaders_changed, only_dim_changed, shader_source_changed;
UpdateHWSettings(&framebuffer_changed, &shaders_changed, &only_dim_changed, nullptr, &shader_source_changed);
if (framebuffer_changed)
{
@ -810,7 +819,13 @@ void GPU_HW_OpenGL::UpdateSettings()
CreateFramebuffer();
}
if (shader_source_changed)
CompilePrograms();
{
// only_dim_changed: filter (and/or cbuffer-only members) changed
// but nothing in non_dim_diff. Preserve previously-visited
// filter sub-cubes so the user can cycle filters without paying
// the recompile cost more than once per filter.
CompilePrograms(/*clear_existing_render_programs=*/!only_dim_changed);
}
if (framebuffer_changed)
{
@ -1058,7 +1073,7 @@ bool GPU_HW_OpenGL::CreateTextureBuffer()
return true;
}
bool GPU_HW_OpenGL::CompilePrograms()
bool GPU_HW_OpenGL::CompilePrograms(bool clear_existing_render_programs)
{
// Reset every program object so the new compile starts from a
// clean slate. Without this, on an UpdateSettings round-trip
@ -1075,11 +1090,26 @@ bool GPU_HW_OpenGL::CompilePrograms()
// destination before taking the source's state, so default-
// assigning each slot to a temporary {} both glDeleteProgram's
// the old handle and rewinds the slot to id = 0.
for (auto& a : m_render_programs)
for (auto& b : a)
for (auto& c : b)
for (auto& slot : c)
slot = GL::Program{};
//
// clear_existing_render_programs=false is the dim-cache fast
// path: UpdateSettings on a filter-only flip passes false so
// the previous filter's sub-cube (and any other filter sub-
// cubes the user has visited this session) keep their compiled
// programs. The precompile_sync loop below walks only the new
// filter's sub-cube; slots that were already populated by a
// previous visit short-circuit on IsValid() in GetBatchProgram,
// empty slots get compiled. 5-level nesting matches the
// [filter][render_mode][texture_mode][dithering][interlacing]
// shape of m_render_programs added in the dim cache port.
if (clear_existing_render_programs)
{
for (auto& a : m_render_programs)
for (auto& b : a)
for (auto& c : b)
for (auto& d : c)
for (auto& slot : d)
slot = GL::Program{};
}
// Open the disk-backed program cache once. On subsequent calls
// (UpdateSettings -> CompilePrograms) the instance still holds
@ -1121,6 +1151,15 @@ bool GPU_HW_OpenGL::CompilePrograms()
if (precompile_sync)
{
// The dim cache makes m_render_programs filter-dimensioned.
// precompile_sync walks ONLY the current m_texture_filtering
// sub-cube, not the full 7-filter matrix - pre-filling six
// unused sub-cubes would multiply the cold-cache GLSL compile
// pass by 7x for no gain (the game can only be running under
// one filter at a time, and the other sub-cubes get faulted
// in on demand if the user later flips the filter setting and
// UpdateSettings calls CompilePrograms again).
const GPUTextureFilter cur_filter = m_texture_filtering;
for (uint8_t render_mode = 0; render_mode < 4; render_mode++)
{
for (uint8_t texture_mode = 0; texture_mode < 9; texture_mode++)
@ -1129,7 +1168,7 @@ bool GPU_HW_OpenGL::CompilePrograms()
{
for (uint8_t interlacing = 0; interlacing < 2; interlacing++)
{
const GL::Program* prog = GetBatchProgram(render_mode, texture_mode, static_cast<bool>(dithering),
const GL::Program* prog = GetBatchProgram(cur_filter, render_mode, texture_mode, static_cast<bool>(dithering),
static_cast<bool>(interlacing));
if (!prog)
return false;
@ -1286,7 +1325,7 @@ bool GPU_HW_OpenGL::CompilePrograms()
return true;
}
const GL::Program* GPU_HW_OpenGL::GetBatchProgram(uint8_t render_mode, uint8_t texture_mode, bool dithering, bool interlacing)
const GL::Program* GPU_HW_OpenGL::GetBatchProgram(GPUTextureFilter filter, uint8_t render_mode, uint8_t texture_mode, bool dithering, bool interlacing)
{
// Reserved_*Direct16Bit dedup. The fragment shader source for
// texture_mode 3 / 7 is byte-for-byte identical to 2 / 6 after
@ -1300,20 +1339,31 @@ const GL::Program* GPU_HW_OpenGL::GetBatchProgram(uint8_t render_mode, uint8_t t
const uint8_t lookup_mode = (texture_mode == static_cast<uint8_t>(GPUTextureMode::Reserved_Direct16Bit)) ? 2u :
(texture_mode == static_cast<uint8_t>(GPUTextureMode::Reserved_RawDirect16Bit)) ? 6u :
texture_mode;
const uint8_t filter_idx = static_cast<uint8_t>(filter);
GL::Program& slot = m_render_programs[render_mode][texture_mode][static_cast<uint8_t>(dithering)][static_cast<uint8_t>(interlacing)];
GL::Program& slot = m_render_programs[filter_idx][render_mode][texture_mode][static_cast<uint8_t>(dithering)][static_cast<uint8_t>(interlacing)];
if (slot.IsValid())
return &slot;
if (!m_shadergen)
{
Log_ErrorPrint("GetBatchProgram called before CompilePrograms constructed the shadergen");
return nullptr;
}
// Construct a per-call shadergen bound to the requested filter.
// m_shadergen exists for the non-batch programs below
// CompilePrograms and is bound to the runtime-current
// m_texture_filtering. With the dim cache the batch slot we're
// building may be for a filter different from m_texture_filtering
// (when CompilePrograms walks a freshly-toggled filter's sub-cube
// before any draw has run, the runtime is still on the new
// filter, but the contract is to use the explicit filter
// parameter so the cache stays consistent with what would happen
// if a non-current sub-cube were faulted in some other way -
// and to mirror what D3D11 / D3D12 do).
GPU_HW_ShaderGen tmp_shadergen(
m_host_display->GetRenderAPI(), m_resolution_scale, m_multisamples, m_per_sample_shading, m_true_color,
m_scaled_dithering, filter, m_using_uv_limits, m_pgxp_depth_buffer, m_disable_color_perspective,
m_supports_dual_source_blend);
const bool textured = (static_cast<GPUTextureMode>(lookup_mode) != GPUTextureMode::Disabled);
const std::string batch_vs = m_shadergen->GenerateBatchVertexShader(textured);
const std::string fs = m_shadergen->GenerateBatchFragmentShader(
const std::string batch_vs = tmp_shadergen.GenerateBatchVertexShader(textured);
const std::string fs = tmp_shadergen.GenerateBatchFragmentShader(
static_cast<BatchRenderMode>(render_mode), static_cast<GPUTextureMode>(lookup_mode), dithering, interlacing);
const bool use_binding_layout = m_use_binding_layout;
@ -1347,7 +1397,8 @@ const GL::Program* GPU_HW_OpenGL::GetBatchProgram(uint8_t render_mode, uint8_t t
std::optional<GL::Program> prog = m_shader_cache.GetProgram(batch_vs, {}, fs, link_callback);
if (!prog)
{
Log_ErrorPrintf("Lazy batch program compile failed for (rm=%u, tm=%u, d=%u, i=%u)", render_mode, texture_mode,
Log_ErrorPrintf("Lazy batch program compile failed for (f=%u, rm=%u, tm=%u, d=%u, i=%u)",
static_cast<uint8_t>(filter), render_mode, texture_mode,
static_cast<uint8_t>(dithering), static_cast<uint8_t>(interlacing));
return nullptr;
}
@ -1375,7 +1426,13 @@ void GPU_HW_OpenGL::DrawBatchVertices(BatchRenderMode render_mode, uint32_t base
// combination, then cached. Single-threaded - no mutex / no
// atomic - because the libretro hardware-renderer protocol only
// gives us one GL context bound to this thread.
const GL::Program* prog = GetBatchProgram(static_cast<uint8_t>(render_mode), static_cast<uint8_t>(m_batch.texture_mode),
//
// m_texture_filtering selects the active filter's sub-cube. Filter
// is the outermost dim so a filter toggle in UpdateSettings can
// skip the CompilePrograms round trip - the other filters' sub-
// cubes remain valid and reachable, switching back to a previously-
// visited filter is a slot validity check.
const GL::Program* prog = GetBatchProgram(m_texture_filtering, static_cast<uint8_t>(render_mode), static_cast<uint8_t>(m_batch.texture_mode),
m_batch.dithering, m_batch.interlacing);
if (!prog)
return;

View file

@ -138,7 +138,7 @@ private:
bool CreateUniformBuffer();
bool CreateTextureBuffer();
bool CompilePrograms();
bool CompilePrograms(bool clear_existing_render_programs = true);
// Lazy batch-program compile path. The libretro hardware-renderer
// protocol gives us a single GL context bound to the runloop
@ -155,7 +155,24 @@ private:
// applying the Reserved_*Direct16Bit dedup at the matrix level
// by re-linking the program from the canonical mode's source
// string (the shader cache makes the second link cheap).
const GL::Program* GetBatchProgram(uint8_t render_mode, uint8_t texture_mode, bool dithering, bool interlacing);
//
// filter is the outermost cache dimension. With the cbuffer-
// refactor patch (7b575a3) the GLSL is invariant under
// resolution_scale / true_color / scaled_dithering, but it is
// STILL dependent on texture filter - the FilteredSampleFromVRAM
// helper is emitted differently for Nearest / Bilinear / JINC2 /
// xBR / the BinAlpha variants. Dimensioning the cache over
// filter lets a filter toggle skip the DestroyShaders-equivalent
// CompilePrograms round trip in UpdateSettings: the previous
// filter's sub-cube remains valid and reachable, switching back
// to it later is just a slot validity check. Mirrors the D3D12
// / D3D11 dim caches from 10c53b8 / 00cf11f and the Vulkan dim
// cache from the glslang-elimination series. The slow-path
// shadergen is rebuilt per-call against the requested filter
// so the helper stays consistent with its sibling backends even
// though the single-threaded GL context never reaches it with a
// non-current filter today.
const GL::Program* GetBatchProgram(GPUTextureFilter filter, uint8_t render_mode, uint8_t texture_mode, bool dithering, bool interlacing);
void SetDepthFunc();
void SetDepthFunc(GLenum func);
@ -184,8 +201,8 @@ private:
std::unique_ptr<GL::StreamBuffer> m_texture_stream_buffer;
GLuint m_texture_buffer_r16ui_texture = 0;
std::array<std::array<std::array<std::array<GL::Program, 2>, 2>, 9>, 4>
m_render_programs; // [render_mode][texture_mode][dithering][interlacing]
std::array<std::array<std::array<std::array<std::array<GL::Program, 2>, 2>, 9>, 4>, 7>
m_render_programs; // [filter][render_mode][texture_mode][dithering][interlacing]
std::array<std::array<GL::Program, 3>, 2> m_display_programs; // [depth_24][interlaced]
std::array<std::array<GL::Program, 2>, 2> m_vram_fill_programs;
GL::Program m_vram_read_program;