qrhid3d11.cpp 83.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt RHI module
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qrhid3d11_p.h"
#include <QWindow>
#include <QBakedShader>
#include <qmath.h>

#include <d3dcompiler.h>
#include <comdef.h>

QT_BEGIN_NAMESPACE

/*
  Direct3D 11 backend. Provides a double-buffered flip model (FLIP_DISCARD)
  swapchain. Textures and "static" buffers are USAGE_DEFAULT, leaving it to
  UpdateSubResource to upload the data in any way it sees fit. "Dynamic"
  buffers are USAGE_DYNAMIC and updating is done by mapping with WRITE_DISCARD.
  (so here QRhiBuffer keeps a copy of the buffer contents and all of it is
  memcpy'd every time, leaving the rest (juggling with the memory area Map
  returns) to the driver).
*/

QRhiD3D11::QRhiD3D11(QRhiInitParams *params)
58
    : ofr(this)
59 60 61 62 63
{
    QRhiD3D11InitParams *d3dparams = static_cast<QRhiD3D11InitParams *>(params);
    debugLayer = d3dparams->enableDebugLayer;
    importedDevice = d3dparams->importExistingDevice;
    if (importedDevice) {
64 65 66 67 68
        dev = reinterpret_cast<ID3D11Device *>(d3dparams->dev);
        ID3D11DeviceContext *ctx = reinterpret_cast<ID3D11DeviceContext *>(d3dparams->context);
        if (SUCCEEDED(ctx->QueryInterface(IID_ID3D11DeviceContext1, reinterpret_cast<void **>(&context)))) {
            // get rid of the ref added by QueryInterface
            ctx->Release();
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        } else {
            qWarning("ID3D11DeviceContext1 not supported by context, cannot import");
            importedDevice = false;
        }
    }

    create();
}

QRhiD3D11::~QRhiD3D11()
{
    destroy();
}

static QString comErrorMessage(HRESULT hr)
{
#ifndef Q_OS_WINRT
    const _com_error comError(hr);
#else
    const _com_error comError(hr, nullptr);
#endif
    QString result = QLatin1String("Error 0x") + QString::number(ulong(hr), 16);
    if (const wchar_t *msg = comError.ErrorMessage())
        result += QLatin1String(": ") + QString::fromWCharArray(msg);
    return result;
}

static inline uint aligned(uint v, uint byteAlign)
{
    return (v + byteAlign - 1) & ~(byteAlign - 1);
}

void QRhiD3D11::create()
{
    uint flags = 0;
    if (debugLayer)
        flags |= D3D11_CREATE_DEVICE_DEBUG;

107 108 109 110 111 112
    HRESULT hr = CreateDXGIFactory2(0, IID_IDXGIFactory2, reinterpret_cast<void **>(&dxgiFactory));
    if (FAILED(hr)) {
        qWarning("Failed to create DXGI factory: %s", qPrintable(comErrorMessage(hr)));
        return;
    }

113
    if (!importedDevice) {
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        IDXGIAdapter1 *adapterToUse = nullptr;
        IDXGIAdapter1 *adapter;
        int requestedAdapterIndex = -1;
        if (qEnvironmentVariableIsSet("QT_D3D_ADAPTER_INDEX"))
            requestedAdapterIndex = qEnvironmentVariableIntValue("QT_D3D_ADAPTER_INDEX");
        for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(adapterIndex, &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
            DXGI_ADAPTER_DESC1 desc;
            adapter->GetDesc1(&desc);
            const QString name = QString::fromUtf16((char16_t *) desc.Description);
            qDebug("Adapter %d: '%s' (flags 0x%x)", adapterIndex, qPrintable(name), desc.Flags);
            if (!adapterToUse && (requestedAdapterIndex < 0 || requestedAdapterIndex == adapterIndex)) {
                adapterToUse = adapter;
                qDebug("  using this adapter");
            } else {
                adapter->Release();
            }
        }
        if (!adapterToUse) {
            qWarning("No adapter");
            return;
        }

136
        ID3D11DeviceContext *ctx = nullptr;
137
        HRESULT hr = D3D11CreateDevice(adapterToUse, D3D_DRIVER_TYPE_UNKNOWN, nullptr, flags,
138 139
                                       nullptr, 0, D3D11_SDK_VERSION,
                                       &dev, &featureLevel, &ctx);
140
        adapterToUse->Release();
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        if (FAILED(hr)) {
            qWarning("Failed to create D3D11 device and context: %s", qPrintable(comErrorMessage(hr)));
            return;
        }
        if (SUCCEEDED(ctx->QueryInterface(IID_ID3D11DeviceContext1, reinterpret_cast<void **>(&context)))) {
            ctx->Release();
        } else {
            qWarning("ID3D11DeviceContext1 not supported");
            return;
        }
    } else {
        Q_ASSERT(dev && context);
        featureLevel = dev->GetFeatureLevel();
    }
}

void QRhiD3D11::destroy()
{
    if (!importedDevice) {
160
        if (context) {
161
            context->Release();
162 163 164
            context = nullptr;
        }
        if (dev) {
165
            dev->Release();
166 167 168 169 170 171
            dev = nullptr;
        }
    }
    if (dxgiFactory) {
        dxgiFactory->Release();
        dxgiFactory = nullptr;
172 173 174 175 176
    }
}

QVector<int> QRhiD3D11::supportedSampleCounts() const
{
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    return { 1, 2, 4, 8 };
}

DXGI_SAMPLE_DESC QRhiD3D11::effectiveSampleCount(int sampleCount) const
{
    DXGI_SAMPLE_DESC desc;
    desc.Count = 1;
    desc.Quality = 0;

    // Stay compatible with QSurfaceFormat and friends where samples == 0 means the same as 1.
    int s = qBound(1, sampleCount, 64);

    if (!supportedSampleCounts().contains(s)) {
        qWarning("Attempted to set unsupported sample count %d", sampleCount);
        return desc;
    }

    desc.Count = s;
    desc.Quality = s > 1 ? D3D11_STANDARD_MULTISAMPLE_PATTERN : 0;
    return desc;
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
}

QRhiSwapChain *QRhiD3D11::createSwapChain()
{
    return new QD3D11SwapChain(this);
}

QRhiBuffer *QRhiD3D11::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, int size)
{
    return new QD3D11Buffer(this, type, usage, size);
}

int QRhiD3D11::ubufAlignment() const
{
    return 256;
}

bool QRhiD3D11::isYUpInFramebuffer() const
{
    return false;
}

QMatrix4x4 QRhiD3D11::clipSpaceCorrMatrix() const
{
    // Like with Vulkan, but Y is already good.

    static QMatrix4x4 m;
    if (m.isIdentity()) {
        // NB the ctor takes row-major
        m = QMatrix4x4(1.0f, 0.0f, 0.0f, 0.0f,
                       0.0f, 1.0f, 0.0f, 0.0f,
                       0.0f, 0.0f, 0.5f, 0.5f,
                       0.0f, 0.0f, 0.0f, 1.0f);
    }
    return m;
}

234
bool QRhiD3D11::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
235
{
236 237
    Q_UNUSED(flags);

238 239 240 241 242 243
    if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ASTC_12x12)
        return false;

    return true;
}

244
QRhiRenderBuffer *QRhiD3D11::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize,
Laszlo Agocs's avatar
Laszlo Agocs committed
245
                                                int sampleCount, QRhiRenderBuffer::Flags flags)
246
{
Laszlo Agocs's avatar
Laszlo Agocs committed
247
    return new QD3D11RenderBuffer(this, type, pixelSize, sampleCount, flags);
248 249
}

Laszlo Agocs's avatar
Laszlo Agocs committed
250 251
QRhiTexture *QRhiD3D11::createTexture(QRhiTexture::Format format, const QSize &pixelSize,
                                      int sampleCount, QRhiTexture::Flags flags)
252
{
Laszlo Agocs's avatar
Laszlo Agocs committed
253
    return new QD3D11Texture(this, format, pixelSize, sampleCount, flags);
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
}

QRhiSampler *QRhiD3D11::createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
                                      QRhiSampler::Filter mipmapMode,
                                      QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
{
    return new QD3D11Sampler(this, magFilter, minFilter, mipmapMode, u, v, w);
}

