Skip to content

Metal renderer for macOS - #2563

Merged
flyinghead merged 20 commits into
flyinghead:devfrom
Provenance-Emu:metal/pr-backend
Dec 3, 2026
Merged

flyinghead merged 20 commits into
flyinghead:devfrom
Provenance-Emu:metal/pr-backend

Conversation

@JoeMatt

@JoeMatt JoeMatt commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

A native Metal renderer for the macOS SDL build, with per-triangle/per-strip sorting (RenderType::Metal, rend=7) and per-pixel OIT (RenderType::Metal_OIT, rend=8). It picks up Isaac Marovitz's draft #1787 and targets dev.

Metal requires macOS 12. Older macOS versions show an explanation and fall back to OpenGL. CMake keeps Metal disabled for iOS and libretro in this submission. VMU screens, lightgun crosshairs, framebuffer emulation, resolution changes and Syphon output are included.

MetalFX has been removed from this PR and preserved for a separate follow-up.

Review fixes

  • Both geometry uploaders now use GetMainBuffer(). Each upload gets exclusive storage, including multiple uploads in one command buffer. The command pool returns it only after completion; timed-out slots stay quarantined. Shutdown retains the existing bounded-wait policy and deliberately leaks still-busy holders rather than recycling their storage.
  • Rendering, RTT, framebuffer upload and presentation use one command queue. GPU ordering no longer depends on a successful CPU wait or ThreadedRendering. The regular screen drawer uses one persistent target instead of allocating three while always selecting slot zero. Quad vertices use setVertexBytes, so subsequent quads cannot overwrite an earlier draw's vertices.
  • Screen framebuffers are cleaned up before the command pool is terminated. Pool termination resets the slot index and frame-started state.
  • Naomi 2 lights are individually aligned to the binding stride. OIT bindings use the same constant-buffer alignment as the packer. Modifier-volume matrices are bound per volume in the regular and OIT paths, including after an OIT encoder split.
  • RTT readback uses the attachment just rendered. Framebuffer writeback uses a linear-filtered render pass when the PVR scaler changes the output size.
  • Consecutive OIT screen renders keep the same color attachment and respect clearFramebuffer. Each new OIT encoder invalidates its scissor cache.
  • Completed custom-texture loads are applied, and Metal registers its decoded-RGBA texture capabilities and dimension limit.
  • Presentation uses getWindowboxDimensions() and getVideoShift().
  • PerPixelLayers controls the resolve and translucent modifier-volume shader limits, clamped to 8–128. Changing it rebuilds the affected OIT library and pipelines.
  • The initial viewport depth range is 0–1, addressing the Intel macOS 12 failure identified in review. About now reports the OS-supplied Metal driver's OS version string.

Intel/AMD hardware follow-up

  • The full application reproduced a Metal validation abort during BIOS startup on Intel UHD 630: shared storage is not supported for textures. CPU-visible textures now select shared or managed storage from the selected GPU's Metal family at runtime, including RTT targets. Managed RTT textures are synchronized before CPU readback. Packed 16-bit format support also uses the selected GPU's capabilities.
  • Native x86_64 compilation exposed an include-order failure when Mach headers define PAGE_SIZE as vm_page_size. The maximum page size used by static layout checks is now constant on Intel macOS.
  • The regression programs enumerate all Metal devices, so integrated and discrete GPUs are both exercised.

Validation of the review revision

BIOS/storage/OIT regression baseline: 12e7e9d1399c917a396dbeae483f2fb9b21c94eb.

  • Native macOS x86_64 standalone build links on macOS 26.5.2, using the 26.5 SDK.
  • Eight standalone BIOS smoke runs pass with MTL_DEBUG_LAYER=1: Intel UHD 630 and AMD Radeon Pro 5600M, each using per-triangle, per-strip with framebuffer emulation, OIT at 128 layers, and OIT with framebuffer emulation at 8 layers. Every run boots the BIOS twice, captures a nonblank frame through GetLastFrame(), and exits cleanly. Threaded rendering is off in the triangle/128-layer cases and on in the framebuffer cases. A test-only library selects the GPU and requests boot/reload/capture/quit; renderer source is unchanged by the harness.
  • tests/metal/texture_storage.mm passes upload/render/copy/readback on Intel UHD 630 and Radeon Pro 5600M with managed storage, and on Apple M2 Max with shared storage.
  • tests/metal/oit_layer_limit.mm passes on Intel UHD 630, Radeon Pro 5600M and Apple M2 Max with MTL_DEBUG_LAYER=1. A 129-fragment linked list resolves exactly 8, 32, 64 and 128 contributions, with raster-order groups both disabled and enabled. The original shader fails the 8-layer test, returning 32.
  • The same GPU regression test passes against the downstream renderer source.

