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 int listNodeCount = inData.layer.oitNodeCount;
194 const QSSGRhiRenderableTexture *abuf = inData.getRenderResult(QSSGRenderResult::Key::ABufferImage);
195 const QSSGRhiRenderableTexture *aux = inData.getRenderResult(QSSGRenderResult::Key::AuxiliaryImage);
196 const QSSGRhiRenderableTexture *counter = inData.getRenderResult(QSSGRenderResult::Key::CounterImage);
197 shaders.setOITImages(abuf->texture, aux->texture, counter->texture);
199 int abufWidth = RenderHelpers::rhiCalculateABufferSize(inData.layer.oitNodeCount);
200 int listNodeCount = abufWidth * abufWidth;
202 shaders.setUniform(ubufData,
"qt_ABufImageWidth", &abufWidth,
sizeof(
int), &cui.abufImageWidth);
203 shaders.setUniform(ubufData,
"qt_listNodeCount", &listNodeCount,
sizeof(
int), &cui.listNodeCount);
204 int viewSize[2] = {inData.layerPrepResult.textureDimensions().width(), inData.layerPrepResult.textureDimensions().height()};
205 shaders.setUniform(ubufData,
"qt_viewSize", viewSize,
sizeof(
int) * 2, &cui.viewSize);
207 if (inData.m_currentOrigin == QSSGLayerRenderData::WindowOrigin)
208 vpOrigin = inData.m_viewportOrigin;
209 shaders.setUniform(ubufData,
"qt_viewportOrigin", &vpOrigin,
sizeof(
float) * 2, &cui.viewportOrigin);
210 int samples = rhiCtx->mainPassSampleCount();
211 shaders.setUniform(ubufData,
"qt_samples", &samples,
sizeof(
int), &cui.samples);
258 const QSSGParticleBuffer &buffer,
const QSSGRenderParticles &particles,
259 const QVector3D &cameraDirection,
bool animatedParticles)
261 const QMatrix4x4 &modelMatrix = renderData.getGlobalTransform(particles);
262 const QMatrix4x4 &invModelMatrix = modelMatrix.inverted();
263 QVector3D dir = invModelMatrix.map(cameraDirection);
264 QVector3D n = dir.normalized();
265 const auto segments = buffer.segments();
266 auto particleCount = buffer.particleCount();
267 const bool lineParticles = segments > 0;
269 particleCount /= segments;
270 sortData.resize(particleCount);
273 const auto srcParticlePointer = [](
int line,
int segment,
int sc,
int ss,
int pps,
const char *source) ->
const QSSGLineParticle * {
274 int pi = (line * sc + segment) / pps;
275 int i = (line * sc + segment) % pps;
276 const QSSGLineParticle *sp =
reinterpret_cast<
const QSSGLineParticle *>(source + pi * ss);
282 const auto slices = buffer.sliceCount();
283 const auto ss = buffer.sliceStride();
284 const auto pps = buffer.particlesPerSlice();
287 const char *source = buffer.pointer();
288 const char *begin = source;
291 for (i = 0; i < particleCount; i++) {
293 const QSSGLineParticle *lineBegin = srcParticlePointer(i, 0, segments, ss, pps, source);
295 lineData
.d = QVector3D::dotProduct(lineBegin->position, n);
296 for (
int j = 1; j < buffer.segments(); j++) {
297 const QSSGLineParticle *p = srcParticlePointer(i, j, segments, ss, pps, source);
298 lineData
.d = qMin(lineData
.d, QVector3D::dotProduct(p->position, n));
302 }
else if (animatedParticles) {
303 for (
int s = 0; s < slices; s++) {
304 const QSSGParticleAnimated *sp =
reinterpret_cast<
const QSSGParticleAnimated *>(source);
305 for (
int p = 0; p < pps && i < particleCount; p++) {
306 *dst = { QVector3D::dotProduct(sp->position, n),
int(
reinterpret_cast<
const char *>(sp) - begin)};
314 for (
int s = 0; s < slices; s++) {
315 const QSSGParticleSimple *sp =
reinterpret_cast<
const QSSGParticleSimple *>(source);
316 for (
int p = 0; p < pps && i < particleCount; p++) {
317 *dst = { QVector3D::dotProduct(sp->position, n),
int(
reinterpret_cast<
const char *>(sp) - begin)};
328 result.resize(buffer.bufferSize());
329 std::sort(sortData.begin(), sortData.end(), [](
const QSSGRhiSortData &a,
const QSSGRhiSortData &b){
333 auto copyParticles = [&](QByteArray &dst,
const QList<QSSGRhiSortData> &data,
const QSSGParticleBuffer &buffer) {
334 const auto slices = buffer.sliceCount();
335 const auto ss = buffer.sliceStride();
336 const auto pps = buffer.particlesPerSlice();
338 char *dest = dst.data();
339 const char *source = buffer.pointer();
343 for (
int s = 0; s < slices; s++) {
344 QSSGLineParticle *dp =
reinterpret_cast<QSSGLineParticle *>(dest);
345 for (
int p = 0; p < pps && i < particleCount; p++) {
346 *dp = *srcParticlePointer(sdata
->indexOrOffset, seg, segments, ss, pps, source);
349 if (seg == segments) {
357 }
else if (animatedParticles) {
358 for (
int s = 0; s < slices; s++) {
359 QSSGParticleAnimated *dp =
reinterpret_cast<QSSGParticleAnimated *>(dest);
360 for (
int p = 0; p < pps && i < particleCount; p++) {
361 *dp = *
reinterpret_cast<
const QSSGParticleAnimated *>(source + sdata
->indexOrOffset);
369 for (
int s = 0; s < slices; s++) {
370 QSSGParticleSimple *dp =
reinterpret_cast<QSSGParticleSimple *>(dest);
371 for (
int p = 0; p < pps && i < particleCount; p++) {
372 *dp = *
reinterpret_cast<
const QSSGParticleSimple *>(source + sdata
->indexOrOffset);
383 copyParticles(result, sortData, buffer);
397void QSSGParticleRenderer::rhiPrepareRenderable(QSSGRhiShaderPipeline &shaderPipeline,
399 QSSGRhiContext *rhiCtx,
400 QSSGRhiGraphicsPipelineState *ps,
401 QSSGParticlesRenderable &renderable,
402 const QSSGLayerRenderData &inData,
403 QRhiRenderPassDescriptor *renderPassDescriptor,
406 QSSGRenderCamera *alteredCamera,
407 QSSGRenderTextureCubeFace cubeFace,
408 QSSGReflectionMapEntry *entry,
411 const void *node = &renderable.particles;
412 const bool needsConversion = !rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32F);
414 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
415 QSSGRhiDrawCallData &dcd = QSSGRhiContextPrivate::get(rhiCtx)->drawCallData({ passKey, node,
nullptr, entry,
417 shaderPipeline.ensureUniformBuffer(&dcd.ubuf);
419 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
420 if (!alteredCamera) {
421 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, inData.renderedCameras);
423 QSSGRenderCameraList cameras({ alteredCamera });
424 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, cameras);
426 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
428 QSSGRhiParticleData &particleData = QSSGRhiContextPrivate::get(rhiCtx)->particleData(&renderable.particles);
429 const QSSGParticleBuffer &particleBuffer = renderable.particles.m_particleBuffer;
430 int particleCount = particleBuffer.particleCount();
431 if (particleData.texture ==
nullptr || particleData.particleCount != particleCount) {
432 QSize size(particleBuffer.size());
433 if (!particleData.texture) {
434 particleData.texture = rhiCtx->rhi()->newTexture(needsConversion ? QRhiTexture::RGBA16F : QRhiTexture::RGBA32F, size);
435 particleData.texture->create();
437 particleData.texture->setPixelSize(size);
438 particleData.texture->create();
440 particleData.particleCount = particleCount;
443 bool sortingChanged = particleData.sorting != renderable.particles.m_depthSorting;
444 if (sortingChanged && !renderable.particles.m_depthSorting) {
445 particleData.sortData.clear();
446 particleData.sortedData.clear();
448 particleData.sorting = renderable.particles.m_depthSorting;
450 QByteArray uploadData;
452 if (renderable.particles.m_depthSorting) {
453 bool animatedParticles = renderable.particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::Animated;
454 if (!alteredCamera) {
455 sortParticles(inData, particleData.sortedData, particleData.sortData, particleBuffer, renderable.particles, inData.renderedCameraData.value()[0].direction, animatedParticles);
457 const QMatrix4x4 globalTransform = inData.getGlobalTransform(*alteredCamera);
458 sortParticles(inData, particleData.sortedData, particleData.sortData, particleBuffer, renderable.particles, QSSGRenderNode::getScalingCorrectDirection(globalTransform), animatedParticles);
460 uploadData = convertParticleData(particleData.convertData, particleData.sortedData, needsConversion);
462 uploadData = convertParticleData(particleData.convertData, particleBuffer.data(), needsConversion);
465 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
466 QRhiTextureSubresourceUploadDescription upload;
467 upload.setData(uploadData);
468 QRhiTextureUploadDescription uploadDesc(QRhiTextureUploadEntry(0, 0, upload));
469 rub->uploadTexture(particleData.texture, uploadDesc);
470 rhiCtx->commandBuffer()->resourceUpdate(rub);
472 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
473 ia.topology = QRhiGraphicsPipeline::TriangleStrip;
474 ia.inputLayout = QRhiVertexInputLayout();
477 ps->samples = samples;
478 ps->viewCount = viewCount;
479 ps->cullMode = QRhiGraphicsPipeline::None;
481 if (inData.orderIndependentTransparencyEnabled ==
false) {
482 if (renderable.renderableFlags.hasTransparency())
483 fillTargetBlend(ps->targetBlend[0], renderable.particles.m_blendMode);
485 ps->targetBlend[0] = QRhiGraphicsPipeline::TargetBlend();
488 QSSGRhiShaderResourceBindingList bindings;
489 bindings.addUniformBuffer(0, VISIBILITY_ALL, dcd.ubuf, 0, shaderPipeline.ub0Size());
493 QSSGRenderableImage *renderableImage = renderable.firstImage;
495 int samplerBinding = shaderPipeline.bindingForTexture(
"qt_sprite");
496 if (samplerBinding >= 0) {
497 QRhiTexture *texture = renderableImage ? renderableImage->m_texture.m_texture :
nullptr;
498 if (samplerBinding >= 0 && texture) {
499 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
500 QRhiSampler *sampler = rhiCtx->sampler({ QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
501 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
502 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
503 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
504 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
505 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
507 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
509 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
510 QRhiTexture *texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
511 rhiCtx->commandBuffer()->resourceUpdate(rub);
512 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
513 QRhiSampler::Nearest,
515 QRhiSampler::ClampToEdge,
516 QRhiSampler::ClampToEdge,
519 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
523 samplerBinding = shaderPipeline.bindingForTexture(
"qt_particleTexture");
524 if (samplerBinding >= 0) {
525 QRhiTexture *texture = particleData.texture;
526 if (samplerBinding >= 0 && texture) {
527 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
528 QRhiSampler::Nearest,
530 QRhiSampler::ClampToEdge,
531 QRhiSampler::ClampToEdge,
534 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
538 samplerBinding = shaderPipeline.bindingForTexture(
"qt_colorTable");
539 if (samplerBinding >= 0) {
540 bool hasTexture =
false;
541 if (renderable.colorTable) {
542 QRhiTexture *texture = renderable.colorTable->m_texture.m_texture;
545 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
546 QRhiSampler::Nearest,
548 QRhiSampler::ClampToEdge,
549 QRhiSampler::ClampToEdge,
552 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
557 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
558 QRhiTexture *texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
559 rhiCtx->commandBuffer()->resourceUpdate(rub);
560 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
561 QRhiSampler::Nearest,
563 QRhiSampler::ClampToEdge,
564 QRhiSampler::ClampToEdge,
567 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
571 if (oit && inData.layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
572 RenderHelpers::addAccumulatorImageBindings(&shaderPipeline, bindings);
574 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
577 QRhiShaderResourceBindings *&srb = dcd.srb;
578 bool srbChanged =
false;
579 if (!srb || bindings != dcd.bindings) {
580 srb = rhiCtxD->srb(bindings);
581 rhiCtxD->releaseCachedSrb(dcd.bindings);
582 dcd.bindings = bindings;
586 if (cubeFace == QSSGRenderTextureCubeFaceNone)
587 renderable.rhiRenderData.mainPass.srb = srb;
589 renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx] = srb;
591 const auto pipelineKey = QSSGGraphicsPipelineStateKey::create(*ps, renderPassDescriptor, srb);
594 && dcd.renderTargetDescriptionHash == pipelineKey.extra.renderTargetDescriptionHash
595 && dcd.renderTargetDescription == pipelineKey.renderTargetDescription
598 if (cubeFace == QSSGRenderTextureCubeFaceNone)
599 renderable.rhiRenderData.mainPass.pipeline = dcd.pipeline;
601 renderable.rhiRenderData.reflectionPass.pipeline = dcd.pipeline;
603 if (cubeFace == QSSGRenderTextureCubeFaceNone) {
604 renderable.rhiRenderData.mainPass.pipeline = rhiCtxD->pipeline(pipelineKey,
605 renderPassDescriptor,
607 dcd.pipeline = renderable.rhiRenderData.mainPass.pipeline;
609 renderable.rhiRenderData.reflectionPass.pipeline = rhiCtxD->pipeline(pipelineKey,
610 renderPassDescriptor,
612 dcd.pipeline = renderable.rhiRenderData.reflectionPass.pipeline;
614 dcd.renderTargetDescriptionHash = pipelineKey.extra.renderTargetDescriptionHash;
615 dcd.renderTargetDescription = pipelineKey.renderTargetDescription;
620void QSSGParticleRenderer::prepareParticlesForModel(QSSGRhiShaderPipeline &shaderPipeline,
621 QSSGRhiContext *rhiCtx,
622 QSSGRhiShaderResourceBindingList &bindings,
623 const QSSGRenderModel *model)
625 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
626 QSSGRhiParticleData &particleData = rhiCtxD->particleData(model);
627 const QSSGParticleBuffer &particleBuffer = *model->particleBuffer;
628 int particleCount = particleBuffer.particleCount();
629 bool update = particleBuffer.serial() != particleData.serial;
630 const bool needsConversion = !rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32F);
631 if (particleData.texture ==
nullptr || particleData.particleCount != particleCount) {
632 QSize size(particleBuffer.size());
633 if (!particleData.texture) {
634 particleData.texture = rhiCtx->rhi()->newTexture(needsConversion ? QRhiTexture::RGBA16F : QRhiTexture::RGBA32F, size);
635 particleData.texture->create();
637 particleData.texture->setPixelSize(size);
638 particleData.texture->create();
640 particleData.particleCount = particleCount;
645 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
646 QRhiTextureSubresourceUploadDescription upload;
647 upload.setData(convertParticleData(particleData.convertData, particleBuffer.data(), needsConversion));
648 QRhiTextureUploadDescription uploadDesc(QRhiTextureUploadEntry(0, 0, upload));
649 rub->uploadTexture(particleData.texture, uploadDesc);
650 rhiCtx->commandBuffer()->resourceUpdate(rub);
652 particleData.serial = particleBuffer.serial();
653 int samplerBinding = shaderPipeline.bindingForTexture(
"qt_particleTexture");
654 if (samplerBinding >= 0) {
655 QRhiTexture *texture = particleData.texture;
656 if (samplerBinding >= 0 && texture) {
657 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
658 QRhiSampler::Nearest,
660 QRhiSampler::ClampToEdge,
661 QRhiSampler::ClampToEdge,
664 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
771QSSGRhiShaderPipelinePtr QSSGParticleRenderer::generateRhiShaderPipeline(QSSGRenderer &renderer,
772 QSSGParticlesRenderable &inRenderable,
773 const QSSGShaderFeatures &inFeatureSet,
774 QByteArray &shaderString,
775 const QSSGShaderParticleMaterialKeyProperties &shaderKeyProperties)
777 const auto &m_contextInterface = renderer.m_contextInterface;
778 const auto &shaderCache = m_contextInterface->shaderCache();
779 const auto &shaderProgramGenerator = m_contextInterface->shaderProgramGenerator();
780 const auto &shaderLibraryManager = m_contextInterface->shaderLibraryManager();
782 shaderString = particlesLogPrefix();
783 QSSGShaderParticleMaterialKey theKey(inRenderable.shaderDescription);
785 theKey.toString(shaderString, shaderKeyProperties);
787 if (s_shaderCacheEnabled) {
788 if (
const auto &maybePipeline = shaderCache->tryGetRhiShaderPipeline(shaderString, inFeatureSet))
789 return maybePipeline;
791 const QByteArray qsbcKey = QQsbCollection::EntryDesc::generateSha(shaderString, QQsbCollection::toFeatureSet(inFeatureSet));
793 if (renderer.m_currentLayer) {
794 QQsbCollection::EntryMap &pregenEntries = renderer.m_currentLayer->m_particleShaderEntries;
795 if (pregenEntries.isEmpty()) {
796 renderer.m_currentLayer->m_particleShaderEntries = shaderLibraryManager->getParticleShaderEntries();
797 pregenEntries = renderer.m_currentLayer->m_particleShaderEntries;
799 if (!pregenEntries.isEmpty()) {
800 const auto foundIt = pregenEntries.constFind(QQsbCollection::Entry(qsbcKey));
801 if (foundIt != pregenEntries.cend())
802 return shaderCache->newPipelineFromPregenerated(shaderString, inFeatureSet, *foundIt, inRenderable.particles);
807 if (
const auto &maybePipeline = shaderCache->tryNewPipelineFromPersistentCache(qsbcKey, shaderString, inFeatureSet))
808 return maybePipeline;
812 shaderProgramGenerator->beginProgram();
813 auto &vertex = *shaderProgramGenerator->getStage(QSSGShaderGeneratorStage::Vertex);
814 auto &fragment = *shaderProgramGenerator->getStage(QSSGShaderGeneratorStage::Fragment);
815 ShaderGeneratorCommon common(*shaderProgramGenerator);
816 const bool isSpriteLinear = shaderKeyProperties.m_isSpriteLinear.getValue(theKey);
817 const bool isColorTableLinear = shaderKeyProperties.m_isColorTableLinear.getValue(theKey);
818 const bool lighting = shaderKeyProperties.m_hasLighting.getValue(theKey);
819 const bool isMapped = shaderKeyProperties.m_isMapped.getValue(theKey);
820 const bool isLineParticle = shaderKeyProperties.m_isLineParticle.getValue(theKey);
821 const bool isAnimated = shaderKeyProperties.m_isAnimated.getValue(theKey);
822 const int viewCount = inFeatureSet.isSet(QSSGShaderFeatures::Feature::DisableMultiView)
823 ? 1 : shaderKeyProperties.m_viewCount.getValue(theKey);
824 const int oit = shaderKeyProperties.m_orderIndependentTransparency.getValue(theKey);
825 const bool oitMSAA = shaderKeyProperties.m_oitMSAA.getValue(theKey);
828 common.addDefinition(
"QSSG_PARTICLES_ENABLE_ANIMATED",
"1");
830 common.addDefinition(
"QSSG_PARTICLES_ENABLE_LINE_PARTICLE",
"1");
832 common.addDefinition(
"QSSG_OIT_METHOD", QStringLiteral(
"%1").arg(oit).toUtf8());
834 common.addDefinition(
"QSSG_MULTISAMPLE",
"1");
836 common.addUniform(
"qt_modelMatrix",
"mat4");
837 if (viewCount >= 2) {
838 common.addUniformArray(
"qt_viewMatrix",
"mat4", viewCount);
839 common.addUniformArray(
"qt_projectionMatrix",
"mat4", viewCount);
841 common.addUniform(
"qt_viewMatrix",
"mat4");
842 common.addUniform(
"qt_projectionMatrix",
"mat4");
845 common.addPrefix(s_lightPrefix);
846 common.addUniform(
"lightData",
"ParticleLightData");
848 common.addUniform(
"qt_spriteConfig",
"vec4");
849 common.addUniform(
"qt_light_ambient_total",
"vec3");
850 common.addUniform(
"qt_oneOverParticleImageSize",
"vec2");
851 common.addUniform(
"qt_countPerSlice",
"uint");
853 common.addUniform(
"qt_lineSegmentCount",
"uint");
854 common.addUniform(
"qt_billboard",
"float");
855 common.addUniform(
"qt_opacity",
"float");
856 if (isLineParticle) {
857 common.addUniform(
"qt_alphaFade",
"float");
858 common.addUniform(
"qt_sizeModifier",
"float");
859 common.addUniform(
"qt_texcoordScale",
"float");
862 common.addUniform(
"qt_pointLights",
"bool");
863 common.addUniform(
"qt_spotLights",
"bool");
865 if (oit == (
int)QSSGRenderLayer::OITMethod::WeightedBlended) {
866 common.addUniform(
"qt_cameraProperties",
"vec2");
867 }
else if (oit == (
int)QSSGRenderLayer::OITMethod::LinkedList) {
868 common.addUniform(
"qt_viewSize",
"ivec2");
869 common.addUniform(
"qt_ABufImageWidth",
"uint");
870 common.addUniform(
"qt_viewportOrigin",
"vec2");
871 common.addUniform(
"qt_listNodeCount",
"uint");
872#ifdef QSSG_OIT_USE_BUFFERS
873 common.addUniform(
"qt_samples",
"uint");
878 vertex.addInclude(
"particleLighting.glsllib");
880 vertex.addUniform(
"qt_particleTexture",
"sampler2D");
882 vertex.addInclude(
"particleLoading.glsllib");
884 common.addInterpolant(
"color",
"vec4");
885 common.addInterpolant(
"spriteData",
"vec2");
886 common.addInterpolant(
"texcoord",
"vec2");
887 common.addFlatInterpolant(
"instanceIndex",
"uint");
888 if (oit == (
int)QSSGRenderLayer::OITMethod::LinkedList && viewCount >= 2)
889 common.addFlatInterpolant(
"v_viewIndex",
"uint");
891 AutoFormatGenerator vg(vertex);
893 vg <<
"const vec2 corners[4] = {{0.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}, {1.0, 1.0}};";
896 vg <<
"out gl_PerVertex {"
897 <<
" vec4 gl_Position;"
900 vg <<
"void main() {";
902 if (isLineParticle) {
903 vg <<
"uint segmentIndex = gl_VertexIndex / 2;"
904 <<
"uint particleIndex = segmentIndex + gl_InstanceIndex * qt_lineSegmentCount;";
906 vg <<
"uint particleIndex = gl_InstanceIndex;"
907 <<
"uint cornerIndex = gl_VertexIndex;"
908 <<
"vec2 corner = corners[cornerIndex];";
910 vg <<
"instanceIndex = particleIndex;"
911 <<
"Particle p = qt_loadParticle(particleIndex);";
913 if (isLineParticle) {
914 vg <<
"float side = float(mod(gl_VertexIndex, 2)) - 0.5;"
915 <<
"float size = p.size * qt_calcSizeFactor(segmentIndex);"
916 <<
"vec3 o = p.binormal * side * size;"
917 <<
"vec4 worldPos = qt_modelMatrix * vec4(p.position + (1.0 - qt_billboard) * o, 1.0);";
918 if (viewCount >= 2) {
919 vg <<
"vec4 viewPos = qt_viewMatrix[gl_ViewIndex] * worldPos;"
920 <<
"vec3 viewBN = (transpose(inverse(qt_viewMatrix[gl_ViewIndex] * qt_modelMatrix)) * vec4(p.binormal, 0.0)).xyz;";
922 vg <<
"vec4 viewPos = qt_viewMatrix * worldPos;"
923 <<
"vec3 viewBN = (transpose(inverse(qt_viewMatrix * qt_modelMatrix)) * vec4(p.binormal, 0.0)).xyz;";
925 vg <<
"viewBN.z = 0;"
926 <<
"viewBN = normalize(viewBN) * side * size;"
927 <<
"viewPos = viewPos + vec4(viewBN, 0.0) * qt_billboard;"
928 <<
"texcoord.x = p.segmentLength * qt_texcoordScale;"
929 <<
"texcoord.y = float(mod(gl_VertexIndex, 2));"
930 <<
"color = p.color;"
931 <<
"color.a *= qt_opacity * qt_calcAlphaFade(segmentIndex);";
933 vg <<
"mat3 rotMat = qt_fromEulerRotation(p.rotation);"
934 <<
"vec4 worldPos = qt_modelMatrix * vec4(p.position, 1.0);"
935 <<
"vec4 viewPos = worldPos;"
936 <<
"vec3 offset = (p.size * vec3(corner - vec2(0.5), 0.0));"
937 <<
"viewPos.xyz += offset * rotMat * (1.0 - qt_billboard);";
939 vg <<
"viewPos = qt_viewMatrix[gl_ViewIndex] * viewPos;";
941 vg <<
"viewPos = qt_viewMatrix * viewPos;";
942 vg <<
"viewPos.xyz += rotMat * offset * qt_billboard;"
943 <<
"texcoord = corner;"
944 <<
"color = p.color;"
945 <<
"color.a *= qt_opacity;";
948 vg <<
"color.rgb *= qt_calcLightColor(worldPos.xyz);";
949 if (viewCount >= 2) {
950 if (oit ==
int(QSSGRenderLayer::OITMethod::LinkedList))
951 vg <<
"v_viewIndex = gl_ViewIndex;";
952 vg <<
"gl_Position = qt_projectionMatrix[gl_ViewIndex] * viewPos;";
954 vg <<
"gl_Position = qt_projectionMatrix * viewPos;";
957 vg <<
"spriteData.x = qt_ageToSpriteFactor(p.age);";
959 vg <<
"spriteData.y = p.animationFrame;";
964 fragment.addInclude(
"tonemapping.glsllib");
965 fragment.addInclude(
"particleSprite.glsllib");
966 fragment.addUniform(
"qt_sprite",
"sampler2D");
968 AutoFormatGenerator fg(fragment);
970 if (oit ==
int(QSSGRenderLayer::OITMethod::WeightedBlended)) {
971 fragment.addInclude(
"oitweightedblended.glsllib");
972 fg <<
"layout(location = 1) out vec4 revealageOutput;";
973 }
else if (oit ==
int(QSSGRenderLayer::OITMethod::LinkedList)) {
974#ifdef QSSG_OIT_USE_BUFFERS
975 fragment.addInclude(
"oitlinkedlist_buf.glsllib");
976 QSSGShaderResourceMergeContext::setAdditionalBufferAmount(3);
978 fragment.addInclude(
"oitlinkedlist.glsllib");
982 fg <<
"#define spriteFunc";
984 fg <<
"#define spriteFunc qt_sRGBToLinear";
986 fragment.addUniform(
"qt_colorTable",
"sampler2D");
987 if (isColorTableLinear)
988 fg <<
"#define colorTableFunc";
990 fg <<
"#define colorTableFunc qt_sRGBToLinear";
993 fg <<
"vec4 qt_readSprite() {";
996 fg <<
"vec2 coords[2];"
997 <<
"float factor = qt_spriteCoords(coords);"
998 <<
"return mix(spriteFunc(texture(qt_sprite, coords[0])), spriteFunc(texture(qt_sprite, coords[1])), factor);";
1000 fg <<
"return spriteFunc(texture(qt_sprite, texcoord));";
1004 fg <<
"vec4 qt_readColor() {";
1007 fg <<
"return color * colorTableFunc(texture(qt_colorTable, vec2(spriteData.x, qt_rand(vec2(instanceIndex, 0)))));";
1009 fg <<
"return color;";
1012 fg <<
"void main() {";
1014 fg <<
"vec4 ret = qt_readColor() * qt_readSprite();";
1016 if (oit ==
int(QSSGRenderLayer::OITMethod::WeightedBlended)) {
1017 fg <<
"float z = abs(gl_FragCoord.z);"
1018 <<
"float distWeight = qt_transparencyWeight(z, ret.a, qt_cameraProperties.y);"
1019 <<
"fragOutput = distWeight * qt_tonemap(ret);"
1020 <<
"revealageOutput = vec4(ret.a);";
1021 }
else if (oit ==
int(QSSGRenderLayer::OITMethod::LinkedList)) {
1022#ifdef QSSG_OIT_USE_BUFFERS
1024 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex, qt_samples);";
1026 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0, qt_samples);";
1029 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex);";
1031 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0);";
1035 fg <<
"fragOutput = qt_tonemap(ret);";
1041 return shaderProgramGenerator->compileGeneratedRhiShader(shaderString,
1043 *shaderLibraryManager,
1045 QSSGRhiShaderPipeline::UsedWithoutIa,
1047 shaderKeyProperties.m_viewCount.getValue(inRenderable.shaderDescription),
1097void QSSGParticleRenderer::rhiRenderRenderable(QSSGRhiContext *rhiCtx,
1098 QSSGParticlesRenderable &renderable,
1099 bool *needsSetViewport,
1100 QSSGRenderTextureCubeFace cubeFace,
1101 const QSSGRhiGraphicsPipelineState &state)
1103 QRhiGraphicsPipeline *ps = renderable.rhiRenderData.mainPass.pipeline;
1104 QRhiShaderResourceBindings *srb = renderable.rhiRenderData.mainPass.srb;
1106 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
1107 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
1108 ps = renderable.rhiRenderData.reflectionPass.pipeline;
1109 srb = renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx];
1115 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
1117 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
1119 cb->setGraphicsPipeline(ps);
1120 cb->setVertexInput(0, 0,
nullptr);
1121 cb->setShaderResources(srb);
1123 if (needsSetViewport && *needsSetViewport) {
1124 cb->setViewport(state.viewport);
1125 *needsSetViewport =
false;
1127 if (renderable.particles.m_featureLevel >= QSSGRenderParticles::FeatureLevel::Line) {
1129 int S = renderable.particles.m_particleBuffer.segments();
1130 int N = renderable.particles.m_particleBuffer.particleCount() / S;
1133 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderCall, (2 * S | quint64(N) << 32), renderable.particles.profilingId);
1136 cb->draw(4, renderable.particles.m_particleBuffer.particleCount());
1137 QSSGRHICTX_STAT(rhiCtx, draw(4, renderable.particles.m_particleBuffer.particleCount()));
1138 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderCall, (4 | quint64(renderable.particles.m_particleBuffer.particleCount()) << 32), renderable.particles.profilingId);