QRhiTextureRenderTarget *QRhiD3D11::createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
                                                              QRhiTextureRenderTarget::Flags flags)
{
    return new QD3D11TextureRenderTarget(this, desc, flags);
}

QRhiGraphicsPipeline *QRhiD3D11::createGraphicsPipeline()
{
    return new QD3D11GraphicsPipeline(this);
}

QRhiShaderResourceBindings *QRhiD3D11::createShaderResourceBindings()
{
    return new QD3D11ShaderResourceBindings(this);
}

void QRhiD3D11::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps, QRhiShaderResourceBindings *srb)
{
    Q_ASSERT(inPass);

Laszlo Agocs's avatar
Laszlo Agocs committed
283
    QD3D11GraphicsPipeline *psD = QRHI_RES(QD3D11GraphicsPipeline, ps);
284
    if (!srb)
Laszlo Agocs's avatar
Laszlo Agocs committed
285
        srb = psD->m_shaderResourceBindings;
286 287 288 289 290 291

    QD3D11ShaderResourceBindings *srbD = QRHI_RES(QD3D11ShaderResourceBindings, srb);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);

    bool resChanged = false;
    for (int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
Laszlo Agocs's avatar
Laszlo Agocs committed
292
        const QRhiShaderResourceBinding &b(srbD->sortedBindings[i]);
293 294
        QD3D11ShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);
        switch (b.type) {
Laszlo Agocs's avatar
Laszlo Agocs committed
295
        case QRhiShaderResourceBinding::UniformBuffer:
296 297 298 299 300
            if (QRHI_RES(QD3D11Buffer, b.ubuf.buf)->generation != bd.ubuf.generation) {
                resChanged = true;
                bd.ubuf.generation = QRHI_RES(QD3D11Buffer, b.ubuf.buf)->generation;
            }
            break;
Laszlo Agocs's avatar
Laszlo Agocs committed
301
        case QRhiShaderResourceBinding::SampledTexture:
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
            if (QRHI_RES(QD3D11Texture, b.stex.tex)->generation != bd.stex.texGeneration
                    || QRHI_RES(QD3D11Sampler, b.stex.sampler)->generation != bd.stex.samplerGeneration)
            {
                resChanged = true;
                bd.stex.texGeneration = QRHI_RES(QD3D11Texture, b.stex.tex)->generation;
                bd.stex.samplerGeneration = QRHI_RES(QD3D11Sampler, b.stex.sampler)->generation;
            }
            break;
        default:
            Q_UNREACHABLE();
            break;
        }
    }
    if (resChanged)
        updateShaderResourceBindings(srbD);

    const bool pipelineChanged = cbD->currentPipeline != ps || cbD->currentPipelineGeneration != psD->generation;
    const bool srbChanged = cbD->currentSrb != srb || cbD->currentSrbGeneration != srbD->generation;

    if (pipelineChanged || srbChanged || resChanged) {
        cbD->currentPipeline = ps;
        cbD->currentPipelineGeneration = psD->generation;
        cbD->currentSrb = srb;
        cbD->currentSrbGeneration = srbD->generation;

        QD3D11CommandBuffer::Command cmd;
        cmd.cmd = QD3D11CommandBuffer::Command::BindGraphicsPipeline;
        cmd.args.bindGraphicsPipeline.ps = psD;
        cmd.args.bindGraphicsPipeline.srb = srbD;
        cmd.args.bindGraphicsPipeline.resOnlyChange = !pipelineChanged && !srbChanged && resChanged;
        cbD->commands.append(cmd);
    }
}

336 337
void QRhiD3D11::setVertexInput(QRhiCommandBuffer *cb, int startBinding, const QVector<QRhiCommandBuffer::VertexInput> &bindings,
                               QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
338 339 340 341 342 343 344 345 346 347 348 349
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);

    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::BindVertexBuffers;
    cmd.args.bindVertexBuffers.startSlot = startBinding;
    cmd.args.bindVertexBuffers.slotCount = bindings.count();
    for (int i = 0, ie = bindings.count(); i != ie; ++i) {
        QRhiBuffer *buf = bindings[i].first;
        quint32 ofs = bindings[i].second;
        QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
350
        Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
351 352
        cmd.args.bindVertexBuffers.buffers[i] = bufD->buffer;
        cmd.args.bindVertexBuffers.offsets[i] = ofs;
Laszlo Agocs's avatar
Laszlo Agocs committed
353 354 355
        cmd.args.bindVertexBuffers.strides[i] =
                QRHI_RES(QD3D11GraphicsPipeline, cbD->currentPipeline)->m_vertexInputLayout.bindings[i].stride;
        if (bufD->m_type == QRhiBuffer::Dynamic)
356 357 358 359 360 361
            executeBufferHostWritesForCurrentFrame(bufD);
    }
    cbD->commands.append(cmd);

    if (indexBuf) {
        QD3D11Buffer *ibufD = QRHI_RES(QD3D11Buffer, indexBuf);
Laszlo Agocs's avatar
Laszlo Agocs committed
362
        Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
363 364 365 366
        QD3D11CommandBuffer::Command cmd;
        cmd.cmd = QD3D11CommandBuffer::Command::BindIndexBuffer;
        cmd.args.bindIndexBuffer.buffer = ibufD->buffer;
        cmd.args.bindIndexBuffer.offset = indexOffset;
367 368
        cmd.args.bindIndexBuffer.format = indexFormat == QRhiCommandBuffer::IndexUInt16 ? DXGI_FORMAT_R16_UINT
                                                                                        : DXGI_FORMAT_R32_UINT;
369
        cbD->commands.append(cmd);
Laszlo Agocs's avatar
Laszlo Agocs committed
370
        if (ibufD->m_type == QRhiBuffer::Dynamic)
371 372 373 374 375 376 377 378 379 380 381 382
            executeBufferHostWritesForCurrentFrame(ibufD);
    }
}

void QRhiD3D11::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    Q_ASSERT(cbD->currentTarget);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::Viewport;
    cmd.args.viewport.x = viewport.r.x();
Laszlo Agocs's avatar
Laszlo Agocs committed
383
    // d3d expects top-left, QRhiViewport is bottom-left
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    cmd.args.viewport.y = cbD->currentTarget->sizeInPixels().height() - (viewport.r.y() + viewport.r.w() - 1);
    cmd.args.viewport.y = viewport.r.y();
    cmd.args.viewport.w = viewport.r.z();
    cmd.args.viewport.h = viewport.r.w();
    cmd.args.viewport.d0 = viewport.minDepth;
    cmd.args.viewport.d1 = viewport.maxDepth;
    cbD->commands.append(cmd);
}

void QRhiD3D11::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    Q_ASSERT(cbD->currentTarget);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::Scissor;
    cmd.args.scissor.x = scissor.r.x();
    // d3d expects top-left, QRhiScissor is bottom-left
    cmd.args.scissor.y = cbD->currentTarget->sizeInPixels().height() - (scissor.r.y() + scissor.r.w() - 1);
    cmd.args.scissor.w = scissor.r.z();
    cmd.args.scissor.h = scissor.r.w();
    cbD->commands.append(cmd);
}

void QRhiD3D11::setBlendConstants(QRhiCommandBuffer *cb, const QVector4D &c)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::BlendConstants;
    cmd.args.blendConstants.ps = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentPipeline);
    memcpy(cmd.args.blendConstants.c, &c, 4 * sizeof(float));
    cbD->commands.append(cmd);
}

void QRhiD3D11::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::StencilRef;
    cmd.args.stencilRef.ps = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentPipeline);
    cmd.args.stencilRef.ref = refValue;
    cbD->commands.append(cmd);
}

void QRhiD3D11::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
                     quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::Draw;
    cmd.args.draw.ps = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentPipeline);
    cmd.args.draw.vertexCount = vertexCount;
    cmd.args.draw.instanceCount = instanceCount;
    cmd.args.draw.firstVertex = firstVertex;
    cmd.args.draw.firstInstance = firstInstance;
    cbD->commands.append(cmd);
}

