Skip to content

Metal renderer for macOS (per-triangle + OIT) - #1

Closed
JoeMatt wants to merge 6 commits into
devfrom
metal/backend-v1
Closed

JoeMatt wants to merge 6 commits into
devfrom
metal/backend-v1

Conversation

@JoeMatt

@JoeMatt JoeMatt commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

A native Metal renderer for the macOS SDL build, in both flavours flycast has for its other APIs: per-triangle sorting (RenderType::Metal) and per-pixel order-independent transparency (RenderType::Metal_OIT). It runs on macOS 12 and later, on Apple Silicon and on Intel/AMD Macs. Older systems fall back to OpenGL.

This builds on Isaac Marovitz's Metal backend draft, flyinghead#1787. The integration points (renderer type, build option, context creation, settings UI, ImGui Metal backend) follow that draft.

What's in it

Four commits, each one builds on its own:

  1. metal: Metal renderer integration for macOS. Adds the USE_METAL option (on for macOS, forced off for iOS and libretro), the renderer types, Metal context creation in initRenderApi with an OpenGL fallback, the settings UI entries, and the Dear ImGui Metal backend. It also fixes the non-Xcode (Ninja/Makefiles) macOS build: -lz was treated as a file dependency, and Syphon's C++-only prefix header leaked into flycast's .mm files.
  2. metal: Metal renderer. The per-triangle renderer. It follows the Vulkan renderer's structure: context and swap chain on the SDL CAMetalLayer, screen and RTT drawers, pipeline and depth/stencil state caches, a texture cache, and runtime-compiled MSL specialised with function constants. Framebuffer emulation and RTT readback write back to VRAM.
  3. metal: per-pixel (OIT) renderer. A port of the Vulkan OIT renderer: per-pixel linked lists, collect and resolve passes, translucent modifier volumes, and two-volume polygons. On Apple GPUs the opaque depth stays in tile memory (a memoryless R32Float attachment read with framebuffer fetch). Intel/AMD GPUs use a depth copy instead.
  4. metal: VMU screens and lightgun crosshairs. A port of VulkanOverlay, drawn by the context, so both renderers get it.

Fixed beyond the original draft

  • OIT collect fragments are now depth-tested in the shader before the a-buffer append, like the Vulkan OIT's "manual depth testing". Before this, translucent geometry behind opaque surfaces was collected and blended on top, because [[depth(any)]] moves the hardware test after the fragment function. Two-volume collects use an early-fragment-tests entry point so the stencil-area test also runs before the append.
  • The OIT frame is waited on before presenting. The renderer's command pool and the present path use different command queues, which Metal doesn't order against each other, so the present could sample the attachment before the resolve finished. This showed up as a flickering translucent layer.
  • Released buffers and textures are no longer set to MTLPurgeableStateEmpty while a command buffer still uses them. The validation layer asserts on that. A double delete in GetMainBuffer is also fixed.
  • Render-to-texture frames are quarantined only when the GPU wait actually timed out. Before, almost every RTT frame was quarantined, because the command buffer status turns Completed slightly after the shared event fires.
  • ImGui setup no longer holds one of the layer's drawables without presenting it.
  • The swap chain color space reference is released instead of leaking on every CreateSwapChain.
  • GPU waits are bounded at 200 ms, so a missing completion signal drops a frame instead of hanging the render and SH4 threads.
  • On GPUs that don't support the packed 16-bit texture formats (anything that isn't an Apple GPU), those formats are expanded to RGBA8.

Testing

  • Tony Hawk's Pro Skater 2, Sonic Adventure 2 and Resident Evil 3 on both Metal renderers on an M2 Max (macOS, standalone SDL build). In THPS2 the shadows render correctly, and translucent geometry behind opaque surfaces (the helicopter rotor behind the ramp) is no longer drawn on top. The tile-memory and depth-copy OIT paths produce pixel-identical frames.
  • Run with the Metal API validation layer enabled: no validation errors.
  • A standalone arm64 Ninja build with USE_VULKAN=OFF links and runs. The universal (x86_64 + arm64) Xcode build compiles.
  • The same renderer code also runs on iOS and tvOS devices in a separate app. The iOS/tvOS host integration isn't part of this PR, but the TARGET_OS_* paths in the renderer come from there.

Known gaps

  • No Syphon video routing for Metal yet.
  • No swap-interval (vsync) override.
  • No MetalFX upscaling.

🤖 Generated with Claude Code


Note

High Risk
Large new GPU renderer plus modem/network and disc-read behavior changes affect core emulation paths on macOS and online play.

Overview
Adds a native Metal graphics path for macOS SDL builds: new USE_METAL / RenderType::Metal (+ OIT variant), renderer registration, SDL Metal window metrics, Dear ImGui Metal backend, and a full core/rend/metal/ stack (context/swapchain, screen + RTT drawers, pipelines, command-pool lifecycle with bounded GPU waits, texture cache, overlay). Build fixes gate -lz to the Xcode generator and stop Syphon’s PCH from breaking flycast .mm compilation.

