Repository navigation
Add Metal variant (macOS + iOS) - #47
igagis-bot wants to merge 19 commits into
Conversation
Add a Metal variant of the ruisapp glue layer for macOS and iOS: - macOS: MetalView/CAMetalLayer-based window, Cocoa glue, key-code mapping - iOS: UIKit/CAMetalLayer-based window - CMake: build the Metal variant library (with the corresponding glue sources) for the current platform, plus the ruisapp-metal-test application. Depends on ruis with the native_window::get_native_metal_layer() method and on ruis-render-metal (Metal renderer).
Replace the native_window::get_native_metal_layer() virtual with the surface approach (mirroring the Vulkan renderer): the glue creates a ruis::render::metal::surface holding the window's CAMetalLayer and the shared device, and passes it to the Metal context, which keeps it alive for its own lifetime.
The surface now holds a shared_ref to the window (ruis-render-metal PR #3), so the glue passes its window reference to the surface constructor.
The context now takes the CAMetalLayer by reference, so the glue passes it directly instead of creating a surface provider.
The content view is layer-backed, so AppKit keeps the CAMetalLayer's geometry in sync with the view's bounds. resize() set layer.frame to a screen-coordinate rect, which fought that sync and mispositioned the rendered content (it appeared shifted up by the title-bar height, easing into place at launch). Let AppKit own the layer geometry; only set contentsScale, which AppKit does not derive for the drawable.
|
why separate glue and application created for metal, is it too different from opengl one? can't it be done using #ifdef interlieved in same glue and application? |
|
The split is per-variant because each variant owns a different rendering surface, which is inherent to the backend:
The The So: yes, it can be done with Let me know which direction you'd like and I'll do it. |
|
make two window implementations opengl_window and metal_window, everything else merge into same files |
… separate
Per review feedback, instead of a fully separate glue tree for the metal
variant, the shared glue files (application, glue, cocoa) are now a single
copy that selects the rendering backend via #ifdef RUISAPP_RENDER_METAL.
Only the window implementations are kept as separate per-backend files:
opengl_window.{hxx,cxx} - the opengl / opengles window (and its GL context
wrapper on macos)
metal_window.{hxx,cxx} - the metal window (owns the CAMetalLayer)
This removes the duplicated application/glue/cocoa/key_code code that
differed between the two backends by only a handful of lines.
macos:
- macos/window.{hxx,cxx} -> macos/opengl_window.{hxx,cxx}
- macos/metal/window.{hxx,cxx} -> macos/metal_window.{hxx,cxx}
- macos/metal/{application,glue,cocoa,key_code.map}.* removed (merged)
ios:
- ios/window.{hxx,cxx} -> ios/opengl_window.{hxx,cxx}
- ios/metal/window.{hxx,cxx} -> ios/metal_window.{hxx,cxx}
- ios/metal/{application,glue}.* removed (merged)
build/cmake: the metal variant now reuses the shared glue directory instead
of a per-variant /metal subdirectory.
|
Done — pushed as There are now two window implementations (
The redundant per-variant |
LICENSE file and all other sources (the license check compares each file's header against the LICENSE file).
|
Note on CI: the The other failures (lint, msys2, sanitizer, macosx) were a license-header year mismatch in the renamed |
…w obj-c code to satisfy the lint job.
metal_window.cxx) to satisfy the lint job.
| @end | ||
|
|
||
| namespace { | ||
| class native_window : public ruis::render::native_window |
There was a problem hiding this comment.
don't opengl_window and metal_window share something? would it make sense to make base cocoa_window : public ruis::native_window and derive metal and opengl windows from the cocoa window?
There was a problem hiding this comment.
You're right — after the split into opengl_window / metal_window, almost everything left is shared. I measured the duplication:
- Obj-C
CocoaWindowdelegate methods (init_stuff,windowDidResize:,windowDidChangeScreen:,windowWillResize:,windowShouldClose:,canBecomeKeyWindow,canBecomeMainWindow,acceptsFirstResponder): identical except for one line (the view class instantiated ininitWithContentRect:). - Obj-C view event handlers (all of
mouseDown:/mouseUp:/rightMouse*/otherMouse*/scrollWheel:/mouseMoved:/*MouseDragged:/mouseEntered:/mouseExited:/keyDown:/keyUp:, ~16 methods): functionally identical. The only real difference is thatMetalView'sinitWithFrame:creates theCAMetalLayer; the GL file also carries somelog_debugcalls and a different call formatting, both of which would be normalized in a shared base. - C++
cocoa_window_wrapper(NSWindow alloc/init/title/show/release lifecycle): near-identical. - C++
native_windowcommon surface: the same members (before_fullscreen_window_rect,mouse_cursor_currently_visible,cur_win_dims) and the same methods (set_app_window, cursor visibility,dims/get_dims/get_scale/get_dpi,set_fullscreen_internal).
What is genuinely backend-specific is small:
- Metal: the
CAMetalLayerbacking layer,current_metal_layer(), no-opbind_rendering_context()/swap_frame_buffers(),displaySyncEnabledvsync,contentsScaleon resize. - GL:
opengl_context_wrapper(NSOpenGLPixelFormat/NSOpenGLContext),makeCurrentContext/flushBuffer,NSOpenGLCPSwapIntervalvsync,[context update]on resize, and the extrashared_gl_context_native_windowctor arg.
So a base class makes sense. The shape I'd take:
- C++:
cocoa_window : public ruis::render::native_windowownscocoa_window_wrapper+ the common members/methods, and exposes the backend hooks as virtuals (bind_rendering_context,swap_frame_buffers,set_vsync_enabled_internal,resize).metal_windowandopengl_windowderive from it and override only those hooks; GL keepsopengl_context_wrapperand the shared-context ctor arg. - Obj-C: one base view (e.g.
ruis_view : NSView) owning thewindowpointer and all event forwarding;MetalViewderives from it and just adds theCAMetalLayerininitWithFrame:/dealloc.CocoaWindowbecomes a single shared class (its delegate methods are backend-agnostic), typed against the base view.
Two things to flag before I start:
-
Build model fits:
glue.mm#includes exactly one ofmetal_window.cxx/opengl_window.cxxunder#ifdef RUISAPP_RENDER_*(the.cxxfiles areHEADER_FILE_ONLY, never compiled standalone). The base would live in an always-included header/TU, and the#ifdefselects only the derived window — no change to the selection mechanism. -
iOS parity + manual retain/release:
glue/ios/mirrors this (metal_window.cxx+opengl_window.cxxunder#ifdef RUISAPP_RENDER_METAL/OPENGLES), so the refactor should apply to both platforms to keep them consistent — that's where most of the work is. The Obj-C side is manual retain/release (no ARC), so the new class hierarchy needs care aroundinit/deallocchaining and the view pointer lifecycle.
Net: this removes on the order of ~400 lines of duplicated code and prevents the two files from drifting (they've already drifted slightly in formatting/logging). I'm happy to do it — just confirming the shape above is what you had in mind, and whether you'd like it in this PR or as a focused follow-up.
There was a problem hiding this comment.
Done for macOS — pushed as 16f169c.
The two window implementations now share a cocoa_window base (cocoa_window.{hxx,cxx}), mirroring the shape we discussed:
- C++:
cocoa_window : public ruis::render::native_windowowns thecocoa_window_wrapper(NSWindow lifecycle) plus the common members (before_fullscreen_window_rect,mouse_cursor_currently_visible,cur_win_dims) and the common methods (set_app_window, cursor visibility,dims/get_dims/get_scale/get_dpi,set_fullscreen_internal,resize).metal_window/opengl_windowderive from it and override only the backend hooks (bind_rendering_context,swap_frame_buffers,set_vsync_enabled_internal, and theCAMetalLayercontentsScale/drawableSizehandling on resize). GL keeps itsopengl_context_wrapperand the shared-context ctor arg. - Obj-C: one shared
ruis_view : NSViewbase carries thewindowpointer and all ~16 event-forwarding handlers;MetalViewderives from it and only adds theCAMetalLayerininitWithFrame:/layoutSubviews.CocoaWindowis a single shared delegate class. The only per-backend difference ininitWithContentRect:is the view class, now passed in.
glue.mm includes the shared cocoa_window.cxx once, then #ifdef-selects the one derived window — same selection mechanism as before. Both macOS variants build, full rebuild is clean, 353/353 tests pass, and the Metal and OpenGL test apps render identically to before. Net removal of the duplicated delegate/view/event code.
Also fixed the iOS counterpart of the resize bug in dd8e07c: the iOS CAMetalLayer never had its drawableSize updated, so on a view-size change (fullscreen toggle / rotation) the content got stretched. MetalView.layoutSubviews now sets drawableSize = bounds * contentsScale, matching get_dims().
On the iOS half of the shared-base refactor — flagging before I sink time into it: the two iOS view controllers cannot share a base class (Metal's is UIViewController + CADisplayLink, GL's is GLKViewController + EAGLContext), so unlike macOS only the C++ window/method layer could be shared, not the view layer. That C++ base also runs into a construction-order wrinkle (the window wrapper needs the view controller, but the base is constructed before the derived's VC member) on top of manual retain/release. I can't runtime-verify iOS in this environment (code-signing), so I'd rather not ship an unverifiable memory-management change for a ~150-line dedup — happy to attempt it anyway if you want, but wanted to surface the tradeoff first.
There was a problem hiding this comment.
don't do iOS refactoring then, seems like it makes no sense.
There was a problem hiding this comment.
Understood — skipping the iOS shared-base refactor then.
To be clear on what stays: the iOS drawableSize change (dd8e07c) is a genuine bug fix (the CAMetalLayer drawable never resized, so content got stretched on fullscreen toggle/rotation), not part of the refactor — I'll keep that. The macOS shared-base refactor is in 16f169c.
iOS touch coordinate offset:
- Convert touch locations (view coords, points) to GUI coordinates by
scaling to pixels and subtracting the viewport origin (content_rect.p).
Previously the status-bar height was not subtracted, so taps landed
below the actual touch position; most noticeable with Metal, whose
viewport is offset by the status-bar height (the GLES viewport starts
at the top of the screen).
iOS fullscreen:
- Add a custom Info.plist template (ios_info.plist.in) declaring an empty
UILaunchScreen dict. Without a launch screen iOS runs the app in a
scaled compatibility mode (320x480pt) instead of natively filling the
whole screen, like the Android backend does.
- The template uses Xcode build-setting vars ($(EXECUTABLE_NAME),
$(PRODUCT_BUNDLE_IDENTIFIER), $(PRODUCT_NAME)) because custom
MACOSX_BUNDLE_INFO_PLIST templates do not get ${APPLE_GUI_*} subst.
iOS deprecations / Metal layer:
- Replace deprecated UI_USER_INTERFACE_IDIOM() with
[[UIDevice currentDevice] userInterfaceIdiom]; silence statusBarFrame
and mainScreen deprecations with pragmas.
- Use the CAMetalLayer created via the +layerClass override instead of
assigning a new layer to the readonly UIView.layer.
Review feedback - rendering API conditionals:
- Restructure "#ifdef RUISAPP_RENDER_METAL / #else" into
"#ifdef METAL / #elif defined(OPENGL|OPENGLES) / #else #error
"Unknown graphics API"", matching the other glue backends.
- Convert the "#ifndef RUISAPP_RENDER_METAL" shared-GL-context member to
the positive condition "#ifdef RUISAPP_RENDER_OPENGL".
src/makefile: the glue.mm Objective-C++ compile rule was defined before prorab-build-lib runs and referenced this_cxxflags, which prorab-clear-this-vars empties at the end of the makefile. The renderer define (-D RUISAPP_RENDER_<api>) therefore never reached glue.mm, tripping its #error "Unknown graphics API" in the macosx CI job. Move the rule to after prorab-build-lib and use prorab_cxxflags (the snapshot that survives the clear), matching how the regular .cpp objects compile. macos glue: drop the manual NSWindowDidChangeScreenNotification addObserver/removeObserver pair from both the metal and opengl windows. windowDidResize:/windowDidChangeScreen: are NSWindowDelegate methods already invoked through setDelegate:, and init_stuff runs on every fullscreen toggle, so the manual registration accumulated duplicate observers. ios/metal_window.cxx: fix comment indentation flagged by clang-format.
The vcpkg ios/macos CI legs failed with 'No "Findruis-render-metal.cmake" found in CMAKE_MODULE_PATH' because ruis-render-metal was not declared as a dependency of the ruisapp vcpkg port, so vcpkg never installed it. The port already exists in cppfw/vcpkg-repo at the pinned baseline (versions/r-/ruis-render-metal.json -> 1.0.2), so this only adds the missing wiring: - build/vcpkg/vcpkg.json.in: depend on ruis-render-metal for osx|ios, matching the Metal renderer's platform support. - build/vcpkg/test/vcpkg-configuration.json: add ruis-render-metal to the cppfw registry package list so vcpkg resolves it from cppfw/vcpkg-repo. The linux/windows vcpkg legs are unaffected (the dependency is platform-filtered to osx|ios).
The drawable surface size was never updated when the window resized, so the rendered content kept the initial surface size and got stretched/squeezed to fit the new window size. Update layer.drawableSize to the content size (in points) times contentsScale in native_window::resize(), matching get_dims(). The render/projection matrix was already correct (scaled to the viewport dims in the shared ruis::gui::render path); only the Metal surface size was stale.
|
Added a fix for the macOS Metal window-resize bug (commit 438af74). Bug: resizing the window did not update Root cause: unlike the OpenGL default framebuffer, Fix: in Verification: instrumented the resize path — before the fix a resize to 1920x1080 left Note: iOS has the same latent issue (it never sets |
Extract the Cocoa window/view code that was duplicated between the Metal and OpenGL backends into a shared base, per review: - cocoa_window.hxx/.cxx (new): shared Obj-C ruis_view (NSView) with all event handlers, shared CocoaWindow (NSWindow) delegate, and the C++ cocoa_window base class (window wrapper, fullscreen/mouse-cursor/ resize-and-dims tracking). - metal_window: MetalView now derives from ruis_view and adds only the CAMetalLayer; native_window derives from cocoa_window. - opengl_window: reuses ruis_view (the duplicated CocoaView is removed); native_window derives from cocoa_window. Pure refactor, behavior-preserving: all event handler bodies, the window delegate logic, and the Metal CAMetalLayer.drawableSize resize fix are unchanged.
The iOS CAMetalLayer never had its drawableSize updated, so on a view size change (fullscreen toggle via the test app's fullscreen button, or rotation) the drawable kept the old size and the rendered content got stretched/squeezed. This is the iOS counterpart of the macOS fix: update drawableSize (bounds x contentsScale) in MetalView's layoutSubviews.
iOS has no concept of application exit: the lifecycle is managed by the OS and the main run loop (UIApplicationMain) does not return until the system terminates the app, so there is no loop iteration a quit request could end. A bare exit(0) is deliberately not used: it would skip the applicationWillTerminate: lifecycle callback and would not destroy the application object owned by the AppDelegate, so Metal/GL contexts and windows would not be released cleanly.
The non-fullscreen branch of set_fullscreen_internal() offset the root view's frame down by the status-bar height and shrank it, while get_content_rect() already returns a viewport that is inset by the same status-bar height (and touch_to_gui_pos() accounts for it too). The inset was therefore applied twice, so every fullscreen -> normal toggle pushed the content further down (roughly doubling the offset each time). Keep the view filling the whole window in both states and let the viewport be the single source of the status-bar inset, so toggling returns to the same position the app launched at.
Fix: iOS Metal content slid further down on every fullscreen toggleSymptom. On iOS the Metal app launched correctly below the status bar, but pressing the fullscreen button and then pressing it again left the content starting roughly twice as far down as at launch (and each extra toggle pushed it further). Root cause. The status-bar inset was applied twice in the non-fullscreen state:
At launch the view is still full-screen (so only the viewport inset applied → correct 1×), but after a fullscreen→normal toggle the view-frame shift was added on top of the viewport inset → 2×, drifting further with each toggle. Fix. Keep the view filling the whole window in both states and let the viewport be the single source of the status-bar inset (commit 75b4a1e). The OpenGL ES iOS variant is unaffected — its Verification (iPhone 16 simulator, iOS 18.6, Metal variant; toggled via the probe by clicking
The window now returns to its exact launch position on every toggle — no cumulative offset. |
The OpenGL ES iOS backend still used the pre-fix approach for the non-fullscreen state: get_content_rect() returned a zero origin while set_fullscreen_internal() shifted the view frame down by the status-bar height. The viewport and the view frame disagreed, so toggling fullscreen back produced a red band at the top and clipped content. - get_content_rect() now returns the status-bar offset as the content rect origin in the non-fullscreen state, and the view always fills the whole window (mirrors the Metal backend fix). - drawInRect: now pushes the viewport to the renderer on every frame: GLKView resets glViewport before every call, while gui::set_viewport() only pushes it when the rect changes, so only the first frame used to get the correct viewport. - window_parameters::fullscreen is now applied when creating the window on iOS (previously ignored; the app always started non-fullscreen).
OpenGL ES iOS backend: same fullscreen fix + honoring the
|
| state | top edge | red band |
|---|---|---|
launch (fullscreen == false) |
162 | none |
| toggle → fullscreen ON | 0 | none |
| toggle → back to non-fullscreen | 162 | none |
| second full cycle | 0 → 162 → 0 → 162 | none |
No drift, no red band (the broken state had ~9400 red samples in the top band). The Metal variant was re-checked after the shared application.cxx change: launch top=162, toggle 0↔162, no regressions.
Summary
Add a Metal variant of the ruisapp glue layer for macOS and iOS:
CAMetalLayer-based window (MetalView/CocoaWindow), Cocoa glue, key-code mappingCAMetalLayer-based windowRUISAPP_RENDER_METALdefine, and theruisapp-metal-testapplicationCAMetalLayerby reference to the Metal context (the one held by the native_window) — nonative_window-specific method is needed (mirrors the Vulkan renderer's surface approach)Depends on ruis PR #211 (register the renderer in the monorepo build) and on the Metal renderer PR (cppfw/ruis-render-metal PR #3).