void QRhiD3D11::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
                            quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::DrawIndexed;
    cmd.args.drawIndexed.ps = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentPipeline);
    cmd.args.drawIndexed.indexCount = indexCount;
    cmd.args.drawIndexed.instanceCount = instanceCount;
    cmd.args.drawIndexed.firstIndex = firstIndex;
    cmd.args.drawIndexed.vertexOffset = vertexOffset;
    cmd.args.drawIndexed.firstInstance = firstInstance;
    cbD->commands.append(cmd);
}

QRhi::FrameOpResult QRhiD3D11::beginFrame(QRhiSwapChain *swapChain)
{
    Q_ASSERT(!inFrame);
    inFrame = true;

    QD3D11SwapChain *swapChainD = QRHI_RES(QD3D11SwapChain, swapChain);
Laszlo Agocs's avatar
Laszlo Agocs committed
467
    contextState.currentSwapChain = swapChainD;
468 469 470
    swapChainD->cb.resetState();

    swapChainD->rt.d.pixelSize = swapChainD->pixelSize;
471
    swapChainD->rt.d.rtv[0] = swapChainD->sampleDesc.Count > 1 ?
472
                swapChainD->msaaRtv[swapChainD->currentFrame] : swapChainD->rtv[swapChainD->currentFrame];
473
    swapChainD->rt.d.dsv = swapChainD->ds ? swapChainD->ds->dsv : nullptr;
474 475 476 477 478 479 480 481 482 483 484 485

    return QRhi::FrameOpSuccess;
}

QRhi::FrameOpResult QRhiD3D11::endFrame(QRhiSwapChain *swapChain)
{
    Q_ASSERT(inFrame);
    inFrame = false;

    QD3D11SwapChain *swapChainD = QRHI_RES(QD3D11SwapChain, swapChain);
    executeCommandBuffer(&swapChainD->cb);

486
    if (swapChainD->sampleDesc.Count > 1) {
487 488
        context->ResolveSubresource(swapChainD->tex[swapChainD->currentFrame], 0,
                                    swapChainD->msaaTex[swapChainD->currentFrame], 0,
489 490 491
                                    swapChainD->colorFormat);
    }

492 493 494 495 496 497
    const UINT swapInterval = 1;
    const UINT presentFlags = 0;
    HRESULT hr = swapChainD->swapChain->Present(swapInterval, presentFlags);
    if (FAILED(hr))
        qWarning("Failed to present: %s", qPrintable(comErrorMessage(hr)));

498
    swapChainD->currentFrame = (swapChainD->currentFrame + 1) % QD3D11SwapChain::BUFFER_COUNT;
499

Laszlo Agocs's avatar
Laszlo Agocs committed
500
    contextState.currentSwapChain = nullptr;
501 502 503 504
    ++finishedFrameCount;
    return QRhi::FrameOpSuccess;
}

505 506
QRhi::FrameOpResult QRhiD3D11::beginOffscreenFrame(QRhiCommandBuffer **cb)
{
507 508 509 510 511 512 513 514
    Q_ASSERT(!inFrame);
    inFrame = true;
    ofr.active = true;

    ofr.cbWrapper.resetState();
    *cb = &ofr.cbWrapper;

    return QRhi::FrameOpSuccess;
515 516
}

517
QRhi::FrameOpResult QRhiD3D11::endOffscreenFrame()
518
{
519 520 521 522 523 524 525 526
    Q_ASSERT(inFrame && ofr.active);
    inFrame = false;
    ofr.active = false;

    executeCommandBuffer(&ofr.cbWrapper);

    ++finishedFrameCount;
    return QRhi::FrameOpSuccess;;
527 528
}

Laszlo Agocs's avatar
Laszlo Agocs committed
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
static inline DXGI_FORMAT toD3DTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
{
    const bool srgb = flags.testFlag(QRhiTexture::sRGB);
    switch (format) {
    case QRhiTexture::RGBA8:
        return srgb ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM;
    case QRhiTexture::BGRA8:
        return srgb ? DXGI_FORMAT_B8G8R8A8_UNORM_SRGB : DXGI_FORMAT_B8G8R8A8_UNORM;
    case QRhiTexture::R8:
        return DXGI_FORMAT_R8_UNORM;
    case QRhiTexture::R16:
        return DXGI_FORMAT_R16_UNORM;

    case QRhiTexture::D16:
        return DXGI_FORMAT_R16_TYPELESS;
    case QRhiTexture::D32:
        return DXGI_FORMAT_R32_TYPELESS;

    case QRhiTexture::BC1:
        return srgb ? DXGI_FORMAT_BC1_UNORM_SRGB : DXGI_FORMAT_BC1_UNORM;
    case QRhiTexture::BC2:
        return srgb ? DXGI_FORMAT_BC2_UNORM_SRGB : DXGI_FORMAT_BC2_UNORM;
    case QRhiTexture::BC3:
        return srgb ? DXGI_FORMAT_BC3_UNORM_SRGB : DXGI_FORMAT_BC3_UNORM;
    case QRhiTexture::BC4:
        return DXGI_FORMAT_BC4_UNORM;
    case QRhiTexture::BC5:
        return DXGI_FORMAT_BC5_UNORM;
    case QRhiTexture::BC6H:
        return DXGI_FORMAT_BC6H_UF16;
    case QRhiTexture::BC7:
        return srgb ? DXGI_FORMAT_BC7_UNORM_SRGB : DXGI_FORMAT_BC7_UNORM;

    case QRhiTexture::ETC2_RGB8:
        Q_FALLTHROUGH();
    case QRhiTexture::ETC2_RGB8A1:
        Q_FALLTHROUGH();
    case QRhiTexture::ETC2_RGBA8:
        qWarning("QRhiD3D11 does not support ETC2 textures");
        return DXGI_FORMAT_R8G8B8A8_UNORM;

    case QRhiTexture::ASTC_4x4:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_5x4:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_5x5:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_6x5:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_6x6:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_8x5:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_8x6:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_8x8:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_10x5:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_10x6:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_10x8:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_10x10:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_12x10:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_12x12:
        qWarning("QRhiD3D11 does not support ASTC textures");
        return DXGI_FORMAT_R8G8B8A8_UNORM;

    default:
        Q_UNREACHABLE();
        return DXGI_FORMAT_R8G8B8A8_UNORM;
    }
}

static inline QRhiTexture::Format colorTextureFormatFromDxgiFormat(DXGI_FORMAT format, QRhiTexture::Flags *flags)
{
    switch (format) {
    case DXGI_FORMAT_R8G8B8A8_UNORM:
        return QRhiTexture::RGBA8;
    case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
        if (flags)
            (*flags) |= QRhiTexture::sRGB;
        return QRhiTexture::RGBA8;
    case DXGI_FORMAT_B8G8R8A8_UNORM:
        return QRhiTexture::BGRA8;
    case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
        if (flags)
            (*flags) |= QRhiTexture::sRGB;
        return QRhiTexture::BGRA8;
    case DXGI_FORMAT_R8_UNORM:
        return QRhiTexture::R8;
    case DXGI_FORMAT_R16_UNORM:
        return QRhiTexture::R16;
    default: // this cannot assert, must warn and return unknown
        qWarning("DXGI_FORMAT %d is not a recognized uncompressed color format", format);
        break;
    }
    return QRhiTexture::UnknownFormat;
}

static inline bool isDepthTextureFormat(QRhiTexture::Format format)
633
{
Laszlo Agocs's avatar
Laszlo Agocs committed
634 635 636 637 638
    switch (format) {
    case QRhiTexture::Format::D16:
        Q_FALLTHROUGH();
    case QRhiTexture::Format::D32:
        return true;
639

Laszlo Agocs's avatar
Laszlo Agocs committed
640 641 642 643 644 645 646
    default:
        return false;
    }
}

