Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The GPU canvas

A canvas3d is a box the GPU draws into with an application's own renderer, and goldberry-gpu on the module path is what makes a window present through the GPU at all.

By the end of this chapter you can put a 3D view in a window, write the renderer it draws with, decide whether it is drawn every frame or on demand, and read from the log and from Window.presentation() whether a window went through the GPU.

The showcase's GPU screen: a lit cube in a continuous canvas with a chip painted over it, the same cube in an on-demand canvas with a slider under it, a hud of the present readings showing dashes, and a card on what is measured

The showcase's GPU screen. The left cube spins on every frame, the right one turns when the slider moves.

What the module does to a window

The UI is painted on the CPU whatever the window presents through. goldberry-gpu changes the last step. Put it on the module path and every window presents its frame through the GPU: the frame’s damage is uploaded to a texture and drawn onto the window’s swapchain, on Metal, Vulkan or Direct3D 12. Where that cannot be done, with no device, a refused claim or a popup, the window presents on the CPU exactly as it does without the module. The window says which, once per change:

[GPU] "Goldberry — showcase on Linux / amd64" presents through the GPU (vulkan)

Window.presentation() answers the same thing in code, as a Presentation.Gpu with the driver’s name or a Presentation.Cpu with the reason, and Window.onPresentationChange(handler) hears each change.

On macOS an embedded WKWebView sits above the window’s Metal view, so the window keeps presenting through Metal while the page is open.

Two system properties set the policy:

PropertyValuesWhat it does
goldberry.gpuauto, offoff never touches the GPU. Every window stays on the CPU and a canvas3d shows a notice instead of a picture
goldberry.gpu.compositealways, auto, neveralways composites every window from its first frame. auto composites a window only while it shows GPU layers. never composites none and reads every layer back

What the GPU path adds is GPU layers: opaque rectangles in the frame’s paint order that the GPU fills and the UI is composited over. A window that cannot composite reads a layer back into its frame instead, so the same tree draws the same picture both ways. canvas3d is one layer. A video-view is the other, when goldberry-media and goldberry-gpu are both present.

canvas3d

A 3D view: a leaf sized by its stylesheet, whose picture an application’s Canvas3dRenderer draws on the window’s device.

canvas3d renderer="cube" continuous=#true depth="d16"
import dev.goldberry.gpu.view.Canvas3d;

new Canvas3d(Cube.spinning()).continuous(true).depth(Canvas3d.Depth.D16);
new Canvas3d(viewer).revision(revision).withAttributes(Attributes.NONE.id("model"));

In markup the renderer is a named object the application registered, resolved by renderer=. A node with no renderer to resolve against does not inflate, so the sample above is a fragment.

When it is drawn. A continuous canvas is drawn on every frame and keeps the window drawing frames while it is shown: a spinning model, a game. Otherwise it is drawn once, then again when its size changes and when its revision does. A model viewer that redraws when its camera moves rebuilds the widget with the next revision, and between those the last picture is shown again and nothing is rendered.

Where there is no GPU. With goldberry.gpu=off, with no device, or inside an opacity group, the box is filled with --gb-canvas3d-unavailable and a notice says why.

The renderer

public interface Canvas3dRenderer {
    void init(GpuDevice device);
    default void resize(PhysicalSize size) {}
    void render(GpuFrame frame, Canvas3dTarget target);
    void dispose();
}

init is called once, before the first render, with the window’s device. resize follows it and runs again whenever the canvas’s size in physical pixels changes. render runs for each frame the canvas is drawn. dispose runs when the canvas leaves the tree, or before init on a new device. Every call is on the UI thread, which is the device’s. The canvas keeps the renderer while it is mounted and makes a new layer when the widget is rebuilt with another renderer or depth.

The showcase’s cube is a renderer written as an application writes one:

public final class Cube implements Canvas3dRenderer {

    @Override
    public void init(GpuDevice device) {
        vertex = device.createShader(ShaderCode.load(ShaderStage.VERTEX, "cube.vert", 0, 1, Cube::resource));
        fragment = device.createShader(ShaderCode.load(ShaderStage.FRAGMENT, "cube.frag", 0, 0, Cube::resource));
        pipeline = device.createPipeline(PipelineSpec.builder(vertex, fragment, TextureFormat.B8G8R8A8_UNORM)
                .vertexBuffer(...)
                .build());
        mesh = device.createBuffer(BufferUsage.VERTEX, STRIDE * VERTICES);
    }

