1009void QSSGLayerRenderData::prepareImageForRender(QSSGRenderImage &inImage,
1010 QSSGRenderableImage::Type inMapType,
1011 QSSGRenderableImage *&ioFirstImage,
1012 QSSGRenderableImage *&ioNextImage,
1013 QSSGRenderableObjectFlags &ioFlags,
1014 QSSGShaderDefaultMaterialKey &inShaderKey,
1015 quint32 inImageIndex,
1016 QSSGRenderDefaultMaterial *inMaterial)
1018 QSSGRenderContextInterface &contextInterface = *renderer->contextInterface();
1019 const auto &bufferManager = contextInterface.bufferManager();
1021 if (inImage.clearDirty())
1022 ioFlags |= QSSGRenderableObjectFlag::Dirty;
1033 const QSSGRenderImageTexture texture = bufferManager->loadRenderImage(&inImage);
1035 if (texture.m_texture) {
1036 if (texture.m_flags.hasTransparency()
1037 && (inMapType == QSSGRenderableImage::Type::Diffuse
1038 || inMapType == QSSGRenderableImage::Type::Opacity
1039 || inMapType == QSSGRenderableImage::Type::Translucency))
1041 ioFlags |= QSSGRenderableObjectFlag::HasTransparency;
1044 QSSGRenderableImage *theImage = RENDER_FRAME_NEW<QSSGRenderableImage>(contextInterface, inMapType, inImage, texture);
1045 QSSGShaderKeyImageMap &theKeyProp = defaultMaterialShaderKeyProperties.m_imageMaps[inImageIndex];
1047 theKeyProp.setEnabled(inShaderKey,
true);
1048 switch (inImage.m_mappingMode) {
1049 case QSSGRenderImage::MappingModes::Normal:
1051 case QSSGRenderImage::MappingModes::Environment:
1052 theKeyProp.setEnvMap(inShaderKey,
true);
1054 case QSSGRenderImage::MappingModes::LightProbe:
1055 theKeyProp.setLightProbe(inShaderKey,
true);
1065 switch (texture.m_texture->format()) {
1066 case QRhiTexture::Format::RED_OR_ALPHA8:
1067 hasA = !renderer->contextInterface()->rhiContext()->rhi()->isFeatureSupported(QRhi::RedOrAlpha8IsRed);
1069 case QRhiTexture::Format::R8:
1079 if (inImage.isImageTransformIdentity())
1080 theKeyProp.setIdentityTransform(inShaderKey,
true);
1082 if (inImage.m_indexUV == 1)
1083 theKeyProp.setUsesUV1(inShaderKey,
true);
1085 if (texture.m_flags.isLinear())
1086 theKeyProp.setLinear(inShaderKey,
true);
1088 if (texture.m_flags.isPreMultipliedAlpha())
1089 theKeyProp.setPreMultipliedAlpha(inShaderKey,
true);
1091 if (ioFirstImage ==
nullptr)
1092 ioFirstImage = theImage;
1094 ioNextImage->m_nextImage = theImage;
1096 ioNextImage = theImage;
1098 if (inMaterial && inImageIndex >= QSSGShaderDefaultMaterialKeyProperties::SingleChannelImagesFirst) {
1099 QSSGRenderDefaultMaterial::TextureChannelMapping value = QSSGRenderDefaultMaterial::R;
1101 const quint32 scIndex = inImageIndex - QSSGShaderDefaultMaterialKeyProperties::SingleChannelImagesFirst;
1102 QSSGShaderKeyTextureChannel &channelKey = defaultMaterialShaderKeyProperties.m_textureChannels[scIndex];
1103 switch (inImageIndex) {
1104 case QSSGShaderDefaultMaterialKeyProperties::OpacityMap:
1105 value = inMaterial->opacityChannel;
1107 case QSSGShaderDefaultMaterialKeyProperties::RoughnessMap:
1108 value = inMaterial->roughnessChannel;
1110 case QSSGShaderDefaultMaterialKeyProperties::MetalnessMap:
1111 value = inMaterial->metalnessChannel;
1113 case QSSGShaderDefaultMaterialKeyProperties::OcclusionMap:
1114 value = inMaterial->occlusionChannel;
1116 case QSSGShaderDefaultMaterialKeyProperties::TranslucencyMap:
1117 value = inMaterial->translucencyChannel;
1119 case QSSGShaderDefaultMaterialKeyProperties::HeightMap:
1120 value = inMaterial->heightChannel;
1122 case QSSGShaderDefaultMaterialKeyProperties::ClearcoatMap:
1123 value = inMaterial->clearcoatChannel;
1125 case QSSGShaderDefaultMaterialKeyProperties::ClearcoatRoughnessMap:
1126 value = inMaterial->clearcoatRoughnessChannel;
1128 case QSSGShaderDefaultMaterialKeyProperties::SheenRoughnessMap:
1129 value = inMaterial->sheenRoughnessChannel;
1131 case QSSGShaderDefaultMaterialKeyProperties::IridescenceMap:
1132 value = inMaterial->iridescenceChannel;
1134 case QSSGShaderDefaultMaterialKeyProperties::IridescenceThicknessMap:
1135 value = inMaterial->iridescenceThicknessChannel;
1137 case QSSGShaderDefaultMaterialKeyProperties::TransmissionMap:
1138 value = inMaterial->transmissionChannel;
1140 case QSSGShaderDefaultMaterialKeyProperties::ThicknessMap:
1141 value = inMaterial->thicknessChannel;
1143 case QSSGShaderDefaultMaterialKeyProperties::BaseColorMap:
1144 value = inMaterial->baseColorChannel;
1146 case QSSGShaderDefaultMaterialKeyProperties::SpecularAmountMap:
1147 value = inMaterial->specularAmountChannel;
1149 case QSSGShaderDefaultMaterialKeyProperties::EmissiveMap:
1150 value = inMaterial->emissiveChannel;
1155 bool useDefault =
false;
1157 case QSSGRenderDefaultMaterial::TextureChannelMapping::G:
1160 case QSSGRenderDefaultMaterial::TextureChannelMapping::B:
1163 case QSSGRenderDefaultMaterial::TextureChannelMapping::A:
1170 value = QSSGRenderDefaultMaterial::R;
1171 channelKey.setTextureChannel(QSSGShaderKeyTextureChannel::TexturChannelBits(value), inShaderKey);
1201QSSGDefaultMaterialPreparationResult QSSGLayerRenderData::prepareDefaultMaterialForRender(
1202 QSSGRenderDefaultMaterial &inMaterial,
1203 QSSGRenderableObjectFlags &inExistingFlags,
1204 float inOpacity,
bool hasAnyLights,
1205 bool anyLightHasShadows,
1206 QSSGLayerRenderPreparationResultFlags &ioFlags)
1208 QSSGRenderDefaultMaterial *theMaterial = &inMaterial;
1209 QSSGDefaultMaterialPreparationResult retval(QSSGShaderDefaultMaterialKey(qHash(features)));
1210 retval.renderableFlags = inExistingFlags;
1211 QSSGRenderableObjectFlags &renderableFlags(retval.renderableFlags);
1212 QSSGShaderDefaultMaterialKey &theGeneratedKey(retval.materialKey);
1213 retval.opacity = inOpacity;
1214 float &subsetOpacity(retval.opacity);
1216 if (theMaterial->isDirty())
1217 renderableFlags |= QSSGRenderableObjectFlag::Dirty;
1219 subsetOpacity *= theMaterial->opacity;
1221 QSSGRenderableImage *firstImage =
nullptr;
1223 const bool lighting = theMaterial->lighting != QSSGRenderDefaultMaterial::MaterialLighting::NoLighting;
1224 defaultMaterialShaderKeyProperties.m_hasLighting.setValue(theGeneratedKey, lighting);
1226 defaultMaterialShaderKeyProperties.m_hasPunctualLights.setValue(theGeneratedKey, hasAnyLights);
1227 defaultMaterialShaderKeyProperties.m_hasShadows.setValue(theGeneratedKey, anyLightHasShadows);
1228 const bool validSky = layer.skyMaterial !=
nullptr && layer.skyMaterial->enableIBL;
1229 defaultMaterialShaderKeyProperties.m_hasIbl.setValue(theGeneratedKey, layer.lightProbe !=
nullptr || validSky);
1232 defaultMaterialShaderKeyProperties.m_specularAAEnabled.setValue(theGeneratedKey, layer.specularAAEnabled);
1235 defaultMaterialShaderKeyProperties.m_isDoubleSided.setValue(theGeneratedKey, theMaterial->cullMode == QSSGCullFaceMode::Disabled);
1238 defaultMaterialShaderKeyProperties.m_overridesPosition.setValue(theGeneratedKey,
false);
1242 if (!renderableFlags.hasAttributePosition() && warnOnce(OneShotWarning::MissingPosition))
1243 warnMissingPosition();
1246 defaultMaterialShaderKeyProperties.m_usesProjectionMatrix.setValue(theGeneratedKey,
false);
1247 defaultMaterialShaderKeyProperties.m_usesInverseProjectionMatrix.setValue(theGeneratedKey,
false);
1249 defaultMaterialShaderKeyProperties.m_usesVarColor.setValue(theGeneratedKey,
false);
1252 defaultMaterialShaderKeyProperties.m_alphaMode.setValue(theGeneratedKey, theMaterial->alphaMode);
1255 setVertexInputPresence(renderableFlags, theGeneratedKey);
1258 defaultMaterialShaderKeyProperties.m_usesPointsTopology.setValue(theGeneratedKey, renderableFlags.isPointsTopology());
1261 defaultMaterialShaderKeyProperties.m_lightmapEnabled.setValue(theGeneratedKey, renderableFlags.rendersWithLightmap());
1262 defaultMaterialShaderKeyProperties.m_metallicRoughnessEnabled.setValue(theGeneratedKey, theMaterial->type == QSSGRenderDefaultMaterial::Type::PrincipledMaterial);
1263 defaultMaterialShaderKeyProperties.m_specularGlossyEnabled.setValue(theGeneratedKey, theMaterial->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial);
1267 defaultMaterialShaderKeyProperties.m_debugMode.setValue(theGeneratedKey,
int(layer.debugMode));
1270 defaultMaterialShaderKeyProperties.m_fogEnabled.setValue(theGeneratedKey, layer.fog.enabled);
1273 defaultMaterialShaderKeyProperties.m_viewCount.setValue(theGeneratedKey, layer.viewCount);
1274 defaultMaterialShaderKeyProperties.m_usesViewIndex.setValue(theGeneratedKey, layer.viewCount >= 2);
1276 if (!defaultMaterialShaderKeyProperties.m_hasIbl.getValue(theGeneratedKey) && theMaterial->iblProbe) {
1277 features.set(QSSGShaderFeatures::Feature::LightProbe,
true);
1278 defaultMaterialShaderKeyProperties.m_hasIbl.setValue(theGeneratedKey,
true);
1283 if (subsetOpacity >= QSSGRendererPrivate::minimumRenderOpacity) {
1299 if (theMaterial->blendMode != QSSGRenderDefaultMaterial::MaterialBlendMode::SourceOver
1300 || theMaterial->opacityMap
1301 || theMaterial->alphaMode == QSSGRenderDefaultMaterial::Blend)
1303 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1306 const bool specularEnabled = theMaterial->isSpecularEnabled();
1307 const bool metalnessEnabled = theMaterial->isMetalnessEnabled();
1308 defaultMaterialShaderKeyProperties.m_specularEnabled.setValue(theGeneratedKey, specularEnabled || metalnessEnabled);
1309 defaultMaterialShaderKeyProperties.m_specularModel.setSpecularModel(theGeneratedKey, theMaterial->specularModel);
1310 defaultMaterialShaderKeyProperties.m_diffuseModel.setDiffuseModel(theGeneratedKey, theMaterial->diffuseModel);
1311 defaultMaterialShaderKeyProperties.m_fresnelScaleBiasEnabled.setValue(theGeneratedKey, theMaterial->isFresnelScaleBiasEnabled());
1312 defaultMaterialShaderKeyProperties.m_clearcoatFresnelScaleBiasEnabled.setValue(theGeneratedKey, theMaterial->isClearcoatFresnelScaleBiasEnabled());
1313 defaultMaterialShaderKeyProperties.m_fresnelEnabled.setValue(theGeneratedKey, theMaterial->isFresnelEnabled());
1314 defaultMaterialShaderKeyProperties.m_baseColorSingleChannelEnabled.setValue(theGeneratedKey, theMaterial->isBaseColorSingleChannelEnabled());
1315 defaultMaterialShaderKeyProperties.m_specularSingleChannelEnabled.setValue(theGeneratedKey, theMaterial->isSpecularAmountSingleChannelEnabled());
1316 defaultMaterialShaderKeyProperties.m_emissiveSingleChannelEnabled.setValue(theGeneratedKey, theMaterial->isEmissiveSingleChannelEnabled());
1317 defaultMaterialShaderKeyProperties.m_invertOpacityMapValue.setValue(theGeneratedKey, theMaterial->isInvertOpacityMapValue());
1318 defaultMaterialShaderKeyProperties.m_vertexColorsEnabled.setValue(theGeneratedKey, theMaterial->isVertexColorsEnabled());
1319 defaultMaterialShaderKeyProperties.m_vertexColorsMaskEnabled.setValue(theGeneratedKey, theMaterial->isVertexColorsMaskEnabled());
1320 defaultMaterialShaderKeyProperties.m_vertexColorRedMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorRedMask.toInt()));
1321 defaultMaterialShaderKeyProperties.m_vertexColorGreenMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorGreenMask.toInt()));
1322 defaultMaterialShaderKeyProperties.m_vertexColorBlueMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorBlueMask.toInt()));
1323 defaultMaterialShaderKeyProperties.m_vertexColorAlphaMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorAlphaMask.toInt()));
1324 defaultMaterialShaderKeyProperties.m_clearcoatEnabled.setValue(theGeneratedKey, theMaterial->isClearcoatEnabled());
1325 defaultMaterialShaderKeyProperties.m_sheenEnabled.setValue(theGeneratedKey, theMaterial->isSheenEnabled());
1326 defaultMaterialShaderKeyProperties.m_anisotropyEnabled.setValue(theGeneratedKey, theMaterial->isAnisotropyEnabled());
1327 defaultMaterialShaderKeyProperties.m_iridescenceEnabled.setValue(theGeneratedKey, theMaterial->isIridescenceEnabled());
1328 defaultMaterialShaderKeyProperties.m_dispersionEnabled.setValue(theGeneratedKey, theMaterial->isDispersionEnabled());
1329 defaultMaterialShaderKeyProperties.m_transmissionEnabled.setValue(theGeneratedKey, theMaterial->isTransmissionEnabled());
1334 QSSGRenderableImage *nextImage =
nullptr;
1335#define CHECK_IMAGE_AND_PREPARE(img, imgtype, shadercomponent)
1337 prepareImageForRender(*(img), imgtype, firstImage, nextImage, renderableFlags,
1338 theGeneratedKey, shadercomponent, &inMaterial)
1340 if (theMaterial->type == QSSGRenderGraphObject::Type::PrincipledMaterial ||
1341 theMaterial->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial) {
1343 QSSGRenderableImage::Type::BaseColor,
1344 QSSGShaderDefaultMaterialKeyProperties::BaseColorMap);
1346 QSSGRenderableImage::Type::Occlusion,
1347 QSSGShaderDefaultMaterialKeyProperties::OcclusionMap);
1349 QSSGRenderableImage::Type::Height,
1350 QSSGShaderDefaultMaterialKeyProperties::HeightMap);
1352 QSSGRenderableImage::Type::Clearcoat,
1353 QSSGShaderDefaultMaterialKeyProperties::ClearcoatMap);
1355 QSSGRenderableImage::Type::ClearcoatRoughness,
1356 QSSGShaderDefaultMaterialKeyProperties::ClearcoatRoughnessMap);
1358 QSSGRenderableImage::Type::ClearcoatNormal,
1359 QSSGShaderDefaultMaterialKeyProperties::ClearcoatNormalMap);
1361 QSSGRenderableImage::Type::SheenColor,
1362 QSSGShaderDefaultMaterialKeyProperties::SheenColorMap);
1364 QSSGRenderableImage::Type::SheenRoughness,
1365 QSSGShaderDefaultMaterialKeyProperties::SheenRoughnessMap);
1367 QSSGRenderableImage::Type::Anisotropy,
1368 QSSGShaderDefaultMaterialKeyProperties::AnisotropyMap);
1370 QSSGRenderableImage::Type::Iridescence,
1371 QSSGShaderDefaultMaterialKeyProperties::IridescenceMap);
1373 QSSGRenderableImage::Type::IridescenceThickness,
1374 QSSGShaderDefaultMaterialKeyProperties::IridescenceThicknessMap);
1376 QSSGRenderableImage::Type::Transmission,
1377 QSSGShaderDefaultMaterialKeyProperties::TransmissionMap);
1379 QSSGRenderableImage::Type::Thickness,
1380 QSSGShaderDefaultMaterialKeyProperties::ThicknessMap);
1381 if (theMaterial->type == QSSGRenderGraphObject::Type::PrincipledMaterial) {
1383 QSSGRenderableImage::Type::Metalness,
1384 QSSGShaderDefaultMaterialKeyProperties::MetalnessMap);
1388 QSSGRenderableImage::Type::Diffuse,
1389 QSSGShaderDefaultMaterialKeyProperties::DiffuseMap);
1391 CHECK_IMAGE_AND_PREPARE(theMaterial->emissiveMap, QSSGRenderableImage::Type::Emissive, QSSGShaderDefaultMaterialKeyProperties::EmissiveMap);
1393 QSSGRenderableImage::Type::Specular,
1394 QSSGShaderDefaultMaterialKeyProperties::SpecularMap);
1396 QSSGRenderableImage::Type::Roughness,
1397 QSSGShaderDefaultMaterialKeyProperties::RoughnessMap);
1398 CHECK_IMAGE_AND_PREPARE(theMaterial->opacityMap, QSSGRenderableImage::Type::Opacity, QSSGShaderDefaultMaterialKeyProperties::OpacityMap);
1399 CHECK_IMAGE_AND_PREPARE(theMaterial->bumpMap, QSSGRenderableImage::Type::Bump, QSSGShaderDefaultMaterialKeyProperties::BumpMap);
1401 QSSGRenderableImage::Type::SpecularAmountMap,
1402 QSSGShaderDefaultMaterialKeyProperties::SpecularAmountMap);
1403 CHECK_IMAGE_AND_PREPARE(theMaterial->normalMap, QSSGRenderableImage::Type::Normal, QSSGShaderDefaultMaterialKeyProperties::NormalMap);
1405 QSSGRenderableImage::Type::Translucency,
1406 QSSGShaderDefaultMaterialKeyProperties::TranslucencyMap);
1408#undef CHECK_IMAGE_AND_PREPARE
1410 if (subsetOpacity < QSSGRendererPrivate::minimumRenderOpacity) {
1411 subsetOpacity = 0.0f;
1415 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1416 renderableFlags |= QSSGRenderableObjectFlag::CompletelyTransparent;
1419 if (subsetOpacity > 1.f - QSSGRendererPrivate::minimumRenderOpacity)
1420 subsetOpacity = 1.f;
1422 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1424 if (inMaterial.isTransmissionEnabled()) {
1425 ioFlags.setRequiresScreenTexture(
true);
1426 ioFlags.setRequiresMipmapsForScreenTexture(
true);
1427 renderableFlags |= QSSGRenderableObjectFlag::RequiresScreenTexture;
1430 if (renderableFlags.hasTransparency()) {
1431 if (orderIndependentTransparencyEnabled)
1432 defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.setValue(theGeneratedKey,
int(layer.oitMethod));
1433 if (layer.oitMethodDirty)
1434 renderableFlags |= QSSGRenderableObjectFlag::Dirty;
1437 retval.firstImage = firstImage;
1438 if (retval.renderableFlags.isDirty())
1439 retval.dirty =
true;
1441 renderer->addMaterialDirtyClear(&inMaterial);
1445QSSGDefaultMaterialPreparationResult QSSGLayerRenderData::prepareCustomMaterialForRender(
1446 QSSGRenderCustomMaterial &inMaterial, QSSGRenderableObjectFlags &inExistingFlags,
1447 float inOpacity,
bool alreadyDirty,
bool hasAnyLights,
bool anyLightHasShadows,
1448 QSSGLayerRenderPreparationResultFlags &ioFlags)
1450 QSSGDefaultMaterialPreparationResult retval(QSSGShaderDefaultMaterialKey(qHash(features)));
1451 retval.renderableFlags = inExistingFlags;
1452 QSSGRenderableObjectFlags &renderableFlags(retval.renderableFlags);
1453 QSSGShaderDefaultMaterialKey &theGeneratedKey(retval.materialKey);
1454 retval.opacity = inOpacity;
1455 float &subsetOpacity(retval.opacity);
1457 if (subsetOpacity < QSSGRendererPrivate::minimumRenderOpacity) {
1458 subsetOpacity = 0.0f;
1462 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1463 renderableFlags |= QSSGRenderableObjectFlag::CompletelyTransparent;
1466 if (subsetOpacity > 1.f - QSSGRendererPrivate::minimumRenderOpacity)
1467 subsetOpacity = 1.f;
1469 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1471 defaultMaterialShaderKeyProperties.m_hasLighting.setValue(theGeneratedKey,
true);
1472 defaultMaterialShaderKeyProperties.m_hasPunctualLights.setValue(theGeneratedKey, hasAnyLights);
1473 defaultMaterialShaderKeyProperties.m_hasShadows.setValue(theGeneratedKey, anyLightHasShadows);
1474 defaultMaterialShaderKeyProperties.m_hasIbl.setValue(theGeneratedKey, layer.lightProbe !=
nullptr || layer.skyMaterial !=
nullptr);
1475 defaultMaterialShaderKeyProperties.m_specularEnabled.setValue(theGeneratedKey,
true);
1477 defaultMaterialShaderKeyProperties.m_specularAAEnabled.setValue(theGeneratedKey, layer.specularAAEnabled);
1480 defaultMaterialShaderKeyProperties.m_isDoubleSided.setValue(theGeneratedKey, inMaterial.m_cullMode == QSSGCullFaceMode::Disabled);
1483 defaultMaterialShaderKeyProperties.m_metallicRoughnessEnabled.setValue(theGeneratedKey,
true);
1486 const bool overridesPosition = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::OverridesPosition);
1487 defaultMaterialShaderKeyProperties.m_overridesPosition.setValue(theGeneratedKey, overridesPosition);
1490 const bool usesProjectionMatrix = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ProjectionMatrix);
1491 defaultMaterialShaderKeyProperties.m_usesProjectionMatrix.setValue(theGeneratedKey, usesProjectionMatrix);
1492 const bool usesInvProjectionMatrix = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::InverseProjectionMatrix);
1493 defaultMaterialShaderKeyProperties.m_usesInverseProjectionMatrix.setValue(theGeneratedKey, usesInvProjectionMatrix);
1496 setVertexInputPresence(renderableFlags, theGeneratedKey);
1499 if (!renderableFlags.hasAttributePosition()
1500 && !inMaterial.m_customShaderPresence.testFlag(QSSGRenderCustomMaterial::CustomShaderPresenceFlag::Vertex)
1501 && warnOnce(OneShotWarning::MissingPosition)) {
1502 warnMissingPosition();
1506 defaultMaterialShaderKeyProperties.m_usesPointsTopology.setValue(theGeneratedKey, renderableFlags.isPointsTopology());
1509 defaultMaterialShaderKeyProperties.m_lightmapEnabled.setValue(theGeneratedKey, renderableFlags.rendersWithLightmap());
1512 defaultMaterialShaderKeyProperties.m_debugMode.setValue(theGeneratedKey,
int(layer.debugMode));
1515 defaultMaterialShaderKeyProperties.m_fogEnabled.setValue(theGeneratedKey, layer.fog.enabled);
1518 defaultMaterialShaderKeyProperties.m_viewCount.setValue(theGeneratedKey, layer.viewCount);
1519 defaultMaterialShaderKeyProperties.m_usesViewIndex.setValue(theGeneratedKey,
1520 inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ViewIndex));
1525 const bool usesVarColor = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::VarColor);
1526 defaultMaterialShaderKeyProperties.m_usesVarColor.setValue(theGeneratedKey, usesVarColor);
1528 const bool usesClearcoat = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Clearcoat);
1529 defaultMaterialShaderKeyProperties.m_clearcoatEnabled.setValue(theGeneratedKey, usesClearcoat);
1531 const bool usesSheen = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Sheen);
1532 defaultMaterialShaderKeyProperties.m_sheenEnabled.setValue(theGeneratedKey, usesSheen);
1534 const bool usesAnisotropy = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Anisotropy);
1535 defaultMaterialShaderKeyProperties.m_anisotropyEnabled.setValue(theGeneratedKey, usesAnisotropy);
1537 const bool usesIridescence = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Iridescence);
1538 defaultMaterialShaderKeyProperties.m_iridescenceEnabled.setValue(theGeneratedKey, usesIridescence);
1540 const bool usesDispersion = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Dispersion);
1541 defaultMaterialShaderKeyProperties.m_dispersionEnabled.setValue(theGeneratedKey, usesDispersion);
1543 const bool usesClearcoatFresnelScaleBias = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ClearcoatFresnelScaleBias);
1544 defaultMaterialShaderKeyProperties.m_clearcoatFresnelScaleBiasEnabled.setValue(theGeneratedKey, usesClearcoatFresnelScaleBias);
1546 const bool usesFresnelScaleBias = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::FresnelScaleBias);
1547 defaultMaterialShaderKeyProperties.m_fresnelScaleBiasEnabled.setValue(theGeneratedKey, usesFresnelScaleBias);
1549 const bool usesTransmission = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Transmission);
1550 defaultMaterialShaderKeyProperties.m_transmissionEnabled.setValue(theGeneratedKey, usesTransmission);
1552 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Blending))
1553 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1555 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ScreenTexture)) {
1556 ioFlags.setRequiresScreenTexture(
true);
1557 renderableFlags |= QSSGRenderableObjectFlag::RequiresScreenTexture;
1560 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ScreenMipTexture)) {
1561 ioFlags.setRequiresScreenTexture(
true);
1562 ioFlags.setRequiresMipmapsForScreenTexture(
true);
1563 renderableFlags |= QSSGRenderableObjectFlag::RequiresScreenTexture;
1566 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::DepthTexture))
1567 ioFlags.setRequiresDepthTexture(
true);
1569 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::NormalTexture)) {
1570 ioFlags.setRequiresNormalTexture(
true);
1571 renderableFlags |= QSSGRenderableObjectFlag::RequiresNormalTexture;
1574 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::AoTexture)) {
1575 ioFlags.setRequiresDepthTexture(
true);
1576 ioFlags.setRequiresSsaoPass(
true);
1578 if (orderIndependentTransparencyEnabled && renderableFlags.hasTransparency())
1579 defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.setValue(theGeneratedKey,
int(layer.oitMethod));
1581 retval.firstImage =
nullptr;
1583 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::MotionVectorTexture))
1584 ioFlags.setRequiresMotionVectorPass(
true);
1586 if (retval.dirty || alreadyDirty)
1587 renderer->addMaterialDirtyClear(&inMaterial);
1727bool QSSGLayerRenderData::prepareModelsForRender(QSSGRenderContextInterface &contextInterface,
1728 const RenderableNodeEntries &renderableModels,
1729 QSSGLayerRenderPreparationResultFlags &ioFlags,
1730 const QSSGRenderCameraList &allCameras,
1731 const QSSGRenderCameraDataList &allCameraData,
1732 TModelContextPtrList &modelContexts,
1733 QSSGRenderableObjectList &opaqueObjects,
1734 QSSGRenderableObjectList &transparentObjects,
1735 QSSGRenderableObjectList &screenTextureObjects,
1738 const auto &rhiCtx = contextInterface.rhiContext();
1739 const auto &bufferManager = contextInterface.bufferManager();
1741 const auto &debugDrawSystem = contextInterface.debugDrawSystem();
1742 if (debugDrawSystem && layer.drawLevelsOfDetail)
1743 debugDrawSystem->setEnabled(
true);
1744 const bool maybeDebugDraw = debugDrawSystem && debugDrawSystem->isEnabled();
1745 const bool debugDrawMeshLod = maybeDebugDraw
1746 && (layer.drawLevelsOfDetail || debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLod));
1748 bool wasDirty =
false;
1753 const bool isLayerCamera = !allCameras.isEmpty() && !renderedCameras.isEmpty()
1754 && allCameras.first() == renderedCameras.first();
1756 for (
const QSSGRenderableNodeEntry &renderable : renderableModels) {
1757 if ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::Disabled) != 0)
1760 const QSSGRenderModel &model = *
static_cast<QSSGRenderModel *>(renderable.node);
1761 const auto &lights = renderable.lights;
1762 QSSGRenderMesh *theMesh = modelData->getMesh(model);
1766 const bool altGlobalTransform = ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::GlobalTransform) != 0);
1767 const auto &globalTransform = altGlobalTransform ? renderable.extOverrides.globalTransform : getGlobalTransform(model);
1768 QMatrix3x3 normalMatrix { Qt::Uninitialized };
1769 QSSGLayerRenderData::ModelViewProjections mvps;
1770 if (altGlobalTransform) {
1771 QSSGRenderNode::calculateNormalMatrix(globalTransform, normalMatrix);
1772 size_t mvpCount = 0;
1773 for (
const auto &cameraData : allCameraData) {
1774 QSSGRenderNode::calculateMVPAndNormalMatrix(globalTransform, cameraData.viewProjection, mvps[mvpCount++], normalMatrix);
1777 if (model.usesBoneTexture()) {
1781 size_t mvpCount = 0;
1782 for (
const QSSGRenderCameraData &cameraData : allCameraData) {
1783 mvps[mvpCount++] = cameraData.viewProjection;
1784 normalMatrix = QMatrix3x3();
1787 normalMatrix = getNormalMatrix(model);
1788 mvps = getModelMvps(model);
1791 const bool altModelOpacity = ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::GlobalOpacity) != 0);
1792 const float modelGlobalOpacity = altModelOpacity ? renderable.extOverrides.globalOpacity : getGlobalOpacity(model);
1793 QSSGModelContext &theModelContext = *RENDER_FRAME_NEW<QSSGModelContext>(contextInterface, model, globalTransform, normalMatrix, mvps);
1794 modelContexts.push_back(&theModelContext);
1796 if (model.usesBufferlessInstancing()) {
1797 if (!rhiCtx->rhi()->isFeatureSupported(QRhi::Instancing) && warnOnce(OneShotWarning::BufferlessInstancingUnsupported)) {
1798 qCWarning(lcQuick3DRender,
"ShaderInstancing requires instancing support, which this "
1799 "graphics API or device does not provide.");
1801 if ((model.instancingLodMin >= 0 || model.instancingLodMax >= 0) && warnOnce(OneShotWarning::BufferlessInstancingLod)) {
1802 qCWarning(lcQuick3DRender,
"Model.instancingLodMin/instancingLodMax have no effect with "
1803 "ShaderInstancing: instance level of detail needs per-instance "
1804 "data to read. Cull in the vertex shader instead.");
1809 const auto &meshSubsets = theMesh->subsets;
1810 const auto meshSubsetCount = meshSubsets.size();
1811 theModelContext.subsets = RENDER_FRAME_NEW_BUFFER<QSSGSubsetRenderable>(contextInterface, meshSubsetCount);
1815 auto boneTexture = bufferManager->loadSkinmap(model.skin);
1816 setBonemapTexture(theModelContext, boneTexture.m_texture);
1817 }
else if (model.skeleton) {
1818 auto boneTexture = bufferManager->loadSkinmap(&(model.skeleton->boneTexData));
1819 setBonemapTexture(theModelContext, boneTexture.m_texture);
1823 QSSGRenderableObjectFlags renderableFlagsForModel;
1825 bool usesBlendParticles = particlesEnabled && theModelContext.model.particleBuffer !=
nullptr
1826 && model.particleBuffer->particleCount();
1828 if (meshSubsetCount > 0) {
1829 const QSSGRenderSubset &theSubset = meshSubsets.at(0);
1831 renderableFlagsForModel.setCastsShadows(model.castsShadows);
1832 renderableFlagsForModel.setReceivesShadows(model.receivesShadows);
1833 renderableFlagsForModel.setReceivesReflections(model.receivesReflections);
1834 renderableFlagsForModel.setCastsReflections(model.castsReflections);
1836 renderableFlagsForModel.setUsedInBakedLighting(model.usedInBakedLighting);
1837 if (model.hasLightmap()) {
1838 QSSGRenderImageTexture lmImageTexture = bufferManager->loadLightmap(model);
1839 if (lmImageTexture.m_texture) {
1840 renderableFlagsForModel.setRendersWithLightmap(
true);
1841 setLightmapTexture(theModelContext, lmImageTexture.m_texture);
1850 bool hasJoint =
false;
1851 bool hasWeight =
false;
1852 bool hasMorphTarget = theSubset.rhi.targetsTexture !=
nullptr;
1853 for (
const QSSGRhiInputAssemblerState::InputSemantic &sem : std::as_const(theSubset.rhi.ia.inputs)) {
1854 if (sem == QSSGRhiInputAssemblerState::PositionSemantic) {
1855 renderableFlagsForModel.setHasAttributePosition(
true);
1856 }
else if (sem == QSSGRhiInputAssemblerState::NormalSemantic) {
1857 renderableFlagsForModel.setHasAttributeNormal(
true);
1858 }
else if (sem == QSSGRhiInputAssemblerState::TexCoord0Semantic) {
1859 renderableFlagsForModel.setHasAttributeTexCoord0(
true);
1860 }
else if (sem == QSSGRhiInputAssemblerState::TexCoord1Semantic) {
1861 renderableFlagsForModel.setHasAttributeTexCoord1(
true);
1862 }
else if (sem == QSSGRhiInputAssemblerState::TexCoordLightmapSemantic) {
1863 renderableFlagsForModel.setHasAttributeTexCoordLightmap(
true);
1864 }
else if (sem == QSSGRhiInputAssemblerState::TangentSemantic) {
1865 renderableFlagsForModel.setHasAttributeTangent(
true);
1866 }
else if (sem == QSSGRhiInputAssemblerState::BinormalSemantic) {
1867 renderableFlagsForModel.setHasAttributeBinormal(
true);
1868 }
else if (sem == QSSGRhiInputAssemblerState::ColorSemantic) {
1869 renderableFlagsForModel.setHasAttributeColor(
true);
1872 }
else if (sem == QSSGRhiInputAssemblerState::JointSemantic) {
1874 }
else if (sem == QSSGRhiInputAssemblerState::WeightSemantic) {
1878 renderableFlagsForModel.setHasAttributeJointAndWeight(hasJoint && hasWeight);
1879 renderableFlagsForModel.setHasAttributeMorphTarget(hasMorphTarget);
1884 renderableFlagsForModel.setMotionVectorParticipant(
1885 model.motionVectorEnabled && !usesBlendParticles
1886 && renderableFlagsForModel.hasAttributePosition());
1889 QSSGRenderableObjectList bakedLightingObjects;
1890 const bool anyLightHasShadows = std::find_if(lights.begin(),
1892 [](
const QSSGShaderLight &light) {
return light.shadows; })
1894 const bool hasAnyLights = !lights.isEmpty();
1895 QSSGRenderLight::SoftShadowQuality maxSoftShadowQuality = QSSGRenderLight::SoftShadowQuality::Hard;
1896 if (anyLightHasShadows) {
1898 for (
const QSSGShaderLight &light : lights) {
1899 if (light.shadows && light.light->m_softShadowQuality > maxSoftShadowQuality)
1900 maxSoftShadowQuality = light.light->m_softShadowQuality;
1906 auto &renderableSubsets = theModelContext.subsets;
1907 const bool hasMaterialOverrides = ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::Materials) != 0);
1908 const auto &materials = hasMaterialOverrides ? renderable.extOverrides.materials : modelData->getMaterials(model);
1909 const auto materialCount = materials.size();
1910 QSSGRenderGraphObject *lastMaterial = !materials.isEmpty() ? materials.last() :
nullptr;
1911 int idx = 0, subsetIdx = 0;
1912 for (; idx < meshSubsetCount; ++idx) {
1914 QSSGRenderGraphObject *theMaterialObject = (idx >= materialCount) ? lastMaterial : materials[idx];
1915 if (!theMaterialObject)
1918 const QSSGRenderSubset &theSubset = meshSubsets.at(idx);
1919 QSSGRenderableObjectFlags renderableFlags = renderableFlagsForModel;
1920 float subsetOpacity = modelGlobalOpacity;
1922 renderableFlags.setPointsTopology(theSubset.rhi.ia.topology == QRhiGraphicsPipeline::Points);
1923 QSSGRenderableObject *theRenderableObject = &renderableSubsets[subsetIdx++];
1925 const bool usesInstanceBuffer = theModelContext.model.usesInstanceBuffer()
1926 && rhiCtx->rhi()->isFeatureSupported(QRhi::Instancing);
1927 const bool usesBufferlessInstancing = theModelContext.model.usesBufferlessInstancing()
1928 && rhiCtx->rhi()->isFeatureSupported(QRhi::Instancing);
1930 if (usesInstanceBuffer && theModelContext.model.instanceTable->hasTransparency())
1931 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1932 if (theModelContext.model.hasTransparency)
1933 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1936 quint32 subsetLevelOfDetail = 0;
1939 const bool autoInstanceLod = usesInstanceBuffer && isLayerCamera
1940 && usesAutoInstanceLod(model, theSubset, lodThreshold);
1941 if (!theSubset.lods.isEmpty() && lodThreshold > 0.0f) {
1943 float lodDistanceMultiplier = camerasView[0]->getLevelOfDetailMultiplier();
1944 float distanceThreshold = 0.0f;
1945 const auto scale = QSSGUtils::mat44::getScale(globalTransform);
1946 float modelScale = qMax(scale.x(), qMax(scale.y(), scale.z()));
1947 QSSGBounds3 transformedBounds = theSubset.bounds;
1948 transformedBounds.transform(globalTransform);
1949 if (camerasView[0]->type != QSSGRenderGraphObject::Type::OrthographicCamera) {
1950 if (maybeDebugDraw && debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLod))
1951 debugDrawSystem->drawBounds(transformedBounds, QColor(Qt::red));
1952 const QMatrix4x4 cameraGlobalTranform = getGlobalTransform(*camerasView[0]);
1953 const QVector3D cameraNormal = QSSGRenderNode::getScalingCorrectDirection(cameraGlobalTranform);
1954 const QVector3D cameraPosition = QSSGRenderNode::getGlobalPos(cameraGlobalTranform);
1955 const QSSGPlane cameraPlane = QSSGPlane(cameraPosition, cameraNormal);
1956 const QVector3D lodSupportMin = transformedBounds.getSupport(-cameraNormal);
1957 const QVector3D lodSupportMax = transformedBounds.getSupport(cameraNormal);
1958 if (maybeDebugDraw && debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLod))
1959 debugDrawSystem->drawPoint(lodSupportMin, QColor(
"orange"));
1961 const float distanceMin = cameraPlane.distance(lodSupportMin);
1962 const float distanceMax = cameraPlane.distance(lodSupportMax);
1964 if (distanceMin * distanceMax < 0.0)
1965 distanceThreshold = 0.0;
1966 else if (distanceMin >= 0.0)
1967 distanceThreshold = distanceMin;
1968 else if (distanceMax <= 0.0)
1969 distanceThreshold = -distanceMax;
1973 distanceThreshold = 1.0;
1976 int currentLod = -1;
1977 if (model.levelOfDetailBias > 0.0f) {
1978 const int lodsCount = theSubset.lods.size();
1979 if (model.instanceTable) {
1984 if (!autoInstanceLod)
1985 currentLod = qRound(lodsCount * qBound(0.f, model.instancingLodFactor, 1.f)) - 1;
1987 const float threshold = distanceThreshold * lodDistanceMultiplier;
1988 const float modelBias = 1 / model.levelOfDetailBias;
1989 for (qsizetype i = 0; i < lodsCount; ++i) {
1990 float subsetDistance = theSubset.lods[i].distance * modelScale * modelBias;
1991 float screenSize = subsetDistance / threshold;
1992 if (screenSize > lodThreshold)
1998 Q_ASSERT(currentLod >= -1);
1999 subsetLevelOfDetail = currentLod + 1;
2001 if (debugDrawMeshLod && !autoInstanceLod && !model.instanceTable)
2002 debugDrawSystem->drawBounds(transformedBounds, QSSGDebugDrawSystem::levelOfDetailColor(subsetLevelOfDetail));
2005 QVector3D theModelCenter(theSubset.bounds.center());
2006 theModelCenter = QSSGUtils::mat44::transform(globalTransform, theModelCenter);
2007 if (maybeDebugDraw && debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLodNormal)) {
2008 const QMatrix4x4 allCamera0GlobalTransform = getGlobalTransform(*allCameras[0]);
2009 debugDrawSystem->debugNormals(*bufferManager, theModelContext, theSubset, subsetLevelOfDetail, (theModelCenter - QSSGRenderNode::getGlobalPos(allCamera0GlobalTransform)).length() * 0.01);
2012 auto checkF32TypeIndex = [&rhiCtx](QRhiVertexInputAttribute::Format f) {
2013 if ((f == QRhiVertexInputAttribute::Format::Float4)
2014 || (f == QRhiVertexInputAttribute::Format::Float3)
2015 || (f == QRhiVertexInputAttribute::Format::Float2)
2016 || (f == QRhiVertexInputAttribute::Format::Float)) {
2019 if (!rhiCtx->rhi()->isFeatureSupported(QRhi::IntAttributes))
2020 qWarning() <<
"WARN: Model has non-integer type indices for skinning but current RHI backend doesn't support it!";
2024 if (theMaterialObject->type == QSSGRenderGraphObject::Type::DefaultMaterial ||
2025 theMaterialObject->type == QSSGRenderGraphObject::Type::PrincipledMaterial ||
2026 theMaterialObject->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial) {
2027 QSSGRenderDefaultMaterial &theMaterial(
static_cast<QSSGRenderDefaultMaterial &>(*theMaterialObject));
2028 QSSGDefaultMaterialPreparationResult theMaterialPrepResult(prepareDefaultMaterialForRender(theMaterial, renderableFlags, subsetOpacity, hasAnyLights, anyLightHasShadows, ioFlags));
2029 QSSGShaderDefaultMaterialKey &theGeneratedKey(theMaterialPrepResult.materialKey);
2030 subsetOpacity = theMaterialPrepResult.opacity;
2031 QSSGRenderableImage *firstImage(theMaterialPrepResult.firstImage);
2032 wasDirty |= theMaterialPrepResult.dirty;
2033 renderableFlags = theMaterialPrepResult.renderableFlags;
2034 if (renderableFlags.hasTransparency())
2035 ioFlags.setHasCustomBlendMode(theMaterial.blendMode != QSSGRenderDefaultMaterial::MaterialBlendMode::SourceOver);
2038 defaultMaterialShaderKeyProperties.m_blendParticles.setValue(theGeneratedKey, usesBlendParticles);
2040 if (defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.getValue(theGeneratedKey) ==
int(QSSGRenderLayer::OITMethod::LinkedList))
2041 defaultMaterialShaderKeyProperties.m_oitMSAA.setValue(theGeneratedKey, rhiCtx->mainPassSampleCount() > 1);
2044 const auto boneCount = model.skin ? model.skin->boneCount :
2045 model.skeleton ? model.skeleton->boneCount : 0;
2046 defaultMaterialShaderKeyProperties.m_boneCount.setValue(theGeneratedKey, boneCount);
2047 if (
auto idJoint = theSubset.rhi.ia.inputs.indexOf(QSSGRhiInputAssemblerState::JointSemantic); idJoint != -1) {
2048 const auto attr = theSubset.rhi.ia.inputLayout.attributeAt(idJoint);
2049 defaultMaterialShaderKeyProperties.m_usesFloatJointIndices.setValue(theGeneratedKey, checkF32TypeIndex(attr->format()));
2053 defaultMaterialShaderKeyProperties.m_shadowSoftness.setShadowSoftness(theGeneratedKey, maxSoftShadowQuality);
2056 defaultMaterialShaderKeyProperties.m_usesInstanceBuffer.setValue(theGeneratedKey, usesInstanceBuffer);
2057 defaultMaterialShaderKeyProperties.m_usesBufferlessInstancing.setValue(theGeneratedKey, usesBufferlessInstancing);
2059 defaultMaterialShaderKeyProperties.m_targetCount.setValue(theGeneratedKey,
2060 theSubset.rhi.ia.targetCount);
2061 defaultMaterialShaderKeyProperties.m_targetPositionOffset.setValue(theGeneratedKey,
2062 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::PositionSemantic]);
2063 defaultMaterialShaderKeyProperties.m_targetNormalOffset.setValue(theGeneratedKey,
2064 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::NormalSemantic]);
2065 defaultMaterialShaderKeyProperties.m_targetTangentOffset.setValue(theGeneratedKey,
2066 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TangentSemantic]);
2067 defaultMaterialShaderKeyProperties.m_targetBinormalOffset.setValue(theGeneratedKey,
2068 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::BinormalSemantic]);
2069 defaultMaterialShaderKeyProperties.m_targetTexCoord0Offset.setValue(theGeneratedKey,
2070 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord0Semantic]);
2071 defaultMaterialShaderKeyProperties.m_targetTexCoord1Offset.setValue(theGeneratedKey,
2072 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord1Semantic]);
2073 defaultMaterialShaderKeyProperties.m_targetColorOffset.setValue(theGeneratedKey,
2074 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::ColorSemantic]);
2076 new (theRenderableObject) QSSGSubsetRenderable(QSSGSubsetRenderable::Type::DefaultMaterialMeshSubset,
2083 subsetLevelOfDetail,
2088 anyLightHasShadows);
2089 wasDirty = wasDirty || renderableFlags.isDirty();
2090 }
else if (theMaterialObject->type == QSSGRenderGraphObject::Type::CustomMaterial) {
2091 QSSGRenderCustomMaterial &theMaterial(
static_cast<QSSGRenderCustomMaterial &>(*theMaterialObject));
2093 const auto &theMaterialSystem(contextInterface.customMaterialSystem());
2094 wasDirty |= theMaterialSystem->prepareForRender(theModelContext.model, theSubset, theMaterial);
2096 if (theMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Blending))
2097 ioFlags.setHasCustomBlendMode(!hasCustomBlendMode(theMaterial));
2099 QSSGDefaultMaterialPreparationResult theMaterialPrepResult(
2100 prepareCustomMaterialForRender(theMaterial, renderableFlags, subsetOpacity, wasDirty,
2101 hasAnyLights, anyLightHasShadows, ioFlags));
2102 QSSGShaderDefaultMaterialKey &theGeneratedKey(theMaterialPrepResult.materialKey);
2103 subsetOpacity = theMaterialPrepResult.opacity;
2104 QSSGRenderableImage *firstImage(theMaterialPrepResult.firstImage);
2105 renderableFlags = theMaterialPrepResult.renderableFlags;
2107 if (model.particleBuffer && model.particleBuffer->particleCount())
2108 defaultMaterialShaderKeyProperties.m_blendParticles.setValue(theGeneratedKey,
true);
2110 defaultMaterialShaderKeyProperties.m_blendParticles.setValue(theGeneratedKey,
false);
2112 if (defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.getValue(theGeneratedKey) ==
int(QSSGRenderLayer::OITMethod::LinkedList))
2113 defaultMaterialShaderKeyProperties.m_oitMSAA.setValue(theGeneratedKey, rhiCtx->mainPassSampleCount() > 1);
2116 defaultMaterialShaderKeyProperties.m_shadowSoftness.setShadowSoftness(theGeneratedKey, maxSoftShadowQuality);
2119 const auto boneCount = model.skin ? model.skin->boneCount :
2120 model.skeleton ? model.skeleton->boneCount : 0;
2121 defaultMaterialShaderKeyProperties.m_boneCount.setValue(theGeneratedKey, boneCount);
2122 if (
auto idJoint = theSubset.rhi.ia.inputs.indexOf(QSSGRhiInputAssemblerState::JointSemantic); idJoint != -1) {
2123 const auto attr = theSubset.rhi.ia.inputLayout.attributeAt(idJoint);
2124 defaultMaterialShaderKeyProperties.m_usesFloatJointIndices.setValue(theGeneratedKey, checkF32TypeIndex(attr->format()));
2128 defaultMaterialShaderKeyProperties.m_usesInstanceBuffer.setValue(theGeneratedKey, usesInstanceBuffer);
2129 defaultMaterialShaderKeyProperties.m_usesBufferlessInstancing.setValue(theGeneratedKey, usesBufferlessInstancing);
2131 defaultMaterialShaderKeyProperties.m_targetCount.setValue(theGeneratedKey,
2132 theSubset.rhi.ia.targetCount);
2133 defaultMaterialShaderKeyProperties.m_targetPositionOffset.setValue(theGeneratedKey,
2134 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::PositionSemantic]);
2135 defaultMaterialShaderKeyProperties.m_targetNormalOffset.setValue(theGeneratedKey,
2136 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::NormalSemantic]);
2137 defaultMaterialShaderKeyProperties.m_targetTangentOffset.setValue(theGeneratedKey,
2138 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TangentSemantic]);
2139 defaultMaterialShaderKeyProperties.m_targetBinormalOffset.setValue(theGeneratedKey,
2140 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::BinormalSemantic]);
2141 defaultMaterialShaderKeyProperties.m_targetTexCoord0Offset.setValue(theGeneratedKey,
2142 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord0Semantic]);
2143 defaultMaterialShaderKeyProperties.m_targetTexCoord1Offset.setValue(theGeneratedKey,
2144 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord1Semantic]);
2145 defaultMaterialShaderKeyProperties.m_targetColorOffset.setValue(theGeneratedKey,
2146 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::ColorSemantic]);
2148 if (theMaterial.m_iblProbe)
2149 theMaterial.m_iblProbe->clearDirty();
2151 new (theRenderableObject) QSSGSubsetRenderable(QSSGSubsetRenderable::Type::CustomMaterialMeshSubset,
2158 subsetLevelOfDetail,
2163 anyLightHasShadows);
2165 if (theRenderableObject) {
2166 theRenderableObject->camdistSq = getCameraDistanceSq(*theRenderableObject, allCameraData[0]);
2169 if (autoInstanceLod) {
2170 auto *sr =
static_cast<QSSGSubsetRenderable *>(theRenderableObject);
2172 const float lodDistMult = allCameras.first()->getLevelOfDetailMultiplier();
2173 sr->usesAutoLod =
true;
2174 sr->autoLodTint = layer.drawLevelsOfDetail;
2175 sr->autoLodLevelCount = qMin(
int(theSubset.lods.size()) + 1,
2176 QSSGSubsetRenderable::MaxAutoLodLevels);
2177 sr->autoLodThresholdFactor = 1.0f / (model.levelOfDetailBias * lodDistMult * lodThreshold);
2180 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(contextInterface.rhiContext().get());
2181 rhiCtxD->instanceBufferData(&model).subsetLodData[{ &theSubset, &layer }].lastUsedFrame = renderer->frameCount();
2186 if (model.geometry && model.geometry->indirectDraw().enabled)
2187 prepareIndirectDraw(contextInterface, *
this, *model.geometry,
2188 *
static_cast<QSSGSubsetRenderable *>(theRenderableObject));
2193 if (Q_UNLIKELY(idx != subsetIdx))
2194 renderableSubsets.mSize = subsetIdx;
2196 for (
auto &ro : renderableSubsets) {
2197 const auto depthMode = ro.depthWriteMode;
2198 hasDepthWriteObjects |= (depthMode == QSSGDepthDrawMode::Always || depthMode == QSSGDepthDrawMode::OpaqueOnly);
2199 enum ObjectType : quint8 { ScreenTexture, Transparent, Opaque };
2200 static constexpr DepthPrepassObject ppState[][2] = { {DepthPrepassObject::None, DepthPrepassObject::ScreenTexture},
2201 {DepthPrepassObject::None, DepthPrepassObject::Transparent},
2202 {DepthPrepassObject::None, DepthPrepassObject::Opaque} };
2204 if (ro.renderableFlags.requiresScreenTexture()) {
2205 depthPrepassObjectsState |= DepthPrepassObjectStateT(ppState[ObjectType::ScreenTexture][size_t(depthMode == QSSGDepthDrawMode::OpaquePrePass)]);
2206 screenTextureObjects.push_back({&ro, ro.camdistSq, model.tag});
2207 }
else if (ro.renderableFlags.hasTransparency()) {
2208 depthPrepassObjectsState |= DepthPrepassObjectStateT(ppState[ObjectType::Transparent][size_t(depthMode == QSSGDepthDrawMode::OpaquePrePass)]);
2209 transparentObjects.push_back({&ro, ro.camdistSq, model.tag});
2211 depthPrepassObjectsState |= DepthPrepassObjectStateT(ppState[ObjectType::Opaque][size_t(depthMode == QSSGDepthDrawMode::OpaquePrePass)]);
2212 opaqueObjects.push_back({&ro, ro.camdistSq, model.tag});
2215 if (ro.renderableFlags.usedInBakedLighting())
2216 bakedLightingObjects.push_back({&ro, ro.camdistSq, model.tag});
2220 if (!bakedLightingObjects.isEmpty() && model.geometry
2221 && model.geometry->meshData().isVertexCountOnly()) {
2222 if (warnOnce(OneShotWarning::BakedLightingWithoutVertexData))
2223 qCWarning(lcQuick3DRender,
"Models without vertex data (ShaderGeometry/IndirectShaderGeometry) cannot be used with baked lighting.");
2224 bakedLightingObjects.clear();
2227 if (!bakedLightingObjects.isEmpty())
2228 bakedLightingModels.push_back(QSSGBakedLightingModel(&model, bakedLightingObjects));
2234bool QSSGLayerRenderData::prepareParticlesForRender(
const RenderableNodeEntries &renderableParticles,
const QSSGRenderCameraData &cameraData, QSSGLayerRenderPreparationResultFlags &ioFlags)
2236 QSSG_ASSERT(particlesEnabled,
return false);
2238 QSSGRenderContextInterface &contextInterface = *renderer->contextInterface();
2243 auto &opaqueObjects = opaqueObjectStore[0];
2244 auto &transparentObjects = transparentObjectStore[0];
2245 auto &screenTextureObjects = screenTextureObjectStore[0];
2247 for (
auto &renderable : renderableParticles) {
2248 QSSGShaderParticleMaterialKeyProperties &properties = particleMaterialShaderKeyProperties;
2250 QSSGRenderParticles &particles = *
static_cast<QSSGRenderParticles *>(renderable.node);
2251 QSSGShaderParticleMaterialKey &theGeneratedKey(particles.materialKey);
2252 const auto &lights = renderable.lights;
2254 QSSGRenderableObjectFlags renderableFlags;
2255 renderableFlags.setCastsShadows(
false);
2256 renderableFlags.setReceivesShadows(
false);
2257 renderableFlags.setHasAttributePosition(
true);
2258 renderableFlags.setHasAttributeNormal(
true);
2259 renderableFlags.setHasAttributeTexCoord0(
true);
2260 renderableFlags.setHasAttributeColor(
true);
2261 renderableFlags.setHasTransparency(particles.m_hasTransparency);
2262 renderableFlags.setCastsReflections(particles.m_castsReflections);
2263 if (particles.m_hasTransparency && particles.m_blendMode != QSSGRenderParticles::BlendMode::SourceOver)
2264 ioFlags.setHasCustomBlendMode(
true);
2266 properties.m_isLineParticle.setValue(theGeneratedKey, particles.m_featureLevel >= QSSGRenderParticles::FeatureLevel::Line);
2267 const bool animated = particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineAnimated
2268 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::Animated
2269 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::AnimatedVLight
2270 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineAnimatedVLight;
2271 const bool mapped = particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineMapped
2272 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::Mapped
2273 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::MappedVLight
2274 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineMappedVLight;
2275 const bool lit = particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineVLight
2276 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::AnimatedVLight
2277 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::MappedVLight
2278 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineMappedVLight
2279 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineAnimatedVLight
2280 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::SimpleVLight;
2281 properties.m_isAnimated.setValue(theGeneratedKey, animated);
2282 properties.m_isMapped.setValue(theGeneratedKey, mapped);
2283 properties.m_hasLighting.setValue(theGeneratedKey, lit);
2284 properties.m_viewCount.setValue(theGeneratedKey, layer.viewCount);
2285 if (renderableFlags.hasTransparency() && orderIndependentTransparencyEnabled) {
2286 properties.m_orderIndependentTransparency.setValue(theGeneratedKey,
int(layer.oitMethod));
2287 if (layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
2288 properties.m_oitMSAA.setValue(theGeneratedKey, contextInterface.rhiContext()->mainPassSampleCount() > 1);
2290 properties.m_orderIndependentTransparency.setValue(theGeneratedKey,
int(0));
2293 float opacity = getGlobalOpacity(particles);
2294 const QMatrix4x4 globalTransform = getGlobalTransform(particles);
2295 QVector3D center(particles.m_particleBuffer.bounds().center());
2296 center = QSSGUtils::mat44::transform(globalTransform, center);
2298 QSSGRenderableImage *firstImage =
nullptr;
2299 if (particles.m_sprite) {
2300 const auto &bufferManager = contextInterface.bufferManager();
2302 if (particles.m_sprite->clearDirty())
2305 const QSSGRenderImageTexture texture = bufferManager->loadRenderImage(particles.m_sprite);
2306 QSSGRenderableImage *theImage = RENDER_FRAME_NEW<QSSGRenderableImage>(contextInterface, QSSGRenderableImage::Type::Diffuse, *particles.m_sprite, texture);
2307 firstImage = theImage;
2308 properties.m_isSpriteLinear.setValue(theGeneratedKey, texture.m_flags.isLinear());
2311 QSSGRenderableImage *colorTable =
nullptr;
2312 if (particles.m_colorTable) {
2313 const auto &bufferManager = contextInterface.bufferManager();
2315 if (particles.m_colorTable->clearDirty())
2318 const QSSGRenderImageTexture texture = bufferManager->loadRenderImage(particles.m_colorTable);
2320 QSSGRenderableImage *theImage = RENDER_FRAME_NEW<QSSGRenderableImage>(contextInterface, QSSGRenderableImage::Type::Diffuse, *particles.m_colorTable, texture);
2321 colorTable = theImage;
2322 properties.m_isColorTableLinear.setValue(theGeneratedKey, texture.m_flags.isLinear());
2325 if (opacity > 0.0f && particles.m_particleBuffer.particleCount()) {
2326 auto *theRenderableObject = RENDER_FRAME_NEW<QSSGParticlesRenderable>(contextInterface,
2337 if (theRenderableObject) {
2338 if (theRenderableObject->renderableFlags.requiresScreenTexture())
2339 screenTextureObjects.push_back({theRenderableObject, getCameraDistanceSq(*theRenderableObject, cameraData), particles.tag});
2340 else if (theRenderableObject->renderableFlags.hasTransparency())
2341 transparentObjects.push_back({theRenderableObject, getCameraDistanceSq(*theRenderableObject, cameraData), particles.tag});
2343 opaqueObjects.push_back({theRenderableObject, getCameraDistanceSq(*theRenderableObject, cameraData), particles.tag});
2630void QSSGLayerRenderData::prepareForRender()
2632 QSSG_ASSERT_X(layerPrepResult.isNull(),
"Prep-result was not reset for render!", layerPrepResult = {});
2634 QRect theViewport(renderer->viewport());
2635 const auto &rhiCtx = renderer->contextInterface()->rhiContext();
2639 frameData.m_ctx = renderer->contextInterface();
2644 ps.viewport = {
float(theViewport.x()),
float(theViewport.y()),
float(theViewport.width()),
float(theViewport.height()), 0.0f, 1.0f };
2645 if (layer.scissorRect.isValid()) {
2646 ps.flags |= QSSGRhiGraphicsPipelineState::Flag::UsesScissor;
2647 ps.scissor = { theViewport.x() + layer.scissorRect.x(),
2648 theViewport.y() + theViewport.height() - (layer.scissorRect.y() + layer.scissorRect.height()),
2649 layer.scissorRect.width(),
2650 layer.scissorRect.height() };
2654 auto *rt = rhiCtx->renderTarget();
2655 if (!rt || renderer->contextInterface()->rhi()->isYUpInFramebuffer())
2656 m_viewportOrigin = QVector2D(theViewport.x(), theViewport.y());
2658 m_viewportOrigin = QVector2D(theViewport.x(), rt->pixelSize().height() - theViewport.y() - theViewport.height());
2660 ps.depthFunc = QRhiGraphicsPipeline::LessOrEqual;
2661 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::BlendEnabled,
false);
2664 ps.polygonMode = layer.wireframeMode ? QRhiGraphicsPipeline::Line : QRhiGraphicsPipeline::Fill;
2666 bool wasDirty =
false;
2667 bool wasDataDirty =
false;
2668 wasDirty = layer.isDirty();
2670 const bool shouldDisableInternalPasses = (layer.renderOverrides & size_t(QSSGRenderLayer::RenderOverrides::DisableInternalPasses)) != 0;
2671 wasDirty |= (shouldDisableInternalPasses != disableMainPasses);
2672 disableMainPasses = shouldDisableInternalPasses;
2675 layerPrepResult = { theViewport, layer };
2678 const bool SSAOEnabled = layer.ssaoEnabled();
2679 layerPrepResult.flags.setRequiresSsaoPass(SSAOEnabled);
2680 features.set(QSSGShaderFeatures::Feature::Ssao, SSAOEnabled);
2683 bool requiresDepthTexture = SSAOEnabled;
2684 bool requiresNormalTexture =
false;
2685 bool requiresMotionVectorTexture =
false;
2686 for (QSSGRenderEffect *theEffect = layer.firstEffect; theEffect; theEffect = theEffect->m_nextEffect) {
2687 if (theEffect->isDirty()) {
2689 theEffect->clearDirty();
2691 if (theEffect->testFlag(QSSGRenderEffect::Flags::UsesDepthTexture))
2692 requiresDepthTexture =
true;
2693 if (theEffect->testFlag(QSSGRenderEffect::Flags::UsesNormalTexture))
2694 requiresNormalTexture =
true;
2695 if (theEffect->testFlag(QSSGRenderEffect::Flags::UsesMotionVectorTexture))
2696 requiresMotionVectorTexture =
true;
2699 orderIndependentTransparencyEnabled = (layer.oitMethod != QSSGRenderLayer::OITMethod::None);
2700 if (layer.oitMethod == QSSGRenderLayer::OITMethod::WeightedBlended) {
2701 orderIndependentTransparencyEnabled = rhiCtx->rhi()->isFeatureSupported(QRhi::PerRenderTargetBlending);
2702 if (rhiCtx->mainPassSampleCount() > 1)
2703 orderIndependentTransparencyEnabled &= rhiCtx->rhi()->isFeatureSupported(QRhi::TexelFetch) && rhiCtx->rhi()->isFeatureSupported(QRhi::SampleVariables);
2704 if (!orderIndependentTransparencyEnabled && warnOnce(OneShotWarning::OitUnsupported))
2705 qCWarning(lcQuick3DRender) <<
"WeightedBlended OIT is requested, but it is not supported.";
2706 }
else if (layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList) {
2707 orderIndependentTransparencyEnabled = rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32UI, QRhiTexture::UsedWithLoadStore);
2708 if (rhiCtx->mainPassSampleCount() > 1)
2709 orderIndependentTransparencyEnabled &= rhiCtx->rhi()->isFeatureSupported(QRhi::SampleVariables);
2710 if (!orderIndependentTransparencyEnabled && warnOnce(OneShotWarning::OitUnsupported))
2711 qCWarning(lcQuick3DRender) <<
"LinkedList OIT is requested, but it is not supported.";
2713 if (layer.oitMethodDirty) {
2714 oitRenderContext.reset();
2715 QSSGRhiResourceRegistry *registry = &QSSGRhiContextPrivate::get(rhiCtx.get())->resourceRegistry();
2716 for (
auto &renderResult : renderResults)
2717 renderResult.reset(registry);
2720 layerPrepResult.flags.setRequiresDepthTexture(requiresDepthTexture);
2722 layerPrepResult.flags.setRequiresNormalTexture(requiresNormalTexture);
2724 layerPrepResult.flags.setRequiresMotionVectorPass(requiresMotionVectorTexture);
2728 if (!layer.firstEffect)
2729 QSSGLayerRenderData::setTonemapFeatures(features, layer.tonemapMode);
2736 if (rhiCtx->rhi()->resourceLimit(QRhi::MaxUniformBufferRange) < REDUCED_MAX_LIGHT_COUNT_THRESHOLD_BYTES) {
2737 features.set(QSSGShaderFeatures::Feature::ReduceMaxNumLights,
true);
2738 static bool notified =
false;
2741 qCDebug(lcQuick3DRender,
"Qt Quick 3D maximum number of lights has been reduced from %d to %d due to the graphics driver's limitations",
2742 QSSG_MAX_NUM_LIGHTS, QSSG_REDUCED_MAX_NUM_LIGHTS);
2747 const auto &lightProbeSettings = layer.lightProbeSettings;
2748 if (layer.lightProbe) {
2749 if (layer.lightProbe->m_format == QSSGRenderTextureFormat::Unknown) {
2752 if (renderer->contextInterface()->rhiContext()->rhi()->isTextureFormatSupported(QRhiTexture::RGBA16F))
2753 layer.lightProbe->m_format = QSSGRenderTextureFormat::RGBA16F;
2755 layer.lightProbe->m_format = QSSGRenderTextureFormat::RGBE8;
2758 if (layer.lightProbe->clearDirty())
2759 wasDataDirty =
true;
2761 features.set(QSSGShaderFeatures::Feature::LightProbe,
true);
2762 features.set(QSSGShaderFeatures::Feature::IblOrientation, !lightProbeSettings.probeOrientation.isIdentity());
2763 if (layer.lightProbe->m_format.format == QSSGRenderTextureFormat::Format::RGBE8)
2764 features.set(QSSGShaderFeatures::Feature::RGBELightProbe,
true);
2766 }
else if (layer.skyMaterial) {
2767 if (layer.skyMaterial->enableIBL) {
2768 features.set(QSSGShaderFeatures::Feature::LightProbe,
true);
2769 features.set(QSSGShaderFeatures::Feature::IblOrientation, !lightProbeSettings.probeOrientation.isIdentity());
2771 layerPrepResult.flags.setRequiresSkyMaterialPass(
true);
2774 const bool forceIblExposureValues = (features.isSet(QSSGShaderFeatures::Feature::LightProbe)
2775 && layer.tonemapMode == QSSGRenderLayer::TonemapMode::Custom);
2776 features.set(QSSGShaderFeatures::Feature::ForceIblExposure, forceIblExposureValues);
2778 frameData.m_ctx->bufferManager()->setLightmapSource(layer.lightmapSource);
2782 version = nodeData->version();
2787 auto &globalTransforms = nodeData->globalTransforms;
2788 auto &globalOpacities = nodeData->globalOpacities;
2789 auto &instanceTransforms = nodeData->instanceTransforms;
2792 QSSGRenderDataHelpers::GlobalStateResultT globalStateResult = QSSGRenderDataHelpers::GlobalStateResult::None;
2794 const bool layerTreeWasDirty = layer.isDirty(QSSGRenderLayer::DirtyFlag::TreeDirty);
2795 layer.clearDirty(QSSGRenderLayer::DirtyFlag::TreeDirty);
2796 if (layerTreeWasDirty) {
2797 wasDataDirty =
true;
2798 layerNodes = nodeData->getLayerNodeView(layer);
2800 using GlobalStateResult = QSSGRenderDataHelpers::GlobalStateResult;
2802 constexpr QSSGRenderDataHelpers::GlobalStateResultT FilterAffectingChanges = GlobalStateResult::ActiveChanged
2803 | GlobalStateResult::TagChanged;
2804 bool sharedStateChanged =
false;
2805 for (
auto &node : layerNodes) {
2806 const auto result = QSSGRenderDataHelpers::updateGlobalNodeState(node, version);
2807 globalStateResult |= result;
2811 const bool affectsFilter = ((result & FilterAffectingChanges) != 0);
2812 const bool isShared = node->getGlobalState(QSSGRenderNode::GlobalState::Imported);
2813 sharedStateChanged |= (affectsFilter && isShared);
2816 if (sharedStateChanged)
2817 nodeData->bumpStateGeneration();
2819 bool transformAndOpacityDirty =
false;
2820 for (
auto &node : layerNodes)
2821 transformAndOpacityDirty |= QSSGRenderDataHelpers::calcGlobalNodeData<QSSGRenderDataHelpers::Strategy::Update>(node, version, globalTransforms, globalOpacities);
2824 if (transformAndOpacityDirty) {
2825 for (
const auto &node : layerNodes)
2826 wasDataDirty |= QSSGRenderDataHelpers::calcInstanceTransforms(node, version, globalTransforms, instanceTransforms);
2829 wasDataDirty |= transformAndOpacityDirty;
2836 const bool viewportVisibilityDirty = layer.isDirty(QSSGRenderLayer::DirtyFlag::VisibilityDirty);
2837 layer.clearDirty(QSSGRenderLayer::DirtyFlag::VisibilityDirty);
2838 if (viewportVisibilityDirty)
2839 wasDataDirty =
true;
2844 const bool hasExplicitCamera = (layer.explicitCameras.size() != 0);
2845 bool cameraLayerMaskDirty =
false;
2846 quint32 layerMask = QSSGRenderCamera::LayerMaskAll;
2847 if (hasExplicitCamera) {
2848 QSSGRenderCamera *explicitCamera = layer.explicitCameras[0];
2851 layerMask = explicitCamera->tag.value() | QSSGRenderCamera::ReservedLayerMask;
2852 cameraLayerMaskDirty = explicitCamera->isDirty(QSSGRenderCamera::DirtyFlag::LayerMaskDirty);
2853 explicitCamera->clearDirty(QSSGRenderCamera::DirtyFlag::LayerMaskDirty);
2857 const bool sharedStateDirty = (stateGeneration != nodeData->stateGeneration());
2858 stateGeneration = nodeData->stateGeneration();
2860 const bool restatNodes = (layerTreeWasDirty
2861 || (globalStateResult & (QSSGRenderDataHelpers::GlobalStateResult::ActiveChanged | QSSGRenderDataHelpers::GlobalStateResult::TagChanged))
2862 || cameraLayerMaskDirty
2863 || sharedStateDirty);
2866 updateFilteredLayerNodes(layerMask);
2872 QSSGRenderCamera::Configuration cameraConfig { renderer->dpr(), layer.isSsaaEnabled() ? layer.ssaaMultiplier : 1.0f };
2873 renderedCameras.clear();
2874 if (!layer.explicitCameras.isEmpty()) {
2875 for (QSSGRenderCamera *cam : std::as_const(layer.explicitCameras)) {
2877 if (cam->getGlobalState(QSSGRenderCamera::GlobalState::Active)) {
2878 const bool computeFrustumSucceeded = cam->calculateProjection(theViewport, cameraConfig);
2879 if (Q_LIKELY(computeFrustumSucceeded))
2880 renderedCameras.append(cam);
2882 qCCritical(INTERNAL_ERROR,
"Failed to calculate camera frustum");
2886 }
else if (QSSG_GUARD_X(layer.viewCount == 1,
"Multiview rendering requires explicit cameras to be set!.")) {
2891 for (
auto iter = camerasView.begin(); renderedCameras.isEmpty() && iter != camerasView.end(); iter++) {
2892 QSSGRenderCamera *theCamera = *iter;
2893 if (theCamera->getGlobalState(QSSGRenderCamera::GlobalState::Active)) {
2894 const bool computeFrustumSucceeded = theCamera->calculateProjection(theViewport, cameraConfig);
2895 if (Q_LIKELY(computeFrustumSucceeded))
2896 renderedCameras.append(theCamera);
2898 qCCritical(INTERNAL_ERROR,
"Failed to calculate camera frustum");
2906 if (renderedCameras.size() > 0 && (renderedCameras[0]->layerMask & QSSGRenderCamera::LayerMaskUserAll) != QSSGRenderCamera::LayerMaskUserAll) {
2907 if (warnOnce(OneShotWarning::NonExplicitCameraWithLayerMask)) {
2908 qWarning() <<
"Scenes with non-explicit cameras with a layer detected!"
2909 " Set the camera explicitly to avoid unnecessary evaluation of scene nodes!";
2913 layerMask = renderedCameras[0]->layerMask;
2914 updateFilteredLayerNodes(layerMask);
2918 float meshLodThreshold = 1.0f;
2919 if (!renderedCameras.isEmpty())
2920 meshLodThreshold = renderedCameras[0]->levelOfDetailPixelThreshold / theViewport.width();
2922 layer.renderedCamerasMutex.lock();
2923 layer.renderedCameras = renderedCameras;
2924 layer.renderedCamerasMutex.unlock();
2927 const QSSGRenderCameraDataList &renderCameraData = getCachedCameraDatas();
2928 modelData->updateModelData(modelsView, renderer, renderCameraData);
2931 item2DData->updateItem2DData(item2DsView, renderer, renderCameraData);
2934 prepareResourceLoaders();
2937 updateDirtySkeletons(*
this, modelsView);
2940 int directionalLightsCount = 0;
2941 int positionalLightsCount = 0;
2942 const int maxLightCount = effectiveMaxLightCount(features);
2943 const int maxDirectionalLights = effectiveMaxDirectionalLightCount(features);
2944 QSSGShaderLightList renderableLights;
2945 int shadowMapCount = 0;
2946 bool hasScopedLights =
false;
2952 auto it = std::make_reverse_iterator(lightsView.end());
2953 const auto end = it + qMin(maxLightCount, lightsView.size());
2954 for (; it != end; ++it) {
2955 QSSGRenderLight *renderLight = (*it);
2956 QMatrix4x4 renderLightTransform = getGlobalTransform(*renderLight);
2957 if (renderLight->type == QSSGRenderGraphObject::Type::DirectionalLight)
2958 directionalLightsCount++;
2960 positionalLightsCount++;
2962 if (positionalLightsCount > maxLightCount)
2964 if (directionalLightsCount > maxDirectionalLights)
2968 hasScopedLights |= (renderLight->m_scope !=
nullptr);
2969 const bool castShadows = renderLight->m_castShadow && !renderLight->m_fullyBaked;
2970 shadowMapCount +=
int(castShadows);
2971 const auto &direction = renderLight->getScalingCorrectDirection(renderLightTransform);
2972 renderableLights.push_back(QSSGShaderLight{ renderLight, castShadows, direction });
2976 if (positionalLightsCount > maxLightCount && warnOnce(OneShotWarning::TooManyLights))
2977 qWarning(
"Too many lights in scene, maximum is %d", maxLightCount);
2979 if (directionalLightsCount > maxDirectionalLights && warnOnce(OneShotWarning::TooManyDirectionalLights))
2980 qWarning(
"Too many directional lights in scene, maximum is %d", maxDirectionalLights);
2982 if (shadowMapCount > 0) {
2983 requestShadowMapManager();
2984 layerPrepResult.flags.setRequiresShadowMapPass(
true);
2989 features.set(QSSGShaderFeatures::Feature::Ssm,
true);
2990 shadowMapManager->addShadowMaps(renderableLights);
2991 }
else if (shadowMapManager) {
2993 shadowMapManager->releaseCachedResources();
2999 QSSG_ASSERT(globalLights.isEmpty(), globalLights.clear());
3000 if (hasScopedLights) {
3001 for (
const auto &shaderLight : std::as_const(renderableLights)) {
3002 if (!shaderLight.light->m_scope)
3003 globalLights.push_back(shaderLight);
3006 const auto prepareLightsWithScopedLights = [&renderableLights,
this](QVector<QSSGRenderableNodeEntry> &renderableNodes) {
3007 for (qint32 idx = 0, end = renderableNodes.size(); idx < end; ++idx) {
3008 QSSGRenderableNodeEntry &theNodeEntry(renderableNodes[idx]);
3009 QSSGShaderLightList filteredLights;
3010 for (
const auto &light : std::as_const(renderableLights)) {
3011 if (light.light->m_scope && !scopeLight(theNodeEntry.node, light.light->m_scope))
3013 filteredLights.push_back(light);
3016 if (filteredLights.isEmpty()) {
3017 theNodeEntry.lights = QSSGDataView(globalLights);
3022 auto customLightList = RENDER_FRAME_NEW_BUFFER<QSSGShaderLight>(*renderer->contextInterface(), filteredLights.size());
3023 std::copy(filteredLights.cbegin(), filteredLights.cend(), customLightList.begin());
3024 theNodeEntry.lights = customLightList;
3029 prepareLightsWithScopedLights(renderableModels);
3030 prepareLightsWithScopedLights(renderableParticles);
3032 globalLights = renderableLights;
3034 const auto prepareLights = [
this](QVector<QSSGRenderableNodeEntry> &renderableNodes) {
3035 for (qint32 idx = 0, end = renderableNodes.size(); idx < end; ++idx) {
3036 QSSGRenderableNodeEntry &theNodeEntry(renderableNodes[idx]);
3037 theNodeEntry.lights = QSSGDataView(globalLights);
3041 prepareLights(renderableModels);
3042 prepareLights(renderableParticles);
3048 Q_STATIC_ASSERT(USERPASSES == size_t(QSSGRenderLayer::RenderExtensionStage::Count));
3049 for (size_t i = 0; i != size_t(QSSGRenderLayer::RenderExtensionStage::Count); ++i) {
3050 const auto &renderExtensions = layer.renderExtensions[i];
3051 auto &userPass = userPasses[i];
3052 for (
auto rit = renderExtensions.crbegin(), rend = renderExtensions.crend(); rit != rend; ++rit) {
3053 if ((*rit)->prepareData(frameData)) {
3055 userPass.extensions.push_back(*rit);
3063 const auto &userRenderPassManager = requestUserRenderPassManager();
3064 userRenderPassManager->updateUserPassOrder(layerTreeWasDirty);
3065 const bool willRender = !renderedCameras.isEmpty() && layerPrepResult.isLayerVisible();
3066 userRenderPassManager->selectPassesForFrame(*renderer->contextInterface()->bufferManager(), willRender,
3067 earlyUserPasses.userPasses, userRenderPasses.userPasses);
3072 const bool computeSupported = rhiCtx->rhi()->isFeatureSupported(QRhi::Compute);
3073 for (
const auto *userPass : std::as_const(userRenderPasses.userPasses)) {
3074 if (!computeSupported || userPass->type != QSSGRenderGraphObject::Type::ComputePass)
3076 const auto *computePass =
static_cast<
const QSSGRenderComputePass *>(userPass);
3077 if (!computePass->willDispatch())
3079 const auto &identifiers = computePass->computeShader.identifiers;
3080 if (identifiers.contains(QByteArrayLiteral(
"SCREEN_TEXTURE")))
3081 layerPrepResult.flags.setRequiresScreenTexture(
true);
3082 if (identifiers.contains(QByteArrayLiteral(
"SCREEN_MIP_TEXTURE"))) {
3083 layerPrepResult.flags.setRequiresScreenTexture(
true);
3084 layerPrepResult.flags.setRequiresMipmapsForScreenTexture(
true);
3086 if (identifiers.contains(QByteArrayLiteral(
"DEPTH_TEXTURE")))
3087 layerPrepResult.flags.setRequiresDepthTexture(
true);
3088 if (identifiers.contains(QByteArrayLiteral(
"AO_TEXTURE"))) {
3089 layerPrepResult.flags.setRequiresDepthTexture(
true);
3090 layerPrepResult.flags.setRequiresSsaoPass(
true);
3092 if (computePass->computeShader.needsNormalTexture)
3093 layerPrepResult.flags.setRequiresNormalTexture(
true);
3096 auto &opaqueObjects = opaqueObjectStore[0];
3097 auto &transparentObjects = transparentObjectStore[0];
3098 auto &screenTextureObjects = screenTextureObjectStore[0];
3100 if (!renderedCameras.isEmpty()) {
3101 wasDirty |= prepareModelsForRender(*renderer->contextInterface(), renderableModels, layerPrepResult.flags, renderedCameras, getCachedCameraDatas(), modelContexts, opaqueObjects, transparentObjects, screenTextureObjects, meshLodThreshold);
3102 if (particlesEnabled) {
3103 const auto &cameraDatas = getCachedCameraDatas();
3104 wasDirty |= prepareParticlesForRender(renderableParticles, cameraDatas[0], layerPrepResult.flags);
3107 wasDirty |= (item2DsView.size() != 0);
3109 if (orderIndependentTransparencyEnabled) {
3111 if (transparentObjects.size() > 0 && !layerPrepResult.flags.hasCustomBlendMode()) {
3112 if (layer.oitMethod != QSSGRenderLayer::OITMethod::None) {
3113 if (rhiCtx->mainPassSampleCount() > 1)
3114 layerPrepResult.flags.setRequiresDepthTextureMS(
true);
3116 layerPrepResult.flags.setRequiresDepthTexture(
true);
3119 orderIndependentTransparencyEnabled =
false;
3120 if (warnOnce(OneShotWarning::OitInvalidBlendMode)) {
3121 qCWarning(lcQuick3DRender) <<
"Order Independent Transparency requested, but disabled due to invalid blend modes.";
3122 qCWarning(lcQuick3DRender) <<
"Use SourceOver blend mode for Order Independent Transparency.";
3126 layer.oitMethodDirty =
false;
3128 prepareReflectionProbesForRender();
3130 wasDirty = wasDirty || wasDataDirty;
3131 layerPrepResult.flags.setWasDirty(wasDirty);
3132 layerPrepResult.flags.setLayerDataDirty(wasDataDirty);
3135 const bool animating = wasDirty;
3137 layer.progAAPassIndex = 0;
3139 const bool progressiveAA = layer.isProgressiveAAEnabled() && !animating;
3140 layer.progressiveAAIsActive = progressiveAA;
3141 const bool temporalAA = layer.isTemporalAAEnabled() && !progressiveAA;
3143 layer.temporalAAIsActive = temporalAA;
3145 QVector2D vertexOffsetsAA;
3147 if (progressiveAA && layer.progAAPassIndex > 0 && layer.progAAPassIndex < quint32(layer.antialiasingQuality)) {
3148 int idx = layer.progAAPassIndex - 1;
3149 vertexOffsetsAA = s_ProgressiveAAVertexOffsets[idx] / QVector2D{
float(theViewport.width()/2.0),
float(theViewport.height()/2.0) };
3153 if (layer.temporalAAMode == QSSGRenderLayer::TAAMode::MotionVector && layer.tempAAPassIndex > 0) {
3154 if (layer.tempAAPassIndex >= quint32(MAX_AA_LEVELS) + 1)
3155 layer.tempAAPassIndex = 1;
3156 int idx = layer.tempAAPassIndex - 1;
3157 vertexOffsetsAA = s_ProgressiveAAVertexOffsets[idx] / QVector2D{
float(theViewport.width()/2.0),
float(theViewport.height()/2.0) };
3158 layer.currentAndLastJitter = QVector4D(vertexOffsetsAA, layer.currentAndLastJitter.x(), layer.currentAndLastJitter.y());
3159 layerPrepResult.flags.setRequiresMotionVectorPass(
true);
3160 layerPrepResult.flags.setRequiresDepthTexture(
true);
3162 const int t = 1 - 2 * (layer.tempAAPassIndex % 2);
3163 const float f = t * layer.temporalAAStrength;
3164 vertexOffsetsAA = { f /
float(theViewport.width()/2.0), f /
float(theViewport.height()/2.0) };
3168 if (!renderedCameras.isEmpty()) {
3169 if (temporalAA || progressiveAA ) {
3170 QMatrix4x4 offsetProjection = renderedCameras[0]->projection;
3171 QMatrix4x4 invProjection = renderedCameras[0]->projection.inverted();
3172 if (renderedCameras[0]->type == QSSGRenderCamera::Type::OrthographicCamera) {
3173 offsetProjection(0, 3) -= vertexOffsetsAA.x();
3174 offsetProjection(1, 3) -= vertexOffsetsAA.y();
3175 }
else if (renderedCameras[0]->type == QSSGRenderCamera::Type::PerspectiveCamera) {
3176 offsetProjection(0, 2) += vertexOffsetsAA.x();
3177 offsetProjection(1, 2) += vertexOffsetsAA.y();
3179 for (
auto &modelContext : std::as_const(modelContexts)) {
3180 for (
int mvpIdx = 0; mvpIdx < renderedCameras.count(); ++mvpIdx)
3181 modelContext->modelViewProjections[mvpIdx] = offsetProjection * invProjection * modelContext->modelViewProjections[mvpIdx];
3186 const bool hasItem2Ds = (item2DsView.size() > 0);
3187 const bool layerEnableDepthTest = layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthTest);
3188 const bool layerEnabledDepthPrePass = layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthPrePass);
3189 const bool depthTestEnableDefault = layerEnableDepthTest && (!opaqueObjects.isEmpty() || depthPrepassObjectsState || hasDepthWriteObjects);
3190 const bool zPrePassForced = (depthPrepassObjectsState != 0);
3191 zPrePassActive = zPrePassForced || (layerEnabledDepthPrePass && layerEnableDepthTest && (hasDepthWriteObjects || hasItem2Ds));
3192 const bool depthWriteEnableDefault = depthTestEnableDefault && (!layerEnabledDepthPrePass || !zPrePassActive);
3194 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::DepthTestEnabled, depthTestEnableDefault);
3195 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::DepthWriteEnabled, depthWriteEnableDefault);
3199 layerPrepResult.setState(QSSGLayerRenderPreparationResult::State::Done);
3202 QSSG_ASSERT(activePasses.isEmpty(), activePasses.clear());
3203 if (earlyUserPasses.hasData())
3204 activePasses.push_back(&earlyUserPasses);
3209 if (layerPrepResult.flags.requiresDepthTexture())
3210 activePasses.push_back(&depthMapPass);
3211 if (layerPrepResult.flags.requiresDepthTextureMS())
3212 activePasses.push_back(&depthMapPassMS);
3214 if (layerPrepResult.flags.requiresNormalTexture())
3215 activePasses.push_back(&normalPass);
3218 if (layerPrepResult.flags.requiresSsaoPass())
3219 activePasses.push_back(&ssaoMapPass);
3222 if (layerPrepResult.flags.requiresShadowMapPass())
3223 activePasses.push_back(&shadowMapPass);
3225 if (zPrePassActive && !disableMainPasses)
3226 activePasses.push_back(&zPrePassPass);
3229 if (layerPrepResult.flags.requiresScreenTexture())
3230 activePasses.push_back(&screenMapPass);
3233 if (layerPrepResult.flags.requiresSkyMaterialPass())
3234 activePasses.push_back(&skyMaterialPass);
3237 if (reflectionProbesView.size() != 0)
3238 activePasses.push_back(&reflectionMapPass);
3240 auto &textureExtensionPass = userPasses[size_t(QSSGRenderLayer::RenderExtensionStage::TextureProviders)];
3241 if (textureExtensionPass.hasData())
3242 activePasses.push_back(&textureExtensionPass);
3244 auto &underlayPass = userPasses[size_t(QSSGRenderLayer::RenderExtensionStage::Underlay)];
3245 if (underlayPass.hasData())
3246 activePasses.push_back(&underlayPass);
3249 if (userRenderPasses.hasData())
3250 activePasses.push_back(&userRenderPasses);
3252 const bool hasOpaqueObjects = (opaqueObjects.size() > 0);
3254 if (hasOpaqueObjects && !disableMainPasses)
3255 activePasses.push_back(&opaquePass);
3258 if (layerPrepResult.flags.requiresMotionVectorPass())
3259 activePasses.push_back(&motionVectorMapPass);
3263 if (renderer->contextInterface()->rhiContext()->rhi()->isFeatureSupported(QRhi::TexelFetch)) {
3264 if (layer.background == QSSGRenderLayer::Background::SkyBoxCubeMap && layer.skyBoxCubeMap && !disableMainPasses)
3265 activePasses.push_back(&skyboxCubeMapPass);
3266 else if (layer.background == QSSGRenderLayer::Background::SkyBox && layer.lightProbe && !disableMainPasses)
3267 activePasses.push_back(&skyboxPass);
3268 else if (layer.background == QSSGRenderLayer::Background::SkyMaterial && layer.skyMaterial && !disableMainPasses) {
3269 if (layer.skyMaterial->skyboxMode != QSSGRenderSkyMaterial::SkyboxMode::Cubemap)
3270 activePasses.push_back(&skyMaterialBackgroundPass);
3272 activePasses.push_back(&skyboxPass);
3276 if (hasItem2Ds && !disableMainPasses)
3277 activePasses.push_back(&item2DPass);
3279 if (layerPrepResult.flags.requiresScreenTexture())
3280 activePasses.push_back(&reflectionPass);
3283 if ((transparentObjects.size() > 0 || (!layerEnableDepthTest && hasOpaqueObjects)) && !disableMainPasses) {
3284 if (orderIndependentTransparencyEnabled) {
3285 activePasses.push_back(&oitRenderPass);
3286 activePasses.push_back(&oitCompositePass);
3287 oitRenderPass.setMethod(layer.oitMethod);
3288 oitCompositePass.setMethod(layer.oitMethod);
3290 activePasses.push_back(&transparentPass);
3294 auto &overlayPass = userPasses[size_t(QSSGRenderLayer::RenderExtensionStage::Overlay)];
3295 if (overlayPass.hasData())
3296 activePasses.push_back(&overlayPass);
3298 if (layer.gridEnabled)
3299 activePasses.push_back(&infiniteGridPass);
3301 if (
const auto &dbgDrawSystem = renderer->contextInterface()->debugDrawSystem(); dbgDrawSystem && dbgDrawSystem->isEnabled() && !disableMainPasses)
3302 activePasses.push_back(&debugDrawPass);
3813bool QSSGLayerRenderData::prepareInstancing(QSSGRhiContext *rhiCtx,
3814 QSSGSubsetRenderable *renderable,
3815 const QVector3D &cameraDirection,
3816 const QVector3D &cameraPosition,
3819 const QSSGLayerRenderData &layerData)
3821 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
3822 auto &modelContext = renderable->modelContext;
3823 auto &instanceBuffer = renderable->instanceBuffer;
3824 if (!modelContext.model.usesInstanceBuffer() || instanceBuffer)
3825 return instanceBuffer;
3826 const InstanceTransforms instanceTransforms = layerData.getInstanceTransforms(modelContext.model);
3827 auto *table = modelContext.model.instanceTable;
3828 bool usesLod = minThreshold >= 0 || maxThreshold >= 0;
3831 modelContext.model.instanceLodCount = -1;
3834 const bool perModel = usesLod || table->isDepthSortingEnabled();
3836 rhiCtxD->releaseModelInstanceCopy(&modelContext.model);
3837 QSSGRhiInstanceBufferData &instanceData(perModel ? rhiCtxD->instanceBufferData(&modelContext.model) : rhiCtxD->instanceBufferData(table));
3838 quint32 instanceBufferSize = table->dataSize();
3840 bool sortingChanged = table->isDepthSortingEnabled() != instanceData.sorting;
3841 bool cameraDirectionChanged = !qFuzzyCompare(instanceData.sortedCameraDirection, cameraDirection);
3842 bool cameraPositionChanged = !qFuzzyCompare(instanceData.cameraPosition, cameraPosition);
3843 const QMatrix4x4 &globalInstanceTransform = instanceTransforms.global;
3845 const QVector3D localInstanceTranslation = instanceTransforms.local.column(3).toVector3D();
3848 bool transformChanged = instanceData.globalInstanceTransform != globalInstanceTransform
3849 || instanceData.localInstanceTranslation != localInstanceTranslation;
3850 bool updateInstanceBuffer = table != instanceData.table
3851 || table->generation() != instanceData.tableGeneration
3853 || ((cameraDirectionChanged || transformChanged) && table->isDepthSortingEnabled());
3854 bool instanceBufferSizeChanged = instanceData.buffer && instanceBufferSize != instanceData.buffer->size();
3858 bool rangeChanged = perModel && (instanceData.lodMin != minThreshold || instanceData.lodMax != maxThreshold);
3859 bool updateForLod = (cameraPositionChanged || instanceBufferSizeChanged || transformChanged || rangeChanged) && usesLod;
3861 if (rangeChanged && !usesLod)
3862 updateInstanceBuffer =
true;
3865 if (usesLod && modelContext.model.instanceLodCount < 0)
3866 updateForLod =
true;
3867 if (sortingChanged && !table->isDepthSortingEnabled()) {
3868 instanceData.sortedData.clear();
3869 instanceData.sortData.clear();
3870 instanceData.sortedCameraDirection = {};
3872 instanceData.sorting = table->isDepthSortingEnabled();
3873 if (instanceData.buffer && instanceData.buffer->size() < instanceBufferSize) {
3874 updateInstanceBuffer =
true;
3876 instanceData.buffer->setSize(instanceBufferSize);
3877 instanceData.buffer->create();
3879 if (!instanceData.buffer) {
3881 updateInstanceBuffer =
true;
3882 instanceData.buffer = rhiCtx->rhi()->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::VertexBuffer, instanceBufferSize);
3883 instanceData.buffer->create();
3887 if (updateInstanceBuffer && usesLod)
3888 updateForLod =
true;
3889 if (updateInstanceBuffer || updateForLod) {
3890 Q_ASSERT(table->stride() ==
sizeof(QSSGRenderInstanceTableEntry));
3891 const void *data =
nullptr;
3892 if (table->isDepthSortingEnabled()) {
3893 if (updateInstanceBuffer) {
3894 instanceData.sortedData.resize(table->dataSize());
3895 sortInstances(instanceEntries(instanceData.sortedData),
3896 instanceData.sortData,
3897 instanceEntries(table->constData(), table->dataSize(), table->count()),
3898 globalInstanceTransform,
3899 localInstanceTranslation,
3902 data = instanceData.sortedData.constData();
3903 instanceData.sortedCameraDirection = cameraDirection;
3905 data = table->constData();
3909 modelContext.model.instanceLodCount = cullLodInstances(instanceData,
3911 globalInstanceTransform,
3912 localInstanceTranslation,
3916 data = instanceData.lodData.constData();
3920 if (!modelContext.model.instanceLodCount)
3921 instanceData.lodData.clear();
3923 instanceBufferSize = modelContext.model.instanceLodCount *
sizeof(QSSGRenderInstanceTableEntry);
3926 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
3927 rub->updateDynamicBuffer(instanceData.buffer, 0, instanceBufferSize, data);
3928 rhiCtx->commandBuffer()->resourceUpdate(rub);
3931 qWarning() <<
"NO DATA IN INSTANCE TABLE";
3935 instanceData.instanceIndicesDirty =
true;
3936 ++instanceData.generation;
3938 instanceData.lodInstanceIndices.clear();
3939 instanceData.table = table;
3940 instanceData.tableGeneration = table->generation();
3941 instanceData.cameraPosition = cameraPosition;
3942 instanceData.globalInstanceTransform = globalInstanceTransform;
3943 instanceData.localInstanceTranslation = localInstanceTranslation;
3944 instanceData.lodMin = minThreshold;
3945 instanceData.lodMax = maxThreshold;
3947 instanceBuffer = instanceData.buffer;
3948 if (instanceBuffer && usesInstanceIndex(renderable->material))
3949 renderable->instanceIndexBuffer = prepareInstanceIndices(rhiCtx, instanceData, *table,
3951 return instanceBuffer;
3993void QSSGLayerRenderData::prepareAutoLodInstancing(QSSGRhiContext *rhiCtx,
3994 QSSGSubsetRenderable *renderable,
3995 const QSSGLayerRenderData &layerData)
3997 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
3998 auto &modelContext = renderable->modelContext;
3999 if (!modelContext.model.instancing() || !renderable->usesAutoLod)
4002 auto *table = modelContext.model.instanceTable;
4003 const QSSGRenderCameraDataList &cameraDatas = *layerData.renderedCameraData;
4004 const QVector3D &cameraPosition = cameraDatas[0].position;
4005 const QVector3D cameraDirection = cameraDatas[0].direction.normalized();
4006 const bool orthographic = layerData.renderedCameras[0]->type == QSSGRenderGraphObject::Type::OrthographicCamera;
4009 const QSSGClippingFrustum *frustum = (cameraDatas.size() == 1 && cameraDatas[0].clippingFrustum.has_value())
4010 ? &cameraDatas[0].clippingFrustum.value()
4013 QSSGRhiInstanceBufferData &instanceData = rhiCtxD->instanceBufferData(&modelContext.model);
4014 QSSGRhiInstanceBufferData::SubsetLodData &subsetLod = instanceData.subsetLodData[{ &renderable->subset, &layerData.layer }];
4019 const bool ranged = renderable->instancingLodMin >= 0.0f || renderable->instancingLodMax >= 0.0f;
4021 const QSSGRhiInstancePlacement placement = instancePlacement(layerData, *renderable);
4022 const bool projectionChanged = subsetLod.orthographic != orthographic;
4025 const bool cullingChanged = subsetLod.culled != (frustum !=
nullptr);
4026 const bool vpChanged = frustum && subsetLod.cameraViewProjection != cameraDatas[0].viewProjection;
4027 const bool tableChanged = table != subsetLod.table || table->generation() != subsetLod.tableGeneration;
4028 const int expectedLevels = renderable->autoLodLevelCount;
4029 const bool levelsChanged = subsetLod.levelCount != expectedLevels;
4033 decltype(subsetLod.lodDistancesSq) lodDistancesSq;
4034 const auto &lods = renderable->subset.lods;
4035 const int numSwitches = qMin(
int(lods.size()), expectedLevels - 1);
4036 for (
int i = 0; i < numSwitches; ++i) {
4037 const float d = lods[i].distance * renderable->autoLodThresholdFactor;
4038 lodDistancesSq.push_back(d * d);
4040 const bool distancesChanged = subsetLod.lodDistancesSq != lodDistancesSq;
4041 const bool placementChanged = subsetLod.placement != placement;
4044 const bool sourceChanged = subsetLod.sourceGeneration != instanceData.generation;
4047 const bool cameraMoved = !orthographic
4048 && (!qFuzzyCompare(subsetLod.cameraPosition, cameraPosition)
4049 || !qFuzzyCompare(subsetLod.cameraDirection, cameraDirection));
4050 const bool tintChanged = subsetLod.tinted != renderable->autoLodTint;
4052 if (cameraMoved || projectionChanged || cullingChanged || vpChanged || tableChanged || levelsChanged
4053 || distancesChanged || placementChanged || sourceChanged || tintChanged || !subsetLod.valid) {
4054 const auto sourceInstances = ranged
4055 ? instanceEntries(instanceData.lodData.constData(), instanceData.lodData.size(), modelContext.model.instanceLodCount)
4056 : instanceEntries(table->constData(), table->dataSize(), table->count());
4059 const QSpan<
const qint32> sourceInstanceIndices = ranged ? QSpan<
const qint32>(instanceData.lodInstanceIndices) : QSpan<
const qint32>();
4060 distributeInstancesToLods(subsetLod, rhiCtxD->m_autoLodLevelOfInstance, sourceInstances, sourceInstanceIndices, placement,
4061 cameraPosition, cameraDirection, orthographic, lodDistancesSq, frustum,
4062 renderable->autoLodTint);
4067 constexpr quint32 entrySize =
sizeof(QSSGRenderInstanceTableEntry);
4068 const quint32 dataSize = quint32(subsetLod.data.size());
4069 const quint32 needed = qMax(dataSize, entrySize);
4070 const quint32 sourceSize = qMax(quint32(sourceInstances.size()) * entrySize, needed);
4071 const quint32 currentSize = subsetLod.buffer ? subsetLod.buffer->size() : 0;
4072 if (currentSize < needed || currentSize > 4 * needed + 65536) {
4073 const quint32 bufferSize = qMin(needed + needed / 2, sourceSize);
4074 if (!subsetLod.buffer)
4075 subsetLod.buffer = rhiCtx->rhi()->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::VertexBuffer, bufferSize);
4077 subsetLod.buffer->setSize(bufferSize);
4078 if (!subsetLod.buffer->create()) {
4079 qWarning(
"Failed to create the instance buffer of the automatic level of detail");
4082 delete subsetLod.buffer;
4083 subsetLod.buffer =
nullptr;
4084 subsetLod.valid =
false;
4085 renderable->autoLodBuffer =
nullptr;
4086 renderable->autoLodInstanceCounts = {};
4091 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
4092 rub->updateDynamicBuffer(subsetLod.buffer, 0, dataSize, subsetLod.data.constData());
4093 rhiCtx->commandBuffer()->resourceUpdate(rub);
4096 subsetLod.cameraPosition = cameraPosition;
4097 subsetLod.cameraDirection = cameraDirection;
4098 subsetLod.cameraViewProjection = frustum ? cameraDatas[0].viewProjection : QMatrix4x4{};
4099 subsetLod.culled = frustum !=
nullptr;
4100 subsetLod.orthographic = orthographic;
4101 subsetLod.table = table;
4102 subsetLod.tableGeneration = table->generation();
4103 subsetLod.lodDistancesSq = lodDistancesSq;
4104 subsetLod.sourceGeneration = instanceData.generation;
4105 subsetLod.placement = placement;
4106 subsetLod.tinted = renderable->autoLodTint;
4107 subsetLod.valid =
true;
4111 renderable->autoLodBuffer = subsetLod.buffer;
4112 renderable->autoLodInstanceCounts = subsetLod.counts;
4113 if (usesInstanceIndex(renderable->material))
4114 renderable->autoLodInstanceIndexBuffer = prepareAutoLodInstanceIndices(rhiCtx, subsetLod);