bool QRhiD3D11::readback(QRhiCommandBuffer *cb, const QRhiReadbackDescription &rb, QRhiReadbackResult *result)
{
647
    Q_ASSERT(inFrame && !inPass);
648

Laszlo Agocs's avatar
Laszlo Agocs committed
649 650 651 652 653 654 655 656
    ID3D11Resource *src;
    DXGI_FORMAT dxgiFormat;
    QSize pixelSize;
    QRhiTexture::Format format;
    UINT subres = 0;
    QD3D11Texture *texD = QRHI_RES(QD3D11Texture, rb.texture);
    QD3D11SwapChain *swapChainD = nullptr;
    if (texD) {
Laszlo Agocs's avatar
Laszlo Agocs committed
657 658 659 660
        if (texD->sampleDesc.Count > 1) {
            qWarning("Multisample texture cannot be read back");
            return false;
        }
Laszlo Agocs's avatar
Laszlo Agocs committed
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
        src = texD->tex;
        dxgiFormat = toD3DTextureFormat(texD->m_format, texD->m_flags);
        pixelSize = texD->m_pixelSize;
        if (rb.level > 0) {
            pixelSize.setWidth(qFloor(float(qMax(1, pixelSize.width() >> rb.level))));
            pixelSize.setHeight(qFloor(float(qMax(1, pixelSize.height() >> rb.level))));
        }
        format = texD->m_format;
        subres = D3D11CalcSubresource(rb.level, rb.layer, texD->mipLevelCount);
    } else {
        Q_ASSERT(contextState.currentSwapChain);
        swapChainD = QRHI_RES(QD3D11SwapChain, contextState.currentSwapChain);
        src = swapChainD->tex[swapChainD->currentFrame];
        dxgiFormat = swapChainD->colorFormat;
        pixelSize = swapChainD->pixelSize;
        format = colorTextureFormatFromDxgiFormat(dxgiFormat, nullptr);
        if (format == QRhiTexture::UnknownFormat)
            return false;
    }
    quint32 bufSize = 0;
    textureFormatInfo(format, pixelSize, nullptr, &bufSize);

    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::ReadPixels;
    cmd.args.readPixels.src = src;
    cmd.args.readPixels.dxgiFormat = dxgiFormat;
    cmd.args.readPixels.format = format;
    cmd.args.readPixels.w = pixelSize.width();
    cmd.args.readPixels.h = pixelSize.height();
    cmd.args.readPixels.byteSize = bufSize;
    cmd.args.readPixels.subres = subres;
    cmd.args.readPixels.result = result;
    cbD->commands.append(cmd);

    return true;
697 698 699 700 701
}

QRhi::FrameOpResult QRhiD3D11::finish()
{
    Q_ASSERT(!inPass);
Laszlo Agocs's avatar
Laszlo Agocs committed
702 703 704 705 706 707 708 709 710 711 712
    if (inFrame) {
        if (ofr.active) {
            Q_ASSERT(!contextState.currentSwapChain);
            executeCommandBuffer(&ofr.cbWrapper);
            ofr.cbWrapper.resetCommands();
        } else {
            Q_ASSERT(contextState.currentSwapChain);
            executeCommandBuffer(&contextState.currentSwapChain->cb);
            contextState.currentSwapChain->cb.resetCommands();
        }
    }
713 714 715
    return QRhi::FrameOpSuccess;
}

716 717 718 719 720 721
void QRhiD3D11::commitResourceUpdates(QRhiResourceUpdateBatch *resourceUpdates)
{
    QRhiResourceUpdateBatchPrivate *ud = QRhiResourceUpdateBatchPrivate::get(resourceUpdates);

    for (const QRhiResourceUpdateBatchPrivate::DynamicBufferUpdate &u : ud->dynamicBufferUpdates) {
        QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, u.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
722
        Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
723 724 725 726 727 728
        memcpy(bufD->dynBuf.data() + u.offset, u.data.constData(), u.data.size());
        bufD->hasPendingDynamicUpdates = true;
    }

    for (const QRhiResourceUpdateBatchPrivate::StaticBufferUpload &u : ud->staticBufferUploads) {
        QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, u.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
729 730
        Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
        Q_ASSERT(u.data.size() == bufD->m_size);
731 732 733 734 735 736 737 738
        if (!(u.data.size() & 0xFF)) {
            context->UpdateSubresource(bufD->buffer, 0, nullptr, u.data.constData(), 0, 0);
        } else {
            // Specify the region since the ID3D11Buffer's size is rounded up to be
            // a multiple of 256 while the data we have has the original size.
            D3D11_BOX box;
            box.left = box.top = box.front = 0;
            box.back = box.bottom = 1;
739
            box.right = u.data.size(); // no -1: right, bottom, back are exclusive, see D3D11_BOX doc
740 741 742 743 744 745 746
            context->UpdateSubresource(bufD->buffer, 0, &box, u.data.constData(), 0, 0);
        }
    }

    for (const QRhiResourceUpdateBatchPrivate::TextureUpload &u : ud->textureUploads) {
        QD3D11Texture *texD = QRHI_RES(QD3D11Texture, u.tex);
        for (int layer = 0, layerCount = u.desc.layers.count(); layer != layerCount; ++layer) {
Laszlo Agocs's avatar
Laszlo Agocs committed
747
            const QRhiTextureUploadDescription::Layer &layerDesc(u.desc.layers[layer]);
748
            for (int level = 0, levelCount = layerDesc.mipImages.count(); level != levelCount; ++level) {
Laszlo Agocs's avatar
Laszlo Agocs committed
749
                const QRhiTextureUploadDescription::Layer::MipLevel mipDesc(layerDesc.mipImages[level]);
750
                UINT subres = D3D11CalcSubresource(level, layer, texD->mipLevelCount);
751 752
                const int dx = mipDesc.destinationTopLeft.x();
                const int dy = mipDesc.destinationTopLeft.y();
753 754 755 756
                D3D11_BOX box;
                box.front = 0;
                // back, right, bottom are exclusive
                box.back = 1;
757
                if (!mipDesc.image.isNull()) {
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
                    QImage img = mipDesc.image;
                    int w = img.width();
                    int h = img.height();
                    int bpl = img.bytesPerLine();
                    const uchar *p = img.constBits();
                    if (!mipDesc.sourceSize.isEmpty() || !mipDesc.sourceTopLeft.isNull()) {
                        const int sx = mipDesc.sourceTopLeft.x();
                        const int sy = mipDesc.sourceTopLeft.y();
                        if (!mipDesc.sourceSize.isEmpty()) {
                            w = mipDesc.sourceSize.width();
                            h = mipDesc.sourceSize.height();
                        }
                        if (img.depth() == 32) {
                            p = img.constBits() + sy * img.bytesPerLine() + sx * 4;
                        } else {
                            img = img.copy(sx, sy, w, h);
                            bpl = img.bytesPerLine();
                            p = img.constBits();
                        }
                    }
                    box.left = dx;
                    box.top = dy;
                    box.right = dx + w;
                    box.bottom = dy + h;
                    context->UpdateSubresource(texD->tex, subres, &box, p, bpl, 0);
783
                } else if (!mipDesc.compressedData.isEmpty() && isCompressedFormat(texD->m_format)) {
784
                    int w, h;
785
                    if (mipDesc.sourceSize.isEmpty()) {
786 787 788
                        w = qFloor(float(qMax(1, texD->m_pixelSize.width() >> level)));
                        h = qFloor(float(qMax(1, texD->m_pixelSize.height() >> level)));
                    } else {
789 790
                        w = mipDesc.sourceSize.width();
                        h = mipDesc.sourceSize.height();
791
                    }
792
                    quint32 bpl = 0;
793 794 795 796 797
                    QSize blockDim;
                    compressedFormatInfo(texD->m_format, QSize(w, h), &bpl, nullptr, &blockDim);
                    // Everything must be a multiple of the block width and
                    // height, so e.g. a mip level of size 2x2 will be 4x4 when it
                    // comes to the actual data.
798 799 800 801
                    box.left = aligned(dx, blockDim.width());
                    box.top = aligned(dy, blockDim.height());
                    box.right = aligned(dx + w, blockDim.width());
                    box.bottom = aligned(dy + h, blockDim.height());
802
                    context->UpdateSubresource(texD->tex, subres, &box,
803 804
                                               mipDesc.compressedData.constData(), bpl, 0);
                }
805 806 807 808
            }
        }
    }

809 810 811 812 813 814 815 816
    for (const QRhiResourceUpdateBatchPrivate::TextureCopy &u : ud->textureCopies) {
        Q_ASSERT(u.src && u.dst);
        QD3D11Texture *srcD = QRHI_RES(QD3D11Texture, u.src);
        QD3D11Texture *dstD = QRHI_RES(QD3D11Texture, u.dst);
        UINT srcSubRes = D3D11CalcSubresource(u.desc.sourceLevel, u.desc.sourceLayer, srcD->mipLevelCount);
        UINT dstSubRes = D3D11CalcSubresource(u.desc.destinationLevel, u.desc.destinationLayer, dstD->mipLevelCount);
        const float dx = u.desc.destinationTopLeft.x();
        const float dy = u.desc.destinationTopLeft.y();
Laszlo Agocs's avatar
Laszlo Agocs committed
817
        const QSize size = u.desc.pixelSize.isEmpty() ? srcD->m_pixelSize : u.desc.pixelSize;
818 819 820 821 822 823 824 825 826 827 828 829
        D3D11_BOX srcBox;
        srcBox.left = u.desc.sourceTopLeft.x();
        srcBox.top = u.desc.sourceTopLeft.y();
        srcBox.front = 0;
        // back, right, bottom are exclusive
        srcBox.right = srcBox.left + size.width();
        srcBox.bottom = srcBox.top + size.height();
        srcBox.back = 1;
        context->CopySubresourceRegion(dstD->tex, dstSubRes, dx, dy, 0,
                                       srcD->tex, srcSubRes, &srcBox);
    }

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    ud->free();
}

