52void QSSGParticleRenderer::updateUniformsForParticles(
const QSSGLayerRenderData &inData,
53 QSSGRhiShaderPipeline &shaders,
54 QSSGRhiContext *rhiCtx,
56 QSSGParticlesRenderable &renderable,
57 const QSSGRenderCameraList &cameras)
59 const QMatrix4x4 clipSpaceCorrMatrix = rhiCtx->rhi()->clipSpaceCorrMatrix();
61 QSSGRhiShaderPipeline::CommonUniformIndices &cui = shaders.commonUniformIndices;
63 const int viewCount = cameras.count();
66 QMatrix4x4 camGlobalTransforms[2] { QMatrix4x4{Qt::Uninitialized}, QMatrix4x4{Qt::Uninitialized} };
68 camGlobalTransforms[0] = inData.getGlobalTransform(*cameras[0]);
70 for (size_t viewIndex = 0; viewIndex != std::size(camGlobalTransforms); ++viewIndex)
71 camGlobalTransforms[viewIndex] = inData.getGlobalTransform(*cameras[viewIndex]);
75 const QMatrix4x4 projection = clipSpaceCorrMatrix * cameras[0]->projection;
76 shaders.setUniform(ubufData,
"qt_projectionMatrix", projection.constData(), 16 *
sizeof(
float), &cui.projectionMatrixIdx);
77 const QMatrix4x4 viewMatrix = camGlobalTransforms[0].inverted();
78 shaders.setUniform(ubufData,
"qt_viewMatrix", viewMatrix.constData(), 16 *
sizeof(
float), &cui.viewMatrixIdx);
80 QVarLengthArray<QMatrix4x4, 2> projectionMatrices(viewCount);
81 QVarLengthArray<QMatrix4x4, 2> viewMatrices(viewCount);
82 for (
int viewIndex = 0; viewIndex < viewCount; ++viewIndex) {
83 projectionMatrices[viewIndex] = clipSpaceCorrMatrix * cameras[viewIndex]->projection;
84 viewMatrices[viewIndex] = camGlobalTransforms[viewIndex].inverted();
86 shaders.setUniformArray(ubufData,
"qt_projectionMatrix", projectionMatrices.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4, &cui.projectionMatrixIdx);
87 shaders.setUniformArray(ubufData,
"qt_viewMatrix", viewMatrices.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4, &cui.viewMatrixIdx);
90 const QMatrix4x4 &modelMatrix = renderable.globalTransform;
91 shaders.setUniform(ubufData,
"qt_modelMatrix", modelMatrix.constData(), 16 *
sizeof(
float), &cui.modelMatrixIdx);
93 const QVector2D camProperties(cameras[0]->clipPlanes);
94 shaders.setUniform(ubufData,
"qt_cameraProperties", &camProperties, 2 *
sizeof(
float), &cui.cameraPropertiesIdx);
96 QVector2D oneOverSize = QVector2D(1.0f, 1.0f);
97 auto &particleBuffer = renderable.particles.m_particleBuffer;
98 const quint32 particlesPerSlice = particleBuffer.particlesPerSlice();
99 oneOverSize = QVector2D(1.0f / particleBuffer.size().width(), 1.0f / particleBuffer.size().height());
100 shaders.setUniform(ubufData,
"qt_oneOverParticleImageSize", &oneOverSize, 2 *
sizeof(
float));
101 shaders.setUniform(ubufData,
"qt_countPerSlice", &particlesPerSlice, 1 *
sizeof(quint32));
104 shaders.setUniform(ubufData,
"qt_opacity", &renderable.opacity, 1 *
sizeof(
float));
106 float blendImages = renderable.particles.m_blendImages ? 1.0f : 0.0f;
107 float imageCount =
float(renderable.particles.m_spriteImageCount);
108 float ooImageCount = 1.0f / imageCount;
110 QVector4D spriteConfig(imageCount, ooImageCount, 0.0f, blendImages);
111 shaders.setUniform(ubufData,
"qt_spriteConfig", &spriteConfig, 4 *
sizeof(
float));
113 const float billboard = renderable.particles.m_billboard ? 1.0f : 0.0f;
114 shaders.setUniform(ubufData,
"qt_billboard", &billboard, 1 *
sizeof(
float));
117 QVector3D theLightAmbientTotal;
118 bool hasLights = !renderable.particles.m_lights.isEmpty();
122 ParticleLightData lightData;
123 auto &lights = renderable.lights;
124 for (quint32 lightIdx = 0, lightEnd = lights.size();
126 QSSGRenderLight *theLight(lights[lightIdx].light);
128 if (!renderable.particles.m_lights.contains(theLight))
131 const QMatrix4x4 lightGlobalTransform = inData.getGlobalTransform(*theLight);
133 if (theLight->type == QSSGRenderLight::Type::DirectionalLight) {
134 theLightAmbientTotal += theLight->m_diffuseColor * theLight->m_brightness;
135 }
else if (theLight->type == QSSGRenderLight::Type::PointLight && pointLight < 4) {
136 lightData.pointLightColor[pointLight] = QVector4D(theLight->m_diffuseColor * theLight->m_brightness, 1.0f);
137 lightData.pointLightPos[pointLight] = QVector4D(QSSGRenderNode::getGlobalPos(lightGlobalTransform), 1.0f);
138 lightData.pointLightConstantAtt[pointLight] = QSSGUtils::aux::translateConstantAttenuation(theLight->m_constantFade);
139 lightData.pointLightLinearAtt[pointLight] = QSSGUtils::aux::translateLinearAttenuation(theLight->m_linearFade);
140 lightData.pointLightQuadAtt[pointLight] = QSSGUtils::aux::translateQuadraticAttenuation(theLight->m_quadraticFade);
142 }
else if (theLight->type == QSSGRenderLight::Type::SpotLight && spotLight < 4) {
143 lightData.spotLightColor[spotLight] = QVector4D(theLight->m_diffuseColor * theLight->m_brightness, 1.0f);
144 lightData.spotLightPos[spotLight] = QVector4D(QSSGRenderNode::getGlobalPos(lightGlobalTransform), 1.0f);
145 lightData.spotLightDir[spotLight] = QVector4D(lights[lightIdx].direction, 0.0f);
146 lightData.spotLightConstantAtt[spotLight] = QSSGUtils::aux::translateConstantAttenuation(theLight->m_constantFade);
147 lightData.spotLightLinearAtt[spotLight] = QSSGUtils::aux::translateLinearAttenuation(theLight->m_linearFade);
148 lightData.spotLightQuadAtt[spotLight] = QSSGUtils::aux::translateQuadraticAttenuation(theLight->m_quadraticFade);
149 float coneAngle = theLight->m_coneAngle;
151 float innerConeAngle = std::min(theLight->m_innerConeAngle, coneAngle - 0.01f);
152 lightData.spotLightConeAngle[spotLight] = qDegreesToRadians(coneAngle);
153 lightData.spotLightInnerConeAngle[spotLight] = qDegreesToRadians(innerConeAngle);
156 theLightAmbientTotal += theLight->m_ambientColor;
159 int lightOffset = shaders.offsetOfUniform(
"lightData");
160 if (lightOffset >= 0)
161 memcpy(ubufData + lightOffset, &lightData,
sizeof(ParticleLightData));
163 shaders.setUniform(ubufData,
"qt_light_ambient_total", &theLightAmbientTotal, 3 *
sizeof(
float), &cui.light_ambient_totalIdx);
164 int enablePointLights = pointLight > 0 ? 1 : 0;
165 int enableSpotLights = spotLight > 0 ? 1 : 0;
166 shaders.setUniform(ubufData,
"qt_pointLights", &enablePointLights,
sizeof(
int));
167 shaders.setUniform(ubufData,
"qt_spotLights", &enableSpotLights,
sizeof(
int));
170 int segmentCount = particleBuffer.segments();
172 shaders.setUniform(ubufData,
"qt_lineSegmentCount", &segmentCount,
sizeof(
int));
173 float alphaFade = renderable.particles.m_alphaFade;
174 float sizeModifier = renderable.particles.m_sizeModifier;
175 float texcoordScale = renderable.particles.m_texcoordScale;
176 auto image = renderable.firstImage;
177 if (image && image->m_texture.m_texture) {
178 const auto size = image->m_texture.m_texture->pixelSize();
179 texcoordScale *=
float(size.height()) /
float(size.width());
181 shaders.setUniform(ubufData,
"qt_alphaFade", &alphaFade,
sizeof(
float));
182 shaders.setUniform(ubufData,
"qt_sizeModifier", &sizeModifier,
sizeof(
float));
183 shaders.setUniform(ubufData,
"qt_texcoordScale", &texcoordScale,
sizeof(
float));
186#ifdef QSSG_OIT_USE_BUFFERS
187 shaders.setOITImages((QRhiTexture*)inData.oitRenderContext.aBuffer,
188 (QRhiTexture*)inData.oitRenderContext.auxBuffer,
189 (QRhiTexture*)inData.oitRenderContext.counterBuffer);
190 if (inData.oitRenderContext.aBuffer) {
192 const QSSGRhiRenderableTexture *abuf = inData.getRenderResult(QSSGRenderResult::Key::ABufferImage);
193 const QSSGRhiRenderableTexture *aux = inData.getRenderResult(QSSGRenderResult::Key::AuxiliaryImage);
194 const QSSGRhiRenderableTexture *counter = inData.getRenderResult(QSSGRenderResult::Key::CounterImage);
195 shaders.setOITImages(abuf->texture, aux->texture, counter->texture);
198 int abufWidth = RenderHelpers::rhiCalculateABufferSize(inData.layer.oitNodeCount);
199 int listNodeCount = abufWidth * abufWidth;
200 shaders.setUniform(ubufData,
"qt_ABufImageWidth", &abufWidth,
sizeof(
int), &cui.abufImageWidth);
201 shaders.setUniform(ubufData,
"qt_listNodeCount", &listNodeCount,
sizeof(
int), &cui.listNodeCount);
202 int viewSize[2] = {inData.layerPrepResult.textureDimensions().width(), inData.layerPrepResult.textureDimensions().height()};
203 shaders.setUniform(ubufData,
"qt_viewSize", viewSize,
sizeof(
int) * 2, &cui.viewSize);
204 int samples = rhiCtx->mainPassSampleCount();
205 shaders.setUniform(ubufData,
"qt_samples", &samples,
sizeof(
int), &cui.samples);
252 const QSSGParticleBuffer &buffer,
const QSSGRenderParticles &particles,
253 const QVector3D &cameraDirection,
bool animatedParticles)
255 const QMatrix4x4 &modelMatrix = renderData.getGlobalTransform(particles);
256 const QMatrix4x4 &invModelMatrix = modelMatrix.inverted();
257 QVector3D dir = invModelMatrix.map(cameraDirection);
258 QVector3D n = dir.normalized();
259 const auto segments = buffer.segments();
260 auto particleCount = buffer.particleCount();
261 const bool lineParticles = segments > 0;
263 particleCount /= segments;
264 sortData.resize(particleCount);
267 const auto srcParticlePointer = [](
int line,
int segment,
int sc,
int ss,
int pps,
const char *source) ->
const QSSGLineParticle * {
268 int pi = (line * sc + segment) / pps;
269 int i = (line * sc + segment) % pps;
270 const QSSGLineParticle *sp =
reinterpret_cast<
const QSSGLineParticle *>(source + pi * ss);
276 const auto slices = buffer.sliceCount();
277 const auto ss = buffer.sliceStride();
278 const auto pps = buffer.particlesPerSlice();
281 const char *source = buffer.pointer();
282 const char *begin = source;
285 for (i = 0; i < particleCount; i++) {
287 const QSSGLineParticle *lineBegin = srcParticlePointer(i, 0, segments, ss, pps, source);
289 lineData.d = QVector3D::dotProduct(lineBegin->position, n);
290 for (
int j = 1; j < buffer.segments(); j++) {
291 const QSSGLineParticle *p = srcParticlePointer(i, j, segments, ss, pps, source);
292 lineData
.d = qMin(lineData
.d, QVector3D::dotProduct(p->position, n));
296 }
else if (animatedParticles) {
297 for (
int s = 0; s < slices; s++) {
298 const QSSGParticleAnimated *sp =
reinterpret_cast<
const QSSGParticleAnimated *>(source);
299 for (
int p = 0; p < pps && i < particleCount; p++) {
300 *dst = { QVector3D::dotProduct(sp->position, n),
int(
reinterpret_cast<
const char *>(sp) - begin)};
308 for (
int s = 0; s < slices; s++) {
309 const QSSGParticleSimple *sp =
reinterpret_cast<
const QSSGParticleSimple *>(source);
310 for (
int p = 0; p < pps && i < particleCount; p++) {
311 *dst = { QVector3D::dotProduct(sp->position, n),
int(
reinterpret_cast<
const char *>(sp) - begin)};
322 result.resize(buffer.bufferSize());
323 std::sort(sortData.begin(), sortData.end(), [](
const QSSGRhiSortData &a,
const QSSGRhiSortData &b){
327 auto copyParticles = [&](QByteArray &dst,
const QList<QSSGRhiSortData> &data,
const QSSGParticleBuffer &buffer) {
328 const auto slices = buffer.sliceCount();
329 const auto ss = buffer.sliceStride();
330 const auto pps = buffer.particlesPerSlice();
332 char *dest = dst.data();
333 const char *source = buffer.pointer();
337 for (
int s = 0; s < slices; s++) {
338 QSSGLineParticle *dp =
reinterpret_cast<QSSGLineParticle *>(dest);
339 for (
int p = 0; p < pps && i < particleCount; p++) {
340 *dp = *srcParticlePointer(sdata
->indexOrOffset, seg, segments, ss, pps, source);
343 if (seg == segments) {
351 }
else if (animatedParticles) {
352 for (
int s = 0; s < slices; s++) {
353 QSSGParticleAnimated *dp =
reinterpret_cast<QSSGParticleAnimated *>(dest);
354 for (
int p = 0; p < pps && i < particleCount; p++) {
355 *dp = *
reinterpret_cast<
const QSSGParticleAnimated *>(source + sdata
->indexOrOffset);
363 for (
int s = 0; s < slices; s++) {
364 QSSGParticleSimple *dp =
reinterpret_cast<QSSGParticleSimple *>(dest);
365 for (
int p = 0; p < pps && i < particleCount; p++) {
366 *dp = *
reinterpret_cast<
const QSSGParticleSimple *>(source + sdata
->indexOrOffset);
377 copyParticles(result, sortData, buffer);
391void QSSGParticleRenderer::rhiPrepareRenderable(QSSGRhiShaderPipeline &shaderPipeline,
393 QSSGRhiContext *rhiCtx,
394 QSSGRhiGraphicsPipelineState *ps,
395 QSSGParticlesRenderable &renderable,
396 const QSSGLayerRenderData &inData,
397 QRhiRenderPassDescriptor *renderPassDescriptor,
400 QSSGRenderCamera *alteredCamera,
401 QSSGRenderTextureCubeFace cubeFace,
402 QSSGReflectionMapEntry *entry,
405 const void *node = &renderable.particles;
406 const bool needsConversion = !rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32F);
408 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
409 QSSGRhiDrawCallData &dcd = QSSGRhiContextPrivate::get(rhiCtx)->drawCallData({ passKey, node,
nullptr, entry,
411 shaderPipeline.ensureUniformBuffer(&dcd.ubuf);
413 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
414 if (!alteredCamera) {
415 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, inData.renderedCameras);
417 QSSGRenderCameraList cameras({ alteredCamera });
418 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, cameras);
420 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
422 QSSGRhiParticleData &particleData = QSSGRhiContextPrivate::get(rhiCtx)->particleData(&renderable.particles);
423 const QSSGParticleBuffer &particleBuffer = renderable.particles.m_particleBuffer;
424 int particleCount = particleBuffer.particleCount();
425 if (particleData.texture ==
nullptr || particleData.particleCount != particleCount) {
426 QSize size(particleBuffer.size());
427 if (!particleData.texture) {
428 particleData.texture = rhiCtx->rhi()->newTexture(needsConversion ? QRhiTexture::RGBA16F : QRhiTexture::RGBA32F, size);
429 particleData.texture->create();
431 particleData.texture->setPixelSize(size);
432 particleData.texture->create();
434 particleData.particleCount = particleCount;
437 bool sortingChanged = particleData.sorting != renderable.particles.m_depthSorting;
438 if (sortingChanged && !renderable.particles.m_depthSorting) {
439 particleData.sortData.clear();
440 particleData.sortedData.clear();
442 particleData.sorting = renderable.particles.m_depthSorting;
444 QByteArray uploadData;
446 if (renderable.particles.m_depthSorting) {
447 bool animatedParticles = renderable.particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::Animated;
448 if (!alteredCamera) {
449 sortParticles(inData, particleData.sortedData, particleData.sortData, particleBuffer, renderable.particles, inData.renderedCameraData.value()[0].direction, animatedParticles);
451 const QMatrix4x4 globalTransform = inData.getGlobalTransform(*alteredCamera);
452 sortParticles(inData, particleData.sortedData, particleData.sortData, particleBuffer, renderable.particles, QSSGRenderNode::getScalingCorrectDirection(globalTransform), animatedParticles);
454 uploadData = convertParticleData(particleData.convertData, particleData.sortedData, needsConversion);
456 uploadData = convertParticleData(particleData.convertData, particleBuffer.data(), needsConversion);
459 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
460 QRhiTextureSubresourceUploadDescription upload;
461 upload.setData(uploadData);
462 QRhiTextureUploadDescription uploadDesc(QRhiTextureUploadEntry(0, 0, upload));
463 rub->uploadTexture(particleData.texture, uploadDesc);
464 rhiCtx->commandBuffer()->resourceUpdate(rub);
466 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
467 ia.topology = QRhiGraphicsPipeline::TriangleStrip;
468 ia.inputLayout = QRhiVertexInputLayout();
471 ps->samples = samples;
472 ps->viewCount = viewCount;
473 ps->cullMode = QRhiGraphicsPipeline::None;
475 if (inData.orderIndependentTransparencyEnabled ==
false) {
476 if (renderable.renderableFlags.hasTransparency())
477 fillTargetBlend(ps->targetBlend[0], renderable.particles.m_blendMode);
479 ps->targetBlend[0] = QRhiGraphicsPipeline::TargetBlend();
482 QSSGRhiShaderResourceBindingList bindings;
483 bindings.addUniformBuffer(0, VISIBILITY_ALL, dcd.ubuf, 0, shaderPipeline.ub0Size());
487 QSSGRenderableImage *renderableImage = renderable.firstImage;
489 int samplerBinding = shaderPipeline.bindingForTexture(
"qt_sprite");
490 if (samplerBinding >= 0) {
491 QRhiTexture *texture = renderableImage ? renderableImage->m_texture.m_texture :
nullptr;
492 if (samplerBinding >= 0 && texture) {
493 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
494 QRhiSampler *sampler = rhiCtx->sampler({ QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
495 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
496 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
497 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
498 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
499 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
501 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
503 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
504 QRhiTexture *texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
505 rhiCtx->commandBuffer()->resourceUpdate(rub);
506 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
507 QRhiSampler::Nearest,
509 QRhiSampler::ClampToEdge,
510 QRhiSampler::ClampToEdge,
513 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
517 samplerBinding = shaderPipeline.bindingForTexture(
"qt_particleTexture");
518 if (samplerBinding >= 0) {
519 QRhiTexture *texture = particleData.texture;
520 if (samplerBinding >= 0 && texture) {
521 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
522 QRhiSampler::Nearest,
524 QRhiSampler::ClampToEdge,
525 QRhiSampler::ClampToEdge,
528 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
532 samplerBinding = shaderPipeline.bindingForTexture(
"qt_colorTable");
533 if (samplerBinding >= 0) {
534 bool hasTexture =
false;
535 if (renderable.colorTable) {
536 QRhiTexture *texture = renderable.colorTable->m_texture.m_texture;
539 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
540 QRhiSampler::Nearest,
542 QRhiSampler::ClampToEdge,
543 QRhiSampler::ClampToEdge,
546 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
551 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
552 QRhiTexture *texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
553 rhiCtx->commandBuffer()->resourceUpdate(rub);
554 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
555 QRhiSampler::Nearest,
557 QRhiSampler::ClampToEdge,
558 QRhiSampler::ClampToEdge,
561 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
565 if (oit && inData.layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
566 RenderHelpers::addAccumulatorImageBindings(&shaderPipeline, bindings);
568 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
571 QRhiShaderResourceBindings *&srb = dcd.srb;
572 bool srbChanged =
false;
573 if (!srb || bindings != dcd.bindings) {
574 srb = rhiCtxD->srb(bindings);
575 rhiCtxD->releaseCachedSrb(dcd.bindings);
576 dcd.bindings = bindings;
580 if (cubeFace == QSSGRenderTextureCubeFaceNone)
581 renderable.rhiRenderData.mainPass.srb = srb;
583 renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx] = srb;
585 const auto pipelineKey = QSSGGraphicsPipelineStateKey::create(*ps, renderPassDescriptor, srb);
588 && dcd.renderTargetDescriptionHash == pipelineKey.extra.renderTargetDescriptionHash
589 && dcd.renderTargetDescription == pipelineKey.renderTargetDescription
592 if (cubeFace == QSSGRenderTextureCubeFaceNone)
593 renderable.rhiRenderData.mainPass.pipeline = dcd.pipeline;
595 renderable.rhiRenderData.reflectionPass.pipeline = dcd.pipeline;
597 if (cubeFace == QSSGRenderTextureCubeFaceNone) {
598 renderable.rhiRenderData.mainPass.pipeline = rhiCtxD->pipeline(pipelineKey,
599 renderPassDescriptor,
601 dcd.pipeline = renderable.rhiRenderData.mainPass.pipeline;
603 renderable.rhiRenderData.reflectionPass.pipeline = rhiCtxD->pipeline(pipelineKey,
604 renderPassDescriptor,
606 dcd.pipeline = renderable.rhiRenderData.reflectionPass.pipeline;
608 dcd.renderTargetDescriptionHash = pipelineKey.extra.renderTargetDescriptionHash;
609 dcd.renderTargetDescription = pipelineKey.renderTargetDescription;
614void QSSGParticleRenderer::prepareParticlesForModel(QSSGRhiShaderPipeline &shaderPipeline,
615 QSSGRhiContext *rhiCtx,
616 QSSGRhiShaderResourceBindingList &bindings,
617 const QSSGRenderModel *model)
619 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
620 QSSGRhiParticleData &particleData = rhiCtxD->particleData(model);
621 const QSSGParticleBuffer &particleBuffer = *model->particleBuffer;
622 int particleCount = particleBuffer.particleCount();
623 bool update = particleBuffer.serial() != particleData.serial;
624 const bool needsConversion = !rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32F);
625 if (particleData.texture ==
nullptr || particleData.particleCount != particleCount) {
626 QSize size(particleBuffer.size());
627 if (!particleData.texture) {
628 particleData.texture = rhiCtx->rhi()->newTexture(needsConversion ? QRhiTexture::RGBA16F : QRhiTexture::RGBA32F, size);
629 particleData.texture->create();
631 particleData.texture->setPixelSize(size);
632 particleData.texture->create();
634 particleData.particleCount = particleCount;
639 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
640 QRhiTextureSubresourceUploadDescription upload;
641 upload.setData(convertParticleData(particleData.convertData, particleBuffer.data(), needsConversion));
642 QRhiTextureUploadDescription uploadDesc(QRhiTextureUploadEntry(0, 0, upload));
643 rub->uploadTexture(particleData.texture, uploadDesc);
644 rhiCtx->commandBuffer()->resourceUpdate(rub);
646 particleData.serial = particleBuffer.serial();
647 int samplerBinding = shaderPipeline.bindingForTexture(
"qt_particleTexture");
648 if (samplerBinding >= 0) {
649 QRhiTexture *texture = particleData.texture;
650 if (samplerBinding >= 0 && texture) {
651 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
652 QRhiSampler::Nearest,
654 QRhiSampler::ClampToEdge,
655 QRhiSampler::ClampToEdge,
658 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
765QSSGRhiShaderPipelinePtr QSSGParticleRenderer::generateRhiShaderPipeline(QSSGRenderer &renderer,
766 QSSGParticlesRenderable &inRenderable,
767 const QSSGShaderFeatures &inFeatureSet,
768 QByteArray &shaderString,
769 const QSSGShaderParticleMaterialKeyProperties &shaderKeyProperties)
771 const auto &m_contextInterface = renderer.m_contextInterface;
772 const auto &shaderCache = m_contextInterface->shaderCache();
773 const auto &shaderProgramGenerator = m_contextInterface->shaderProgramGenerator();
774 const auto &shaderLibraryManager = m_contextInterface->shaderLibraryManager();
776 shaderString = particlesLogPrefix();
777 QSSGShaderParticleMaterialKey theKey(inRenderable.shaderDescription);
779 theKey.toString(shaderString, shaderKeyProperties);
781 if (s_shaderCacheEnabled) {
782 if (
const auto &maybePipeline = shaderCache->tryGetRhiShaderPipeline(shaderString, inFeatureSet))
783 return maybePipeline;
785 const QByteArray qsbcKey = QQsbCollection::EntryDesc::generateSha(shaderString, QQsbCollection::toFeatureSet(inFeatureSet));
787 if (renderer.m_currentLayer) {
788 QQsbCollection::EntryMap &pregenEntries = renderer.m_currentLayer->m_particleShaderEntries;
789 if (pregenEntries.isEmpty()) {
790 renderer.m_currentLayer->m_particleShaderEntries = shaderLibraryManager->getParticleShaderEntries();
791 pregenEntries = renderer.m_currentLayer->m_particleShaderEntries;
793 if (!pregenEntries.isEmpty()) {
794 const auto foundIt = pregenEntries.constFind(QQsbCollection::Entry(qsbcKey));
795 if (foundIt != pregenEntries.cend())
796 return shaderCache->newPipelineFromPregenerated(shaderString, inFeatureSet, *foundIt, inRenderable.particles);
801 if (
const auto &maybePipeline = shaderCache->tryNewPipelineFromPersistentCache(qsbcKey, shaderString, inFeatureSet))
802 return maybePipeline;
806 shaderProgramGenerator->beginProgram();
807 auto &vertex = *shaderProgramGenerator->getStage(QSSGShaderGeneratorStage::Vertex);
808 auto &fragment = *shaderProgramGenerator->getStage(QSSGShaderGeneratorStage::Fragment);
809 ShaderGeneratorCommon common(*shaderProgramGenerator);
810 const bool isSpriteLinear = shaderKeyProperties.m_isSpriteLinear.getValue(theKey);
811 const bool isColorTableLinear = shaderKeyProperties.m_isColorTableLinear.getValue(theKey);
812 const bool lighting = shaderKeyProperties.m_hasLighting.getValue(theKey);
813 const bool isMapped = shaderKeyProperties.m_isMapped.getValue(theKey);
814 const bool isLineParticle = shaderKeyProperties.m_isLineParticle.getValue(theKey);
815 const bool isAnimated = shaderKeyProperties.m_isAnimated.getValue(theKey);
816 const int viewCount = inFeatureSet.isSet(QSSGShaderFeatures::Feature::DisableMultiView)
817 ? 1 : shaderKeyProperties.m_viewCount.getValue(theKey);
818 const int oit = shaderKeyProperties.m_orderIndependentTransparency.getValue(theKey);
819 const bool oitMSAA = shaderKeyProperties.m_oitMSAA.getValue(theKey);
822 common.addDefinition(
"QSSG_PARTICLES_ENABLE_ANIMATED",
"1");
824 common.addDefinition(
"QSSG_PARTICLES_ENABLE_LINE_PARTICLE",
"1");
826 common.addDefinition(
"QSSG_OIT_METHOD", QStringLiteral(
"%1").arg(oit).toUtf8());
828 common.addDefinition(
"QSSG_MULTISAMPLE",
"1");
830 common.addUniform(
"qt_modelMatrix",
"mat4");
831 if (viewCount >= 2) {
832 common.addUniformArray(
"qt_viewMatrix",
"mat4", viewCount);
833 common.addUniformArray(
"qt_projectionMatrix",
"mat4", viewCount);
835 common.addUniform(
"qt_viewMatrix",
"mat4");
836 common.addUniform(
"qt_projectionMatrix",
"mat4");
839 common.addPrefix(s_lightPrefix);
840 common.addUniform(
"lightData",
"ParticleLightData");
842 common.addUniform(
"qt_spriteConfig",
"vec4");
843 common.addUniform(
"qt_light_ambient_total",
"vec3");
844 common.addUniform(
"qt_oneOverParticleImageSize",
"vec2");
845 common.addUniform(
"qt_countPerSlice",
"uint");
847 common.addUniform(
"qt_lineSegmentCount",
"uint");
848 common.addUniform(
"qt_billboard",
"float");
849 common.addUniform(
"qt_opacity",
"float");
850 if (isLineParticle) {
851 common.addUniform(
"qt_alphaFade",
"float");
852 common.addUniform(
"qt_sizeModifier",
"float");
853 common.addUniform(
"qt_texcoordScale",
"float");
856 common.addUniform(
"qt_pointLights",
"bool");
857 common.addUniform(
"qt_spotLights",
"bool");
859 if (oit == (
int)QSSGRenderLayer::OITMethod::WeightedBlended) {
860 common.addUniform(
"qt_cameraProperties",
"vec2");
861 }
else if (oit == (
int)QSSGRenderLayer::OITMethod::LinkedList) {
862 common.addUniform(
"qt_viewSize",
"ivec2");
863 common.addUniform(
"qt_ABufImageWidth",
"uint");
864 common.addUniform(
"qt_listNodeCount",
"uint");
865#ifdef QSSG_OIT_USE_BUFFERS
866 common.addUniform(
"qt_samples",
"uint");
871 vertex.addInclude(
"particleLighting.glsllib");
873 vertex.addUniform(
"qt_particleTexture",
"sampler2D");
875 vertex.addInclude(
"particleLoading.glsllib");
877 common.addInterpolant(
"color",
"vec4");
878 common.addInterpolant(
"spriteData",
"vec2");
879 common.addInterpolant(
"texcoord",
"vec2");
880 common.addFlatInterpolant(
"instanceIndex",
"uint");
881 if (oit == (
int)QSSGRenderLayer::OITMethod::LinkedList && viewCount >= 2)
882 common.addFlatInterpolant(
"v_viewIndex",
"uint");
884 AutoFormatGenerator vg(vertex);
886 vg <<
"const vec2 corners[4] = {{0.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}, {1.0, 1.0}};";
889 vg <<
"out gl_PerVertex {"
890 <<
" vec4 gl_Position;"
893 vg <<
"void main() {";
895 if (isLineParticle) {
896 vg <<
"uint segmentIndex = gl_VertexIndex / 2;"
897 <<
"uint particleIndex = segmentIndex + gl_InstanceIndex * qt_lineSegmentCount;";
899 vg <<
"uint particleIndex = gl_InstanceIndex;"
900 <<
"uint cornerIndex = gl_VertexIndex;"
901 <<
"vec2 corner = corners[cornerIndex];";
903 vg <<
"instanceIndex = particleIndex;"
904 <<
"Particle p = qt_loadParticle(particleIndex);";
906 if (isLineParticle) {
907 vg <<
"float side = float(mod(gl_VertexIndex, 2)) - 0.5;"
908 <<
"float size = p.size * qt_calcSizeFactor(segmentIndex);"
909 <<
"vec3 o = p.binormal * side * size;"
910 <<
"vec4 worldPos = qt_modelMatrix * vec4(p.position + (1.0 - qt_billboard) * o, 1.0);";
911 if (viewCount >= 2) {
912 vg <<
"vec4 viewPos = qt_viewMatrix[gl_ViewIndex] * worldPos;"
913 <<
"vec3 viewBN = (transpose(inverse(qt_viewMatrix[gl_ViewIndex] * qt_modelMatrix)) * vec4(p.binormal, 0.0)).xyz;";
915 vg <<
"vec4 viewPos = qt_viewMatrix * worldPos;"
916 <<
"vec3 viewBN = (transpose(inverse(qt_viewMatrix * qt_modelMatrix)) * vec4(p.binormal, 0.0)).xyz;";
918 vg <<
"viewBN.z = 0;"
919 <<
"viewBN = normalize(viewBN) * side * size;"
920 <<
"viewPos = viewPos + vec4(viewBN, 0.0) * qt_billboard;"
921 <<
"texcoord.x = p.segmentLength * qt_texcoordScale;"
922 <<
"texcoord.y = float(mod(gl_VertexIndex, 2));"
923 <<
"color = p.color;"
924 <<
"color.a *= qt_opacity * qt_calcAlphaFade(segmentIndex);";
926 vg <<
"mat3 rotMat = qt_fromEulerRotation(p.rotation);"
927 <<
"vec4 worldPos = qt_modelMatrix * vec4(p.position, 1.0);"
928 <<
"vec4 viewPos = worldPos;"
929 <<
"vec3 offset = (p.size * vec3(corner - vec2(0.5), 0.0));"
930 <<
"viewPos.xyz += offset * rotMat * (1.0 - qt_billboard);";
932 vg <<
"viewPos = qt_viewMatrix[gl_ViewIndex] * viewPos;";
934 vg <<
"viewPos = qt_viewMatrix * viewPos;";
935 vg <<
"viewPos.xyz += rotMat * offset * qt_billboard;"
936 <<
"texcoord = corner;"
937 <<
"color = p.color;"
938 <<
"color.a *= qt_opacity;";
941 vg <<
"color.rgb *= qt_calcLightColor(worldPos.xyz);";
942 if (viewCount >= 2) {
943 if (oit ==
int(QSSGRenderLayer::OITMethod::LinkedList))
944 vg <<
"v_viewIndex = gl_ViewIndex;";
945 vg <<
"gl_Position = qt_projectionMatrix[gl_ViewIndex] * viewPos;";
947 vg <<
"gl_Position = qt_projectionMatrix * viewPos;";
950 vg <<
"spriteData.x = qt_ageToSpriteFactor(p.age);";
952 vg <<
"spriteData.y = p.animationFrame;";
957 fragment.addInclude(
"tonemapping.glsllib");
958 fragment.addInclude(
"particleSprite.glsllib");
959 fragment.addUniform(
"qt_sprite",
"sampler2D");
961 AutoFormatGenerator fg(fragment);
963 if (oit ==
int(QSSGRenderLayer::OITMethod::WeightedBlended)) {
964 fragment.addInclude(
"oitweightedblended.glsllib");
965 fg <<
"layout(location = 1) out vec4 revealageOutput;";
966 }
else if (oit ==
int(QSSGRenderLayer::OITMethod::LinkedList)) {
967#ifdef QSSG_OIT_USE_BUFFERS
968 fragment.addInclude(
"oitlinkedlist_buf.glsllib");
969 QSSGShaderResourceMergeContext::setAdditionalBufferAmount(3);
971 fragment.addInclude(
"oitlinkedlist.glsllib");
975 fg <<
"#define spriteFunc";
977 fg <<
"#define spriteFunc qt_sRGBToLinear";
979 fragment.addUniform(
"qt_colorTable",
"sampler2D");
980 if (isColorTableLinear)
981 fg <<
"#define colorTableFunc";
983 fg <<
"#define colorTableFunc qt_sRGBToLinear";
986 fg <<
"vec4 qt_readSprite() {";
989 fg <<
"vec2 coords[2];"
990 <<
"float factor = qt_spriteCoords(coords);"
991 <<
"return mix(spriteFunc(texture(qt_sprite, coords[0])), spriteFunc(texture(qt_sprite, coords[1])), factor);";
993 fg <<
"return spriteFunc(texture(qt_sprite, texcoord));";
997 fg <<
"vec4 qt_readColor() {";
1000 fg <<
"return color * colorTableFunc(texture(qt_colorTable, vec2(spriteData.x, qt_rand(vec2(instanceIndex, 0)))));";
1002 fg <<
"return color;";
1005 fg <<
"void main() {";
1007 fg <<
"vec4 ret = qt_readColor() * qt_readSprite();";
1009 if (oit ==
int(QSSGRenderLayer::OITMethod::WeightedBlended)) {
1010 fg <<
"float z = abs(gl_FragCoord.z);"
1011 <<
"float distWeight = qt_transparencyWeight(z, ret.a, qt_cameraProperties.y);"
1012 <<
"fragOutput = distWeight * qt_tonemap(ret);"
1013 <<
"revealageOutput = vec4(ret.a);";
1014 }
else if (oit ==
int(QSSGRenderLayer::OITMethod::LinkedList)) {
1015#ifdef QSSG_OIT_USE_BUFFERS
1017 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex, qt_samples);";
1019 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0, qt_samples);";
1022 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex);";
1024 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0);";
1028 fg <<
"fragOutput = qt_tonemap(ret);";
1034 return shaderProgramGenerator->compileGeneratedRhiShader(shaderString,
1036 *shaderLibraryManager,
1038 QSSGRhiShaderPipeline::UsedWithoutIa,
1040 shaderKeyProperties.m_viewCount.getValue(inRenderable.shaderDescription),
1090void QSSGParticleRenderer::rhiRenderRenderable(QSSGRhiContext *rhiCtx,
1091 QSSGParticlesRenderable &renderable,
1092 bool *needsSetViewport,
1093 QSSGRenderTextureCubeFace cubeFace,
1094 const QSSGRhiGraphicsPipelineState &state)
1096 QRhiGraphicsPipeline *ps = renderable.rhiRenderData.mainPass.pipeline;
1097 QRhiShaderResourceBindings *srb = renderable.rhiRenderData.mainPass.srb;
1099 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
1100 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
1101 ps = renderable.rhiRenderData.reflectionPass.pipeline;
1102 srb = renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx];
1108 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
1110 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
1112 cb->setGraphicsPipeline(ps);
1113 cb->setVertexInput(0, 0,
nullptr);
1114 cb->setShaderResources(srb);
1116 if (needsSetViewport && *needsSetViewport) {
1117 cb->setViewport(state.viewport);
1118 *needsSetViewport =
false;
1120 if (renderable.particles.m_featureLevel >= QSSGRenderParticles::FeatureLevel::Line) {
1122 int S = renderable.particles.m_particleBuffer.segments();
1123 int N = renderable.particles.m_particleBuffer.particleCount() / S;
1126 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderCall, (2 * S | quint64(N) << 32), renderable.particles.profilingId);
1129 cb->draw(4, renderable.particles.m_particleBuffer.particleCount());
1130 QSSGRHICTX_STAT(rhiCtx, draw(4, renderable.particles.m_particleBuffer.particleCount()));
1131 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderCall, (4 | quint64(renderable.particles.m_particleBuffer.particleCount()) << 32), renderable.particles.profilingId);