Game-content follow-up

Revision: 07ab5b955c12ad0005ac95b5009a2c8414cf088b. Native x86_64 standalone on macOS 26.7.2, Intel UHD 630 and Radeon Pro 5600M, with MTL_DEBUG_LAYER=1.

Entering THPS2's Hangar exposed an additional validation abort: the CPU fragment-uniform block was 88 bytes, while MSL requires 96 bytes due to its float4 alignment. The shared CPU struct now has 16-byte alignment and a compile-time size assertion. The failing scene passes after the fix.

  • SA2 City Escape attract demo: per-triangle and per-pixel on AMD; threaded per-strip fast-forward and per-pixel on Intel. Captured downhill road/building scenes did not reproduce the large black road areas. This is sampled scene coverage, not a claim that the earlier investigation's root cause is established.
  • THPS2 Hangar gameplay: regular and per-pixel on both GPUs, with visible skater shadows and RTT-to-VRAM copying. THPS2's compatibility override enables copying at startup. Additional threaded runs change the effective option off/on/off at 6/12/18 seconds without recreating the renderer, on both GPUs and in both modes; all finish without Metal validation errors. Intel regular fast-forward also passes.
  • Beach Spikers Naomi 2 attract match: regular and per-pixel on both GPUs, with visible player lighting and ground shadows. An OpenGL run from the same native state provides a visual reference; sampled lighting, shadows and impact effects are consistent.
  • Native states were created with this public core. A test-only injected library selects the GPU, sends SDL input, captures rendered frames and requests normal shutdown. Frame timing differs between renderers; these are visual checks, not pixel-identical comparisons or performance measurements.

Game-switch follow-up

Actual-game switching exposed a separate SDL lifecycle bug that also reproduces with OpenGL: in unthreaded mode, Maple DMA polls SDL input, and handling a file drop there unloaded the game and started loading the next one while the old DMA call stack was still active.

That fix is no longer part of this PR. It changes game loading for every SDL frontend, so it was reverted here (e5efd6321) and submitted separately as #2649. Until #2649 is merged, switching games by file drop or native file-open with threaded rendering off can still crash on this branch, with any renderer, as it does on dev.

The switching runs below were made at 5ca6f58c2, with the SDL fix still included:

  • SA2 → THPS2 → Beach Spikers → SA2 completes with clean shutdown using unthreaded AMD per-pixel Metal, unthreaded Intel per-triangle Metal, and unthreaded OpenGL. The AMD per-pixel and OpenGL cases crashed before the fix; the pre-fix Metal crash also occurs with frame capture disabled.
  • A threaded AMD per-pixel control and unthreaded Intel per-pixel native file-open requests complete the same sequence.
  • Metal runs retain API validation; captures after each load show the new game. These are short lifecycle regressions, not extended unload/reload stress.

Second review round

Revision: e5efd632142d374d32c54cf94f9f7c65b4fd82a0.

  • The framebuffer-emulation scaler uses the renderer's shader manager; drawers no longer compile their own shader libraries (d8956ef4a).
  • MetalRingBuffer, MetalBufferPacker::uploadToBuffer() and MetalQuadBuffer are removed. The regular screen drawer holds a single target instead of single-element vectors (96854524d).
  • The per-pixel screen drawer owns one color/depth pair and the per-pixel RTT drawer allocates none (f49b2c149).
  • Render() always ends the screen render pass, so no render encoder is open when the next Process() generates mipmaps on the same command buffer (344f34c42).
  • The quad pipeline's source alpha factor is One, keeping routed (Syphon) frames opaque under overlays, as in Fix dark Spout/Syphon video output by keeping routed frames opaque #2606 (9d826d8a0).
  • The macOS 12 requirement message is translatable (249693009).

Checked on Apple M2 Max, arm64 standalone build, with MTL_DEBUG_LAYER=1: Crazy Taxi for 40–45 seconds in regular and per-pixel mode, threaded and unthreaded, with and without framebuffer emulation, and with Delay Frame Swapping on in the unthreaded runs. No validation errors; the frame was inspected in the two unthreaded runs without framebuffer emulation. That scene is mostly 2D with no RTT. The open-encoder case was fixed from the code path and not reproduced first, and the alpha change was not checked against a Syphon receiver. The Intel/AMD runs above have not been repeated on this revision.

Earlier Apple-silicon framebuffer/resolution/Syphon checks have not been repeated for this revision. The reviewer confirmed Syphon reception in OBS on an earlier revision.

