7#include "graphobjects/qssgrendergraphobject_p.h"
11#include <QtQuick3DUtils/private/qssgutils_p.h>
12#include <QtQuick3DUtils/private/qquick3dprofiler_p.h>
14#include <QtQuick3DRuntimeRender/private/qssgruntimerenderlogging_p.h>
15#include <qtquick3d_tracepoints_p.h>
17#include <QCoreApplication>
18#include <QStandardPaths>
23#include <QtGui/qsurfaceformat.h>
25# include <QtGui/qopenglcontext.h>
28#ifdef QT_QUICK3D_HAS_RUNTIME_SHADERS
29#include <rhi/qshaderbaker.h>
32#include <QtCore/qmutex.h>
36Q_TRACE_POINT(qtquick3d, QSSG_loadShader_entry)
37Q_TRACE_POINT(qtquick3d, QSSG_loadShader_exit)
39static QtQuick3DEditorHelpers::ShaderBaker::StatusCallback s_statusCallback =
nullptr;
42size_t qHash(QSSGShaderFeatures features)
noexcept {
return (features.flags & (~QSSGShaderFeatures::IndexMask)); }
44#ifdef QT_QUICK3D_HAS_RUNTIME_SHADERS
46static QString dumpFilename(QShader::Stage stage)
49 case QShader::VertexStage:
50 return QStringLiteral(
"failedvert.txt");
52 case QShader::FragmentStage:
53 return QStringLiteral(
"failedfrag.txt");
55 case QShader::ComputeStage:
56 return QStringLiteral(
"failedcomp.txt");
59 return QStringLiteral(
"failedshader.txt");
63static void dumpShader(QShader::Stage stage,
const QByteArray &code)
66 case QShader::Stage::VertexStage:
67 qDebug(
"VERTEX SHADER:\n*****\n");
69 case QShader::Stage::FragmentStage:
70 qDebug(
"FRAGMENT SHADER:\n*****\n");
72 case QShader::Stage::ComputeStage:
73 qDebug(
"COMPUTE SHADER:\n*****\n");
76 qDebug(
"SHADER:\n*****\n");
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());
85static void dumpShaderToFile(QShader::Stage stage,
const QByteArray &data)
87 QFile f(dumpFilename(stage));
88 if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {
91 qWarning(
"Failed to write to file: %s (%s)\n",
92 qPrintable(f.fileName()), qPrintable(f.errorString()));
99 const char *
name =
nullptr;
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 }
127static_assert(std::size(DefineTable) == QSSGShaderFeatures::Count,
"Missing feature define?");
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; }
132void QSSGShaderFeatures::set(QSSGShaderFeatures::Feature feature,
bool val)
135 flags |= (
static_cast<FlagType>(feature) & ~IndexMask);
137 flags &= ~(
static_cast<FlagType>(feature) & ~IndexMask);
140QList<QShaderVersion> QSSGShaderCache::glslTargetsForContext(
const QSurfaceFormat &format,
bool isGLESModule)
142 QList<QShaderVersion> versions;
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);
151 const auto version = format.version();
153 if (format.profile() == QSurfaceFormat::CoreProfile && version >= qMakePair(3, 3)) {
156 versions.append(QShaderVersion(330));
158 if (version > qMakePair(3, 3))
159 versions.append(fromVersion(version));
160 }
else if (format.renderableType() == QSurfaceFormat::OpenGLES || isGLESModule) {
161 if (format.majorVersion() >= 3) {
164 versions.append(QShaderVersion(300, QShaderVersion::GlslEs));
166 if (version > qMakePair(3, 0))
167 versions.append(fromVersion(version, QShaderVersion::GlslEs));
169 versions.append(QShaderVersion(100, QShaderVersion::GlslEs));
186 versions.append(QShaderVersion(version >= qMakePair(3, 1) ? 140 : 130));
187 if (version >= qMakePair(3, 3))
188 versions.append(fromVersion(version));
196 QSurfaceFormat format = QSurfaceFormat::defaultFormat();
197 *isGLESModule =
false;
199 auto h =
static_cast<
const QRhiGles2NativeHandles *>(rhi->nativeHandles());
201 format = h->context->format();
202 *isGLESModule = QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES;
209bool QSSGShaderCache::isGlslEsTarget(QRhi *rhi)
211 if (!rhi || rhi->backend() != QRhi::OpenGLES2)
213 bool isGLESModule =
false;
214 const QSurfaceFormat format = glContextFormat(rhi, &isGLESModule);
215 return format.renderableType() == QSurfaceFormat::OpenGLES || isGLESModule;
218#ifdef QT_QUICK3D_HAS_RUNTIME_SHADERS
219static void initBakerForNonPersistentUse(QShaderBaker *baker, QRhi *rhi)
221 QVector<QShaderBaker::GeneratedShader> outputs;
222 switch (rhi->backend()) {
224 outputs.append({ QShader::HlslShader, QShaderVersion(50) });
227 outputs.append({ QShader::HlslShader, QShaderVersion(61) });
230#if defined(Q_OS_VISIONOS)
231 outputs.append({ QShader::MslShader, QShaderVersion(21) });
233 outputs.append({ QShader::MslShader, QShaderVersion(12) });
236 case QRhi::OpenGLES2:
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 });
247 outputs.append({ QShader::SpirvShader, QShaderVersion(100) });
253 baker->setBreakOnShaderTranslationError(
false);
254 baker->setGeneratedShaders(outputs);
255 baker->setGeneratedShaderVariants({ QShader::StandardShader });
258void QSSGShaderCache::initBakerForPersistentUse(QShaderBaker *baker, QRhi *)
260 QVector<QShaderBaker::GeneratedShader> outputs;
264 outputs.append({ QShader::SpirvShader, QShaderVersion(100) });
265 outputs.append({ QShader::HlslShader, QShaderVersion(50) });
266 outputs.append({ QShader::HlslShader, QShaderVersion(61) });
267#if defined(Q_OS_VISIONOS)
268 outputs.append({ QShader::MslShader, QShaderVersion(21) });
270 outputs.append({ QShader::MslShader, QShaderVersion(12) });
273 outputs.append({ QShader::GlslShader, QShaderVersion(430) });
274 outputs.append({ QShader::GlslShader, QShaderVersion(420) });
275 outputs.append({ QShader::GlslShader, QShaderVersion(330) });
276 outputs.append({ QShader::GlslShader, QShaderVersion(140) });
277 outputs.append({ QShader::GlslShader, QShaderVersion(130) });
278 outputs.append({ QShader::GlslShader, QShaderVersion(100, QShaderVersion::GlslEs) });
280 outputs.append({ QShader::GlslShader, QShaderVersion(300, QShaderVersion::GlslEs) });
281 outputs.append({ QShader::GlslShader, QShaderVersion(310, QShaderVersion::GlslEs) });
282 outputs.append({ QShader::GlslShader, QShaderVersion(320, QShaderVersion::GlslEs) });
296 baker->setBreakOnShaderTranslationError(
false);
298 baker->setGeneratedShaders(outputs);
299 baker->setGeneratedShaderVariants({ QShader::StandardShader });
307void QSSGShaderCache::initBakerForPersistentUse(QShaderBaker *, QRhi *)
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);
326 QDir::root().mkpath(name);
327 return QFileInfo(name).isWritable();
332 static bool checked =
false;
333 static QString currentCacheDir;
334 static bool cacheWritable =
false;
337 return cacheWritable ? currentCacheDir : QString();
340 const QString cachePath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
341 const QString subPath = QLatin1String(
"/q3dshadercache-") + QSysInfo::buildAbi() + QLatin1Char(
'/');
343 if (!cachePath.isEmpty()) {
344 currentCacheDir = cachePath + subPath;
345 cacheWritable = ensureWritableDir(currentCacheDir);
348 return cacheWritable ? currentCacheDir : QString();
353 const QString cacheDir = persistentQsbcDir();
354 if (!cacheDir.isEmpty())
355 return cacheDir + QLatin1String(
"q3dshadercache.qsbc");
360QSSGShaderCache::QSSGShaderCache(QSSGRhiContext &ctx,
361 const InitBakerFunc initBakeFn)
363 m_initBaker(initBakeFn),
364 m_builtInShaders(*
this)
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)) {
373 qDebug(
"Attempting to seed material shader cache from %s", qPrintable(m_persistentShaderStorageFileName));
374 if (m_persistentShaderBakingCache.load(m_persistentShaderStorageFileName)) {
376 const int count = m_persistentShaderBakingCache.availableEntries().count();
377 qDebug(
"Loaded %d shader pipelines into the material shader cache", count);
392 m_initBaker = m_persistentShaderStorageFileName.isEmpty() ? initBakerForNonPersistentUse
393 : QSSGShaderCache::initBakerForPersistentUse;
397QSSGShaderCache::~QSSGShaderCache()
399 if (!m_persistentShaderStorageFileName.isEmpty())
400 m_persistentShaderBakingCache.save(m_persistentShaderStorageFileName);
403void QSSGShaderCache::releaseCachedResources()
405 m_builtInShaders.releaseCachedResources();
407 m_rhiShaders.clear();
413QSSGRhiShaderPipelinePtr QSSGShaderCache::tryGetRhiShaderPipeline(
const QByteArray &inKey,
414 const QSSGShaderFeatures &inFeatures)
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();
428bool QSSGShaderCache::hasRhiShaderPipeline(
const QByteArray &inKey,
const QSSGShaderFeatures &inFeatures)
const
430 QSSGShaderCacheKey cacheKey(inKey);
431 cacheKey.m_features = inFeatures;
432 cacheKey.updateHashCode();
433 return m_rhiShaders.contains(cacheKey);
437void QSSGShaderCache::addShaderPreprocessor(QByteArray &str,
438 const QByteArray &inKey,
439 ShaderType shaderType,
440 const QSSGShaderFeatures &inFeatures,
441 const QSSGUserShaderAugmentation &shaderAugmentation,
446 m_insertStr +=
"#version 440\n";
448 if (!inKey.isNull()) {
449 m_insertStr +=
"//Shader name -";
450 m_insertStr += inKey;
454 m_insertStr +=
"#define texture2D texture\n";
457 m_insertStr +=
"#define QSHADER_VIEW_COUNT ";
458 m_insertStr += QByteArray::number(viewCount);
461 str.insert(0, m_insertStr);
462 QString::size_type insertPos =
int(m_insertStr.size());
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");
474 str.insert(insertPos, m_insertStr);
475 insertPos +=
int(m_insertStr.size());
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";
489 m_insertStr +=
"layout(location = 0) out vec4 fragOutput;\n";
493 str.insert(insertPos, m_insertStr);
496QByteArray QSSGShaderCache::resourceFolder()
498 return QByteArrayLiteral(
":/res/rhishaders/");
501QByteArray QSSGShaderCache::shaderCollectionFile()
503 return QByteArrayLiteral(
"qtappshaders.qsbc");
506QByteArray QSSGShaderCache::particleShaderCollectionFile()
508 return QByteArrayLiteral(
"qtparticleshaders.qsbc");
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)
517#ifdef QT_QUICK3D_HAS_RUNTIME_SHADERS
521 const QByteArray &cacheKeyString = inCacheKey.isEmpty() ? inKey : inCacheKey;
523 const QSSGRhiShaderPipelinePtr &rhiShaders = tryGetRhiShaderPipeline(cacheKeyString, inFeatures);
525 QSSG_ASSERT(rhiShaders->vertexStage() && rhiShaders->fragmentStage(),
return {});
529 QSSGShaderCacheKey tempKey(cacheKeyString);
530 tempKey.m_features = inFeatures;
531 tempKey.updateHashCode();
533 QByteArray vertexCode = inVert;
534 QByteArray fragmentCode = inFrag;
536 if (!vertexCode.isEmpty())
537 addShaderPreprocessor(vertexCode, inKey, ShaderType::Vertex, inFeatures, shaderAugmentation, viewCount);
539 if (!fragmentCode.isEmpty())
540 addShaderPreprocessor(fragmentCode, inKey, ShaderType::Fragment, inFeatures, shaderAugmentation, viewCount);
544 QSSGRhiShaderPipelinePtr shaders;
545 QString vertErr, fragErr;
548 m_initBaker(&baker, m_rhiContext.rhi());
553 baker.setPerTargetCompilation(perTargetCompilation);
557 baker.setMultiViewCount(viewCount);
561 const bool mediumPrecision = qEnvironmentVariableIntValue(
"QT_QUICK3D_MEDIUM_PRECISION");
563 baker.setGlslOptions(QShaderBaker::GlslOption::GlslEsFragDefaultFloatPrecisionMedium);
565 const bool editorMode = QSSGRhiContextPrivate::editorMode();
567 const bool shaderDebug = !editorMode && QSSGRhiContextPrivate::shaderDebuggingEnabled();
569 baker.setSourceString(vertexCode, QShader::VertexStage);
570 QShader vertexShader = baker.bake();
571 const auto vertShaderValid = vertexShader.isValid();
572 if (!vertShaderValid) {
573 vertErr = baker.errorMessage();
575 qWarning(
"Failed to compile vertex shader: %s\n", qPrintable(vertErr));
577 qWarning() << inKey <<
'\n';
582 dumpShader(QShader::Stage::VertexStage, vertexCode);
583 if (!vertShaderValid)
584 dumpShaderToFile(QShader::Stage::VertexStage, vertexCode);
587 baker.setSourceString(fragmentCode, QShader::FragmentStage);
588 QShader fragmentShader = baker.bake();
589 const bool fragShaderValid = fragmentShader.isValid();
590 if (!fragShaderValid) {
591 fragErr = baker.errorMessage();
593 qWarning(
"Failed to compile fragment shader: %s\n", qPrintable(fragErr));
595 qWarning() << inKey <<
'\n';
600 dumpShader(QShader::Stage::FragmentStage, fragmentCode);
601 if (!fragShaderValid)
602 dumpShaderToFile(QShader::Stage::FragmentStage, fragmentCode);
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);
610 qDebug(
"Compilation for vertex and fragment stages succeeded");
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);
622 auto result = m_rhiShaders.insert(tempKey, shaders).value();
623 if (result && result->vertexStage() && result->fragmentStage()) {
624 QQsbCollection::EntryDesc entryDesc = {
626 QQsbCollection::toFeatureSet(inFeatures),
627 result->vertexStage()->shader(),
628 result->fragmentStage()->shader()
630 m_persistentShaderBakingCache.addEntry(entryDesc.generateSha(), entryDesc);
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.");
647QSSGRhiShaderPipelinePtr QSSGShaderCache::compileComputePipeline(
648 const QByteArray &inKey,
const QByteArray &inComp,
649 int viewCount,
bool perTargetCompilation,
const QByteArray &inCacheKey)
651#ifdef QT_QUICK3D_HAS_RUNTIME_SHADERS
652 const QByteArray &cacheKeyString = inCacheKey.isEmpty() ? inKey : inCacheKey;
653 const QSSGRhiShaderPipelinePtr &rhiShaders = tryGetRhiShaderPipeline(cacheKeyString, {});
655 QSSG_ASSERT(rhiShaders->computeStage(),
return {});
658 QSSGShaderCacheKey tempKey(cacheKeyString);
659 tempKey.updateHashCode();
662 m_initBaker(&baker, m_rhiContext.rhi());
664 QByteArray computeCode =
"#version 440\n";
666 if (!inKey.isNull()) {
667 computeCode +=
"//Shader name -";
668 computeCode += inKey;
672 computeCode +=
"#define QSHADER_VIEW_COUNT ";
673 computeCode += QByteArray::number(viewCount);
676 computeCode += inComp;
681 baker.setPerTargetCompilation(perTargetCompilation);
682 baker.setSourceString(computeCode, QShader::ComputeStage);
683 baker.setMultiViewCount(viewCount);
685 const bool editorMode = QSSGRhiContextPrivate::editorMode();
687 const bool shaderDebug = !editorMode && QSSGRhiContextPrivate::shaderDebuggingEnabled();
689 QShader computeShader = baker.bake();
690 QSSGRhiShaderPipelinePtr shaders;
691 const auto valid = computeShader.isValid();
693 dumpShader(QShader::Stage::ComputeStage, computeCode);
695 dumpShaderToFile(QShader::Stage::ComputeStage, computeCode);
698 shaders = std::make_shared<QSSGRhiShaderPipeline>(m_rhiContext);
699 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Compute, computeShader), {});
701 qDebug(
"Compilation for compute stage succeeded");
702 }
else if (!editorMode) {
703 qWarning(
"Failed to compile compute shader: %s\n", qPrintable(baker.errorMessage()));
705 qWarning() << inKey <<
'\n';
707 auto result = m_rhiShaders.insert(tempKey, shaders).value();
708 if (result && result->computeStage()) {
709 QQsbCollection::EntryDesc entryDesc = {
712 result->computeStage()->shader(),
715 m_persistentShaderBakingCache.addEntry(entryDesc.generateSha(), entryDesc);
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.");
730QSSGRhiShaderPipelinePtr QSSGShaderCache::newPipelineFromPregenerated(
const QByteArray &inKey,
731 const QSSGShaderFeatures &inFeatures,
732 QQsbCollection::Entry entry,
733 const QSSGRenderGraphObject &obj,
734 QSSGRhiShaderPipeline::StageFlags stageFlags)
743 const bool shaderDebug = !QSSGRhiContextPrivate::editorMode() && QSSGRhiContextPrivate::shaderDebuggingEnabled();
745 qDebug(
"Loading pregenerated rhi shader(s)");
747 Q_TRACE_SCOPE(QSSG_loadShader);
748 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DLoadShader);
751 QSSGRhiShaderPipelinePtr shaders(
new QSSGRhiShaderPipeline(m_rhiContext));
753 const QStringList collectionFiles
754 = {QString::fromLatin1(resourceFolder() + shaderCollectionFile()),
755 QString::fromLatin1(resourceFolder() + particleShaderCollectionFile())};
757 QQsbCollection::EntryDesc entryDesc;
758 QScopedPointer<QQsbIODeviceCollection> qsbc;
759 for (
const auto &collectionFile : collectionFiles) {
760 QFileInfo info(collectionFile);
764 qsbc.reset(
new QQsbIODeviceCollection(collectionFile));
765 if (qsbc->map(QQsbIODeviceCollection::Read)) {
766 if (qsbc->extractEntry(entry, entryDesc))
774 qWarning(
"Failed to open entry %s", entry.key.constData());
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);
780 qDebug(
"Loading of vertex and fragment stages succeeded");
783#if !QT_CONFIG(qml_debug)
786 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DLoadShader, 0, obj.profilingId);
789 QSSGShaderCacheKey cacheKey(inKey);
790 cacheKey.m_features = inFeatures;
791 cacheKey.updateHashCode();
793 const auto inserted = m_rhiShaders.insert(cacheKey, shaders);
796 return inserted.value();
799QSSGRhiShaderPipelinePtr QSSGShaderCache::tryNewPipelineFromPersistentCache(
const QByteArray &qsbcKey,
800 const QByteArray &inKey,
801 const QSSGShaderFeatures &inFeatures,
802 QSSGRhiShaderPipeline::StageFlags stageFlags)
811 QQsbCollection::EntryDesc entryDesc;
815 if (!m_persistentShaderBakingCache.extractEntry(QQsbCollection::Entry(qsbcKey), entryDesc))
818 if (entryDesc.vertShader.isValid() && entryDesc.fragShader.isValid()) {
819 const bool shaderDebug = !QSSGRhiContextPrivate::editorMode() && QSSGRhiContextPrivate::shaderDebuggingEnabled();
821 qDebug(
"Loading rhi shaders from disk cache for %s (%s)", qsbcKey.constData(), inKey.constData());
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();
833 qDebug(
"Loading rhi shaders from disk cache for %s (%s)", qsbcKey.constData(), inKey.constData());
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());
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();
850QSSGRhiShaderPipelinePtr QSSGShaderCache::loadBuiltinUncached(
const QByteArray &inKey,
int viewCount,
851 QSSGRhiShaderPipeline::StageFlags vertexStageFlags)
853 const bool shaderDebug = !QSSGRhiContextPrivate::editorMode() && QSSGRhiContextPrivate::shaderDebuggingEnabled();
855 qDebug(
"Loading builtin rhi shader: %s (view count: %d)", inKey.constData(), viewCount);
857 Q_TRACE_SCOPE(QSSG_loadShader);
858 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DLoadShader);
861 QSSGRhiShaderPipelinePtr shaders(
new QSSGRhiShaderPipeline(m_rhiContext));
866 const QString prefix = QString::fromUtf8(resourceFolder() + inKey);
867 QString vertexFileName = prefix + QLatin1String(
".vert.qsb");
868 QString fragmentFileName = prefix + QLatin1String(
".frag.qsb");
872 if (viewCount == 2) {
873 vertexFileName += QLatin1String(
".mv2qsb");
874 fragmentFileName += QLatin1String(
".mv2qsb");
877 QShader vertexShader;
878 QShader fragmentShader;
881 f.setFileName(vertexFileName);
882 if (f.open(QIODevice::ReadOnly)) {
883 const QByteArray vsData = f.readAll();
884 vertexShader = QShader::fromSerialized(vsData);
887 qWarning(
"Failed to open %s", qPrintable(f.fileName()));
889 f.setFileName(fragmentFileName);
890 if (f.open(QIODevice::ReadOnly)) {
891 const QByteArray fsData = f.readAll();
892 fragmentShader = QShader::fromSerialized(fsData);
895 qWarning(
"Failed to open %s", qPrintable(f.fileName()));
898 if (vertexShader.isValid() && fragmentShader.isValid()) {
899 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Vertex, vertexShader), vertexStageFlags);
900 shaders->addStage(QRhiShaderStage(QRhiShaderStage::Fragment, fragmentShader));
902 qDebug(
"Loading of vertex and fragment stages succeeded");
905 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DLoadShader, 0, inKey);
913 QMutexLocker locker(&*s_statusMutex);
914 s_statusCallback = cb;
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[]