    @Override
    public void render(GpuFrame frame, Canvas3dTarget target) {
        frame.renderPass(target.colour(), Load.clear(0, 0, 0, 1), target.clearDepth(), pass -> {
            pass.bindPipeline(pipeline);
            pass.bindVertexBuffer(0, mesh);
            pass.pushVertexUniforms(0, transform(target.aspect(), target.seconds()));
            pass.draw(VERTICES);
        });
    }

    @Override
    public void dispose() {
        pipeline.close();
        mesh.close();
    }
}

GpuDevice makes textures, buffers, samplers, shaders and pipelines from records, and beginFrame() starts a GpuFrame. A frame is a command buffer recorded pass by pass: copyPass uploads into buffers and textures, and renderPass draws into a target, with a Load for what happens first and an optional DepthTarget. A pass is open only while its body runs. The toolkit submits the canvas’s frame, and a frame closed without submit is discarded. A RenderPass binds a pipeline, vertex and index buffers and fragment samplers, pushes uniforms, and calls draw or drawIndexed. Misuse the API can see, a closed resource or a draw with nothing bound, throws in Java before the driver is reached. Everything is confined to the device’s thread.

The Canvas3dTarget is a colour texture at the canvas’s size in physical pixels, a depth texture beside it when the canvas asked for one, and nanos, the frame’s time since the canvas was first drawn. target.aspect() is what a projection is made with, target.seconds() is what an animation is a function of, and target.clearDepth() is the depth target cleared to the far plane. The renderer covers every pixel of the colour texture, and its picture is opaque, as every GPU layer is.

Shaders

Shaders are written in HLSL and compiled offline. The sources live in src/main/shaders/*.hlsl, and ./gradlew :gpu:compileShaders compiles them to SPIR-V, DXIL and MSL, then writes the bytecode as resources beside the code that loads them. It is a task run on purpose, not part of build, because its compilers come with the Vulkan SDK, which is too much to ask of every build. The task also compiles the showcase’s own cube.vert.hlsl and cube.frag.hlsl. ShaderCode.load(stage, name, samplers, uniformBuffers, lookup) reads name.spv, name.dxil and name.msl through the caller’s own resource lookup, and device.createShader(code) picks the format the device takes.

Attributes

AttributeTypeDefaultWhat it does
renderernamed Canvas3dRendererrequiredWhat draws the picture
render-scalenumber1Fraction of the box at which the renderer draws
upscalelinear or fsr1linearFilter used to scale the result to the box
sharpnessnumber, 0 to 10.87FSR 1 sharpening
continuousboolean#falseDrawn on every frame, and keeps the window drawing them
depthnone, d16, d32noneThe depth target the renderer draws with. Anything else is refused
revisionnumber0A value other than the last one drawn has an on-demand canvas drawn again
idstringnoneThe canvas’s id
classstringnoneClasses on its box

Children are refused.

Styling

The CSS type is canvas3d, sized like an image or a canvas by width and height. It is a GPU layer, so it is opaque, what is painted after it is over it, and a clip cuts it to a rectangle. Without a GPU the box is filled with --gb-canvas3d-unavailable, and the notice is a message with the class canvas3d-notice inside a stack with the class canvas3d-stage.

and a clip cuts it to a rectangle. Inside a box that clips to a border-radius, the clip is that box’s bounding rectangle, and whatever is painted over the corners rounds it.

Keyboard

None. A canvas3d is not focusable.

The texture model

A TextureSpec is a 2D texture of a format and a size, with three counts that default to one: layers, mipLevels and samples. TextureSpec.sampled, renderTarget, depth and sampledDepth make the common shapes; TextureSpec.array(format, width, height, layers, usages) makes an array, and withMipLevels, withMipChain, withLayers, withSamples and withUsages vary any spec.

var faceUsages = EnumSet.of(TextureUsage.COLOR_TARGET, TextureUsage.SAMPLER);
var faces = device.createTexture(TextureSpec.array(TextureFormat.B8G8R8A8_UNORM, 256, 358, 64, faceUsages));
var board = device.createTexture(TextureSpec.renderTarget(TextureFormat.R8G8B8A8_UNORM, 2048, 2048).withMipChain());
var shadow = device.createTexture(TextureSpec.sampledDepth(TextureFormat.D32_FLOAT, 2048, 2048));
var scene = device.createTexture(TextureSpec.renderTarget(TextureFormat.R16G16B16A16_FLOAT, w, h));

Layers and levels are addressed, not made. A GpuTexture stands for its level 0 of layer 0 wherever a RenderTarget is taken. texture.layer(i), texture.level(n) and texture.view(level, layer) name one level of one layer as a TextureView, which frame.renderPass draws into, copy.upload fills, and frame.readback reads. A shader samples the array as one Texture2DArray in HLSL and picks the layer by index, so a card-face cache is one texture and every card one instance of one draw.

Mip levels are uploaded one at a time through a view, or generated: frame.generateMipmaps(texture) fills every level below the first from the one above it, outside any pass, for a texture made with TextureSpec.renderTarget, because the drivers blit through a colour target. A SamplerSpec reads level 0 alone unless it has a mip filter: SamplerSpec.trilinear(), or withMipFilter(Filter.LINEAR), reads the level the footprint calls for.

Float colour formats. R16G16B16A16_FLOAT, R32_FLOAT and R11G11B10_UFLOAT are colour targets a Load.clear takes past 1 and below 0, and read back as their bytes: halves, which Float.float16ToFloat decodes, or floats. The canvas’s own target stays B8G8R8A8_UNORM; a renderer draws its scene in HDR and tonemaps into the canvas in its last pass. Whether a device renders into R11G11B10_UFLOAT is a question for device.supports(format, usages).

A depth texture can be sampled. TextureSpec.sampledDepth makes a depth target a later pass reads: a shadow map. It is drawn in a render pass with no colour target, frame.renderPass(DepthTarget.clear(shadow), body), with a pipeline made by PipelineSpec.depthOnly(vertex, fragment, DepthTest.less(format)) whose fragment shader outputs nothing. The two kinds of pipeline and pass do not cross: a colour pipeline in a depth-only pass, or the reverse, is refused in Java. The scene then binds the shadow map like any texture, through a sampler with a comparison, SamplerSpec.linear().withCompare(CompareOp.LESS_OR_EQUAL), for HLSL’s SampleCmp. A sampled depth texture reads back as floats or shorts. One made with TextureSpec.depth alone is never read back.

Samples. A spec with samples of 2, 4 or 8 is a multisampled render target: one layer, one level, never sampled itself. A pipeline made with .samples(4) draws into it, in a pass that names where the samples go: frame.renderPass(msaa, load, resolved.level(0), body) resolves them into a single-sampled texture of the same format and size when the pass ends, and the multisampled texture’s own contents are then undefined. A depth target in such a pass has the same sample count. The sampled picture is the resolved one.

Which counts a device has for a format is asked before the target is made: device.supportsSamples(format, samples) is true for 1 and the driver’s answer for 2, 4 and 8, and device.maxSamples(format, limit) is the highest supported count at most limit. A renderer with an anti-aliasing setting asks for both of its targets’ formats and takes the smaller answer:

var samples = Math.min(
        device.maxSamples(TextureFormat.B8G8R8A8_UNORM, settings.msaa()),
        device.maxSamples(TextureFormat.D32_FLOAT, settings.msaa())
);

A sampler per slot. pass.bindFragmentSamplers(sampler, textures...) reads every texture of a shader with one sampler. A shader that reads its textures differently binds a SamplerBinding per slot, slot 0 first:

pass.bindFragmentSamplers(List.of(
        new SamplerBinding(faces, trilinear),
        new SamplerBinding(shadow, shadowCompare)
));

The shader declares the slots in the same order, each texture with its own sampler: a SamplerState for the first and a SamplerComparisonState for the second, read with Sample and SampleCmp. bindVertexSamplers takes the same list for a vertex shader.

Uploads

Upload memory written elsewhere. GpuDevice.createUploadBuffer makes memory a producer on another thread fills while it is mapped, and CopyPass.upload(texture, buffer, offset, rowBytes) records the upload from it with no copy. Mapping, unmapping and uploading are the device’s thread’s; only the bytes may be written elsewhere, and unmapping ends the mapping for every thread. Rows padded to 256 bytes upload in one copy where GpuDevice.uploadsPaddedRows() is true, Vulkan and Direct3D 12; Metal reads an upload’s rows as packed, so there padded rows are recorded one at a time and packed rows are the ones to stage.

Compute and storage

A compute shader is <name>.comp.hlsl, compiled by the same task, and loaded by ComputeCode.load with a builder that says its workgroup and what it binds. device.createComputePipeline(code) makes the pipeline, and a frame runs it in a compute pass that names what it writes:

var declared = ComputeCode.builder(64, 1, 1).readOnlyStorageBuffers(1).readWriteStorageBuffers(1).uniformBuffers(1);
var code = ComputeCode.load("particles.comp", declared, Vfx.class::getResourceAsStream);
var simulate = device.createComputePipeline(code);
var usages = EnumSet.of(BufferUsage.COMPUTE_STORAGE_WRITE, BufferUsage.GRAPHICS_STORAGE_READ);
var particles = device.createBuffer(usages, COUNT * STRIDE);

frame.computePass(particles, pass -> {
    pass.bindPipeline(simulate);
    pass.bindStorageBuffers(emitters);
    pass.pushUniforms(0, dt, 0, 0, 0);
    pass.dispatch(COUNT / 64);
});
frame.renderPass(target.colour(), Load.keep(), pass -> {
    pass.bindPipeline(sprites);
    pass.bindVertexStorageBuffers(particles);
    pass.draw(6, COUNT, 0, 0);
});

What a pass writes is said when it begins, frame.computePass(written, body) or the form with lists of buffers and texture views, so the driver orders the writes against the draws around them. What it reads is bound after the pipeline with bindStorageBuffers and bindStorageTextures. A buffer or texture carries the usages of every stage that touches it: COMPUTE_STORAGE_WRITE for the pass, GRAPHICS_STORAGE_READ for the draw that reads it through bindVertexStorageBuffers, bindFragmentStorageBuffers or bindFragmentStorageTextures, COMPUTE_STORAGE_READ for a later pass. A graphics shader that reads storage says so when loaded, ShaderCode.builder(stage).storageBuffers(n), and a vertex shader that samples a texture, a height map, binds it with bindVertexSamplers.

the windowing backend’s HLSL bindings for compute: samplers, then read-only storage textures and buffers, as t[n] in space 0; read-write storage textures and buffers as u[n] in space 1; uniform blocks as b[n] in space 2. For a vertex shader, storage comes after its samplers in space 0; for a fragment shader, in space 2 after its samplers.

BlendMode.ADDITIVE sums the output onto the target, colour and alpha alike: particles, glows and light. The counts and the usages are checked in Java before the backend sees a dispatch or a draw, as everything in this API is.

Indirect draws, stencil and copies

A draw can take its counts from a buffer rather than from its arguments, so that a compute pass decides what is drawn: the instances that survived culling, or the particles still alive, with nothing read back. The buffer is made with BufferUsage.INDIRECT, and with COMPUTE_STORAGE_WRITE too when a compute pass writes it. Its commands are the records in dev.goldberry.gpu.indirect: a DrawCommand is four words (vertices, instances, first vertex, first instance), an IndexedDrawCommand five, and a DispatchCommand three.

var usages = EnumSet.of(BufferUsage.COMPUTE_STORAGE_WRITE, BufferUsage.INDIRECT);
var commands = device.createBuffer(usages, DrawCommand.BYTES);

frame.computePass(commands, pass -> {
    pass.bindPipeline(cull);
    pass.bindStorageBuffers(instances);
    pass.dispatch(INSTANCES / 64);
});
frame.renderPass(target, Load.clear(0, 0, 0, 1), depth, pass -> {
    pass.bindPipeline(lit);
    pass.bindVertexBuffer(0, cube);
    pass.drawIndirect(commands, 0, 1);
});

drawIndirect(buffer, offset, count) draws count commands that lie one after another from offset, and drawIndexedIndirect does the same from the bound index buffer. ComputePass.dispatchIndirect(buffer, offset) reads its workgroups the same way. A command with zero vertices or zero workgroups does nothing, which is what a culling pass writes when it culls everything. From Java, IndirectCommand.pack(list) lays the commands out to upload. The offset is a whole word, and a command that runs past the buffer’s end is refused.

A stencil test masks where a pipeline draws. It needs a depth format with a stencil, D24_UNORM_S8_UINT or D32_FLOAT_S8_UINT. Apple’s GPUs have only the second, so ask device.supports(format, usages) first. One pipeline marks the pixels with the pass’s reference, and the next draws only where the mark is:

var stencil = TextureFormat.D32_FLOAT_S8_UINT;
var depthStencil = device.createTexture(TextureSpec.depth(stencil, width, height));
var mark = device.createPipeline(PipelineSpec.builder(vertex, flat, format).depthTest(DepthTest.off(stencil)).stencilTest(StencilTest.replace()).build());
var through = device.createPipeline(PipelineSpec.builder(vertex, lit, format).depthTest(DepthTest.less(stencil)).stencilTest(StencilTest.equal()).build());

frame.renderPass(target, Load.clear(0, 0, 0, 1), DepthTarget.clear(depthStencil, 1, 0), pass -> {
    pass.setStencilReference(1);
    pass.bindPipeline(mark);
    drawPortal(pass);
    pass.bindPipeline(through);
    drawFarRoom(pass);
});

StencilTest.notEqual() draws everywhere but the mark, as an outline around a selection does. DepthTest.off(format) passes every fragment and writes no depth, for a pipeline that tests stencil alone. A DepthTarget clears the stencil with the depth, to the value its fourth component gives, and keeps it at the end of the pass.

BlendMode.CONSTANT mixes the output into the target by the pass’s blend constants, src × c + dst × (1 − c) channel by channel: a cross-fade, or a tint, changed per draw with pass.setBlendConstants(r, g, b, a) and no second pipeline.

A copy pass also copies on the GPU. copy.copy(source, destination) copies a whole texture into one of its size and format, or a whole buffer into one of its size. The longer forms copy a box of texels from one level and layer to another, or a range of bytes, in whole words, between two buffers or two parts of one that do not overlap. Last frame’s picture for a motion blur, a history buffer, or the output of a compute pass moved into a buffer of another usage are all copies.

A compute shader samples textures through pass.bindSamplers(sampler, textures...), as many as ComputeCode.builder(...).samplers(n) declares, in t[n] and s[n] of space 0 before its read-only storage. A vertex shader reads storage textures, texel by texel, through bindVertexStorageTextures: a height field that a compute pass wrote, displacing a terrain. Such a texture is made with GRAPHICS_STORAGE_READ and not SAMPLER. the backend takes a texture as one or the other, and TextureSpec refuses both.

device.adapter() names the GPU and its driver in the system’s words, for a settings screen or a log. device.waitForIdle() waits until everything submitted has finished. texture.setDebugName(name) and buffer.setDebugName(name) are what RenderDoc, PIX and Xcode show the resource as.

What a device can do

device.features() answers the questions an options screen asks before it offers a choice: the colour and depth sample counts (colorSampleCounts(), ascending from 1 and not always every one, since some devices have 4 and 8 but no 2), the depth formats with a stencil (stencilFormat() picks the smaller one the device has), the block-compressed formats it samples, whether it renders half-float targets, and the adapter’s name. It is asked once and kept.

var features = device.features();
var antiAliasing = features.colorSampleCounts();
var outlines = features.stencilFormat().isPresent();

Ray tracing is asked separately, with RayTracer.availability(), because it runs on a device of its own that is only looked for when something asks.

Rendering offscreen

A test of a scene with a canvas3d in it opens an OffscreenGpu and hands its surface to Offscreen:

try (var gpu = OffscreenGpu.open()) {
    var picture = Offscreen.of(1600, 900).gpu(gpu.surface()).render(new Board(state));
    GoldenImage.assertMatches("board", picture);
}

The surface is the read-back kind a window that presents on the CPU has: each layer the frame places is rendered on the device, downloaded, and drawn into the picture, so the picture holds the canvas’s pixels as a window would show them, and a golden compares them. The device is made on the calling thread, and the renderer’s init, render and dispose run on it as they would in a window. Closing the OffscreenGpu closes the device and everything left on it. Where no window has started the windowing backend’s video, the offscreen GPU does, under the driver goldberry.gpu.videoDriver names, the windowing backend’s default, or offscreen when the default cannot start on a machine with no display. It quits what it started when closed. With no device at all, open throws with the driver’s reason, rather than rendering the notice.

strip(...) and session(...) show GPU layers through the same surface, in every frame they hand out, so a test that clicks the board and moves the clock compares pictures with the canvas in them:

try (var gpu = OffscreenGpu.open();
        var session = Offscreen.of(1600, 900).gpu(gpu.surface()).session(new Board(state))) {
    session.click("pass");
    session.advance(Duration.ofSeconds(1));
    GoldenImage.assertMatches("board-after-pass", session.frame());
}

A running window’s picture is window.capture(): the last frame as the screen shows it, GPU layers and all, composited again into a texture and read back where the window is composited, and the window surface’s pixels where it presents on the CPU. The launcher writes it for a run that paints a set number of frames: --frames=N --capture=PATH writes the last frame as a PNG. The flags are listed under Measuring.

OffscreenGpu.open(GpuPower.HIGH) prefers the discrete GPU on a machine with two, and gpu.adapter().name() says which one the driver gave.

Ray tracing

dev.goldberry.gpu.raytrace traces rays through a scene of triangle meshes, and hands back what each pixel’s ray hit and whether the light reaches it. It traces in one of two tiers, behind one API that answers alike:

  • In software, on the canvas’s own device, any GPU it has: the scene is a hierarchy of boxes built on the CPU, and compute shaders walk it.
  • In hardware, on a GPU whose driver has ray tracing. The windowing layer’s GPU has none, so this tier runs on a Vulkan device of its own beside it, and its answers come back through memory for a renderer to upload into a texture or a buffer of the canvas’s device.

Asking first. RayTracer.open(device, mode) opens a tracer on the canvas’s device, which a renderer has from init. RayTracingMode.SOFTWARE traces in software; HARDWARE in hardware, or throws with a sentence that says why there is none — no Vulkan, or each device and what it lacks; AUTO in hardware where its device is a GPU, and in software otherwise; OFF opens nothing. RayTracer.availability(device, mode) answers which without opening anything: RayTracing.Software or RayTracing.Hardware, each naming its device, or RayTracing.Unavailable with the sentence. A settings screen shows that sentence beside its switch, and tracer.device() says which tier a tracer got. RayTracer.availability() is the hardware tier’s answer alone, for a screen with no device to hand. The system property goldberry.raytracing=off, software or hardware overrides what an application asks, for the process, and goldberry.raytracing.device=<part of a name> picks the hardware tier’s device where there are several.

The scene. A TriangleMesh is positions and indices. An Instance places a mesh with a Transform and gives it an id, which is what a hit reports, and a mask. SceneGeometry.of(instances…) is the scene, and tracer.build(scene) builds it into a RayScene: one structure for each distinct mesh, shared by every instance of it, and one over the instances. scene.update(geometry) places other instances of the same meshes — moved, renumbered, more or fewer — and rebuilds that last structure alone, which is what a frame of a moving scene costs. A mesh the scene was not built with, or one whose triangles changed, is a new scene. scene.structureBytes() is the GPU memory it holds.

try (var tracer = RayTracer.open(device, RayTracingMode.AUTO).orElseThrow()) {
    var cube = TriangleMesh.of(positions, indices);
    var ground = Instance.of(plane, Transform.IDENTITY, 1);
    var box = Instance.of(cube, Transform.translation(new Vector3(0, 0.5f, 0)), 2);
    try (var scene = tracer.build(SceneGeometry.of(ground, box))) {
        var camera = Camera.lookingAt(new Vector3(0, 6, 8), Vector3.ZERO, 50);
        var request = TraceRequest.of(camera, 640, 360).withShadowsToward(sun);
        var shadows = tracer.traceShadows(scene, request);
        frame.copyPass(pass -> pass.upload(shadowTexture, shadows.pixels()));
        scene.update(SceneGeometry.of(ground, box.withTransform(next)));
    }
}

The rays. A TraceRequest sends one ray through the centre of each pixel of a Camera’s picture, rows from the top, and, with withShadowsToward, a second ray from each hit toward a directional light. A camera a renderer rasterizes with gives rays through the same pixel centres, so the traced picture lines up with the drawn one.

The hits. Hits holds a 24-byte record a pixel: the instance’s id (or Hits.MISS), the triangle’s index in its mesh, the distance along the ray, the barycentrics of the triangle’s second and third vertex, and whether the light reaches the point. hits.hit(x, y) reads one as a Hit. hits.shadowMask() is a ShadowMask; hits.distances(miss) is an R32_FLOAT picture; hits.records() is the records themselves, for a storage buffer a shader reads.

The shadows alone. tracer.traceShadows(scene, request) traces the same rays and answers with a ShadowMask, made on the GPU: a byte a pixel, 255 in the light (or where the ray hit nothing) and 0 in shadow, rows with no padding. mask.pixels() uploads into an R8_UNORM texture, which a shader samples as 1 and 0; mask.isLit(x, y) reads one pixel. A request without a light is refused.

The lighting. tracer.traceLighting(scene, LightingRequest.of(request)) traces, from each primary hit, the shadow ray, rays around the hit for ambient occlusion and a ray off it for its reflection, and answers with a Lighting of two planes laid out for two textures. lighting.shading() is R8G8B8A8_UNORM: red 255 in the light and 0 in shadow, green how open the hit is (the share of its occlusion rays that escaped), blue how lit the surface its reflection sees is, alpha 255 where the primary ray hit anything. lighting.reflectedIds() is R32_FLOAT: the id of the instance the reflection saw, or -1, from which a shader looks up what that surface looks like. withOcclusion(rays, radius) sets how many occlusion rays a hit takes, up to 64, and how far they look; 0 turns occlusion off. withReflections(false) leaves reflections out. The occlusion rays follow a fixed sequence for each pixel, so a still scene lights the same on every trace.

var lighting = tracer.traceLighting(scene, LightingRequest.of(request).withOcclusion(12, 1.4f));
frame.copyPass(pass -> pass.upload(shadingTexture, lighting.shading()));

The lighting into textures. A renderer that only samples the lighting can leave it on the GPU. LightingTargets.create(device, width, height) makes the two textures, sampled and written by compute, and tracer.traceLighting(frame, scene, request, targets) records the lighting into them in the frame, before the passes that sample them. In software the shaders write the textures where they are, and nothing crosses to the CPU; in hardware the tracer traces at once and the frame uploads the planes. Either way the textures hold what traceLighting(scene, request) returns.

targets = LightingTargets.create(device, size.width(), size.height());
tracer.traceLighting(frame, scene, LightingRequest.of(request), targets);

What it costs. A trace that returns its answers returns when the GPU is done, with its output copied back: the rays, then the copy. traceShadows copies a byte a pixel, traceLighting eight and trace 24, so a renderer that wants the light alone asks for the mask, and one that samples it traces into textures. The lighting traces up to four rays a pixel and its occlusion rays besides. The software tier walks its boxes in compute shaders, which on a GPU with ray-tracing hardware is slower than the hardware tier and on one without is not far from it. Tracing a smaller picture than the canvas and sampling it scaled is the usual way to keep either within a frame.

Where it runs. The software tier runs wherever a canvas3d has a GPU: Metal, Direct3D 12 and Vulkan. The hardware tier runs on Linux and Windows, on a GPU whose Vulkan driver has the ray-tracing pipeline extensions — NVIDIA from the GTX 16 series, AMD from RDNA 2, Intel Arc — whichever API the window draws with, and on the CPU through Mesa’s software Vulkan where it runs at 256-bit vectors, as x86 machines do. An arm64 machine’s software Vulkan runs at 128 bits, crashes building a scene there, and is refused, so availability() says so. macOS has no hardware tier.

In the Showcase’s Ray tracing and settings card, choose Auto to use the available tracing backend or GPU compute to run on the canvas’s device. On Metal, both choices run the compute shaders. Hardware requests the Vulkan ray-tracing backend.

Render scale and upscaling

A canvas3d can be drawn at a scale of its box and brought up to it: the setting a game’s options screen calls render scale. Fewer pixels drawn is frame rate bought for sharpness.

canvas3d renderer="cube" continuous=#true depth="d16" render-scale=0.67 upscale="fsr1"
var canvas = new Canvas3d(cube).continuous(true).renderScale(RenderScale.of(0.67).withFilter(UpscaleFilter.FSR1));

The renderer draws into a colour texture at the scaled size, and is told that size by resize. target.size() and target.aspect() are the scaled texture’s, which keeps the box’s aspect. The canvas then brings the picture up to the box with one of two filters:

  • linear, the default: each pixel interpolated from the four nearest. One pass, soft edges.
  • fsr1: AMD FidelityFX Super Resolution 1. EASU upscales along the edges it finds and keeps them sharp, then RCAS sharpens by sharpness=, from 0 (not at all) to 1 (the most). The default, 0.87, is what AMD recommends. Its quality modes are render scales: ultra quality 0.77, quality 0.67, balanced 0.59, performance 0.5.

A scale above 1 draws more pixels than the box has and brings them down linearly, whichever filter is named. At exactly 1 the renderer draws straight into the box and nothing else runs. A new scale draws an on-demand canvas again; the renderer keeps what it made and is resized.

A renderer that draws into textures of its own can upscale one the same way, with an Upscaler made on its device in init:

upscaler.upscale(frame, small, target, UpscaleFilter.FSR1, RenderScale.DEFAULT_SHARPNESS);

FSR 1 expects a picture whose values are what the display shows, as a B8G8R8A8_UNORM target holds them, and it leaves alpha opaque.

AttributeTypeDefaultWhat it does
render-scalenumber, 0.5 to 21The size drawn at over the box’s size, per axis. Anything outside is refused
upscalelinear, fsr1linearHow the picture is brought to the box. Anything else is refused
sharpnessnumber, 0 to 10.87How much fsr1 sharpens; linear ignores it

Raster textures

A RasterTexture is a texture kept in step with a raster the toolkit’s painter draws: a board’s tiles, a chart, a sheet of labels, drawn by a Canvas3dRenderer like any other texture. It owns the texture, the raster and what has been painted since the last upload.

tile = RasterTexture.create(device, new PhysicalSize(256, 256));
tile.paint(List.of(PhysicalRect.of(0, 0, 64, 64)), frame -> drawSquare(frame));
frame.copyPass(tile::upload);
frame.copyPass(copy -> copy.copy(tile.texture().view(0, 0), 0, 0, target.colour().view(0, 0), x, y, 256, 256));

What is painted is what goes up. paint(regions, painter) runs the painter once per region, clipped to it, and remembers the regions; upload(copy) copies exactly those into the texture and forgets them. A new raster is transparent and damaged whole, so its first upload fills the texture. paint(regions, scale, painter) draws at a scale, so a painter can work in units of its own whatever the tile’s size in pixels. damage() says what the next upload copies.

Where the raster lives. On a device whose upload memory reads like ordinary memory, the raster is painted in that memory, and an upload is a copy the GPU makes out of it, with nothing copied on the CPU. Elsewhere the raster is ordinary memory and an upload stages its damage, as CopyPass.upload does. inPlace() says which. The device decides once, at start-up, by timing a paint in each; goldberry.gpu.inPlace=on or off decides instead, and RasterTexture.staged(device, size) always stages.

A paint waits for the frame of the last upload. Painted in place, pixels the GPU is still copying must not change, so paint waits for that frame to have run, which it has, in all but a GPU-bound frame, by the time the next paint comes. Before the frame is submitted, a paint does not wait; the frame may then copy what was painted since, and the next upload copies it either way. A frame discarded with an upload in it loses that damage.

One thread, the device’s. Close a raster texture once the frame of its last upload has been submitted or discarded; closing waits for that frame and releases the texture with it.

A composited window paints in place too

The same memory serves the window. Where the device’s check says so, a composited window lends the frame loop a frame in upload memory to paint into, and its present copies the damage straight out of it; the UI frame is no longer copied on the CPU at all. The hud’s upload reading is that copy’s recording. Nothing changes for an application, and goldberry.gpu.inPlace=off puts every window back on the staged path.

What it costs

The figures are for Metal on an M1 Pro, except where another driver is named. Creating the device costs about 20 ms at the first frame there, and 190 to 320 ms on NVIDIA’s Vulkan driver on Linux. A whole 2560 by 1600 frame costs 1.1 ms of CPU to composite against 2.65 ms for the window-surface present of the same frame, and a minute of 4K60 VP9 through a GPU layer shows all 3600 pictures where CPU present drops 1581.

A device lost mid-render shows black and does not fall back.