Pending validation

  • macOS 12 runtime checks. The BIOS checks used macOS 26.5.2 and the game follow-up used 26.7.2; neither establishes compatibility with the older drivers.
  • Extended upload/asynchronous-RTT stress, forced timeout/quarantine and long game-to-game unload/reload stress beyond the short BIOS and game runs above.
  • Broader Naomi 2 coverage and explicit multi-light/model instrumentation beyond Beach Spikers; delayed framebuffer renders; PVR scaling; integer scaling/video shift; replacement-texture arrival during play.
  • Broader reproduction of the previously reported SA2 City Escape OIT black areas; the sampled scenes above did not reproduce them.
  • No swap-interval override.

Original implementation prepared with Claude Code; review corrections prepared with Codex.

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.

@JoeMatt JoeMatt changed the title Metal renderer for macOS Metal v3 renderer for macOS/iOS/tvOS Intel + ARM Oct 17, 2026
@flyinghead
flyinghead requested a review from vkedwardli October 19, 2026 19:43
JoeMatt and others added 8 commits October 25, 2026 21:29
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>
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>
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>
Publish the presented image to Syphon with the Metal renderers, like the
OpenGL and Vulkan renderers do on macOS.

MetalContext::EndFrame hands the drawable texture, after the frame, the
overlays and the UI are drawn, to os_VideoRoutingPublishFrameTexture()
on the frame's command buffer. The macOS shell implements it with a
SyphonMetalServer, shared with the Vulkan renderer, and recreates the
server if the Metal device changes. The image is published flipped,
which gives clients the same orientation as the OpenGL renderer.

"Scale down before sending" renders the image into a texture of the
requested size with linear filtering before publishing it, as the
OpenGL renderer does with glBlitFramebuffer.

The server is stopped when the option is turned off and when the
renderer or the context is terminated.

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>
Comment thread core/rend/metal/metal_drawer.mm Resolved
Comment thread core/rend/metal/metal_context.mm Resolved
Comment thread core/rend/metal/metal_drawer.h Resolved
Comment thread core/rend/metal/metal_renderer.mm Resolved
Comment thread core/rend/metal/metal_drawer.mm Resolved
Comment thread core/rend/metal/oit/metal_oit_drawer.mm Resolved
Comment thread core/rend/metal/oit/metal_oit_drawer.mm Resolved
Comment thread core/rend/metal/metal_renderer.mm Resolved
Comment thread core/rend/metal/metal_context.mm Resolved
Comment thread core/rend/metal/oit/metal_oit_shaders.h Resolved
@vkedwardli

Copy link
Copy Markdown
Collaborator

optional MetalFX spatial upscaling

I’d prefer to move MetalFX upscaling into a separate PR and keep this one focused on the Metal renderer.

I’ve been testing different internal resolutions and still haven’t found a setting where I’d want MetalFX enabled. In my previous test, an M1 Max Mac Studio ran Flycast smoothly at 7200p (15×) with the widescreen cheat, and only started dropping frames at 8640p (18×). So for desktop class Apple Silicon, I’d just render at a higher resolution. There may be more value on iOS?

There’s also a real chance upscaling gets rejected upstream. @flyinghead removed xBR texture upscaling because users enabled it for 3D games, adding a lot of processing for little benefit when it was better suited to 2D artwork. MetalFX could raise a similar concern if users enable it assuming it always improves the image.

A separate PR would give us room to establish useful settings and measurable benefits. Temporal antialiasing and upscaling would also be worth exploring there, though I understand that’s considerably more work.

@vkedwardli

Copy link
Copy Markdown
Collaborator
  1. Not working on macOS 12, Intel UHD 630 nor AMD Radeon Pro 5500M
Screenshot 2026-11-08 at 5 15 13 AM 2 Screenshot 2026-11-08 at 5 11 46 AM 2
  1. Syphon is working on OBS

  2. Settings -> About -> Metal -> Version is empty

Comment thread core/rend/metal/metal_renderer.h Resolved
@JoeMatt

JoeMatt commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

@vkedwardli this is S-Tier review, thanks a ton!

The issues on macOS aren't so suprising, I've tested the heck out of this across iOS and tvOS chips but less so on mac, especially the Intel chips.

I have a few legacy systems around so I'll send jobs over to validate these issues.

I agree, metalfx should be pulled out and up to @flyinghead if wanting to keep. In my limited experience, it does a bit more than just upscaling, like the BIOS boot alone has a crisper more modern look. Purists will hate that obviously, and usually I would too, but something about the DC rendering, the look and feel was really ahead of it's time and some of these games actually look realllllly nice with MetalFX on, even if already upscaled to 1080p. Maybe an "advanced" user option as I have it in iFly alphas.

