Skip to content

metal: optional MetalFX spatial upscaling - #2565

Closed
JoeMatt wants to merge 7 commits into
flyinghead:devfrom
Provenance-Emu:metal/pr-metalfx
Closed

JoeMatt wants to merge 7 commits into
flyinghead:devfrom
Provenance-Emu:metal/pr-metalfx

Conversation

@JoeMatt

@JoeMatt JoeMatt commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Optional MetalFX spatial upscaling for the Metal renderers, behind a CMake option that is off by default. It depends on #2563, so only the last commit is new. With USE_METALFX=OFF nothing changes: no new code is compiled and MetalFX isn't linked.

Switches. -DUSE_METALFX=ON builds it in. The rend.MetalFXUpscale setting (off by default, shown in Video settings when the Metal API is selected) turns it on. It upscales the frame to its on-screen size with MTLFXSpatialScaler instead of the bilinear/nearest present, and is meant to be used with a low internal resolution. That's a GPU saving for Macs with weaker integrated GPUs, at the cost of a scaler pass.

Where it runs.

  • The scaler runs in MetalContext::PresentFrame, in the frame's command buffer before the present render pass. It covers rend=7, rend=8 and the framebuffer path; render to texture is unaffected.
  • The output is the aspect-fitted frame rectangle in whole pixels (swapped when the frame is rotated), drawn 1:1.

Scaler cache.

  • The scaler is rebuilt when the input format, input size or output size changes (window resize, internal resolution change).
  • Duplicated frames and PresentLastFrame reuse the last result.
  • Screenshots and savestate thumbnails keep the original frame.

Availability.

  • MetalFX needs macOS 13 and a GPU that passes [MTLFXSpatialScalerDescriptor supportsDevice:].
  • The framework is weak linked and every use is behind @available, so a USE_METALFX=ON build still runs on macOS 12.
  • It falls back to the normal present when MetalFX is unsupported, when the scaler can't be created, when the frame is tiny (the 1x1 border frame shown while video output is disabled), or when the output isn't larger than the input.

A runtime-only toggle without the CMake option would also work, since the code already falls back at runtime. I kept it opt-in at build time in case you'd rather not carry it.

Testing

Run on an M2 Max (macOS 26) and an M4 Max (macOS 27), internal resolution 480 unless noted, window 1280x960.

Scaler sizes.

  • 640x480 -> 1280x960 for 3D frames.
  • 960x720 -> 1280x960 at internal 720 (rend=7 and rend=8).
  • No scaler at internal 960, where input equals output.
  • With Rotate90: 640x480 -> 960x720 (the 720x960 on-screen rect, before rotation).

Content. SA2, THPS2 and RE3 on rend=7 and rend=8. Full framebuffer emulation on rend=7. HUD text and edges are visibly sharper than with the bilinear present at 480, and close to native 960.

Validation. MTL_DEBUG_LAYER=1 clean on rend=7 and rend=8.

Builds and linking.

  • USE_METALFX=OFF: the binary has no MetalFX load command.
  • USE_METALFX=ON: MetalFX is LC_LOAD_WEAK_DYLIB.
  • Built with Xcode 26.5 and Xcode 27; the MetalFX code also compiles for x86_64.

Known gaps

  • Untested hardware: Intel/AMD Macs (whether supportsDevice: passes there is unknown) and macOS 12.
  • Scaler rebuilds. Switching between framebuffer-path frames and 3D frames of a different size rebuilds the scaler, because one configuration is cached.

🤖 Generated with Claude Code

JoeMatt and others added 4 commits October 15, 2026 22:34
Based on Isaac Marovitz's Metal backend draft, flyinghead#1787.

Adds the RenderType::Metal renderer type and the USE_METAL build option
(on by default for macOS, forced off for iOS and libretro), creates the
Metal graphics context from initRenderApi with an OpenGL fallback, and
adds a Metal choice to the video settings. The duplicate frames option
and the About page also handle Metal. The switcher is compiled as
Objective-C++ when Metal is enabled because the Metal context header
uses Objective-C types.

The SDL display metrics use SDL_Metal_GetDrawableSize for Metal windows.
mainui maps renderer types to graphics APIs with a helper so that
switching to or from Metal recreates the graphics context.

Adds the Dear ImGui Metal backend. It is the upstream v1.92.8 file
without the platform_io DrawCallback_* registrations, which the vendored
imgui 1.92.6 does not have.

