Debian Codegraph @

tests/manual/rhi/hdr/hdr.cpp

raw
1 // Copyright (C) 2023 The Qt Company Ltd.
2 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
4 // Test application for HDR with scRGB.
5 // Launch with the argument "scrgb" or "sdr", perhaps side-by-side even.
6
7 #define EXAMPLEFW_PREINIT
8 #define EXAMPLEFW_IMGUI
9 #include "../shared/examplefw.h"
10
11 #include "../shared/cube.h"
12
13 QByteArray loadHdr(const QString &fn, QSize *size)
14 {
15 QFile f(fn);
16 if (!f.open(QIODevice::ReadOnly)) {
17 qWarning("Failed to open %s", qPrintable(fn));
18 return QByteArray();
19 }
20
21 char sig[256];
22 f.read(sig, 11);
23 if (strncmp(sig, "#?RADIANCE\n", 11))
24 return QByteArray();
25
26 QByteArray buf = f.readAll();
27 const char *p = buf.constData();
28 const char *pEnd = p + buf.size();
29
30 // Process lines until the empty one.
31 QByteArray line;
32 while (p < pEnd) {
33 char c = *p++;
34 if (c == '\n') {
35 if (line.isEmpty())
36 break;
37 if (line.startsWith(QByteArrayLiteral("FORMAT="))) {
38 const QByteArray format = line.mid(7).trimmed();
39 if (format != QByteArrayLiteral("32-bit_rle_rgbe")) {
40 qWarning("HDR format '%s' is not supported", format.constData());
41 return QByteArray();
42 }
43 }
44 line.clear();
45 } else {
46 line.append(c);
47 }
48 }
49 if (p == pEnd) {
50 qWarning("Malformed HDR image data at property strings");
51 return QByteArray();
52 }
53
54 // Get the resolution string.
55 while (p < pEnd) {
56 char c = *p++;
57 if (c == '\n')
58 break;
59 line.append(c);
60 }
61 if (p == pEnd) {
62 qWarning("Malformed HDR image data at resolution string");
63 return QByteArray();
64 }
65
66 int w = 0, h = 0;
67 // We only care about the standard orientation.
68 if (!sscanf(line.constData(), "-Y %d +X %d", &h, &w)) {
69 qWarning("Unsupported HDR resolution string '%s'", line.constData());
70 return QByteArray();
71 }
72 if (w <= 0 || h <= 0) {
73 qWarning("Invalid HDR resolution");
74 return QByteArray();
75 }
76
77 // output is RGBA32F
78 const int blockSize = 4 * sizeof(float);
79 QByteArray data;
80 data.resize(w * h * blockSize);
81
82 typedef unsigned char RGBE[4];
83 RGBE *scanline = new RGBE[w];
84
85 for (int y = 0; y < h; ++y) {
86 if (pEnd - p < 4) {
87 qWarning("Unexpected end of HDR data");
88 delete[] scanline;
89 return QByteArray();
90 }
91
92 scanline[0][0] = *p++;
93 scanline[0][1] = *p++;
94 scanline[0][2] = *p++;
95 scanline[0][3] = *p++;
96
97 if (scanline[0][0] == 2 && scanline[0][1] == 2 && scanline[0][2] < 128) {
98 // new rle, the first pixel was a dummy
99 for (int channel = 0; channel < 4; ++channel) {
100 for (int x = 0; x < w && p < pEnd; ) {
101 unsigned char c = *p++;
102 if (c > 128) { // run
103 if (p < pEnd) {
104 int repCount = c & 127;
105 c = *p++;
106 while (repCount--)
107 scanline[x++][channel] = c;
108 }
109 } else { // not a run
110 while (c-- && p < pEnd)
111 scanline[x++][channel] = *p++;
112 }
113 }
114 }
115 } else {
116 // old rle
117 scanline[0][0] = 2;
118 int bitshift = 0;
119 int x = 1;
120 while (x < w && pEnd - p >= 4) {
121 scanline[x][0] = *p++;
122 scanline[x][1] = *p++;
123 scanline[x][2] = *p++;
124 scanline[x][3] = *p++;
125
126 if (scanline[x][0] == 1 && scanline[x][1] == 1 && scanline[x][2] == 1) { // run
127 int repCount = scanline[x][3] << bitshift;
128 while (repCount--) {
129 memcpy(scanline[x], scanline[x - 1], 4);
130 ++x;
131 }
132 bitshift += 8;
133 } else { // not a run
134 ++x;
135 bitshift = 0;
136 }
137 }
138 }
139
140 // adjust for -Y orientation
141 float *fp = reinterpret_cast<float *>(data.data() + (h - 1 - y) * blockSize * w);
142 for (int x = 0; x < w; ++x) {
143 float d = qPow(2.0f, float(scanline[x][3]) - 128.0f);
144 float r = scanline[x][0] / 256.0f * d;
145 float g = scanline[x][1] / 256.0f * d;
146 float b = scanline[x][2] / 256.0f * d;
147 float a = 1.0f;
148 *fp++ = r;
149 *fp++ = g;
150 *fp++ = b;
151 *fp++ = a;
152 }
153 }
154
155 delete[] scanline;
156
157 *size = QSize(w, h);
158
159 return data;
160 }
161
162 struct {
163 QMatrix4x4 winProj;
164 QList<QRhiResource *> releasePool;
165 QRhiResourceUpdateBatch *initialUpdates = nullptr;
166 QRhiBuffer *vbuf = nullptr;
167 QRhiBuffer *ubuf = nullptr;
168 QRhiTexture *tex = nullptr;
169 QRhiSampler *sampler = nullptr;
170 QRhiShaderResourceBindings *srb = nullptr;
171 QRhiGraphicsPipeline *ps = nullptr;
172 bool showDemoWindow = true;
173 QVector3D rotation;
174
175 bool usingHDRWindow;
176 bool adjustSDR = false;
177 float SDRWhiteLevelInNits = 200.0f;
178 bool tonemapHDR = false;
179 float tonemapInMax = 2.5f;
180 float tonemapOutMax = 0.0f;
181
182 QString imageFile;
183 } d;
184
185 void preInit()
186 {
187 QStringList args = QCoreApplication::arguments();
188 if (args.contains("scrgb")) {
189 d.usingHDRWindow = true;
190 swapchainFormat = QRhiSwapChain::HDRExtendedSrgbLinear;
191 } else if (args.contains("p3")) {
192 d.usingHDRWindow = true;
193 swapchainFormat = QRhiSwapChain::HDRExtendedDisplayP3Linear;
194 } else if (args.contains("sdr")) {
195 d.usingHDRWindow = false;
196 swapchainFormat = QRhiSwapChain::SDR;
197 } else {
198 qFatal("Missing command line argument, specify scrgb or sdr");
199 }
200
201 if (args.contains("file")) {
202 d.imageFile = args[args.indexOf("file") + 1];
203 qDebug("Using HDR image file %s", qPrintable(d.imageFile));
204 } else {
205 qFatal("Missing command line argument, specify 'file' followed by a .hdr file. "
206 "Download for example the original .exr from https://viewer.openhdr.org/i/5fcb9a595812624a99d24c62/linear "
207 "and use ImageMagick's 'convert' to convert from .exr to .hdr");
208 }
209 }
210
211 void Window::customInit()
212 {
213 if (!m_r->isTextureFormatSupported(QRhiTexture::RGBA32F))
214 qWarning("RGBA32F texture format is not supported");
215
216 d.initialUpdates = m_r->nextResourceUpdateBatch();
217
218 d.vbuf = m_r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(cube));
219 d.vbuf->create();
220 d.releasePool << d.vbuf;
221
222 d.initialUpdates->uploadStaticBuffer(d.vbuf, cube);
223
224 d.ubuf = m_r->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 64 + 4 * 4);
225 d.ubuf->create();
226 d.releasePool << d.ubuf;
227
228 qint32 flip = 1;
229 d.initialUpdates->updateDynamicBuffer(d.ubuf, 64, 4, &flip);
230
231 qint32 doLinearToSRGBInShader = !d.usingHDRWindow;
232 d.initialUpdates->updateDynamicBuffer(d.ubuf, 68, 4, &doLinearToSRGBInShader);
233
234 QSize size;
235 QByteArray floatData = loadHdr(d.imageFile, &size);
236
237 d.tex = m_r->newTexture(QRhiTexture::RGBA32F, size);
238 d.releasePool << d.tex;
239 d.tex->create();
240 QRhiTextureUploadDescription desc({ 0, 0, { floatData.constData(), quint32(floatData.size()) } });
241 d.initialUpdates->uploadTexture(d.tex, desc);
242
243 d.sampler = m_r->newSampler(QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
244 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge);
245 d.releasePool << d.sampler;
246 d.sampler->create();
247
248 d.srb = m_r->newShaderResourceBindings();
249 d.releasePool << d.srb;
250 d.srb->setBindings({
251 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, d.ubuf),
252 QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, d.tex, d.sampler)
253 });
254 d.srb->create();
255
256 d.ps = m_r->newGraphicsPipeline();
257 d.releasePool << d.ps;
258 d.ps->setCullMode(QRhiGraphicsPipeline::Back);
259 const QRhiShaderStage stages[] = {
260 { QRhiShaderStage::Vertex, getShader(QLatin1String(":/hdrtexture.vert.qsb")) },
261 { QRhiShaderStage::Fragment, getShader(QLatin1String(":/hdrtexture.frag.qsb")) }
262 };
263 d.ps->setShaderStages(stages, stages + 2);
264 QRhiVertexInputLayout inputLayout;
265 inputLayout.setBindings({
266 { 3 * sizeof(float) },
267 { 2 * sizeof(float) }
268 });
269 inputLayout.setAttributes({
270 { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
271 { 1, 1, QRhiVertexInputAttribute::Float2, 0 }
272 });
273 d.ps->setVertexInputLayout(inputLayout);
274 d.ps->setShaderResourceBindings(d.srb);
275 d.ps->setRenderPassDescriptor(m_rp);
276 d.ps->create();
277 }
278
279 void Window::customRelease()
280 {
281 qDeleteAll(d.releasePool);
282 d.releasePool.clear();
283 }
284
285 void Window::customRender()
286 {
287 if (d.tonemapOutMax == 0.0f) {
288 QRhiSwapChainHdrInfo info = m_sc->hdrInfo();
289 switch (info.limitsType) {
290 case QRhiSwapChainHdrInfo::LuminanceInNits:
291 d.tonemapOutMax = info.limits.luminanceInNits.maxLuminance / 80.0f;
292 break;
293 case QRhiSwapChainHdrInfo::ColorComponentValue:
294 // because on macOS it changes dynamically when starting up, so retry in next frame if it's still just 1.0
295 if (info.limits.colorComponentValue.maxColorComponentValue > 1.0f)
296 d.tonemapOutMax = info.limits.colorComponentValue.maxColorComponentValue;
297 break;
298 }
299 }
300
301 QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
302 QRhiResourceUpdateBatch *u = m_r->nextResourceUpdateBatch();
303 if (d.initialUpdates) {
304 u->merge(d.initialUpdates);
305 d.initialUpdates->release();
306 d.initialUpdates = nullptr;
307 }
308
309 QMatrix4x4 mvp = m_proj;
310 mvp.rotate(d.rotation.x(), 1, 0, 0);
311 mvp.rotate(d.rotation.y(), 0, 1, 0);
312 mvp.rotate(d.rotation.z(), 0, 0, 1);
313 u->updateDynamicBuffer(d.ubuf, 0, 64, mvp.constData());
314
315 if (d.usingHDRWindow && d.tonemapHDR) {
316 u->updateDynamicBuffer(d.ubuf, 72, 4, &d.tonemapInMax);
317 u->updateDynamicBuffer(d.ubuf, 76, 4, &d.tonemapOutMax);
318 } else {
319 float zero[2] = {};
320 u->updateDynamicBuffer(d.ubuf, 72, 8, zero);
321 }
322
323 QColor clearColor = Qt::green; // sRGB
324 if (d.usingHDRWindow && d.adjustSDR) {
325 float sdrMultiplier = d.SDRWhiteLevelInNits / 80.0f; // scRGB 1.0 = 80 nits (and linear gamma)
326 clearColor = QColor::fromRgbF(clearColor.redF() * sdrMultiplier,
327 clearColor.greenF() * sdrMultiplier,
328 clearColor.blueF() * sdrMultiplier,
329 1.0f);
330 }
331
332 const QSize outputSizeInPixels = m_sc->currentPixelSize();
333 cb->beginPass(m_sc->currentFrameRenderTarget(), clearColor, { 1.0f, 0 }, u);
334
335 cb->setGraphicsPipeline(d.ps);
336 cb->setViewport(QRhiViewport(0, 0, outputSizeInPixels.width(), outputSizeInPixels.height()));
337 cb->setShaderResources();
338 const QRhiCommandBuffer::VertexInput vbufBindings[] = {
339 { d.vbuf, 0 },
340 { d.vbuf, quint32(36 * 3 * sizeof(float)) }
341 };
342 cb->setVertexInput(0, 2, vbufBindings);
343 cb->draw(36);
344
345 m_imguiRenderer->render();
346
347 cb->endPass();
348 }
349
350 static void addTip(const char *s)
351 {
352 ImGui::SameLine();
353 ImGui::TextDisabled("(?)");
354 if (ImGui::IsItemHovered()) {
355 ImGui::BeginTooltip();
356 ImGui::PushTextWrapPos(300);
357 ImGui::TextUnformatted(s);
358 ImGui::PopTextWrapPos();
359 ImGui::EndTooltip();
360 }
361 }
362
363 void Window::customGui()
364 {
365 ImGui::SetNextWindowBgAlpha(1.0f);
366 ImGui::SetNextWindowPos(ImVec2(10, 420), ImGuiCond_FirstUseEver);
367 ImGui::SetNextWindowSize(ImVec2(800, 300), ImGuiCond_FirstUseEver);
368 ImGui::Begin("HDR test");
369
370 if (d.usingHDRWindow) {
371 if (swapchainFormat == QRhiSwapChain::HDRExtendedDisplayP3Linear) {
372 ImGui::Text("The window is now Extended Linear Display P3 + FP16 color buffer,\n"
373 "the ImGui UI and the green background are considered SDR content,\n"
374 "the cube is using a HDR texture.");
375 } else {
376 ImGui::Text("The window is now scRGB (Extended Linear sRGB) + FP16 color buffer,\n"
377 "the ImGui UI and the green background are considered SDR content,\n"
378 "the cube is using a HDR texture.");
379 }
380 ImGui::Checkbox("Adjust SDR content", &d.adjustSDR);
381 addTip("Multiplies fragment colors for non-HDR content with sdr_white_level / 80. "
382 "Not relevant with macOS (due to EDR being display-referred).");
383 if (d.adjustSDR) {
384 ImGui::SliderFloat("SDR white level (nits)", &d.SDRWhiteLevelInNits, 0.0f, 1000.0f);
385 imguiHDRMultiplier = d.SDRWhiteLevelInNits / 80.0f; // scRGB 1.0 = 80 nits (and linear gamma)
386 } else {
387 imguiHDRMultiplier = 1.0f; // 0 would mean linear to sRGB; don't want that with HDR
388 }
389 ImGui::Separator();
390 ImGui::Checkbox("Tonemap HDR content", &d.tonemapHDR);
391 addTip("Perform some most basic Reinhard tonemapping (changed to suit HDR) on the 3D content (the cube). "
392 "Display max luminance is set to the max color component value (macOS) or max luminance in nits / 80 (Windows) by default.");
393 if (d.tonemapHDR) {
394 ImGui::SliderFloat("Content max luminance\n(color component value)", &d.tonemapInMax, 0.0f, 20.0f);
395 ImGui::SliderFloat("Display max luminance\n(color component value)", &d.tonemapOutMax, 0.0f, 20.0f);
396 }
397 } else {
398 ImGui::Text("The window is standard dynamic range (no HDR, so non-linear sRGB effectively).\n"
399 "Here we just do linear -> sRGB for everything (UI, textured cube)\n"
400 "at the end of the pipeline, while the Qt::green background is already sRGB.");
401 }
402
403 ImGui::End();
404
405 ImGui::SetNextWindowPos(ImVec2(850, 560), ImGuiCond_FirstUseEver);
406 ImGui::SetNextWindowSize(ImVec2(420, 140), ImGuiCond_FirstUseEver);
407 ImGui::Begin("Misc");
408 float *rot = reinterpret_cast<float *>(&d.rotation);
409 ImGui::SliderFloat("Rotation X", &rot[0], 0.0f, 360.0f);
410 ImGui::SliderFloat("Rotation Y", &rot[1], 0.0f, 360.0f);
411 ImGui::SliderFloat("Rotation Z", &rot[2], 0.0f, 360.0f);
412 ImGui::End();
413
414 if (d.usingHDRWindow) {
415 ImGui::SetNextWindowPos(ImVec2(850, 10), ImGuiCond_FirstUseEver);
416 ImGui::SetNextWindowSize(ImVec2(420, 180), ImGuiCond_FirstUseEver);
417 ImGui::Begin("Actual platform info");
418 QRhiSwapChainHdrInfo info = m_sc->hdrInfo();
419 switch (info.limitsType) {
420 case QRhiSwapChainHdrInfo::LuminanceInNits:
421 ImGui::Text("Platform provides luminance in nits");
422 addTip("Windows/D3D: On laptops this will be screen brightness dependent. Increasing brightness implies the max luminance decreases. "
423 "It also seems to be affected by HDR Content Brightness in the Settings, if there is one (e.g. on laptops; not to be confused with SDR Content Brightess). "
424 "(note that the DXGI query does not seem to return changed values if there are runtime changes unless restarting the app).");
425 ImGui::Text("Min luminance: %.4f\nMax luminance: %.4f",
426 info.limits.luminanceInNits.minLuminance,
427 info.limits.luminanceInNits.maxLuminance);
428 break;
429 case QRhiSwapChainHdrInfo::ColorComponentValue:
430 ImGui::Text("Platform provides color component values");
431 addTip("macOS/Metal: On laptops this will be screen brightness dependent. Increasing brightness decreases the max color value. "
432 "Max brightness may bring it down to 1.0.");
433 ImGui::Text("maxColorComponentValue: %.4f\nmaxPotentialColorComponentValue: %.4f",
434 info.limits.colorComponentValue.maxColorComponentValue,
435 info.limits.colorComponentValue.maxPotentialColorComponentValue);
436 break;
437 }
438 ImGui::Separator();
439 switch (info.luminanceBehavior) {
440 case QRhiSwapChainHdrInfo::SceneReferred:
441 ImGui::Text("Luminance behavior is scene-referred");
442 break;
443 case QRhiSwapChainHdrInfo::DisplayReferred:
444 ImGui::Text("Luminance behavior is display-referred");
445 break;
446 }
447 addTip("Windows (DWM) HDR is scene-referred: 1.0 = 80 nits.\n\n"
448 "Apple EDR is display-referred: the value of 1.0 refers to whatever the system's current SDR white level is (100, 200, ... nits depending on the brightness).");
449 if (info.luminanceBehavior == QRhiSwapChainHdrInfo::SceneReferred) {
450 ImGui::Text("SDR white level: %.4f nits", info.sdrWhiteLevel);
451 addTip("On Windows this is queried from DISPLAYCONFIG_SDR_WHITE_LEVEL. "
452 "Affected by the slider in the Windows Settings (System/Display/HDR/[S|H]DR Content Brightness). "
453 "With max screen brightness (laptops) the value will likely be the same as the max luminance.");
454 }
455 ImGui::End();
456 }
457 }