I may have to wait a bit to get to these fixes since I have to fix my Intel machines after not booting them for a while and not having the required tooling installed.

JoeMatt and others added 2 commits November 7, 2026 20:48
Retire each upload through the command pool and share the presentation queue. Fix teardown ordering, Naomi 2 buffer strides and modifier-volume uniforms, RTT source selection, framebuffer scaling and delayed OIT renders. Honor custom textures, integer scaling, video shift and the OIT layer limit; initialize a valid viewport depth range and report driver version information.

macOS arm64 build links. The Metal validation regression test resolves exactly 8/32/64/128 fragments under both ordering variants on an M2 Max; the original shader fails the 8-layer case. Intel runtime validation remains pending.

Co-Authored-By: Codex <codex@openai.com>
Keep the renderer PR focused on Metal rendering. Preserve integer scaling and video shift; retain MetalFX separately for follow-up evaluation.

Co-Authored-By: Codex <codex@openai.com>
@JoeMatt JoeMatt changed the title Metal v3 renderer for macOS/iOS/tvOS Intel + ARM Metal renderer for macOS Nov 8, 2026
JoeMatt and others added 3 commits November 7, 2026 21:31
Use managed CPU-visible textures on Mac GPU families that reject shared
textures, and synchronize RTT writes before CPU readback. Keep shared
storage on Apple GPUs and choose packed-format support at runtime.

Keep the Intel macOS maximum page size constant even when Mach headers
define PAGE_SIZE as vm_page_size. Exercise every detected GPU in the OIT
layer-limit test and add upload/render/copy/readback coverage.

Validated with Metal API validation on Intel UHD 630 and Radeon Pro 5600M:
OIT limits 8/32/64/128 with both ordering specializations, texture readback,
and eight BIOS boot/reload/capture/shutdown runs across regular, per-strip,
OIT and framebuffer-emulation configurations. Apple M2 Max storage and OIT
regressions also pass. Hardware runtime checks used macOS 26.5.2, not 12.

Co-Authored-By: Codex <noreply@openai.com>
MSL rounds FragmentShaderUniforms to 96 bytes because its float4 members
require 16-byte alignment. The CPU struct was only 88 bytes, so a final
packed uniform block could end eight bytes before the shader argument.
Metal validation aborts when entering THPS2's Hangar on Radeon Pro 5600M.

Align the shared CPU uniform struct to 16 bytes and assert its size.
This fixes both regular and per-pixel uploads without changing field offsets.

Validated THPS2 Hangar gameplay, shadows and RTT-to-VRAM copying with
Metal API validation on Intel UHD 630 and Radeon Pro 5600M, in regular
and per-pixel modes on macOS 26.7.2.

Co-Authored-By: Codex <noreply@openai.com>
Unthreaded Maple input polls SDL events from the emulation call stack.
Opening a file there unloads the active game and starts asynchronous loading
while the old DMA code is still running. This can corrupt DMA state and
crash across game changes with both OpenGL and Metal.

Keep the first pending file path and consume it in mainui_rend_frame after
input polling. Apply this to drop events and native file-open requests,
and discard pending paths when the SDL input subsystem shuts down.

Tested native x86_64 game switching between SA2, THPS2 and Beach Spikers
with Metal API validation and an OpenGL regression run.

Co-Authored-By: Codex <noreply@openai.com>
@JoeMatt

JoeMatt commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

Following up on the MetalFX scope comment: removed MetalFX from this PR in a74c562. The implementation is preserved for a separate follow-up; no separate PR has been opened yet. This submission now focuses on the native Metal renderer. Any later upscaling proposal will need its own image-quality/performance evidence and discussion of useful settings.

@JoeMatt

JoeMatt commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Following up on the Intel/macOS, Syphon and About report:

  1. Applied the 0–1 viewport depth range. Native Intel testing also reproduced a Metal validation abort from unsupported shared textures: 12e7e9d selects shared/managed CPU-visible texture storage from the selected GPU's Metal family at runtime, synchronizes managed RTT readback, and gates packed 16-bit formats by GPU capability. This is device-based rather than a CPU-architecture switch. Native x86_64 compilation also needed the Mach PAGE_SIZE constant fix.
  2. Thanks for confirming Syphon reception in OBS. That reception check has not been repeated on the latest revision.
  3. About → Metal → Version now returns the OS version string, identifying the OS-supplied Metal driver instead of displaying an empty field.

