Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qssgrhiparticles.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5
8
9#include <qfloat16.h>
10
11#include <QtQuick3DUtils/private/qssgutils_p.h>
12
13#include <QtQuick3DRuntimeRender/private/qssgrenderer_p.h>
14#include <QtQuick3DRuntimeRender/private/qssgrendercamera_p.h>
15#include <QtQuick3DRuntimeRender/private/qssglayerrenderdata_p.h>
16#include <QtQuick3DRuntimeRender/private/qssgrenderhelpers_p.h>
17#include <QtQuick3DRuntimeRender/private/qssgshaderresourcemergecontext_p.h>
18
19#include <ssg/qssgrendercontextcore.h>
21
22#include "qtquick3d_tracepoints_p.h"
23
25
27 QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage;
28
30{
32 float pointLightConstantAtt[4] = {1.0f, 1.0f, 1.0f, 1.0f};
33 float pointLightLinearAtt[4] = {0.0f};
34 float pointLightQuadAtt[4] = {0.0f};
37 float spotLightConstantAtt[4] = {1.0f, 1.0f, 1.0f, 1.0f};
38 float spotLightLinearAtt[4] = {0.0f};
39 float spotLightQuadAtt[4] = {0.0f};
42 float spotLightConeAngle[4] = {0.0f};
43 float spotLightInnerConeAngle[4] = {0.0f};
44};
45
46static bool s_shaderCacheEnabled = true;
47void QSSGParticleRenderer::setShaderCacheEnabled(bool enabled)
48{
49 s_shaderCacheEnabled = enabled;
50}
51
52void QSSGParticleRenderer::updateUniformsForParticles(const QSSGLayerRenderData &inData,
53 QSSGRhiShaderPipeline &shaders,
54 QSSGRhiContext *rhiCtx,
55 char *ubufData,
56 QSSGParticlesRenderable &renderable,
57 const QSSGRenderCameraList &cameras)
58{
59 const QMatrix4x4 clipSpaceCorrMatrix = rhiCtx->rhi()->clipSpaceCorrMatrix();
60
61 QSSGRhiShaderPipeline::CommonUniformIndices &cui = shaders.commonUniformIndices;
62
63 const int viewCount = cameras.count();
64
65 // Pull the camera transforms from the render data once.
66 QMatrix4x4 camGlobalTransforms[2] { QMatrix4x4{Qt::Uninitialized}, QMatrix4x4{Qt::Uninitialized} };
67 if (viewCount < 2) {
68 camGlobalTransforms[0] = inData.getGlobalTransform(*cameras[0]);
69 } else {
70 for (size_t viewIndex = 0; viewIndex != std::size(camGlobalTransforms); ++viewIndex)
71 camGlobalTransforms[viewIndex] = inData.getGlobalTransform(*cameras[viewIndex]);
72 }
73
74 if (viewCount < 2) {
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);
79 } else {
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();
85 }
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);
88 }
89
90 const QMatrix4x4 &modelMatrix = renderable.globalTransform;
91 shaders.setUniform(ubufData, "qt_modelMatrix", modelMatrix.constData(), 16 * sizeof(float), &cui.modelMatrixIdx);
92
93 const QVector2D camProperties(cameras[0]->clipPlanes);
94 shaders.setUniform(ubufData, "qt_cameraProperties", &camProperties, 2 * sizeof(float), &cui.cameraPropertiesIdx);
95
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));
102
103 // Global opacity of the particles node
104 shaders.setUniform(ubufData, "qt_opacity", &renderable.opacity, 1 * sizeof(float));
105
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;
109
110 QVector4D spriteConfig(imageCount, ooImageCount, 0.0f, blendImages);
111 shaders.setUniform(ubufData, "qt_spriteConfig", &spriteConfig, 4 * sizeof(float));
112
113 const float billboard = renderable.particles.m_billboard ? 1.0f : 0.0f;
114 shaders.setUniform(ubufData, "qt_billboard", &billboard, 1 * sizeof(float));
115
116 // Lights
117 QVector3D theLightAmbientTotal;
118 bool hasLights = !renderable.particles.m_lights.isEmpty();
119 int pointLight = 0;
120 int spotLight = 0;
121 if (hasLights) {
122 ParticleLightData lightData;
123 auto &lights = renderable.lights;
124 for (quint32 lightIdx = 0, lightEnd = lights.size();
125 lightIdx < lightEnd && lightIdx < QSSG_MAX_NUM_LIGHTS; ++lightIdx) {
126 QSSGRenderLight *theLight(lights[lightIdx].light);
127 // Ignore lights which are not specified for the particle
128 if (!renderable.particles.m_lights.contains(theLight))
129 continue;
130
131 const QMatrix4x4 lightGlobalTransform = inData.getGlobalTransform(*theLight);
132
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);
141 pointLight++;
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;
150 // Inner cone angle must always be < cone angle, to not have possible undefined behavior for shader smoothstep
151 float innerConeAngle = std::min(theLight->m_innerConeAngle, coneAngle - 0.01f);
152 lightData.spotLightConeAngle[spotLight] = qDegreesToRadians(coneAngle);
153 lightData.spotLightInnerConeAngle[spotLight] = qDegreesToRadians(innerConeAngle);
154 spotLight++;
155 }
156 theLightAmbientTotal += theLight->m_ambientColor;
157 }
158 // Copy light data
159 int lightOffset = shaders.offsetOfUniform("lightData");
160 if (lightOffset >= 0)
161 memcpy(ubufData + lightOffset, &lightData, sizeof(ParticleLightData));
162 }
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));
168
169 // Line particle uniform
170 int segmentCount = particleBuffer.segments();
171 if (segmentCount) {
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());
180 }
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));
184 }
185
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) {
191#else
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);
196 if (abuf->texture) {
197#endif
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);
206 }
207
208}
209
210void QSSGParticleRenderer::updateUniformsForParticleModel(QSSGRhiShaderPipeline &shaderPipeline,
211 char *ubufData,
212 const QSSGRenderModel *model,
213 quint32 offset)
214{
215 auto &particleBuffer = *model->particleBuffer;
216 const quint32 particlesPerSlice = particleBuffer.particlesPerSlice();
217 const QVector2D oneOverSize = QVector2D(1.0f / particleBuffer.size().width(), 1.0f / particleBuffer.size().height());
218 shaderPipeline.setUniform(ubufData, "qt_oneOverParticleImageSize", &oneOverSize, 2 * sizeof(float));
219 shaderPipeline.setUniform(ubufData, "qt_countPerSlice", &particlesPerSlice, sizeof(quint32));
220 const QMatrix4x4 &particleMatrix = model->particleMatrix;
221 shaderPipeline.setUniform(ubufData, "qt_particleMatrix", &particleMatrix, 16 * sizeof(float));
222 shaderPipeline.setUniform(ubufData, "qt_particleIndexOffset", &offset, sizeof(quint32));
223}
224
225static void fillTargetBlend(QRhiGraphicsPipeline::TargetBlend &targetBlend, QSSGRenderParticles::BlendMode mode)
226{
227 switch (mode) {
228 case QSSGRenderParticles::BlendMode::Screen:
229 targetBlend.srcColor = QRhiGraphicsPipeline::SrcAlpha;
230 targetBlend.dstColor = QRhiGraphicsPipeline::One;
231 targetBlend.srcAlpha = QRhiGraphicsPipeline::One;
232 targetBlend.dstAlpha = QRhiGraphicsPipeline::One;
233 break;
234 case QSSGRenderParticles::BlendMode::Multiply:
235 targetBlend.srcColor = QRhiGraphicsPipeline::DstColor;
236 targetBlend.dstColor = QRhiGraphicsPipeline::Zero;
237 targetBlend.srcAlpha = QRhiGraphicsPipeline::One;
238 targetBlend.dstAlpha = QRhiGraphicsPipeline::One;
239 break;
240 default:
241 // Source over as default
242 targetBlend.srcColor = QRhiGraphicsPipeline::SrcAlpha;
243 targetBlend.dstColor = QRhiGraphicsPipeline::OneMinusSrcAlpha;
244 targetBlend.srcAlpha = QRhiGraphicsPipeline::One;
245 targetBlend.dstAlpha = QRhiGraphicsPipeline::OneMinusSrcAlpha;
246 break;
247
248 }
249}
250
251static void sortParticles(const QSSGLayerRenderData &renderData, QByteArray &result, QList<QSSGRhiSortData> &sortData,
252 const QSSGParticleBuffer &buffer, const QSSGRenderParticles &particles,
253 const QVector3D &cameraDirection, bool animatedParticles)
254{
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;
262 if (lineParticles)
263 particleCount /= segments;
264 sortData.resize(particleCount);
265 sortData.fill({});
266
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);
271 return sp + i;
272 };
273
274 // create sort data
275 {
276 const auto slices = buffer.sliceCount();
277 const auto ss = buffer.sliceStride();
278 const auto pps = buffer.particlesPerSlice();
279
280 QSSGRhiSortData *dst = sortData.data();
281 const char *source = buffer.pointer();
282 const char *begin = source;
283 int i = 0;
284 if (lineParticles) {
285 for (i = 0; i < particleCount; i++) {
286 QSSGRhiSortData lineData;
287 const QSSGLineParticle *lineBegin = srcParticlePointer(i, 0, segments, ss, pps, source);
288 lineData.indexOrOffset = i;
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));
293 }
294 *dst++ = lineData;
295 }
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)};
301 sp++;
302 dst++;
303 i++;
304 }
305 source += ss;
306 }
307 } else {
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)};
312 sp++;
313 dst++;
314 i++;
315 }
316 source += ss;
317 }
318 }
319 }
320
321 // sort
322 result.resize(buffer.bufferSize());
323 std::sort(sortData.begin(), sortData.end(), [](const QSSGRhiSortData &a, const QSSGRhiSortData &b){
324 return a.d > b.d;
325 });
326
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();
331 const QSSGRhiSortData *sdata = data.data();
332 char *dest = dst.data();
333 const char *source = buffer.pointer();
334 int i = 0;
335 if (lineParticles) {
336 int seg = 0;
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);
341 dp++;
342 seg++;
343 if (seg == segments) {
344 sdata++;
345 i++;
346 seg = 0;
347 }
348 }
349 dest += ss;
350 }
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);
356 dp++;
357 sdata++;
358 i++;
359 }
360 dest += ss;
361 }
362 } else {
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);
367 dp++;
368 sdata++;
369 i++;
370 }
371 dest += ss;
372 }
373 }
374 };
375
376 // write result
377 copyParticles(result, sortData, buffer);
378}
379
380static QByteArray convertParticleData(QByteArray &dest, const QByteArray &data, bool convert)
381{
382 if (!convert)
383 return data;
384 int count = data.size() / 4;
385 if (dest.size() != count * 2)
386 dest.resize(2 * count);
387 qFloatToFloat16(reinterpret_cast<qfloat16 *>(dest.data()), reinterpret_cast<const float *>(data.constData()), count);
388 return dest;
389}
390
391void QSSGParticleRenderer::rhiPrepareRenderable(QSSGRhiShaderPipeline &shaderPipeline,
392 QSSGPassKey passKey,
393 QSSGRhiContext *rhiCtx,
394 QSSGRhiGraphicsPipelineState *ps,
395 QSSGParticlesRenderable &renderable,
396 const QSSGLayerRenderData &inData,
397 QRhiRenderPassDescriptor *renderPassDescriptor,
398 int samples,
399 int viewCount,
400 QSSGRenderCamera *alteredCamera,
401 QSSGRenderTextureCubeFace cubeFace,
402 QSSGReflectionMapEntry *entry,
403 bool oit)
404{
405 const void *node = &renderable.particles;
406 const bool needsConversion = !rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32F);
407
408 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
409 QSSGRhiDrawCallData &dcd = QSSGRhiContextPrivate::get(rhiCtx)->drawCallData({ passKey, node, nullptr, entry,
410 cubeFaceIdx });
411 shaderPipeline.ensureUniformBuffer(&dcd.ubuf);
412
413 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
414 if (!alteredCamera) {
415 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, inData.renderedCameras);
416 } else {
417 QSSGRenderCameraList cameras({ alteredCamera });
418 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, cameras);
419 }
420 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
421
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();
430 } else {
431 particleData.texture->setPixelSize(size);
432 particleData.texture->create();
433 }
434 particleData.particleCount = particleCount;
435 }
436
437 bool sortingChanged = particleData.sorting != renderable.particles.m_depthSorting;
438 if (sortingChanged && !renderable.particles.m_depthSorting) {
439 particleData.sortData.clear();
440 particleData.sortedData.clear();
441 }
442 particleData.sorting = renderable.particles.m_depthSorting;
443
444 QByteArray uploadData;
445
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);
450 } else {
451 const QMatrix4x4 globalTransform = inData.getGlobalTransform(*alteredCamera);
452 sortParticles(inData, particleData.sortedData, particleData.sortData, particleBuffer, renderable.particles, QSSGRenderNode::getScalingCorrectDirection(globalTransform), animatedParticles);
453 }
454 uploadData = convertParticleData(particleData.convertData, particleData.sortedData, needsConversion);
455 } else {
456 uploadData = convertParticleData(particleData.convertData, particleBuffer.data(), needsConversion);
457 }
458
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);
465
466 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
467 ia.topology = QRhiGraphicsPipeline::TriangleStrip;
468 ia.inputLayout = QRhiVertexInputLayout();
469 ia.inputs.clear();
470
471 ps->samples = samples;
472 ps->viewCount = viewCount;
473 ps->cullMode = QRhiGraphicsPipeline::None;
474
475 if (inData.orderIndependentTransparencyEnabled == false) {
476 if (renderable.renderableFlags.hasTransparency())
477 fillTargetBlend(ps->targetBlend[0], renderable.particles.m_blendMode);
478 else
479 ps->targetBlend[0] = QRhiGraphicsPipeline::TargetBlend();
480 }
481
482 QSSGRhiShaderResourceBindingList bindings;
483 bindings.addUniformBuffer(0, VISIBILITY_ALL, dcd.ubuf, 0, shaderPipeline.ub0Size());
484
485 // Texture maps
486 // we only have one image
487 QSSGRenderableImage *renderableImage = renderable.firstImage;
488
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)
500 });
501 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
502 } else {
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,
508 QRhiSampler::None,
509 QRhiSampler::ClampToEdge,
510 QRhiSampler::ClampToEdge,
511 QRhiSampler::Repeat
512 });
513 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
514 }
515 }
516
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,
523 QRhiSampler::None,
524 QRhiSampler::ClampToEdge,
525 QRhiSampler::ClampToEdge,
526 QRhiSampler::Repeat
527 });
528 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
529 }
530 }
531
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;
537 if (texture) {
538 hasTexture = true;
539 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
540 QRhiSampler::Nearest,
541 QRhiSampler::None,
542 QRhiSampler::ClampToEdge,
543 QRhiSampler::ClampToEdge,
544 QRhiSampler::Repeat
545 });
546 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
547 }
548 }
549
550 if (!hasTexture) {
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,
556 QRhiSampler::None,
557 QRhiSampler::ClampToEdge,
558 QRhiSampler::ClampToEdge,
559 QRhiSampler::Repeat
560 });
561 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
562 }
563 }
564
565 if (oit && inData.layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
566 RenderHelpers::addAccumulatorImageBindings(&shaderPipeline, bindings);
567
568 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
569
570 // TODO: This is identical to other renderables. Make into a function?
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;
577 srbChanged = true;
578 }
579
580 if (cubeFace == QSSGRenderTextureCubeFaceNone)
581 renderable.rhiRenderData.mainPass.srb = srb;
582 else
583 renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx] = srb;
584
585 const auto pipelineKey = QSSGGraphicsPipelineStateKey::create(*ps, renderPassDescriptor, srb);
586 if (dcd.pipeline
587 && !srbChanged
588 && dcd.renderTargetDescriptionHash == pipelineKey.extra.renderTargetDescriptionHash
589 && dcd.renderTargetDescription == pipelineKey.renderTargetDescription
590 && dcd.ps == *ps)
591 {
592 if (cubeFace == QSSGRenderTextureCubeFaceNone)
593 renderable.rhiRenderData.mainPass.pipeline = dcd.pipeline;
594 else
595 renderable.rhiRenderData.reflectionPass.pipeline = dcd.pipeline;
596 } else {
597 if (cubeFace == QSSGRenderTextureCubeFaceNone) {
598 renderable.rhiRenderData.mainPass.pipeline = rhiCtxD->pipeline(pipelineKey,
599 renderPassDescriptor,
600 srb);
601 dcd.pipeline = renderable.rhiRenderData.mainPass.pipeline;
602 } else {
603 renderable.rhiRenderData.reflectionPass.pipeline = rhiCtxD->pipeline(pipelineKey,
604 renderPassDescriptor,
605 srb);
606 dcd.pipeline = renderable.rhiRenderData.reflectionPass.pipeline;
607 }
608 dcd.renderTargetDescriptionHash = pipelineKey.extra.renderTargetDescriptionHash;
609 dcd.renderTargetDescription = pipelineKey.renderTargetDescription;
610 dcd.ps = *ps;
611 }
612}
613
614void QSSGParticleRenderer::prepareParticlesForModel(QSSGRhiShaderPipeline &shaderPipeline,
615 QSSGRhiContext *rhiCtx,
616 QSSGRhiShaderResourceBindingList &bindings,
617 const QSSGRenderModel *model)
618{
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();
630 } else {
631 particleData.texture->setPixelSize(size);
632 particleData.texture->create();
633 }
634 particleData.particleCount = particleCount;
635 update = true;
636 }
637
638 if (update) {
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);
645 }
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,
653 QRhiSampler::None,
654 QRhiSampler::ClampToEdge,
655 QRhiSampler::ClampToEdge,
656 QRhiSampler::Repeat
657 });
658 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
659 }
660 }
661}
662
663static QByteArray particlesLogPrefix() { return QByteArrayLiteral("particle material pipeline-- "); }
664
666{
674 void addUniform(const QByteArray &name, const QByteArray &type)
675 {
676 vs->addUniform(name, type);
677 fs->addUniform(name, type);
678 }
679 void addUniformArray(const QByteArray &name, const QByteArray &type, quint32 size)
680 {
681 vs->addUniformArray(name, type, size);
682 fs->addUniformArray(name, type, size);
683 }
684 void addDefinition(const QByteArray &name, const QByteArray &value)
685 {
686 vs->addDefinition(name, value);
687 fs->addDefinition(name, value);
688 }
689 void addInterpolant(const QByteArray &name, const QByteArray &type)
690 {
691 vs->addOutgoing(name, type);
692 fs->addIncoming(name, type);
693 }
694 void addFlatInterpolant(const QByteArray &name, const QByteArray &type)
695 {
696 vs->addFlatOutgoing(name, type);
697 fs->addFlatIncoming(name, type);
698 }
699 void addPrefix(const QByteArray &prefix)
700 {
701 vs->addPrefix(prefix);
702 fs->addPrefix(prefix);
703 }
704};
705
707{
709 int indent = 0;
710 AutoFormatGenerator(QSSGStageGeneratorBase &g)
711 : gen(g)
712 {
713
714 }
715 AutoFormatGenerator &operator<<(const QByteArray &data)
716 {
717 for (int i = 0; i < indent; i++)
718 gen << " ";
719 gen << data << "\n";
720 return *this;
721 }
723 {
724 indent++;
725 }
727 {
728 indent--;
729 Q_ASSERT(indent >= 0);
730 }
731};
732
733static const char *s_lightPrefix = {
734 "struct ParticleLightData\n"
735 "{\n"
736 " vec4 qt_pointLightPosition[4];\n"
737 " vec4 qt_pointLightConstantAtt;\n"
738 " vec4 qt_pointLightLinearAtt;\n"
739 " vec4 qt_pointLightQuadAtt;\n"
740 " vec4 qt_pointLightColor[4];\n"
741 " vec4 qt_spotLightPosition[4];\n"
742 " vec4 qt_spotLightConstantAtt;\n"
743 " vec4 qt_spotLightLinearAtt;\n"
744 " vec4 qt_spotLightQuadAtt;\n"
745 " vec4 qt_spotLightColor[4];\n"
746 " vec4 qt_spotLightDirection[4];\n"
747 " vec4 qt_spotLightConeAngle;\n"
748 " vec4 qt_spotLightInnerConeAngle;\n"
749 "};\n"
750};
751
752QSSGShaderFeatures QSSGParticleRenderer::particleShaderFeatures(const QSSGShaderFeatures& features)
753{
754#define COPY_FEATURE(f) ret.set(f, features.isSet(f));
755 QSSGShaderFeatures ret;
756 COPY_FEATURE(QSSGShaderFeatures::Feature::LinearTonemapping);
757 COPY_FEATURE(QSSGShaderFeatures::Feature::AcesTonemapping);
758 COPY_FEATURE(QSSGShaderFeatures::Feature::HejlDawsonTonemapping);
759 COPY_FEATURE(QSSGShaderFeatures::Feature::FilmicTonemapping);
760 COPY_FEATURE(QSSGShaderFeatures::Feature::DisableMultiView);
761#undef COPY_FEATURE
762 return ret;
763}
764
765QSSGRhiShaderPipelinePtr QSSGParticleRenderer::generateRhiShaderPipeline(QSSGRenderer &renderer,
766 QSSGParticlesRenderable &inRenderable,
767 const QSSGShaderFeatures &inFeatureSet,
768 QByteArray &shaderString,
769 const QSSGShaderParticleMaterialKeyProperties &shaderKeyProperties)
770{
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();
775
776 shaderString = particlesLogPrefix();
777 QSSGShaderParticleMaterialKey theKey(inRenderable.shaderDescription);
778
779 theKey.toString(shaderString, shaderKeyProperties);
780
781 if (s_shaderCacheEnabled) {
782 if (const auto &maybePipeline = shaderCache->tryGetRhiShaderPipeline(shaderString, inFeatureSet))
783 return maybePipeline;
784
785 const QByteArray qsbcKey = QQsbCollection::EntryDesc::generateSha(shaderString, QQsbCollection::toFeatureSet(inFeatureSet));
786 // Check if there's a pre-built (offline generated) shader for available.
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;
792 }
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);
797 }
798 }
799
800 // Try the persistent (disk-based) cache then.
801 if (const auto &maybePipeline = shaderCache->tryNewPipelineFromPersistentCache(qsbcKey, shaderString, inFeatureSet))
802 return maybePipeline;
803 }
804
805 // generate shader code
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);
820
821 if (isAnimated)
822 common.addDefinition("QSSG_PARTICLES_ENABLE_ANIMATED", "1");
823 if (isLineParticle)
824 common.addDefinition("QSSG_PARTICLES_ENABLE_LINE_PARTICLE", "1");
825 if (oit)
826 common.addDefinition("QSSG_OIT_METHOD", QStringLiteral("%1").arg(oit).toUtf8());
827 if (oitMSAA)
828 common.addDefinition("QSSG_MULTISAMPLE", "1");
829
830 common.addUniform("qt_modelMatrix", "mat4");
831 if (viewCount >= 2) {
832 common.addUniformArray("qt_viewMatrix", "mat4", viewCount);
833 common.addUniformArray("qt_projectionMatrix", "mat4", viewCount);
834 } else {
835 common.addUniform("qt_viewMatrix", "mat4");
836 common.addUniform("qt_projectionMatrix", "mat4");
837 }
838 if (lighting) {
839 common.addPrefix(s_lightPrefix);
840 common.addUniform("lightData", "ParticleLightData");
841 }
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");
846 if (isLineParticle)
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");
854 }
855 if (lighting) {
856 common.addUniform("qt_pointLights", "bool");
857 common.addUniform("qt_spotLights", "bool");
858 }
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");
867#endif
868 }
869
870 if (lighting)
871 vertex.addInclude("particleLighting.glsllib");
872
873 vertex.addUniform("qt_particleTexture", "sampler2D");
874
875 vertex.addInclude("particleLoading.glsllib");
876
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");
883
884 AutoFormatGenerator vg(vertex);
885 if (!isLineParticle)
886 vg << "const vec2 corners[4] = {{0.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}, {1.0, 1.0}};";
887
888 // vertex shader main
889 vg << "out gl_PerVertex {"
890 << " vec4 gl_Position;"
891 << "};";
892
893 vg << "void main() {";
894 vg.incIndent();
895 if (isLineParticle) {
896 vg << "uint segmentIndex = gl_VertexIndex / 2;"
897 << "uint particleIndex = segmentIndex + gl_InstanceIndex * qt_lineSegmentCount;";
898 } else {
899 vg << "uint particleIndex = gl_InstanceIndex;"
900 << "uint cornerIndex = gl_VertexIndex;"
901 << "vec2 corner = corners[cornerIndex];";
902 }
903 vg << "instanceIndex = particleIndex;"
904 << "Particle p = qt_loadParticle(particleIndex);";
905
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;";
914 } else {
915 vg << "vec4 viewPos = qt_viewMatrix * worldPos;"
916 << "vec3 viewBN = (transpose(inverse(qt_viewMatrix * qt_modelMatrix)) * vec4(p.binormal, 0.0)).xyz;";
917 }
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);";
925 } else {
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);";
931 if (viewCount >= 2)
932 vg << "viewPos = qt_viewMatrix[gl_ViewIndex] * viewPos;";
933 else
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;";
939 }
940 if (lighting)
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;";
946 } else {
947 vg << "gl_Position = qt_projectionMatrix * viewPos;";
948 }
949 if (isMapped)
950 vg << "spriteData.x = qt_ageToSpriteFactor(p.age);";
951 if (isAnimated)
952 vg << "spriteData.y = p.animationFrame;";
953 vg.decIndent();
954 vg << "}";
955
956 // fragment shader main
957 fragment.addInclude("tonemapping.glsllib");
958 fragment.addInclude("particleSprite.glsllib");
959 fragment.addUniform("qt_sprite", "sampler2D");
960
961 AutoFormatGenerator fg(fragment);
962
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);
970#else
971 fragment.addInclude("oitlinkedlist.glsllib");
972#endif
973 }
974 if (isSpriteLinear)
975 fg << "#define spriteFunc";
976 else
977 fg << "#define spriteFunc qt_sRGBToLinear";
978 if (isMapped) {
979 fragment.addUniform("qt_colorTable", "sampler2D");
980 if (isColorTableLinear)
981 fg << "#define colorTableFunc";
982 else
983 fg << "#define colorTableFunc qt_sRGBToLinear";
984 }
985
986 fg << "vec4 qt_readSprite() {";
987 fg.incIndent();
988 if (isAnimated) {
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);";
992 } else {
993 fg << "return spriteFunc(texture(qt_sprite, texcoord));";
994 }
995 fg.decIndent();
996 fg << "}";
997 fg << "vec4 qt_readColor() {";
998 fg.incIndent();
999 if (isMapped)
1000 fg << "return color * colorTableFunc(texture(qt_colorTable, vec2(spriteData.x, qt_rand(vec2(instanceIndex, 0)))));";
1001 else
1002 fg << "return color;";
1003 fg.decIndent();
1004 fg << "}";
1005 fg << "void main() {";
1006 fg.incIndent();
1007 fg << "vec4 ret = qt_readColor() * qt_readSprite();";
1008 if (oit) {
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
1016 if (viewCount >= 2)
1017 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex, qt_samples);";
1018 else
1019 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0, qt_samples);";
1020#else
1021 if (viewCount >= 2)
1022 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex);";
1023 else
1024 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0);";
1025#endif
1026 }
1027 } else {
1028 fg << "fragOutput = qt_tonemap(ret);";
1029 }
1030 fg.decIndent();
1031 fg << "}";
1032
1033
1034 return shaderProgramGenerator->compileGeneratedRhiShader(shaderString,
1035 inFeatureSet,
1036 *shaderLibraryManager,
1037 *shaderCache,
1038 QSSGRhiShaderPipeline::UsedWithoutIa,
1039 {},
1040 shaderKeyProperties.m_viewCount.getValue(inRenderable.shaderDescription),
1041 false);
1042}
1043
1044QSSGRhiShaderPipelinePtr QSSGParticleRenderer::getShaderPipelineParticles(QSSGRenderer &renderer,
1045 QSSGParticlesRenderable &inRenderable,
1046 const QSSGShaderFeatures &inFeatureSet)
1047{
1048 const auto features = particleShaderFeatures(inFeatureSet);
1049 auto *m_currentLayer = renderer.m_currentLayer;
1050 QSSG_ASSERT(m_currentLayer != nullptr, return {});
1051
1052 auto &shaderMap = m_currentLayer->particleShaderMap;
1053
1054 QElapsedTimer timer;
1055 timer.start();
1056
1057 QSSGRhiShaderPipelinePtr shaderPipeline;
1058
1059 // This just references inFeatureSet and inRenderable.shaderDescription -
1060 // cheap to construct and is good enough for the find()
1061 QSSGParticleShaderMapKey skey = QSSGParticleShaderMapKey(QByteArray(),
1062 features,
1063 inRenderable.shaderDescription);
1064 auto it = shaderMap.find(skey);
1065 if (it == shaderMap.end()) {
1066 Q_TRACE_SCOPE(QSSG_generateShader);
1067 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DGenerateShader);
1068 auto &shaderString = renderer.m_currentLayer->generatedShaderString;
1069 shaderPipeline = QSSGParticleRenderer::generateRhiShaderPipeline(renderer, inRenderable, features, shaderString, m_currentLayer->particleMaterialShaderKeyProperties);
1070 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DGenerateShader, 0, inRenderable.particles.profilingId);
1071 // make skey useable as a key for the QHash (makes a copy of the materialKey, instead of just referencing)
1072 skey.detach();
1073 // insert it no matter what, no point in trying over and over again
1074 shaderMap.insert(skey, shaderPipeline);
1075 } else {
1076 shaderPipeline = it.value();
1077 }
1078
1079 if (shaderPipeline != nullptr) {
1080 if (m_currentLayer && !m_currentLayer->renderedCameras.isEmpty())
1081 m_currentLayer->ensureCachedCameraDatas();
1082 }
1083
1084 const auto &rhiContext = renderer.m_contextInterface->rhiContext();
1085 QSSGRhiContextStats::get(*rhiContext).registerMaterialShaderGenerationTime(timer.elapsed());
1086
1087 return shaderPipeline;
1088}
1089
1090void QSSGParticleRenderer::rhiRenderRenderable(QSSGRhiContext *rhiCtx,
1091 QSSGParticlesRenderable &renderable,
1092 bool *needsSetViewport,
1093 QSSGRenderTextureCubeFace cubeFace,
1094 const QSSGRhiGraphicsPipelineState &state)
1095{
1096 QRhiGraphicsPipeline *ps = renderable.rhiRenderData.mainPass.pipeline;
1097 QRhiShaderResourceBindings *srb = renderable.rhiRenderData.mainPass.srb;
1098
1099 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
1100 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
1101 ps = renderable.rhiRenderData.reflectionPass.pipeline;
1102 srb = renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx];
1103 }
1104
1105 if (!ps || !srb)
1106 return;
1107
1108 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
1109
1110 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
1111 // QRhi optimizes out unnecessary binding of the same pipline
1112 cb->setGraphicsPipeline(ps);
1113 cb->setVertexInput(0, 0, nullptr);
1114 cb->setShaderResources(srb);
1115
1116 if (needsSetViewport && *needsSetViewport) {
1117 cb->setViewport(state.viewport);
1118 *needsSetViewport = false;
1119 }
1120 if (renderable.particles.m_featureLevel >= QSSGRenderParticles::FeatureLevel::Line) {
1121 // draw triangle strip with 2 * segmentCount vertices N times
1122 int S = renderable.particles.m_particleBuffer.segments();
1123 int N = renderable.particles.m_particleBuffer.particleCount() / S;
1124 cb->draw(2 * S, N);
1125 QSSGRHICTX_STAT(rhiCtx, draw(2 * S, N));
1126 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderCall, (2 * S | quint64(N) << 32), renderable.particles.profilingId);
1127 } else {
1128 // draw triangle strip with 2 triangles N times
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);
1132 }
1133}
1134
1135QT_END_NAMESPACE
\keyword 16-bit Floating Point Support\inmodule QtCore \inheaderfile QFloat16
Definition qfloat16.h:57
Combined button and popup list for selecting options.
Q_CORE_EXPORT void qFloatToFloat16(qfloat16 *, const float *, qsizetype length) noexcept
#define QSSGRHICTX_STAT(ctx, f)
#define QSSG_MAX_NUM_LIGHTS
static QByteArray particlesLogPrefix()
static const char * s_lightPrefix
static QByteArray convertParticleData(QByteArray &dest, const QByteArray &data, bool convert)
static void fillTargetBlend(QRhiGraphicsPipeline::TargetBlend &targetBlend, QSSGRenderParticles::BlendMode mode)
static bool s_shaderCacheEnabled
static void sortParticles(const QSSGLayerRenderData &renderData, QByteArray &result, QList< QSSGRhiSortData > &sortData, const QSSGParticleBuffer &buffer, const QSSGRenderParticles &particles, const QVector3D &cameraDirection, bool animatedParticles)
static QT_BEGIN_NAMESPACE const QRhiShaderResourceBinding::StageFlags VISIBILITY_ALL
#define COPY_FEATURE(f)
AutoFormatGenerator(QSSGStageGeneratorBase &g)
QSSGStageGeneratorBase & gen
QVector4D spotLightPos[4]
QVector4D spotLightColor[4]
QVector4D pointLightColor[4]
QVector4D pointLightPos[4]
QVector4D spotLightDir[4]
void addUniformArray(const QByteArray &name, const QByteArray &type, quint32 size)
void addInterpolant(const QByteArray &name, const QByteArray &type)
ShaderGeneratorCommon(QSSGProgramGenerator &gen)
void addUniform(const QByteArray &name, const QByteArray &type)
void addFlatInterpolant(const QByteArray &name, const QByteArray &type)
QSSGStageGeneratorBase * vs
QSSGStageGeneratorBase * fs
void addPrefix(const QByteArray &prefix)
void addDefinition(const QByteArray &name, const QByteArray &value)