static inline QD3D11BasicRenderTargetData *basicRtData(QRhiRenderTarget *rt)
{
    switch (rt->type()) {
    case QRhiRenderTarget::RtRef:
        return &QRHI_RES(QD3D11ReferenceRenderTarget, rt)->d;
    case QRhiRenderTarget::RtTexture:
        return &QRHI_RES(QD3D11TextureRenderTarget, rt)->d;
    default:
        Q_UNREACHABLE();
        return nullptr;
    }
}

void QRhiD3D11::beginPass(QRhiRenderTarget *rt,
                          QRhiCommandBuffer *cb,
                          const QRhiColorClearValue &colorClearValue,
                          const QRhiDepthStencilClearValue &depthStencilClearValue,
                          QRhiResourceUpdateBatch *resourceUpdates)
{
    Q_ASSERT(!inPass);

    if (resourceUpdates)
        commitResourceUpdates(resourceUpdates);

    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    bool needsColorClear = true;
    QD3D11BasicRenderTargetData *rtD = basicRtData(rt);
    if (rt->type() == QRhiRenderTarget::RtTexture) {
        QD3D11TextureRenderTarget *rtTex = QRHI_RES(QD3D11TextureRenderTarget, rt);
Laszlo Agocs's avatar
Laszlo Agocs committed
862
        needsColorClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents);
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
    }

    cbD->currentTarget = rt;

    QD3D11CommandBuffer::Command fbCmd;
    fbCmd.cmd = QD3D11CommandBuffer::Command::SetRenderTarget;
    fbCmd.args.setRenderTarget.rt = rt;
    cbD->commands.append(fbCmd);

    QD3D11CommandBuffer::Command clearCmd;
    clearCmd.cmd = QD3D11CommandBuffer::Command::Clear;
    clearCmd.args.clear.rt = rt;
    clearCmd.args.clear.mask = 0;
    if (!rtD->colorAttCount)
        needsColorClear = false;
    if (rtD->dsAttCount)
        clearCmd.args.clear.mask |= QD3D11CommandBuffer::Command::Depth | QD3D11CommandBuffer::Command::Stencil;
    if (needsColorClear)
        clearCmd.args.clear.mask |= QD3D11CommandBuffer::Command::Color;

    memcpy(clearCmd.args.clear.c, &colorClearValue.rgba, sizeof(float) * 4);
    clearCmd.args.clear.d = depthStencilClearValue.d;
    clearCmd.args.clear.s = depthStencilClearValue.s;

    cbD->commands.append(clearCmd);

    inPass = true;
}

void QRhiD3D11::endPass(QRhiCommandBuffer *cb)
{
    Q_ASSERT(inPass);
    inPass = false;

    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    cbD->currentTarget = nullptr;
}

void QRhiD3D11::updateShaderResourceBindings(QD3D11ShaderResourceBindings *srbD)
{
    srbD->vsubufs.clear();
    srbD->vsubufoffsets.clear();
    srbD->vsubufsizes.clear();

    srbD->fsubufs.clear();
    srbD->fsubufoffsets.clear();
    srbD->fsubufsizes.clear();

    srbD->vssamplers.clear();
    srbD->vsshaderresources.clear();

    srbD->fssamplers.clear();
    srbD->fsshaderresources.clear();

    for (int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
Laszlo Agocs's avatar
Laszlo Agocs committed
918
        const QRhiShaderResourceBinding &b(srbD->sortedBindings[i]);
919 920
        QD3D11ShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);
        switch (b.type) {
Laszlo Agocs's avatar
Laszlo Agocs committed
921
        case QRhiShaderResourceBinding::UniformBuffer:
922 923 924 925 926 927 928 929
        {
            QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, b.ubuf.buf);
            Q_ASSERT(aligned(b.ubuf.offset, 256) == b.ubuf.offset);
            bd.ubuf.generation = bufD->generation;
            const uint offsetInConstants = b.ubuf.offset / 16;
            // size must be 16 mult. (in constants, i.e. multiple of 256 bytes).
            // We can round up if needed since the buffers's actual size
            // (ByteWidth) is always a multiple of 256.
Laszlo Agocs's avatar
Laszlo Agocs committed
930 931
            const uint sizeInConstants = aligned(b.ubuf.maybeSize ? b.ubuf.maybeSize : bufD->m_size, 256) / 16;
            if (b.stage.testFlag(QRhiShaderResourceBinding::VertexStage)) {
932 933 934 935
                srbD->vsubufs.feed(b.binding, bufD->buffer);
                srbD->vsubufoffsets.feed(b.binding, offsetInConstants);
                srbD->vsubufsizes.feed(b.binding, sizeInConstants);
            }
Laszlo Agocs's avatar
Laszlo Agocs committed
936
            if (b.stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
937 938 939 940 941 942
                srbD->fsubufs.feed(b.binding, bufD->buffer);
                srbD->fsubufoffsets.feed(b.binding, offsetInConstants);
                srbD->fsubufsizes.feed(b.binding, sizeInConstants);
            }
        }
            break;
Laszlo Agocs's avatar
Laszlo Agocs committed
943
        case QRhiShaderResourceBinding::SampledTexture:
944 945 946 947
            // A sampler with binding N is mapped to a HLSL sampler and texture
            // with registers sN and tN by SPIRV-Cross.
            bd.stex.texGeneration = QRHI_RES(QD3D11Texture, b.stex.tex)->generation;
            bd.stex.samplerGeneration = QRHI_RES(QD3D11Sampler, b.stex.sampler)->generation;
Laszlo Agocs's avatar
Laszlo Agocs committed
948
            if (b.stage.testFlag(QRhiShaderResourceBinding::VertexStage)) {
949 950 951
                srbD->vssamplers.feed(b.binding, QRHI_RES(QD3D11Sampler, b.stex.sampler)->samplerState);
                srbD->vsshaderresources.feed(b.binding, QRHI_RES(QD3D11Texture, b.stex.tex)->srv);
            }
Laszlo Agocs's avatar
Laszlo Agocs committed
952
            if (b.stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
                srbD->fssamplers.feed(b.binding, QRHI_RES(QD3D11Sampler, b.stex.sampler)->samplerState);
                srbD->fsshaderresources.feed(b.binding, QRHI_RES(QD3D11Texture, b.stex.tex)->srv);
            }
            break;
        default:
            Q_UNREACHABLE();
            break;
        }
    }

    srbD->vsubufs.finish();
    srbD->vsubufoffsets.finish();
    srbD->vsubufsizes.finish();

    srbD->fsubufs.finish();
    srbD->fsubufoffsets.finish();
    srbD->fsubufsizes.finish();

    srbD->vssamplers.finish();
    srbD->vsshaderresources.finish();

    srbD->fssamplers.finish();
    srbD->fsshaderresources.finish();
}

void QRhiD3D11::executeBufferHostWritesForCurrentFrame(QD3D11Buffer *bufD)
{
    if (!bufD->hasPendingDynamicUpdates)
        return;

    bufD->hasPendingDynamicUpdates = false;
    D3D11_MAPPED_SUBRESOURCE mp;
    HRESULT hr = context->Map(bufD->buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mp);
    if (SUCCEEDED(hr)) {
        memcpy(mp.pData, bufD->dynBuf.constData(), bufD->dynBuf.size());
        context->Unmap(bufD->buffer, 0);
    } else {
        qWarning("Failed to map buffer: %s", qPrintable(comErrorMessage(hr)));
    }
}