Hardware results: Intel UHD 630 and Radeon Pro 5600M. Eight BIOS smoke runs passed on macOS 26.5.2; subsequent game tests used 26.7.2, all with MTL_DEBUG_LAYER=1. SA2 City Escape, THPS2 Hangar and Beach Spikers Naomi 2 pass in regular/OIT coverage on both GPUs. THPS2 live RTT off/on/off tests pass in both modes on both GPUs; fast-forward was also checked on Intel. The sampled SA2 scenes did not reproduce the large black road areas.

Those runs found two additional bugs, now fixed: the CPU fragment-uniform block was 88 bytes but the MSL argument requires 96 bytes; the CPU struct now has 16-byte alignment and a size assertion (07ab5b9), and unthreaded SDL game loading could reset state from inside Maple DMA (5ca6f58). Five short SA2 → THPS2 → Beach Spikers → SA2 lifecycle sequences now pass, covering Intel/AMD Metal, an OpenGL regression, threaded/unthreaded rendering, and native file-open requests.

All 20 CI checks pass at 5ca6f58. macOS 12 and Radeon Pro 5500M remain untested here; these results do not establish compatibility with the original older-driver combination. Specific pending checks are listed in the PR description and individual thread replies.

@JoeMatt
JoeMatt requested a review from vkedwardli November 8, 2026 07:52
Comment thread core/rend/metal/metal_drawer.h Resolved
Comment thread core/rend/metal/metal_buffer.h Resolved
Comment thread core/rend/metal/oit/metal_oit_drawer.mm Resolved
Comment thread core/ui/mainui.cpp Resolved
Comment thread core/rend/metal/metal_context.mm Resolved
Comment thread core/rend/metal/metal_renderer.mm Resolved
Comment thread core/rend/metal/metal_quad.mm Resolved
@JoeMatt

JoeMatt commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

I will get to this shortly. Sorry for the delay. I'm in the process of releasing iCube and iFly and grinding on dozens of tickets there. Need the mental bandwidth to properly do this one. Maybe next weekend.

JoeMatt and others added 7 commits December 3, 2026 02:14
Every drawer owned a MetalShaders for the framebuffer-emulation scaler,
and its constructor compiles all the shader libraries: two extra sets in
regular mode and four in per-pixel mode, even with framebuffer emulation
off, and the RTT drawers never scale. The screen drawers already receive
the renderer's shader manager in Init(); the scaler uses that one.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Both geometry uploaders use GetMainBuffer() and quads use setVertexBytes,
so MetalRingBuffer, MetalBufferPacker::uploadToBuffer() and
MetalQuadBuffer have no callers. The ring constructor also allocated with
the unaligned slice size while stepping by the aligned one.

The regular screen drawer always rendered to image 0 of single-element
vectors. It now holds one color attachment and one pair of pass
descriptors, and releases its attachments in one place. The texture
drawer's framebuffer vector was never used.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
MakeBuffers() created two color and two depth textures at the internal
resolution for both per-pixel drawers. The screen drawer only renders to
and presents slot 0, and the RTT drawer renders into the texture's own
color image and its own depth attachment, so it used neither pair.

The screen drawer now owns a single color/depth pair and the RTT drawer
allocates none. The shared a-buffer and resolve background are unchanged.
The framebuffer index and its toggle are gone with the second slot.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
With threaded rendering and framebuffer emulation off, Render() left the
screen encoder open until Present(). If the game rendered again before
presenting (DelayFrameSwapping), the next Process() did its texture work
on the same command buffer, and mipmap generation opens a blit encoder
there while the render encoder is still active, which Metal forbids.

Render() now always ends the pass. A repeated screen render starts a new
pass that loads the color attachment, as the threaded path already did.
The per-pixel renderer already ends its frame in Render().

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Same change as 3a5267a for Vulkan and DirectX 11: the quad pipeline
blended alpha with SourceAlpha, so the VMU and crosshair overlays left
alpha below 1 in the frame sent to Syphon. Source alpha factor One keeps
an opaque target opaque. Color blending is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This reverts commit 5ca6f58. The change
affects game loading on every SDL frontend regardless of the renderer,
so it is submitted on its own.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@vkedwardli vkedwardli left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@flyinghead Green light from me. This is ready to merge.

Thanks Joe, all of the second-round comments are addressed. Tested on macOS 12.7.6 with a Radeon Pro 5500M under MTL_DEBUG_LAYER=1: per-triangle and per-pixel, framebuffer emulation, unthreaded with Delay Frame Swapping, and render-to-texture in per-pixel mode all work, with no validation errors.

@flyinghead
flyinghead merged commit b5141d5 into flyinghead:dev Dec 3, 2026
20 checks passed
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.

4 participants