Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qssgrendershadercache.cpp
Go to the documentation of this file.
1// Copyright (C) 2008-2012 NVIDIA Corporation.
2// Copyright (C) 2019 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
6
7#include "graphobjects/qssgrendergraphobject_p.h"
10
11#include <QtQuick3DUtils/private/qssgutils_p.h>
12#include <QtQuick3DUtils/private/qquick3dprofiler_p.h>
13
14#include <QtQuick3DRuntimeRender/private/qssgruntimerenderlogging_p.h>
15#include <qtquick3d_tracepoints_p.h>
16
17#include <QCoreApplication>
18#include <QStandardPaths>
19#include <QString>
20#include <QFile>
21#include <QDir>
22
23#include <QtGui/qsurfaceformat.h>
24#if QT_CONFIG(opengl)
25# include <QtGui/qopenglcontext.h>
26#endif
27
28#ifdef QT_QUICK3D_HAS_RUNTIME_SHADERS
29#include <rhi/qshaderbaker.h>
30#endif
31
32#include <QtCore/qmutex.h>
33
35
36Q_TRACE_POINT(qtquick3d, QSSG_loadShader_entry)
37Q_TRACE_POINT(qtquick3d, QSSG_loadShader_exit)
38
39static QtQuick3DEditorHelpers::ShaderBaker::StatusCallback s_statusCallback = nullptr;
41
42size_t qHash(QSSGShaderFeatures features) noexcept { return (features.flags & (~QSSGShaderFeatures::IndexMask)); }
43
44#ifdef QT_QUICK3D_HAS_RUNTIME_SHADERS
45
46static QString dumpFilename(QShader::Stage stage)
47{
48 switch (stage) {
49 case QShader::VertexStage:
50 return QStringLiteral("failedvert.txt");
51 break;
52 case QShader::FragmentStage:
53 return QStringLiteral("failedfrag.txt");
54 break;
55 case QShader::ComputeStage:
56 return QStringLiteral("failedcomp.txt");
57 break;
58 default:
59 return QStringLiteral("failedshader.txt");
60 }
61}
62
63static void dumpShader(QShader::Stage stage, const QByteArray &code)
64{
65 switch (stage) {
66 case QShader::Stage::VertexStage:
67 qDebug("VERTEX SHADER:\n*****\n");
68 break;
69 case QShader::Stage::FragmentStage:
70 qDebug("FRAGMENT SHADER:\n*****\n");
71 break;
72 case QShader::Stage::ComputeStage:
73 qDebug("COMPUTE SHADER:\n*****\n");
74 break;
75 default:
76 qDebug("SHADER:\n*****\n");
77 break;
78 }
79 const auto lines = code.split('\n');
80 for (int i = 0; i < lines.size(); i++)
81 qDebug("%3d %s", i + 1, lines.at(i).constData());
82 qDebug("\n*****\n");
83}
84
85static void dumpShaderToFile(QShader::Stage stage, const QByteArray &data)
86{
87 QFile f(dumpFilename(stage));
88 if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {
89 f.write(data);
90 } else {
91 qWarning("Failed to write to file: %s (%s)\n",
92 qPrintable(f.fileName()), qPrintable(f.errorString()));
93 }
94}
95#endif // QT_QUICK3D_HAS_RUNTIME_SHADERS
96
98{
99 const char *name = nullptr;
101};
102
103static constexpr DefineEntry DefineTable[] {
104 { "QSSG_ENABLE_LIGHT_PROBE", QSSGShaderFeatures::Feature::LightProbe },
105 { "QSSG_ENABLE_IBL_ORIENTATION", QSSGShaderFeatures::Feature::IblOrientation },
106 { "QSSG_ENABLE_SSM", QSSGShaderFeatures::Feature::Ssm },
107 { "QSSG_ENABLE_SSAO", QSSGShaderFeatures::Feature::Ssao },
108 { "QSSG_ENABLE_DEPTH_PASS", QSSGShaderFeatures::Feature::DepthPass },
109 { "QSSG_ENABLE_ORTHO_SHADOW_PASS", QSSGShaderFeatures::Feature::OrthoShadowPass },
110 { "QSSG_ENABLE_PERSPECTIVE_SHADOW_PASS", QSSGShaderFeatures::Feature::PerspectiveShadowPass },
111 { "QSSG_ENABLE_LINEAR_TONEMAPPING", QSSGShaderFeatures::Feature::LinearTonemapping },
112 { "QSSG_ENABLE_ACES_TONEMAPPING", QSSGShaderFeatures::Feature::AcesTonemapping },
113 { "QSSG_ENABLE_HEJLDAWSON_TONEMAPPING", QSSGShaderFeatures::Feature::HejlDawsonTonemapping },
114 { "QSSG_ENABLE_FILMIC_TONEMAPPING", QSSGShaderFeatures::Feature::FilmicTonemapping },
115 { "QSSG_ENABLE_RGBE_LIGHT_PROBE", QSSGShaderFeatures::Feature::RGBELightProbe },
116 { "QSSG_ENABLE_OPAQUE_DEPTH_PRE_PASS", QSSGShaderFeatures::Feature::OpaqueDepthPrePass },
117 { "QSSG_ENABLE_REFLECTION_PROBE", QSSGShaderFeatures::Feature::ReflectionProbe },
118 { "QSSG_REDUCE_MAX_NUM_LIGHTS", QSSGShaderFeatures::Feature::ReduceMaxNumLights },
119 { "QSSG_ENABLE_LIGHTMAP", QSSGShaderFeatures::Feature::Lightmap },
120 { "QSSG_DISABLE_MULTIVIEW", QSSGShaderFeatures::Feature::DisableMultiView },
121 { "QSSG_FORCE_IBL_EXPOSURE", QSSGShaderFeatures::Feature::ForceIblExposure },
122 { "QSSG_ENABLE_NORMAL_PASS", QSSGShaderFeatures::Feature::NormalPass },
123 { "QSSG_ENABLE_USER_RENDER_PASS", QSSGShaderFeatures::Feature::UserRenderPass},
124 { "QSSG_ENABLE_MOTION_VECTOR", QSSGShaderFeatures::Feature::MotionVector }
125};
126
127static_assert(std::size(DefineTable) == QSSGShaderFeatures::Count, "Missing feature define?");
128
129const char *QSSGShaderFeatures::asDefineString(QSSGShaderFeatures::Feature feature) { return DefineTable[static_cast<FlagType>(feature) & QSSGShaderFeatures::IndexMask].name; }
130QSSGShaderFeatures::Feature QSSGShaderFeatures::fromIndex(quint32 idx) { return DefineTable[idx].feature; }
131
132void QSSGShaderFeatures::set(QSSGShaderFeatures::Feature feature, bool val)
133{
134 if (val)
135 flags |= (static_cast<FlagType>(feature) & ~IndexMask);
136 else
137 flags &= ~(static_cast<FlagType>(feature) & ~IndexMask);
138}
139
140QList<QShaderVersion> QSSGShaderCache::glslTargetsForContext(const QSurfaceFormat &format, bool isGLESModule)
141{
142 QList<QShaderVersion> versions;
143
144 // QShaderVersion from QSurfaceFormat::version pair. Only valid from GLSL
145 // 330 and GLSL ES 300 up; below those the GLSL version does not follow the
146 // context version, but the callers below never get there.
147 const auto fromVersion = [](const std::pair<int, int> &version, const QShaderVersion::Flags flags = {}) -> QShaderVersion {
148 return QShaderVersion(version.first * 100 + version.second * 10, flags);
149 };
150
151 const auto version = format.version();
152
153 if (format.profile() == QSurfaceFormat::CoreProfile && version >= qMakePair(3, 3)) {
154 // Add the floor version so that silent translation errors do not leave the
155 // GLSL outputs empty
156 versions.append(QShaderVersion(330));
157 // Use actual version
158 if (version > qMakePair(3, 3))
159 versions.append(fromVersion(version));
160 } else if (format.renderableType() == QSurfaceFormat::OpenGLES || isGLESModule) {
161 if (format.majorVersion() >= 3) {
162 // Add the floor version so that silent translation errors do not leave the
163 // GLSL outputs empty
164 versions.append(QShaderVersion(300, QShaderVersion::GlslEs));
165 // Use actual version
166 if (version > qMakePair(3, 0))
167 versions.append(fromVersion(version, QShaderVersion::GlslEs));
168 } else {
169 versions.append(QShaderVersion(100, QShaderVersion::GlslEs)); // GLES 2.0
170 }
171 } else {
172 // Need to default to at least GLSL 130 (OpenGL 3.0), not 120.
173 // The difference is actually relevant when it comes to certain
174 // GLSL features (textureSize, unsigned integers, and with
175 // SPIRV-Cross even bool), and we do not have to care about
176 // pure OpenGL (non-ES) 2.x implementations in practice.
177
178 // For full feature set we need GLSL 140 (OpenGL 3.1), e.g.
179 // because of inverse() used for instancing.
180
181 // GLSL 130 should still be attempted, to support old Mesa
182 // llvmpipe that only gives us OpenGL 3.0. At the time of
183 // writing the opengl32sw.dll shipped with pre-built Qt is one
184 // of these still.
185
186 versions.append(QShaderVersion(version >= qMakePair(3, 1) ? 140 : 130));
187 if (version >= qMakePair(3, 3))
188 versions.append(fromVersion(version));
189 }
190
191 return versions;
192}
193
194static QSurfaceFormat glContextFormat(QRhi *rhi, bool *isGLESModule)
195{
196 QSurfaceFormat format = QSurfaceFormat::defaultFormat();
197 *isGLESModule = false;
198#if QT_CONFIG(opengl)
199 auto h = static_cast<const QRhiGles2NativeHandles *>(rhi->nativeHandles());
200 if (h && h->context)
201 format = h->context->format();
202 *isGLESModule = QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES;
203#else
204 Q_UNUSED(rhi);
205#endif
206 return format;
207}
208
209bool QSSGShaderCache::isGlslEsTarget(QRhi *rhi)
210{
211 if (!rhi || rhi->backend() != QRhi::OpenGLES2)
212 return false;
213 bool isGLESModule = false;
214 const QSurfaceFormat format = glContextFormat(rhi, &isGLESModule);
215 return format.renderableType() == QSurfaceFormat::OpenGLES || isGLESModule;
216}
217
218#ifdef QT_QUICK3D_HAS_RUNTIME_SHADERS
219static void initBakerForNonPersistentUse(QShaderBaker *baker, QRhi *rhi)
220{
221 QVector<QShaderBaker::GeneratedShader> outputs;
222 switch (rhi->backend()) {
223 case QRhi::D3D11:
224 outputs.append({ QShader::HlslShader, QShaderVersion(50) }); // Shader Model 5.0
225 break;
226 case QRhi::D3D12:
227 outputs.append({ QShader::HlslShader, QShaderVersion(61) }); // Shader Model 6.1 (includes multiview support)
228 break;
229 case QRhi::Metal:
230#if defined(Q_OS_VISIONOS)
231 outputs.append({ QShader::MslShader, QShaderVersion(21) }); // Metal 2.1 (multiview support)
232#else
233 outputs.append({ QShader::MslShader, QShaderVersion(12) }); // Metal 1.2
234#endif // Q_OS_VISIONOS
235 break;
236 case QRhi::OpenGLES2:
237 {
238 bool isGLESModule = false;
239 const QSurfaceFormat format = glContextFormat(rhi, &isGLESModule);
240 const QList<QShaderVersion> versions = QSSGShaderCache::glslTargetsForContext(format, isGLESModule);
241 outputs.reserve(outputs.size() + versions.size());
242 for (const QShaderVersion &version : versions)
243 outputs.append({ QShader::GlslShader, version });
244 }
245 break;
246 default: // Vulkan, Null
247 outputs.append({ QShader::SpirvShader, QShaderVersion(100) });
248 break;
249 }
250
251 // Do not fail baking if one of the target fails
252 // See comment on initBakerForPersistentUse
253 baker->setBreakOnShaderTranslationError(false);
254 baker->setGeneratedShaders(outputs);
255 baker->setGeneratedShaderVariants({ QShader::StandardShader });
256}
257
258void QSSGShaderCache::initBakerForPersistentUse(QShaderBaker *baker, QRhi *)
259{
260 QVector<QShaderBaker::GeneratedShader> outputs;
261 outputs.reserve(13);
262
263#ifndef Q_OS_WASM
264 outputs.append({ QShader::SpirvShader, QShaderVersion(100) });
265 outputs.append({ QShader::HlslShader, QShaderVersion(50) }); // Shader Model 5.0
266 outputs.append({ QShader::HlslShader, QShaderVersion(61) }); // Shader Model 6.1 (for multiview on d3d12)
267#if defined(Q_OS_VISIONOS)
268 outputs.append({ QShader::MslShader, QShaderVersion(21) }); // Metal 2.1 (multiview support)
269#else
270 outputs.append({ QShader::MslShader, QShaderVersion(12) }); // Metal 1.2
271#endif // Q_OS_VISIONOS
272
273 outputs.append({ QShader::GlslShader, QShaderVersion(430) }); // OpenGL 4.3+ (compute shaders, shader storage buffers)
274 outputs.append({ QShader::GlslShader, QShaderVersion(420) }); // OpenGL 4.2+
275 outputs.append({ QShader::GlslShader, QShaderVersion(330) }); // OpenGL 3.3+
276 outputs.append({ QShader::GlslShader, QShaderVersion(140) }); // OpenGL 3.1+
277 outputs.append({ QShader::GlslShader, QShaderVersion(130) }); // OpenGL 3.0+
278 outputs.append({ QShader::GlslShader, QShaderVersion(100, QShaderVersion::GlslEs) }); // GLES 2.0
279#endif
280 outputs.append({ QShader::GlslShader, QShaderVersion(300, QShaderVersion::GlslEs) }); // GLES 3.0+
281 outputs.append({ QShader::GlslShader, QShaderVersion(310, QShaderVersion::GlslEs) }); // GLES 3.1+
282 outputs.append({ QShader::GlslShader, QShaderVersion(320, QShaderVersion::GlslEs) }); // GLES 3.2+ (image atomics)
283
284 // If one of the above cannot be generated due to failing at the
285 // SPIRV-Cross translation stage, it will be skipped, but bake() will not
286 // fail. This is essential, because with the default fail if anything fails
287 // behavior many shaders could not be baked at all due to failing for e.g.
288 // GLSL ES 100. This is a non-issue when choosing the targets dynamically
289 // based on the current API/context, but here we need to ensure what we
290 // generate will work with a different RHI backend, graphics API, and
291 // perhaps even on a different platform (if the cache file is manually
292 // moved). So have to generate what we can, without breaking the
293 // application when the shader is not compatible with a target. (if that
294 // shader is not used at runtime, it's fine anyway, it it is, it won't work
295 // just as with the other, non-caching path)
296 baker->setBreakOnShaderTranslationError(false);
297
298 baker->setGeneratedShaders(outputs);
299 baker->setGeneratedShaderVariants({ QShader::StandardShader });
300}
301
302#else
303static void initBakerForNonPersistentUse(QShaderBaker *, QRhi *)
304{
305}
306
307void QSSGShaderCache::initBakerForPersistentUse(QShaderBaker *, QRhi *)
308{
309}
310#endif // QT_QUICK3D_HAS_RUNTIME_SHADERS
311
312static bool s_autoDiskCacheEnabled = true;
313
315{
316 // these three mirror QOpenGLShaderProgram/QQuickGraphicsConfiguration/QSGRhiSupport
317 static const bool diskCacheDisabled = qEnvironmentVariableIntValue("QT_DISABLE_SHADER_DISK_CACHE")
318 || qEnvironmentVariableIntValue("QSG_RHI_DISABLE_DISK_CACHE");
319 const bool attrDiskCacheDisabled = (qApp ? qApp->testAttribute(Qt::AA_DisableShaderDiskCache) : false);
320 return (!diskCacheDisabled && !attrDiskCacheDisabled && s_autoDiskCacheEnabled);
321
322}
323
324static inline bool ensureWritableDir(const QString &name)
325{
326 QDir::root().mkpath(name);
327 return QFileInfo(name).isWritable();
328}
329
331{
332 static bool checked = false;
333 static QString currentCacheDir;
334 static bool cacheWritable = false;
335
336 if (checked)
337 return cacheWritable ? currentCacheDir : QString();
338
339 checked = true;
340 const QString cachePath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
341 const QString subPath = QLatin1String("/q3dshadercache-") + QSysInfo::buildAbi() + QLatin1Char('/');
342
343 if (!cachePath.isEmpty()) {
344 currentCacheDir = cachePath + subPath;
345 cacheWritable = ensureWritableDir(currentCacheDir);
346 }
347
348 return cacheWritable ? currentCacheDir : QString();
349}
350
352{
353 const QString cacheDir = persistentQsbcDir();
354 if (!cacheDir.isEmpty())
355 return cacheDir + QLatin1String("q3dshadercache.qsbc");
356
357 return QString();
358}
359
360QSSGShaderCache::QSSGShaderCache(QSSGRhiContext &ctx,
361 const InitBakerFunc initBakeFn)
362 : m_rhiContext(ctx),
363 m_initBaker(initBakeFn),
364 m_builtInShaders(*this)
365{
366 if (isAutoDiskCacheEnabled()) {
367 const bool shaderDebug = !QSSGRhiContextPrivate::editorMode() && QSSGRhiContextPrivate::shaderDebuggingEnabled();
368 m_persistentShaderStorageFileName = persistentQsbcFileName();
369 if (!m_persistentShaderStorageFileName.isEmpty()) {
370 const bool skipCacheFile = qEnvironmentVariableIntValue("QT_QUICK3D_NO_SHADER_CACHE_LOAD");
371 if (!skipCacheFile && QFileInfo::exists(m_persistentShaderStorageFileName)) {
372 if (shaderDebug)
373 qDebug("Attempting to seed material shader cache from %s", qPrintable(m_persistentShaderStorageFileName));
374 if (m_persistentShaderBakingCache.load(m_persistentShaderStorageFileName)) {
375 if (shaderDebug) {
376 const int count = m_persistentShaderBakingCache.availableEntries().count();
377 qDebug("Loaded %d shader pipelines into the material shader cache", count);
378 }
379 }
380 }
381 }
382 }
383
384 if (!m_initBaker) {
385 // It is important to generate all possible shader variants if the qsb
386 // collection is going to be stored on disk. Otherwise switching the
387 // rhi backend could break the application. This is however an overkill
388 // if we know that what we bake will not be reused in future runs of
389 // the application, so do not do it if the disk cache was disabled or
390 // the cache directory was not available (no file system, no
391 // permissions, etc.).
392 m_initBaker = m_persistentShaderStorageFileName.isEmpty() ? initBakerForNonPersistentUse
393 : QSSGShaderCache::initBakerForPersistentUse;
394 }
395}
396
397QSSGShaderCache::~QSSGShaderCache()
398{
399 if (!m_persistentShaderStorageFileName.isEmpty())
400 m_persistentShaderBakingCache.save(m_persistentShaderStorageFileName);
401}
402
403void QSSGShaderCache::releaseCachedResources()
404{
405 m_builtInShaders.releaseCachedResources();
406
407 m_rhiShaders.clear();
408
409 // m_persistentShaderBakingCache is not cleared, that is intentional,
410 // otherwise we would permanently lose what got loaded at startup.
411}
412
413QSSGRhiShaderPipelinePtr QSSGShaderCache::tryGetRhiShaderPipeline(const QByteArray &inKey,
414 const QSSGShaderFeatures &inFeatures)
415{
416 QSSGShaderCacheKey cacheKey(inKey);
417 cacheKey.m_features = inFeatures;
418 cacheKey.updateHashCode();
419 const auto theIter = m_rhiShaders.constFind(cacheKey);
420 if (theIter != m_rhiShaders.cend())
421 return theIter.value();
422 return nullptr;
423}
424
425// True also when the shaders failed to compile and the cache holds a null
426// pipeline for the key, which tryGetRhiShaderPipeline() cannot tell apart
427// from a key that was never compiled.
428bool QSSGShaderCache::hasRhiShaderPipeline(const QByteArray &inKey, const QSSGShaderFeatures &inFeatures) const
429{
430 QSSGShaderCacheKey cacheKey(inKey);
431 cacheKey.m_features = inFeatures;
432 cacheKey.updateHashCode();
433 return m_rhiShaders.contains(cacheKey);
434}
435
436
437void QSSGShaderCache::addShaderPreprocessor(QByteArray &str,
438 const QByteArray &inKey,
439 ShaderType shaderType,
440 const QSSGShaderFeatures &inFeatures,
441 const QSSGUserShaderAugmentation &shaderAugmentation,
442 int viewCount)
443{
444 m_insertStr.clear();
445
446 m_insertStr += "#version 440\n";
447
448 if (!inKey.isNull()) {
449 m_insertStr += "//Shader name -";
450 m_insertStr += inKey;
451 m_insertStr += "\n";
452 }
453
454 m_insertStr += "#define texture2D texture\n";
455
456 // match Qt Quick and QSGMaterial(Shader)
457 m_insertStr += "#define QSHADER_VIEW_COUNT ";
458 m_insertStr += QByteArray::number(viewCount);
459 m_insertStr += "\n";
460
461 str.insert(0, m_insertStr);
462 QString::size_type insertPos = int(m_insertStr.size());
463
464 m_insertStr.clear();
465 const bool fragOutputEnabled = (!inFeatures.isSet(QSSGShaderFeatures::Feature::DepthPass)) && shaderType == ShaderType::Fragment;
466 for (const auto &def : DefineTable) {
467 m_insertStr.append("#define ");
468 m_insertStr.append(def.name);
469 m_insertStr.append(" ");
470 m_insertStr.append(inFeatures.isSet(def.feature) ? "1" : "0");
471 m_insertStr.append("\n");
472 }
473
474 str.insert(insertPos, m_insertStr);
475 insertPos += int(m_insertStr.size());
476
477 m_insertStr.clear();
478 if (fragOutputEnabled) {
479 if (shaderAugmentation.outputs.size() != 0) {
480 const auto &outputs = shaderAugmentation.outputs;
481 for (int i = 0; i < outputs.size(); ++i) {
482 m_insertStr += "layout(location = ";
483 m_insertStr += QByteArray::number(i);
484 m_insertStr += ") out vec4 ";
485 m_insertStr += outputs[i];
486 m_insertStr += ";\n";
487 }
488 } else {
489 m_insertStr += "layout(location = 0) out vec4 fragOutput;\n";
490 }
491 }
492
493 str.insert(insertPos, m_insertStr);
494}
495
496QByteArray QSSGShaderCache::resourceFolder()
497{
498 return QByteArrayLiteral(":/res/rhishaders/");
499}
500
501QByteArray QSSGShaderCache::shaderCollectionFile()
502{
503 return QByteArrayLiteral("qtappshaders.qsbc");
504}
505
506QByteArray QSSGShaderCache::particleShaderCollectionFile()
507{
508 return QByteArrayLiteral("qtparticleshaders.qsbc");
509}
510
511QSSGRhiShaderPipelinePtr QSSGShaderCache::compileGraphicsPipeline(
512 const QByteArray &inKey, const QByteArray &inVert, const QByteArray &inFrag,
513 const QSSGShaderFeatures &inFeatures, QSSGRhiShaderPipeline::StageFlags stageFlags,
514 const QSSGUserShaderAugmentation &shaderAugmentation,
515 int viewCount, bool perTargetCompilation, const QByteArray &inCacheKey)
516{
517#ifdef QT_QUICK3D_HAS_RUNTIME_SHADERS
518 // inKey is also used as the shader name in a comment in the generated
519 // source, so it may not contain everything needed to identify the
520 // shaders. When inCacheKey is set, that is what the caches are keyed on.
521 const QByteArray &cacheKeyString = inCacheKey.isEmpty() ? inKey : inCacheKey;
522
523 const QSSGRhiShaderPipelinePtr &rhiShaders = tryGetRhiShaderPipeline(cacheKeyString, inFeatures);
524 if (rhiShaders) {
525 QSSG_ASSERT(rhiShaders->vertexStage() && rhiShaders->fragmentStage(), return {});
526 return rhiShaders;
527 }
528
529 QSSGShaderCacheKey tempKey(cacheKeyString);
530 tempKey.m_features = inFeatures;
531 tempKey.updateHashCode();
532
533 QByteArray vertexCode = inVert;
534 QByteArray fragmentCode = inFrag;
535
536 if (!vertexCode.isEmpty())
537 addShaderPreprocessor(vertexCode, inKey, ShaderType::Vertex, inFeatures, shaderAugmentation, viewCount);
538
539 if (!fragmentCode.isEmpty())
540 addShaderPreprocessor(fragmentCode, inKey, ShaderType::Fragment, inFeatures, shaderAugmentation, viewCount);
541
542 // lo and behold the final shader strings are ready
543
544 QSSGRhiShaderPipelinePtr shaders;
545 QString vertErr, fragErr;
546
547 QShaderBaker baker;
548 m_initBaker(&baker, m_rhiContext.rhi());
549
550 // If requested, per-target compilation allows doing things like #if
551 // QSHADER_HLSL in the shader code, at the expense of spending more time in
552 // bake())
553 baker.setPerTargetCompilation(perTargetCompilation);
554
555 // This is in the shader key, but cannot query that here anymore now that it's serialized.
556 // So we get it as a dedicated argument.
557 baker.setMultiViewCount(viewCount);
558
559 // For fragment shaders for GLSL ES (but only ES) we can make the generated
560 // sources contain 'precision mediump float' instead of 'precision highp float'.
561 const bool mediumPrecision = qEnvironmentVariableIntValue("QT_QUICK3D_MEDIUM_PRECISION");
562 if (mediumPrecision)
563 baker.setGlslOptions(QShaderBaker::GlslOption::GlslEsFragDefaultFloatPrecisionMedium);
564
565 const bool editorMode = QSSGRhiContextPrivate::editorMode();
566 // Shader debug is disabled in editor mode
567 const bool shaderDebug = !editorMode && QSSGRhiContextPrivate::shaderDebuggingEnabled();
568
569 baker.setSourceString(vertexCode, QShader::VertexStage);
570 QShader vertexShader = baker.bake();
571 const auto vertShaderValid = vertexShader.isValid();
572 if (!vertShaderValid) {
573 vertErr = baker.errorMessage();
574 if (!editorMode) {
575 qWarning("Failed to compile vertex shader: %s\n", qPrintable(vertErr));
576 if (!shaderDebug)
577 qWarning() << inKey << '\n';
578 }
579 }
580
581 if (shaderDebug) {
582 dumpShader(QShader::Stage::VertexStage, vertexCode);
583 if (!vertShaderValid)
584 dumpShaderToFile(QShader::Stage::VertexStage, vertexCode);
585 }
586
587 baker.setSourceString(fragmentCode, QShader::FragmentStage);
588 QShader fragmentShader = baker.bake();
589 const bool fragShaderValid = fragmentShader.isValid();
590 if (!fragShaderValid) {
591 fragErr = baker.errorMessage();
592 if (!editorMode) {
593 qWarning("Failed to compile fragment shader: %s\n", qPrintable(fragErr));
594 if (!shaderDebug)
595 qWarning() << inKey << '\n';
596 }
597 }
598
599 if (shaderDebug) {
600 dumpShader(QShader::Stage::FragmentStage, fragmentCode);
601 if (!fragShaderValid)
602 dumpShaderToFile(QShader::Stage::FragmentStage, fragmentCode);
603 }
604
605 if (vertShaderValid && fragShaderValid) {
606 shaders = std::make_shared<QSSGRhiShaderPipeline>(m_rhiContext);
607 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Vertex, vertexShader), stageFlags);
608 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Fragment, fragmentShader), stageFlags);
609 if (shaderDebug)
610 qDebug("Compilation for vertex and fragment stages succeeded");
611 }
612
613 if (editorMode && s_statusCallback) {
614 using namespace QtQuick3DEditorHelpers::ShaderBaker;
615 const auto vertStatus = vertShaderValid ? Status::Success : Status::Error;
616 const auto fragStatus = fragShaderValid ? Status::Success : Status::Error;
617 QMutexLocker locker(&*s_statusMutex);
618 s_statusCallback(inKey, vertStatus, vertErr, QShader::VertexStage);
619 s_statusCallback(inKey, fragStatus, fragErr, QShader::FragmentStage);
620 }
621
622 auto result = m_rhiShaders.insert(tempKey, shaders).value();
623 if (result && result->vertexStage() && result->fragmentStage()) {
624 QQsbCollection::EntryDesc entryDesc = {
625 cacheKeyString,
626 QQsbCollection::toFeatureSet(inFeatures),
627 result->vertexStage()->shader(),
628 result->fragmentStage()->shader()
629 };
630 m_persistentShaderBakingCache.addEntry(entryDesc.generateSha(), entryDesc);
631 }
632 return result;
633
634#else
635 Q_UNUSED(inKey);
636 Q_UNUSED(inVert);
637 Q_UNUSED(inFrag);
638 Q_UNUSED(inFeatures);
639 Q_UNUSED(stageFlags);
640 Q_UNUSED(inCacheKey);
641 qWarning("Cannot compile and condition shaders at runtime because this build of Qt Quick 3D is not linking to Qt Shader Tools. "
642 "Only pre-processed materials are supported.");
643 return {};
644#endif
645}
646
647QSSGRhiShaderPipelinePtr QSSGShaderCache::compileComputePipeline(
648 const QByteArray &inKey, const QByteArray &inComp,
649 int viewCount, bool perTargetCompilation, const QByteArray &inCacheKey)
650{
651#ifdef QT_QUICK3D_HAS_RUNTIME_SHADERS
652 const QByteArray &cacheKeyString = inCacheKey.isEmpty() ? inKey : inCacheKey;
653 const QSSGRhiShaderPipelinePtr &rhiShaders = tryGetRhiShaderPipeline(cacheKeyString, {});
654 if (rhiShaders) {
655 QSSG_ASSERT(rhiShaders->computeStage(), return {});
656 return rhiShaders;
657 }
658 QSSGShaderCacheKey tempKey(cacheKeyString);
659 tempKey.updateHashCode();
660
661 QShaderBaker baker;
662 m_initBaker(&baker, m_rhiContext.rhi());
663
664 QByteArray computeCode = "#version 440\n";
665
666 if (!inKey.isNull()) {
667 computeCode += "//Shader name -";
668 computeCode += inKey;
669 computeCode += "\n";
670 }
671 // match Qt Quick and QSGMaterial(Shader)
672 computeCode += "#define QSHADER_VIEW_COUNT ";
673 computeCode += QByteArray::number(viewCount);
674 computeCode += "\n";
675
676 computeCode += inComp;
677
678 // If requested, per-target compilation allows doing things like #if
679 // QSHADER_HLSL in the shader code, at the expense of spending more time in
680 // bake())
681 baker.setPerTargetCompilation(perTargetCompilation);
682 baker.setSourceString(computeCode, QShader::ComputeStage);
683 baker.setMultiViewCount(viewCount);
684
685 const bool editorMode = QSSGRhiContextPrivate::editorMode();
686 // Shader debug is disabled in editor mode
687 const bool shaderDebug = !editorMode && QSSGRhiContextPrivate::shaderDebuggingEnabled();
688
689 QShader computeShader = baker.bake();
690 QSSGRhiShaderPipelinePtr shaders;
691 const auto valid = computeShader.isValid();
692 if (shaderDebug) {
693 dumpShader(QShader::Stage::ComputeStage, computeCode);
694 if (!valid)
695 dumpShaderToFile(QShader::Stage::ComputeStage, computeCode);
696 }
697 if (valid) {
698 shaders = std::make_shared<QSSGRhiShaderPipeline>(m_rhiContext);
699 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Compute, computeShader), {});
700 if (shaderDebug)
701 qDebug("Compilation for compute stage succeeded");
702 } else if (!editorMode) {
703 qWarning("Failed to compile compute shader: %s\n", qPrintable(baker.errorMessage()));
704 if (!shaderDebug)
705 qWarning() << inKey << '\n';
706 }
707 auto result = m_rhiShaders.insert(tempKey, shaders).value();
708 if (result && result->computeStage()) {
709 QQsbCollection::EntryDesc entryDesc = {
710 cacheKeyString,
711 {},
712 result->computeStage()->shader(),
713 {}
714 };
715 m_persistentShaderBakingCache.addEntry(entryDesc.generateSha(), entryDesc);
716 }
717 return result;
718#else
719 Q_UNUSED(inKey);
720 Q_UNUSED(inComp);
721 Q_UNUSED(viewCount);
722 Q_UNUSED(perTargetCompilation);
723 Q_UNUSED(inCacheKey);
724 qWarning("Cannot compile and condition shaders at runtime because this build of Qt Quick 3D is not linking to Qt Shader Tools. "
725 "Only pre-processed materials are supported.");
726 return {};
727#endif
728}
729
730QSSGRhiShaderPipelinePtr QSSGShaderCache::newPipelineFromPregenerated(const QByteArray &inKey,
731 const QSSGShaderFeatures &inFeatures,
732 QQsbCollection::Entry entry,
733 const QSSGRenderGraphObject &obj,
734 QSSGRhiShaderPipeline::StageFlags stageFlags)
735{
736 // No lookup in m_rhiShaders. It is up to the caller to do that, if they
737 // want to. We will insert into it at the end, but there is intentionally
738 // no lookup. The result from this function is always a new
739 // QSSGRhiShaderPipeline (it's just much faster to create than the
740 // full-blown generator). That is important for some clients (effect
741 // system) so returning an existing QSSGRhiShaderPipeline is _wrong_.
742
743 const bool shaderDebug = !QSSGRhiContextPrivate::editorMode() && QSSGRhiContextPrivate::shaderDebuggingEnabled();
744 if (shaderDebug)
745 qDebug("Loading pregenerated rhi shader(s)");
746
747 Q_TRACE_SCOPE(QSSG_loadShader);
748 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DLoadShader);
749
750 // Note that we are required to return a non-null (but empty) shader set even if loading fails.
751 QSSGRhiShaderPipelinePtr shaders(new QSSGRhiShaderPipeline(m_rhiContext));
752
753 const QStringList collectionFiles
754 = {QString::fromLatin1(resourceFolder() + shaderCollectionFile()),
755 QString::fromLatin1(resourceFolder() + particleShaderCollectionFile())};
756
757 QQsbCollection::EntryDesc entryDesc;
758 QScopedPointer<QQsbIODeviceCollection> qsbc;
759 for (const auto &collectionFile : collectionFiles) {
760 QFileInfo info(collectionFile);
761 if (!info.exists())
762 continue;
763
764 qsbc.reset(new QQsbIODeviceCollection(collectionFile));
765 if (qsbc->map(QQsbIODeviceCollection::Read)) {
766 if (qsbc->extractEntry(entry, entryDesc))
767 break;
768 else
769 qsbc.reset();
770 }
771 }
772
773 if (qsbc.isNull())
774 qWarning("Failed to open entry %s", entry.key.constData());
775
776 if (entryDesc.vertShader.isValid() && entryDesc.fragShader.isValid()) {
777 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Vertex, entryDesc.vertShader), stageFlags);
778 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Fragment, entryDesc.fragShader), stageFlags);
779 if (shaderDebug)
780 qDebug("Loading of vertex and fragment stages succeeded");
781 }
782
783#if !QT_CONFIG(qml_debug)
784 Q_UNUSED(obj);
785#else
786 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DLoadShader, 0, obj.profilingId);
787#endif
788
789 QSSGShaderCacheKey cacheKey(inKey);
790 cacheKey.m_features = inFeatures;
791 cacheKey.updateHashCode();
792
793 const auto inserted = m_rhiShaders.insert(cacheKey, shaders);
794 if (qsbc)
795 qsbc->unmap();
796 return inserted.value();
797}
798
799QSSGRhiShaderPipelinePtr QSSGShaderCache::tryNewPipelineFromPersistentCache(const QByteArray &qsbcKey,
800 const QByteArray &inKey,
801 const QSSGShaderFeatures &inFeatures,
802 QSSGRhiShaderPipeline::StageFlags stageFlags)
803{
804 // No lookup in m_rhiShaders. it is up to the caller to do that, if they
805 // want to. We will insert into it at the end, but there is intentionally
806 // no lookup. The result from this function is always a new
807 // QSSGRhiShaderPipeline (it's just much faster to create than the
808 // full-blown generator). That is important for some clients (effect
809 // system) so returning an existing QSSGRhiShaderPipeline is _wrong_.
810
811 QQsbCollection::EntryDesc entryDesc;
812
813 // Here we are allowed to return null to indicate that there is no such
814 // entry in this particular cache.
815 if (!m_persistentShaderBakingCache.extractEntry(QQsbCollection::Entry(qsbcKey), entryDesc))
816 return {};
817
818 if (entryDesc.vertShader.isValid() && entryDesc.fragShader.isValid()) {
819 const bool shaderDebug = !QSSGRhiContextPrivate::editorMode() && QSSGRhiContextPrivate::shaderDebuggingEnabled();
820 if (shaderDebug)
821 qDebug("Loading rhi shaders from disk cache for %s (%s)", qsbcKey.constData(), inKey.constData());
822
823 QSSGRhiShaderPipelinePtr shaders(new QSSGRhiShaderPipeline(m_rhiContext));
824 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Vertex, entryDesc.vertShader), stageFlags);
825 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Fragment, entryDesc.fragShader), stageFlags);
826 QSSGShaderCacheKey cacheKey(inKey);
827 cacheKey.m_features = inFeatures;
828 cacheKey.updateHashCode();
829 return m_rhiShaders.insert(cacheKey, shaders).value();
830 } else if (entryDesc.vertShader.isValid()) {
831 const bool shaderDebug = !QSSGRhiContextPrivate::editorMode() && QSSGRhiContextPrivate::shaderDebuggingEnabled();
832 if (shaderDebug)
833 qDebug("Loading rhi shaders from disk cache for %s (%s)", qsbcKey.constData(), inKey.constData());
834
835 if (entryDesc.vertShader.stage() != QShader::ComputeStage) {
836 qWarning("Failed to find compute stage while loading rhi shaders from disk cache for %s.", qsbcKey.constData());
837 return {};
838 }
839 QSSGRhiShaderPipelinePtr shaders(new QSSGRhiShaderPipeline(m_rhiContext));
840 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Compute, entryDesc.vertShader), stageFlags);
841 QSSGShaderCacheKey cacheKey(inKey);
842 cacheKey.m_features = inFeatures;
843 cacheKey.updateHashCode();
844 return m_rhiShaders.insert(cacheKey, shaders).value();
845 }
846
847 return {};
848}
849
850QSSGRhiShaderPipelinePtr QSSGShaderCache::loadBuiltinUncached(const QByteArray &inKey, int viewCount,
851 QSSGRhiShaderPipeline::StageFlags vertexStageFlags)
852{
853 const bool shaderDebug = !QSSGRhiContextPrivate::editorMode() && QSSGRhiContextPrivate::shaderDebuggingEnabled();
854 if (shaderDebug)
855 qDebug("Loading builtin rhi shader: %s (view count: %d)", inKey.constData(), viewCount);
856
857 Q_TRACE_SCOPE(QSSG_loadShader);
858 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DLoadShader);
859
860 // Note that we are required to return a non-null (but empty) shader set even if loading fails.
861 QSSGRhiShaderPipelinePtr shaders(new QSSGRhiShaderPipeline(m_rhiContext));
862
863 // inShaderName is a prefix of a .qsb file, so "abc" means we should
864 // look for abc.vert.qsb and abc.frag.qsb.
865
866 const QString prefix = QString::fromUtf8(resourceFolder() + inKey);
867 QString vertexFileName = prefix + QLatin1String(".vert.qsb");
868 QString fragmentFileName = prefix + QLatin1String(".frag.qsb");
869
870 // This must match QSGMaterial(Shader) in Qt Quick, in particular the
871 // QSGMaterialShader::setShaderFileName() overload taking a viewCount.
872 if (viewCount == 2) {
873 vertexFileName += QLatin1String(".mv2qsb");
874 fragmentFileName += QLatin1String(".mv2qsb");
875 }
876
877 QShader vertexShader;
878 QShader fragmentShader;
879
880 QFile f;
881 f.setFileName(vertexFileName);
882 if (f.open(QIODevice::ReadOnly)) {
883 const QByteArray vsData = f.readAll();
884 vertexShader = QShader::fromSerialized(vsData);
885 f.close();
886 } else {
887 qWarning("Failed to open %s", qPrintable(f.fileName()));
888 }
889 f.setFileName(fragmentFileName);
890 if (f.open(QIODevice::ReadOnly)) {
891 const QByteArray fsData = f.readAll();
892 fragmentShader = QShader::fromSerialized(fsData);
893 f.close();
894 } else {
895 qWarning("Failed to open %s", qPrintable(f.fileName()));
896 }
897
898 if (vertexShader.isValid() && fragmentShader.isValid()) {
899 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Vertex, vertexShader), vertexStageFlags);
900 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Fragment, fragmentShader));
901 if (shaderDebug)
902 qDebug("Loading of vertex and fragment stages succeeded");
903 }
904
905 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DLoadShader, 0, inKey);
906
907 return shaders;
908}
909
912{
913 QMutexLocker locker(&*s_statusMutex);
914 s_statusCallback = cb;
915}
916
918{
919 s_autoDiskCacheEnabled = enable;
920}
921
926
927}
928
929QT_END_NAMESPACE
Combined button and popup list for selecting options.
Q_QUICK3DRUNTIMERENDER_EXPORT void setStatusCallback(StatusCallback cb)
void(*)(const QByteArray &descKey, Status status, const QString &err, QShader::Stage stage) StatusCallback
Q_QUICK3DRUNTIMERENDER_EXPORT void setAutomaticDiskCache(bool enable)
Q_QUICK3DRUNTIMERENDER_EXPORT bool isAutomaticDiskCacheEnabled()
Q_GLOBAL_STATIC(QReadWriteLock, g_updateMutex)
static QString persistentQsbcFileName()
static bool isAutoDiskCacheEnabled()
size_t qHash(QSSGShaderFeatures features) noexcept
static bool ensureWritableDir(const QString &name)
static bool s_autoDiskCacheEnabled
static QSurfaceFormat glContextFormat(QRhi *rhi, bool *isGLESModule)
static QString persistentQsbcDir()
static void initBakerForNonPersistentUse(QShaderBaker *, QRhi *)
static constexpr DefineEntry DefineTable[]