void QRhiD3D11::setShaderResources(QD3D11ShaderResourceBindings *srbD)
{
    for (int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
Laszlo Agocs's avatar
Laszlo Agocs committed
997
        const QRhiShaderResourceBinding &b(srbD->sortedBindings[i]);
998
        switch (b.type) {
Laszlo Agocs's avatar
Laszlo Agocs committed
999
        case QRhiShaderResourceBinding::UniformBuffer:
1000 1001
        {
            QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, b.ubuf.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
1002
            if (bufD->m_type == QRhiBuffer::Dynamic)
1003 1004 1005
                executeBufferHostWritesForCurrentFrame(bufD);
        }
            break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1006
        case QRhiShaderResourceBinding::SampledTexture:
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
            break;
        default:
            Q_UNREACHABLE();
            break;
        }
    }

    for (const auto &batch : srbD->vssamplers.batches)
        context->VSSetSamplers(batch.startBinding, batch.resources.count(), batch.resources.constData());

    for (const auto &batch : srbD->vsshaderresources.batches) {
        context->VSSetShaderResources(batch.startBinding, batch.resources.count(), batch.resources.constData());
        contextState.vsLastActiveSrvBinding = batch.startBinding + batch.resources.count() - 1;
    }

    for (const auto &batch : srbD->fssamplers.batches)
        context->PSSetSamplers(batch.startBinding, batch.resources.count(), batch.resources.constData());

    for (const auto &batch : srbD->fsshaderresources.batches) {
        context->PSSetShaderResources(batch.startBinding, batch.resources.count(), batch.resources.constData());
        contextState.fsLastActiveSrvBinding = batch.startBinding + batch.resources.count() - 1;
    }

    for (int i = 0, ie = srbD->vsubufs.batches.count(); i != ie; ++i) {
        context->VSSetConstantBuffers1(srbD->vsubufs.batches[i].startBinding,
                                       srbD->vsubufs.batches[i].resources.count(),
                                       srbD->vsubufs.batches[i].resources.constData(),
                                       srbD->vsubufoffsets.batches[i].resources.constData(),
                                       srbD->vsubufsizes.batches[i].resources.constData());
    }

    for (int i = 0, ie = srbD->fsubufs.batches.count(); i != ie; ++i) {
        context->PSSetConstantBuffers1(srbD->fsubufs.batches[i].startBinding,
                                       srbD->fsubufs.batches[i].resources.count(),
                                       srbD->fsubufs.batches[i].resources.constData(),
                                       srbD->fsubufoffsets.batches[i].resources.constData(),
                                       srbD->fsubufsizes.batches[i].resources.constData());
    }
}

void QRhiD3D11::executeCommandBuffer(QD3D11CommandBuffer *cbD)
{
    quint32 stencilRef = 0;
    float blendConstants[] = { 1, 1, 1, 1 };

    for (const QD3D11CommandBuffer::Command &cmd : qAsConst(cbD->commands)) {
        switch (cmd.cmd) {
        case QD3D11CommandBuffer::Command::SetRenderTarget:
        {
            QRhiRenderTarget *rt = cmd.args.setRenderTarget.rt;
            // The new output cannot be bound as input from the previous frame,
            // otherwise the debug layer complains. Avoid this.
            const int nullsrvCount = qMax(contextState.vsLastActiveSrvBinding, contextState.fsLastActiveSrvBinding) + 1;
            QVarLengthArray<ID3D11ShaderResourceView *,
                    D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT> nullsrvs(nullsrvCount);
            for (int i = 0; i < nullsrvs.count(); ++i)
                nullsrvs[i] = nullptr;
            context->VSSetShaderResources(0, nullsrvs.count(), nullsrvs.constData());
            context->PSSetShaderResources(0, nullsrvs.count(), nullsrvs.constData());
            QD3D11BasicRenderTargetData *rtD = basicRtData(rt);
1067
            context->OMSetRenderTargets(rtD->colorAttCount, rtD->colorAttCount ? rtD->rtv : nullptr, rtD->dsv);
1068 1069 1070 1071
        }
            break;
        case QD3D11CommandBuffer::Command::Clear:
        {
1072
            QD3D11BasicRenderTargetData *rtD = basicRtData(cmd.args.clear.rt);
1073 1074
            if (cmd.args.clear.mask & QD3D11CommandBuffer::Command::Color) {
                for (int i = 0; i < rtD->colorAttCount; ++i)
1075
                    context->ClearRenderTargetView(rtD->rtv[i], cmd.args.clear.c);
1076 1077 1078 1079 1080 1081 1082
            }
            uint ds = 0;
            if (cmd.args.clear.mask & QD3D11CommandBuffer::Command::Depth)
                ds |= D3D11_CLEAR_DEPTH;
            if (cmd.args.clear.mask & QD3D11CommandBuffer::Command::Stencil)
                ds |= D3D11_CLEAR_STENCIL;
            if (ds)
1083
                context->ClearDepthStencilView(rtD->dsv, ds, cmd.args.clear.d, cmd.args.clear.s);
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
        }
            break;
        case QD3D11CommandBuffer::Command::Viewport:
        {
            D3D11_VIEWPORT v;
            v.TopLeftX = cmd.args.viewport.x;
            v.TopLeftY = cmd.args.viewport.y;
            v.Width = cmd.args.viewport.w;
            v.Height = cmd.args.viewport.h;
            v.MinDepth = cmd.args.viewport.d0;
            v.MaxDepth = cmd.args.viewport.d1;
            context->RSSetViewports(1, &v);
        }
            break;
        case QD3D11CommandBuffer::Command::Scissor:
        {
            D3D11_RECT r;
            r.left = cmd.args.scissor.x;
            r.top = cmd.args.scissor.y;
            r.right = cmd.args.scissor.x + cmd.args.scissor.w - 1;
            r.bottom = cmd.args.scissor.y + cmd.args.scissor.h - 1;
            context->RSSetScissorRects(1, &r);
        }
            break;
        case QD3D11CommandBuffer::Command::BindVertexBuffers:
            context->IASetVertexBuffers(cmd.args.bindVertexBuffers.startSlot,
                                        cmd.args.bindVertexBuffers.slotCount,
                                        cmd.args.bindVertexBuffers.buffers,
                                        cmd.args.bindVertexBuffers.strides,
                                        cmd.args.bindVertexBuffers.offsets);
            break;
        case QD3D11CommandBuffer::Command::BindIndexBuffer:
            context->IASetIndexBuffer(cmd.args.bindIndexBuffer.buffer,
                                      cmd.args.bindIndexBuffer.format,
                                      cmd.args.bindIndexBuffer.offset);
            break;
        case QD3D11CommandBuffer::Command::BindGraphicsPipeline:
        {
            QD3D11GraphicsPipeline *psD = cmd.args.bindGraphicsPipeline.ps;
            QD3D11ShaderResourceBindings *srbD = cmd.args.bindGraphicsPipeline.srb;
            if (!cmd.args.bindGraphicsPipeline.resOnlyChange) {
                context->VSSetShader(psD->vs, nullptr, 0);
                context->PSSetShader(psD->fs, nullptr, 0);
                context->IASetPrimitiveTopology(psD->d3dTopology);
                context->IASetInputLayout(psD->inputLayout);
                context->OMSetDepthStencilState(psD->dsState, stencilRef);
                context->OMSetBlendState(psD->blendState, blendConstants, 0xffffffff);
                context->RSSetState(psD->rastState);
            }
            setShaderResources(srbD);
        }
            break;
        case QD3D11CommandBuffer::Command::StencilRef:
            stencilRef = cmd.args.stencilRef.ref;
            context->OMSetDepthStencilState(cmd.args.stencilRef.ps->dsState, stencilRef);
            break;
        case QD3D11CommandBuffer::Command::BlendConstants:
            memcpy(blendConstants, cmd.args.blendConstants.c, 4 * sizeof(float));
            context->OMSetBlendState(cmd.args.blendConstants.ps->blendState, blendConstants, 0xffffffff);
            break;
        case QD3D11CommandBuffer::Command::Draw:
            if (cmd.args.draw.ps) {
                if (cmd.args.draw.instanceCount == 1)
                    context->Draw(cmd.args.draw.vertexCount, cmd.args.draw.firstVertex);
                else
                    context->DrawInstanced(cmd.args.draw.vertexCount, cmd.args.draw.instanceCount,
                                           cmd.args.draw.firstVertex, cmd.args.draw.firstInstance);
            } else {
                qWarning("No graphics pipeline active for draw; ignored");
            }
            break;
        case QD3D11CommandBuffer::Command::DrawIndexed:
            if (cmd.args.drawIndexed.ps) {
                if (cmd.args.drawIndexed.instanceCount == 1)
                    context->DrawIndexed(cmd.args.drawIndexed.indexCount, cmd.args.drawIndexed.firstIndex,
                                         cmd.args.drawIndexed.vertexOffset);
                else
                    context->DrawIndexedInstanced(cmd.args.drawIndexed.indexCount, cmd.args.drawIndexed.instanceCount,
                                                  cmd.args.drawIndexed.firstIndex, cmd.args.drawIndexed.vertexOffset,
                                                  cmd.args.drawIndexed.firstInstance);
            } else {
                qWarning("No graphics pipeline active for drawIndexed; ignored");
            }
            break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1168 1169 1170
        case QD3D11CommandBuffer::Command::ReadPixels:
            readPixels(cmd);
            break;
1171 1172 1173 1174 1175 1176
        default:
            break;
        }
    }
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
void QRhiD3D11::readPixels(const QD3D11CommandBuffer::Command &cmd)
{
    D3D11_TEXTURE2D_DESC desc;
    memset(&desc, 0, sizeof(desc));
    desc.Width = cmd.args.readPixels.w;
    desc.Height = cmd.args.readPixels.h;
    desc.MipLevels = 1;
    desc.ArraySize = 1;
    desc.Format = cmd.args.readPixels.dxgiFormat;
    desc.SampleDesc.Count = 1;
    desc.Usage = D3D11_USAGE_STAGING;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
    ID3D11Texture2D *stagingTex;
    HRESULT hr = dev->CreateTexture2D(&desc, nullptr, &stagingTex);
    if (FAILED(hr)) {
        qWarning("Failed to create readback staging texture: %s", qPrintable(comErrorMessage(hr)));
        return;
    }

    context->CopySubresourceRegion(stagingTex, 0, 0, 0, 0,
                                   cmd.args.readPixels.src, cmd.args.readPixels.subres, nullptr);

    D3D11_MAPPED_SUBRESOURCE mp;
    hr = context->Map(stagingTex, 0, D3D11_MAP_READ, 0, &mp);
    if (FAILED(hr)) {
        qWarning("Failed to map readback staging texture: %s", qPrintable(comErrorMessage(hr)));
        stagingTex->Release();
        return;
    }
    QRhiReadbackResult *result = cmd.args.readPixels.result;
    result->format = cmd.args.readPixels.format;
    result->pixelSize = QSize(cmd.args.readPixels.w, cmd.args.readPixels.h);
    result->data.resize(cmd.args.readPixels.byteSize);
    memcpy(result->data.data(), mp.pData, result->data.size());
    context->Unmap(stagingTex, 0);

    stagingTex->Release();

    if (result->completed)
        result->completed();
}

1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
QD3D11Buffer::QD3D11Buffer(QRhiImplementation *rhi, Type type, UsageFlags usage, int size)
    : QRhiBuffer(rhi, type, usage, size)
{
}

void QD3D11Buffer::release()
{
    if (!buffer)
        return;

    dynBuf.clear();

    buffer->Release();
    buffer = nullptr;
}

static inline uint toD3DBufferUsage(QRhiBuffer::UsageFlags usage)
{
    int u = 0;
    if (usage.testFlag(QRhiBuffer::VertexBuffer))
        u |= D3D11_BIND_VERTEX_BUFFER;;
    if (usage.testFlag(QRhiBuffer::IndexBuffer))
        u |= D3D11_BIND_INDEX_BUFFER;
    if (usage.testFlag(QRhiBuffer::UniformBuffer))
        u |= D3D11_BIND_CONSTANT_BUFFER;
    return u;
}

bool QD3D11Buffer::build()
{
    if (buffer)
        release();

    D3D11_BUFFER_DESC desc;
    memset(&desc, 0, sizeof(desc));
Laszlo Agocs's avatar
Laszlo Agocs committed
1254 1255 1256 1257
    desc.ByteWidth = m_usage.testFlag(QRhiBuffer::UniformBuffer) ? aligned(m_size, 256) : m_size;
    desc.Usage = m_type == Dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
    desc.BindFlags = toD3DBufferUsage(m_usage);
    desc.CPUAccessFlags = m_type == Dynamic ? D3D11_CPU_ACCESS_WRITE : 0;
1258 1259 1260 1261 1262 1263 1264 1265

    QRHI_RES_RHI(QRhiD3D11);
    HRESULT hr = rhiD->dev->CreateBuffer(&desc, nullptr, &buffer);
    if (FAILED(hr)) {
        qWarning("Failed to create buffer: %s", qPrintable(comErrorMessage(hr)));
        return false;
    }

Laszlo Agocs's avatar
Laszlo Agocs committed
1266 1267
    if (m_type == Dynamic) {
        dynBuf.resize(m_size);
1268 1269 1270 1271 1272 1273 1274 1275
        hasPendingDynamicUpdates = false;
    }

    generation += 1;
    return true;
}

QD3D11RenderBuffer::QD3D11RenderBuffer(QRhiImplementation *rhi, Type type, const QSize &pixelSize,
Laszlo Agocs's avatar
Laszlo Agocs committed
1276 1277
                                       int sampleCount, QRhiRenderBuffer::Flags flags)
    : QRhiRenderBuffer(rhi, type, pixelSize, sampleCount, flags)
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
{
}

void QD3D11RenderBuffer::release()
{
    if (!tex)
        return;

    if (dsv) {
        dsv->Release();
        dsv = nullptr;
    }

    tex->Release();
    tex = nullptr;
}

bool QD3D11RenderBuffer::build()
{
    if (tex)
        release();

    QRHI_RES_RHI(QRhiD3D11);
    static const DXGI_FORMAT dsFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
Laszlo Agocs's avatar
Laszlo Agocs committed
1302
    if (m_type == DepthStencil) {
1303 1304
        D3D11_TEXTURE2D_DESC desc;
        memset(&desc, 0, sizeof(desc));
Laszlo Agocs's avatar
Laszlo Agocs committed
1305 1306
        desc.Width = m_pixelSize.width();
        desc.Height = m_pixelSize.height();
1307 1308 1309
        desc.MipLevels = 1;
        desc.ArraySize = 1;
        desc.Format = dsFormat;
1310
        desc.SampleDesc = rhiD->effectiveSampleCount(m_sampleCount);
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
        desc.Usage = D3D11_USAGE_DEFAULT;
        desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
        HRESULT hr = rhiD->dev->CreateTexture2D(&desc, nullptr, &tex);
        if (FAILED(hr)) {
            qWarning("Failed to create depth-stencil buffer: %s", qPrintable(comErrorMessage(hr)));
            return false;
        }
        D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
        memset(&dsvDesc, 0, sizeof(dsvDesc));
        dsvDesc.Format = dsFormat;
Laszlo Agocs's avatar
Laszlo Agocs committed
1321 1322
        dsvDesc.ViewDimension = desc.SampleDesc.Count > 1 ? D3D11_DSV_DIMENSION_TEXTURE2DMS
                                                          : D3D11_DSV_DIMENSION_TEXTURE2D;
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
        hr = rhiD->dev->CreateDepthStencilView(tex, &dsvDesc, &dsv);
        if (FAILED(hr)) {
            qWarning("Failed to create dsv: %s", qPrintable(comErrorMessage(hr)));
            return false;
        }
        return true;
    }

    return false;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1334 1335 1336
QD3D11Texture::QD3D11Texture(QRhiImplementation *rhi, Format format, const QSize &pixelSize,
                             int sampleCount, Flags flags)
    : QRhiTexture(rhi, format, pixelSize, sampleCount, flags)
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
{
}

void QD3D11Texture::release()
{
    if (!tex)
        return;

    if (srv) {
        srv->Release();
        srv = nullptr;
    }

    tex->Release();
    tex = nullptr;
}

static inline DXGI_FORMAT toD3DDepthTextureSRVFormat(QRhiTexture::Format format)
{
    switch (format) {
    case QRhiTexture::Format::D16:
        return DXGI_FORMAT_R16_FLOAT;
    case QRhiTexture::Format::D32:
        return DXGI_FORMAT_R32_FLOAT;
    default:
        Q_UNREACHABLE();
        return DXGI_FORMAT_R32_FLOAT;
    }
}

static inline DXGI_FORMAT toD3DDepthTextureDSVFormat(QRhiTexture::Format format)
{
    switch (format) {
    case QRhiTexture::Format::D16:
        return DXGI_FORMAT_D16_UNORM;
    case QRhiTexture::Format::D32:
        return DXGI_FORMAT_D32_FLOAT;
    default:
        Q_UNREACHABLE();
        return DXGI_FORMAT_D32_FLOAT;
    }
}

static inline QSize safeSize(const QSize &size)
{
    return size.isEmpty() ? QSize(16, 16) : size;
}

bool QD3D11Texture::build()
{
    if (tex)
        release();

Laszlo Agocs's avatar
Laszlo Agocs committed
1390
    QRHI_RES_RHI(QRhiD3D11);
Laszlo Agocs's avatar
Laszlo Agocs committed
1391 1392 1393 1394
    const QSize size = safeSize(m_pixelSize);
    const bool isDepth = isDepthTextureFormat(m_format);
    const bool isCube = m_flags.testFlag(CubeMap);
    const bool hasMipMaps = m_flags.testFlag(MipMapped);
1395 1396

    mipLevelCount = hasMipMaps ? qCeil(log2(qMax(size.width(), size.height()))) + 1 : 1;
Laszlo Agocs's avatar
Laszlo Agocs committed
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
    sampleDesc = rhiD->effectiveSampleCount(m_sampleCount);
    if (sampleDesc.Count > 1) {
        if (isCube) {
            qWarning("Cubemap texture cannot be multisample");
            return false;
        }
        if (hasMipMaps) {
            qWarning("Multisample texture cannot have mipmaps");
            return false;
        }
    }
1408 1409

    uint bindFlags = D3D11_BIND_SHADER_RESOURCE;
Laszlo Agocs's avatar
Laszlo Agocs committed
1410
    if (m_flags.testFlag(RenderTarget)) {
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
        if (isDepth)
            bindFlags |= D3D11_BIND_DEPTH_STENCIL;
        else
            bindFlags |= D3D11_BIND_RENDER_TARGET;
    }

    D3D11_TEXTURE2D_DESC desc;
    memset(&desc, 0, sizeof(desc));
    desc.Width = size.width();
    desc.Height = size.height();
    desc.MipLevels = mipLevelCount;
    desc.ArraySize = isCube ? 6 : 1;;
1423
    desc.Format = toD3DTextureFormat(m_format, m_flags);
Laszlo Agocs's avatar
Laszlo Agocs committed
1424
    desc.SampleDesc = sampleDesc;
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
    desc.Usage = D3D11_USAGE_DEFAULT;
    desc.BindFlags = bindFlags;
    desc.MiscFlags = isCube ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;

    HRESULT hr = rhiD->dev->CreateTexture2D(&desc, nullptr, &tex);
    if (FAILED(hr)) {
        qWarning("Failed to create texture: %s", qPrintable(comErrorMessage(hr)));
        return false;
    }

    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
    memset(&srvDesc, 0, sizeof(srvDesc));
Laszlo Agocs's avatar
Laszlo Agocs committed
1437
    srvDesc.Format = isDepth ? toD3DDepthTextureSRVFormat(m_format) : desc.Format;
1438 1439 1440 1441
    if (isCube) {
        srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
        srvDesc.TextureCube.MipLevels = desc.MipLevels;
    } else {
Laszlo Agocs's avatar
Laszlo Agocs committed
1442 1443 1444 1445 1446 1447
        if (sampleDesc.Count > 1) {
            srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMS;
        } else {
            srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
            srvDesc.Texture2D.MipLevels = desc.MipLevels;
        }
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    }

    hr = rhiD->dev->CreateShaderResourceView(tex, &srvDesc, &srv);
    if (FAILED(hr)) {
        qWarning("Failed to create srv: %s", qPrintable(comErrorMessage(hr)));
        return false;
    }

    generation += 1;
    return true;
}

QD3D11Sampler::QD3D11Sampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode,
                             AddressMode u, AddressMode v, AddressMode w)
    : QRhiSampler(rhi, magFilter, minFilter, mipmapMode, u, v, w)
{
}

void QD3D11Sampler::release()
{
    if (!samplerState)
        return;

    samplerState->Release();
    samplerState = nullptr;
}

static inline D3D11_FILTER toD3DFilter(QRhiSampler::Filter minFilter, QRhiSampler::Filter magFilter, QRhiSampler::Filter mipFilter)
{
    if (minFilter == QRhiSampler::Nearest) {
        if (magFilter == QRhiSampler::Nearest) {
            if (mipFilter == QRhiSampler::Linear)
                return D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR;
            else
                return D3D11_FILTER_MIN_MAG_MIP_POINT;
        } else {
            if (mipFilter == QRhiSampler::Linear)
                return D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR;
            else
                return D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT;
        }
    } else {
        if (magFilter == QRhiSampler::Nearest) {
            if (mipFilter == QRhiSampler::Linear)
                return D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR;
            else
                return D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT;
        } else {
            if (mipFilter == QRhiSampler::Linear)
                return D3D11_FILTER_MIN_MAG_MIP_LINEAR;
            else
                return D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
        }
    }

    Q_UNREACHABLE();
    return D3D11_FILTER_MIN_MAG_MIP_LINEAR;
}

static inline D3D11_TEXTURE_ADDRESS_MODE toD3DAddressMode(QRhiSampler::AddressMode m)
{
    switch (m) {
    case QRhiSampler::Repeat:
        return D3D11_TEXTURE_ADDRESS_WRAP;
    case QRhiSampler::ClampToEdge:
        return D3D11_TEXTURE_ADDRESS_CLAMP;
    case QRhiSampler::Border:
        return D3D11_TEXTURE_ADDRESS_BORDER;
    case QRhiSampler::Mirror:
        return D3D11_TEXTURE_ADDRESS_MIRROR;
    case QRhiSampler::MirrorOnce:
        return D3D11_TEXTURE_ADDRESS_MIRROR_ONCE;
    default:
        Q_UNREACHABLE();
        return D3D11_TEXTURE_ADDRESS_CLAMP;
    }
}

bool QD3D11Sampler::build()
{
    if (samplerState)
        release();

    D3D11_SAMPLER_DESC desc;
    memset(&desc, 0, sizeof(desc));
Laszlo Agocs's avatar
Laszlo Agocs committed
1533 1534 1535 1536
    desc.Filter = toD3DFilter(m_minFilter, m_magFilter, m_mipmapMode);
    desc.AddressU = toD3DAddressMode(m_addressU);
    desc.AddressV = toD3DAddressMode(m_addressV);
    desc.AddressW = toD3DAddressMode(m_addressW);
1537
    desc.MaxAnisotropy = 1.0f;
Laszlo Agocs's avatar
Laszlo Agocs committed
1538
    desc.MaxLOD = m_mipmapMode == None ? 0.0f : 1000.0f;
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550

    QRHI_RES_RHI(QRhiD3D11);
    HRESULT hr = rhiD->dev->CreateSamplerState(&desc, &samplerState);
    if (FAILED(hr)) {
        qWarning("Failed to create sampler state: %s", qPrintable(comErrorMessage(hr)));
        return false;
    }

    generation += 1;
    return true;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1551
// dummy, no Vulkan-style RenderPass+Framebuffer concept here
1552 1553
QD3D11RenderPassDescriptor::QD3D11RenderPassDescriptor(QRhiImplementation *rhi)
    : QRhiRenderPassDescriptor(rhi)
1554 1555 1556
{
}