Separate from rendering, the PR also enables Capcom peer-to-peer modem mode by routing synchronous HDLC through a new HdlcSyncAsync bridge (with V.42 disconnect/CRC tweaks) and simplifying Capcom Direct ICE I/O; GD-ROM read gains 2336→2340 conversion (Bleemcast) with synthesized sector headers.

Reviewed by Cursor Bugbot for commit 307ce35. Configure here.

flyinghead and others added 6 commits October 14, 2026 13:20
Let peers exchange V.42 frames instead of implementing the protocol
locally so that error correction works end to end.
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.

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 02:48
@qodo-code-review

Copy link
Copy Markdown

ⓘ Qodo reviews are paused because the subscription is no longer active. Ask your workspace admin to reactivate the subscription to resume reviews. Manage billing

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.

@cursor

cursor Bot commented Oct 16, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: 6e461522-7b9d-41a6-9af1-59236a81aec5)

@JoeMatt

JoeMatt commented Oct 17, 2026

Copy link
Copy Markdown
Member Author

Superseded by the upstream Metal PR flyinghead#2563 on the main flycast repo.

@JoeMatt JoeMatt closed this Oct 17, 2026
@JoeMatt
JoeMatt deleted the metal/backend-v1 branch October 17, 2026 05:11
JoeMatt added a commit that referenced this pull request Oct 22, 2026
… logs

AUDIO (#1): the internal-UI mute set config::AudioVolume=0. flycast's
settings-close SaveSettings() iterates ALL options and writes each to emu.cfg —
so closing the internal settings while muted persisted volume=0 to disk,
leaving audio permanently silent across relaunches ("audio mutes after opening
the internal settings UI"). Replaced with a transient mute: a static
std::atomic<bool> s_audioMuted in audiostream.cpp; WriteSample emits zeros when
set; SetAudioMuted(bool) flips it. config::AudioVolume is never touched, so
nothing persists. The iFly bridge (flycast_set_audio_enabled) now calls
SetAudioMuted instead of zeroing the volume. (Note: with threaded rendering
currently off, emu.stop() already silences via TermAudio, so the mute is mostly
vestigial today — but this keeps it correct for when threaded rendering returns,
without the data-loss.)

METAL (flyinghead#6): removed 5 INFO_LOG calls from the per-polygon texture-binding path
in metal_drawer.mm (fired every poly every frame). ERROR_LOG paths kept.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
JoeMatt added a commit that referenced this pull request Oct 22, 2026
WriteMemBlock_nommu_dma is the #1 open Bugsnag crash again — 78 events across
21 users, first seen 2026-08-27, EXC_BAD_ACCESS on a garbage pointer inside
__platform_memmove. The stack is unambiguous: RenderLoopThread → display link →
RenderFrameDriver.tick() → WriteMemBlock_nommu_dma → memmove, ~13s into the
session, i.e. during boot.

The July 2026 root-cause work (52230c8) identified the mechanism — a game
reload or platform switch frees mem_b/vram/aica_ram while memInfo_ptr still
encodes the old host base, so writeConst/readConst hand back dangling pointers —
and added isLiveMemPtr guards. It guarded the dst_ismem && src_ismem branch and
WriteMemBlock_nommu_ptr's own destination. It missed the middle branch:

    else if (src_ismem)
        WriteMemBlock_nommu_ptr(dst, (u32*)src_ptr, size);

src_ptr comes straight from readConst and is exactly as stale-able as the
dst_ptr guarded one branch above, but nothing checks it. WriteMemBlock_nommu_ptr
validates only its destination, and says why in its own comment: "`src` is
already a host pointer here, so only the destination needs bounding." That is
true of its other callers, which pass real host buffers. It is false of this
caller.

So the guard belongs at this call site, not inside WriteMemBlock_nommu_ptr —
moving it there would reject the other callers' legitimate non-guest buffers,
which correctly lie outside every guest region.

The size clamp at the top of the function does not already cover this. It bounds
both extents via memRegionBytesLeft, which derives from memInfo_ptr — the same
structure that goes stale — so a freed region still reports a plausible
bytes-left. Only isLiveMemPtr distinguishes live from freed.

Not claimed: that this closes the whole cluster. addrspace::write32/64 (40 and 8
events) still reach freed memory through writet<T> on the hot path, which the
July notes flagged as needing the real lifecycle fix — quiesce/serialize DMA and
clear-or-repoint memInfo_ptr across teardown — rather than another point guard.
A TOCTOU race also remains possible on every one of these guards, since teardown
can run on another thread between the check and the copy.

Not built or benched here — Joe rebuilds the xcframework in Xcode.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
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.

3 participants