Debian Codegraph @

tests/manual/rhi/floattexture/floattexture.cpp

raw
1 /****************************************************************************
2 **
3 ** Copyright (C) 2018 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the examples of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 ** * Redistributions of source code must retain the above copyright
25 ** notice, this list of conditions and the following disclaimer.
26 ** * Redistributions in binary form must reproduce the above copyright
27 ** notice, this list of conditions and the following disclaimer in
28 ** the documentation and/or other materials provided with the
29 ** distribution.
30 ** * Neither the name of The Qt Company Ltd nor the names of its
31 ** contributors may be used to endorse or promote products derived
32 ** from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50
51 #include "../shared/examplefw.h"
52 #include <qmath.h>
53
54 QByteArray loadHdr(const QString &fn, QSize *size)
55 {
56 QFile f(fn);
57 if (!f.open(QIODevice::ReadOnly)) {
58 qWarning("Failed to open %s", qPrintable(fn));
59 return QByteArray();
60 }
61
62 char sig[256];
63 f.read(sig, 11);
64 if (strncmp(sig, "#?RADIANCE\n", 11))
65 return QByteArray();
66
67 QByteArray buf = f.readAll();
68 const char *p = buf.constData();
69 const char *pEnd = p + buf.size();
70
71 // Process lines until the empty one.
72 QByteArray line;
73 while (p < pEnd) {
74 char c = *p++;
75 if (c == '\n') {
76 if (line.isEmpty())
77 break;
78 if (line.startsWith(QByteArrayLiteral("FORMAT="))) {
79 const QByteArray format = line.mid(7).trimmed();
80 if (format != QByteArrayLiteral("32-bit_rle_rgbe")) {
81 qWarning("HDR format '%s' is not supported", format.constData());
82 return QByteArray();
83 }
84 }
85 line.clear();
86 } else {
87 line.append(c);
88 }
89 }
90 if (p == pEnd) {
91 qWarning("Malformed HDR image data at property strings");
92 return QByteArray();
93 }
94
95 // Get the resolution string.
96 while (p < pEnd) {
97 char c = *p++;
98 if (c == '\n')
99 break;
100 line.append(c);
101 }
102 if (p == pEnd) {
103 qWarning("Malformed HDR image data at resolution string");
104 return QByteArray();
105 }
106
107 int w = 0, h = 0;
108 // We only care about the standard orientation.
109 if (!sscanf(line.constData(), "-Y %d +X %d", &h, &w)) {
110 qWarning("Unsupported HDR resolution string '%s'", line.constData());
111 return QByteArray();
112 }
113 if (w <= 0 || h <= 0) {
114 qWarning("Invalid HDR resolution");
115 return QByteArray();
116 }
117
118 // output is RGBA32F
119 const int blockSize = 4 * sizeof(float);
120 QByteArray data;
121 data.resize(w * h * blockSize);
122
123 typedef unsigned char RGBE[4];
124 RGBE *scanline = new RGBE[w];
125
126 for (int y = 0; y < h; ++y) {
127 if (pEnd - p < 4) {
128 qWarning("Unexpected end of HDR data");
129 delete[] scanline;
130 return QByteArray();
131 }
132
133 scanline[0][0] = *p++;
134 scanline[0][1] = *p++;
135 scanline[0][2] = *p++;
136 scanline[0][3] = *p++;
137
138 if (scanline[0][0] == 2 && scanline[0][1] == 2 && scanline[0][2] < 128) {
139 // new rle, the first pixel was a dummy
140 for (int channel = 0; channel < 4; ++channel) {
141 for (int x = 0; x < w && p < pEnd; ) {
142 unsigned char c = *p++;
143 if (c > 128) { // run
144 if (p < pEnd) {
145 int repCount = c & 127;
146 c = *p++;
147 while (repCount--)
148 scanline[x++][channel] = c;
149 }
150 } else { // not a run
151 while (c-- && p < pEnd)
152 scanline[x++][channel] = *p++;
153 }
154 }
155 }
156 } else {
157 // old rle
158 scanline[0][0] = 2;
159 int bitshift = 0;
160 int x = 1;
161 while (x < w && pEnd - p >= 4) {
162 scanline[x][0] = *p++;
163 scanline[x][1] = *p++;
164 scanline[x][2] = *p++;
165 scanline[x][3] = *p++;
166
167 if (scanline[x][0] == 1 && scanline[x][1] == 1 && scanline[x][2] == 1) { // run
168 int repCount = scanline[x][3] << bitshift;
169 while (repCount--) {
170 memcpy(scanline[x], scanline[x - 1], 4);
171 ++x;
172 }
173 bitshift += 8;
174 } else { // not a run
175 ++x;
176 bitshift = 0;
177 }
178 }
179 }
180
181 // adjust for -Y orientation
182 float *fp = reinterpret_cast<float *>(data.data() + (h - 1 - y) * blockSize * w);
183 for (int x = 0; x < w; ++x) {
184 float d = qPow(2.0f, float(scanline[x][3]) - 128.0f);
185 // r, g, b, a
186 *fp++ = scanline[x][0] / 256.0f * d;
187 *fp++ = scanline[x][1] / 256.0f * d;
188 *fp++ = scanline[x][2] / 256.0f * d;
189 *fp++ = 1.0f;
190 }
191 }
192
193 delete[] scanline;
194
195 if (size)
196 *size = QSize(w, h);
197
198 return data;
199 }
200
201 static float vertexData[] =
202 { // Y up, CCW
203 -0.5f, 0.5f, 0.0f, 0.0f,
204 -0.5f, -0.5f, 0.0f, 1.0f,
205 0.5f, -0.5f, 1.0f, 1.0f,
206 0.5f, 0.5f, 1.0f, 0.0f
207 };
208
209 static quint16 indexData[] =
210 {
211 0, 1, 2, 0, 2, 3
212 };
213
214 struct {
215 QVector<QRhiResource *> releasePool;
216 QRhiBuffer *vbuf = nullptr;
217 QRhiBuffer *ibuf = nullptr;
218 QRhiBuffer *ubuf = nullptr;
219 QRhiTexture *tex = nullptr;
220 QRhiSampler *sampler = nullptr;
221 QRhiShaderResourceBindings *srb = nullptr;
222 QRhiGraphicsPipeline *ps = nullptr;
223 QRhiResourceUpdateBatch *initialUpdates = nullptr;
224 QMatrix4x4 winProj;
225 } d;
226
227 void Window::customInit()
228 {
229 if (!m_r->isTextureFormatSupported(QRhiTexture::RGBA32F))
230 qWarning("RGBA32F texture format is not supported");
231
232 QSize size;
233 QByteArray floatData = loadHdr(QLatin1String(":/OpenfootageNET_fieldairport-512.hdr"), &size);
234 Q_ASSERT(!floatData.isEmpty());
235 qDebug() << size;
236
237 d.vbuf = m_r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData));
238 d.vbuf->build();
239 d.releasePool << d.vbuf;
240
241 d.ibuf = m_r->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::IndexBuffer, sizeof(indexData));
242 d.ibuf->build();
243 d.releasePool << d.ibuf;
244
245 d.ubuf = m_r->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 68);
246 d.ubuf->build();
247 d.releasePool << d.ubuf;
248
249 d.tex = m_r->newTexture(QRhiTexture::RGBA32F, size);
250 d.releasePool << d.tex;
251 d.tex->build();
252
253 d.sampler = m_r->newSampler(QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
254 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge);
255 d.releasePool << d.sampler;
256 d.sampler->build();
257
258 d.srb = m_r->newShaderResourceBindings();
259 d.releasePool << d.srb;
260 d.srb->setBindings({
261 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, d.ubuf),
262 QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, d.tex, d.sampler)
263 });
264 d.srb->build();
265
266 d.ps = m_r->newGraphicsPipeline();
267 d.releasePool << d.ps;
268 d.ps->setShaderStages({
269 { QRhiShaderStage::Vertex, getShader(QLatin1String(":/texture.vert.qsb")) },
270 { QRhiShaderStage::Fragment, getShader(QLatin1String(":/texture.frag.qsb")) }
271 });
272 QRhiVertexInputLayout inputLayout;
273 inputLayout.setBindings({
274 { 4 * sizeof(float) }
275 });
276 inputLayout.setAttributes({
277 { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
278 { 0, 1, QRhiVertexInputAttribute::Float2, 2 * sizeof(float) }
279 });
280 d.ps->setVertexInputLayout(inputLayout);
281 d.ps->setShaderResourceBindings(d.srb);
282 d.ps->setRenderPassDescriptor(m_rp);
283 d.ps->build();
284
285 d.initialUpdates = m_r->nextResourceUpdateBatch();
286 d.initialUpdates->uploadStaticBuffer(d.vbuf, vertexData);
287 d.initialUpdates->uploadStaticBuffer(d.ibuf, indexData);
288
289 qint32 flip = 1;
290 d.initialUpdates->updateDynamicBuffer(d.ubuf, 64, 4, &flip);
291
292 QRhiTextureUploadDescription desc({ 0, 0, { floatData.constData(), floatData.size() } });
293 d.initialUpdates->uploadTexture(d.tex, desc);
294 }
295
296 void Window::customRelease()
297 {
298 qDeleteAll(d.releasePool);
299 d.releasePool.clear();
300 }
301
302 void Window::customRender()
303 {
304 QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
305 QRhiResourceUpdateBatch *u = m_r->nextResourceUpdateBatch();
306 if (d.initialUpdates) {
307 u->merge(d.initialUpdates);
308 d.initialUpdates->release();
309 d.initialUpdates = nullptr;
310 }
311
312 if (d.winProj != m_proj) {
313 d.winProj = m_proj;
314 QMatrix4x4 mvp = m_proj;
315 mvp.scale(2.5f);
316 u->updateDynamicBuffer(d.ubuf, 0, 64, mvp.constData());
317 }
318
319 const QSize outputSizeInPixels = m_sc->currentPixelSize();
320 cb->beginPass(m_sc->currentFrameRenderTarget(), m_clearColor, { 1.0f, 0 }, u);
321 cb->setGraphicsPipeline(d.ps);
322 cb->setViewport({ 0, 0, float(outputSizeInPixels.width()), float(outputSizeInPixels.height()) });
323 cb->setShaderResources();
324 const QRhiCommandBuffer::VertexInput vbufBinding(d.vbuf, 0);
325 cb->setVertexInput(0, 1, &vbufBinding, d.ibuf, 0, QRhiCommandBuffer::IndexUInt16);
326 cb->drawIndexed(6);
327 cb->endPass();
328 }