The USE_METAL compile definition and the Metal sources are added with
the renderer in the next commit; until then this code is compiled out.

Also fixes two problems that kept the standalone macOS app from building
with a non-Xcode generator:

- ZLIB_LIBRARY is set to "-lz" for the Xcode generator. With Ninja the
  ZLIB::ZLIB imported target then lists "-lz" as a file dependency of the
  final link, which fails with "no known rule to make it". Only set it
  for the Xcode generator.

- Syphon declares its prefix header with target_precompile_headers
  PUBLIC, so it propagates to flycast. flycast then gets a C++-only
  precompiled header, and every .mm file fails with "Objective-C was
  disabled in precompiled file". Clear Syphon's interface precompiled
  headers; the prefix header is only meant for Syphon's own sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Native Metal renderer for the macOS SDL build, selectable as "Metal" in
the video settings. It follows the Vulkan renderer's structure: a Metal
graphics context that presents through the SDL window's CAMetalLayer,
screen and render-to-texture drawers, a pipeline and depth/stencil state
cache, a texture cache, and the Dear ImGui Metal backend for the UI.

Shaders are MSL compiled at runtime and specialised with function
constants, like the Vulkan shader variants. Framebuffer emulation and
render-to-texture readback write back to VRAM. With threaded rendering,
Render() waits for the GPU before returning, so the SH4 thread is not
released on RENDER_DONE while the frame is still being drawn. GPU waits
are bounded (200ms) so a missing completion signal drops a frame instead
of hanging the render and SH4 threads. Only a wait that actually timed
out quarantines the frame; the command buffer status switches to
Completed slightly after the shared event fires, so checking it after a
successful wait would quarantine most render-to-texture frames.

