diff --git a/apps/docs/content/docs/getting-started/native-api.mdx b/apps/docs/content/docs/getting-started/native-api.mdx index eb651233d5..bcb4c4f6cd 100644 --- a/apps/docs/content/docs/getting-started/native-api.mdx +++ b/apps/docs/content/docs/getting-started/native-api.mdx @@ -124,7 +124,7 @@ This only works with a library that links the same Dawn build as React Native We ## Rendering to a native window -`RNWebGPU.MakeWebGPUCanvasContextFromNativeWindow()` makes a canvas context that presents to a native window other than a `Canvas`, for instance the input `Surface` of a `MediaCodec` encoder on Android. The window is an `ANativeWindow*` on Android or a `CAMetalLayer*` on Apple platforms, passed as a `BigInt`; `width` and `height` size the drawing buffer, like `canvas.width` and `canvas.height`. The context retains the window for as long as it lives, so the pointer stays valid; whatever the window belongs to (the encoder, the layer's view) is yours to keep alive while you present to it. Unlike a `Canvas`, nothing drives the context for you: call it from one thread at a time. On Apple platforms, `configure()` leaves the layer's `colorspace` as it is: set it yourself, on the main thread, to match the `colorSpace` and format you configure. +`RNWebGPU.MakeWebGPUCanvasContextFromNativeWindow()` makes a canvas context that presents to a native window other than a `Canvas`, for instance the input `Surface` of a `MediaCodec` encoder on Android. The window is an `ANativeWindow*` on Android or a `CAMetalLayer*` on Apple platforms, passed as a `BigInt`; `width` and `height` size the drawing buffer, like `canvas.width` and `canvas.height`. The context retains the window for as long as it lives, so the pointer stays valid; whatever the window belongs to (the encoder, the layer's view) is yours to keep alive while you present to it. Unlike a `Canvas`, nothing drives the context for you: call it from one thread at a time. On Apple platforms, `configure()` leaves the layer's `colorspace` as it is: set it yourself, on the main thread, to match the `colorSpace` and format you configure. The same goes for `toneMapping` on a float format: set `toneMapMode` (and on the 26 SDKs `preferredDynamicRange` and `contentsHeadroom`) as `applyCAMetalLayerColorSpace` in `apple/MetalLayerColorSpace.mm` does for a `Canvas`. Without tone mapping the layer may not clip at SDR white: while another layer on screen shows EDR, Core Animation clamps it at the display's headroom instead. ```tsx const context = RNWebGPU.MakeWebGPUCanvasContextFromNativeWindow( diff --git a/apps/example/src/App.tsx b/apps/example/src/App.tsx index d2aa9ddd69..ff036d6f16 100644 --- a/apps/example/src/App.tsx +++ b/apps/example/src/App.tsx @@ -49,6 +49,7 @@ import { BackgroundDetach } from "./Diagnostics/BackgroundDetach"; import { SurfaceChurn } from "./Diagnostics/SurfaceChurn"; import { TransparencyMode } from "./Diagnostics/TransparencyMode"; import { DeviceDestroyBeforeDetach } from "./Diagnostics/DeviceDestroyBeforeDetach"; +import { ToneMapping } from "./Diagnostics/ToneMapping"; import { StorageBufferVertices } from "./StorageBufferVertices"; import { SharedTextureMemory } from "./SharedTextureMemory"; import { ImportExternalTexture } from "./ImportExternalTexture"; @@ -113,6 +114,7 @@ const linking: LinkingOptions = { SurfaceChurn: "diagnostics/surface-churn", TransparencyMode: "diagnostics/transparency-mode", DeviceDestroyBeforeDetach: "diagnostics/device-destroy-before-detach", + ToneMapping: "diagnostics/tone-mapping", StorageBufferVertices: "storage-buffer-vertices", SharedTextureMemory: "shared-texture-memory", ImportExternalTexture: "import-external-texture", @@ -215,6 +217,7 @@ function App() { name="DeviceDestroyBeforeDetach" component={DeviceDestroyBeforeDetach} /> + { diff --git a/apps/example/src/Diagnostics/ToneMapping.tsx b/apps/example/src/Diagnostics/ToneMapping.tsx new file mode 100644 index 0000000000..cd2785e36b --- /dev/null +++ b/apps/example/src/Diagnostics/ToneMapping.tsx @@ -0,0 +1,241 @@ +import React, { useEffect, useRef, useState } from "react"; +import { PixelRatio, Pressable, StyleSheet, Text, View } from "react-native"; +import type { CanvasRef } from "react-native-webgpu"; +import { Canvas, useDevice } from "react-native-webgpu"; + +// Canvases with toneMapping "extended" (left) and "standard" (right), each a +// gray ramp from 0 (bottom) to MAX_VALUE (top): smooth up to a black line at +// 1.0, then in steps of 0.5, beside a strip of plain SDR white. On an HDR +// display, with rgba16float, the extended steps above 1.0 are brighter than +// the strip up to the display's headroom, and standard is the strip's white; +// with bgra8unorm both clip at 1.0. Below 1.0 they all look the same. +// A screenshot does not capture EDR: look at the device. +const MAX_VALUE = 4; +const LABEL_HEIGHT = 14; + +const MODES = ["extended", "standard"] as const; +const SHOWN = ["both", ...MODES] as const; +const FORMATS = ["rgba16float", "bgra8unorm"] as const; + +const shader = /* wgsl */ ` +struct VertexOut { + @builtin(position) position: vec4f, + @location(0) uv: vec2f, +}; + +@vertex +fn vs(@builtin(vertex_index) index: u32) -> VertexOut { + let corners = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3)); + var out: VertexOut; + out.position = vec4f(corners[index], 0, 1); + out.uv = (corners[index] + 1) * 0.5; + return out; +} + +@fragment +fn fs(in: VertexOut) -> @location(0) vec4f { + let ramp = in.uv.y * ${MAX_VALUE}.0; + // Smooth up to 1.0, then steps of 0.5, so the step where it stops shows. + let value = select(floor(ramp * 2) / 2, ramp, ramp <= 1); + let line = abs(ramp - round(ramp)) < fwidth(ramp) * 2; + let marker = line && round(ramp) == 1; + let tick = line && round(ramp) > 1 && in.uv.x < 0.25; + if (marker || tick) { + return vec4f(0, 0, 0, 1); + } + return vec4f(value, value, value, 1); +} +`; + +interface RampCanvasProps { + device: GPUDevice; + mode: GPUCanvasToneMappingMode; + format: GPUTextureFormat; +} + +const RampCanvas = ({ device, mode, format }: RampCanvasProps) => { + const ref = useRef(null); + useEffect(() => { + const context = ref.current?.getContext("webgpu"); + if (!context) { + return; + } + const canvas = context.canvas as HTMLCanvasElement; + canvas.width = canvas.clientWidth * PixelRatio.get(); + canvas.height = canvas.clientHeight * PixelRatio.get(); + context.configure({ + device, + format, + alphaMode: "opaque", + toneMapping: { mode }, + }); + const module = device.createShaderModule({ code: shader }); + const pipeline = device.createRenderPipeline({ + layout: "auto", + vertex: { module, entryPoint: "vs" }, + fragment: { module, entryPoint: "fs", targets: [{ format }] }, + }); + const encoder = device.createCommandEncoder(); + const pass = encoder.beginRenderPass({ + colorAttachments: [ + { + view: context.getCurrentTexture().createView(), + loadOp: "clear", + storeOp: "store", + }, + ], + }); + pass.setPipeline(pipeline); + pass.draw(3); + pass.end(); + device.queue.submit([encoder.finish()]); + context.present(); + }, [device, mode, format]); + return ( + + + {/* Plain SDR white, the reference for the part above 1.0. */} + + + ); +}; + +const Buttons = ({ + options, + value, + onChange, +}: { + options: readonly T[]; + value: T; + onChange: (value: T) => void; +}) => ( + + {options.map((option) => ( + onChange(option)} + style={[styles.button, value === option && styles.buttonActive]} + > + {option} + + ))} + +); + +export const ToneMapping = () => { + const { device } = useDevice(); + const [shown, setShown] = useState<(typeof SHOWN)[number]>("both"); + const [format, setFormat] = useState<(typeof FORMATS)[number]>(FORMATS[0]); + return ( + + + + + {MODES.map((mode, index) => ( + + {index > 0 && } + {mode} + + ))} + + + {MODES.map((mode, index) => ( + + {index > 0 && ( + + {Array.from({ length: MAX_VALUE + 1 }, (_, value) => ( + + {value.toFixed(1)} + + ))} + + )} + + {device && (shown === "both" || shown === mode) && ( + // A new format needs a new canvas: the layer is tagged as the + // canvas mounts. + + )} + + + ))} + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + padding: 16, + backgroundColor: "black", + }, + row: { + flexDirection: "row", + }, + ramps: { + flex: 1, + }, + column: { + flex: 1, + }, + title: { + color: "white", + textAlign: "center", + marginBottom: 8, + }, + pair: { + flex: 1, + flexDirection: "row", + }, + canvas: { + flex: 1, + }, + sdrWhite: { + width: 12, + marginTop: "auto", + height: `${((MAX_VALUE - 1) / MAX_VALUE) * 100}%`, + backgroundColor: "white", + }, + buttons: { + flexDirection: "row", + justifyContent: "center", + gap: 8, + marginBottom: 8, + }, + button: { + paddingHorizontal: 12, + paddingVertical: 6, + borderRadius: 6, + backgroundColor: "#333", + }, + buttonActive: { + backgroundColor: "#06c", + }, + buttonText: { + color: "white", + }, + scale: { + width: 40, + }, + label: { + position: "absolute", + width: "100%", + textAlign: "center", + color: "white", + fontSize: 12, + lineHeight: LABEL_HEIGHT, + transform: [{ translateY: LABEL_HEIGHT / 2 }], + }, +}); diff --git a/apps/example/src/Route.ts b/apps/example/src/Route.ts index 3b16552fbe..eda62b1f67 100644 --- a/apps/example/src/Route.ts +++ b/apps/example/src/Route.ts @@ -40,6 +40,7 @@ export type Routes = { SurfaceChurn: undefined; TransparencyMode: undefined; DeviceDestroyBeforeDetach: undefined; + ToneMapping: undefined; StorageBufferVertices: undefined; SharedTextureMemory: undefined; ImportExternalTexture: undefined; diff --git a/packages/webgpu/apple/MetalLayerColorSpace.h b/packages/webgpu/apple/MetalLayerColorSpace.h index aaa7f6944d..7edc7c0e6a 100644 --- a/packages/webgpu/apple/MetalLayerColorSpace.h +++ b/packages/webgpu/apple/MetalLayerColorSpace.h @@ -6,8 +6,8 @@ namespace rnwgpu { -// Tags a new CAMetalLayer with the colorspace of the canvas, and opts it into -// the display's extended dynamic range for an "extended" toneMapping mode. +// Tags a new CAMetalLayer with the colorspace of the canvas, and sets its +// dynamic range and tone mapping from the canvas's toneMapping mode. // Main thread only, where the platform view calls it as the canvas mounts (see // -[MetalView configure]): the threads that configure and present the surface // (JS, worklet runtimes) never touch a CATransaction. diff --git a/packages/webgpu/apple/MetalLayerColorSpace.mm b/packages/webgpu/apple/MetalLayerColorSpace.mm index 0e8e7f373a..b39f775ab8 100644 --- a/packages/webgpu/apple/MetalLayerColorSpace.mm +++ b/packages/webgpu/apple/MetalLayerColorSpace.mm @@ -2,8 +2,37 @@ #import #import +#include +#include + #include "MetalLayerColorSpace.h" +// @available guards the runtime, not the compilation: these say which SDK +// declares the APIs, so older Xcodes keep building. The visionOS SDK keeps +// __IPHONE_OS_VERSION_MAX_ALLOWED at 17.0, hence its own macro. +// CALayer.toneMapMode: iOS 18 / macOS 15 / visionOS 2 SDKs (Xcode 16). +#if (TARGET_OS_IOS && defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + __IPHONE_OS_VERSION_MAX_ALLOWED >= 180000) || \ + (TARGET_OS_VISION && defined(__VISION_OS_VERSION_MAX_ALLOWED) && \ + __VISION_OS_VERSION_MAX_ALLOWED >= 20000) || \ + (TARGET_OS_OSX && defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + __MAC_OS_X_VERSION_MAX_ALLOWED >= 150000) +#define RNWGPU_HAS_CA_TONE_MAP_MODE 1 +#else +#define RNWGPU_HAS_CA_TONE_MAP_MODE 0 +#endif +// preferredDynamicRange, contentsHeadroom, CADynamicRange*: 26 SDKs (Xcode 26). +#if (TARGET_OS_IOS && defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + __IPHONE_OS_VERSION_MAX_ALLOWED >= 260000) || \ + (TARGET_OS_VISION && defined(__VISION_OS_VERSION_MAX_ALLOWED) && \ + __VISION_OS_VERSION_MAX_ALLOWED >= 260000) || \ + (TARGET_OS_OSX && defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + __MAC_OS_X_VERSION_MAX_ALLOWED >= 260000) +#define RNWGPU_HAS_CA_DYNAMIC_RANGE 1 +#else +#define RNWGPU_HAS_CA_DYNAMIC_RANGE 0 +#endif + namespace rnwgpu { // WebGPU canvas values are encoded with the sRGB transfer function regardless @@ -20,12 +49,10 @@ // converted from sRGB first. // // The toneMapping mode says what happens to values above 1.0 on a float -// canvas. Core Animation keeps an extended colorspace inside the display's -// SDR range unless the layer asks for extended dynamic range content, so -// without it the values clip at white: that is "standard". For "extended" the -// layer opts in, and the values use the display's headroom (EDR) as they do in -// a browser. An 8-bit canvas cannot hold values above 1.0, so the flag has no -// visible effect there. +// canvas: "standard" clips them at SDR white, and "extended" shows them +// brighter, up to the display's headroom (EDR), as a browser does. An 8-bit +// canvas cannot hold values above 1.0, so the mode has no visible effect +// there. void applyCAMetalLayerColorSpace(CAMetalLayer *layer, CanvasLayerColorSpace colorSpace) { // Main thread only: the properties land in the calling thread's implicit @@ -41,17 +68,37 @@ void applyCAMetalLayerColorSpace(CAMetalLayer *layer, : kCGColorSpaceExtendedSRGB); layer.colorspace = cgColorSpace; CGColorSpaceRelease(cgColorSpace); - const bool extendedRange = + [[maybe_unused]] const bool extendedRange = colorSpace.toneMappingMode == CanvasToneMappingMode::Extended; - // The property does not exist on tvOS (the SDK marks it unavailable, which - // @available cannot work around), so it is compiled only where it exists. - // On tvOS "extended" behaves like "standard". + // The EDR properties do not exist on tvOS (the SDK marks them unavailable, + // which @available cannot work around), so they are compiled only where + // they exist. On tvOS "extended" behaves like "standard". #if TARGET_OS_IOS || TARGET_OS_OSX || TARGET_OS_VISION if (@available(iOS 16.0, macOS 10.11, visionOS 1.0, *)) { layer.wantsExtendedDynamicRangeContent = extendedRange; } -#else - (void)extendedRange; +#endif + // The flag alone does not keep "standard" in SDR: while any layer on screen + // shows EDR, Core Animation clamps all content to the display's headroom + // rather than 1.0 (see wantsExtendedDynamicRangeContent in CAMetalLayer.h). + // "standard" is tone mapped to SDR; "extended" is not tone mapped, so it is + // shown up to the display's headroom, never compressed. +#if RNWGPU_HAS_CA_TONE_MAP_MODE + if (@available(iOS 18.0, macOS 15.0, visionOS 2.0, *)) { + layer.toneMapMode = + extendedRange ? CAToneMapModeNever : CAToneMapModeIfSupported; + } +#endif + // The 26 SDKs replace the flag with preferredDynamicRange, which lights EDR + // only for a contentsHeadroom above 1.0. "extended" declares more than any + // display has; "standard" declares 1.0 (SDR), so its tone mapping keeps + // values up to 1.0 as they are and clips above. +#if RNWGPU_HAS_CA_DYNAMIC_RANGE + if (@available(iOS 26.0, macOS 26.0, visionOS 26.0, *)) { + layer.preferredDynamicRange = + extendedRange ? CADynamicRangeHigh : CADynamicRangeStandard; + layer.contentsHeadroom = extendedRange ? 16.0 : 1.0; + } #endif }