Link Search Menu Expand Document

Rendering

These types form the rendering layer of OCCTSwiftViewport. ViewportRenderer is the live Metal render loop that drives an MTKView; OffscreenRenderer is a headless variant that produces CGImage and PNG output without any window or view. Supporting types — OffscreenRenderOptions, OffscreenRenderError, OrthoBounds, and DisplayMode — configure both renderers.

Topics


DisplayMode

public enum DisplayMode: String, CaseIterable, Sendable

Controls how geometry is drawn in the viewport or an offscreen render.

Cases

Case Description
.wireframe Edges only — no surface fill.
.shaded Lit surface shading (Cook-Torrance GGX + hemisphere ambient + Fresnel rim). No edge overlay.
.shadedWithEdges Shaded surfaces with a contrast-adaptive wireframe overlay.
.flat Surface fill without smooth normal interpolation.
.unlit Flat-colour shading — each body drawn in its constant color with no lighting, ambient, shadows, Fresnel, or tone-mapping. Faithful per-body colour for diagnostic renders (v1.1.21+).
.xray Transparent surface with visible internal edges.
.rendered Surfaces with full material/texture treatment.

Computed properties

public var displayName: String        // "Wireframe", "Shaded", "Shaded + Edges", "Flat", "Unlit", "X-Ray", "Rendered"
public var showsSurfaces: Bool        // false only for .wireframe
public var showsEdges: Bool           // true for .wireframe, .shadedWithEdges, .xray
public var usesSmoothShading: Bool    // false only for .flat
public var usesTransparency: Bool     // true only for .xray
public var keyboardShortcut: Character? // "w", "s", "e", "x" for the named modes; nil otherwise

OrthoBounds

public struct OrthoBounds: Sendable, Hashable, Codable

Explicit orthographic projection bounds in world units. When supplied to OffscreenRenderOptions.explicitOrthoBounds, the renderer uses these exact bounds instead of fitting to scene extents or deriving from CameraState.orthographicScale. Required when the output must be pixel-registered against an external reference (for example, a drawing view for SSIM reprojection comparison).

Stored properties

public var left:   Float
public var right:  Float
public var bottom: Float
public var top:    Float

Initializer

public init(left: Float, right: Float, bottom: Float, top: Float)

Example — render a 200 × 200 mm region centred at the origin:

let bounds = OrthoBounds(left: -100, right: 100, bottom: -100, top: 100)
var opts = OffscreenRenderOptions(width: 1024, height: 1024)
opts.explicitOrthoBounds = bounds

OffscreenRenderOptions

public struct OffscreenRenderOptions: Sendable

Full configuration for a single offscreen render pass. All fields have defaults; the no-argument init is valid. Every scene default is read from ViewportController.defaultConfiguration (.cad, what ViewportController() uses) and ViewportController.defaultEdgeIntensity, so a default offscreen render shows what a default live viewport shows. The defaults below are those values.

Stored properties