macOS specifics: constant buffer offsets are 256-byte aligned, the
packed 16-bit texture formats are expanded to RGBA8 on GPUs that don't
support them (anything that isn't an Apple GPU), and the context refuses
to start before macOS 12 (MTLSharedEvent timed waits), so initRenderApi
falls back to OpenGL there.

Apple's MacTypes.h and QuickDraw headers declare global Rect and RGBColor
types that clash with flycast's. metal_apple.h imports the Apple
frameworks with those names renamed and is included first by every Metal
header.

Resource lifetime: buffers and textures are released by dropping the
last reference. Command buffers retain what they reference, so memory is
freed once the GPU is done with it; resources are not set to
MTLPurgeableStateEmpty first, which the Metal validation layer rejects
while a command buffer still uses them. ImGui setup reads the attachment
pixel format from a 1x1 texture instead of holding one of the layer's
drawables, and the swap chain color space reference is released.

Not implemented yet: video routing (Syphon). The VMU and crosshair
overlay is added in a later commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of the Vulkan OIT renderer, selected with Metal + Per Pixel
transparent sorting (RenderType::Metal_OIT). Translucent fragments are
appended to per-pixel linked lists in a collect pass, then sorted and
blended over the opaque background in a resolve pass. Translucent
modifier volumes and two-volume polygons are supported.

The TA parser treats Metal_OIT as per-pixel, like the other OIT
renderers, so translucent polygons are not sorted per triangle.

The opaque background is copied to a texture between the collect and
resolve encoders instead of being read with [[color(0)]] framebuffer
fetch, which not every Metal implementation supports. The collect and
resolve passes use separate render encoders because Metal does not
order device-memory atomics against later draws in the same encoder.

The OIT frame is waited on before presenting: the renderer's command
pool and the context's present path use different command queues, which
Metal does not order, and without the wait the present could sample the
color attachment before the resolve finished.

Collect fragments are depth-tested in the shader before they are
appended. fs_main writes [[depth(any)]], so the hardware depth test runs
after the fragment function, when the a-buffer append (device atomics)
has already happened; relying on it let translucent geometry behind
opaque surfaces be collected and blended on top. As in the Vulkan OIT
shaders ("Manual depth testing"), the collect discards fragments that
fail GEqual against the opaque depth:

- On Apple GPUs (MTLGPUFamilyApple2 or later: programmable blending and
  memoryless render targets), the OIT pass has a second colour
  attachment, R32Float and memoryless, that the OP/PT pipelines write
  their fragment depth to; the collect reads it with [[color(1)]]
  framebuffer fetch. Every pipeline in that encoder declares the
  attachment (writeMask None where it must not write) and the resolve
  encoder detaches it. Passes after the first seed it with a full-screen
  draw from a depth copy blitted before the encoder opens.
- Elsewhere (Intel/AMD Macs), the encoder is ended after the OP/PT
  draws, the depth attachment is blitted to a sampled copy, and the
  collect reads that copy.

Two-volume translucent collects (stencil areas 1/2) use an
[[early_fragment_tests]] entry point with a depth-Always,
stencil-area-test state, so the stencil test runs before the append;
depth is still tested in the shader.

The translucent modifier volume marks, their inclusion/exclusion sums
and the resolve run in one render encoder and access the shaded pixel's
a-buffer list. Where Vulkan uses two by-region fragment-to-fragment
barriers, the shaders put the pixel buffer and head pointers in raster
order group 0 when the GPU supports raster order groups. Otherwise the
encoder uses a fragment memory barrier on Intel/AMD GPUs, where it is
valid, or is ended and reopened at each ordering point.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of VulkanOverlay. The overlay is drawn by the Metal context after
the frame and before ImGui, so both Metal renderers get it. A VMU texture
is recreated when its screen changes rather than updated in place, since
a frame still in flight may be sampling it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings October 16, 2026 21:37

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

With rend.EmulateFramebuffer on, Present() shows the frame read back from
VRAM (presentFramebuffer), but MetalOITScreenDrawer::EndFrame never wrote the
rendered frame there, so the per-pixel renderer presented black frames. The
regular Metal renderer was fine.

Do what Vulkan's OITScreenDrawer::EndFrame does: when emulating the
framebuffer, call scaleAndWriteFramebuffer on the attachment just rendered,
before the ping-pong index advances. scaleAndWriteFramebuffer and its cached
readback textures move from MetalScreenDrawer to MetalBaseDrawer (Vulkan keeps
it on BaseDrawer) so both screen drawers share it. The copies are now also
bounded by the source texture, since the OIT attachments are sized from the
drawer viewport rather than globClip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
JoeMatt and others added 2 commits October 16, 2026 19:14
OITMetalRenderer::Render never called resize(), so the OIT screen
drawer kept BaseMetalRenderer's 640x480 default viewport. Per-pixel
mode ignored rend.Resolution, and under EmulateFramebuffer a PVR
framebuffer that isn't 640x480 was rendered into 640x480.

Port OITVulkanRenderer::resize: Render() resizes to
framebufferWidth/Height, and the override grows the a-buffer (one
head pointer per pixel) and re-inits the screen drawer.

The screen drawer's attachments only ever grew, but it presents and
reads back the whole color attachment, so a smaller viewport now
drops them and MakeBuffers reallocates them at the exact size.

MakeBuffers grows the shared OIT buffers before its early return,
like Vulkan OITDrawer::MakeBuffers, and the first-frame head-pointer
clear covers the whole buffer instead of the current pass's w*h.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add a CMake option, USE_METALFX (off by default), that builds the Metal
renderer with MetalFX spatial upscaling, and a setting,
rend.MetalFXUpscale (off by default), that turns it on. It upscales the
rendered frame to its on-screen size with the MetalFX spatial scaler
instead of the bilinear/nearest present, and is meant to be used with a
low internal resolution.

The scaler runs in MetalContext::PresentFrame, in the frame's command
buffer before the present render pass, so it covers the per-triangle and
per-pixel renderers and the framebuffer path. Render-to-texture passes
are not affected. The output size is the aspect-fitted frame rectangle
in whole pixels (swapped when the frame is rotated) and the result is
drawn 1:1. The scaler is recreated when the input format, input size or
output size changes, which covers window resizes and internal
resolution changes. Duplicated frames and PresentLastFrame reuse the
last upscaled texture. Screenshots and savestate thumbnails still use
the original frame.

MetalFX needs macOS 13 and a supported GPU
(MTLFXSpatialScalerDescriptor supportsDevice:). The framework is weak
linked and every use is behind @available, so the renderer still runs
on macOS 12. When MetalFX is unsupported, the scaler can't be created,
the frame is tiny (such as the 1x1 border color frame shown when video
output is disabled) or the output isn't larger than the input, the
frame is presented as before.

The setting is shown in the video settings when the Metal API is
selected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@JoeMatt

JoeMatt commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

Folded into #2563 as a commit there, so it's one PR instead of three stacked ones.

@JoeMatt JoeMatt closed this Oct 17, 2026
@JoeMatt
JoeMatt deleted the metal/pr-metalfx branch October 17, 2026 05:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants