Rendering

Matchstick owns the window, the swap chain and the present. You own the drawing: the host gives you a Direct3D 12 device and a back buffer, and you submit the command lists.

You will learn

  • How to tell the host what your game needs from the GPU
  • How to draw and submit a frame
  • When it is safe to reuse or release GPU resources
  • How to handle a resize or a lost device
  • How to time GPU work

Declare what you need

The host calls GetGraphicsRequirements before it creates the device. Fill in the minimum your game can run on, and the host picks an adapter that meets it.

extern "C" __declspec(dllexport) HRESULT
GetGraphicsRequirements(MGDFGraphicsRequirements *requirements) {
  *requirements = {};
  // The host refuses to start on a GPU below either minimum
  requirements->MinFeatureLevel = D3D_FEATURE_LEVEL_11_0;
  requirements->MinShaderModel = D3D_SHADER_MODEL_6_0;
  return S_OK;
}
FieldSet it to
MinFeatureLevelThe lowest Direct3D feature level you support.
MinShaderModelThe lowest shader model your shaders compile for.
HDRFormatThe format you write when HDR is on. Zero means scRGB. See HDR output.
VRTRUE if you render to a headset. See the VR guide.

Get the device and queues

Both host interfaces hand out the device and the three command queues. You can call these from either thread.

MGDF::ComObject<ID3D12Device10> device;
host->GetD3D12Device(device.Assign());

MGDF::ComObject<ID3D12CommandQueue> directQueue;
host->GetDirectQueue(directQueue.Assign());

GetComputeQueue and GetCopyQueue work the same way. See IMGDFCommonHost.

Draw a frame

Each frame, the host calls RTDraw, presents, and then calls RTAfterPresent.

RTDraw record and execute lists Present host RTAfterPresent background work Frame fence host signals back buffer PRESENT → RENDER_TARGET → PRESENT
Green steps are yours. The rest belong to the host.

Inside RTDraw, ask for the current frame. It carries the back buffer and its render target view.

BOOL __stdcall Module::RTDraw(IMGDFRenderHost *host, double alpha) {
  MGDFFrameInfo frame = {};
  host->GetCurrentFrame(&frame);

  // One allocator per frame slot. The GPU has finished with this
  // slot's previous commands, so its memory is safe to reuse.
  auto allocator = _allocators[frame.FrameSlot].Get();
  allocator->Reset();
  _commands.Reset(allocator);
  auto list = _commands.Get();

  // The back buffer arrives in the PRESENT state. A barrier tells
  // the GPU you are about to draw to it.
  D3D12_RESOURCE_BARRIER barrier = {};
  barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  barrier.Transition.pResource = frame.BackBuffer;
  barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
  barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
  list->ResourceBarrier(1, &barrier);

  const float color[4] = {0.1f, 0.2f, 0.3f, 1.0f};
  list->ClearRenderTargetView(frame.BackBufferRTV, color, 0, nullptr);

  // Hand it back in the PRESENT state, ready for the host to show
  std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter);
  list->ResourceBarrier(1, &barrier);

  // Nothing runs until the list is closed and sent to the queue
  _commands.Close();
  ID3D12CommandList *lists[] = {list};
  _directQueue->ExecuteCommandLists(1, lists);
  return TRUE;
}

Three rules make this work:

  1. The back buffer arrives in the PRESENT state. Transition it before you draw.
  2. Put it back in PRESENT at the end of your last list.
  3. Execute your lists on the direct queue before RTDraw returns. The host presents straight after.

The swap chain has one sample per pixel and no depth buffer. Create your own depth and multisample targets.

NoteThe example uses MGDF::D3D12CommandList from MGDF/D3D12CommandList.hpp. Create leaves the list open, so close it once after you create it. The host needs the wrapper for GPU counters and upscaling.

Reuse and release resources safely

The GPU runs behind the CPU. When RTDraw returns, the frame you submitted may not have started. The host lets two frames be in flight at once, and MGDFFrameInfo tells you where you stand.

FieldMeaning
FrameOrdinalThis frame's number. It only goes up.
FrameSlotFrameOrdinal % FramesInFlight, so 0 or 1.
CompletedOrdinalThe newest frame the GPU has finished.
BackBufferIndexWhich swap chain image this is. It is unrelated to the slot.

To reuse per-frame resources, keep one set for each slot. The host waits for a slot's previous frame before it calls RTDraw, so you can reset that slot's command allocator straight away.

To release a resource, note the FrameOrdinal of its last use and hold on to it until the GPU catches up:

// lastUse is the FrameOrdinal of the last frame that drew with the resource
void Module::ReleaseLater(MGDF::ComObject<ID3D12Resource> resource, UINT64 lastUse) {
  _pending.push_back({std::move(resource), lastUse});
}

// Call once per frame. Erasing an entry drops the last reference.
void Module::Collect(const MGDFFrameInfo &frame) {
  std::erase_if(_pending, [&](const Pending &p) {
    // The GPU has finished every frame up to CompletedOrdinal
    return frame.CompletedOrdinal >= p.LastUse;
  });
}

PitfallThe frame fence only covers the direct queue. If you submit work on the compute or copy queue, signal your own fence there and wait for it on the direct queue before RTAfterPresent returns.

Handle resizes and device loss

The swap chain changes when the window resizes or a display setting changes. Less often, the whole device goes away. The host warns you before each one and tells you when it is over.

EventBeforeAfter
Back buffer changeRTBeforeBackBufferChange
Release every reference to the back buffer.
RTBackBufferChange
Recreate anything sized to it.
Device resetRTBeforeDeviceReset
Release every device resource, then call QueueDeviceReset.
RTDeviceReset
Recreate them on the new device.

Read the new size in RTBackBufferChange:

BOOL __stdcall Module::RTBackBufferChange(IMGDFRenderHost *host) {
  MGDFBackBufferInfo info = {};
  host->GetBackBufferInfo(&info);
  // Anything sized to the window has to be rebuilt to match
  return CreateDepthBuffer(info.Width, info.Height);
}

PitfallThe back buffer in MGDFFrameInfo is borrowed. Don't keep a pointer to it across frames unless you add a reference, and drop that reference in RTBeforeBackBufferChange.

Time GPU work

A GPU counter measures how long a stretch of commands takes and records it to a metric. Create the metric once, then open a scope around the commands you want to time.

// Once
host->CreateGaugeMetric("shadow_pass_ms", "Shadow pass GPU time",
                        _shadowMetric.Assign());

// Each frame, while the list is recording
MGDF::ComObject<IMGDFPerformanceCounter> counter;
host->CreateGPUCounter(_shadowMetric, list, counter.Assign());
{
  // Timing stops when the scope is released at the closing brace
  MGDF::ComObject<IMGDFPerformanceCounterScope> scope;
  counter->Begin(nullptr, scope.Assign());
  DrawShadows(list);
}

The scope must end before you close the list, and the list must execute in the same frame. Counters only work on direct-queue lists created with MGDF::D3D12CommandList.

To see the numbers, start the host with -metricsport and point Prometheus at it. See CreateGPUCounter for the full contract.

Next steps