Property Type Default Notes
width Int 1024 Output image width in pixels.
height Int 768 Output image height in pixels.
cameraState CameraState .isometric Camera pose, projection, and FOV.
displayMode DisplayMode .shaded Visual representation style.
xrayOpacity Float DisplayMode.defaultXRayOpacity (0.2) Surface opacity ceiling in .xray; mirrors ViewportConfiguration.xrayOpacity. Clamped to 0...1.
lightingConfiguration LightingConfiguration .threePoint Key/fill/back lights, shadows, SSAO (enableSSAO, on in .threePoint), and tone mapping (exposure, whitePoint, applied in linear space to every lit surface). Image-based lighting and the skybox (drawBackground) use the map named by environmentMapURL / environmentMapData; see Parity with the live viewport.
backgroundColor SIMD4<Float> (0.95, 0.95, 0.95, 1.0) RGBA background colour in the light appearance, sRGB (display) values.
darkModeBackgroundColor SIMD4<Float>? ViewportConfiguration.defaultDarkModeBackgroundColor Background in the dark appearance; nil uses backgroundColor for both. Matches ViewportConfiguration.darkModeBackgroundColor.
appearance RenderAppearance .system Which background the render uses: .system (the system appearance at render time, like the onscreen view), .light or .dark. Pin one for reproducible output. See below.
showGrid Bool true Draw the ground grid (XY plane).
showAxes Bool true Draw the RGB world-space axes.
gridStyle GridStyle .plane Grid style; matches ViewportConfiguration.gridStyle.
gridSize Float 100 Side of the square grid around the origin; matches ViewportConfiguration.gridSize.
axisLength Float? nil Axis length; nil sizes the axes to the rendered bodies, as ViewportConfiguration.axisLength does.
axisRadius Float? nil Axis radius; nil is automatic (1 % of the axis length for .cylinder), as ViewportConfiguration.axisRadius.
axisStyle AxisStyle .cylinder Axis style; matches ViewportConfiguration.axisStyle.
msaaSampleCount Int 4 MSAA sample count. 1 or less disables MSAA; otherwise the largest of 8, 4 and 2 that does not exceed it and that the device supports is used. Can change between renders on one OffscreenRenderer.
gridBaseSpacing Float 1.0 Fundamental grid unit in world units, mirroring ViewportConfiguration.gridBaseSpacing.
gridSubdivisions Int 10 Subdivision factor between adaptive grid spacing levels, mirroring ViewportConfiguration.gridSubdivisions.
edgeLineConfiguration EdgeLineConfiguration .default Edge width and dash pattern, mirroring ViewportConfiguration.edgeLineConfiguration. See EdgeLineConfiguration.
explicitOrthoBounds OrthoBounds? nil Override projection with exact world-unit bounds. See OrthoBounds.
pixelPan SIMD2<Float>? nil Screen-space nudge in pixels. +x = right, +y = down. Lightweight alternative to adjusting the camera for small registration corrections. The near/far fit counts overlay bodies inside the panned (and explicitOrthoBounds) view, so an overlay either brings into view is not clipped (#209).
measurements [ViewportMeasurement] [] Measurement annotations composited over the Metal pass via Core Graphics. World-space anchors must already be resolved on the input values.
edgeIntensity Float 1.0 Edge intensity, mirroring ViewportController.edgeIntensity: 1 is fully opaque, lower values fade edges linearly with view distance between the near and far clip planes, 0 hides them.
clipPlanes [ClipPlane] [] Section planes, mirroring ViewportController.clipPlanes. The first ClipPlane.maxActivePlanes (4) enabled planes clip every pass, the shadow map included.
selectedBodyIDs Set<String> [] Bodies drawn selected (tint and outline ring), mirroring ViewportController.selectedBodyIDs. Meshed bodies get the ring in every display mode, translucent ones included; edge-only and point bodies get none.
hoveredBodyID String? nil Body drawn hovered (lighter tint and outline), mirroring ViewportController.hoveredBodyID.
selectionOutline SelectionOutlineStyle .selection Outline colour and pixel width for selected bodies, mirroring ViewportConfiguration.selectionOutline.
hoverOutline SelectionOutlineStyle .hover Outline colour and pixel width for the hovered body, mirroring ViewportConfiguration.hoverOutline.
selectionTint SelectionTintStyle .selection Surface tint colour and strength for selected bodies, mirroring ViewportConfiguration.selectionTint. .off removes the wash. See SelectionTintStyle.
hoverTint SelectionTintStyle .hover Surface tint for the hovered body, mirroring ViewportConfiguration.hoverTint.
heightfieldMeshCellPixels Float 4 The widest a heightfield mesh cell may appear, in pixels, mirroring ViewportConfiguration.heightfieldMeshCellPixels (clamped to 1...32; 2 is a cost cliff).
heightfieldLatticePixels Float 16 How far apart the lines of a heightfield’s .wireframe lattice are on screen, in pixels, mirroring ViewportConfiguration.heightfieldLatticePixels (clamped to 1...256). No effect in other display modes.
autoSmoothNormals Bool false Crease-aware normal smoothing of interleaved meshes, mirroring ViewportConfiguration.autoSmoothNormals (on in .cadHighQuality).
normalSmoothingCreaseAngle Float 0.524 Crease angle in radians for autoSmoothNormals.
enableSilhouettes Bool true Screen-space depth silhouettes, mirroring ViewportConfiguration.enableSilhouettes. Shares one composite pass with SSAO (tone mapping happens in the surface shader, not here); the pass is skipped in .wireframe and .unlit.
silhouetteThickness Float 1.0 Mirrors ViewportConfiguration.silhouetteThickness.
silhouetteIntensity Float 0.7 Mirrors ViewportConfiguration.silhouetteIntensity.
renderingQuality RenderingQuality .standard Surface path, mirroring ViewportConfiguration.renderingQuality: GPU PN-triangle tessellation at .enhanced; mesh shaders at .maximum on Apple9 GPUs (M3, A17 and later), which subdivide each triangle with the same PN patches and per-frame factors as .enhanced (#175), falling back to tessellation elsewhere. Direct-mesh bodies, and bodies whose faceIndices don’t cover every triangle, draw their mesh as given. The mesh-shader shadow map has its own object function (meshlet_shadow_object), so it binds the uniform struct its functions declare and no longer aborts under Metal API validation (MTL_DEBUG_LAYER=1).
tessellationMaxFactor Int 32 Mirrors ViewportConfiguration.tessellationMaxFactor; clamped to 2...64 and rounded up to even.
adaptiveTessellation Bool true Mirrors ViewportConfiguration.adaptiveTessellation. Adaptive factors depend only on the camera, the output size and tessellationMaxFactor.
uniformTessellationFactor UniformTessellationFactor .loadAdaptive() Factor when adaptiveTessellation is false. .fixed(n) uses n; .loadAdaptive has no load to follow offscreen and always uses tessellationMaxFactor, so the same options always give the same image.
pickRadius Int 0 Tolerance of the offscreen GPU pick, mirroring PickingConfiguration.pickRadius: 0 picks the exact pixel, above 0 the best hit in the (2 * pickRadius + 1) square around it. Clamped to 0...32. Used by renderPickMap and its pick methods; it changes nothing in a render.
selectionFilter PickResultFilter? nil Filter the offscreen pick passes its hit through, mirroring ViewportController.selectionFilter; a .widget-layer hit bypasses it, as live.

Behaviour change (issue #136): the default options now run the SSAO / silhouette composite (as the live viewport’s defaults do), so a lit render is ambient-occluded and silhouetted. Lit surfaces are ACES tone-mapped in linear space whether or not the composite runs. Set enableSilhouettes = false and lightingConfiguration.enableSSAO = false for the previous look.

The scene-content defaults changed too, to match a default ViewportController: displayMode is now .shaded (was .shadedWithEdges), showGrid and showAxes are now true (were false), and cameraState is now .isometric (was CameraState()). Pass the old values explicitly to keep the previous framing and content.

Initializer

public init(
    width: Int = 1024,
    height: Int = 768,
    // Scene defaults come from ViewportController.defaultConfiguration (.cad).
    cameraState: CameraState = .isometric,
    displayMode: DisplayMode = .shaded,
    xrayOpacity: Float = DisplayMode.defaultXRayOpacity,
    lightingConfiguration: LightingConfiguration = .threePoint,
    backgroundColor: SIMD4<Float> = SIMD4<Float>(0.95, 0.95, 0.95, 1.0),
    darkModeBackgroundColor: SIMD4<Float>? = ViewportConfiguration.defaultDarkModeBackgroundColor,
    appearance: RenderAppearance = .system,
    showGrid: Bool = true,
    showAxes: Bool = true,
    msaaSampleCount: Int = 4,
    gridBaseSpacing: Float = 1.0,
    gridSubdivisions: Int = 10,
    gridStyle: GridStyle = .plane,
    gridSize: Float = 100.0,
    axisLength: Float? = nil,
    axisRadius: Float? = nil,
    axisStyle: AxisStyle = .cylinder,
    edgeLineConfiguration: EdgeLineConfiguration = .default,
    explicitOrthoBounds: OrthoBounds? = nil,
    pixelPan: SIMD2<Float>? = nil,
    measurements: [ViewportMeasurement] = [],
    edgeIntensity: Float = 1.0,
    clipPlanes: [ClipPlane] = [],
    selectedBodyIDs: Set<String> = [],
    hoveredBodyID: String? = nil,
    selectionOutline: SelectionOutlineStyle = .selection,
    hoverOutline: SelectionOutlineStyle = .hover,
    selectionTint: SelectionTintStyle = .selection,
    hoverTint: SelectionTintStyle = .hover,
    heightfieldMeshCellPixels: Float = 4,
    heightfieldLatticePixels: Float = 16,
    autoSmoothNormals: Bool = false,
    normalSmoothingCreaseAngle: Float = 0.524,
    enableSilhouettes: Bool = true,
    silhouetteThickness: Float = 1.0,
    silhouetteIntensity: Float = 0.7,
    renderingQuality: RenderingQuality = .standard,
    tessellationMaxFactor: Int = 32,
    adaptiveTessellation: Bool = true,
    uniformTessellationFactor: UniformTessellationFactor = .loadAdaptive(),
    pickRadius: Int = 0,
    selectionFilter: PickResultFilter? = nil
)

@MainActor
public init(matching controller: ViewportController, width: Int, height: Int)

init(matching:width:height:) copies everything the offscreen path honours from a live controller: camera, display mode, lighting, grid and axes, edge intensity, clip planes, selection and hover, the controller’s selectionFilter, and the relevant ViewportConfiguration fields (background colour, MSAA, grid spacing, edge lines, selection and hover outline styles, silhouettes, normal smoothing, pickingConfiguration.pickRadius). Measurements are not copied.

Example — thumbnail of what the viewport currently shows:

let opts = OffscreenRenderOptions(matching: controller, width: 512, height: 384)
let image = renderer.render(bodies: bodies, options: opts)

How a headless render picks its appearance

Offscreen defaults follow onscreen. MetalViewportView follows the SwiftUI colour scheme of its environment; a headless render has no view, so appearance decides:

RenderAppearance Background
.system (default) As .dark when the appearance in effect at render time is dark, otherwise as .light. macOS: NSApp.effectiveAppearance when the process has an NSApplication, so an app that forces its own appearance with NSApp.appearance renders in it; a plain headless process with no application uses the user’s Light/Dark setting. iOS/visionOS: UITraitCollection.current. That is usually unspecified outside a view’s trait update, which makes a headless render light; call render inside your view’s traitCollection.performAsCurrent { … } to follow its style, or pin .light / .dark (#202)
.light backgroundColor
.dark darkModeBackgroundColor, or backgroundColor when that is nil

Because .system makes the image depend on the host’s appearance, pin .light or .dark wherever output must be reproducible: tests, CI, golden/reference images and documentation figures. This package’s own pixel tests and its DocFigures / CookbookRender harnesses pin .light. resolvedBackgroundColor returns the colour a render will use.

var options = OffscreenRenderOptions(width: 800, height: 600, appearance: .light)  // CI-stable

Example — render a diagnostic unlit pass at 2 K:

var opts = OffscreenRenderOptions(
    width: 2048,
    height: 2048,
    displayMode: .unlit,
    backgroundColor: SIMD4<Float>(0.1, 0.1, 0.1, 1.0),
    showAxes: true
)

OffscreenRenderError

public enum OffscreenRenderError: Error, Sendable

Thrown by OffscreenRenderer.renderToPNG(bodies:url:options:).

Case Meaning
.renderFailed The Metal render pass returned no image.
.fileCreationFailed CGImageDestinationCreateWithURL could not open the destination URL.
.writeFailed CGImageDestinationFinalize failed to write the PNG.

OffscreenRenderer

@MainActor
public final class OffscreenRenderer: Sendable

Headless Metal renderer that produces a CGImage from an array of ViewportBody values without requiring MTKView or a window. Uses MSAA 4× by default, an MSAA resolve pass, and a CPU-side blit readback. Translucent bodies (opacity < 1, or every body in .xray) have their surfaces deferred to a back-to-front sorted pass; their edges still draw. An orthographic camera (or explicitOrthoBounds) has its eye moved back along the line of sight in front of its bodies, overlay bodies and axes, as CameraState.placingOrthographicEye(inFrontOf:) does, so an eye built inside the scene does not near-clip it (issue #215). Where the eye is placed changes neither the projection, the lit shading nor the depth range: in orthographic, lit shading takes its view vector along the line of sight, the same for every pixel, rather than toward the eye (live too), the clip planes are fitted to the scene’s depth rather than to the eye (CameraState.clipPlanes(sceneBounds:)), and the composite pass (SSAO, silhouettes) decodes orthographic depth linearly and measures its thresholds against the height of the view, so the edge depth fade and the composite look the same wherever the eye is (issue #217). Point-cloud bodies (primitiveKind == .point) are drawn via a dedicated point-sprite pipeline.

The renderer caches GPU buffers per body ID and regenerates them only when a body’s generation counter changes, which happens on init and on any geometry mutation.

Picking: render(bodies:options:) draws no pick texture. The GPU pick pass runs on request, through renderPickMap(bodies:options:), performPick(bodies:at:options:) and performRegionPick(bodies:rect:options:), and per-body isPickable is honoured there (see GPU picking). Selection and hover are drawn (tint and outline ring) from OffscreenRenderOptions.selectedBodyIDs / hoveredBodyID.

Parity with the live viewport

For the same bodies and settings, OffscreenRenderer produces the same image as a headless frame of ViewportRenderer (pinned per scene by OffscreenParityTests). OffscreenRenderOptions(matching:width:height:) copies those settings from a live ViewportController.

Reproduced offscreen: the shadow map, grid, axes, opaque and transparent surfaces (interleaved and direct-mesh), edges (native and quad-expanded), analytic arcs, point clouds, per-vertex colours on mesh bodies (vertexColors with vertexColorMode, on every mesh path), per-triangle highlights (triangleStyles), per-segment edge colours and visible range (edgeColors, edgeDrawRange), the selection/hover tint and outline, the overlay render layer (drawn last on top of all geometry, in every display mode, arcs included, neither casting nor receiving shadows), clip planes (first four enabled, shadow map included), edgeIntensity, crease-aware normal smoothing, the linear-space lighting and ACES tone mapping (exposure, whitePoint), the SSAO occlusion and blur passes (lightingConfiguration.ssaoBlur) and the SSAO / silhouette composite, image-based lighting plus the HDR skybox (drawBackground) from the environment map named by LightingConfiguration.environmentMapURL / environmentMapData, and the renderingQuality surface paths: PN-triangle tessellation (.enhanced, tessellationMaxFactor, adaptiveTessellation, uniformTessellationFactor) and mesh shaders (.maximum on Apple9, which subdivide each triangle in the mesh stage from the same patches and factors, up to 16 segments per edge, #175) in the shaded, shadow-map and SSAO depth passes. The per-triangle highlight, the selection stencil mask and the outline are drawn on the tessellated or mesh-shader surface too, so a highlight is not hidden by the PN bulge and the ring sits outside the rounded silhouette (#202). These passes evaluate the same patch through different vertex functions and rely on them producing bit-identical positions, which Apple GPUs do in practice; Metal only guarantees it for [[invariant]] positions in a library compiled with preserveInvariance, which the build-time default.metallib cannot be. That guarantee is deferred (#209): SwiftPM and Xcode pass no flags to a package’s build-time metallib, and the Metal compiler ignores the in-source #pragma clang fp and #pragma metal fp controls, so it needs the run-time compile path described in #209. A highlight over a mesh-shader surface does not rely on it: it is drawn with a small depth bias toward the viewer (#213). Every mesh-shader pass places vertices with that same pnPatchPosition through the same subdivision, so the passes agree on the surface. PN patch edges whose end normals differ by more than normalSmoothingCreaseAngle stay flat. Overlay bodies draw the untessellated mesh, as live, and are left out of the per-frame tessellation factors.

Not reproduced offscreen:

Live feature Offscreen behaviour
An environment map loaded imperatively with ViewportRenderer.loadEnvironmentMap(...) Lives on that renderer and is not seen offscreen. Name the map in LightingConfiguration instead.
The tessellation load governor (uniformTessellationFactor = .loadAdaptive) Not run: offscreen tessellates uniformly at tessellationMaxFactor, so output is deterministic. A live view whose GPU is saturated may be tessellating more coarsely. A debug build, which leaves the GPU idle, never saturates it, and the governor ignores the slow frames that follow an idle GPU (see UniformTessellationFactor in the Configuration reference).
TAA and progressive accumulation Not run; MSAA (msaaSampleCount) is the only anti-aliasing.
Depth of field Never applied by the composite pass.
Frustum culling Not run; it only affects performance.

The GPU pick pass is reproduced, but on request rather than with every render: see GPU picking.

Initializer

public init?()

Returns nil if the system provides no default Metal device or command queue, or if any required pipeline state fails to compile. In practice this succeeds on any device that supports Metal (iOS 18+, macOS 15+, visionOS 1+).

Example:

guard let renderer = await MainActor.run(body: { OffscreenRenderer() }) else {
    fatalError("Metal not available")
}

Rendering

render(bodies:options:)

public func render(
    bodies: [ViewportBody],
    options: OffscreenRenderOptions = .init()
) -> CGImage?

Renders bodies synchronously and returns a CGImage in BGRA8 format, or nil on failure. Blocks the calling thread until the GPU command buffer and the blit readback both complete.

Invisible bodies (isVisible == false) are skipped. Scene-adaptive near/far clip planes are derived from the union of all visible geometry bounding boxes.

Example:

@MainActor
func snapshot(bodies: [ViewportBody], camera: CameraState) -> CGImage? {
    guard let renderer = OffscreenRenderer() else { return nil }
    let opts = OffscreenRenderOptions(
        width: 1920,
        height: 1080,
        cameraState: camera,
        displayMode: .shadedWithEdges
    )
    return renderer.render(bodies: bodies, options: opts)
}

renderToPNG(bodies:url:options:)

@discardableResult
public func renderToPNG(
    bodies: [ViewportBody],
    url: URL,
    options: OffscreenRenderOptions = .init()
) throws -> Int

Renders bodies and writes the result as a PNG to url. Returns the written file size in bytes. Throws OffscreenRenderError on failure.

Example:

@MainActor
func savePNG(bodies: [ViewportBody], to url: URL) throws {
    guard let renderer = OffscreenRenderer() else { return }
    let size = try renderer.renderToPNG(bodies: bodies, url: url)
    print("Wrote \(size) bytes to \(url.lastPathComponent)")
}

Heightfield bodies

A body with a heightfield renders, shadows, outlines and picks offscreen exactly as it does live, through the same tile planner and shaders: the shaded and translucent passes, the shadow map (with its own light-side tile plan), the SSAO and silhouette depth prepass, section planes, the selection outline, the overlay layer, and the GPU pick pass (PickResult.heightfield). The renderer keeps the GPU copy of each field and uploads only the tiles edited since it last drew, so calling render after replace(region:...) is cheap. .wireframe draws a heightfield as a lattice (the surface is not drawn), through the same code, and picks its lines. A field the GPU cannot allocate is logged once (os.Logger, subsystem OCCTSwiftViewport, category Heightfield) and not drawn.

GPU picking

An offscreen renderer can ask what is under a pixel without a view. The pick pass is the live viewport’s own: the same pipelines, the same PickEncoding (RG32Uint, R = object index, G = 30-bit primitive index + 2 kind bits), the same PickResult. For the same scene and camera, an offscreen pick returns the same PickResult as ViewportRenderer.performPick(at:completion:) and performRegionPick(rect:completion:) (pinned per body kind by OffscreenPickTests, which compares every sampled pixel with a live headless frame).

Everything the live pick handles is stamped: interleaved and direct-mesh faces; tessellated (.enhanced) and mesh-shader (.maximum) surfaces, which report the input triangle index; edges (edgeIndices, edgeDrawRange) and analytic arcs, native or quad-expanded to the drawn width; vertices and point-cloud bodies; and overlay-layer bodies, which win over the geometry they cover. displayMode decides what is written (.wireframe writes no faces), clipPlanes discard clipped fragments, each body’s transform is applied, isVisible and isPickable are honoured, and bodies are numbered in draw order over the visible ones, so PickResult.bodyIndex agrees with a live viewport showing the same list. The frame is the one render(bodies:options:) draws for the same options: same camera, projection and scene-fitted near/far planes.

The pass shares its encoder with the live renderer (RendererSharedSetup.encodePickPass), so the two cannot drift apart. The pick is 1x, so msaaSampleCount has no effect on it.

renderPickMap(bodies:options:)

public func renderPickMap(
    bodies: [ViewportBody],
    options: OffscreenRenderOptions = .init()
) -> OffscreenPickMap?

Runs the pick pass and reads the whole pick texture back, synchronously. Returns nil when options.width or height is not positive, or a texture, pipeline or command buffer cannot be made. Pick any number of pixels, neighbourhoods and regions from the returned OffscreenPickMap; the render is paid once. Costs 8 * width * height bytes of readback.

performPick(bodies:at:options:)

public func performPick(
    bodies: [ViewportBody],
    at pixel: SIMD2<Int>,
    options: OffscreenRenderOptions = .init()
) -> PickResult?

The offscreen performPick(at:completion:): renders the pick pass and returns the pick under pixel (render pixels, origin top left), or nil for background. With options.pickRadius above 0 it samples the (2r + 1) square around the pixel and returns the best hit (a vertex over an edge over a face, the nearest of equals), exactly as the live neighbourhood pick does. A hit that options.selectionFilter rejects is a miss, except a widget-layer hit. Synchronous, and it renders the pass on every call: to pick many pixels of one scene use renderPickMap.

performRegionPick(bodies:rect:options:)

public func performRegionPick(
    bodies: [ViewportBody],
    rect: CGRect,
    options: OffscreenRenderOptions = .init()
) -> [PickResult]

The offscreen performRegionPick(rect:completion:): every distinct primitive under rect (render pixels, clamped to the render), in scan order of first appearance, filtered by options.selectionFilter. Occlusion-aware and pixel-accurate; [] for a rectangle that misses the render or covers only background.

Example, matching what a live viewport shows:

@MainActor
func whatIsUnderCursor(
    controller: ViewportController, bodies: [ViewportBody], pixel: SIMD2<Int>
) -> PickResult? {
    guard let renderer = OffscreenRenderer() else { return nil }
    let opts = OffscreenRenderOptions(matching: controller, width: 1024, height: 768)
    return renderer.performPick(bodies: bodies, at: pixel, options: opts)
}

OffscreenPickMap

public struct OffscreenPickMap: Sendable

The pick texture of one offscreen render, on the CPU. Its methods decode through the same functions the live renderer’s readback uses.

Member Notes
width, height Size in pixels, from the render’s options.
pickRadius Tolerance pick(at:) samples with (options.pickRadius).
selectionFilter Filter picks pass through (options.selectionFilter).
func pick(at: SIMD2<Int>) -> PickResult? The exact pixel (clamped to the render) when pickRadius is 0, else the best hit in the neighbourhood. Filtered.
func pickRegion(_: CGRect) -> [PickResult] Distinct primitives under the rectangle, in scan order of first appearance. Filtered.

ViewportRenderer

@MainActor
public final class ViewportRenderer: NSObject, MTKViewDelegate, Sendable

The live Metal render loop. Created by MetalViewportView and configured by a ViewportController. Implements MTKViewDelegate to drive the MTKView draw loop. Handles the full rendering pipeline including MSAA, shadow mapping, hardware tessellation (PN triangles on .enhanced/.maximum quality), mesh shaders (Apple9+ GPU families), SSAO post-processing, TAA, environment map IBL, the GPU pick texture, and per-body features such as transparency, triangle highlights, and render-layer separation.

Most behaviour is configured via ViewportController properties rather than directly on this type. The public surface is intentionally narrow.

In orthographic each frame draws the controller’s camera with its eye moved back, if need be, in front of the bodies, overlay bodies and axes (CameraState.placingOrthographicEye(inFrontOf:)), as OffscreenRenderer does (issue #215). The axes count as thick as they are drawn, and the grid, which the eye is not placed in front of, is drawn with depth clamping, so the part of it in front of the eye is not near-clipped; both renderers do the same (issue #217). Under MetalViewportView the controller already keeps the eye there, so this changes nothing; it covers a controller without a sceneBoundsProvider, whose cameraState keeps its own distance.

Initializer

public init?(controller: ViewportController, bodies: Binding<[ViewportBody]>)

Returns nil if Metal device/queue creation fails or any required pipeline state cannot be compiled. configuration.msaaSampleCount is first clamped to a count the device supports (the same mapping OffscreenRenderer uses), so an unsupported value no longer makes this fail; MetalViewportView configures its MTKView with the clamped count. Normally called by MetalViewportView — you do not need to create ViewportRenderer directly.

Properties

metalDevice

public var metalDevice: MTLDevice { get }

The underlying MTLDevice. Exposed for MTKView configuration (for example setting preferredFramesPerSecond).

lastDrawableSize

public private(set) var lastDrawableSize: CGSize

The most recent drawable size in pixels, updated each frame. Use this to convert point coordinates to drawable pixels without accessing UIScreen/NSScreen (works on iOS, macOS, and visionOS).

effectiveRenderingQuality

public var effectiveRenderingQuality: RenderingQuality { get }

The RenderingQuality the renderer actually draws with: configuration.renderingQuality, or lower when the device can’t run it (.maximum without an Apple9 GPU runs .enhanced). Fixed when the renderer is created, which also logs the fallback once. ViewportController.effectiveRenderingQuality forwards it (nil before a renderer is attached).

Environment map (IBL)

Three overloads load an equirectangular HDR environment map into the IBL pipeline. On success, the renderer generates prefiltered, irradiance, and cube-map textures and applies them to subsequent frames.

loadEnvironmentMap(data:)

public func loadEnvironmentMap(data: Data)

Legacy path. Expects raw bytes in the layout Int32 width | Int32 height | RGBA32Float pixels.

loadEnvironmentMap(url:)

public func loadEnvironmentMap(url: URL) throws

Loads a Radiance .hdr file. Throws on parse failure.

Example:

if let url = Bundle.main.url(forResource: "studio", withExtension: "hdr") {
    try renderer.loadEnvironmentMap(url: url)
}

loadEnvironmentMap(width:height:pixels:)

public func loadEnvironmentMap(width: Int, height: Int, pixels: [Float])

Loads pre-decoded equirectangular RGBA32Float pixel data.

clearEnvironmentMap()

public func clearEnvironmentMap()

Removes the current environment map and disables IBL on subsequent frames.

Buffer management

invalidateBuffers()

public func invalidateBuffers()

Clears the GPU buffer cache so all body buffers are rebuilt on the next draw call. Call this if you have replaced all body geometry outside the normal generation-counter mechanism.

GPU picking

performPick(at:completion:)

public func performPick(at pixel: SIMD2<Int>, completion: @escaping @Sendable (PickResult?) -> Void)

Asynchronously reads a single pixel from the RG32Uint pick texture (populated during the previous frame’s pick sub-pass) and calls completion on the main actor with the decoded PickResult, or nil for a background or no-hit pixel. The pixel coordinate is in drawable pixels (not points).

Each texel is two 32-bit channels: R is the body’s draw-order objectIndex and G is a 30-bit primitive index plus a 2-bit kind (see Picking: Bit layout). The renderer rebuilds the objectIndex → bodyID map each frame. The texel is 8 bytes, so the readback and the texture are twice what the old R32Uint target took (see Picking: Cost); in exchange a scene can hold 4 billion pickable bodies and a body 1 billion primitives per kind, and triangleIndex is always exact.

Example:

// In a tap handler, convert the tap point to drawable pixels first.
let scale = renderer.lastDrawableSize.width / viewSize.width
let drawablePx = SIMD2<Int>(Int(tapPt.x * scale), Int(tapPt.y * scale))
renderer.performPick(at: drawablePx) { result in
    if let result {
        print("Hit body \(result.bodyID), primitive \(result.triangleIndex)")
    }
}

MTKViewDelegate (protocol conformance)

These are protocol requirements; you will not normally call them directly.

nonisolated public func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize)
nonisolated public func draw(in view: MTKView)

Off-screen frame rendering (internal)

ViewportRenderer can render a frame without a live MTKView drawable. This is internal, not public API: it exists so the live renderer’s real per-frame output can be regression-tested, which was previously impossible (issue #103, follow-up to #101/#102).

// Internal to the module; reachable from tests via @testable import.
struct FrameRenderTargets {
    let mainPassDescriptor: MTLRenderPassDescriptor
    let finalColorTexture: MTLTexture
    let size: CGSize
    let presentable: (any MTLDrawable)?
}

func encodeFrame(into targets: FrameRenderTargets)

func renderHeadlessBGRA(
    width: Int, height: Int, backgroundColor: SIMD4<Float>, frameCount: Int = 1
) -> [UInt8]?

func renderHeadless(
    width: Int, height: Int, backgroundColor: SIMD4<Float>, frameCount: Int = 1
) -> CGImage?

draw(in:) and renderHeadlessBGRA(...) are both thin wrappers over the same encodeFrame(into:), so the off-screen path runs every pass the live path runs — shadow map, skybox, grid, axes, opaque and transparent surfaces, analytic arcs, point clouds, per-triangle highlights, selection outline, overlay layer, the RG32Uint pick pass, the TAA resolve, the SSAO occlusion pass and its depth-aware blur (only when enableSSAO is on; the blur is skipped when lightingConfiguration.ssaoBlur is false), and the SSAO/silhouette composite. (Tone mapping is not a pass: the surface shader applies it, so both renderers get it.) draw(in:) supplies the drawable’s texture and presents it; the off-screen path supplies renderer-owned textures (HeadlessRenderTargets) built to the same specification MetalViewRepresentable configures on the live view (BGRA8 colour, depth32Float_stencil8 depth/stencil, matching MSAA sample count) and presents nothing.

This differs from OffscreenRenderer in kind, not just degree: OffscreenRenderer is a separate public pipeline that shares the live renderer’s shaders and pipeline factories and reproduces most of its passes (see Parity with the live viewport), but has no TAA or depth of field, and runs its pick pass on request (see GPU picking), whereas this path is the live renderer.

Notes:

  • TAA accumulates across frames. Pass frameCount > 1 to warm up the history texture before readback; a single frame has no history to blend. With TAA on and no SSAO/silhouette composite, a final pass copies the TAA output to the target (issue #244), so a mesh body keeps its colour from the first frame.
  • State. The call updates lastDrawableSize and the renderer’s own caches, exactly as a live frame would. Use a dedicated renderer instance rather than one currently driving an on-screen view.
  • The pick texture is populated, so performPick(at:) / performRegionPick(rect:) work headlessly.

Tests/OCCTSwiftViewportTests/ViewportRendererHeadlessTests.swift is the permanent harness built on this: a fixed battery of deterministic scenes, hashed per scene, with a VIEWPORT_HEADLESS_DUMP_DIR environment variable that dumps hashes plus raw BGRA buffers so two branches can be compared pixel-for-pixel.